src/Event/EasyAdminSubscriber.php line 172

Open in your IDE?
  1. <?php
  2. namespace App\Event;
  3. use App\Entity\Algorithm;
  4. use App\Entity\AlgorithmCondition;
  5. use App\Entity\App;
  6. use App\Entity\AppTranslations;
  7. use App\Entity\Category;
  8. use App\Entity\Disease;
  9. use App\Entity\Drug;
  10. use App\Entity\Flow;
  11. use App\Entity\Import;
  12. use App\Entity\Language;
  13. use App\Entity\ObjectType;
  14. use App\Entity\Page;
  15. use App\Entity\Test;
  16. use App\Entity\TestDefinition;
  17. use App\Entity\Therapy;
  18. use App\Entity\User;
  19. use App\Service\AlgorithmService;
  20. use App\Service\EntityUsageService;
  21. use App\Service\ImportService;
  22. use App\Service\PageGeneratorService;
  23. use App\Service\SlugService;
  24. use App\Service\TestService;
  25. use Doctrine\ORM\EntityManagerInterface;
  26. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  27. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  28. use Symfony\Component\EventDispatcher\GenericEvent;
  29. use Symfony\Component\Filesystem\Filesystem;
  30. use Symfony\Component\HttpFoundation\RequestStack;
  31. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  32. use Symfony\Component\HttpKernel\KernelInterface;
  33. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  34. class EasyAdminSubscriber implements EventSubscriberInterface {
  35.     private $entity_manager;
  36.     public function __constructEntityManagerInterface $entity_managerEntityUsageService $entityUsageService,  AlgorithmService $algorithmServiceTokenStorageInterface $token_storageSlugService $slugServiceTestService $testServiceKernelInterface $kernelImportService $importServiceRequestStack $requestSessionInterface $sessionPageGeneratorService $pageGeneratorService) {
  37.         $this->entity_manager $entity_manager;
  38.         $this->token_storage $token_storage;
  39.         $this->testService $testService;
  40.         $this->kernel $kernel;
  41.         $this->importService $importService;
  42.         $this->request $request;
  43.         $this->session $session;
  44.         $this->pageGeneratorService $pageGeneratorService;
  45.         $this->slugService $slugService;
  46.         $this->algorithmService $algorithmService;
  47.         $this->entityUsageService $entityUsageService;
  48.     }
  49.     public static function getSubscribedEvents(): ?array {
  50.         return [
  51.             EasyAdminEvents::POST_UPDATE => 'onPostUpdate',
  52.             EasyAdminEvents::POST_PERSIST => 'onPostPersist',
  53.             EasyAdminEvents::PRE_PERSIST => 'onPrePersist',
  54.             EasyAdminEvents::PRE_UPDATE => 'onPreUpdate',
  55.             EasyAdminEvents::POST_EDIT => 'onPostEdit',
  56.                 ];
  57.     }
  58.     public function onPreUpdate(GenericEvent $event) {
  59.         $entity $event->getSubject();
  60.         if ($entity instanceof App) {
  61.             $id $entity->getId();
  62.             // query manager to get the old entity, before update
  63.             $qb $this->entity_manager->createQueryBuilder();
  64.             $qb->select('a.Settings')
  65.                 ->from('App:App''a')
  66.                 ->where('a.id = :id')->setParameter('id'$id);
  67.             $qb->setMaxResults(1);
  68.             $oldSettingsVar $qb->getQuery()->getSingleResult();
  69.             $oldSettings $oldSettingsVar['Settings'];
  70.             $Settings $entity->getSettings();
  71.             $primaryColor $Settings['primaryColor'];
  72.             $oldPrimaryColor = isset($oldSettings['primaryColor']) ? $oldSettings['primaryColor'] : '';
  73.             $secondaryColor $Settings['secondaryColor'];
  74.             $oldSecondaryColor = isset($oldSettings['secondaryColor']) ? $oldSettings['secondaryColor'] : '';
  75.             $infoColor $Settings['infoColor'];
  76.             $oldInfoColor = isset($oldSettings['infoColor']) ? $oldSettings['infoColor'] : '';
  77.             $successColor $Settings['successColor'];
  78.             $oldSuccessColor = isset($oldSettings['successColor']) ? $oldSettings['successColor'] : '';
  79.             $dangerColor $Settings['dangerColor'];
  80.             $oldDangerColor = isset($oldSettings['dangerColor']) ? $oldSettings['dangerColor'] : '';
  81.             $warningColor $Settings['warningColor'];
  82.             $oldWarningColor = isset($oldSettings['warningColor']) ? $oldSettings['warningColor'] : '';
  83.             $request $this->request->getCurrentRequest();
  84.             $baseurl $request->getScheme() . '://' $request->getHttpHost() . $request->getBasePath();
  85.             $output null;
  86.             if (($primaryColor!=$oldPrimaryColor) || ($secondaryColor!=$oldSecondaryColor) || ($infoColor!=$oldInfoColor) || ($successColor!=$oldSuccessColor) || ($dangerColor!=$oldDangerColor) || ($warningColor!=$oldWarningColor)) { // if colors changes update the css
  87.                 $output $this->pageGeneratorService->compileCss($entity);
  88.                 $Settings['cssUpdatedAt'] = time();
  89.             }
  90.             $this->pageGeneratorService->storeCustomCssJs($entity);
  91.             $Web $entity->getWeb();
  92.             if ($Web) {
  93.                 $apiUserId =  isset($Settings['ApiUser']) ? $Settings['ApiUser'] : 0;
  94.                 $User $this->entity_manager->getRepository(User::class)->find($apiUserId);
  95.                 if (!empty($User->getApiToken())) {
  96.                     $webapp $this->pageGeneratorService->updateWebApp($entity$User->getApiToken());
  97.                 }
  98.             }
  99.        }
  100.     }
  101.     public function onPostEdit(GenericEvent $event) {
  102.         $token $this->token_storage->getToken();
  103.         $User $token->getUser();
  104.         $Customer $User->getCustomer();
  105.         $entity $event->getSubject();
  106.         $entityName = (isset($entity['name'])) ? $entity['name']  : null;
  107.         if ($entityName == 'Algorithm') {
  108.             $request $this->request->getCurrentRequest();
  109.             $id $request->query->get('id');
  110.             $Algorithm $this->entity_manager->getRepository(Algorithm::class)->find($id);
  111.             $errors $this->algorithmService->checkAlgorithm($Algorithm$Customer);
  112.             if (!empty($errors)) {
  113.                 foreach ($errors as $error) {
  114.                     $this->session->getFlashBag()->add('danger',$error);
  115.                 }
  116.             }
  117.         }
  118.     }
  119.     public function onPrePersist(GenericEvent $event) {
  120.         $entity $event->getSubject();
  121.         if ($entity instanceof TestDefinition) {
  122.         }
  123.     }
  124.     public function onPostPersist(GenericEvent $event) {
  125.         $entity $event->getSubject();
  126.         $token $this->token_storage->getToken();
  127.         $User $token->getUser();
  128.         $Customer $User->getCustomer();
  129.         $lang $Customer->getDefaultLanguageCode();
  130.         if ($entity instanceof Page) {
  131.             // save tree
  132.             $parent_id=$entity->getParent();
  133.             $Parent = ($parent_id>0) ? $this->entity_manager->getRepository(Page::class)->find($parent_id) : null;
  134.             if (!empty($Parent)) {
  135.                 $entity->setChildNodeOf($Parent);
  136.                 $this->entity_manager->persist($Parent);
  137.                 $this->entity_manager->flush();
  138.             } else {
  139.                 $entity->setMaterializedPath('');
  140.             }
  141.             $translations $entity->getTranslations();
  142.             $imagesArray preg_match_all('/<img[^>]+>/i',$entity->get$result);
  143.             $this->entity_manager->persist($entity);
  144.             $this->entity_manager->flush();
  145.         }
  146.         if ($entity instanceof Algorithm) {
  147.             $algorithmType $entity->getType();
  148.             $algorithmObjectType  $entity->getObjectType();
  149.             if (!empty($algorithmObjectType)) {
  150.                 $Taxonomy $algorithmObjectType->getSlug();
  151.                 if ($algorithmType == "modifier") {
  152.                     $ObjectId $entity->getObjectId();
  153.                     if (($Taxonomy == "test") && ($ObjectId 0)) {
  154.                         $Test $this->entity_manager->getRepository(Test::class)->find($ObjectId);
  155.                         $tesDefinitions $this->testService->getAllVariables($Test);
  156.                         foreach ($tesDefinitions as $tesDefinition) {
  157.                             $algorithmCondition = new AlgorithmCondition();
  158.                             $algorithmCondition->setFormula($tesDefinition->getSlug());
  159.                             $algorithmCondition->setActive(true);
  160.                             $algorithmCondition->setObjectId($tesDefinition->getId());
  161.                             $entity->addAlgorithmCondition($algorithmCondition);
  162.                         }
  163.                     }
  164.                 }
  165.             }
  166.         }
  167.     }
  168.     public function onPostUpdate(GenericEvent $event) {
  169.         $entity $event->getSubject();
  170.         $token $this->token_storage->getToken();
  171.         $User $token->getUser();
  172.         $Customer $User->getCustomer();
  173.         $lang $Customer->getDefaultLanguageCode();
  174.         $Settings $Customer->getSettings();
  175.         $languages = (isset($Settings['languages'])) ? $Settings['languages'] : array();
  176.         foreach ($languages as $languageId) {
  177.             $Language $this->entity_manager->getRepository(Language::class)->find($languageId);
  178.             $usedLanguagesArray[] = $Language->getCode();
  179.         }
  180.         if ($entity instanceof Category) {
  181.             $this->entity_manager->persist($entity);
  182.             $this->entity_manager->flush();
  183.         }
  184.         if ($entity instanceof Import) {
  185.             $projectRoot $this->kernel->getProjectDir();
  186.             $fileName urldecode($entity->getFilename());
  187.             $type urldecode($entity->getType());
  188.             $Taxonomy=$entity->getTaxonomy();
  189.             $Worksheet=$entity->getWorksheet();
  190.             $ObjectId=$entity->getObjectType()->getId();
  191.             $taxonomyName $Taxonomy->getSlug();
  192.             $fullPath $projectRoot.'/public'.$fileName;
  193.             $importSettings $entity->getSettings();
  194.             $importStatus $entity->getStatus();
  195.             if (file_exists($fullPath)) {
  196.                 if ($taxonomyName == 'country') {
  197.                     $str file_get_contents($fullPath);
  198.                     $this->importService->importCountriesJson($str$ObjectId);
  199.                     $entity->setStatus('finished');
  200.                     $importSettings = array('stage'=>2);
  201.                     $entity->setSettings($importSettings);
  202.                     $this->entity_manager->persist($entity);
  203.                     $this->entity_manager->flush();
  204.                 } elseif ($taxonomyName == 'test') {
  205.                     $stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
  206.                     $startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
  207.                     if (($importStatus=='initial') && (empty($Worksheet))) {
  208.                         $worksheets $this->importService->importIcd9Xls($fullPath$stage$ObjectId0,1000$Taxonomy$Worksheet);
  209.                         $importSettings = array('stage'=>1'worksheet'=>'''worksheets'=>$worksheets);
  210.                         $entity->setSettings($importSettings);
  211.                     } elseif (!empty($Worksheet)) {
  212.                         $importedArray $this->importService->importIcd9Xls($fullPath$stage$ObjectId$startFrom,1000$Taxonomy,$Worksheet);
  213.                         $imported $importedArray[0];
  214.                         $totalRows $importedArray[1];
  215.                         $importSettings['stage'] = 2;
  216.                         $importSettings['worksheet'] = $Worksheet;
  217.                         $importSettings['ObjectId'] = $ObjectId;
  218.                         $importSettings['imported'] = $imported;
  219.                         $importSettings['totalRows'] =$totalRows;
  220.                         $entity->setStatus('finished');
  221.                         $entity->setSettings($importSettings);
  222.                     }
  223.                     $this->entity_manager->persist($entity);
  224.                     $this->entity_manager->flush();
  225.                 } elseif ($taxonomyName == 'disease') {
  226.                     $stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
  227.                     $startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
  228.                     if ($type == 'xlsx') {
  229.                         $importedArray $this->importService->importIcd10($fullPath$ObjectId$startFrom100);
  230.                         $imported $importedArray[0];
  231.                         $totalRows $importedArray[1];
  232.                         $stage 1;
  233.                         $importSettings['stage'] = $stage;
  234.                         $importSettings['ObjectId'] = $ObjectId;
  235.                         $importSettings['imported'] = $imported;
  236.                         $importSettings['totalRows'] = $totalRows;
  237.                         $importSettings['startFrom'] = $startFrom 100;
  238.                         if ($imported == 101) {
  239.                             $entity->setStatus('partial');
  240.                         } else {
  241.                             $entity->setStatus('finished');
  242.                         }
  243.                         $entity->setStatus('finished');
  244.                         $entity->setSettings($importSettings);
  245.                     } elseif ($type == 'json') {
  246.                         if ($ObjectId == 19) {
  247.                             $importedArray $this->importService->importInteractions($fullPath$ObjectId02000);
  248.                         }
  249.                         $imported $importedArray[0];
  250.                         $totalRows $importedArray[1];
  251.                         $stage 1;
  252.                         $importSettings['stage'] = $stage;
  253.                         $importSettings['ObjectId'] = $ObjectId;
  254.                         $importSettings['imported'] = $imported;
  255.                         $importSettings['totalRows'] = $totalRows;
  256.                         $importSettings['startFrom'] = $startFrom 2000;
  257.                         if ($imported == 2001) {
  258.                             $entity->setStatus('partial');
  259.                         } else {
  260.                             $entity->setStatus('finished');
  261.                         }
  262.                         $entity->setSettings($importSettings);
  263.                     }
  264.                     $this->entity_manager->persist($entity);
  265.                     $this->entity_manager->flush();
  266.                 } elseif ($taxonomyName == 'customentity') {
  267.                     $stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
  268.                     $startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
  269.                     if ($type == 'xlsx') {
  270.                     } elseif ($type == 'json') {
  271.                         if ($ObjectId == 20) {
  272.                             $importedArray $this->importService->importInteractionsCustom($fullPath$ObjectId02000);
  273.                         }
  274.                         $imported $importedArray[0];
  275.                         $totalRows $importedArray[1];
  276.                         $stage 1;
  277.                         $importSettings['stage'] = $stage;
  278.                         $importSettings['ObjectId'] = $ObjectId;
  279.                         $importSettings['imported'] = $imported;
  280.                         $importSettings['totalRows'] = $totalRows;
  281.                         $importSettings['startFrom'] = $startFrom 2000;
  282.                         if ($imported == 2001) {
  283.                             $entity->setStatus('partial');
  284.                         } else {
  285.                             $entity->setStatus('finished');
  286.                         }
  287.                         $entity->setSettings($importSettings);
  288.                     }
  289.                     $this->entity_manager->persist($entity);
  290.                     $this->entity_manager->flush();
  291.                 } elseif ($taxonomyName == 'drug') {
  292.                     $stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
  293.                     $startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
  294.                     if (($importStatus=='initial') && (empty($Worksheet))) {
  295.                         if ($type == 'xlsx') {
  296.                             if ($ObjectId == 10) {
  297.                                 $worksheets $this->importService->importAtcXls($fullPath$stage$ObjectId01000$Taxonomy'');
  298.                             } elseif ($ObjectId == 11) {
  299.                                 $worksheets $this->importService->importRplXls($fullPath$stage$ObjectId01000$Taxonomy'');
  300.                             }
  301.                             $importSettings = array('stage' => 1'worksheet' => '''worksheets' => $worksheets);
  302.                             $entity->setSettings($importSettings);
  303.                         } elseif ($type == 'json') {
  304.                             if ($ObjectId == 17) {
  305.                                 $importedArray $this->importService->importInteractionDrugs($fullPath$stage$ObjectId$Taxonomy);
  306.                             }
  307.                             $imported $importedArray[0];
  308.                             $totalRows $importedArray[1];
  309.                             $importSettings['imported'] = $imported;
  310.                             $importSettings['startFrom'] = $startFrom 1000;
  311.                             $importSettings['totalRows'] = $totalRows;
  312.                             if ($imported != $totalRows) {
  313.                                 $entity->setStatus('partial');
  314.                             } else {
  315.                                 $entity->setStatus('finished');
  316.                             }
  317.                             $entity->setSettings($importSettings);
  318.                         }
  319.                     } elseif (!empty($Worksheet)) {
  320.                         $stage 2;
  321.                         $importSettings['stage'] = $stage;
  322.                         $importSettings['worksheet'] = $Worksheet;
  323.                         $importSettings['ObjectId'] = $ObjectId;
  324.                         if ($type == 'xlsx') {
  325.                             if ($ObjectId==10) {
  326.                                 $importedArray $this->importService->importAtcXls($fullPath$stage$ObjectId$startFrom1000$Taxonomy$Worksheet);
  327.                             } elseif ($ObjectId == 11) {
  328.                                 $importedArray $this->importService->importRplXls($fullPath$stage$ObjectId$startFrom1000$Taxonomy$Worksheet);
  329.                             }
  330.                             $imported $importedArray[0];
  331.                             $totalRows $importedArray[1];
  332.                             $importSettings['imported'] = $imported;
  333.                             $importSettings['startFrom'] = $startFrom 1000;
  334.                             $importSettings['totalRows'] = $totalRows;
  335.                             if ($imported == 1001) {
  336.                                 $entity->setStatus('partial');
  337.                             } else {
  338.                                 $entity->setStatus('finished');
  339.                             }
  340.                             $entity->setSettings($importSettings);
  341.                         }
  342.                     }
  343.                     $this->entity_manager->persist($entity);
  344.                     $this->entity_manager->flush();
  345.                 } elseif ($taxonomyName == 'page') {
  346.                 } elseif ($taxonomyName == 'procedure') {
  347.                     $stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
  348.                     $startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
  349.                     if (($importStatus=='initial') && (empty($Worksheet))) {
  350.                         $worksheets $this->importService->importIcd9Xls($fullPath$stage$ObjectId,0,1000,$Taxonomy'');
  351.                         $importSettings = array('stage'=>1'worksheet'=>'''worksheets'=>$worksheets);
  352.                         $entity->setSettings($importSettings);
  353.                     } elseif (!empty($Worksheet)) {
  354.                         $stage 2;
  355.                         $importSettings['stage'] = $stage;
  356.                         $importSettings['worksheet'] = $Worksheet;
  357.                         $importSettings['ObjectId'] = $ObjectId;
  358.                         $imported $this->importService->importIcd9Xls($fullPath$stage$ObjectId$startFrom1000,$Taxonomy$Worksheet);
  359.                         $importSettings['imported'] = $imported;
  360.                         $importSettings['startFrom'] = $startFrom 1000;
  361.                         if ($imported == 1001) {
  362.                             $entity->setStatus('partial');
  363.                         } else {
  364.                             $entity->setStatus('finished');
  365.                         }
  366.                         $entity->setSettings($importSettings);
  367.                     }
  368.                     $this->entity_manager->persist($entity);
  369.                     $this->entity_manager->flush();
  370.                 }
  371.             }
  372.         }
  373.         if ($entity instanceof TestDefinition) {
  374.             $errors $this->entityUsageService->checkTestDefinitionStructure($entity$lang$usedLanguagesArray$User);
  375.             $this->entity_manager->persist($entity);
  376.             $this->entity_manager->flush();
  377.         }
  378.         if ($entity instanceof Test) {
  379.             //$entity->generateSlug();
  380.             $this->entity_manager->persist($entity);
  381.             $this->entity_manager->flush();
  382.         }
  383.         if ($entity instanceof Drug) {
  384.             $name $entity->translate($lang)->getName();
  385.             $slug $this->slugService->generateSlug($name);
  386.             $entity->setSlug($slug);
  387.             $this->entity_manager->persist($entity);
  388.             $this->entity_manager->flush();
  389.         }
  390.         if ($entity instanceof Disease) {
  391.             $name $entity->translate($lang)->getName();
  392.             $slug $this->slugService->generateSlug($name);
  393.             $entity->setSlug($slug);
  394.             $this->entity_manager->persist($entity);
  395.             $this->entity_manager->flush();
  396.         }
  397.         if ($entity instanceof Flow) {
  398.             $entity->generateSlug();
  399.             $this->entity_manager->persist($entity);
  400.             $this->entity_manager->flush();
  401.         }
  402.         if ($entity instanceof Page) {
  403.             $projectRoot $this->kernel->getProjectDir();
  404.             $translations $entity->getTranslations();
  405.             $request $this->request->getCurrentRequest();
  406.             $baseurl $request->getScheme() . '://' $request->getHttpHost() . $request->getBasePath();
  407.             foreach ($translations as $translation) { // get array of missing files
  408.                 $missingFilesArray $this->pageGeneratorService->getAttachmentsFromTranslation($entity$translationtrue);
  409.             }
  410.             $missingFiles implode(', ',$missingFilesArray);
  411.             $message 'There are missing files in the page body: '.$missingFiles;
  412.             if (!empty($missingFilesArray)) {
  413.                 $this->session->getFlashBag()->add('danger',$message);
  414.             }
  415.             $now = new \DateTime('now');
  416.             $entity->setUpdatedAt($now);
  417.             $this->entity_manager->persist($entity);
  418.             $this->entity_manager->flush();
  419.             // Update images / attachments array for current page and  whole app files array
  420.             $App $entity->getApp();
  421.             $AppSettings $App->getSettings();
  422.             $languages = isset($AppSettings['languages']) ? $AppSettings['languages'] : array();
  423.             $appFilesArray = array();
  424.             foreach ($languages as $languageId) {
  425.                 $Language $this->entity_manager->getRepository(Language::class)->find($languageId);
  426.                 $appFilesArray[$Language->getCode()]['images'] = array();
  427.                 $appFilesArray[$Language->getCode()]['attachments'] = array();
  428.             }
  429.             if (empty($appFilesArray)) {
  430.                 $appFilesArray['en']['images'] = array();
  431.                 $appFilesArray['en']['attachments'] = array();
  432.             }
  433.             $pages $this->entity_manager->getRepository(Page::class)->findBy(array('App'=>$App));
  434.             // update pages
  435.             $hasNews 0;
  436.             $hasCalendar 0;
  437.             foreach ($pages as $page) {
  438.                 // check for notifications
  439.                 $template $page->getTemplate();
  440.                 if ($template == 'newsfeed') {
  441.                     $hasNews 1;
  442.                 } elseif ($template == 'custom') {
  443.                     $pageSettings $page->getSettings();
  444.                     $customFunction = (isset($pageSettings['customFunction'])) ? $pageSettings['customFunction'] : null;
  445.                     if ($customFunction == 'my_calendar') {
  446.                         $hasCalendar 1;
  447.                     }
  448.                 }
  449.                 // check translations
  450.                 $translations $page->getTranslations();
  451.                 foreach ($translations as $translation) {
  452.                     $pageLocale $translation->getLocale();
  453.                     $translation $this->pageGeneratorService->getAttachmentsFromTranslation($page$translationfalse);
  454.                     $pageFiles $translation->getFiles();
  455.                     $pageImagesArray $pageFiles['images'];
  456.                     $pageAttachmentsArray $pageFiles['attachments'];
  457.                     if (isset($appFilesArray[$pageLocale]))  {
  458.                         if (!empty($pageImagesArray)) {
  459.                             $appFilesArray[$pageLocale]['images'][] = $pageImagesArray;
  460.                         }
  461.                         if (!empty($pageAttachmentsArray)) {
  462.                             $appFilesArray[$pageLocale]['attachments'][] = $pageAttachmentsArray;
  463.                         }
  464.                     }
  465.                 }
  466.                 //$this->entity_manager->persist($page);
  467.                 //$this->entity_manager->flush();
  468.             }
  469.             // update notifications array
  470.             $notificationsArray = array('newsfeed'=>$hasNews'calendar'=>$hasCalendar);
  471.             $App->setNotifications($notificationsArray);
  472.             foreach ($appFilesArray as $locale=>$filesArray) { // rearrange array, make files unique
  473.                $imagesArray $filesArray['images'];
  474.                $attachmentsArray $filesArray['attachments'];
  475.                $newImagesArray = array();
  476.                foreach ($imagesArray as $value1) { // merge arrays from different pages
  477.                    $newImagesArray array_merge($newImagesArray$value1);
  478.                }
  479.                 $newImagesArray1 = array();
  480.                 foreach ($newImagesArray as $value2) {// create array with paths as keys to make unique data
  481.                     if (is_array($value2)) {
  482.                         $newImagesArray1[$value2['path']] = array('time'=>$value2['time'], 'size'=> $value2['size']);
  483.                     }
  484.                 }
  485.                 $newImagesArray2 = array();
  486.                 foreach ($newImagesArray1 as $imagePath=>$imageData) { // loop through imagesArray1 to make path/time keys back
  487.                     $newImagesArray2[] = array('path'=>(!empty($imagePath)) ? $baseurl.$imagePath '''time'=>$imageData['time'], 'size'=>$imageData['size']);
  488.                 }
  489.                 
  490.                 /// attachments
  491.                 $newattachmentsArray = array();
  492.                 foreach ($attachmentsArray as $value1) { // merge arrays from different pages
  493.                     $newattachmentsArray array_merge($newattachmentsArray$value1);
  494.                 }
  495.                 $newattachmentsArray1 = array();
  496.                 foreach ($newattachmentsArray as $value2) {// create array with paths as keys to make unique data
  497.                     if (is_array($value2)) {
  498.                          $newattachmentsArray1[$value2['path']] = array('time'=>$value2['time'], 'size'=> $value2['size'] );
  499.                     }
  500.                 }
  501.                 $newattachmentsArray2 = array();
  502.                 foreach ($newattachmentsArray1 as $imagePath=>$imageData) { // loop through attachmentsArray1 to make path/time keys back
  503.                     $newattachmentsArray2[] = array('path'=>(!empty($imagePath)) ? $baseurl.$imagePath '''time'=>$imageData['time'], 'size'=>$imageData['size']);
  504.                 }
  505.                 $webFiles $this->pageGeneratorService->returnPageFilesArray($App$baseurl); // get design files for App
  506.                 $appFilesArray[$locale] = array('images'=>$newImagesArray2'attachments'=>$newattachmentsArray2'webdesign'=>$webFiles);
  507.             }
  508.             $taxonomyPagesArray $this->pageGeneratorService->getTaxonomyPagesForApp($App$lang);
  509.             $App->setTaxonomyPages($taxonomyPagesArray);
  510.             $App->setFiles($appFilesArray);
  511.             $this->entity_manager->persist($App);
  512.             $this->entity_manager->flush();
  513.         }
  514.         if ($entity instanceof App) {
  515.             $appTranslations $entity->getTranslations();
  516.             $Settings $entity->getSettings();
  517.             $selectedObjectsIds = isset($Settings['ObjectTypes']) ? $Settings['ObjectTypes'] : [];
  518.             $defaultSearchObjectType = isset($Settings['defaultSearchObjectType']) ? $Settings['defaultSearchObjectType'] : null;
  519.             $firebaseServiceAccount = isset($Settings['firebaseServiceAccount']) ? $Settings['firebaseServiceAccount'] : '';
  520.             $updateEmptyTranslations $entity->isUpdateEmptyTranslations();
  521.             // update languageCode
  522.             $languageId $entity->getDefaultLanguage();
  523.             $Language $this->entity_manager->getRepository(Language::class)->find($languageId);
  524.             if (!empty($Language)) {
  525.                 $defaultLanguageCode $Language->getCode();
  526.                 $entity->setDefaultLanguageCode($defaultLanguageCode);
  527.             }
  528.             // copy empty translations from default translations
  529.             if ($updateEmptyTranslations) {
  530.                 $usedLanguagesArray = array();
  531.                 $languages = (isset($Settings['languages'])) ? $Settings['languages'] : array();
  532.                 foreach ($languages as $languageId) {
  533.                     $Language $this->entity_manager->getRepository(Language::class)->find($languageId);
  534.                     $usedLanguagesArray[] = $Language->getCode();
  535.                 }
  536.                 $appTranslationsStrings $this->entity_manager->getRepository(AppTranslations::class)->findBy(array('App'=>$entity));
  537.                 foreach ($appTranslationsStrings as $AppTranslationString) {
  538.                     foreach ($usedLanguagesArray as $languageCode) {
  539.                         $translation trim($AppTranslationString->translate($languageCodefalse)->getName());
  540.                         if (is_null($translation) || $translation === "") {
  541.                             $defaultTranslationKey $AppTranslationString->getTranslationKey();
  542.                             $DefaultTranslation $this->entity_manager->getRepository(AppTranslations::class)->findOneBy(array('App'=>null'TranslationKey'=>$defaultTranslationKey));
  543.                             $defaultTranslation $DefaultTranslation->translate($languageCodefalse)->getName();
  544.                             if ((!is_null($translation)) && ($defaultTranslation != "")) {
  545.                                 $AppTranslationString->translate($languageCode)->setName($defaultTranslation);
  546.                             }
  547.                         }
  548.                     }
  549.                     $AppTranslationString->mergeNewTranslations();
  550.                     $this->entity_manager->persist($AppTranslationString);
  551.                     $this->entity_manager->flush();
  552.                 }
  553.             }
  554.             // update translations strings array
  555.             foreach ($appTranslations as $appTranslation) {
  556.                 $appLocaleSettings $appTranslation->getSettings();
  557.                 $locale $appTranslation->getLocale();
  558.                 $objectTypesAray = array();
  559.                 foreach($selectedObjectsIds as $selectedObjectId) {
  560.                     $ObjectType $this->entity_manager->getRepository(ObjectType::class)->find($selectedObjectId);
  561.                     $objectTypeName $ObjectType->translate($locale)->getName();
  562.                     $objectTypesAray[$selectedObjectId] = array(
  563.                         'name'=>$objectTypeName,
  564.                         'selected'=> ($defaultSearchObjectType == $selectedObjectId) ? true false,
  565.                         'taxonomy'=>$ObjectType->getTaxonomy()->getId());
  566.                 }
  567.                 $translations $this->entity_manager->getRepository(AppTranslations::class)->findByTranslationKey('search_form'$entity);
  568.                 foreach ($translations as $translation) {
  569.                     $translatsionsArray[$translation->getTranslationKey()] = $translation->translate($locale)->getName();
  570.                 }
  571.                 $appLocaleSettings['searchObjectTypes'] = $objectTypesAray;
  572.                 $appLocaleSettings['searchFormTranslations'] = $translatsionsArray;
  573.                 $appTranslation->setSettings($appLocaleSettings);
  574.                 $translationsAdmin $this->entity_manager->getRepository(AppTranslations::class)->findBy(['App'=>null]);
  575.                 foreach ($translationsAdmin as $translationAdmin) {
  576.                     $translationsAdminArray[$translationAdmin->getTranslationKey()] = $translationAdmin->translate($locale)->getName();
  577.                 }
  578.                 $translations $this->entity_manager->getRepository(AppTranslations::class)->findBy(['App'=>$entity]);
  579.                 foreach ($translations as $translation) {
  580.                     $translationsArray[$translation->getTranslationKey()] = $translation->translate($locale)->getName();
  581.                 }
  582.                 $finalTranslationsArray array_merge($translationsArrayarray_diff_key($translationsAdminArray$translationsArray)); // merge only translations that are missing in app translations (translationsArray)
  583.                 $appTranslation->setTranslationStrings($finalTranslationsArray);
  584.             }
  585.             // update google assetlinks.json and apple app-site-association.json
  586.             $projectRoot $this->kernel->getProjectDir();
  587.             $storePath $projectRoot.'/public';
  588.             $configPath $projectRoot.'/config/apps/'.$entity->getId().'/';
  589.             $apps $this->entity_manager->getRepository(App::class)->findAll();
  590.             $appleSiteAssociationArray = array('applinks'=>array('details'=>null));
  591.             $googleAssetlinksArray = array();
  592.             $filesystem = new Filesystem();
  593.             // save firebase service account json
  594.             if (!empty($firebaseServiceAccount)) {
  595.                 $firebaseServiceAccount trim($firebaseServiceAccount);
  596.                 $filesystem->dumpFile($configPath.'firebase.json'$firebaseServiceAccount);
  597.             }
  598.             foreach ($apps as $App) {
  599.                 $appSettings $App->getSettings();
  600.                 $appleTeamId = (isset($appSettings['appleTeamId'])) ? $appSettings['appleTeamId'] : '';
  601.                 $appleBundleId = (isset($appSettings['appleBundleId'])) ? $appSettings['appleBundleId'] : '';
  602.                 $googleCertFingerprint = (isset($appSettings['googleCertFingerprint'])) ? $appSettings['googleCertFingerprint'] : '';
  603.                 $googlePackageName = (isset($appSettings['googlePackageName'])) ? $appSettings['googlePackageName'] : '';
  604.                 if (stristr($googleCertFingerprint',')) {
  605.                     $googleCertFingerprint str_replace('"','',$googleCertFingerprint);
  606.                     $googleCertFingerprint preg_replace('/[\r\n\s]+/'''$googleCertFingerprint);
  607.                     $certFingerprintArray explode(',',$googleCertFingerprint);
  608.                 } else {
  609.                     $certFingerprintArray = array($googleCertFingerprint);
  610.                 }
  611.                 if (!empty($appleTeamId) && !empty($appleBundleId)) {
  612.                     $appleSingleSiteAssociationArray = array(
  613.                         'appID'=>$appleTeamId.'.'.$appleBundleId,
  614.                         'components'=>array(array('/'=>'/r/'.$App->getId().'/*',
  615.                                             'comment'=>'comment'))
  616.                     );
  617.                     $appleSiteAssociationArray['applinks']['details'][] = $appleSingleSiteAssociationArray;
  618.                 }
  619.                 if (!empty($googleCertFingerprint) && !empty($googlePackageName)) {
  620.                     $googleSingleSiteAssociationArray = array(
  621.                         'relation'=>array('delegate_permission/common.handle_all_urls'),
  622.                         'target'=>array('namespace'=>'android_app',
  623.                                         'package_name'=>$googlePackageName,
  624.                                         'sha256_cert_fingerprints'=>$certFingerprintArray)
  625.                     );
  626.                     $googleAssetlinksArray[] = $googleSingleSiteAssociationArray;
  627.                 }
  628.             }
  629.             $googleAssetlinksJson json_encode($googleAssetlinksArrayJSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  630.             $appleSiteAssociationJson json_encode($appleSiteAssociationArrayJSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
  631.             $filesystem->dumpFile($storePath.'/.well-known/assetlinks.json'$googleAssetlinksJson);
  632.             $filesystem->dumpFile($storePath.'/.well-known/apple-app-site-association'$appleSiteAssociationJson);
  633.             $this->entity_manager->persist($entity);
  634.             $entity->mergeNewTranslations();
  635.             $this->entity_manager->flush();
  636.         }
  637.         if ($entity instanceof Algorithm) {
  638.             $algorithmType $entity->getType();
  639.             $algorithmObjectType  $entity->getObjectType();
  640.             if (!empty($algorithmObjectType)) {
  641.                 $Taxonomy $algorithmObjectType->getSlug();
  642.                 if ($algorithmType == "modifier") {
  643.                     $ObjectId $entity->getObjectId();
  644.                     if ($ObjectId 0) {
  645.                         if ($Taxonomy == "test")  {
  646.                             $Test $this->entity_manager->getRepository(Test::class)->find($ObjectId);
  647.                             $algorithmConditionRepository $this->entity_manager->getRepository(AlgorithmCondition::class);
  648.                             $testDefinitions $this->testService->getAllVariables($Test);
  649.                             $newAlgorithmConditionsArray = array();
  650.                             foreach ($testDefinitions as $testDefinition) {
  651.                                 $algorithmCondition = new AlgorithmCondition();
  652.                                 $algorithmCondition->setFormula($testDefinition->getSlug());
  653.                                 $algorithmCondition->setActive(true);
  654.                                 $algorithmCondition->setObjectId($testDefinition->getId());
  655.                                 $testDefinitionId $testDefinition->getId();
  656.                                 $storedCondition $algorithmConditionRepository->findOneBy(array('Algorithm' => $entity->getId(), 'ObjectId' => $testDefinitionId));
  657.                                 if (empty($storedCondition)) {
  658.                                     $entity->addAlgorithmCondition($algorithmCondition);
  659.                                 }
  660.                                 array_push($newAlgorithmConditionsArray$testDefinitionId); // create array for all new algorithm conditions
  661.                             }
  662.                             $StoredConditions $entity->getAlgorithmConditions();
  663.                             foreach ($StoredConditions as $storedCondition) {
  664.                                 $storedConditionId $storedCondition->getObjectId();
  665.                                 if (!in_array($storedConditionId$newAlgorithmConditionsArray)) { // check if stored conditions are in the $newAlgorithmConditionsArray array. If no, remove them.
  666.                                     $entity->removeAlgorithmCondition($storedCondition);
  667.                                 }
  668.                             }
  669.                             $this->entity_manager->persist($entity);
  670.                             $this->entity_manager->flush();
  671.                         } elseif ($Taxonomy == "therapy")  {
  672.                             $Therapy $this->entity_manager->getRepository(Therapy::class)->find($ObjectId);
  673.                             $algorithmConditionRepository $this->entity_manager->getRepository(AlgorithmCondition::class);
  674.                             $therapyDefinitions $Therapy->getTherapyDefinitions();
  675.                             $newAlgorithmConditionsArray = array();
  676.                             foreach ($therapyDefinitions as $therapyDefinition) {
  677.                                 $algorithmCondition = new AlgorithmCondition();
  678.                                 $algorithmCondition->setFormula('');
  679.                                 $algorithmCondition->setActive(false);
  680.                                 $algorithmCondition->setObjectId($therapyDefinition->getId());
  681.                                 $therapyDefinitionId $therapyDefinition->getId();
  682.                                 $storedCondition $algorithmConditionRepository->findOneBy(array('Algorithm' => $entity->getId(), 'ObjectId' => $therapyDefinitionId));
  683.                                 if (empty($storedCondition)) {
  684.                                     $entity->addAlgorithmCondition($algorithmCondition);
  685.                                 }
  686.                                 array_push($newAlgorithmConditionsArray$therapyDefinitionId); // create array for all new algorithm conditions
  687.                             }
  688.                         }
  689.                         $StoredConditions $entity->getAlgorithmConditions();
  690.                         foreach ($StoredConditions as $storedCondition) {
  691.                             $storedConditionId $storedCondition->getObjectId();
  692.                             if (!in_array($storedConditionId$newAlgorithmConditionsArray)) { // check if stored conditions are in the $newAlgorithmConditionsArray array. If no, remove them.
  693.                                 $entity->removeAlgorithmCondition($storedCondition);
  694.                             }
  695.                         }
  696.                         $this->entity_manager->persist($entity);
  697.                         $this->entity_manager->flush();
  698.                     }
  699.                 } elseif ($algorithmType == "scoring") {
  700.                     $Settings $entity->getSettings();
  701.                     $ObjectIds $entity->getObjectIds();
  702.                     if (empty($ObjectIds)) { // remove conditions if objectsids is empty
  703.                         $StoredConditions $entity->getAlgorithmConditions();
  704.                         foreach ($StoredConditions as $storedCondition) {
  705.                             $entity->removeAlgorithmCondition($storedCondition);
  706.                         }
  707.                         $this->entity_manager->persist($entity);
  708.                         $this->entity_manager->flush();
  709.                     }
  710.                     $SimpleScoring = isset($Settings['SimpleScore']) ? $Settings['SimpleScore'] : false;
  711.                     if ($SimpleScoring == false) {
  712.                         $StoredConditions $entity->getAlgorithmConditions();
  713.                         foreach ($StoredConditions as $storedCondition) {
  714.                             $storedCondition->setScore('');
  715.                         }
  716.                         $this->entity_manager->persist($entity);
  717.                         $this->entity_manager->flush();
  718.                     }
  719.                 }
  720.             }
  721.         }
  722.     }
  723. }