<?php
namespace App\Service\Kernel;
use App\Entity\Kernel\User;
use App\Entity\Kernel\ConfigurableList;
use App\Entity\Kernel\ListItem;
use App\Entity\Kernel\DocumentTemplateGroup;
use App\Entity\Kernel\DocumentTemplate;
use App\Entity\Kernel\TemplateType;
use Doctrine\Persistence\ObjectManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Security;
use App\Entity\Kernel\SecurityAction;
use App\Entity\Kernel\UserLog;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
use App\Entity\Kernel\Folder;
use App\Entity\Kernel\KernelFile;
use App\Entity\Kernel\KernelFileVersion;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use \Imagick;
use Dompdf\Dompdf;
use Symfony\Contracts\Translation\TranslatorInterface;
class DMSService {
private $em;
protected $twig;
protected $translator;
private $kernelService;
public function __construct(EntityManagerInterface $entityManager, Environment $twig, TranslatorInterface $translator, KernelService $kernelService) {
$this->em = $entityManager;
$this->twig = $twig;
$this->translator = $translator;
$this->kernelService = $kernelService;
}
public function getFolder($path) {
$tmpfolder = null;
foreach ($path as $childname) {
$tmpfolder = $this->getChildFolder($tmpfolder, $childname);
}
return $tmpfolder;
}
public function getChildFolder($parent, $childname) {
$em = $this->em;
if ($parent == null) {
//$em->getRepository('HVDHBundleKernelBundle:Folder')->find(22);
$query = $em->createQuery("SELECT t FROM App\Entity\Kernel\Folder t
WHERE t.parent IS NULL AND t.name = ?1");
$query = $query->setParameter(1, $childname);
return $query->getOneOrNullResult();
} else {
$query = $em->createQuery("SELECT t FROM App\Entity\Kernel\Folder t
WHERE t.parent = ?2 AND t.name = ?1");
$query = $query->setParameter(1, $childname);
$query = $query->setParameter(2, $parent->getId());
return $query->getOneOrNullResult();
}
}
public function createFolder($name, $parent) {
$em = $this->em;
$entity = new Folder();
$entity->setName($name);
$entity->setParent($parent);
$entity->setState(0);
if ($parent != null) {
$entity->setOrganization($parent->getOrganization());
}
$em->persist($entity);
$em->flush();
return $entity;
}
public function createFolderIfNeeded($name, Folder $parent = null) {
$em = $this->em;
if ($parent == null) {
//$em->getRepository('HVDHBundleKernelBundle:Folder')->find(22);
//App\Entity\Manufacturing\WorkCenter
$query = $em->createQuery("SELECT t FROM App\Entity\Kernel\Folder t
WHERE t.parent IS NULL AND t.name = ?1");
$query = $query->setParameter(1, $name);
$entity = $query->getOneOrNullResult();
} else {
$query = $em->createQuery("SELECT t FROM App\Entity\Kernel\Folder t
WHERE t.parent = ?2 AND t.name = ?1");
$query = $query->setParameter(1, $name);
$query = $query->setParameter(2, $parent->getId());
$entity = $query->getOneOrNullResult();
}
if (!$entity) {
return $this->createFolder($name, $parent);
} else {
return $entity;
}
}
public function copyfile($kernelfile, $tofolder) {
$entity = new KernelFile();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setVersion("0.1");
$kernelfileversion = $kernelfile->getLastKernelFileVersion();
$entity->setName($kernelfile->getName());
$entityversion->setExtention($kernelfileversion->getExtention());
$entityversion->setMime($kernelfileversion->getMime());
$entity->setFolder($tofolder);
$entityversion->setThumb(null);
$entityversion->setSize($kernelfileversion->getSize());
$entityversion->setHeight($kernelfileversion->getHeight());
$entityversion->setWidth($kernelfileversion->getWidth());
$entityversion->setState(0);
$entity->setState(0);
$this->em->persist($entity);
$this->em->persist($entityversion);
$this->em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
$file = $path . $filename;
$oldpath = $kernelfileversion->getFileFolder() . "/";
$oldfilename = $kernelfileversion->getFilename();
$oldfile = $oldpath . $oldfilename;
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
if (!copy($oldfile, $file)) {
echo "failed to copy";
}
$this->createThumbs($entityversion);
return $entity;
}
public function resizefile($kernelfileversion, $width, $heigth) {
$entitynew = new KernelFileVersion();
//$entitynew->setName($kernelfileversion->getName());
$entitynew->setVersion($this->getNextVersion($kernelfileversion->getVersion()));
$entitynew->setExtention($kernelfileversion->getExtention());
//$entitynew->setFolder($tofolder);
$entitynew->setMime($kernelfileversion->getMime());
$entitynew->setTechnical(null);
$entitynew->setKernelFile($kernelfileversion->getKernelFile());
$entitynew->setHeight($heigth);
$entitynew->setWidth($width);
$entitynew->setState(0);
$this->em->persist($entitynew);
$this->em->flush();
$path = $entitynew->getFileFolder() . "/";
$filename = $entitynew->getFilename();
$file = $path . $filename;
$oldpath = $kernelfileversion->getFileFolder() . "/";
$oldfilename = $kernelfileversion->getFilename();
$oldfile = $oldpath . $oldfilename;
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
/* if (($width == null) and ($heigth == null))
{
$width = 100;
$height = 100000;
}
if ($width == null)
{
$width = 100000;
}
if ($heigth == null)
{
$heigth = 100000;
} */
$thumb = new \Imagick($oldfile);
//$thumb->resizeImage($width,$heigth,Imagick::FILTER_LANCZOS,1);
//$thumb->setImageBackgroundColor('#ffffff');
//$thumb = $thumb->flattenImages();
$thumb->thumbnailImage($width, $heigth);
//$thumb->setImageFormat('jpeg');
$thumb->writeImage($file);
$thumb->destroy();
$filesize = filesize($file);
$entitynew->setSize($filesize);
//$entity->setSize($kernelfile->getSize());
$this->em->persist($entitynew);
$this->em->flush();
$this->createThumbs($entitynew);
return $entitynew;
}
public function createsquareThumb($kernelfileversion) {
$heigth = 250;
$width = 250;
$entitynew = new KernelFileVersion();
$entitynew->setversion($kernelfileversion->getVersion());
$entitynew->setExtention($kernelfileversion->getExtention());
$entitynew->setMime($kernelfileversion->getMime());
$entitynew->setTechnical(true);
$entitynew->setKernelFile($kernelfileversion->getKernelFile());
//$entitynew->setFolder($tofolder);
$entitynew->setState(0);
$entitynew->setHeight($heigth);
$entitynew->setWidth($width);
$this->em->persist($entitynew);
$this->em->flush();
$path = $entitynew->getFileFolder() . "/";
$filename = $entitynew->getFilename();
$file = $path . $filename;
$oldpath = $kernelfileversion->getFileFolder() . "/";
$oldfilename = $kernelfileversion->getFilename();
$oldfile = $oldpath . $oldfilename;
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
$thumb = new \Imagick($oldfile);
//$thumb->resizeImage($width,$heigth,Imagick::FILTER_LANCZOS,1);
//$thumb->setImageBackgroundColor('#ffffff');
//$thumb = $thumb->flattenImages();
$thumb->cropThumbnailImage($width, $heigth);
//$thumb->setImageFormat('jpeg');
$thumb->writeImage($file);
$thumb->destroy();
$filesize = filesize($file);
$entitynew->setSize($filesize);
//$entity->setSize($kernelfile->getSize());
$this->em->persist($entitynew);
$this->em->flush();
$kernelfileversion->setSquarethumb($entitynew);
$this->em->persist($entitynew);
$this->em->flush();
return $entitynew;
}
public function createThumb($kernelfileversion) {
$width = 250;
$heigth = 1000;
$entitynew = new KernelFileVersion();
$entitynew->setversion($kernelfileversion->getVersion());
$entitynew->setState(0);
$entitynew->setExtention($kernelfileversion->getExtention());
$entitynew->setMime($kernelfileversion->getMime());
$entitynew->setTechnical(true);
$entitynew->setKernelFile($kernelfileversion->getKernelFile());
//$entitynew->setFolder($tofolder);
//$entitynew->setHeight($heigth);
//$entitynew->setWidth($width);
$this->em->persist($entitynew);
$this->em->flush();
$path = $entitynew->getFileFolder() . "/";
$filename = $entitynew->getFilename();
$file = $path . $filename;
$oldpath = $kernelfileversion->getFileFolder() . "/";
$oldfilename = $kernelfileversion->getFilename();
$oldfile = $oldpath . $oldfilename;
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
$thumb = new \Imagick($oldfile);
//$thumb->resizeImage($width,$heigth,Imagick::FILTER_LANCZOS,1);
//$thumb->cropThumbnailImage($width,$heigth);
//$thumb->setImageBackgroundColor('#ffffff');
//$thumb = $thumb->flattenImages();
$thumb->thumbnailImage($width, $heigth, true);
//$thumb->setImageFormat('jpeg');
$thumb->writeImage($file);
$entitynew->setHeight($thumb->getImageHeight());
$entitynew->setWidth($thumb->getImageWidth());
$thumb->destroy();
$filesize = filesize($file);
$entitynew->setSize($filesize);
//$entity->setSize($kernelfile->getSize());
$this->em->persist($entitynew);
$this->em->flush();
$kernelfileversion->setThumb($entitynew);
$this->em->persist($entitynew);
$this->em->flush();
return $entitynew;
}
public function createPrintThumb($kernelfileversion) {
$width = 350;
$heigth = 2000;
$entitynew = new KernelFileVersion();
$entitynew->setversion($kernelfileversion->getVersion());
$entitynew->setState(0);
$entitynew->setExtention("jpg");
$entitynew->setMime("image/jpeg");
$entitynew->setTechnical(true);
$entitynew->setKernelFile($kernelfileversion->getKernelFile());
//$entitynew->setFolder($tofolder);
//$entitynew->setHeight($heigth);
//$entitynew->setWidth($width);
$this->em->persist($entitynew);
$this->em->flush();
$path = $entitynew->getFileFolder() . "/";
$filename = $entitynew->getFilename();
$file = $path . $filename;
$oldpath = $kernelfileversion->getFileFolder() . "/";
$oldfilename = $kernelfileversion->getFilename();
$oldfile = $oldpath . $oldfilename;
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
$thumb = new \Imagick($oldfile);
//$thumb->resizeImage($width,$heigth,Imagick::FILTER_LANCZOS,1);
//$thumb->cropThumbnailImage($width,$heigth);
$thumb->setImageBackgroundColor('#ffffff');
$thumb = $thumb->flattenImages();
$thumb->thumbnailImage($width, $heigth, true);
$thumb->setImageFormat('jpeg');
$thumb->writeImage($file);
$entitynew->setHeight($thumb->getImageHeight());
$entitynew->setWidth($thumb->getImageWidth());
$thumb->destroy();
$filesize = filesize($file);
$entitynew->setSize($filesize);
//$entity->setSize($kernelfile->getSize());
$this->em->persist($entitynew);
$this->em->flush();
$kernelfileversion->setPrintthumb($entitynew);
$this->em->persist($entitynew);
$this->em->flush();
return $entitynew;
}
public function createThumbs($kernelfileversion) {
$images = array("png", "jpg", "gif", "jpeg");
if (in_array(strtolower($kernelfileversion->getExtention()), $images) == true) {
$path = $kernelfileversion->getFileFolder() . "/";
$filename = $kernelfileversion->getFilename();
$file = $path . $filename;
$image = new \Imagick($file);
$d = $image->getImageGeometry();
$w = $d['width'];
$h = $d['height'];
$kernelfileversion->setWidth($w);
$kernelfileversion->setHeight($h);
$this->em->persist($kernelfileversion);
$this->em->flush();
if ($kernelfileversion->getSquarethumb() == null) {
$this->createsquareThumb($kernelfileversion);
}
if ($kernelfileversion->getThumb() == null) {
$this->createThumb($kernelfileversion);
}
if ($kernelfileversion->getPrintthumb() == null) {
$this->createPrintthumb($kernelfileversion);
}
}
}
public function getMajorVersion($version) {
$arr = explode(".", $version, 2);
return $arr[0];
}
public function getMinorVersion($version) {
$arr = explode(".", $version, 2);
return $arr[1];
}
public function getNextVersion($version) {
return "" . $this->getMajorVersion($version) . "." . (intval($this->getMinorVersion($version)) + 1);
}
public function copyToDMS($file, $tofolder, $filename, $kernelfile = null) {
$em = $this->em;
if (is_null($kernelfile) == true) {
$entity = new KernelFile();
//Voor 20181113 stond dit na de else
$entity->setName($filename);
$entity->setFolder($tofolder);
$entity->setState(0);
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setVersion("0.1");
$entityversion->setState(0);
} else {
$entity = $kernelfile;
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setVersion($this->getNextVersion($entity->getLastKernelFileVersion()->getVersion()));
}
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$entityversion->setExtention($ext);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file);
$entityversion->setMime($mime);
finfo_close($finfo);
$em->persist($entityversion);
$em->persist($entity);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename2 = $entityversion->getFilename();
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
//$entity->setExtention($extention);
copy($file, $path . $filename2);
$this->createThumbs($entityversion);
return $entity;
}
public function createFile($content, $mime, $ext, $filename, $folder, $kernelfile = null) {
$em = $this->em;
if (is_null($kernelfile) == true) {
$entity = new KernelFile();
//Voor 20181113 stond dit na de else
$entity->setName($filename);
$entity->setFolder($folder);
$entity->setState(0);
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setVersion("0.1");
$entityversion->setState(0);
} else {
$entity = $kernelfile;
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setVersion($this->getNextVersion($entity->getLastKernelFileVersion()->getVersion()));
}
$entityversion->setExtention($ext);
$entityversion->setMime($mime);
$em->persist($entityversion);
$em->persist($entity);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename2 = $entityversion->getFilename();
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
$file = fopen($path . $filename2, "w");
fwrite($file, $content);
fclose($file);
$this->createThumbs($entityversion);
return $entity;
}
public function addVersion($kernelfile, $upload) {
$em = $this->em;
$entityversion = new KernelFileVersion();
$entityversion->setState(0);
$entityversion->setKernelFile($kernelfile);
if ($kernelfile->getLastKernelFileVersion() != null) {
$entityversion->setVersion($this->getNextVersion($kernelfile->getLastKernelFileVersion()->getVersion()));
} else {
$entityversion->setVersion("0.1");
}
$entityversion->setFile($upload);
$em->persist($entityversion);
$em->flush();
$entityversion->upload();
$this->createThumbs($entityversion);
return $entityversion;
}
public function addVersionFile($kernelfile, $fileversiontoadd) {
$em = $this->em;
$entityversion = new KernelFileVersion();
$entityversion->setState(0);
$entityversion->setKernelFile($kernelfile);
$entityversion->setExtention($fileversiontoadd->getExtention());
$entityversion->setMime($fileversiontoadd->getExtention());
if ($kernelfile->getLastKernelFileVersion() != null) {
$entityversion->setVersion($this->getNextVersion($kernelfile->getLastKernelFileVersion()->getVersion()));
} else {
$entityversion->setVersion("0.1");
}
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
$file = $path . $filename;
$oldpath = $fileversiontoadd->getFileFolder() . "/";
$oldfilename = $fileversiontoadd->getFilename();
$oldfile = $oldpath . $oldfilename;
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
if (!copy($oldfile, $file)) {
echo "failed to copy";
}
//sleep(2);
$this->createThumbs($entityversion);
return $entityversion;
}
public function uploadfile($upload, $folder) {
$em = $this->em;
$entity = new KernelFile();
$entity->setFolder($folder);
$entity->setState(0);
$entity->setName($upload->getClientOriginalName());
$em->persist($entity);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setState(0);
$entityversion->setKernelFile($entity);
$entityversion->setVersion("0.1");
$entityversion->setFile($upload);
$em->persist($entityversion);
$em->flush();
$entityversion->upload();
$em->persist($entityversion);
$em->flush();
$this->createThumbs($entityversion);
return $entity;
}
public function upzipfile(\ZipArchive $zip,$filename,$folder) {
$entity = new KernelFile();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setVersion("0.1");
//$kernelfileversion = $kernelfile->getLastKernelFileVersion();
$fileinfo = pathinfo($filename);
$entity->setName($fileinfo['basename']);
$file_ext = $fileinfo['extension'] ?? null;
$entityversion->setExtention($file_ext);
$entity->setFolder($folder);
$entityversion->setThumb(null);
$entityversion->setState(0);
$entity->setState(0);
$this->em->persist($entity);
$this->em->persist($entityversion);
$this->em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename2 = $entityversion->getFilename();
$file = $path . $filename2;
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
$RETVAL = $zip->extractTo($path,$filename);
if ($RETVAL) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path."/".$filename);
$entityversion->setMime($mime);
finfo_close($finfo);
$size = filesize($path."/".$filename);
$entityversion->setSize($size);
rename($path."/".$filename,$path."/".$filename2);
$this->em->persist($entity);
$this->em->persist($entityversion);
$this->em->flush();
$this->createThumbs($entityversion);
} else {
echo "failed to copy";
}
return $entity;
}
public function deleteFileIfExist($filename, $folder) {
$em = $this->em;
if ($folder != null) {
$files2 = $folder->getKernelFiles();
$files = array();
foreach ($files2 as $file) {
if ($file->getGarbage() == false) {
if (strpos($file->getName(), $filename) !== false) {
$file->setState(2);
$em->persist($file);
$em->flush();
}
}
}
}
}
public function findFile($filename, $folder) {
$em = $this->em;
if ($folder != null) {
$files2 = $folder->getKernelFiles();
$files = array();
foreach ($files2 as $file) {
if ($file->getState() == 0) {
if (strpos($file->getName(), $filename) !== false) {
return $file;
}
}
}
}
return null;
}
public function testExcel($filename, $folder, $kernelfile = null) {
$em = $this->em;
$ext = "xls";
if (is_null($kernelfile) == true) {
$entity = new KernelFile();
} else {
$entity = $kernelfile;
}
$entity->setName($filename . "." . $ext);
$entity->setFolder($folder);
$entity->setState(0);
$em->persist($entity);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setExtention($ext);
$entityversion->setMime("application/vnd.ms-excel");
$entityversion->setTechnical(null);
$entityversion->setState(0);
if (is_null($kernelfile) == true) {
$entityversion->setVersion("0.1");
} else {
$entityversion->setVersion($this->getNextVersion($entity->getLastKernelFileVersion()->getVersion()));
}
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
if ( ! is_dir($path)) {
mkdir($path,0755,true);
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World 2 !');
$writer = new Xls($spreadsheet);
$writer->save($path . $filename);
$filesize = filesize($path . $filename);
$entityversion->setSize($filesize);
$this->em->persist($entityversion);
$this->em->flush();
}
public function createExcel($spreadsheet, $filename, $folder, $kernelfile = null) {
$em = $this->em;
$ext = "xls";
if (is_null($kernelfile) == true) {
$entity = new KernelFile();
} else {
$entity = $kernelfile;
}
$entity->setName($filename . "." . $ext);
$entity->setFolder($folder);
$entity->setState(0);
$em->persist($entity);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setExtention($ext);
$entityversion->setMime("application/vnd.ms-excel");
$entityversion->setTechnical(null);
$entityversion->setState(0);
if (is_null($kernelfile) == true) {
$entityversion->setVersion("0.1");
} else {
$entityversion->setVersion($this->getNextVersion($entity->getLastKernelFileVersion()->getVersion()));
}
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
if ( ! is_dir($path)) {
mkdir($path,0755,true);
}
/*$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World 2 !');*/
$writer = new Xls($spreadsheet);
$writer->save($path . $filename);
$filesize = filesize($path . $filename);
$entityversion->setSize($filesize);
$this->em->persist($entityversion);
$this->em->flush();
return $entity;
}
public function readExcel(KernelFile $kernelfile) {
$kernelFileVersion = $kernelfile->getLastKernelFileVersion();
$path = $kernelFileVersion->getFileFolder() . "/";
$filename = $kernelFileVersion->getFilename();
if ($kernelFileVersion->getExtention() == "xlsx")
{
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
}
else
{
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
}
$spreadsheet = $reader->load($path . $filename);
/*$sheet = $spreadsheet->getActiveSheet();
$value = $sheet->getCell('A1')->getValue();
$this->testExcel(substr($value, 0, 4), $kernelfile->getFolder());*/
return $spreadsheet;
}
public function testPDF($filename, $folder, $kernelfile = null) {
$em = $this->em;
$ext = "pdf";
if (is_null($kernelfile) == true) {
$entity = new KernelFile();
} else {
$entity = $kernelfile;
}
$entity->setName($filename . "." . $ext);
$entity->setFolder($folder);
$entity->setState(0);
$em->persist($entity);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($entity);
$entityversion->setExtention($ext);
$entityversion->setMime("application/pdf");
$entityversion->setTechnical(null);
$entityversion->setState(0);
if (is_null($kernelfile) == true) {
$entityversion->setVersion("0.1");
} else {
$entityversion->setVersion($this->getNextVersion($entity->getLastKernelFileVersion()->getVersion()));
}
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
if ( ! is_dir($path)) {
mkdir($path,0755,true);
}
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
//$dompdf->stream();
$output = $dompdf->output();
file_put_contents($path . $filename, $output);
$filesize = filesize($path . $filename);
$entityversion->setSize($filesize);
$this->em->persist($entityversion);
$this->em->flush();
}
function addHttp($url) {
// Search the pattern
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
// If not exist then add http
$url = "http://" . $url;
}
// Return the URL
return $url;
}
function addHttps($url) {
// Search the pattern
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
// If not exist then add http
$url = "https://" . $url;
}
// Return the URL
return $url;
}
public function createPDF($filename, $folder, $templatetype, $language = null, $entity=null, $part2iterator=null, $kernelfile = null, $organization=null, $additionalhtml =null) {
$twig = $this->twig;
$kernelService = $this->kernelService;
$templategroup = $kernelService->getApplicationInfoValue("Kernel.DefaultTemplate", $organization);
$em = $this->em;
$template = null;
$templatetypeid = $em->getRepository(TemplateType::class)->findOneByName($templatetype)->getId();
if ($language != null) {
$template = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'language' => $language->getId(), 'type' => $templatetypeid, 'state' => 0) // $where
);
}
if ($template == null) {
$template = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'type' => $templatetypeid, 'state' => 0) // $where
);
}
//$parameters = array();
$headertemplatetypeid = $em->getRepository(TemplateType::class)->findOneByName("TemplateType.Headerfooter")->getId();
$headertemplate = null;
if ($language != null) {
$headertemplate = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'language' => $language->getId(), 'type' => $headertemplatetypeid, 'state' => 0) // $where
);
}
if ($headertemplate == null) {
$headertemplate = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'type' => $headertemplatetypeid, 'state' => 0) // $where
);
}
$parameters = array();
$parameters["color1"] = $kernelService->getApplicationInfoValue("DocumentTemplate.Color1", $organization);
$parameters["color2"] = $kernelService->getApplicationInfoValue("DocumentTemplate.Color2", $organization);
$parameters["company"] = $kernelService->getApplicationInfoValue("Kernel.Company", $organization);
$parameters["address"] = $kernelService->getApplicationInfoValue("Kernel.Address", $organization);
$parameters["tax"] = $kernelService->getApplicationInfoValue("Kernel.Tax", $organization);
$parameters["phone"] = $kernelService->getApplicationInfoValue("Kernel.Phone", $organization);
$parameters["website"] = $kernelService->getApplicationInfoValue("Kernel.Website", $organization);
$parameters["httpwebsite"] = $this->addHttp($parameters["website"]);
$parameters["httpswebsite"] = $this->addHttps($parameters["website"]);
$parameters["iban"] = $kernelService->getApplicationInfoValue("Kernel.Iban", $organization);
$parameters["bic"] = $kernelService->getApplicationInfoValue("Kernel.Bic", $organization);
$parameters["email"] = $kernelService->getApplicationInfoValue("Kernel.Email", $organization);
$parameters["currency"] = $kernelService->getApplicationInfoValue("Kernel.DefaultCurrency", $organization);
$logo = $kernelService->getApplicationInfoFile("Kernel.Logo", $organization)->getLastKernelFileVersion();
$data = file_get_contents($logo->getFileFolder()."/".$logo->getFilename());
$base64 = 'data:image/' . $logo->getExtention() . ';base64,' . base64_encode($data);
$parameters["logo"] = $base64;
$parameters["entity"] = $entity;
$ext = "pdf";
if (is_null($kernelfile) == true) {
$kernelfilenew = new KernelFile();
} else {
$kernelfilenew = $kernelfile;
}
$kernelfilenew->setName($filename . "." . $ext);
$kernelfilenew->setFolder($folder);
$kernelfilenew->setState(0);
$em->persist($kernelfilenew);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($kernelfilenew);
$entityversion->setExtention($ext);
$entityversion->setMime("application/pdf");
$entityversion->setTechnical(null);
$entityversion->setState(0);
if (is_null($kernelfile) == true) {
$entityversion->setVersion("0.1");
} else {
$entityversion->setVersion($this->getNextVersion($kernelfilenew->getLastKernelFileVersion()->getVersion()));
}
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
if ( ! is_dir($path)) {
mkdir($path,0755,true);
}
$options = new \Dompdf\Options();
// set options indvidiually
$options->set('isPhpEnabled', true);
$options->set('IsRemoteEnabled', true);
$dompdf = new Dompdf($options);
//$newproduct = $this->translator->trans("Product.Newproduct");
$html = "<html>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<style>
@font-face {
font-family: 'Helvetica';
}
body {
padding: 0;
margin: 0;
font-family: Helvetica;
}
footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
z-index: 1000;
}
</style>
</head>
<body>
<footer>";
$html = $html . $twig->createTemplate($headertemplate->getPart2())->render($parameters);
$html = $html . "</footer><main>";
$html = $html . $twig->createTemplate($headertemplate->getPart1())->render($parameters);
$html = $html . $twig->createTemplate($template->getPart1())->render($parameters);
//$html = $twig->render($template->getPart1(), $parameters);
if ($part2iterator != null)
{
foreach ($part2iterator as $product) {
if ($product->getState() == 0)
{
$productarray = $parameters;
$productarray["product"] = $product;
$html = $html . $twig->createTemplate($template->getPart2())->render($productarray);
}
}
}
else
{
if (empty($template->getPart2()) == false)
{
$html = $html . $twig->createTemplate($template->getPart2())->render($parameters);
}
}
if (empty($template->getPart3()) == false)
{
$html = $html . $twig->createTemplate($template->getPart3())->render($parameters);
}
if (empty($additionalhtml) == false)
{
$html = $html . $twig->createTemplate($additionalhtml)->render($parameters);
}
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
//$dompdf->stream();
$output = $dompdf->output();
file_put_contents($path . $filename, $output);
$filesize = filesize($path . $filename);
$entityversion->setSize($filesize);
$this->em->persist($entityversion);
$this->em->flush();
return $kernelfilenew;
}
public function createUBL($filename, $folder, $entity=null, $kernelfile = null, $organization=null) {
$em = $this->em;
$kernelService = $this->kernelService;
$ext = "xml";
if (is_null($kernelfile) == true) {
$kernelfilenew = new KernelFile();
} else {
$kernelfilenew = $kernelfile;
}
$kernelfilenew->setName($filename . "." . $ext);
$kernelfilenew->setFolder($folder);
$kernelfilenew->setState(0);
$em->persist($kernelfilenew);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($kernelfilenew);
$entityversion->setExtention($ext);
$entityversion->setMime("application/xml");
$entityversion->setTechnical(null);
$entityversion->setState(0);
if (is_null($kernelfile) == true) {
$entityversion->setVersion("0.1");
} else {
$entityversion->setVersion($this->getNextVersion($kernelfilenew->getLastKernelFileVersion()->getVersion()));
}
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
if ( ! is_dir($path)) {
mkdir($path,0755,true);
}
// Address country
$country = (new \NumNum\UBL\Country())
->setIdentificationCode('BE');
// ->setListId('ISO3166-1:Alpha2');
// Tax scheme
$taxScheme = (new \NumNum\UBL\TaxScheme())
->setId("VAT");
// Full address
$supplierAddress = (new \NumNum\UBL\Address())
->setStreetName($kernelService->getApplicationInfoValue("Kernel.UBLStreetName", $organization))
->setCityName($kernelService->getApplicationInfoValue("Kernel.UBLCityName", $organization))
->setPostalZone($kernelService->getApplicationInfoValue("Kernel.UBLPostalZone", $organization))
->setCountry($country);
$supplierTaxScheme = (new \NumNum\UBL\PartyTaxScheme())
->setCompanyId($kernelService->getApplicationInfoValue("Kernel.Tax", $organization))
->setTaxScheme($taxScheme);
$supplierLegalEntity = (new \NumNum\UBL\LegalEntity())
->setRegistrationName($kernelService->getApplicationInfoValue("Kernel.Company", $organization))
->setCompanyId($kernelService->getApplicationInfoValue("Kernel.Tax", $organization));
$supplierContact = (new \NumNum\UBL\Contact())
->setElectronicMail($kernelService->getApplicationInfoValue("Kernel.Email", $organization))
->setTelephone($kernelService->getApplicationInfoValue("Kernel.Phone", $organization));
// Supplier company node
$supplierCompany = (new \NumNum\UBL\Party())
->setName($kernelService->getApplicationInfoValue("Kernel.Company", $organization))
->setLegalEntity($supplierLegalEntity)
->setPartyTaxScheme($supplierTaxScheme)
->setContact($supplierContact)
->setPostalAddress($supplierAddress);
$clientAddress = (new \NumNum\UBL\Address())
->setStreetName($entity->getStreet() . ' ' . $entity->getHousenumber())
->setCityName($entity->getMunicipality())
->setPostalZone($entity->getPostcode())
->setCountry($country);
$clientLegalEntity = (new \NumNum\UBL\LegalEntity())
->setRegistrationName($entity->getClientString())
->setCompanyId($entity->getTax());
// Client company node
$clientCompany = (new \NumNum\UBL\Party())
->setName($entity->getClientString())
->setLegalEntity($clientLegalEntity)
->setPostalAddress($clientAddress);
$legalMonetaryTotal = (new \NumNum\UBL\LegalMonetaryTotal())
->setPayableAmount(round($entity->getTotalWithTaxAmount(), 2))
->setTaxExclusiveAmount(round($entity->getTotalAmount(), 2))
->setTaxInclusiveAmount(round($entity->getTotalWithTaxAmount(), 2))
->setLineExtensionAmount(round($entity->getTotalAmount(), 2))
->setAllowanceTotalAmount(0);
$categoryArray = array();
$emptyarray = array();
$taxeslist = $kernelService->getList('Finance.tax');
$taxeslistitems = $em->getRepository(ListItem::class)->findBy(array('configurablelist' => $taxeslist, 'state' => 0));
foreach ($taxeslistitems as $taxeslistitem)
{
$newtaxeslistitem = array();
$newtaxeslistitem[] = $taxeslistitem->getId();
$newtaxeslistitem[] = $taxeslistitem->getFloat1();
$newtaxeslistitem[] = (new \NumNum\UBL\TaxCategory())
->setId('S', $emptyarray)
->setPercent($taxeslistitem->getFloat1()*100)
->setTaxScheme($taxScheme);
$newtaxeslistitem[] = (new \NumNum\UBL\ClassifiedTaxCategory())
->setId('S')
->setPercent($taxeslistitem->getFloat1()*100)
->setTaxScheme($taxScheme);
$newtaxeslistitem[] = 0;
$newtaxeslistitem[] = 0;
$categoryArray[] = $newtaxeslistitem;
}
$invoiceLines = array();
$i = 0;
$taxTotal = (new \NumNum\UBL\TaxTotal())
->setTaxAmount(round($entity->getTotalTaxAmount(), 2));
foreach ($entity->getInvoiceproducts() as $product)
{
if($product->getState() == 0)
{
$classifiedTaxCategory = null;
$taxCategory = null;
$taxpercentage = 0;
for ($j=0; $j<count($categoryArray); $j++)
{
$category = $categoryArray[$j];
if ($category[0] == $product->getTaxRate()->getId())
{
$classifiedTaxCategory = $category[3];
$taxCategory = $category[2];
$taxpercentage = $category[1];
// Product
$productItem = (new \NumNum\UBL\Item())
->setName($product->getName())->setClassifiedTaxCategory($classifiedTaxCategory)
;
// Price
$price = (new \NumNum\UBL\Price())
->setBaseQuantity(1)
->setUnitCode(\NumNum\UBL\UnitCode::UNIT)
//->setUnitCodeListId('UNECERec20')
->setPriceAmount($product->getUnitPrice());
// Invoice Line(s)
$invoiceLine = (new \NumNum\UBL\InvoiceLine())
->setId($i)
->setItem($productItem)
->setUnitCode(\NumNum\UBL\UnitCode::UNIT)
//->setUnitCodeListID('UNECERec20')
->setPrice($price)
->setLineExtensionAmount($product->getUnitPrice() * $product->getQuantity())
->setItem($productItem)
->setInvoicedQuantity($product->getQuantity());
$i++;
$categoryArray[$j][4] = $categoryArray[$j][4] + ($product->getUnitPrice() * $product->getQuantity());
$categoryArray[$j][5] = $categoryArray[$j][5] + round($product->getUnitPrice() * $product->getQuantity() * $taxpercentage , 2);
/*$taxSubTotal = (new \NumNum\UBL\TaxSubTotal())
->setTaxableAmount($product->getUnitPrice() * $product->getQuantity())
->setTaxAmount(round($product->getUnitPrice() * $product->getQuantity() * $taxpercentage , 2))
->setTaxCategory($taxCategory);*/
$invoiceLines[] = $invoiceLine;
}
}
}
}
foreach ($categoryArray as $category)
{
if ($category[4] != 0)
{
$taxSubTotal = (new \NumNum\UBL\TaxSubTotal())
->setTaxableAmount($category[4])
->setTaxAmount($category[5])
->setTaxCategory($category[2]);
$taxTotal->addTaxSubTotal($taxSubTotal);
}
}
// Total Taxes
$paymentTerms = (new \NumNum\UBL\PaymentTerms())
->setNote($entity->getSalesConditionText());
$financialInstitutionBranch = (new \NumNum\UBL\FinancialInstitutionBranch())
->setId($kernelService->getApplicationInfoValue("Kernel.Bic", $organization));
$payeeFinancialAccount = (new \NumNum\UBL\PayeeFinancialAccount())
->setId($kernelService->getApplicationInfoValue("Kernel.Iban", $organization))
->setFinancialInstitutionBranch($financialInstitutionBranch);
$paymentMeans = (new \NumNum\UBL\PaymentMeans())
->setPaymentMeansCode(31, array())
->setPayeeFinancialAccount($payeeFinancialAccount);
$additionalDocumentReference = null;
$this->em->refresh($entity);
if ($entity->getPdf() != null)
{
$pdf = $entity->getPdf();
$this->em->refresh($pdf);
$kernelFileVersion = $pdf->getLastKernelFileVersion();
if ($kernelFileVersion != null)
{
$path2 = $kernelFileVersion->getFileFolder() . "/";
$filename2 = $kernelFileVersion->getFilename();
$attachment = new \NumNum\UBL\Attachment();
$attachment->setFilePath($path2 . $filename2);
//if($attachment->validate() == true)
//{
$additionalDocumentReference = new \NumNum\UBL\AdditionalDocumentReference();
$additionalDocumentReference->setId(''.$kernelFileVersion->getId());
$additionalDocumentReference->setDocumentDescription("Invoice");
//$additionalDocumentReference->setDocumentType("pdf");
$additionalDocumentReference->setAttachment($attachment);
//}
}
}
// Invoice object
$invoice = (new \NumNum\UBL\Invoice())
//->setUBLVersionID('2.1')
->setId($entity->getInvoiceNumber())
->setIssueDate($entity->getInvoiceDate())
->setAccountingSupplierParty($supplierCompany)
->setAccountingCustomerParty($clientCompany)
->setInvoiceTypeCode(380)
//->setNote("invoice number: " . $entity->getInvoiceNumber() . " - " . $entity->getAbout())
->setNote($entity->getInvoiceNumber())
->setInvoiceLines($invoiceLines)
->setLegalMonetaryTotal($legalMonetaryTotal)
->setTaxTotal($taxTotal)
->setPaymentTerms($paymentTerms)
->setPaymentMeans($paymentMeans);
if ($additionalDocumentReference != null)
{
$invoice->setAdditionalDocumentReference($additionalDocumentReference);
}
//->setProfileID("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")
;
// Test created object
// Use \NumNum\UBL\Generator to generate an XML string
$generator = new \NumNum\UBL\Generator();
$outputXMLString = $generator->invoice($invoice);
// Create PHP Native DomDocument object, that can be
// used to validate the generate XML
$dom = new \DOMDocument;
$dom->loadXML($outputXMLString);
$dom->save($path . $filename);
//$output = $dompdf->output();
//file_put_contents($path . $filename, $output);
$filesize = filesize($path . $filename);
$entityversion->setSize($filesize);
$this->em->persist($entityversion);
$this->em->flush();
return $kernelfilenew;
}
public function createUBLCreditNote($filename, $folder, $entity=null, $kernelfile = null, $organization=null) {
$em = $this->em;
$kernelService = $this->kernelService;
$ext = "xml";
if (is_null($kernelfile) == true) {
$kernelfilenew = new KernelFile();
} else {
$kernelfilenew = $kernelfile;
}
$kernelfilenew->setName($filename . "." . $ext);
$kernelfilenew->setFolder($folder);
$kernelfilenew->setState(0);
$em->persist($kernelfilenew);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($kernelfilenew);
$entityversion->setExtention($ext);
$entityversion->setMime("application/xml");
$entityversion->setTechnical(null);
$entityversion->setState(0);
if (is_null($kernelfile) == true) {
$entityversion->setVersion("0.1");
} else {
$entityversion->setVersion($this->getNextVersion($kernelfilenew->getLastKernelFileVersion()->getVersion()));
}
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
if ( ! is_dir($path)) {
mkdir($path,0755,true);
}
// Address country
$country = (new \NumNum\UBL\Country())
->setIdentificationCode('BE');
// ->setListId('ISO3166-1:Alpha2');
// Tax scheme
$taxScheme = (new \NumNum\UBL\TaxScheme())
->setId("VAT");
// Full address
$supplierAddress = (new \NumNum\UBL\Address())
->setStreetName($kernelService->getApplicationInfoValue("Kernel.UBLStreetName", $organization))
->setCityName($kernelService->getApplicationInfoValue("Kernel.UBLCityName", $organization))
->setPostalZone($kernelService->getApplicationInfoValue("Kernel.UBLPostalZone", $organization))
->setCountry($country);
$supplierTaxScheme = (new \NumNum\UBL\PartyTaxScheme())
->setCompanyId($kernelService->getApplicationInfoValue("Kernel.Tax", $organization))
->setTaxScheme($taxScheme);
$supplierLegalEntity = (new \NumNum\UBL\LegalEntity())
->setRegistrationName($kernelService->getApplicationInfoValue("Kernel.Company", $organization))
->setCompanyId($kernelService->getApplicationInfoValue("Kernel.Tax", $organization));
$supplierContact = (new \NumNum\UBL\Contact())
->setElectronicMail($kernelService->getApplicationInfoValue("Kernel.Email", $organization))
->setTelephone($kernelService->getApplicationInfoValue("Kernel.Phone", $organization));
// Supplier company node
$supplierCompany = (new \NumNum\UBL\Party())
->setName($kernelService->getApplicationInfoValue("Kernel.Company", $organization))
->setLegalEntity($supplierLegalEntity)
->setPartyTaxScheme($supplierTaxScheme)
->setContact($supplierContact)
->setPostalAddress($supplierAddress);
$clientAddress = (new \NumNum\UBL\Address())
->setStreetName($entity->getStreet() . ' ' . $entity->getHousenumber())
->setCityName($entity->getMunicipality())
->setPostalZone($entity->getPostcode())
->setCountry($country);
$clientLegalEntity = (new \NumNum\UBL\LegalEntity())
->setRegistrationName($entity->getClientString())
->setCompanyId($entity->getTax());
// Client company node
$clientCompany = (new \NumNum\UBL\Party())
->setName($entity->getClientString())
->setLegalEntity($clientLegalEntity)
->setPostalAddress($clientAddress);
$legalMonetaryTotal = (new \NumNum\UBL\LegalMonetaryTotal())
->setPayableAmount(round($entity->getTotalWithTaxAmount(), 2))
->setTaxExclusiveAmount(round($entity->getTotalAmount(), 2))
->setTaxInclusiveAmount(round($entity->getTotalWithTaxAmount(), 2))
->setLineExtensionAmount(round($entity->getTotalAmount(), 2))
->setAllowanceTotalAmount(0);
$categoryArray = array();
$emptyarray = array();
$taxeslist = $kernelService->getList('Finance.tax');
$taxeslistitems = $em->getRepository(ListItem::class)->findBy(array('configurablelist' => $taxeslist, 'state' => 0));
foreach ($taxeslistitems as $taxeslistitem)
{
$newtaxeslistitem = array();
$newtaxeslistitem[] = $taxeslistitem->getId();
$newtaxeslistitem[] = $taxeslistitem->getFloat1();
$newtaxeslistitem[] = (new \NumNum\UBL\TaxCategory())
->setId('S', $emptyarray)
->setPercent($taxeslistitem->getFloat1()*100)
->setTaxScheme($taxScheme);
$newtaxeslistitem[] = (new \NumNum\UBL\ClassifiedTaxCategory())
->setId('S')
->setPercent($taxeslistitem->getFloat1()*100)
->setTaxScheme($taxScheme);
$newtaxeslistitem[] = 0;
$newtaxeslistitem[] = 0;
$categoryArray[] = $newtaxeslistitem;
}
$invoiceLines = array();
$i = 0;
$taxTotal = (new \NumNum\UBL\TaxTotal())
->setTaxAmount(round($entity->getTotalTaxAmount(), 2));
foreach ($entity->getCreditnoteproducts() as $product)
{
if($product->getState() == 0)
{
$classifiedTaxCategory = null;
$taxCategory = null;
$taxpercentage = 0;
for ($j=0; $j<count($categoryArray); $j++)
{
$category = $categoryArray[$j];
if ($category[0] == $product->getTaxRate()->getId())
{
$classifiedTaxCategory = $category[3];
$taxCategory = $category[2];
$taxpercentage = $category[1];
// Product
$productItem = (new \NumNum\UBL\Item())
->setName($product->getName())->setClassifiedTaxCategory($classifiedTaxCategory)
;
// Price
$price = (new \NumNum\UBL\Price())
->setBaseQuantity(1)
->setUnitCode(\NumNum\UBL\UnitCode::UNIT)
//->setUnitCodeListId('UNECERec20')
->setPriceAmount($product->getUnitPrice());
// Invoice Line(s)
$invoiceLine = (new \NumNum\UBL\CreditNoteLine())
->setId($i)
->setItem($productItem)
->setUnitCode(\NumNum\UBL\UnitCode::UNIT)
//->setUnitCodeListID('UNECERec20')
->setPrice($price)
->setLineExtensionAmount($product->getUnitPrice() * $product->getQuantity())
->setItem($productItem)
->setInvoicedQuantity($product->getQuantity());
$i++;
$categoryArray[$j][4] = $categoryArray[$j][4] + ($product->getUnitPrice() * $product->getQuantity());
$categoryArray[$j][5] = $categoryArray[$j][5] + round($product->getUnitPrice() * $product->getQuantity() * $taxpercentage , 2);
/*$taxSubTotal = (new \NumNum\UBL\TaxSubTotal())
->setTaxableAmount($product->getUnitPrice() * $product->getQuantity())
->setTaxAmount(round($product->getUnitPrice() * $product->getQuantity() * $taxpercentage , 2))
->setTaxCategory($taxCategory);*/
$invoiceLines[] = $invoiceLine;
}
}
}
}
foreach ($categoryArray as $category)
{
if ($category[4] != 0)
{
$taxSubTotal = (new \NumNum\UBL\TaxSubTotal())
->setTaxableAmount($category[4])
->setTaxAmount($category[5])
->setTaxCategory($category[2]);
$taxTotal->addTaxSubTotal($taxSubTotal);
}
}
// Total Taxes
$paymentTerms = (new \NumNum\UBL\PaymentTerms())
->setNote($entity->getSalesConditionText());
$financialInstitutionBranch = (new \NumNum\UBL\FinancialInstitutionBranch())
->setId($kernelService->getApplicationInfoValue("Kernel.Bic", $organization));
$payeeFinancialAccount = (new \NumNum\UBL\PayeeFinancialAccount())
->setId($kernelService->getApplicationInfoValue("Kernel.Iban", $organization))
->setFinancialInstitutionBranch($financialInstitutionBranch);
$paymentMeans = (new \NumNum\UBL\PaymentMeans())
->setPaymentMeansCode(31, array())
->setPayeeFinancialAccount($payeeFinancialAccount);
$additionalDocumentReference = null;
$this->em->refresh($entity);
if ($entity->getPdf() != null)
{
$pdf = $entity->getPdf();
$this->em->refresh($pdf);
$kernelFileVersion = $pdf->getLastKernelFileVersion();
if ($kernelFileVersion != null)
{
$path2 = $kernelFileVersion->getFileFolder() . "/";
$filename2 = $kernelFileVersion->getFilename();
$attachment = new \NumNum\UBL\Attachment();
$attachment->setFilePath($path2 . $filename2);
//if($attachment->validate() == true)
//{
$additionalDocumentReference = new \NumNum\UBL\AdditionalDocumentReference();
$additionalDocumentReference->setId(''.$kernelFileVersion->getId());
$additionalDocumentReference->setDocumentDescription("Credit Note");
//$additionalDocumentReference->setDocumentType("pdf");
$additionalDocumentReference->setAttachment($attachment);
//}
}
}
// Invoice object
$creditnote = (new \NumNum\UBL\CreditNote())
//->setUBLVersionID('2.1')
->setId($entity->getCreditNoteNumber())
->setIssueDate($entity->getCreditNoteDate())
->setAccountingSupplierParty($supplierCompany)
->setAccountingCustomerParty($clientCompany)
->setInvoiceTypeCode(\NumNum\UBL\InvoiceTypeCode::CREDIT_NOTE)
//->setNote("credit note number: " . $entity->getCreditNoteNumber() . " - " . $entity->getAbout())
->setNote($entity->getCreditNoteNumber())
->setInvoiceLines($invoiceLines)
->setLegalMonetaryTotal($legalMonetaryTotal)
->setTaxTotal($taxTotal)
->setPaymentTerms($paymentTerms)
->setPaymentMeans($paymentMeans);
if ($additionalDocumentReference != null)
{
$creditnote->setAdditionalDocumentReference($additionalDocumentReference);
}
//->setProfileID("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")
;
// Test created object
// Use \NumNum\UBL\Generator to generate an XML string
$generator = new \NumNum\UBL\Generator();
$outputXMLString = $generator->invoice($creditnote);
// Create PHP Native DomDocument object, that can be
// used to validate the generate XML
$dom = new \DOMDocument;
$dom->loadXML($outputXMLString);
$dom->save($path . $filename);
//$output = $dompdf->output();
//file_put_contents($path . $filename, $output);
$filesize = filesize($path . $filename);
$entityversion->setSize($filesize);
$this->em->persist($entityversion);
$this->em->flush();
return $kernelfilenew;
}
public function createMultiInvoicePDF($filename, $folder, $templatetype, $entities, $organization=null, $creditnotes = null) {
$twig = $this->twig;
$kernelService = $this->kernelService;
$templategroup = $kernelService->getApplicationInfoValue("Kernel.DefaultTemplate", $organization);
$em = $this->em;
$additionalhtml =null;
$ext = "pdf";
$kernelfilenew = new KernelFile();
$kernelfilenew->setName($filename . "." . $ext);
$kernelfilenew->setFolder($folder);
$kernelfilenew->setState(0);
$em->persist($kernelfilenew);
$em->flush();
$entityversion = new KernelFileVersion();
$entityversion->setKernelFile($kernelfilenew);
$entityversion->setExtention($ext);
$entityversion->setMime("application/pdf");
$entityversion->setTechnical(null);
$entityversion->setState(0);
$entityversion->setVersion("0.1");
$em->persist($entityversion);
$em->flush();
$path = $entityversion->getFileFolder() . "/";
$filename = $entityversion->getFilename();
if (!is_dir($path)) {
mkdir($path, 0755, true);
}
$options = new \Dompdf\Options();
// set options indvidiually
$options->set('isPhpEnabled', true);
$options->set('IsRemoteEnabled', true);
$dompdf = new Dompdf($options);
$html = "";
$first = true;
foreach ($entities as $entity)
{
if ($first == true)
{
$first = false;
} else
{
$html = $html . "<div class='page_break'></div>";
}
$language = $entity->getLanguage();
$part2iterator= $entity->getInvoiceproducts();
$template = null;
$templatetypeid = $em->getRepository(TemplateType::class)->findOneByName($templatetype)->getId();
if ($language != null) {
$template = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'language' => $language->getId(), 'type' => $templatetypeid, 'state' => 0) // $where
);
}
if ($template == null) {
$template = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'type' => $templatetypeid, 'state' => 0) // $where
);
}
$headertemplatetypeid = $em->getRepository(TemplateType::class)->findOneByName("TemplateType.Headerfooter")->getId();
$headertemplate = null;
if ($language != null) {
$headertemplate = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'language' => $language->getId(), 'type' => $headertemplatetypeid, 'state' => 0) // $where
);
}
if ($headertemplate == null) {
$headertemplate = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'type' => $headertemplatetypeid, 'state' => 0) // $where
);
}
$parameters = array();
$parameters["color1"] = $kernelService->getApplicationInfoValue("DocumentTemplate.Color1", $organization);
$parameters["color2"] = $kernelService->getApplicationInfoValue("DocumentTemplate.Color2", $organization);
$parameters["company"] = $kernelService->getApplicationInfoValue("Kernel.Company", $organization);
$parameters["address"] = $kernelService->getApplicationInfoValue("Kernel.Address", $organization);
$parameters["tax"] = $kernelService->getApplicationInfoValue("Kernel.Tax", $organization);
$parameters["phone"] = $kernelService->getApplicationInfoValue("Kernel.Phone", $organization);
$parameters["website"] = $kernelService->getApplicationInfoValue("Kernel.Website", $organization);
$parameters["httpwebsite"] = $this->addHttp($parameters["website"]);
$parameters["httpswebsite"] = $this->addHttps($parameters["website"]);
$parameters["iban"] = $kernelService->getApplicationInfoValue("Kernel.Iban", $organization);
$parameters["bic"] = $kernelService->getApplicationInfoValue("Kernel.Bic", $organization);
$parameters["email"] = $kernelService->getApplicationInfoValue("Kernel.Email", $organization);
$parameters["currency"] = $kernelService->getApplicationInfoValue("Kernel.DefaultCurrency", $organization);
$logo = $kernelService->getApplicationInfoFile("Kernel.Logo", $organization)->getLastKernelFileVersion();
$data = file_get_contents($logo->getFileFolder()."/".$logo->getFilename());
$base64 = 'data:image/' . $logo->getExtention() . ';base64,' . base64_encode($data);
$parameters["logo"] = $base64;
$parameters["entity"] = $entity;
$html = $html . "<html>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<style>
@font-face {
font-family: 'Helvetica';
}
body {
padding: 0;
margin: 0;
font-family: Helvetica;
}
footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
z-index: 1000;
}
.page_break { page-break-before: always; }
</style>
</head>
<body>
<footer>";
$html = $html . $twig->createTemplate($headertemplate->getPart2())->render($parameters);
$html = $html . "</footer><main>";
$html = $html . $twig->createTemplate($headertemplate->getPart1())->render($parameters);
$html = $html . $twig->createTemplate($template->getPart1())->render($parameters);
//$html = $twig->render($template->getPart1(), $parameters);
if ($part2iterator != null)
{
foreach ($part2iterator as $product) {
if ($product->getState() == 0)
{
$productarray = $parameters;
$productarray["product"] = $product;
$html = $html . $twig->createTemplate($template->getPart2())->render($productarray);
}
}
}
else
{
if (empty($template->getPart2()) == false)
{
$html = $html . $twig->createTemplate($template->getPart2())->render($parameters);
}
}
if (empty($template->getPart3()) == false)
{
$html = $html . $twig->createTemplate($template->getPart3())->render($parameters);
}
if (empty($additionalhtml) == false)
{
$html = $html . $twig->createTemplate($additionalhtml)->render($parameters);
}
}
if ($creditnotes != null)
{
foreach ($creditnotes as $entity)
{
if ($first == true)
{
$first = false;
} else
{
$html = $html . "<div class='page_break'></div>";
}
$language = $entity->getLanguage();
$part2iterator= $entity->getCreditnoteproducts();
$templatetype = "TemplateType.CreditNote";
$template = null;
$templatetypeid = $em->getRepository(TemplateType::class)->findOneByName($templatetype)->getId();
if ($language != null) {
$template = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'language' => $language->getId(), 'type' => $templatetypeid, 'state' => 0) // $where
);
}
if ($template == null) {
$template = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'type' => $templatetypeid, 'state' => 0) // $where
);
}
$headertemplatetypeid = $em->getRepository(TemplateType::class)->findOneByName("TemplateType.Headerfooter")->getId();
$headertemplate = null;
if ($language != null) {
$headertemplate = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'language' => $language->getId(), 'type' => $headertemplatetypeid, 'state' => 0) // $where
);
}
if ($headertemplate == null) {
$headertemplate = $em->getRepository(DocumentTemplate::class)->findOneBy(
array('documenttemplategroup' => $templategroup, 'type' => $headertemplatetypeid, 'state' => 0) // $where
);
}
$parameters = array();
$parameters["color1"] = $kernelService->getApplicationInfoValue("DocumentTemplate.Color1", $organization);
$parameters["color2"] = $kernelService->getApplicationInfoValue("DocumentTemplate.Color2", $organization);
$parameters["company"] = $kernelService->getApplicationInfoValue("Kernel.Company", $organization);
$parameters["address"] = $kernelService->getApplicationInfoValue("Kernel.Address", $organization);
$parameters["tax"] = $kernelService->getApplicationInfoValue("Kernel.Tax", $organization);
$parameters["phone"] = $kernelService->getApplicationInfoValue("Kernel.Phone", $organization);
$parameters["website"] = $kernelService->getApplicationInfoValue("Kernel.Website", $organization);
$parameters["httpwebsite"] = $this->addHttp($parameters["website"]);
$parameters["httpswebsite"] = $this->addHttps($parameters["website"]);
$parameters["iban"] = $kernelService->getApplicationInfoValue("Kernel.Iban", $organization);
$parameters["bic"] = $kernelService->getApplicationInfoValue("Kernel.Bic", $organization);
$parameters["email"] = $kernelService->getApplicationInfoValue("Kernel.Email", $organization);
$parameters["currency"] = $kernelService->getApplicationInfoValue("Kernel.DefaultCurrency", $organization);
$logo = $kernelService->getApplicationInfoFile("Kernel.Logo", $organization)->getLastKernelFileVersion();
$data = file_get_contents($logo->getFileFolder()."/".$logo->getFilename());
$base64 = 'data:image/' . $logo->getExtention() . ';base64,' . base64_encode($data);
$parameters["logo"] = $base64;
$parameters["entity"] = $entity;
$html = $html . "<html>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<style>
@font-face {
font-family: 'Helvetica';
}
body {
padding: 0;
margin: 0;
font-family: Helvetica;
}
footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 50px;
z-index: 1000;
}
.page_break { page-break-before: always; }
</style>
</head>
<body>
<footer>";
$html = $html . $twig->createTemplate($headertemplate->getPart2())->render($parameters);
$html = $html . "</footer><main>";
$html = $html . $twig->createTemplate($headertemplate->getPart1())->render($parameters);
$html = $html . $twig->createTemplate($template->getPart1())->render($parameters);
//$html = $twig->render($template->getPart1(), $parameters);
if ($part2iterator != null)
{
foreach ($part2iterator as $product) {
if ($product->getState() == 0)
{
$productarray = $parameters;
$productarray["product"] = $product;
$html = $html . $twig->createTemplate($template->getPart2())->render($productarray);
}
}
}
else
{
if (empty($template->getPart2()) == false)
{
$html = $html . $twig->createTemplate($template->getPart2())->render($parameters);
}
}
if (empty($template->getPart3()) == false)
{
$html = $html . $twig->createTemplate($template->getPart3())->render($parameters);
}
if (empty($additionalhtml) == false)
{
$html = $html . $twig->createTemplate($additionalhtml)->render($parameters);
}
}
}
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
//$dompdf->stream();
$output = $dompdf->output();
file_put_contents($path . $filename, $output);
$filesize = filesize($path . $filename);
$entityversion->setSize($filesize);
$this->em->persist($entityversion);
$this->em->flush();
$this->em->persist($kernelfilenew);
$this->em->flush();
$this->em->refresh($kernelfilenew);
return $kernelfilenew;
}
function mime2ext($mime) {
$mime_map = [
'video/3gpp2' => '3g2',
'video/3gp' => '3gp',
'video/3gpp' => '3gp',
'application/x-compressed' => '7zip',
'audio/x-acc' => 'aac',
'audio/ac3' => 'ac3',
'application/postscript' => 'ai',
'audio/x-aiff' => 'aif',
'audio/aiff' => 'aif',
'audio/x-au' => 'au',
'video/x-msvideo' => 'avi',
'video/msvideo' => 'avi',
'video/avi' => 'avi',
'application/x-troff-msvideo' => 'avi',
'application/macbinary' => 'bin',
'application/mac-binary' => 'bin',
'application/x-binary' => 'bin',
'application/x-macbinary' => 'bin',
'image/bmp' => 'bmp',
'image/x-bmp' => 'bmp',
'image/x-bitmap' => 'bmp',
'image/x-xbitmap' => 'bmp',
'image/x-win-bitmap' => 'bmp',
'image/x-windows-bmp' => 'bmp',
'image/ms-bmp' => 'bmp',
'image/x-ms-bmp' => 'bmp',
'application/bmp' => 'bmp',
'application/x-bmp' => 'bmp',
'application/x-win-bitmap' => 'bmp',
'application/cdr' => 'cdr',
'application/coreldraw' => 'cdr',
'application/x-cdr' => 'cdr',
'application/x-coreldraw' => 'cdr',
'image/cdr' => 'cdr',
'image/x-cdr' => 'cdr',
'zz-application/zz-winassoc-cdr' => 'cdr',
'application/mac-compactpro' => 'cpt',
'application/pkix-crl' => 'crl',
'application/pkcs-crl' => 'crl',
'application/x-x509-ca-cert' => 'crt',
'application/pkix-cert' => 'crt',
'text/css' => 'css',
'text/x-comma-separated-values' => 'csv',
'text/comma-separated-values' => 'csv',
'application/vnd.msexcel' => 'csv',
'application/x-director' => 'dcr',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
'application/x-dvi' => 'dvi',
'message/rfc822' => 'eml',
'application/x-msdownload' => 'exe',
'video/x-f4v' => 'f4v',
'audio/x-flac' => 'flac',
'video/x-flv' => 'flv',
'image/gif' => 'gif',
'application/gpg-keys' => 'gpg',
'application/x-gtar' => 'gtar',
'application/x-gzip' => 'gzip',
'application/mac-binhex40' => 'hqx',
'application/mac-binhex' => 'hqx',
'application/x-binhex40' => 'hqx',
'application/x-mac-binhex40' => 'hqx',
'text/html' => 'html',
'image/x-icon' => 'ico',
'image/x-ico' => 'ico',
'image/vnd.microsoft.icon' => 'ico',
'text/calendar' => 'ics',
'application/java-archive' => 'jar',
'application/x-java-application' => 'jar',
'application/x-jar' => 'jar',
'image/jp2' => 'jp2',
'video/mj2' => 'jp2',
'image/jpx' => 'jp2',
'image/jpm' => 'jp2',
'image/jpeg' => 'jpeg',
'image/pjpeg' => 'jpeg',
'application/x-javascript' => 'js',
'application/json' => 'json',
'text/json' => 'json',
'application/vnd.google-earth.kml+xml' => 'kml',
'application/vnd.google-earth.kmz' => 'kmz',
'text/x-log' => 'log',
'audio/x-m4a' => 'm4a',
'audio/mp4' => 'm4a',
'application/vnd.mpegurl' => 'm4u',
'audio/midi' => 'mid',
'application/vnd.mif' => 'mif',
'video/quicktime' => 'mov',
'video/x-sgi-movie' => 'movie',
'audio/mpeg' => 'mp3',
'audio/mpg' => 'mp3',
'audio/mpeg3' => 'mp3',
'audio/mp3' => 'mp3',
'video/mp4' => 'mp4',
'video/mpeg' => 'mpeg',
'application/oda' => 'oda',
'audio/ogg' => 'ogg',
'video/ogg' => 'ogg',
'application/ogg' => 'ogg',
'font/otf' => 'otf',
'application/x-pkcs10' => 'p10',
'application/pkcs10' => 'p10',
'application/x-pkcs12' => 'p12',
'application/x-pkcs7-signature' => 'p7a',
'application/pkcs7-mime' => 'p7c',
'application/x-pkcs7-mime' => 'p7c',
'application/x-pkcs7-certreqresp' => 'p7r',
'application/pkcs7-signature' => 'p7s',
'application/pdf' => 'pdf',
'application/octet-stream' => 'pdf',
'application/x-x509-user-cert' => 'pem',
'application/x-pem-file' => 'pem',
'application/pgp' => 'pgp',
'application/x-httpd-php' => 'php',
'application/php' => 'php',
'application/x-php' => 'php',
'text/php' => 'php',
'text/x-php' => 'php',
'application/x-httpd-php-source' => 'php',
'image/png' => 'png',
'image/x-png' => 'png',
'application/powerpoint' => 'ppt',
'application/vnd.ms-powerpoint' => 'ppt',
'application/vnd.ms-office' => 'ppt',
'application/msword' => 'doc',
'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
'application/x-photoshop' => 'psd',
'image/vnd.adobe.photoshop' => 'psd',
'audio/x-realaudio' => 'ra',
'audio/x-pn-realaudio' => 'ram',
'application/x-rar' => 'rar',
'application/rar' => 'rar',
'application/x-rar-compressed' => 'rar',
'audio/x-pn-realaudio-plugin' => 'rpm',
'application/x-pkcs7' => 'rsa',
'text/rtf' => 'rtf',
'text/richtext' => 'rtx',
'video/vnd.rn-realvideo' => 'rv',
'application/x-stuffit' => 'sit',
'application/smil' => 'smil',
'text/srt' => 'srt',
'image/svg+xml' => 'svg',
'application/x-shockwave-flash' => 'swf',
'application/x-tar' => 'tar',
'application/x-gzip-compressed' => 'tgz',
'image/tiff' => 'tiff',
'font/ttf' => 'ttf',
'text/plain' => 'txt',
'text/x-vcard' => 'vcf',
'application/videolan' => 'vlc',
'text/vtt' => 'vtt',
'audio/x-wav' => 'wav',
'audio/wave' => 'wav',
'audio/wav' => 'wav',
'application/wbxml' => 'wbxml',
'video/webm' => 'webm',
'image/webp' => 'webp',
'audio/x-ms-wma' => 'wma',
'application/wmlc' => 'wmlc',
'video/x-ms-wmv' => 'wmv',
'video/x-ms-asf' => 'wmv',
'font/woff' => 'woff',
'font/woff2' => 'woff2',
'application/xhtml+xml' => 'xhtml',
'application/excel' => 'xl',
'application/msexcel' => 'xls',
'application/x-msexcel' => 'xls',
'application/x-ms-excel' => 'xls',
'application/x-excel' => 'xls',
'application/x-dos_ms_excel' => 'xls',
'application/xls' => 'xls',
'application/x-xls' => 'xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
'application/vnd.ms-excel' => 'xlsx',
'application/xml' => 'xml',
'text/xml' => 'xml',
'text/xsl' => 'xsl',
'application/xspf+xml' => 'xspf',
'application/x-compress' => 'z',
'application/x-zip' => 'zip',
'application/zip' => 'zip',
'application/x-zip-compressed' => 'zip',
'application/s-compressed' => 'zip',
'multipart/x-zip' => 'zip',
'text/x-scriptzsh' => 'zsh',
];
return isset($mime_map[$mime]) ? $mime_map[$mime] : false;
}
}