<?php
/**
* Copyright (C) 2019 Rhyme Digital, LLC.
*
* @link https://rhyme.digital
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*/
namespace Rhyme\WMassArtsHub\Helper;
use Contao\Date;
use Contao\Config;
use Contao\Input;
use Contao\File;
use Contao\Dbafs;
use Contao\System;
use Contao\Controller;
use Contao\CalendarModel;
use Contao\CalendarEventsModel;
use Contao\PageModel;
use Contao\ModuleModel;
use Contao\ArticleModel;
use Contao\FilesModel;
use Contao\StringUtil;
use Contao\Environment;
use Contao\Template;
use Haste\DateTime\DateTime;
use Rhyme\WMassArtsHub\Model\Event;
use Rhyme\WMassArtsHub\Model\Approval;
use numero2\OpenGraph3\OpenGraph3;
use Rhyme\WMassArtsHub\Model\Profile\Item as WMassArtsHub_ProfileItemModel;
/**
* Class EventHelper
* @package Rhyme\Noho\Helper
*/
class EventHelper extends Controller
{
/**
* URL cache array
* @var array
*/
private static $arrUrlCache = array();
/**
* Default event image
* @var string
*/
protected static $placeholderEventImagePath = 'files/noho/images/default_placeholders/businessBg.jpg';
/**
* Adds an approval entry
*
* @param CalendarEventsModel $objEvent
*/
public static function createApprovalForEvent($objEvent) {
if(null !== $objEvent) {
//Check for existing one
$t = CalendarEventsModel::getTable();
$objCheck = Approval::findByRowIdAndFromTable($objEvent->id, $t);
if (null === $objCheck) {
$time = time();
$objApproval = new Approval();
$objApproval->fromTable = CalendarEventsModel::getTable();
$objApproval->rowId = $objEvent->id;
$objApproval->tstamp = $time;
$objApproval->save();
}
}
}
/**
* Generate a URL and return it as string
*
* @param CalendarEventsModel $objEvent
* @param ModuleModel $objModule
* @param boolean $blnAbsolute
*
* @return string
*/
public static function generateEventUrlFromModule($objEvent, $objModule, $blnAbsolute=false)
{
$strCacheKey = 'id_' . $objEvent->id . '_mod' . $objModule->id . ($blnAbsolute ? '_absolute' : '');
// Load the URL from cache
if (isset(self::$arrUrlCache[$strCacheKey]))
{
return self::$arrUrlCache[$strCacheKey];
}
// Initialize the cache
self::$arrUrlCache[$strCacheKey] = null;
switch ($objEvent->source)
{
// Link to an external page
case 'external':
if (substr($objEvent->url, 0, 7) == 'mailto:')
{
self::$arrUrlCache[$strCacheKey] = StringUtil::encodeEmail($objEvent->url);
}
else
{
self::$arrUrlCache[$strCacheKey] = ampersand($objEvent->url);
}
break;
// Link to an internal page
case 'internal':
if (($objTarget = $objEvent->getRelated('jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objTarget->getAbsoluteUrl() : $objTarget->getFrontendUrl());
}
break;
// Link to an article
case 'article':
if (($objArticle = ArticleModel::findByPk($objEvent->articleId)) !== null && ($objPid = $objArticle->getRelated('pid')) instanceof PageModel)
{
$params = '/articles/' . ($objArticle->alias ?: $objArticle->id);
/** @var PageModel $objPid */
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objPid->getAbsoluteUrl($params) : $objPid->getFrontendUrl($params));
}
break;
}
// Link to the default page
if (self::$arrUrlCache[$strCacheKey] === null)
{
$intJumpTo = $objModule->event_jumpTo ?: (($objParent = CalendarModel::findByPk($objEvent->pid)) !== null ? $objParent->jumpTo : null);
if (!$intJumpTo || ($objJumpTo = PageModel::findByPk($intJumpTo)) === null)
{
self::$arrUrlCache[$strCacheKey] = ampersand(Environment::get('request'));
}
else
{
$params = (Config::get('useAutoItem') ? '/' : '/events/') . ($objEvent->alias ?: $objEvent->id);
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objJumpTo->getAbsoluteUrl($params) : $objJumpTo->getFrontendUrl($params));
}
}
return self::$arrUrlCache[$strCacheKey];
}
/**
* Generate a URL and return it as string
*
* @param CalendarEventsModel $objEvent
* @param PageModel $objJumpTo
* @param boolean $blnAbsolute
*
* @return string
*/
public static function generateEventUrl($objEvent, $objJumpTo=null,$blnAbsolute=false)
{
$strCacheKey = 'id_' . $objEvent->id . ($objJumpTo !== null ? '_jumpTo'.$objJumpTo->id : '') . ($blnAbsolute ? '_absolute' : '');
// Load the URL from cache
if (isset(self::$arrUrlCache[$strCacheKey]))
{
return self::$arrUrlCache[$strCacheKey];
}
// Initialize the cache
self::$arrUrlCache[$strCacheKey] = null;
switch ($objEvent->source)
{
// Link to an external page
case 'external':
if (substr($objEvent->url, 0, 7) == 'mailto:')
{
self::$arrUrlCache[$strCacheKey] = StringUtil::encodeEmail($objEvent->url);
}
else
{
self::$arrUrlCache[$strCacheKey] = ampersand($objEvent->url);
}
break;
// Link to an internal page
case 'internal':
if (($objTarget = $objEvent->getRelated('jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objTarget->getAbsoluteUrl() : $objTarget->getFrontendUrl());
}
break;
// Link to an article
case 'article':
if (($objArticle = ArticleModel::findByPk($objEvent->articleId)) !== null && ($objPid = $objArticle->getRelated('pid')) instanceof PageModel)
{
$params = '/articles/' . ($objArticle->alias ?: $objArticle->id);
/** @var PageModel $objPid */
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objPid->getAbsoluteUrl($params) : $objPid->getFrontendUrl($params));
}
break;
}
// Link to the default page
if (self::$arrUrlCache[$strCacheKey] === null)
{
if ($objJumpTo !== null)
{
$params = (Config::get('useAutoItem') ? '/' : '/events/') . ($objEvent->alias ?: $objEvent->id);
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objJumpTo->getAbsoluteUrl($params) : $objJumpTo->getFrontendUrl($params));
}
else
{
global $objPage;
$params = (Config::get('useAutoItem') ? '/' : '/events/') . ($objEvent->alias ?: $objEvent->id);
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objPage->getAbsoluteUrl($params) : $objPage->getFrontendUrl($params));
}
}
return self::$arrUrlCache[$strCacheKey];
}
/**
* Get a timestamp from a date/time string with format (m/d/Y g:i a)
*
* @access public
* @param string $strDate
* @param string $strTime
* @param string $default
* @return integer
*/
public static function getTimestampFromDateTimeString( $strDate, $strTime='12:00 AM', $default='12:00 AM') {
$format = "m/d/Y g:i a";
$dateObj = DateTime::createFromFormat($format, $strDate . ' ' . $strTime);
if(is_bool($dateObj)){
//Error check if the date or time is bad
$dateObj = DateTime::createFromFormat($format, $strDate . ' ' . $default);
}
return $dateObj->getTimestamp();
}
/**
* Appends OpenGraph data from events
*
* @param ModuleModel $objModule
*/
public static function addModuleData( $objModule ) {
$arrArchives = StringUtil::deserialize($objModule->cal_calendar, true);
$objEvent = NULL;
$objEvent = Event::findPublishedByParentAndIdOrAlias(Input::get('events'), $arrArchives);
if( null !== $objEvent ) {
global $objPage;
$strNaturalDate = $objEvent->getFormattedDate();
$objEvent->og_title = $objEvent->title . ' | '. $strNaturalDate .' | Western Mass ArtsHub Events';
$strDescription = 'Check out ' . $objEvent->title . (strlen($objEvent->location) ? ' at ' .$objEvent->location : ''). ' on ' . $strNaturalDate;
$objEvent->og_image = static::getOgImage($objEvent);
$objEvent->og_description = $strDescription;
$objPage->og_title = $objEvent->og_title;
$objPage->og_image = $objEvent->og_image;
$objPage->og_description = $objEvent->og_description;
$objPage->og_updated_time = $objEvent->tstamp;
OpenGraph3::addTagsToPage( $objEvent );
}
}
/**
* Get og:image source
* @param $objEvent
* @return string
* @throws \Exception
*/
protected static function getOgImage($objEvent)
{
$objModel = null;
$strOgPath = '';
$strOriginalPath = '';
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
if ($objEvent->singleSRC != '')
{
$objModel = FilesModel::findByUuid($objEvent->singleSRC);
if ($objModel !== null && is_file($rootDir . '/' . $objModel->path))
{
$strOriginalPath = $rootDir . '/' . $objModel->path;
$strOgPath = dirname($rootDir . '/' . $objModel->path) . '/' . str_ireplace(array('.'.$objModel->extension, ' '), array('-og.'.$objModel->extension, '_'), $objModel->name);
}
}
// Add placeholder image instead
if (!$strOriginalPath || !$strOgPath)
{
$strOriginalPath = $rootDir . '/' . static::$placeholderEventImagePath;
$strOgPath = $rootDir . '/' . str_ireplace(array('.jpg', ' '), array('-og.jpg', '_'), static::$placeholderEventImagePath);
}
$strUrl = urldecode(System::getContainer()
->get('contao.image.image_factory')
->create($strOriginalPath, 14, $strOgPath) // 14 is the "Open Graph Images" image size ID
->getUrl($rootDir)
);
// Update the database
if (Dbafs::shouldBeSynchronized($strUrl))
{
Dbafs::addResource($strUrl);
}
$objModel = FilesModel::findByPath($strUrl);
return $objModel !== null ? $objModel->uuid : '';
}
/**
* Add image methods to a template
* @param Event $objItem
* @param mixed $objSource
* @param Template $objTemplate
* @param array $arrConfig
*/
public static function addImageMethodsToTemplate(Event $objItem, $objSource, Template $objTemplate, $arrConfig=[])
{
$fnAddImageToTemplate = function($uuid, $objItem, $objSource, $objTemplate, $arrConfig=[]) {
$arrImage = [];
$container = System::getContainer();
$rootDir = $container->getParameter('kernel.project_dir');
$staticUrl = $container->get('contao.assets.files_context')->getStaticUrl();
$arrSize = StringUtil::deserialize(\is_array($arrConfig) && $arrConfig['imgSize'] ? $arrConfig['imgSize'] : ($objSource->imgSize ?: $objSource->size), true);
$arrSize += array(0, 0, 'crop');
$objFileModel = FilesModel::findByUuid($uuid);
if ($objFileModel !== null && \file_exists(TL_ROOT . '/' . $objFileModel->path))
{
try {
$objFile = new File($objFileModel->path);
}
catch (\Exception $e) {
return [];
}
if ($objFile->isGdImage)
{
try
{
$picture = $container->get('contao.image.picture_factory')->create($rootDir . '/' . $objFileModel->path, $arrSize);
$picture = array
(
'img' => $picture->getImg($rootDir, $staticUrl),
'sources' => $picture->getSources($rootDir, $staticUrl)
);
$src = $picture['img']['src'];
if ($src !== $objFileModel->path)
{
$objFile = new File(\rawurldecode($src));
}
}
catch (\Exception $e)
{
System::log('Image "' . $objFileModel->path . '" could not be processed: ' . $e->getMessage(), __METHOD__, TL_ERROR);
//$src = '';
$picture = array('img'=>array('src'=>'', 'srcset'=>''), 'sources'=>array());
}
//Add special classes for tall, wide, and small images
$arrClasses = [];
$isTallImage = false;
if($objFile->height/$objFile->width > 1.5) {
$arrClasses[] = 'tall_image';
$isTallImage = true;
}
if($objFile->width/$objFile->height > 1.5) {
$arrClasses[] = 'wide_image';
}
if($objFile->width < 500 || $objFile->height < 500) {
$arrClasses[] = 'small_image';
}
// Add the image
$arrImage = array
(
'file' => $objFile,
'fileModel' => $objFileModel,
'originalSrc' => $objFileModel->path,
'height' => $objFile->height,
'width' => $objFile->width,
'isTallImage' => $isTallImage,
'additionalClasses' => (!empty($arrClasses) ? ' ' . implode(' ', $arrClasses) : ''),
'model' => $objItem,
'picture' => $picture,
'alt' => $objItem->title
);
}
}
return $arrImage;
};
$objTemplate->getListerMainImage = function() use ($objItem, $objSource, $objTemplate, $fnAddImageToTemplate, $arrConfig)
{
return $fnAddImageToTemplate($objItem->singleSRC, $objItem, $objSource, $objTemplate, $arrConfig);
};
$objTemplate->getReaderMainImage = function() use ($objItem, $objSource, $objTemplate, $fnAddImageToTemplate, $arrConfig)
{
return $fnAddImageToTemplate($objItem->singleSRC, $objItem, $objSource, $objTemplate, $arrConfig);
};
}
}