<?php
/**
* Copyright (C) 2021 Rhyme Digital, LLC.
*
* @link https://rhyme.digital
* @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL
*/
namespace Rhyme\WMassArtsHub\Helper;
use Contao\Config;
use Contao\Environment;
use Contao\File;
use Contao\ModuleModel;
use Contao\PageModel;
use Contao\System;
use Contao\StringUtil;
use Contao\Controller;
use Contao\FilesModel;
use Contao\Template;
use Haste\Util\Format;
use MaeEventCategories\MaeEventCatModel;
use Rhyme\WMassArtsHub\Model\Profile\Item as WMassArtsHub_ProfileItemModel;
/**
* Class ProfileHelper
* @package Rhyme\WMassArtsHub\Helper
*/
class ProfileHelper extends Controller
{
/**
* The detail page ID
* @var int
*/
public static $profileDetailPage = 159;
/**
* The placeholder image
* @var string
*/
public static $profilePlaceholderImagePath = 'files/assets/img/placeholders/profile-placeholder.jpg';
/**
* URL cache array
* @var array
*/
private static $arrUrlCache = array();
/**
* Returns a frontend URL for a business detail page
*
* @param WMassArtsHub_ProfileItemModel $objProfileItem
* @param ModuleModel $objModule
* @param boolean $blnAbsolute
*
* @return string
*/
public static function generateProfileItemUrlFromModule($objProfileItem, $objModule, $blnAbsolute=false) {
$strCacheKey = 'id_' . $objProfileItem->id . ($blnAbsolute ? '_absolute' : '');
// Load the URL from cache
if (isset(self::$arrUrlCache[$strCacheKey]))
{
return self::$arrUrlCache[$strCacheKey];
}
$jumpTo = $objModule !== null && $objModule->jumpTo ? $objModule->jumpTo : static::$profileDetailPage;
$objPage = PageModel::findByPk($jumpTo);
if (!$objPage instanceof PageModel)
{
self::$arrUrlCache[$strCacheKey] = ampersand(Environment::get('request'));
}
else
{
$params = (Config::get('useAutoItem') ? '/' : '/detail/') . ($objProfileItem->alias ?: $objProfileItem->id);
self::$arrUrlCache[$strCacheKey] = ampersand($blnAbsolute ? $objPage->getAbsoluteUrl($params) : $objPage->getFrontendUrl($params));
}
return self::$arrUrlCache[$strCacheKey];
}
/**
* Add image methods to a template
* @param WMassArtsHub_ProfileItemModel $objItem
* @param mixed $objSource
* @param Template $objTemplate
* @param array $arrConfig
*/
public static function addImageMethodsToTemplate(WMassArtsHub_ProfileItemModel $objItem, $objSource, Template $objTemplate, $arrConfig=[])
{
$fnAddImageToTemplate = function($uuid, $objItem, $objSource, $objTemplate, $arrConfig=[]) {
$arrImage = [];
$blnIsUsingPlaceholder = false;
$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);
//Grab placeholder as backup
if($objFileModel === null) {
$blnIsUsingPlaceholder = true;
$objFileModel = FilesModel::findByPath(static::$profilePlaceholderImagePath);
}
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());
}
$meta = StringUtil::deserialize($objFileModel->meta, true);
//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
(
'isPlaceholder' => $blnIsUsingPlaceholder,
'file' => $objFile,
'fileModel' => $objFileModel,
'model' => $objItem,
'picture' => $picture,
'originalSrc' => $objFileModel->path,
'height' => $objFile->height,
'width' => $objFile->width,
'isTallImage' => $isTallImage,
'additionalClasses' => (!empty($arrClasses) ? ' ' . implode(' ', $arrClasses) : ''),
'meta' => $meta,
'caption' => $meta['en']['caption'],
'alt' => $meta['en']['alt'],
'id' => 'image-' . $objFileModel->id,
);
}
}
return $arrImage;
};
$objTemplate->getListerMainImage = function() use ($objItem, $objSource, $objTemplate, $fnAddImageToTemplate, $arrConfig)
{
return $fnAddImageToTemplate($objItem->main_image, $objItem, $objSource, $objTemplate, $arrConfig);
};
$objTemplate->getReaderMainImage = function() use ($objItem, $objSource, $objTemplate, $fnAddImageToTemplate, $arrConfig)
{
return $fnAddImageToTemplate($objItem->main_image, $objItem, $objSource, $objTemplate, $arrConfig);
};
$objTemplate->getReaderOtherImages = function() use ($objItem, $objSource, $objTemplate, $fnAddImageToTemplate, $arrConfig)
{
$arrImages=[];
if($arrConfig['gallery_imgSize']) {
$arrConfig['imgSize'] = $arrConfig['gallery_imgSize'];
}
foreach (\array_unique(StringUtil::deserialize($objItem->images, true)) as $image) {
if($image !== $objItem->main_image) {
$arrImages[] = $fnAddImageToTemplate($image, $objItem, $objSource, $objTemplate, $arrConfig);
}
}
return $arrImages;
};
}
/**
* Format an address
* @param string $street1
* @param string $street2
* @param string $city
* @param string $state
* @param string $zip
* @return string
*/
public static function formatAddress($street1, $street2, $city, $state, $zip, $blnAddHTML=false)
{
$liO = function($prefix) use ($blnAddHTML) {
$class = strlen($prefix) ? StringUtil::generateAlias($prefix) : 'none';
return ($blnAddHTML ? '<li class="'.StringUtil::generateAlias($prefix).'"><span class="name">'.$prefix.':</span> <span class="value">' : '');
};
$liC = ($blnAddHTML ? '</span></li>' : '');
$hasStreet = strlen($street1) > 0 || strlen($street2) > 0;
$hasCity = strlen($city) > 0;
$hasState = strlen($state) > 0;
$hasCityAndState = $hasCity && $hasState;
$hasCityOrState = $hasCity || $hasState;
$strAddress = ($blnAddHTML ? '<ul>' : '');
$strAddress .= ($hasStreet ? $liO('Address') . trim($street1 . (strlen($street1) > 0 ? ' ' : '') . $street2) . ' ' .$liC : '');
$strAddress .= ($liO('City/State') . trim($city . ($hasCityAndState ? ', ' : '') . $state . ($hasCityOrState ? ' ' : '') . trim($zip)) .$liC);
return $strAddress . ($blnAddHTML ? '</ul>' : '');
}
/**
* Format an address
* @param string $name
* @param string $title
* @param string $phone
* @param string $email
* @param string $fax
* @return string
*/
public static function formatContactInfo($name, $title, $phone, $email, $fax, $blnAddHTML=false)
{
$liO = function($prefix) use ($blnAddHTML) {
return ($blnAddHTML ? '<li class="'.StringUtil::generateAlias($prefix).'"><span class="name">'.$prefix.':</span> <span class="value">' : '');
};
$liC = ($blnAddHTML ? '</span></li>' : '');
$hasName = strlen($name) > 0;
$hasNameOrTitle = $hasName || strlen($title) > 0;
$hasNameAndTitle = $hasName && strlen($title) > 0;
$strContact = ($blnAddHTML ? '<ul>' : '');
$strContact .= ($hasNameOrTitle ? $liO('Name/Title') . trim($name . ($hasNameAndTitle ? ', ' : '') . $title) .$liC : '');
$strContact .= (strlen($phone) > 0 ? $liO('Phone') . '<a href="tel:'. trim($phone) . '" target="_blank" title="Call this contact">'. trim($phone) . '</a>' . $liC : '');
$strContact .= (strlen($email) > 0 ? $liO('Email') . '<a href="mailto:'. trim($email) . '" target="_blank" title="Email this contact">'. trim($email) . '</a>' .$liC : '');
$strContact .= (strlen($fax) > 0 ? $liO('Fax') . trim($fax) . $liC : '');
return $strContact . ($blnAddHTML ? '</ul>' : '');
}
/**
* Return the class that details how many info boxes are shown
* @param array $arrEducation
* @param array $arrAwards
* @param array $arrAssociations
* @param array $arrAdditionalContent
* @return string
*/
public static function infoBoxClass($arrEducation, $arrAwards, $arrAssociations, $arrAdditionalContent) {
$arrOptions = ['none', 'one', 'two', 'three', 'four', 'five'];
$intCount = 0;
$arrAll = [$arrEducation, $arrAwards, $arrAssociations, $arrAdditionalContent];
foreach($arrAll as $infoBox) {
if(!empty($infoBox)) $intCount++;
}
return 'totalboxes-' . $arrOptions[$intCount];
}
/**
* Load profile field options
* @param $objWidget
*/
public static function addOptionsToWidget(&$objWidget) {
$objProfiles = WMassArtsHub_ProfileItemModel::findPublished(['order'=>'name ASC']);
if ($objProfiles !== null)
{
$arrOptions = array();
while ($objProfiles->next())
{
$arrOptions[$objProfiles->current()->id] = array
(
'value' => $objProfiles->current()->id,
'label' => $objProfiles->current()->name,
'default' => '',
'group' => '',
);
}
$objWidget->options = $arrOptions;
// Apply the "select2" library
$GLOBALS['TL_BODY'][] = "<script>
jQuery(document).ready(function(){ jQuery('#ctrl_".$objWidget->id."').select2({placeholder: 'Select associated profiles/organizations'}); });
jQuery(window).on('ajax_change', function(){ jQuery('#ctrl_".$objWidget->id."').select2({placeholder: 'Select associated profiles/organizations'}); });
</script>";
}
}
/**
* Use output buffer to var dump to a string
*
* @param string
* @return string
*/
public static function varDumpToString($var)
{
ob_start();
var_dump($var);
$result = ob_get_clean();
return $result;
}
}