src/Rhyme/WMassArtsHub/Helper/EventHelper.php line 362

Open in your IDE?
  1. <?php
  2. /**
  3.  * Copyright (C) 2019 Rhyme Digital, LLC.
  4.  *
  5.  * @link       https://rhyme.digital
  6.  * @license    http://www.gnu.org/licenses/lgpl-3.0.html LGPL
  7.  */
  8. namespace Rhyme\WMassArtsHub\Helper;
  9. use Contao\Date;
  10. use Contao\Config;
  11. use Contao\Input;
  12. use Contao\File;
  13. use Contao\Dbafs;
  14. use Contao\System;
  15. use Contao\Controller;
  16. use Contao\CalendarModel;
  17. use Contao\CalendarEventsModel;
  18. use Contao\PageModel;
  19. use Contao\ModuleModel;
  20. use Contao\ArticleModel;
  21. use Contao\FilesModel;
  22. use Contao\StringUtil;
  23. use Contao\Environment;
  24. use Contao\Template;
  25. use Haste\DateTime\DateTime;
  26. use Rhyme\WMassArtsHub\Model\Event;
  27. use Rhyme\WMassArtsHub\Model\Approval;
  28. use numero2\OpenGraph3\OpenGraph3;
  29. use Rhyme\WMassArtsHub\Model\Profile\Item as WMassArtsHub_ProfileItemModel;
  30. /**
  31.  * Class EventHelper
  32.  * @package Rhyme\Noho\Helper
  33.  */
  34. class EventHelper extends Controller
  35. {
  36.     /**
  37.      * URL cache array
  38.      * @var array
  39.      */
  40.     private static $arrUrlCache = array();
  41.     /**
  42.      * Default event image
  43.      * @var string
  44.      */
  45.     protected static $placeholderEventImagePath 'files/noho/images/default_placeholders/businessBg.jpg';
  46.     /**
  47.      * Adds an approval entry
  48.      *
  49.      * @param CalendarEventsModel       $objEvent
  50.      */
  51.     public static function createApprovalForEvent($objEvent) {
  52.         if(null !== $objEvent) {
  53.             //Check for existing one
  54.             $t CalendarEventsModel::getTable();
  55.             $objCheck Approval::findByRowIdAndFromTable($objEvent->id$t);
  56.             if (null === $objCheck) {
  57.                 $time time();
  58.                 $objApproval = new Approval();
  59.                 $objApproval->fromTable CalendarEventsModel::getTable();
  60.                 $objApproval->rowId $objEvent->id;
  61.                 $objApproval->tstamp $time;
  62.                 $objApproval->save();
  63.             }
  64.         }
  65.     }
  66.     /**
  67.      * Generate a URL and return it as string
  68.      *
  69.      * @param CalendarEventsModel $objEvent
  70.      * @param ModuleModel         $objModule
  71.      * @param boolean               $blnAbsolute
  72.      *
  73.      * @return string
  74.      */
  75.     public static function generateEventUrlFromModule($objEvent$objModule$blnAbsolute=false)
  76.     {
  77.         $strCacheKey 'id_' $objEvent->id '_mod' $objModule->id . ($blnAbsolute '_absolute' '');
  78.         // Load the URL from cache
  79.         if (isset(self::$arrUrlCache[$strCacheKey]))
  80.         {
  81.             return self::$arrUrlCache[$strCacheKey];
  82.         }
  83.         // Initialize the cache
  84.         self::$arrUrlCache[$strCacheKey] = null;
  85.         switch ($objEvent->source)
  86.         {
  87.             // Link to an external page
  88.             case 'external':
  89.                 if (substr($objEvent->url07) == 'mailto:')
  90.                 {
  91.                     self::$arrUrlCache[$strCacheKey] = StringUtil::encodeEmail($objEvent->url);
  92.                 }
  93.                 else
  94.                 {
  95.                     self::$arrUrlCache[$strCacheKey] = ampersand($objEvent->url);
  96.                 }
  97.                 break;
  98.             // Link to an internal page
  99.             case 'internal':
  100.                 if (($objTarget $objEvent->getRelated('jumpTo')) instanceof PageModel)
  101.                 {
  102.                     /** @var PageModel $objTarget */
  103.                     self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute $objTarget->getAbsoluteUrl() : $objTarget->getFrontendUrl());
  104.                 }
  105.                 break;
  106.             // Link to an article
  107.             case 'article':
  108.                 if (($objArticle ArticleModel::findByPk($objEvent->articleId)) !== null && ($objPid $objArticle->getRelated('pid')) instanceof PageModel)
  109.                 {
  110.                     $params '/articles/' . ($objArticle->alias ?: $objArticle->id);
  111.                     /** @var PageModel $objPid */
  112.                     self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute $objPid->getAbsoluteUrl($params) : $objPid->getFrontendUrl($params));
  113.                 }
  114.                 break;
  115.         }
  116.         // Link to the default page
  117.         if (self::$arrUrlCache[$strCacheKey] === null)
  118.         {
  119.             $intJumpTo $objModule->event_jumpTo ?: (($objParent CalendarModel::findByPk($objEvent->pid)) !== null $objParent->jumpTo null);
  120.             if (!$intJumpTo || ($objJumpTo PageModel::findByPk($intJumpTo)) === null)
  121.             {
  122.                 self::$arrUrlCache[$strCacheKey] = ampersand(Environment::get('request'));
  123.             }
  124.             else
  125.             {
  126.                 $params = (Config::get('useAutoItem') ? '/' '/events/') . ($objEvent->alias ?: $objEvent->id);
  127.                 self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute $objJumpTo->getAbsoluteUrl($params) : $objJumpTo->getFrontendUrl($params));
  128.             }
  129.         }
  130.         return self::$arrUrlCache[$strCacheKey];
  131.     }
  132.     /**
  133.      * Generate a URL and return it as string
  134.      *
  135.      * @param CalendarEventsModel   $objEvent
  136.      * @param PageModel             $objJumpTo
  137.      * @param boolean               $blnAbsolute
  138.      *
  139.      * @return string
  140.      */
  141.     public static function generateEventUrl($objEvent$objJumpTo=null,$blnAbsolute=false)
  142.     {
  143.         $strCacheKey 'id_' $objEvent->id . ($objJumpTo !== null '_jumpTo'.$objJumpTo->id '') . ($blnAbsolute '_absolute' '');
  144.         // Load the URL from cache
  145.         if (isset(self::$arrUrlCache[$strCacheKey]))
  146.         {
  147.             return self::$arrUrlCache[$strCacheKey];
  148.         }
  149.         // Initialize the cache
  150.         self::$arrUrlCache[$strCacheKey] = null;
  151.         switch ($objEvent->source)
  152.         {
  153.             // Link to an external page
  154.             case 'external':
  155.                 if (substr($objEvent->url07) == 'mailto:')
  156.                 {
  157.                     self::$arrUrlCache[$strCacheKey] = StringUtil::encodeEmail($objEvent->url);
  158.                 }
  159.                 else
  160.                 {
  161.                     self::$arrUrlCache[$strCacheKey] = ampersand($objEvent->url);
  162.                 }
  163.                 break;
  164.             // Link to an internal page
  165.             case 'internal':
  166.                 if (($objTarget $objEvent->getRelated('jumpTo')) instanceof PageModel)
  167.                 {
  168.                     /** @var PageModel $objTarget */
  169.                     self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute $objTarget->getAbsoluteUrl() : $objTarget->getFrontendUrl());
  170.                 }
  171.                 break;
  172.             // Link to an article
  173.             case 'article':
  174.                 if (($objArticle ArticleModel::findByPk($objEvent->articleId)) !== null && ($objPid $objArticle->getRelated('pid')) instanceof PageModel)
  175.                 {
  176.                     $params '/articles/' . ($objArticle->alias ?: $objArticle->id);
  177.                     /** @var PageModel $objPid */
  178.                     self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute $objPid->getAbsoluteUrl($params) : $objPid->getFrontendUrl($params));
  179.                 }
  180.                 break;
  181.         }
  182.         // Link to the default page
  183.         if (self::$arrUrlCache[$strCacheKey] === null)
  184.         {
  185.             if ($objJumpTo !== null)
  186.             {
  187.                 $params = (Config::get('useAutoItem') ? '/' '/events/') . ($objEvent->alias ?: $objEvent->id);
  188.                 self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute $objJumpTo->getAbsoluteUrl($params) : $objJumpTo->getFrontendUrl($params));
  189.             }
  190.             else
  191.             {
  192.                 global $objPage;
  193.                 $params = (Config::get('useAutoItem') ? '/' '/events/') . ($objEvent->alias ?: $objEvent->id);
  194.                 self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute $objPage->getAbsoluteUrl($params) : $objPage->getFrontendUrl($params));
  195.             }
  196.         }
  197.         return self::$arrUrlCache[$strCacheKey];
  198.     }
  199.     /**
  200.      * Get a timestamp from a date/time string with format (m/d/Y g:i a)
  201.      *
  202.      * @access        public
  203.      * @param        string $strDate
  204.      * @param       string $strTime
  205.      * @param       string $default
  206.      * @return        integer
  207.      */
  208.     public static function getTimestampFromDateTimeString$strDate$strTime='12:00 AM'$default='12:00 AM') {
  209.         $format "m/d/Y g:i a";
  210.         $dateObj DateTime::createFromFormat($format$strDate ' ' $strTime);
  211.         if(is_bool($dateObj)){
  212.             //Error check if the date or time is bad
  213.             $dateObj DateTime::createFromFormat($format$strDate ' ' $default);
  214.         }
  215.         return $dateObj->getTimestamp();
  216.     }
  217.     /**
  218.      * Appends OpenGraph data from events
  219.      *
  220.      * @param ModuleModel         $objModule
  221.      */
  222.     public static function addModuleData$objModule ) {
  223.         $arrArchives StringUtil::deserialize($objModule->cal_calendartrue);
  224.         $objEvent NULL;
  225.         $objEvent Event::findPublishedByParentAndIdOrAlias(Input::get('events'), $arrArchives);
  226.         if( null !== $objEvent ) {
  227.             global $objPage;
  228.             $strNaturalDate $objEvent->getFormattedDate();
  229.             $objEvent->og_title $objEvent->title ' | '$strNaturalDate .' | Western Mass ArtsHub Events';
  230.             $strDescription 'Check out ' .  $objEvent->title . (strlen($objEvent->location) ? ' at ' .$objEvent->location ''). ' on ' $strNaturalDate;
  231.             $objEvent->og_image = static::getOgImage($objEvent);
  232.             $objEvent->og_description $strDescription;
  233.             $objPage->og_title $objEvent->og_title;
  234.             $objPage->og_image $objEvent->og_image;
  235.             $objPage->og_description $objEvent->og_description;
  236.             $objPage->og_updated_time $objEvent->tstamp;
  237.             OpenGraph3::addTagsToPage$objEvent );
  238.         }
  239.     }
  240.     /**
  241.      * Get og:image source
  242.      * @param $objEvent
  243.      * @return string
  244.      * @throws \Exception
  245.      */
  246.     protected static function getOgImage($objEvent)
  247.     {
  248.         $objModel null;
  249.         $strOgPath '';
  250.         $strOriginalPath '';
  251.         $rootDir System::getContainer()->getParameter('kernel.project_dir');
  252.         if ($objEvent->singleSRC != '')
  253.         {
  254.             $objModel FilesModel::findByUuid($objEvent->singleSRC);
  255.             if ($objModel !== null && is_file($rootDir '/' $objModel->path))
  256.             {
  257.                 $strOriginalPath $rootDir '/' $objModel->path;
  258.                 $strOgPath dirname($rootDir '/' $objModel->path) . '/' str_ireplace(array('.'.$objModel->extension' '), array('-og.'.$objModel->extension'_'), $objModel->name);
  259.             }
  260.         }
  261.         // Add placeholder image instead
  262.         if (!$strOriginalPath || !$strOgPath)
  263.         {
  264.             $strOriginalPath $rootDir '/' . static::$placeholderEventImagePath;
  265.             $strOgPath $rootDir '/' str_ireplace(array('.jpg'' '), array('-og.jpg''_'), static::$placeholderEventImagePath);
  266.         }
  267.         $strUrl urldecode(System::getContainer()
  268.             ->get('contao.image.image_factory')
  269.             ->create($strOriginalPath14$strOgPath// 14 is the "Open Graph Images" image size ID
  270.             ->getUrl($rootDir)
  271.         );
  272.         // Update the database
  273.         if (Dbafs::shouldBeSynchronized($strUrl))
  274.         {
  275.             Dbafs::addResource($strUrl);
  276.         }
  277.         $objModel FilesModel::findByPath($strUrl);
  278.         return $objModel !== null $objModel->uuid '';
  279.     }
  280.     /**
  281.      * Add image methods to a template
  282.      * @param Event $objItem
  283.      * @param mixed $objSource
  284.      * @param Template $objTemplate
  285.      * @param array $arrConfig
  286.      */
  287.     public static function addImageMethodsToTemplate(Event $objItem$objSourceTemplate $objTemplate$arrConfig=[])
  288.     {
  289.         $fnAddImageToTemplate = function($uuid$objItem$objSource$objTemplate$arrConfig=[]) {
  290.             $arrImage = [];
  291.             $container System::getContainer();
  292.             $rootDir $container->getParameter('kernel.project_dir');
  293.             $staticUrl $container->get('contao.assets.files_context')->getStaticUrl();
  294.             $arrSize StringUtil::deserialize(\is_array($arrConfig) && $arrConfig['imgSize'] ? $arrConfig['imgSize'] : ($objSource->imgSize ?: $objSource->size), true);
  295.             $arrSize += array(00'crop');
  296.             $objFileModel FilesModel::findByUuid($uuid);
  297.             if ($objFileModel !== null && \file_exists(TL_ROOT '/' $objFileModel->path))
  298.             {
  299.                 try {
  300.                     $objFile = new File($objFileModel->path);
  301.                 }
  302.                 catch (\Exception $e) {
  303.                     return [];
  304.                 }
  305.                 if ($objFile->isGdImage)
  306.                 {
  307.                     try
  308.                     {
  309.                         $picture $container->get('contao.image.picture_factory')->create($rootDir '/' $objFileModel->path$arrSize);
  310.                         $picture = array
  311.                         (
  312.                             'img' => $picture->getImg($rootDir$staticUrl),
  313.                             'sources' => $picture->getSources($rootDir$staticUrl)
  314.                         );
  315.                         $src $picture['img']['src'];
  316.                         if ($src !== $objFileModel->path)
  317.                         {
  318.                             $objFile = new File(\rawurldecode($src));
  319.                         }
  320.                     }
  321.                     catch (\Exception $e)
  322.                     {
  323.                         System::log('Image "' $objFileModel->path '" could not be processed: ' $e->getMessage(), __METHOD__TL_ERROR);
  324.                         //$src = '';
  325.                         $picture = array('img'=>array('src'=>'''srcset'=>''), 'sources'=>array());
  326.                     }
  327.                     //Add special classes for tall, wide, and small images
  328.                     $arrClasses = [];
  329.                     $isTallImage false;
  330.                     if($objFile->height/$objFile->width 1.5) {
  331.                         $arrClasses[] = 'tall_image';
  332.                         $isTallImage true;
  333.                     }
  334.                     if($objFile->width/$objFile->height 1.5) {
  335.                         $arrClasses[] = 'wide_image';
  336.                     }
  337.                     if($objFile->width 500 || $objFile->height 500) {
  338.                         $arrClasses[] = 'small_image';
  339.                     }
  340.                     // Add the image
  341.                     $arrImage = array
  342.                     (
  343.                         'file'              => $objFile,
  344.                         'fileModel'         => $objFileModel,
  345.                         'originalSrc'       => $objFileModel->path,
  346.                         'height'            => $objFile->height,
  347.                         'width'             => $objFile->width,
  348.                         'isTallImage'       => $isTallImage,
  349.                         'additionalClasses' => (!empty($arrClasses) ? ' ' implode(' '$arrClasses) : ''),
  350.                         'model'             => $objItem,
  351.                         'picture'           => $picture,
  352.                         'alt'               => $objItem->title
  353.                     );
  354.                 }
  355.             }
  356.             return $arrImage;
  357.         };
  358.         $objTemplate->getListerMainImage = function() use ($objItem$objSource$objTemplate$fnAddImageToTemplate$arrConfig)
  359.         {
  360.             return $fnAddImageToTemplate($objItem->singleSRC$objItem$objSource$objTemplate$arrConfig);
  361.         };
  362.         $objTemplate->getReaderMainImage = function() use ($objItem$objSource$objTemplate$fnAddImageToTemplate$arrConfig)
  363.         {
  364.             return $fnAddImageToTemplate($objItem->singleSRC$objItem$objSource$objTemplate$arrConfig);
  365.         };
  366.     }
  367. }