src/Services/CommonTools.php line 59

Open in your IDE?
  1. <?php
  2. //----------------------------------------------------------------------
  3. // src/Services/CommonTools.php
  4. //----------------------------------------------------------------------
  5. namespace App\Services;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. use Symfony\Component\PropertyAccess\PropertyAccess;
  10. use App\Entity\Access;
  11. use App\Entity\AccessClient\AccessClient;
  12. use App\Entity\Client\Client;
  13. use App\Entity\Client\Title;
  14. use App\Entity\Common\Attachment;
  15. use App\Entity\SocietyGroup;
  16. use App\Entity\Config\Config;
  17. use App\Entity\Config\Module;
  18. use App\Entity\Config\OptionConfig;
  19. use App\Entity\Ikea\ServiceOrder as IkeaServiceOrder;
  20. use App\Entity\Ikea\Product as IkeaProduct;
  21. use App\Entity\Ikea\Template as IkeaTemplate;
  22. use App\Entity\Ikea\TemplateProduct as IkeaTemplateProduct;
  23. use App\Entity\Log\ChangeLog;
  24. use App\Entity\Mission\Mission;
  25. use App\Entity\Mission\MissionOrigin;
  26. use App\Entity\Mission\MissionProject;
  27. use App\Entity\Mission\MissionStatus;
  28. use App\Entity\Mission\MissionType;
  29. use App\Entity\Planning\PlanningResource;
  30. use App\Entity\Planning\TaskStatus;
  31. use App\Entity\Planning\TaskType;
  32. use App\Entity\Platform\Devis\Devis;
  33. use App\Entity\Platform\Origin;
  34. use App\Entity\Platform\PaymentDeadline;
  35. use App\Entity\Platform\SocietyGroup\SocietyGroupFavorite;
  36. use App\Entity\Product\Product;
  37. use App\Entity\Product\Template;
  38. use App\Entity\Webapp\Components\AnomalyAction;
  39. use App\Entity\Webapp\Components\AnomalyCharge;
  40. use App\Entity\Webapp\Components\AnomalyProduct;
  41. use App\Entity\Webapp\Components\AnomalyReason;
  42. use App\Entity\Webapp\Components\AnomalyState;
  43. use App\Entity\Webapp\Components\InterventionType;
  44. use App\Entity\Webapp\Components\ReportType;
  45. use App\Entity\Webapp\Components\Satisfaction;
  46. use App\Services\LogTools;
  47. use App\Services\AccessClient\AccessClientTools;
  48. use App\Services\Config\ModuleTools;
  49. class CommonTools
  50. {
  51.     public function __construct(ManagerRegistry $doctrineRequestStack $requestStackUrlGeneratorInterface $router,
  52.     LogTools $logToolsModuleTools $moduleToolsAccessClientTools $accessClientTools)
  53.     {
  54.         $this->em $doctrine->getManager();
  55.         $this->requestStack $requestStack;
  56.         $this->router $router;
  57.         $this->logTools $logTools;
  58.         $this->moduleTools $moduleTools;
  59.         $this->accessClientTools $accessClientTools;
  60.     }
  61.     // Plan.io Task #4412
  62.     // Only use 10, 25, 50, 100
  63.     const dtDisplayLinesDefault 100;
  64.     const dtDisplayLines = [
  65.         'command'            => 50,
  66.         'cost'              => 50,
  67.         'devis'                => 50,
  68.         'individual'        => 50,
  69.         'installment'        => 50,
  70.         'invoice'            => 50,
  71.         'itask'                => 50,
  72.         'mission'            => 50,
  73.         'prospect'            => 50,
  74.         'store'                => 50,
  75.         'webapp_document'   => 50,
  76.     ];
  77.     public function getClientIp()
  78.     {
  79.         $request $this->requestStack->getCurrentRequest();
  80.         if ($request)
  81.         {
  82.             $clientIp $request->getClientIp();
  83.             return $clientIp;
  84.         }
  85.         return null;
  86.     }    
  87.     // Plan.io Task #3801
  88.     // Pour la 5.4 faudrait essayer d'utiliser ça partout ou on a besoin de créer un url
  89.     public function craftUrl(string $routeName$args = []): string
  90.     {
  91.         $config $this->em->getRepository(Config::class)->findOneByName(Config::URL);
  92.         $url $config->getValue();
  93.         $route $this->router->generate($routeName$args);
  94.         return $url.$route;
  95.     }
  96.     // Plan.io Task #4518
  97.     // But also impacts emails and many other things
  98.     // Get the SocietyGroup of the Object triggering an Event (Notification, Email, other...)
  99.     // This one is tricky, since it needs to take into account the Mission of the Object
  100.     // Is it shared or not ?
  101.     //    1. Not shared => Easy, take the SocietyGroup from the Mission
  102.     //        it is the same as the object's, and the object's client's
  103.     //     2. Shared => The object and the client do not have the same SocietyGroup
  104.     //        The TriggerEvents / EmailConfigs etc must be the ones from the SocietyGroup handling the Mission
  105.     //        ie. Mission.societyGroupOwner    
  106.     public function getSocietyGroup($object)
  107.     {
  108.         $error null;
  109.         $societyGroup null;
  110.         $debugMsgInfo "[".$object->displayForLog()."] ";
  111.         if (!method_exists($object"getMission"))
  112.         {
  113.             $error $debugMsgInfo."[Die.Hard] Object has no Mission ".$object->displayForLog();
  114.             $this->logTools->errorlog($error);
  115.             return null;
  116.         }
  117.         // Get the Mission from the object
  118.         // Exception => Ikea ServiceOrders may not have Missions
  119.         if ($object instanceof IkeaServiceOrder)
  120.         {
  121.             return $object->getSocietyGroup();
  122.         }
  123.         $mission $object->getMission();
  124.         if ($mission === null)
  125.         {
  126.             $error $debugMsgInfo."[Die.Hard] Mission is null for ".$object->displayForLog();
  127.             $this->logTools->errorlog($error);
  128.             return null;
  129.         }
  130.         // Get the SocietyGroup Owner from the Mission
  131.         $societyGroup $mission->getSocietyGroupOwner();
  132.         if ($societyGroup === null)
  133.         {
  134.             $error $debugMsgInfo."[Die.Hard] SocietyGroupOwner is null for Mission ".$mission->displayForLog();
  135.             $this->logTools->errorlog($error);
  136.             return null;
  137.         }
  138.         return $societyGroup;
  139.     }    
  140.     // Plan.io Task #4412
  141.     public function getDtDisplayLines($key)
  142.     {
  143.         if (array_key_exists($keyself::dtDisplayLines))
  144.         {
  145.             return self::dtDisplayLines[$key];
  146.         }
  147.         return self::dtDisplayLinesDefault;
  148.     }
  149.     //--------------------------------------------------------------------------
  150.     // Plan.io Task #4327
  151.     // We need the following methods here, so we can call them in twig
  152.     public function clientHasAccessClient(Client $client)
  153.     {
  154.         return $this->accessClientTools->clientHasAccessClient($client);
  155.     }
  156.     public function missionHasAccessClient(Mission $mission)
  157.     {
  158.         return $this->accessClientTools->missionHasAccessClient($mission);
  159.     }
  160.     public function canBeMadeVisible($objectSocietyGroup $societyGroup)
  161.     {
  162.         return $this->accessClientTools->canBeMadeVisible($object$societyGroup);
  163.     }
  164.     public function isActiveJcaf()
  165.     {
  166.         $config $this->em->getRepository(Config::class)->findOneByName(Config::JCAF_STATE);
  167.         if ($config === null)
  168.         {
  169.             return false;
  170.         }
  171.         return boolval($config->getValue());
  172.     }
  173.     //--------------------------------------------------------------------------
  174.     public function bubbleSortObjects($array$fieldToCompare)
  175.     {
  176.         $propertyAccessor PropertyAccess::createPropertyAccessor();
  177.         if (!$length count($array))
  178.         {
  179.             return $array;
  180.         }
  181.         for ($outer 0$outer $length$outer++)
  182.         {
  183.             for ($inner 0$inner $length$inner++)
  184.             {
  185.                 $outerValue $propertyAccessor->getValue($array[$outer], $fieldToCompare);
  186.                 $innerValue $propertyAccessor->getValue($array[$inner], $fieldToCompare);
  187.                 if ($outerValue $innerValue)
  188.                 {
  189.                     $tmp $array[$outer];
  190.                     $array[$outer] = $array[$inner];
  191.                     $array[$inner] = $tmp;
  192.                 }
  193.             }
  194.         }
  195.         return $array;
  196.     }
  197.     public function isNotFavorite($societyGroup$candidate)
  198.     {
  199.         return !$this->isFavorite($societyGroup$candidate);
  200.     }
  201.     public function isFavorite($societyGroup$candidate)
  202.     {
  203.         $item $this->em->getRepository(SocietyGroupFavorite::class)
  204.             ->findOneBy(array(
  205.                 'societyGroup'        =>    $societyGroup,
  206.                 'favorite'            =>    $candidate,
  207.             ));
  208.         if ($item !== null)
  209.         {
  210.             return true;
  211.         }
  212.         return false;
  213.     }
  214.     public function getFavorite($societyGroup$candidate)
  215.     {
  216.         $item $this->em->getRepository(SocietyGroupFavorite::class)
  217.             ->findOneBy(array(
  218.                 'societyGroup'        =>    $societyGroup,
  219.                 'favorite'            =>    $candidate,
  220.             ));
  221.         return $item;
  222.     }
  223.     public function copyFile($rootDir$source$destination)
  224.     {
  225.         if ($rootDir !== null)
  226.         {
  227.             // Does the path to the destination folder exists ?
  228.             // copy() requires the destination folder to exist
  229.             $do true;
  230.             if (file_exists($rootDir) === false)
  231.             {
  232.                 $do mkdir($rootDir0755true);
  233.                 if ($do === false)
  234.                 {
  235.                     // Something went wrong
  236.                     $this->logTools->errorlog("Error mkdir for path = ".$rootDir);
  237.                     // Skip to the next file
  238.                     return false;
  239.                 }
  240.             }
  241.         }
  242.         // If we are here it means that we have the destination folder
  243.         // (or that we don't care)
  244.         // Copy the actual files
  245.         $do copy($source$destination);
  246.         if ($do === false)
  247.         {
  248.             // Something went wrong
  249.             $this->logTools->errorlog("Error copy for source = ".$source." and destination = ".$destination);
  250.             // Skip to next file
  251.             return false;
  252.         }
  253.         return true;
  254.     }
  255.     public function moveFile($source$destination)
  256.     {
  257.         // If we are here it means that we have the destination folder
  258.         // (or that we don't care)
  259.         // Copy the actual files
  260.         $do rename($source$destination);
  261.         if ($do === false)
  262.         {
  263.             // Something went wrong
  264.             $this->logTools->errorlog("Error move for source = ".$source." and destination = ".$destination);
  265.             // Skip to next file
  266.             return false;
  267.         }
  268.         return true;
  269.     }
  270.     // For RHForms, the attachments are attached to the child (rhFormLeave for example)
  271.     // but need to be created and linked for the pareny ($rhFormLeave->getParent())
  272.     // So pass directly the JSON from the form to this method
  273.     public function handleAttachments($object$files null)
  274.     {
  275.         $attachments = array();
  276.         // Either fetch the files from the arguments, or from the object itself
  277.         if ($files === null$files $object->getFiles();
  278.         if ($files !== null)
  279.         {
  280.             $files json_decode($filestrue);
  281.             $attachmentRepository $this->em->getRepository(Attachment::class);
  282.             foreach ($files as $uuid)
  283.             {
  284.                 $attachment $attachmentRepository->findOneByUuid($uuid);
  285.                 if ($attachment !== null)
  286.                 {
  287.                     $object->addAttachment($attachment);
  288.                     $attachments[] = $attachment;
  289.                 }
  290.             }
  291.         }
  292.         return $attachments;
  293.     }
  294.     public function displayMultipleSocieties(SocietyGroup $societyGroup)
  295.     {
  296.         // If the society group has more than one society,
  297.         // we mult display them all
  298.         // without taking the config into account
  299.         if ($societyGroup->getSocieties()->count() > 1)
  300.         {
  301.             return true;
  302.         }
  303.         // If a single society in the group, check to see if the society module is activated
  304.         $societyModuleActivated false;
  305.         if ($this->moduleTools->isActiveByCode($societyGroupModule::MODULE_SOCIETY))
  306.         {
  307.             $societyModuleActivated true;
  308.         }
  309.         if ($societyModuleActivated === true)
  310.         {
  311.             // Display multiple societies
  312.             return true;
  313.         }
  314.         else
  315.         {
  316.             // Don't display the society notion
  317.             return false;
  318.         }
  319.     }
  320.     public function displayOneSociety(SocietyGroup $societyGroup)
  321.     {
  322.         return !$this->displayMultipleSocieties($societyGroup);
  323.     }
  324.     public function getCssFile(SocietyGroup $societyGroup)
  325.     {
  326.         if($societyGroup == null)
  327.         {
  328.             return 'variables.css';
  329.         }
  330.         else
  331.         {
  332.             // ROOT/public/theme/css/
  333.             $path $this->logTools->getCssDir();
  334.             $filename 'variables_' $societyGroup->getId() . '.css';
  335.             $file $path $filename;
  336.             if(file_exists($file))
  337.             {
  338.                 return $filename;
  339.             }
  340.             else
  341.             {
  342.                 return 'variables.css';
  343.             }
  344.         }
  345.     }
  346.     // Plan.io Task #4327
  347.     // This code needs to be in this service to be used by Twig
  348.     public function getCssFileForAccessClient(AccessClient $accessClient)
  349.     {
  350.         $accessClientRecords $accessClient->getAccessClientRecords();
  351.         if (count($accessClientRecords) < 1)
  352.         {
  353.             return 'variables.css';
  354.         }
  355.         $societyGroup $accessClientRecords[0]->getSocietyGroup();
  356.         if ($societyGroup === null)
  357.         {
  358.             return 'variables.css';
  359.         }
  360.         return $this->getCssFile($societyGroup);
  361.     }
  362.     // Plan.io Task #4455
  363.     // This code needs to be in this service to be used by Twig
  364.     public function getLogoHeaderForAccessClient(AccessClient $accessClient)
  365.     {
  366.         $logos = array();
  367.         $accessClientRecords $accessClient->getAccessClientRecords();
  368.         foreach ($accessClientRecords as $record)
  369.         {
  370.             $societyGroup $record->getSocietyGroup();
  371.             if ($societyGroup === null)
  372.             {
  373.                 continue;
  374.             }
  375.             $logo $societyGroup->getLogo();
  376.             if ($logo === null)
  377.             {
  378.                 continue;
  379.             }
  380.             $logos[] = $logo->getUrlForDisplay();
  381.         }
  382.         if (empty($logos))
  383.         {
  384.             $logos[] = 'assets/logo-rekapp.png';
  385.         }
  386.         return $logos;
  387.     }
  388.     public function getStorageInfo($societyGroup)
  389.     {
  390.         $cloudSize 0;        $cloudSizeMb 0;        $cloudSizeGb 0;        $cloudPercentage 0;
  391.         $platformSize 0;    $platformSizeMb 0;    $platformSizeGb 0;    $platformPercentage 0;
  392.         $webappSize 0;    $webappSizeMb 0;        $webappSizeGb 0;        $webappPercentage 0;
  393.         $used 0;
  394.         $usedPercentage 0;
  395.         $maxStorageSizePerAccess $this->em->getRepository(OptionConfig::class)
  396.             ->findOneBy(array(
  397.                 'code'                =>    OptionConfig::MAX_STORAGE_SIZE_FOR_ACCESS_CODE,
  398.                 'societyGroup'        =>    $societyGroup,
  399.             ));
  400.         if ($maxStorageSizePerAccess === null)
  401.         {
  402.             // This should not happen, but just in case
  403.             $maxStorageSizePerAccess $this->em->getRepository(Config::class)
  404.                 ->findOneBy(array(
  405.                     'name'                =>    Config::DEFAULT_MAX_STORAGE_SIZE_FOR_ACCESS,
  406.                 ));
  407.             if ($maxStorageSizePerAccess === null)
  408.             {
  409.                 return null;
  410.             }
  411.         }
  412.         $activeUsers $this->em->getRepository(Access::class)
  413.             ->getActiveForSocietyGroup($societyGroup);
  414.         $maxStorageSizePerAccess $maxStorageSizePerAccess->getValue();
  415.         $maxStorageSize $maxStorageSizePerAccess count($activeUsers);
  416.         $path str_replace("src/Services/CommonTools.php"""__FILE__);
  417.         $path $path "DMS/";
  418.         $cloudPath $path "Cloud/".$societyGroup->getId();
  419.         $platformPath $path "Platform/".$societyGroup->getId();
  420.         $webappPath $path "Webapp/Images/".$societyGroup->getId();
  421.         if (is_dir($cloudPath))
  422.         {
  423.             $cloudSize $this->folderSize($cloudPath) / 1024;
  424.             $cloudSizeMb $cloudSize 1024;
  425.             $cloudSizeGb $cloudSizeMb 1024;
  426.             if ($maxStorageSize == 0)
  427.                 $cloudPercentage 0;
  428.             else
  429.                 $cloudPercentage = (100 $cloudSizeMb) / $maxStorageSize;
  430.             $used += $cloudSize;
  431.             $usedPercentage += $cloudPercentage;
  432.         }
  433.         if (is_dir($platformPath))
  434.         {
  435.             $platformSize $this->folderSize($platformPath) / 1024;
  436.             $platformSizeMb $platformSize 1024;
  437.             $platformSizeGb $platformSizeMb 1024;
  438.             if ($maxStorageSize == 0)
  439.                 $platformPercentage 0;
  440.             else
  441.                 $platformPercentage = (100 $platformSizeMb) / $maxStorageSize;
  442.             $used += $platformSize;
  443.             $usedPercentage += $platformPercentage;
  444.         }
  445.         if (is_dir($webappPath))
  446.         {
  447.             $webappSize $this->folderSize($webappPath) / 1024;
  448.             $webappSizeMb $webappSize 1024;
  449.             $webappSizeGb $webappSizeMb 1024;
  450.             if ($maxStorageSize == 0)
  451.                 $webappPercentage 0;
  452.             else
  453.                 $webappPercentage = (100 $webappSizeMb) / $maxStorageSize;
  454.             $used += $webappSize;
  455.             $usedPercentage += $webappPercentage;
  456.         }
  457.         // Format numbers
  458.         $maxStorageSizePerAccess number_format($maxStorageSizePerAccess2".""");
  459.         $maxStorageSizePerAccessGb number_format($maxStorageSizePerAccess 10242".""");
  460.         $maxStorageSize number_format($maxStorageSize2".""");
  461.         $maxStorageSizeGb number_format($maxStorageSize 10242".""");
  462.         $used number_format($used2".""");
  463.         $usedMb number_format($used 10242".""");
  464.         $usedGb number_format($usedMb 10242".""");
  465.         $usedPercentage number_format($usedPercentage2".""");
  466.         $cloudSize number_format($cloudSize2".""");
  467.         $cloudSizeMb number_format($cloudSizeMb2".""");
  468.         $cloudSizeGb number_format($cloudSizeGb2".""");
  469.         $cloudPercentage number_format($cloudPercentage2".""");
  470.         $platformSize number_format($platformSize2".""");
  471.         $platformSizeMb number_format($platformSizeMb2".""");
  472.         $platformSizeGb number_format($platformSizeGb2".""");
  473.         $platformPercentage number_format($platformPercentage2".""");
  474.         $webappSize number_format($webappSize2".""");
  475.         $webappSizeMb number_format($webappSizeMb2".""");
  476.         $webappSizeGb number_format($webappSizeGb2".""");
  477.         $webappPercentage number_format($webappPercentage2".""");
  478.         $sizes = array(
  479.             'maxStorageSizePerAccess'        =>    $maxStorageSizePerAccess,
  480.             'maxStorageSizePerAccessGb'        =>    $maxStorageSizePerAccessGb,
  481.             'maxStorageSize'                =>    $maxStorageSize,
  482.             'maxStorageSizeGb'                =>    $maxStorageSizeGb,
  483.             'used'                    =>    array(
  484.                 'size'                =>    $used,
  485.                 'size_mb'            =>    $usedMb,
  486.                 'size_gb'            =>    $usedGb,
  487.                 'percentage'        =>    $usedPercentage,
  488.             ),
  489.             'data'                    =>    array(
  490.                 'cloud'                =>    array(
  491.                     'size'            =>    $cloudSize,
  492.                     'size_mb'        =>    $cloudSizeMb,
  493.                     'size_gb'        =>    $cloudSizeGb,
  494.                     'percentage'    =>    $cloudPercentage,
  495.                 ),
  496.                 'platform'            =>    array(
  497.                     'size'            =>    $platformSize,
  498.                     'size_mb'        =>    $platformSizeMb,
  499.                     'size_gb'        =>    $platformSizeGb,
  500.                     'percentage'    =>    $platformPercentage,
  501.                 ),
  502.                 'webapp'            =>    array(
  503.                     'size'            =>    $webappSize,
  504.                     'size_mb'        =>    $webappSizeMb,
  505.                     'size_gb'        =>    $webappSizeGb,
  506.                     'percentage'    =>    $webappPercentage,
  507.                 ),
  508.             ),
  509.         );
  510.         return $sizes;
  511.     }
  512.     function folderSize($dir)
  513.     {
  514.         $size 0;
  515.         foreach (glob(rtrim($dir'/').'/*'GLOB_NOSORT) as $each)
  516.         {
  517.             //$tmp = filesize($each);
  518.             $tmp stat($each)['blocks'] * 512;
  519.             //$tmp = ceil(stat($each)['size']/1024);
  520.             $size += is_file($each) ? $tmp $this->folderSize($each);
  521.         }
  522.         return $size;
  523.     }
  524.     // This method sort two array of object according to 'position' field
  525.     // (Main case if for Devis => DevisTitle and DevisProduct)
  526.     public function sortByPosition(array $firtArray, array $secondArray)
  527.     {
  528.         $elementsMerged array_merge($firtArray$secondArray);
  529.         // Sort on position
  530.         if (count($elementsMerged))
  531.         {
  532.             $iterator $elementsMerged;
  533.             uasort($elementsMerged,function ($first$second)
  534.             {
  535.                 return (int) $first->getPosition() > (int) $second->getPosition() ? : -1;
  536.             });
  537.         }
  538.         return $elementsMerged;
  539.     }
  540.     public function deleteDir($src)
  541.     {
  542.         if (is_dir($src))
  543.         {
  544.             $dir opendir($src);
  545.             while(false !== ( $file readdir($dir)) )
  546.             {
  547.                 if (( $file != '.' ) && ( $file != '..' ))
  548.                 {
  549.                     if ( is_dir($src '/' $file) )
  550.                     {
  551.                         $this->deleteDir($src '/' $file);
  552.                     }
  553.                     else
  554.                     {
  555.                         unlink($src '/' $file);
  556.                     }
  557.                 }
  558.             }
  559.             closedir($dir);
  560.             rmdir($src);
  561.         }
  562.     }
  563.     public function isSuperadmin(Access $access$societyGroup null)
  564.     {
  565.         if ($societyGroup !== null)
  566.         {
  567.             if ($societyGroup->getAdmin() !== null && $societyGroup->getAdmin()->equals($access))
  568.             {
  569.                 return true;
  570.             }
  571.             return false;
  572.         }
  573.         else
  574.         {
  575.             $groups $this->em->getRepository(SocietyGroup::class)
  576.                 ->findAll();
  577.             foreach ($groups as $societyGroup)
  578.             {
  579.                 if ($societyGroup->getAdmin() !== null && $societyGroup->getAdmin()->equals($access))
  580.                 {
  581.                     return true;
  582.                 }
  583.             }
  584.             return false;
  585.         }
  586.     }
  587.     public function checkPaySettings($societyGroup)
  588.     {
  589.         $paymentDeadline $this->em->getRepository(PaymentDeadline::class);
  590.         $missing = array();
  591.         $objects $paymentDeadline->findBySocietyGroup($societyGroup);
  592.         if (count($objects) < 1)
  593.             $missing[] = 'payment_deadline';
  594.         return $missing;
  595.     }
  596.     public function checkIndividualSettings($societyGroup)
  597.     {
  598.         $originRep $this->em->getRepository(Origin::class);
  599.         $titleRep $this->em->getRepository(Title::class);
  600.         $missing = array();
  601.         $objects $originRep->findBySocietyGroup($societyGroup);
  602.         if (count($objects) < 1)
  603.             $missing[] = 'origin';
  604.         $objects $titleRep->findBySocietyGroup($societyGroup);
  605.         if (count($objects) < 1)
  606.             $missing[] = 'title';
  607.         return $missing;
  608.     }
  609.     public function checkRfiSettings($societyGroup)
  610.     {
  611.         $typeRep $this->em->getRepository(InterventionType::class);
  612.         $satisfactionRep $this->em->getRepository(Satisfaction::class);
  613.         $missing = array();
  614.         $objects $typeRep->findBySocietyGroup($societyGroup);
  615.         if (count($objects) < 1)
  616.             $missing[] = 'intervention_type';
  617.         $objects $satisfactionRep->findBySocietyGroup($societyGroup);
  618.         if (count($objects) < 1)
  619.             $missing[] = 'satisfaction';
  620.         return $missing;
  621.     }
  622.     public function checkAnomalySettings($societyGroup)
  623.     {
  624.         $actionRep $this->em->getRepository(AnomalyAction::class);
  625.         $productRep $this->em->getRepository(AnomalyProduct::class);
  626.         $chargeRep $this->em->getRepository(AnomalyCharge::class);
  627.         $reasonRep $this->em->getRepository(AnomalyReason::class);
  628.         $stateRep $this->em->getRepository(AnomalyState::class);
  629.         $missing = array();
  630.         $objects $actionRep->findBySocietyGroup($societyGroup);
  631.         if (count($objects) < 1)
  632.             $missing[] = 'anomaly_action_label';
  633.         $objects $productRep->findBySocietyGroup($societyGroup);
  634.         if (count($objects) < 1)
  635.             $missing[] = 'anomaly_product_label';
  636.         $objects $chargeRep->findBySocietyGroup($societyGroup);
  637.         if (count($objects) < 1)
  638.             $missing[] = 'anomaly_charge_label';
  639.         $objects $reasonRep->findBySocietyGroup($societyGroup);
  640.         if (count($objects) < 1)
  641.             $missing[] = 'anomaly_reason_label';
  642.         $objects $stateRep->findBySocietyGroup($societyGroup);
  643.         if (count($objects) < 1)
  644.             $missing[] = 'anomaly_state_label';
  645.         return $missing;
  646.     }
  647.     public function checkReportSettings($societyGroup)
  648.     {
  649.         $typeRep $this->em->getRepository(ReportType::class);
  650.         $missing = array();
  651.         $objects $typeRep->findBySocietyGroup($societyGroup);
  652.         if (count($objects) < 1)
  653.             $missing[] = 'report_type';
  654.         return $missing;
  655.     }
  656.     public function missionTypeHasMissions($type)
  657.     {
  658.         $mission $this->em->getRepository(Mission::class)
  659.             ->findOneByType($type);
  660.         if ($mission !== null)
  661.         {
  662.             return true;
  663.         }
  664.         return false;
  665.     }
  666.     public function getLastChangelog()
  667.     {
  668.         $changeLogRepo $this->em->getRepository(ChangeLog::class);
  669.         $changeLog $changeLogRepo->findOneBy(
  670.             array('published' => true),
  671.             array('effectiveDate'=>'DESC'),
  672.         );
  673.         $version "";
  674.         if($changeLog !== null)
  675.         {
  676.             $version $changeLog->getVersion();
  677.         }
  678.         return $version;
  679.     }
  680.     public function isBool($value)
  681.     {
  682.         // Strict check to avoid "true", "false"
  683.         if ($value === false || $value === true)
  684.         {
  685.             return true;
  686.         }
  687.         if ($value == || $value == 1)
  688.         {
  689.             return true;
  690.         }
  691.         return false;
  692.     }
  693.     // This method will get the last position from the repository ($repositoryName)
  694.     // and update '$object' with the right position
  695.     public function handleLastPositionLabel($objectstring $repositoryNameSocietyGroup $societyGroup)
  696.     {
  697.         $repository $this->em->getRepository($repositoryName);
  698.         $objectsPosition $repository->getLastPositionObject($societyGroup);
  699.         $lastPosition 0;
  700.         if (sizeof($objectsPosition) > 0)
  701.         {
  702.             $lastPosition $objectsPosition[0]->getPosition();
  703.         }
  704.         $object->setPosition($lastPosition 1);
  705.         $this->em->persist($object);
  706.     }
  707.     public function handlePositionAfterDeleteLabel($oldPosstring $repositoryNameSocietyGroup $societyGroup)
  708.     {
  709.         $repository $this->em->getRepository($repositoryName);
  710.         $objectsPositions $repository->findBy(
  711.             array(
  712.                 'societyGroup' => $societyGroup,
  713.             ),array(
  714.                 'position' => 'ASC',
  715.             ));
  716.         foreach($objectsPositions as $obj)
  717.         {
  718.             if ($obj->getPosition() > $oldPos)
  719.             {
  720.                 $obj->setPosition($obj->getPosition() - 1);
  721.                 $this->em->persist($obj);
  722.             }
  723.         }
  724.     }
  725.     public function getBannerMaintenance()
  726.     {
  727.         $session $this->requestStack->getSession();
  728.         // check session
  729.         $banner $session->get('_banner_maintenance');
  730.         // if '_banner_maintenance' is not null return void to don't show the banner
  731.         if ($banner == 1)
  732.         {
  733.              return null;
  734.         }
  735.         return $this->getBannerMaintenanceConfig();
  736.     }
  737.     public function getBannerMaintenanceConfig()
  738.     {
  739.         $repoConfig $this->em->getRepository(Config::class);
  740.         $configBanner $repoConfig->findOneByName(Config::MAINTENANCE_INFO_BANNER);
  741.         if ($configBanner === null)
  742.         {
  743.              return null;
  744.         }
  745.         if ($configBanner->getValue() == 0)
  746.         {
  747.              return null;
  748.         }
  749.         return $configBanner;
  750.     }
  751.     /**
  752.      * Set maintenance mode on the whole platforme :
  753.      * - No access for non super admin
  754.      * - Display maintenance banner
  755.      * - Stop ikea import
  756.      *
  757.      *
  758.      *
  759.      * @param  string $mode = up | down
  760.      * @return array
  761.      */
  762.     public function setMaintenanceMode(string $mode): array
  763.     {
  764.         $maintenance $this->em->getRepository(Config::class)->findOneByName(Config::MAINTENANCE);
  765.         if ($maintenance === null)
  766.         {
  767.             $maintenance = new Config();
  768.             $maintenance->setName(Config::MAINTENANCE);
  769.             $this->em->persist($maintenance);
  770.         }
  771.         // Get Config Ikea import in progress
  772.         $configIkeaImportInProgress $this->em->getRepository(Config::class)->findOneByName(Config::IKEA_IMPORT_IN_PROGRESS);
  773.         $lockFile dirname(__FILE__3). "/icod.lock";
  774.         // Try to put on the banner and disable ikea import
  775.         if($mode == 'up')
  776.         {
  777.             if ($configIkeaImportInProgress === null)
  778.             {
  779.                 return array('status' => 'error''msg' => 'Ikea Config not found');
  780.             }
  781.             if ($configIkeaImportInProgress !== null && $configIkeaImportInProgress->getValue())
  782.             {
  783.                 // Do not allow the banner if Ikea import is in progress
  784.                 return array('status' => 'error''msg' => 'Ikea Import in Progress');
  785.             }
  786.             // Enable Banner
  787.             $maintenance->setValue(1);
  788.             // Disable Ikea Import (ikea import is in progress = no more action)
  789.             $configIkeaImportInProgress->setValue(1);
  790.             // Create file icod.lock to stop loadBalancer replication in Prod
  791.             $file fopen($lockFile'w');
  792.             fclose($file);
  793.         }
  794.         else if( $mode 'down' // put down maintenance mode
  795.         {
  796.             // Disable Banner
  797.             $maintenance->setValue(0);
  798.             // Enable Ikea Import (ikea import is not in progress = ne import can be started)
  799.             $configIkeaImportInProgress->setValue(0);
  800.             // Remove file icod.lock to restart loadBalancer replication in Prod
  801.             if(file_exists($lockFile))
  802.                 unlink($lockFile);
  803.         }
  804.         return array('status' => 'success''msg' => '');
  805.     }
  806.     // Input : Array of objects
  807.     // Output : String "(idObject1, idObject2, ...)" or "(0)", if empty array
  808.     public function objectsToString($objects)
  809.     {
  810.         if (!is_array($objects))
  811.         {
  812.             return "(0)";
  813.         }
  814.         $in "";
  815.         foreach ($objects as $object)
  816.         {
  817.             if (!method_exists($object'getId'))
  818.             {
  819.                 continue;
  820.             }
  821.             $in .= $object->getId();
  822.             $in .= ",";
  823.         }
  824.         if ($in != "")
  825.         {
  826.             $in substr($in0, -1);
  827.             $in "(".$in.")";
  828.         }
  829.         else
  830.         {
  831.             $in "(0)";
  832.         }
  833.         return $in;
  834.     }
  835.     // Input : Array of objects
  836.     // Output : String "(id1, id2, ...)" or "(0)", if empty array
  837.     public function arrayToString($ids)
  838.     {
  839.         if (!is_array($ids) || empty($ids))
  840.         {
  841.             return "(0)";
  842.         }
  843.         $in "";
  844.         foreach ($ids as $id)
  845.         {
  846.             $in .= $id;
  847.             $in .= ",";
  848.         }
  849.         if ($in != "")
  850.         {
  851.             $in substr($in0, -1);
  852.             $in "(".$in.")";
  853.         }
  854.         else
  855.         {
  856.             $in "(0)";
  857.         }
  858.         return $in;
  859.     }
  860.     // Input : String link of image
  861.     // Output : String base64 encoded image
  862.     // Updated by : Plan.io #4132
  863.     public function imageToBase64(string $img): string
  864.     {
  865.         $type pathinfo($imgPATHINFO_EXTENSION);
  866.         $data file_get_contents($img);
  867.         return 'data:image/' $type ';base64,' base64_encode($data);
  868.     }
  869.     // Input : String link of image
  870.     // Output : String base64 encoded image
  871.     // Updated by : Plan.io #4132
  872.     public function imageToBase64FromRoot(string $img): string
  873.     {
  874.         $basePath $this->logTools->getRootDir() . "/";
  875.         $img $basePath $img;
  876.         return $this->imageToBase64($img);
  877.     }
  878.     // Input : String link of image
  879.     // Output : String base64 encoded image
  880.     // Updated by : Plan.io #4132
  881.     public function imageToBase64FromPublic(string $img): string
  882.     {
  883.         $basePath $this->logTools->getPublicDir();
  884.         $img $basePath $img;
  885.         return $this->imageToBase64($img);
  886.     }
  887.     // Task plan.io #3690
  888.     public function getNumberPlanningResource(SocietyGroup $societyGroup)
  889.     {
  890.         $countPlanningResourceResult $this->em
  891.             ->getRepository(PlanningResource::class)
  892.             ->countPlanningResource($societyGroup);
  893.         return $countPlanningResourceResult;
  894.     }
  895.     // Plan.io Task #3664
  896.     public function getIkeaTemplateProduct(IkeaTemplate $ikeaTemplateTemplate $productTemplateIkeaProduct $ikeaProduct)
  897.     {
  898.         $object =  $this->em->getRepository(IkeaTemplateProduct::class)
  899.             ->findOneBy(array(
  900.                 "ikeaTemplate"         => $ikeaTemplate,
  901.                 "ikeaProduct"        => $ikeaProduct,
  902.                 "platformTemplate"    => $productTemplate,
  903.             ));
  904.         return $object;
  905.     }
  906.     // Plan.io Task #4561
  907.     public function ikeaTemplateProductExists(Product $productIkeaProduct $ikeaProduct)
  908.     {
  909.         $object =  $this->em->getRepository(IkeaTemplateProduct::class)
  910.             ->findOneBy(array(                
  911.                 "ikeaProduct"        => $ikeaProduct,
  912.                 "platformProduct"    => $product,
  913.             ));
  914.         return $object;
  915.     }
  916. }