<?php
namespace App\Event;
use App\Entity\Algorithm;
use App\Entity\AlgorithmCondition;
use App\Entity\App;
use App\Entity\AppTranslations;
use App\Entity\Category;
use App\Entity\Disease;
use App\Entity\Drug;
use App\Entity\Flow;
use App\Entity\Import;
use App\Entity\Language;
use App\Entity\ObjectType;
use App\Entity\Page;
use App\Entity\Test;
use App\Entity\TestDefinition;
use App\Entity\Therapy;
use App\Entity\User;
use App\Service\AlgorithmService;
use App\Service\EntityUsageService;
use App\Service\ImportService;
use App\Service\PageGeneratorService;
use App\Service\SlugService;
use App\Service\TestService;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class EasyAdminSubscriber implements EventSubscriberInterface {
private $entity_manager;
public function __construct( EntityManagerInterface $entity_manager, EntityUsageService $entityUsageService, AlgorithmService $algorithmService, TokenStorageInterface $token_storage, SlugService $slugService, TestService $testService, KernelInterface $kernel, ImportService $importService, RequestStack $request, SessionInterface $session, PageGeneratorService $pageGeneratorService) {
$this->entity_manager = $entity_manager;
$this->token_storage = $token_storage;
$this->testService = $testService;
$this->kernel = $kernel;
$this->importService = $importService;
$this->request = $request;
$this->session = $session;
$this->pageGeneratorService = $pageGeneratorService;
$this->slugService = $slugService;
$this->algorithmService = $algorithmService;
$this->entityUsageService = $entityUsageService;
}
public static function getSubscribedEvents(): ?array {
return [
EasyAdminEvents::POST_UPDATE => 'onPostUpdate',
EasyAdminEvents::POST_PERSIST => 'onPostPersist',
EasyAdminEvents::PRE_PERSIST => 'onPrePersist',
EasyAdminEvents::PRE_UPDATE => 'onPreUpdate',
EasyAdminEvents::POST_EDIT => 'onPostEdit',
];
}
public function onPreUpdate(GenericEvent $event) {
$entity = $event->getSubject();
if ($entity instanceof App) {
$id = $entity->getId();
// query manager to get the old entity, before update
$qb = $this->entity_manager->createQueryBuilder();
$qb->select('a.Settings')
->from('App:App', 'a')
->where('a.id = :id')->setParameter('id', $id);
$qb->setMaxResults(1);
$oldSettingsVar = $qb->getQuery()->getSingleResult();
$oldSettings = $oldSettingsVar['Settings'];
$Settings = $entity->getSettings();
$primaryColor = $Settings['primaryColor'];
$oldPrimaryColor = isset($oldSettings['primaryColor']) ? $oldSettings['primaryColor'] : '';
$secondaryColor = $Settings['secondaryColor'];
$oldSecondaryColor = isset($oldSettings['secondaryColor']) ? $oldSettings['secondaryColor'] : '';
$infoColor = $Settings['infoColor'];
$oldInfoColor = isset($oldSettings['infoColor']) ? $oldSettings['infoColor'] : '';
$successColor = $Settings['successColor'];
$oldSuccessColor = isset($oldSettings['successColor']) ? $oldSettings['successColor'] : '';
$dangerColor = $Settings['dangerColor'];
$oldDangerColor = isset($oldSettings['dangerColor']) ? $oldSettings['dangerColor'] : '';
$warningColor = $Settings['warningColor'];
$oldWarningColor = isset($oldSettings['warningColor']) ? $oldSettings['warningColor'] : '';
$request = $this->request->getCurrentRequest();
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
$output = null;
if (($primaryColor!=$oldPrimaryColor) || ($secondaryColor!=$oldSecondaryColor) || ($infoColor!=$oldInfoColor) || ($successColor!=$oldSuccessColor) || ($dangerColor!=$oldDangerColor) || ($warningColor!=$oldWarningColor)) { // if colors changes update the css
$output = $this->pageGeneratorService->compileCss($entity);
$Settings['cssUpdatedAt'] = time();
}
$this->pageGeneratorService->storeCustomCssJs($entity);
$Web = $entity->getWeb();
if ($Web) {
$apiUserId = isset($Settings['ApiUser']) ? $Settings['ApiUser'] : 0;
$User = $this->entity_manager->getRepository(User::class)->find($apiUserId);
if (!empty($User->getApiToken())) {
$webapp = $this->pageGeneratorService->updateWebApp($entity, $User->getApiToken());
}
}
}
}
public function onPostEdit(GenericEvent $event) {
$token = $this->token_storage->getToken();
$User = $token->getUser();
$Customer = $User->getCustomer();
$entity = $event->getSubject();
$entityName = (isset($entity['name'])) ? $entity['name'] : null;
if ($entityName == 'Algorithm') {
$request = $this->request->getCurrentRequest();
$id = $request->query->get('id');
$Algorithm = $this->entity_manager->getRepository(Algorithm::class)->find($id);
$errors = $this->algorithmService->checkAlgorithm($Algorithm, $Customer);
if (!empty($errors)) {
foreach ($errors as $error) {
$this->session->getFlashBag()->add('danger',$error);
}
}
}
}
public function onPrePersist(GenericEvent $event) {
$entity = $event->getSubject();
if ($entity instanceof TestDefinition) {
}
}
public function onPostPersist(GenericEvent $event) {
$entity = $event->getSubject();
$token = $this->token_storage->getToken();
$User = $token->getUser();
$Customer = $User->getCustomer();
$lang = $Customer->getDefaultLanguageCode();
if ($entity instanceof Page) {
// save tree
$parent_id=$entity->getParent();
$Parent = ($parent_id>0) ? $this->entity_manager->getRepository(Page::class)->find($parent_id) : null;
if (!empty($Parent)) {
$entity->setChildNodeOf($Parent);
$this->entity_manager->persist($Parent);
$this->entity_manager->flush();
} else {
$entity->setMaterializedPath('');
}
$translations = $entity->getTranslations();
$imagesArray = preg_match_all('/<img[^>]+>/i',$entity->get, $result);
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
if ($entity instanceof Algorithm) {
$algorithmType = $entity->getType();
$algorithmObjectType = $entity->getObjectType();
if (!empty($algorithmObjectType)) {
$Taxonomy = $algorithmObjectType->getSlug();
if ($algorithmType == "modifier") {
$ObjectId = $entity->getObjectId();
if (($Taxonomy == "test") && ($ObjectId > 0)) {
$Test = $this->entity_manager->getRepository(Test::class)->find($ObjectId);
$tesDefinitions = $this->testService->getAllVariables($Test);
foreach ($tesDefinitions as $tesDefinition) {
$algorithmCondition = new AlgorithmCondition();
$algorithmCondition->setFormula($tesDefinition->getSlug());
$algorithmCondition->setActive(true);
$algorithmCondition->setObjectId($tesDefinition->getId());
$entity->addAlgorithmCondition($algorithmCondition);
}
}
}
}
}
}
public function onPostUpdate(GenericEvent $event) {
$entity = $event->getSubject();
$token = $this->token_storage->getToken();
$User = $token->getUser();
$Customer = $User->getCustomer();
$lang = $Customer->getDefaultLanguageCode();
$Settings = $Customer->getSettings();
$languages = (isset($Settings['languages'])) ? $Settings['languages'] : array();
foreach ($languages as $languageId) {
$Language = $this->entity_manager->getRepository(Language::class)->find($languageId);
$usedLanguagesArray[] = $Language->getCode();
}
if ($entity instanceof Category) {
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
if ($entity instanceof Import) {
$projectRoot = $this->kernel->getProjectDir();
$fileName = urldecode($entity->getFilename());
$type = urldecode($entity->getType());
$Taxonomy=$entity->getTaxonomy();
$Worksheet=$entity->getWorksheet();
$ObjectId=$entity->getObjectType()->getId();
$taxonomyName = $Taxonomy->getSlug();
$fullPath = $projectRoot.'/public'.$fileName;
$importSettings = $entity->getSettings();
$importStatus = $entity->getStatus();
if (file_exists($fullPath)) {
if ($taxonomyName == 'country') {
$str = file_get_contents($fullPath);
$this->importService->importCountriesJson($str, $ObjectId);
$entity->setStatus('finished');
$importSettings = array('stage'=>2);
$entity->setSettings($importSettings);
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
} elseif ($taxonomyName == 'test') {
$stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
$startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
if (($importStatus=='initial') && (empty($Worksheet))) {
$worksheets = $this->importService->importIcd9Xls($fullPath, $stage, $ObjectId, 0,1000, $Taxonomy, $Worksheet);
$importSettings = array('stage'=>1, 'worksheet'=>'', 'worksheets'=>$worksheets);
$entity->setSettings($importSettings);
} elseif (!empty($Worksheet)) {
$importedArray = $this->importService->importIcd9Xls($fullPath, $stage, $ObjectId, $startFrom,1000, $Taxonomy,$Worksheet);
$imported = $importedArray[0];
$totalRows = $importedArray[1];
$importSettings['stage'] = 2;
$importSettings['worksheet'] = $Worksheet;
$importSettings['ObjectId'] = $ObjectId;
$importSettings['imported'] = $imported;
$importSettings['totalRows'] =$totalRows;
$entity->setStatus('finished');
$entity->setSettings($importSettings);
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
} elseif ($taxonomyName == 'disease') {
$stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
$startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
if ($type == 'xlsx') {
$importedArray = $this->importService->importIcd10($fullPath, $ObjectId, $startFrom, 100);
$imported = $importedArray[0];
$totalRows = $importedArray[1];
$stage = 1;
$importSettings['stage'] = $stage;
$importSettings['ObjectId'] = $ObjectId;
$importSettings['imported'] = $imported;
$importSettings['totalRows'] = $totalRows;
$importSettings['startFrom'] = $startFrom + 100;
if ($imported == 101) {
$entity->setStatus('partial');
} else {
$entity->setStatus('finished');
}
$entity->setStatus('finished');
$entity->setSettings($importSettings);
} elseif ($type == 'json') {
if ($ObjectId == 19) {
$importedArray = $this->importService->importInteractions($fullPath, $ObjectId, 0, 2000);
}
$imported = $importedArray[0];
$totalRows = $importedArray[1];
$stage = 1;
$importSettings['stage'] = $stage;
$importSettings['ObjectId'] = $ObjectId;
$importSettings['imported'] = $imported;
$importSettings['totalRows'] = $totalRows;
$importSettings['startFrom'] = $startFrom + 2000;
if ($imported == 2001) {
$entity->setStatus('partial');
} else {
$entity->setStatus('finished');
}
$entity->setSettings($importSettings);
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
} elseif ($taxonomyName == 'customentity') {
$stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
$startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
if ($type == 'xlsx') {
} elseif ($type == 'json') {
if ($ObjectId == 20) {
$importedArray = $this->importService->importInteractionsCustom($fullPath, $ObjectId, 0, 2000);
}
$imported = $importedArray[0];
$totalRows = $importedArray[1];
$stage = 1;
$importSettings['stage'] = $stage;
$importSettings['ObjectId'] = $ObjectId;
$importSettings['imported'] = $imported;
$importSettings['totalRows'] = $totalRows;
$importSettings['startFrom'] = $startFrom + 2000;
if ($imported == 2001) {
$entity->setStatus('partial');
} else {
$entity->setStatus('finished');
}
$entity->setSettings($importSettings);
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
} elseif ($taxonomyName == 'drug') {
$stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
$startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
if (($importStatus=='initial') && (empty($Worksheet))) {
if ($type == 'xlsx') {
if ($ObjectId == 10) {
$worksheets = $this->importService->importAtcXls($fullPath, $stage, $ObjectId, 0, 1000, $Taxonomy, '');
} elseif ($ObjectId == 11) {
$worksheets = $this->importService->importRplXls($fullPath, $stage, $ObjectId, 0, 1000, $Taxonomy, '');
}
$importSettings = array('stage' => 1, 'worksheet' => '', 'worksheets' => $worksheets);
$entity->setSettings($importSettings);
} elseif ($type == 'json') {
if ($ObjectId == 17) {
$importedArray = $this->importService->importInteractionDrugs($fullPath, $stage, $ObjectId, $Taxonomy);
}
$imported = $importedArray[0];
$totalRows = $importedArray[1];
$importSettings['imported'] = $imported;
$importSettings['startFrom'] = $startFrom + 1000;
$importSettings['totalRows'] = $totalRows;
if ($imported != $totalRows) {
$entity->setStatus('partial');
} else {
$entity->setStatus('finished');
}
$entity->setSettings($importSettings);
}
} elseif (!empty($Worksheet)) {
$stage = 2;
$importSettings['stage'] = $stage;
$importSettings['worksheet'] = $Worksheet;
$importSettings['ObjectId'] = $ObjectId;
if ($type == 'xlsx') {
if ($ObjectId==10) {
$importedArray = $this->importService->importAtcXls($fullPath, $stage, $ObjectId, $startFrom, 1000, $Taxonomy, $Worksheet);
} elseif ($ObjectId == 11) {
$importedArray = $this->importService->importRplXls($fullPath, $stage, $ObjectId, $startFrom, 1000, $Taxonomy, $Worksheet);
}
$imported = $importedArray[0];
$totalRows = $importedArray[1];
$importSettings['imported'] = $imported;
$importSettings['startFrom'] = $startFrom + 1000;
$importSettings['totalRows'] = $totalRows;
if ($imported == 1001) {
$entity->setStatus('partial');
} else {
$entity->setStatus('finished');
}
$entity->setSettings($importSettings);
}
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
} elseif ($taxonomyName == 'page') {
} elseif ($taxonomyName == 'procedure') {
$stage = (isset($importSettings['stage'])) ? $importSettings['stage'] : 1;
$startFrom = (isset($importSettings['startFrom'])) ? $importSettings['startFrom'] : 0;
if (($importStatus=='initial') && (empty($Worksheet))) {
$worksheets = $this->importService->importIcd9Xls($fullPath, $stage, $ObjectId,0,1000,$Taxonomy, '');
$importSettings = array('stage'=>1, 'worksheet'=>'', 'worksheets'=>$worksheets);
$entity->setSettings($importSettings);
} elseif (!empty($Worksheet)) {
$stage = 2;
$importSettings['stage'] = $stage;
$importSettings['worksheet'] = $Worksheet;
$importSettings['ObjectId'] = $ObjectId;
$imported = $this->importService->importIcd9Xls($fullPath, $stage, $ObjectId, $startFrom, 1000,$Taxonomy, $Worksheet);
$importSettings['imported'] = $imported;
$importSettings['startFrom'] = $startFrom + 1000;
if ($imported == 1001) {
$entity->setStatus('partial');
} else {
$entity->setStatus('finished');
}
$entity->setSettings($importSettings);
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
}
}
if ($entity instanceof TestDefinition) {
$errors = $this->entityUsageService->checkTestDefinitionStructure($entity, $lang, $usedLanguagesArray, $User);
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
if ($entity instanceof Test) {
//$entity->generateSlug();
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
if ($entity instanceof Drug) {
$name = $entity->translate($lang)->getName();
$slug = $this->slugService->generateSlug($name);
$entity->setSlug($slug);
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
if ($entity instanceof Disease) {
$name = $entity->translate($lang)->getName();
$slug = $this->slugService->generateSlug($name);
$entity->setSlug($slug);
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
if ($entity instanceof Flow) {
$entity->generateSlug();
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
if ($entity instanceof Page) {
$projectRoot = $this->kernel->getProjectDir();
$translations = $entity->getTranslations();
$request = $this->request->getCurrentRequest();
$baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath();
foreach ($translations as $translation) { // get array of missing files
$missingFilesArray = $this->pageGeneratorService->getAttachmentsFromTranslation($entity, $translation, true);
}
$missingFiles = implode(', ',$missingFilesArray);
$message = 'There are missing files in the page body: '.$missingFiles;
if (!empty($missingFilesArray)) {
$this->session->getFlashBag()->add('danger',$message);
}
$now = new \DateTime('now');
$entity->setUpdatedAt($now);
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
// Update images / attachments array for current page and whole app files array
$App = $entity->getApp();
$AppSettings = $App->getSettings();
$languages = isset($AppSettings['languages']) ? $AppSettings['languages'] : array();
$appFilesArray = array();
foreach ($languages as $languageId) {
$Language = $this->entity_manager->getRepository(Language::class)->find($languageId);
$appFilesArray[$Language->getCode()]['images'] = array();
$appFilesArray[$Language->getCode()]['attachments'] = array();
}
if (empty($appFilesArray)) {
$appFilesArray['en']['images'] = array();
$appFilesArray['en']['attachments'] = array();
}
$pages = $this->entity_manager->getRepository(Page::class)->findBy(array('App'=>$App));
// update pages
$hasNews = 0;
$hasCalendar = 0;
foreach ($pages as $page) {
// check for notifications
$template = $page->getTemplate();
if ($template == 'newsfeed') {
$hasNews = 1;
} elseif ($template == 'custom') {
$pageSettings = $page->getSettings();
$customFunction = (isset($pageSettings['customFunction'])) ? $pageSettings['customFunction'] : null;
if ($customFunction == 'my_calendar') {
$hasCalendar = 1;
}
}
// check translations
$translations = $page->getTranslations();
foreach ($translations as $translation) {
$pageLocale = $translation->getLocale();
$translation = $this->pageGeneratorService->getAttachmentsFromTranslation($page, $translation, false);
$pageFiles = $translation->getFiles();
$pageImagesArray = $pageFiles['images'];
$pageAttachmentsArray = $pageFiles['attachments'];
if (isset($appFilesArray[$pageLocale])) {
if (!empty($pageImagesArray)) {
$appFilesArray[$pageLocale]['images'][] = $pageImagesArray;
}
if (!empty($pageAttachmentsArray)) {
$appFilesArray[$pageLocale]['attachments'][] = $pageAttachmentsArray;
}
}
}
//$this->entity_manager->persist($page);
//$this->entity_manager->flush();
}
// update notifications array
$notificationsArray = array('newsfeed'=>$hasNews, 'calendar'=>$hasCalendar);
$App->setNotifications($notificationsArray);
foreach ($appFilesArray as $locale=>$filesArray) { // rearrange array, make files unique
$imagesArray = $filesArray['images'];
$attachmentsArray = $filesArray['attachments'];
$newImagesArray = array();
foreach ($imagesArray as $value1) { // merge arrays from different pages
$newImagesArray = array_merge($newImagesArray, $value1);
}
$newImagesArray1 = array();
foreach ($newImagesArray as $value2) {// create array with paths as keys to make unique data
if (is_array($value2)) {
$newImagesArray1[$value2['path']] = array('time'=>$value2['time'], 'size'=> $value2['size']);
}
}
$newImagesArray2 = array();
foreach ($newImagesArray1 as $imagePath=>$imageData) { // loop through imagesArray1 to make path/time keys back
$newImagesArray2[] = array('path'=>(!empty($imagePath)) ? $baseurl.$imagePath : '', 'time'=>$imageData['time'], 'size'=>$imageData['size']);
}
/// attachments
$newattachmentsArray = array();
foreach ($attachmentsArray as $value1) { // merge arrays from different pages
$newattachmentsArray = array_merge($newattachmentsArray, $value1);
}
$newattachmentsArray1 = array();
foreach ($newattachmentsArray as $value2) {// create array with paths as keys to make unique data
if (is_array($value2)) {
$newattachmentsArray1[$value2['path']] = array('time'=>$value2['time'], 'size'=> $value2['size'] );
}
}
$newattachmentsArray2 = array();
foreach ($newattachmentsArray1 as $imagePath=>$imageData) { // loop through attachmentsArray1 to make path/time keys back
$newattachmentsArray2[] = array('path'=>(!empty($imagePath)) ? $baseurl.$imagePath : '', 'time'=>$imageData['time'], 'size'=>$imageData['size']);
}
$webFiles = $this->pageGeneratorService->returnPageFilesArray($App, $baseurl); // get design files for App
$appFilesArray[$locale] = array('images'=>$newImagesArray2, 'attachments'=>$newattachmentsArray2, 'webdesign'=>$webFiles);
}
$taxonomyPagesArray = $this->pageGeneratorService->getTaxonomyPagesForApp($App, $lang);
$App->setTaxonomyPages($taxonomyPagesArray);
$App->setFiles($appFilesArray);
$this->entity_manager->persist($App);
$this->entity_manager->flush();
}
if ($entity instanceof App) {
$appTranslations = $entity->getTranslations();
$Settings = $entity->getSettings();
$selectedObjectsIds = isset($Settings['ObjectTypes']) ? $Settings['ObjectTypes'] : [];
$defaultSearchObjectType = isset($Settings['defaultSearchObjectType']) ? $Settings['defaultSearchObjectType'] : null;
$firebaseServiceAccount = isset($Settings['firebaseServiceAccount']) ? $Settings['firebaseServiceAccount'] : '';
$updateEmptyTranslations = $entity->isUpdateEmptyTranslations();
// update languageCode
$languageId = $entity->getDefaultLanguage();
$Language = $this->entity_manager->getRepository(Language::class)->find($languageId);
if (!empty($Language)) {
$defaultLanguageCode = $Language->getCode();
$entity->setDefaultLanguageCode($defaultLanguageCode);
}
// copy empty translations from default translations
if ($updateEmptyTranslations) {
$usedLanguagesArray = array();
$languages = (isset($Settings['languages'])) ? $Settings['languages'] : array();
foreach ($languages as $languageId) {
$Language = $this->entity_manager->getRepository(Language::class)->find($languageId);
$usedLanguagesArray[] = $Language->getCode();
}
$appTranslationsStrings = $this->entity_manager->getRepository(AppTranslations::class)->findBy(array('App'=>$entity));
foreach ($appTranslationsStrings as $AppTranslationString) {
foreach ($usedLanguagesArray as $languageCode) {
$translation = trim($AppTranslationString->translate($languageCode, false)->getName());
if (is_null($translation) || $translation === "") {
$defaultTranslationKey = $AppTranslationString->getTranslationKey();
$DefaultTranslation = $this->entity_manager->getRepository(AppTranslations::class)->findOneBy(array('App'=>null, 'TranslationKey'=>$defaultTranslationKey));
$defaultTranslation = $DefaultTranslation->translate($languageCode, false)->getName();
if ((!is_null($translation)) && ($defaultTranslation != "")) {
$AppTranslationString->translate($languageCode)->setName($defaultTranslation);
}
}
}
$AppTranslationString->mergeNewTranslations();
$this->entity_manager->persist($AppTranslationString);
$this->entity_manager->flush();
}
}
// update translations strings array
foreach ($appTranslations as $appTranslation) {
$appLocaleSettings = $appTranslation->getSettings();
$locale = $appTranslation->getLocale();
$objectTypesAray = array();
foreach($selectedObjectsIds as $selectedObjectId) {
$ObjectType = $this->entity_manager->getRepository(ObjectType::class)->find($selectedObjectId);
$objectTypeName = $ObjectType->translate($locale)->getName();
$objectTypesAray[$selectedObjectId] = array(
'name'=>$objectTypeName,
'selected'=> ($defaultSearchObjectType == $selectedObjectId) ? true : false,
'taxonomy'=>$ObjectType->getTaxonomy()->getId());
}
$translations = $this->entity_manager->getRepository(AppTranslations::class)->findByTranslationKey('search_form', $entity);
foreach ($translations as $translation) {
$translatsionsArray[$translation->getTranslationKey()] = $translation->translate($locale)->getName();
}
$appLocaleSettings['searchObjectTypes'] = $objectTypesAray;
$appLocaleSettings['searchFormTranslations'] = $translatsionsArray;
$appTranslation->setSettings($appLocaleSettings);
$translationsAdmin = $this->entity_manager->getRepository(AppTranslations::class)->findBy(['App'=>null]);
foreach ($translationsAdmin as $translationAdmin) {
$translationsAdminArray[$translationAdmin->getTranslationKey()] = $translationAdmin->translate($locale)->getName();
}
$translations = $this->entity_manager->getRepository(AppTranslations::class)->findBy(['App'=>$entity]);
foreach ($translations as $translation) {
$translationsArray[$translation->getTranslationKey()] = $translation->translate($locale)->getName();
}
$finalTranslationsArray = array_merge($translationsArray, array_diff_key($translationsAdminArray, $translationsArray)); // merge only translations that are missing in app translations (translationsArray)
$appTranslation->setTranslationStrings($finalTranslationsArray);
}
// update google assetlinks.json and apple app-site-association.json
$projectRoot = $this->kernel->getProjectDir();
$storePath = $projectRoot.'/public';
$configPath = $projectRoot.'/config/apps/'.$entity->getId().'/';
$apps = $this->entity_manager->getRepository(App::class)->findAll();
$appleSiteAssociationArray = array('applinks'=>array('details'=>null));
$googleAssetlinksArray = array();
$filesystem = new Filesystem();
// save firebase service account json
if (!empty($firebaseServiceAccount)) {
$firebaseServiceAccount = trim($firebaseServiceAccount);
$filesystem->dumpFile($configPath.'firebase.json', $firebaseServiceAccount);
}
foreach ($apps as $App) {
$appSettings = $App->getSettings();
$appleTeamId = (isset($appSettings['appleTeamId'])) ? $appSettings['appleTeamId'] : '';
$appleBundleId = (isset($appSettings['appleBundleId'])) ? $appSettings['appleBundleId'] : '';
$googleCertFingerprint = (isset($appSettings['googleCertFingerprint'])) ? $appSettings['googleCertFingerprint'] : '';
$googlePackageName = (isset($appSettings['googlePackageName'])) ? $appSettings['googlePackageName'] : '';
if (stristr($googleCertFingerprint, ',')) {
$googleCertFingerprint = str_replace('"','',$googleCertFingerprint);
$googleCertFingerprint = preg_replace('/[\r\n\s]+/', '', $googleCertFingerprint);
$certFingerprintArray = explode(',',$googleCertFingerprint);
} else {
$certFingerprintArray = array($googleCertFingerprint);
}
if (!empty($appleTeamId) && !empty($appleBundleId)) {
$appleSingleSiteAssociationArray = array(
'appID'=>$appleTeamId.'.'.$appleBundleId,
'components'=>array(array('/'=>'/r/'.$App->getId().'/*',
'comment'=>'comment'))
);
$appleSiteAssociationArray['applinks']['details'][] = $appleSingleSiteAssociationArray;
}
if (!empty($googleCertFingerprint) && !empty($googlePackageName)) {
$googleSingleSiteAssociationArray = array(
'relation'=>array('delegate_permission/common.handle_all_urls'),
'target'=>array('namespace'=>'android_app',
'package_name'=>$googlePackageName,
'sha256_cert_fingerprints'=>$certFingerprintArray)
);
$googleAssetlinksArray[] = $googleSingleSiteAssociationArray;
}
}
$googleAssetlinksJson = json_encode($googleAssetlinksArray, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
$appleSiteAssociationJson = json_encode($appleSiteAssociationArray, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
$filesystem->dumpFile($storePath.'/.well-known/assetlinks.json', $googleAssetlinksJson);
$filesystem->dumpFile($storePath.'/.well-known/apple-app-site-association', $appleSiteAssociationJson);
$this->entity_manager->persist($entity);
$entity->mergeNewTranslations();
$this->entity_manager->flush();
}
if ($entity instanceof Algorithm) {
$algorithmType = $entity->getType();
$algorithmObjectType = $entity->getObjectType();
if (!empty($algorithmObjectType)) {
$Taxonomy = $algorithmObjectType->getSlug();
if ($algorithmType == "modifier") {
$ObjectId = $entity->getObjectId();
if ($ObjectId > 0) {
if ($Taxonomy == "test") {
$Test = $this->entity_manager->getRepository(Test::class)->find($ObjectId);
$algorithmConditionRepository = $this->entity_manager->getRepository(AlgorithmCondition::class);
$testDefinitions = $this->testService->getAllVariables($Test);
$newAlgorithmConditionsArray = array();
foreach ($testDefinitions as $testDefinition) {
$algorithmCondition = new AlgorithmCondition();
$algorithmCondition->setFormula($testDefinition->getSlug());
$algorithmCondition->setActive(true);
$algorithmCondition->setObjectId($testDefinition->getId());
$testDefinitionId = $testDefinition->getId();
$storedCondition = $algorithmConditionRepository->findOneBy(array('Algorithm' => $entity->getId(), 'ObjectId' => $testDefinitionId));
if (empty($storedCondition)) {
$entity->addAlgorithmCondition($algorithmCondition);
}
array_push($newAlgorithmConditionsArray, $testDefinitionId); // create array for all new algorithm conditions
}
$StoredConditions = $entity->getAlgorithmConditions();
foreach ($StoredConditions as $storedCondition) {
$storedConditionId = $storedCondition->getObjectId();
if (!in_array($storedConditionId, $newAlgorithmConditionsArray)) { // check if stored conditions are in the $newAlgorithmConditionsArray array. If no, remove them.
$entity->removeAlgorithmCondition($storedCondition);
}
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
} elseif ($Taxonomy == "therapy") {
$Therapy = $this->entity_manager->getRepository(Therapy::class)->find($ObjectId);
$algorithmConditionRepository = $this->entity_manager->getRepository(AlgorithmCondition::class);
$therapyDefinitions = $Therapy->getTherapyDefinitions();
$newAlgorithmConditionsArray = array();
foreach ($therapyDefinitions as $therapyDefinition) {
$algorithmCondition = new AlgorithmCondition();
$algorithmCondition->setFormula('');
$algorithmCondition->setActive(false);
$algorithmCondition->setObjectId($therapyDefinition->getId());
$therapyDefinitionId = $therapyDefinition->getId();
$storedCondition = $algorithmConditionRepository->findOneBy(array('Algorithm' => $entity->getId(), 'ObjectId' => $therapyDefinitionId));
if (empty($storedCondition)) {
$entity->addAlgorithmCondition($algorithmCondition);
}
array_push($newAlgorithmConditionsArray, $therapyDefinitionId); // create array for all new algorithm conditions
}
}
$StoredConditions = $entity->getAlgorithmConditions();
foreach ($StoredConditions as $storedCondition) {
$storedConditionId = $storedCondition->getObjectId();
if (!in_array($storedConditionId, $newAlgorithmConditionsArray)) { // check if stored conditions are in the $newAlgorithmConditionsArray array. If no, remove them.
$entity->removeAlgorithmCondition($storedCondition);
}
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
} elseif ($algorithmType == "scoring") {
$Settings = $entity->getSettings();
$ObjectIds = $entity->getObjectIds();
if (empty($ObjectIds)) { // remove conditions if objectsids is empty
$StoredConditions = $entity->getAlgorithmConditions();
foreach ($StoredConditions as $storedCondition) {
$entity->removeAlgorithmCondition($storedCondition);
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
$SimpleScoring = isset($Settings['SimpleScore']) ? $Settings['SimpleScore'] : false;
if ($SimpleScoring == false) {
$StoredConditions = $entity->getAlgorithmConditions();
foreach ($StoredConditions as $storedCondition) {
$storedCondition->setScore('');
}
$this->entity_manager->persist($entity);
$this->entity_manager->flush();
}
}
}
}
}
}