src/Controller/Edition/EditionController.php line 25
<?phpnamespace App\Controller\Edition;use App\Entity\Document\Block;use App\Entity\Document;use App\Entity\DocumentPermission;use App\Entity\User;use App\Form\NewDocType;use App\Repository\DocumentRepository;use App\Services\Html;use Doctrine\ORM\EntityManagerInterface;use PhpParser\Comment\Doc;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\HttpFoundation\HeaderUtils;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\HttpFoundation\StreamedResponse;use Symfony\Component\Routing\Annotation\Route;class EditionController extends AbstractController{#[Route('/edition', name: 'edition_index')]public function index(EntityManagerInterface $em): Response{$documents = $em->getRepository(Document::class)->findBy(["owner" => $this->getUser(), "type" => Document::TYPE_WEB, "isLastVersion" => true]);$templates = $em->getRepository(Document::class)->findBy(["owner" => $this->getUser(), "type" => Document::TYPE_WEB, "isLastVersion" => true, "isTemplate" => true]);$blocks = $em->getRepository(Block::class)->findBy(["document" => null]);return $this->render('edition/index.html.twig', ["documents" => $documents,"templates" => $templates,"blocks" => $blocks]);}#[Route('/edition/new', name: 'edition_new')]public function new(Request $request, EntityManagerInterface $em): Response{$document = new Document();$form = $this->createForm(NewDocType::class, $document);$form->handleRequest($request);if($form->isSubmitted() && $form->isValid()) {/** @var Document $document */$document = $form->getData();$document->setOwner($this->getUser());$document->setDateCreated(new \DateTime());$document->setDateUpdated(new \DateTime());$document->setVersion(new \DateTime());$document->setType(Document::TYPE_WEB);$document->setVersionOf($document);$document->setIsLastVersion(true);$em->persist($document);$em->flush();return $this->redirectToRoute('edition_edit', ["id" => $document->getId()]);}return $this->render('edition/new.html.twig', ['form' => $form->createView()]);}#[Route('/edition/newfromtemplate/{id}', name: 'edition_newfromtemplate')]public function newfromtemplate(EntityManagerInterface $em, Document $template){$document = Document::clone($template);$document->setTitle("Nouveau document (depuis le modèle " . $document->getTitle() . ")");$em->persist($document);$document->setDateUpdated(new \DateTime());$document->setDateCreated(new \DateTime());$document->setVersion(new \DateTime());$document->setType(Document::TYPE_WEB);$document->setVersionOf($document);$document->setIsLastVersion(true);foreach($document->getBlocks() as $block)$em->persist($block);$em->flush();return $this->redirectToRoute('edition_edit', ["id" => $document->getId()]);}#[Route('/edition/edit/{id}', name: 'edition_edit')]public function edit(EntityManagerInterface $em, Document $document){$this->denyAccessUnlessGranted('edit', $document);$blocks = $em->getRepository(Block::class)->findAll();$blockcategories = $em->getRepository(Document\BlockCategory::class)->findBy(["owner" =>$this->getUser()]);$versions = $em->getRepository(Document::class)->findBy(["versionOf" => $document->getVersionOf()], ["version" => "DESC"]);return $this->render('edition/edit.html.twig', ["blockcategories" => $blockcategories,"blocks" => $blocks,"document" => $document,"versions" => $versions,"users" => $em->getRepository(User::class)->findAll()]);}#[Route('/edition/editblock/{id}', name: 'edition_editblock')]public function editblock(EntityManagerInterface $em, Block $block){$categories = $em->getRepository(Document\BlockCategory::class)->findBy(["owner" =>$this->getUser()]);return $this->render('edition/editblock.html.twig', ["block" => $block,"blockcategories" => $categories,"document" => null]);}#[Route('/edition/createblock', name: 'edition_createblock')]public function createblock(EntityManagerInterface $em){$categories = $em->getRepository(Document\BlockCategory::class)->findBy(["owner" =>$this->getUser()]);return $this->render('edition/editblock.html.twig', ["block" => null,"blockcategories" => $categories,"document" => null]);}#[Route('/edition/test/{id}', name: 'edition_test')]public function test(Document $document){return $this->render('edition/edit.html.twig', ["document" => $document]);}#[Route('/edition/delete/{id}', name: 'edition_delete')]public function delete(EntityManagerInterface $em, Document $document){/** @var DocumentRepository $drep */$drep = $em->getRepository(Document::class);/** @var Document $lastVersion */$lastVersion = null;if(!$document->isIsLastVersion())$lastVersion = $drep->findLastVersionOf($document);$blocks = $em->getRepository(Block::class)->findBy(["document" => $document]);foreach ($blocks as $block) {$em->remove($block);}$em->remove($document);$em->flush();if(!$lastVersion)return $this->redirectToRoute('edition_index');elsereturn $this->redirectToRoute('edition_edit', ["id" => $lastVersion->getId()]);}#[Route('/edition/deleteblock/{id}', name: 'edition_delete_block')]public function deleteblock(EntityManagerInterface $em, Block $block){$em->remove($block);$em->flush();return $this->redirectToRoute('edition_index');}#[Route('/edition/removeUser/{document}/{user}', name: 'edition_removeuser')]public function removeUser(EntityManagerInterface $em, Document $document, User $user){$dps = $em->getRepository(DocumentPermission::class)->findBy(["document" => $document, "user" => $user]);foreach($dps as $dp) {$em->remove($dp);}$em->flush();return $this->redirectToRoute('edition_edit', ["id" => $document->getId()]);}#[Route('/edition/addUser/{document}/{user}', name: 'edition_adduser')]public function addUser(EntityManagerInterface $em, Document $document, User $user){$dps = $em->getRepository(DocumentPermission::class)->findBy(["document" => $document, "user" => $user]);foreach($dps as $dp) {$em->remove($dp);}$em->flush();$dp = new DocumentPermission();$dp->setDocument($document);$dp->setUser($user);$em->persist($dp);$em->flush();return $this->redirectToRoute('edition_edit', ["id" => $document->getId()]);}#[Route('/edition/generate_/{id}', name: 'edition_fakegenerate', methods: ['POST'])]public function fakeGenerate(Document $document, Request $request){$variables = [];$varnames = explode(',', $request->get('vars'));foreach($varnames as $var) {$variables[$var] = $request->get($var);}return new Response("\n<br>" . 'fake generated.');}/** Generate word document.* id: document id from the database* write: option to write in a file instead of a stream to download. For debug purposes.*/#[Route('/edition/generate/{id}/{write}', name: 'edition_generate', methods: ['POST'])]public function generate(Request $request, Document $document, $write = false){/* get variables to replace in document */$variables = [];$varnames = explode(',', $request->get('vars'));foreach($varnames as $var) {$variables[$var] = $request->get($var);}//$html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body>';$html = "<h1>" . $document->getTitle() . "</h1>";$phpWord = new \PhpOffice\PhpWord\PhpWord();$phpWord->addTitleStyle(1, ['name' => 'Calibri', 'size' => 30, 'color' => '1B2232', 'bold' => false], ['numStyle' => 'hNum', 'numLevel' => 0]);$phpWord->addTitleStyle(2, ['name' => 'Calibri', 'size' => 24, 'color' => '1B2232', 'bold' => false], ['numStyle' => 'hNum', 'numLevel' => 1]);$phpWord->addTitleStyle(3, ['name' => 'Calibri', 'size' => 21, 'color' => '1B2232', 'bold' => false], ['numStyle' => 'hNum', 'numLevel' => 2]);$phpWord->addTitleStyle(4, ['name' => 'Calibri', 'size' => 18, 'color' => '1B2232', 'bold' => false], ['numStyle' => 'hNum', 'numLevel' => 3]);$phpWord->addTitleStyle(5, ['name' => 'Calibri', 'size' => 14, 'color' => '1B2232', 'bold' => false], ['numStyle' => 'hNum', 'numLevel' => 4]);$phpWord->addFontStyle('Link', array('color' => '0000FF', 'underline' => 'single'));//$section0 = $phpWord->addSection();//$section0->addTOC(['name' => 'Calibri'], [], 1, 9);$section = $phpWord->addSection();/** @var Block $block */foreach($document->getBlocks() as $block) {if($block->getType() == Block::TYPE_TEXT)\PhpOffice\PhpWord\Shared\Html::addHtml($section, $block->getHydratedContent($variables));if($block->getType() == Block::TYPE_PAGEBREAK)$section->addPageBreak();}$section->addTOC(['name' => 'Calibri'], [], 1, 9);$footer = $section->addFooter();$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.');$phpWord->getCompatibility()->setOoxmlVersion(15);/* write */$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');if($write) {$objWriter->save($document->getTitle() . '.docx');return new Response(".");}else {$response = new StreamedResponse();$response->setCallback(function() use ($objWriter) {$objWriter->save('php://output');});$response->headers->set('Content-Type', 'application/vnd.ms-word');$response->headers->set('Cache-Control', 'max-age=0');$disposition = HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT,$document->getTitle() . '.docx');$response->headers->set('Content-Disposition', $disposition);return $response;}}private function addtest($section) {for($i = 1; $i < 3; $i++) {$section->addTitle("title ".$i, 1);$section->addText('"The greatest accomplishment is not in never falling, '. 'but in rising again after you fall.\n" '. '(Vince Lombardi)'. "The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words. Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators. To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. The new common language will be more simple and regular than the existing European languages. It will be as simple as Occidental; in fact, it will be Occidental. To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is. The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words. Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators. To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. The new common language will be more simple and regular than the existing European languages. It will be as simple as Occidental; in fact, it will be Occidental. To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is.The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words. Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators. To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words. If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages. The new common language will be more simple and regular than the existing European languages.");$section->addTitle("title ".$i.".1", 2);$section->addTitle("title ".$i.".1.1", 3);$section->addText("Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.\n". "(Albert Einstein)\n". 'The tears began to flow and sobs shook him. He gave himself up to them now for the first time on the island; great, shuddering spasms of grief that seemed to wrench his whole body. His voice rose under the black smoke before the burning wreckage of the island; and infected by that emotion, the other little boys began to shake and sob too. ');$section->addTitle("title ".$i.".2", 2);$section->addTitle("title ".$i.".2.1", 3);$section->addText('"The greatest accomplishment is not in never falling, '. 'but in rising again after you fall." '. "(Vince Lombardi)\n"."Researchers suggest that both a tutor’s and student’s mindset shape an academic session:\n Embedded-tutoring programs are worthwhile investments. This research has broken ground in linking mindset changes to writing center work. I hope writing center researchers will continue to explore ways to advance interdisciplinary understanding of the power of mindsets, particularly as they relate to writing improvement. (Miller, 2020, pp. 122-123)");}}#[Route('/edition/test')]public function docxtest(){$phpWord = new \PhpOffice\PhpWord\PhpWord();$phpWord->addTitleStyle(1, ['name' => 'Calibri', 'size' => 30, 'color' => '1B2232', 'bold' => false], []);$phpWord->addTitleStyle(2, ['name' => 'Calibri', 'size' => 24, 'color' => '1B2232', 'bold' => false], []);$phpWord->addTitleStyle(3, ['name' => 'Calibri', 'size' => 21, 'color' => '1B2232', 'bold' => false], []);$phpWord->addTitleStyle(4, ['name' => 'Calibri', 'size' => 18, 'color' => '1B2232', 'bold' => false], []);$phpWord->addTitleStyle(5, ['name' => 'Calibri', 'size' => 14, 'color' => '1B2232', 'bold' => false], []);// Adding an empty Section to the document...$section = $phpWord->addSection();$section->addTOC([], []);// Adding Text element with font customized using named font style...$fontStyleName = 'oneUserDefinedStyle';$phpWord->addFontStyle($fontStyleName,array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true));$section->addText('"The greatest accomplishment is not in never falling, '. 'but in rising again after you fall." '. '(Vince Lombardi)',$fontStyleName);$section->addTitle("title1", 1);$section->addText('"The greatest accomplishment is not in never falling, '. 'but in rising again after you fall." '. '(Vince Lombardi)',$fontStyleName);$section->addTitle("title2", 1);$section->addText('"The greatest accomplishment is not in never falling, '. 'but in rising again after you fall." '. '(Vince Lombardi)',$fontStyleName);$section->addTitle("title2.1", 2);$section->addText('"The greatest accomplishment is not in never falling, '. 'but in rising again after you fall." '. '(Vince Lombardi)',$fontStyleName);// Adding Text element with font customized using explicitly created font style object...$fontStyle = new \PhpOffice\PhpWord\Style\Font();$fontStyle->setBold(true);$fontStyle->setName('Tahoma');$fontStyle->setSize(13);$myTextElement = $section->addText('"Believe you can and you\'re halfway there." (Theodor Roosevelt)');$myTextElement->setFontStyle($fontStyle);// Saving the document as OOXML file...$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');$objWriter->save('helloWorld.docx');return new Response(".");}#[Route('/api/{version}/edition/saveblockasmodel', name: 'edition_api_saveblockasmodel', methods: ['POST'])]public function apiSaveBlockAsModel(Request $request, EntityManagerInterface $em){$b = $request->request->all('block');$block = new Block();// get categoryif ($b["categoryId"] != "" && $b["categoryId"] != "+"){$bCat = $em->getRepository(Document\BlockCategory::class)->find($b["categoryId"]);if ($bCat)$block->setCategory($bCat);}else if($b["categoryId"] == "+" && trim($b["newCategoryTitle"]) != "") {$bCat = new Document\BlockCategory();$bCat->setTitle(trim($b["newCategoryTitle"]));$bCat->setOwner($this->getUser());$em->persist($bCat);$block->setCategory($bCat);}$block->setContent($b["content"]);$block->setTitle($b["title"]);$block->setDescription($b["description"]);$block->setTags($b["tags"]);$block->setOwner($this->getUser());$em->persist($block);$em->flush();$responsedata = ["block" => $block->getContent(),];return new JsonResponse($responsedata);}#[Route('/api/{version}/edition/saveblock', name: 'edition_api_saveblock', methods: ['POST'])]public function apiSaveBlock(Request $request, EntityManagerInterface $em){$b = $request->request->all('block');$block = null;if(isset($b["id"])) {/** @var Block $block */$block = $em->getRepository(Block::class)->find($b["id"]);}if(!$block)$block = new Block();// get categoryif ($b["categoryId"] != "" && $b["categoryId"] != "+"){$bCat = $em->getRepository(Document\BlockCategory::class)->find($b["categoryId"]);if ($bCat)$block->setCategory($bCat);}else if($b["categoryId"] == "+" && trim($b["newCategoryTitle"]) != "") {$bCat = new Document\BlockCategory();$bCat->setTitle(trim($b["newCategoryTitle"]));$bCat->setOwner($this->getUser());$em->persist($bCat);$block->setCategory($bCat);}$block->setContent($b["content"]);$block->setTitle($b["title"]);$block->setDescription($b["description"]);$block->setTags($b["tags"]);$em->persist($block);$em->flush();$responsedata = ["block" => $block->getContent(),"blockId" => $block->getId(),"data" => print_r($b, true)];return new JsonResponse($responsedata);}#[Route('/api/{version}/edition/overwritedoc', name: 'edition_api_overwritedoc', methods: ['POST'])]public function apiOverwriteDoc(Request $request, EntityManagerInterface $em){// This will overwrite the existing document and linked blocks. All changes are therefore permanent./** jsondoc = {* id: document.id,* title: document.title,* description: document.description,* tags: document.tags,* blocks: [{* order: block order in document,* content: block content,* title: block title,* description: block description,* tags: block tags* }]* }**/$jsondoc = $request->request->all('document');/** @var Document $document */$document = $em->getRepository(Document::class)->find($jsondoc["id"]);// deleting current blocks$oldblocks = $em->getRepository(Block::class)->findBy(["document" => $document]);foreach($oldblocks as $ob) {$em->remove($ob);}$blocks = $jsondoc["blocks"];// adding new blocksforeach($blocks as $b) {$oldblock = $em->getRepository(Block::class)->findOneBy(["blockorder" => $b["order"], "document" => $document]);if($oldblock)$em->remove($oldblock);$block = new Block();$block->setContent($b["content"]);$block->setTitle($b["title"]);$block->setDescription($b["description"]);$block->setTags($b["tags"]);$block->setDocument($document);$block->setBlockorder(intval($b["order"]));$block->setIdInDoc($b["idInDoc"]);$block->setType($b["type"]);$em->persist($block);}// updating document information$document->setTitle($jsondoc["title"]);$document->setDescription($jsondoc["description"]);$document->setTags($jsondoc["tags"]);$document->setStatus($jsondoc["status"]);$document->setDateUpdated(new \DateTime());$em->persist($document);$em->flush();$responsedata = ["document" => $jsondoc,"blocks" => $blocks];return new JsonResponse($responsedata);}#[Route('/api/{version}/edition/savedoc', name: 'edition_api_savedoc', methods: ['POST'])]public function apiSaveDoc(Request $request, EntityManagerInterface $em){// This will save a copy of the document and linked blocks, allowing for version management/** jsondoc = {* id: document.id,* title: document.title,* description: document.description,* tags: document.tags,* blocks: [{* order: block order in document,* content: block content,* title: block title,* description: block description,* tags: block tags* }]* }**/$jsondoc = $request->request->all('document');/** @var Document $olddocument */$olddocument = $em->getRepository(Document::class)->find($jsondoc["id"]);/** @var Document $document */$document = new Document();$blocks = $jsondoc["blocks"];// adding new blocksforeach($blocks as $b) {$block = new Block();// get categoryif ($b["category"] != ""){$bCat = $em->getRepository(Document\BlockCategory::class)->find($b["category"]);if ($bCat)$block->setCategory($bCat);else {$bCat = new Document\BlockCategory();$bCat->setTitle(trim($b["category"]));$bCat->setOwner($this->getUser());$em->persist($bCat);$block->setCategory($bCat);}}$block->setContent($b["content"]);$block->setTitle($b["title"]);$block->setDescription($b["description"]);$block->setTags($b["tags"]);$block->setDocument($document);$block->setBlockorder(intval($b["order"]));$block->setIdInDoc($b["idInDoc"]);$block->setType(intval($b["type"]));$em->persist($block);}// all previous versions are not last version anymore$prevdocs = $em->getRepository(Document::class)->findBy(["versionOf" => $olddocument->getVersionOf()]);foreach ($prevdocs as $prevdoc) {/** @var Document $prevdoc */$prevdoc->setIsLastVersion(false);$em->persist($prevdoc);}// updating document information$document->setTitle($jsondoc["title"]);$document->setDescription($jsondoc["description"]);$document->setTags($jsondoc["tags"]);$document->setStatus($jsondoc["status"]);$document->setDateCreated($olddocument->getDateCreated());$document->setDateUpdated(new \DateTime());$document->setVersion(new \DateTime());$document->setType(Document::TYPE_WEB);$document->setOwner($olddocument->getOwner());$document->setVersionOf($olddocument->getVersionOf());$document->setIsLastVersion(true);$em->persist($document);$em->flush();$responsedata = ["document" => $jsondoc,"blocks" => $blocks,"newid" => $document->getId()];return new JsonResponse($responsedata);}#[Route('/api/{version}/edition/getblock/{id}', name: 'edition_api_getblock')]public function apiGetBlock(Request $request, EntityManagerInterface $em, $id){/** @var Block $block */$block = $em->getRepository(Block::class)->find($id);$responsedata = ["block" => $block->getContent()];return new JsonResponse($responsedata);}#[Route('/api/{version}/edition/getlastversion', name: 'edition_api_getlastversion', methods: ['POST'])]public function apiGetLastVersion(Request $request, EntityManagerInterface $em){/** @var Document $document */$document = $em->getRepository(Document::class)->find($request->request->get('document'));$responsedata = ["error" => ""];if($document) {$lastVersion = $em->getRepository(Document::class)->findOneBy(["versionOf" => $document->getVersionOf(), "isLastVersion" => 1]);$responsedata["lastVersion"] = $lastVersion->getId();}else $responsedata["error"] = "document not found";return new JsonResponse($responsedata);}}