vendor/numero2/contao-opengraph3/src/Resources/contao/classes/OpenGraph.php line 304

Open in your IDE?
  1. <?php
  2. /**
  3.  * Contao Open Source CMS
  4.  *
  5.  * Copyright (c) 2005-2022 Leo Feyer
  6.  *
  7.  * @package   Opengraph3
  8.  * @author    Benny Born <benny.born@numero2.de>
  9.  * @author    Michael Bösherz <michael.boesherz@numero2.de>
  10.  * @license   LGPL
  11.  * @copyright 2022 numero2 - Agentur für digitales Marketing GbR
  12.  */
  13. namespace numero2\OpenGraph3;
  14. use Contao\Config;
  15. use Contao\ContentElement;
  16. use Contao\Controller;
  17. use Contao\Environment;
  18. use Contao\File;
  19. use Contao\FilesModel;
  20. use Contao\Frontend;
  21. use Contao\ModuleModel;
  22. use Contao\PageModel;
  23. use Contao\StringUtil;
  24. use Contao\System;
  25. class OpenGraph3 extends Frontend {
  26.     /**
  27.      * Add OpenGraph tags to the current page
  28.      *
  29.      * @param Model $ref
  30.      */
  31.     public static function addTagsToPage$ref=null ): void {
  32.         Controller::loadDataContainer('opengraph_fields');
  33.         System::loadLanguageFile('opengraph_fields');
  34.         global $objPage;
  35.         $objRef = !$ref $objPage $ref;
  36.         $objRootPage = ($objRef instanceof PageModel) ? PageModel::findById($objPage->rootId) : null;
  37.         self::parseAdditionalProperties$objRef );
  38.         self::parseAdditionalProperties$objRootPage );
  39.         // add og tags
  40.         if( !empty($GLOBALS['TL_DCA']['opengraph_fields']['fields']) ) {
  41.             foreach( $GLOBALS['TL_DCA']['opengraph_fields']['fields'] as $fieldName => $field ) {
  42.                 // add tag if missing
  43.                 if( (($objRef && !empty($objRef->{$fieldName})) || ($objRootPage && !empty($objRootPage->{$fieldName}))) && !self::checkTag($field['label'][0]) ) {
  44.                     $tag $field['label'][0];
  45.                     $value null;
  46.                     $value = !empty($objRef->{$fieldName}) ? $objRef->{$fieldName} : $objRootPage->{$fieldName};
  47.                     $resized null;
  48.                     // get value based on inputType
  49.                     switch( $field['inputType'] ) {
  50.                         case 'textarea':
  51.                         case 'select':
  52.                         case 'text':
  53.                             switch( $fieldName ) {
  54.                                 case 'og_country_name':
  55.                                 case 'og_business_contact_data_country_name':
  56.                                     $arrCountries = [];
  57.                                     $arrCountries System::getCountries();
  58.                                     $value $arrCountries[$value];
  59.                                 break;
  60.                             }
  61.                             if( !empty($field['eval']['rgxp']) ) {
  62.                                 switch( $field['eval']['rgxp'] ) {
  63.                                     case 'datim':
  64.                                         $date null;
  65.                                         $date = \DateTime::createFromFormatConfig::get('datimFormat'), $value );
  66.                                         $value $date->format('Y-m-d\TH:i:s');
  67.                                     break;
  68.                                 }
  69.                             }
  70.                         break;
  71.                         case 'fileTree':
  72.                             $objFile null;
  73.                             $objFile FilesModel::findByUuid$value );
  74.                             if( $objFile ) {
  75.                                 $value Environment::get('base') . $objFile->path;
  76.                                 $size Config::get($fieldName.'_size');
  77.                                 if( $size ) {
  78.                                     $oFile = new File($objFile->path);
  79.                                     $size StringUtil::deserialize($size);
  80.                                     if( is_numeric($size) ){
  81.                                         $size = [00, (int) $size];
  82.                                     } else if( !is_array($size) ) {
  83.                                         $size = [];
  84.                                     }
  85.                                     $size += [00'crop'];
  86.                                     if( $oFile && $oFile->exists() && $oFile->isGdImage ) {
  87.                                         try {
  88.                                             $resized System::getContainer()->get('contao.image.image_factory')->create(TL_ROOT '/' $objFile->path$size);
  89.                                             $src $resized->getUrl(TL_ROOT);
  90.                                             if( $src !== $objFile->path ) {
  91.                                                 $value Environment::get('base') . $src;
  92.                                             }
  93.                                         } catch( \Exception $e ) {
  94.                                         }
  95.                                     }
  96.                                 }
  97.                             } else {
  98.                                 continue 2;
  99.                             }
  100.                         break;
  101.                         case 'openGraphProperties':
  102.                             continue 2;
  103.                         break;
  104.                         default:
  105.                             throw new \Exception("Unhandled field type ".$field['inputType']);
  106.                         break;
  107.                     }
  108.                     // add og:image:secure_url and image size tags if applicable
  109.                     if( $tag === 'og:image' && $resized ) {
  110.                         $resizedSize $resized->getDimensions()->getSize();
  111.                         self::addTag('og:image:width'$resizedSize->getWidth());
  112.                         self::addTag('og:image:height'$resizedSize->getHeight());
  113.                         if ( strpos($value,'https:') !== false ) {
  114.                             self::addTag('og:image:secure_url'$value);
  115.                         }
  116.                     }
  117.                     self::addTag($tag$value);
  118.                 }
  119.             }
  120.             // og:locale
  121.             if( !self::checkTag('og:locale') ) {
  122.                 $value = ($objRef && isset($objRef->og_locale) && $objRef->og_locale) ? $objRef->og_locale : (($objRootPage && isset($objRootPage->og_locale) && $objRootPage->og_locale) ? $objRootPage->og_locale null);
  123.                 // set default locale based on the page´s language
  124.                 if( !$value ) {
  125.                     switch( $objPage->language ) {
  126.                         case 'en' :
  127.                             $value 'en_US';
  128.                             break;
  129.                         default :
  130.                             $value sprintf("%s_%s",$objPage->language,strtoupper($objPage->language));
  131.                             break;
  132.                     }
  133.                 }
  134.                 self::addTag'og:locale'$value );
  135.             }
  136.             // og:url added automatically
  137.             if( !self::checkTag('og:url') ) {
  138.                 self::addTag'og:url'Environment::get('url') . Environment::get('requestUri') );
  139.             }
  140.         }
  141.     }
  142.     /**
  143.      * Appends a property to the given object
  144.      *
  145.      * @param string $prop
  146.      * @param string $value
  147.      * @param Model $objRef
  148.      */
  149.     public static function addProperty$prop$value$objRef ): void {
  150.         $aProperties = [];
  151.         $aProperties $objRef->og_properties StringUtil::deserialize($objRef->og_properties) : [];
  152.         $aProperties[] = [$prop$value];
  153.         $objRef->og_properties serialize($aProperties);
  154.     }
  155.     /**
  156.      * Appends OpenGraph data for the given module
  157.      *
  158.      * @param Model $objRow
  159.      * @param String $strBuffer
  160.      * @param Module $objModule
  161.      *
  162.      * @return String
  163.      */
  164.     public function appendTagsByModule$objRow$strBuffer$objModule ): string {
  165.         $moduleClass null;
  166.         $moduleClass get_class($objModule);
  167.         // find and import a matching module to parse the OpenGraph data from
  168.         foreach( $GLOBALS['TL_OG_MODULES'] as $module ) {
  169.             if( $moduleClass === "Contao\ModuleModel" && $objModule->type === $module[0] || $moduleClass === $module[1] ) {
  170.                 $this->import($module[2]);
  171.                 $this->{$module[2]}->addModuleData($objModule);
  172.             }
  173.         }
  174.         return $strBuffer?:'';
  175.     }
  176.     /**
  177.      * Checks if the given Content Element is a module and tries to use it
  178.      * for OpenGraph data
  179.      *
  180.      * @param Model $objRow
  181.      * @param String $strBuffer
  182.      * @param Contao\ContentElement $objElement
  183.      *
  184.      * @return String
  185.      */
  186.     public function findCompatibleModules$objRow$strBuffer$objElement ): string {
  187.         if( get_class($objElement) === "Contao\ContentModule" ) {
  188.             $objModule null;
  189.             $objModule ModuleModel::findById($objElement->module);
  190.             if( $objModule ) {
  191.                 self::appendTagsByModule(null$strBuffer$objModule);
  192.             }
  193.         }
  194.         return $strBuffer?:'';
  195.     }
  196.     /**
  197.     * Adds the additional og_properties as individual attributes
  198.     *
  199.     * @param Model $ref
  200.     */
  201.     private static function parseAdditionalProperties$ref ): void {
  202.         if( !empty($ref->og_properties) ) {
  203.             $props null;
  204.             $props StringUtil::deserialize($ref->og_properties);
  205.             if( !empty($props) ) {
  206.                 foreach( $props as $p ) {
  207.                     if( !isset($ref->{$p[0]}) || empty($ref->{$p[0]}) ) {
  208.                         $ref->{$p[0]} = $p[1];
  209.                     }
  210.                 }
  211.             }
  212.         }
  213.     }
  214.     /**
  215.     * Adds a specific OpenGraph tag to the head
  216.     *
  217.     * @param String $tagName
  218.     * @param String $tagValue
  219.     *
  220.     * @return bool
  221.     */
  222.     private static function addTag$tagName=null$tagValue=null ): bool {
  223.         if( empty($tagName) || empty($tagValue) ) {
  224.             return false;
  225.         }
  226.         $attribute 'property';
  227.         if( strpos($tagName'twitter') === ) {
  228.             $attribute 'name';
  229.         }
  230.         $GLOBALS['TL_HEAD'][] = sprintf(
  231.             '<meta %s="%s" content="%s" />'
  232.         ,   $attribute
  233.         ,   $tagName
  234.         ,   htmlspecialcharsself::replaceInsertTags($tagValue) )
  235.         );
  236.         return true;
  237.     }
  238.     /**
  239.      * Checks if a specific OpenGraph tag already exists
  240.      *
  241.      * @param String $tagName
  242.      * @param String $tagValue
  243.      *
  244.      * @return bool
  245.      */
  246.     private static function checkTag$tagName=null ): bool {
  247.         if( empty($tagName) ) {
  248.             return false;
  249.         }
  250.         if( !empty($GLOBALS['TL_HEAD']) && is_array($GLOBALS['TL_HEAD']) ) {
  251.             foreach( $GLOBALS['TL_HEAD'] as $i => $v ) {
  252.                 if( strpos($v$tagName) !== FALSE ) {
  253.                     return true;
  254.                 }
  255.             }
  256.         }
  257.         return false;
  258.     }
  259. }