vendor/memo_development/contao-foundation-bundle/src/Service/ToolboxService.php line 133

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. /**
  3.  * @package   Memo\MemoFoundationBundle
  4.  * @author    Media Motion AG
  5.  * @license   LGPL-3.0+
  6.  * @copyright Media Motion AG
  7.  */
  8. namespace Memo\FoundationBundle\Service;
  9. use Contao\CoreBundle\DataContainer\PaletteManipulator;
  10. use Contao\CoreBundle\Routing\ResponseContext\HtmlHeadBag\HtmlHeadBag;
  11. use Contao\CoreBundle\Routing\ResponseContext\JsonLd\JsonLdManager;
  12. use Contao\CoreBundle\Routing\ResponseContext\ResponseContext;
  13. use Spatie\SchemaOrg\Graph;
  14. use Spatie\SchemaOrg\JobPosting;
  15. use Spatie\SchemaOrg\Organization;
  16. use Spatie\SchemaOrg\Place;
  17. use Spatie\SchemaOrg\PostalAddress;
  18. use Contao\FilesModel;
  19. use Contao\System;
  20. use Ivory\GoogleMap\Service\Geocoder\GeocoderService;
  21. use Http\Adapter\Guzzle6\Client;
  22. use Http\Message\MessageFactory\GuzzleMessageFactory;
  23. class ToolboxService
  24. {
  25.     /**
  26.      * On Save Callback for coordinates
  27.      * @param DataContainer $dc
  28.      */
  29.     public function setCoordinates(\DataContainer $dc)
  30.     {
  31.         $strTable $dc->table;
  32.         if($strTable == ''){
  33.             return;
  34.         }
  35.         \Controller::loadDataContainer($strTable);
  36.         $strModel $GLOBALS['TL_MODELS'][$strTable];
  37.         if($strModel == ''){
  38.             return;
  39.         }
  40.         $objItem $strModel::findOneById($dc->activeRecord->id);
  41.         if(($dc->activeRecord->lat == '' || $dc->activeRecord->long == '') && $dc->activeRecord->address != ''){
  42.             $arrCoordinates false;
  43.             if(class_exists('\delahaye\GeoCode')){
  44.                 $strKey \Config::get('dlh_googlemaps_apikey');
  45.                 $strCoordinates \delahaye\GeoCode::getCoordinates($dc->activeRecord->address $dc->activeRecord->object_location'ch''de'$strKey);
  46.                 $arrCoordinates explode(','$strCoordinates);
  47.             } elseif(class_exists('\Spatie\Geocoder\Geocoder')){
  48.                 $strKey \Config::get('googlemaps_apiKey') ?? \Config::get('dlh_googlemaps_apikey');
  49.                 $client = new \GuzzleHttp\Client();
  50.                 $geocoder = new \Spatie\Geocoder\Geocoder($client);
  51.                 $geocoder->setApiKey($strKey);
  52.                 $geocoder->setCountry('CH');
  53.                 $response $geocoder->getCoordinatesForAddress($dc->activeRecord->address $dc->activeRecord->object_location);
  54.                 $arrCoordinates = array($response['lat'], $response['lng']);
  55.             }
  56.             if ($arrCoordinates && is_array($arrCoordinates)){
  57.                 if(!is_null($arrCoordinates[0])){
  58.                     $objItem->lat $arrCoordinates[0];
  59.                 }
  60.                 if(!is_null($arrCoordinates[1])){
  61.                     $objItem->long $arrCoordinates[1];
  62.                 }
  63.                 $objItem->save();
  64.             }
  65.         }
  66.     }
  67.     /**
  68.      * Format Date for DCA-View
  69.      * @param $value
  70.      * @return false|int
  71.      */
  72.     public function loadDate($value)
  73.     {
  74.         return strtotime(date('Y-m-d', (int)$value) . ' 00:00:00');
  75.     }
  76.     public static function setJsonLd($JsonLdItem){
  77.         // Get Response Context and check it
  78.         $objResponseContext \System::getContainer()->get('contao.routing.response_context_accessor')->getResponseContext();
  79.         if (!$objResponseContext || !$objResponseContext->has(JsonLdManager::class)) {
  80.             return;
  81.         }
  82.         // Get JsonLdManager
  83.         $objJsonLdManager $objResponseContext->get(JsonLdManager::class);
  84.         // Check Input Parameter and transform (auto) if needed
  85.         if(is_object($JsonLdItem)){
  86.             $objJsonLdItem $JsonLdItem;
  87.         } elseif(is_array($JsonLdItem)){
  88.             $objJsonLdItem $objJsonLdManager->createSchemaOrgTypeFromArray($JsonLdItem);
  89.         }
  90.         // Add the Schema to the Graph (Response)
  91.         $objJsonLdManager->getGraphForSchema(JsonLdManager::SCHEMA_ORG)->set($objJsonLdItemGraph::IDENTIFIER_DEFAULT);
  92.     }
  93.     /**
  94.      * Toggle alias and seo-fields, if no detail-page is set on the parent-archive
  95.      * @param $strTablename
  96.      */
  97.     public static function toggleDetailFieldsFromPalette($strTablename)
  98.     {
  99.         $arrDetailPageIds = array();
  100.         // Get the archive details
  101.         if(array_key_exists('ptable'$GLOBALS['TL_DCA'][$strTablename]['config'])){
  102.             $strArchiveTable $GLOBALS['TL_DCA'][$strTablename]['config']['ptable'];
  103.             $strArchiveModel $GLOBALS['TL_MODELS'][$strArchiveTable];
  104.             // Try to get the jumpTo page ids
  105.             $arrDetailPageIds $strArchiveModel::getDetailPages(false);
  106.         }
  107.         // If no ids were found, there are now detailpages to be expected - so we can cleanup the palette
  108.         if(count($arrDetailPageIds) == 0){
  109.             $objLanguageService \System::getContainer()->get('memo.foundation.language');
  110.             $arrLanguages $objLanguageService->getAllLanguages(true);
  111.             foreach($arrLanguages as $strLanguage)
  112.             {
  113.                 $strPostfix $objLanguageService->getLanguagePostfix($strLanguage);
  114.                 if($strPostfix == ''){
  115.                     $arrFieldsToRemove = array(
  116.                         array('general_legend''alias'),
  117.                         array('meta_legend''seo_title'),
  118.                         array('meta_legend''seo_description'),
  119.                         array('meta_legend''serpPreview'),
  120.                     );
  121.                 } else {
  122.                     $arrFieldsToRemove = array(
  123.                         array('translation' $strPostfix'alias'$strPostfix),
  124.                         array('translation' $strPostfix'seo_title'$strPostfix),
  125.                         array('translation' $strPostfix'seo_description'$strPostfix),
  126.                     );
  127.                 }
  128.                 foreach($GLOBALS['TL_DCA'][$strTablename]['palettes'] as $strKey => $strPalette){
  129.                     if ($strKey == '__selector__') {
  130.                         continue;
  131.                     }
  132.                     foreach($arrFieldsToRemove as $arrFields)
  133.                     {
  134.                         PaletteManipulator::create()
  135.                             ->removeField($arrFields[1], $arrFields[0])
  136.                             ->applyToPalette($strKey$strTablename)
  137.                         ;
  138.                     }
  139.                 }
  140.             }
  141.         }
  142.     }
  143.     public static function collectionToArray($objCollection$bolResetKeys=false$strField='title')
  144.     {
  145.         $arrCollection = array();
  146.         if($objCollection != null)
  147.         {
  148.             foreach($objCollection as $objItem)
  149.             {
  150.                 if($bolResetKeys){
  151.                     $arrCollection[] = $objItem->$strField;
  152.                 } else {
  153.                     $arrCollection[$objItem->id] = $objItem->$strField;
  154.                 }
  155.             }
  156.         }
  157.         return $arrCollection;
  158.     }
  159.     public static function convertOrderString($strOrderBy$strTable)
  160.     {
  161.         $strSQL '';
  162.         switch($strOrderBy)
  163.         {
  164.             case 'order_title':
  165.                 $strSQL "$strTable.title";
  166.                 break;
  167.             case 'order_title_desc':
  168.                 $strSQL "$strTable.title DESC";
  169.                 break;
  170.             case 'order_sorting':
  171.                 $strSQL "$strTable.sorting";
  172.                 break;
  173.             case 'order_sorting_desc':
  174.                 $strSQL "$strTable.sorting DESC";
  175.                 break;
  176.             case 'order_date':
  177.                 $strSQL "$strTable.date";
  178.                 break;
  179.             case 'order_date_desc':
  180.                 $strSQL "$strTable.date DESC";
  181.                 break;
  182.         }
  183.         return $strSQL;
  184.     }
  185.     /**
  186.      * Set page header meta by associative array.
  187.      * @param array $arr
  188.      * @return void
  189.      */
  190.     public static function setPageHeaderMeta(array $arr): void
  191.     {
  192.         if (System::getContainer()->has('contao.routing.response_context_accessor')) {
  193.             $responseContext System::getContainer()->get('contao.routing.response_context_accessor')->getResponseContext();
  194.             $htmlHeadBag $responseContext->get(HtmlHeadBag::class);
  195.             if ($responseContext && $responseContext->has(HtmlHeadBag::class)) {
  196.                 foreach ($arr as $tag => $value) {
  197.                     switch ($tag) {
  198.                         case 'robots':
  199.                             $htmlHeadBag->setMetaRobots($value);
  200.                             break;
  201.                         case 'title':
  202.                             $htmlHeadBag->setTitle($value);
  203.                             break;
  204.                         case 'description':
  205.                             $htmlHeadBag->setMetaDescription($value);
  206.                             break;
  207.                         case 'canonical':
  208.                             $htmlHeadBag->setCanonicalUri($value);
  209.                             break;
  210.                     }
  211.                 }
  212.             }
  213.         } else {
  214.             global $objPage;
  215.             foreach ($arr as $tag => $value) {
  216.                 $objPage->{$tag} = $value;
  217.             }
  218.         }
  219.     }
  220.     public static function generateMarker(\DataContainer $dc)
  221.     {
  222.         // Get & Check Table
  223.         $strTable $dc->table;
  224.         if($strTable == ''){
  225.             \System::log('No table given for marker generation'__METHOD__TL_ERROR);
  226.             return;
  227.         }
  228.         // Get and check Class/Model
  229.         \Controller::loadDataContainer($strTable);
  230.         $strModel $GLOBALS['TL_MODELS'][$strTable];
  231.         if($strModel == '' || !class_exists($strModel)){
  232.             \System::log('No model found for table ' $strTable__METHOD__TL_ERROR);
  233.             return;
  234.         }
  235.         // Get Item
  236.         $objItem $strModel::findOneById($dc->activeRecord->id);
  237.         if(!$objItem){
  238.             \System::log('No item found for table ' $strTable ' with id ' $dc->activeRecord->id__METHOD__TL_ERROR);
  239.             return;
  240.         }
  241.         // Get Parent / Archive
  242.         $objArchive $objItem->getRelated('pid');
  243.         if(!$objArchive){
  244.             \System::log('No archive found for table ' $strTable ' with id ' $dc->activeRecord->id__METHOD__TL_ERROR);
  245.             return;
  246.         }
  247.         // Check data
  248.         if(!$objArchive->addMarker || !$objArchive->markerSRC || $objArchive->markerSRC == ''){
  249.             \System::log('No marker found for table ' $strTable ' with id ' $dc->activeRecord->id__METHOD__TL_ERROR);
  250.             return;
  251.         }
  252.         if(!$objItem->singleSRC || $objItem->singleSRC == ''){
  253.             \System::log('No image found for item: table ' $strTable ' with id ' $dc->activeRecord->id__METHOD__TL_ERROR);
  254.             return;
  255.         }
  256.         // Get Item Image
  257.         $objItemImage \FilesModel::findByUuid($objItem->singleSRC);
  258.         // Check File
  259.         if(!$objItemImage || file_exists($objItemImage->path) === false){
  260.             \System::log('Defined image not found for item: table ' $strTable ' with id ' $dc->activeRecord->id__METHOD__TL_ERROR);
  261.             return;
  262.         }
  263.         // Get Template Image
  264.         $objTemplateImage \FilesModel::findByUuid($objArchive->markerSRC);
  265.         // Check File
  266.         if(!$objTemplateImage || file_exists($objTemplateImage->path) === false){
  267.             \System::log('Defined marker background image not found for item: table ' $strTable ' with id ' $dc->activeRecord->id__METHOD__TL_ERROR);
  268.             return;
  269.         }
  270.         // Check the destination
  271.         $objMarkerFolder FilesModel::findByUuid($objArchive->markerFolder);
  272.         if(!$objMarkerFolder || file_exists($objMarkerFolder->path) === false){
  273.             \System::log('Defined marker folder not found'__METHOD__TL_ERROR);
  274.             return;
  275.         }
  276.         // Create Base from Original Image
  277.         switch($objItemImage->extension){
  278.             case 'jpeg':
  279.             case 'jpg':
  280.                 $objItemImageSource imagecreatefromjpeg($objItemImage->path);
  281.                 break;
  282.             case 'png':
  283.                 $objItemImageSource imagecreatefrompng($objItemImage->path);
  284.                 break;
  285.             case 'gif':
  286.                 $objItemImageSource imagecreatefromgif($objItemImage->path);
  287.                 break;
  288.             default:
  289.                 \System::log('Image type not supported for marker generation: ' $objItemImage->extension__METHOD__TL_ERROR);
  290.                 return;
  291.         }
  292.         // Define  filename, path etc.
  293.         if($objItem->alias != ''){
  294.             $strFilename 'marker-' $objItem->alias '-'.$objItem->id.'.png';
  295.         } else {
  296.             $strFilename 'marker-' $objItem->id.'.png';
  297.         }
  298.         $strFilename $objItem->alias '-'.$objItem->id.'.png';
  299.         $strFilepath $objMarkerFolder->path '/' $strFilename;
  300.         // Get Image Size
  301.         list($intSourceWidth$intSourceHeight) = getimagesize($objItemImage->path);
  302.         // Load Marker Template
  303.         switch($objTemplateImage->extension){
  304.             case 'jpeg':
  305.             case 'jpg':
  306.                 $objMarker imagecreatefromjpeg($objTemplateImage->path);
  307.                 break;
  308.             case 'png':
  309.                 $objMarker imagecreatefrompng($objTemplateImage->path);
  310.                 break;
  311.             case 'gif':
  312.                 $objMarker imagecreatefromgif($objTemplateImage->path);
  313.                 break;
  314.             default:
  315.                 \System::log('Image type not supported for marker generation: ' $objTemplateImage->extension__METHOD__TL_ERROR);
  316.                 return;
  317.         }
  318.         imagesavealpha($objMarkertrue);
  319.         // Get Marker Sizes
  320.         $intMarkerWidth imagesx$objMarker );
  321.         $intMarkerHeight imagesy$objMarker );
  322.         // Create new Image and crop on Item Image
  323.         $objMarkerImage imagecreatetruecolor($intMarkerWidth,$intMarkerHeight);
  324.         imagealphablending$objMarkerImagefalse );
  325.         imagecopyresampled$objMarkerImage$objItemImageSource0000$intMarkerWidth $objArchive->markerWidthTrim$intMarkerHeight $objArchive->markerHeightTrim$intSourceWidth$intSourceHeight);
  326.         // Merge Item Image into Marker Image with offset (for border)
  327.         imagecopyresampled$objMarker$objMarkerImage $objArchive->markerOffsetX$objArchive->markerOffsetY00$intMarkerWidth $objArchive->markerWidthTrim$intMarkerHeight $objArchive->markerHeightTrim$intMarkerWidth $objArchive->markerWidthTrim$intMarkerHeight $objArchive->markerHeightTrim);
  328.         // Write Marker to Folder
  329.         imagepng$objMarker,$strFilepath );
  330.         if(!file_exists($strFilepath)){
  331.             \System::log('Marker could not be created'__METHOD__TL_ERROR);
  332.             return;
  333.         }
  334.         \Dbafs::addResource($strFilepath);
  335.         // Get Marker Object
  336.         $objMarkerFile \FilesModel::findByPath($strFilepath);
  337.         // Check Marker Object
  338.         if(!$objMarkerFile){
  339.             \System::log('Marker could not be added to database'__METHOD__TL_ERROR);
  340.             return;
  341.         }
  342.         // Update Item
  343.         $objItem->markerSRC $objMarkerFile->uuid;
  344.         $objItem->save();
  345.     }
  346. }