src/Rhyme/WMassArtsHub/Model/Profile/Item.php line 400

Open in your IDE?
  1. <?php
  2. /**
  3.  * Copyright (c) 2020 Rhyme Digital LLC (https://rhyme.digital)
  4.  *
  5.  * @license LGPL-3.0-or-later
  6.  */
  7. namespace Rhyme\WMassArtsHub\Model\Profile;
  8. use Contao\ContentElement;
  9. use Contao\Controller;
  10. use Contao\Environment;
  11. use Contao\FrontendTemplate;
  12. use Contao\Model;
  13. use Contao\Database;
  14. use Contao\PageModel;
  15. use Contao\StringUtil;
  16. use Contao\Model\Collection;
  17. use Contao\Model\QueryBuilder;
  18. use Contao\System;
  19. use Exception;
  20. use Haste\Util\Url;
  21. use Rhyme\WMassArtsHub\Helper\GeneralHelper;
  22. use Rhyme\WMassArtsHub\Helper\ProfileHelper;
  23. use Rhyme\WMassArtsHub\Model\Profile\Discipline;
  24. /**
  25.  * Class Item
  26.  * @package Rhyme\WMassArtsHub\Model\Profile
  27.  *
  28.  * @property string $main_image
  29.  *
  30.  * @method static Collection|Item[]|Item|null findMultipleByIds($val, array $opt=array())
  31.  */
  32. class Item extends Model
  33. {
  34.     /**
  35.      * @var string
  36.      */
  37.     protected static $strTable 'tl_artshub_profile_item';
  38.     /**
  39.      * Unique form ID
  40.      * @var string
  41.      */
  42.     protected $strFormId 'artshub_profile_item';
  43.     /**
  44.      * @var array|null
  45.      */
  46.     protected $arrCategories;
  47.     /**
  48.      * List of types (classes) for this model
  49.      * @var array
  50.      */
  51.     protected static $arrModelTypes = array();
  52.     /**
  53.      * Generate a product template
  54.      *
  55.      * @param array $arrConfig
  56.      *
  57.      * @return string
  58.      *
  59.      * @throws \InvalidArgumentException
  60.      */
  61.     public function generate(array $arrConfig)
  62.     {
  63.         $this->strFormId = (($arrConfig['module'] instanceof ContentElement) ? 'cte' 'fmd') . $arrConfig['module']->id '_profileItem_' $this->id;
  64.         $objTemplate = new FrontendTemplate($arrConfig['template']);
  65.         $objTemplate->setData($this->arrData);
  66.         $objTemplate->item              $this;
  67.         $objTemplate->config            $arrConfig;
  68.         $objTemplate->raw               $this->arrData;
  69.         $objTemplate->href              $this->generateUrl($arrConfig['jumpTo']);
  70.         $objTemplate->enctype           $this->hasUpload 'multipart/form-data' 'application/x-www-form-urlencoded';
  71.         $objTemplate->formId            $this->getFormId();
  72.         $objTemplate->action            = \ampersand(Environment::get('request') ?: Environment::get('base'), true);
  73.         $objTemplate->formSubmit        $this->getFormId();
  74.         $objTemplate->item_id           $this->id;
  75.         $objTemplate->module_id         $arrConfig['module']->id;
  76.         ProfileHelper::addImageMethodsToTemplate($this$arrConfig['module'], $objTemplate$arrConfig);
  77.         // !HOOK: alter data before output
  78.         if (isset($GLOBALS['TL_HOOKS']['generateProfileItem']) && \is_array($GLOBALS['TL_HOOKS']['generateProfileItem'])) {
  79.             foreach ($GLOBALS['TL_HOOKS']['generateProfileItem'] as $callback) {
  80.                 System::importStatic($callback[0])->{$callback[1]}($objTemplate$this);
  81.             }
  82.         }
  83.         return \trim($objTemplate->parse());
  84.     }
  85.     /**
  86.      * Generate url
  87.      *
  88.      * @param PageModel $objJumpTo A PageModel instance
  89.      *
  90.      * @return string
  91.      *
  92.      * @throws \InvalidArgumentException
  93.      */
  94.     public function generateUrl(PageModel $objJumpTo null)
  95.     {
  96.         if (null === $objJumpTo) {
  97.             global $objPage;
  98.             $objJumpTo $objPage;
  99.         }
  100.         if (null === $objJumpTo) {
  101.             return '';
  102.         }
  103.         $objJumpTo->loadDetails();
  104.         $strUrl '/' . ($this->arrData['alias'] ?: $this->id);
  105.         if (!$GLOBALS['TL_CONFIG']['useAutoItem'] || !in_array('detail'$GLOBALS['TL_AUTO_ITEM'], true)) {
  106.             $strUrl '/detail' $strUrl;
  107.         }
  108.         return Url::addQueryString(
  109.             '',
  110.             Controller::generateFrontendUrl($objJumpTo->row(), $strUrl$objJumpTo->language)
  111.         );
  112.     }
  113.     /**
  114.      * Return the Google Maps link
  115.      * @return string
  116.      */
  117.     public function getGoogleMapsLink() {
  118.         return 'https://www.google.com/maps/search/'.$this->latitude.','.$this->longitude;
  119.     }
  120.     /**
  121.      * Return a formatted array
  122.      * @return array
  123.      */
  124.     public function getArrayContent($strField) {
  125.         return StringUtil::deserialize($this->{$strField}, true);
  126.     }
  127.     /**
  128.      * Get the related Institution Type
  129.      * @return Collection|Item|null
  130.      * @throws Exception
  131.      */
  132.     public function getInstitutionType()
  133.     {
  134.         try {
  135.             return $this->getRelated('primary_type');
  136.         } catch (Exception $e) { }
  137.         return null;
  138.     }
  139.     /**
  140.      * Get all the additional content as an array
  141.      * @return array
  142.      */
  143.     public function getAdditionalContent()
  144.     {
  145.         $arrAdditionalContent = [];
  146.         //Year founded
  147.         if($this->year_founded 0) {
  148.             $arrAdditionalContent[] = 'Year founded: ' date('Y'$this->year_founded);
  149.         }
  150.         //NA Artist
  151.         if($this->native_american_artist) {
  152.             $arrAdditionalContent[] = 'Is a Native American Artist';
  153.         }
  154.         //Teaching Artist
  155.         if($this->is_teaching_artist) {
  156.             $arrAdditionalContent[] = 'Is a Teaching Artist';
  157.         }
  158.         //Touring Artist
  159.         if($this->is_touring_artist) {
  160.             $arrAdditionalContent[] = 'Is a Touring Artist';
  161.         }
  162.         //Events per year
  163.         if($this->events_per_year 0) {
  164.             $arrAdditionalContent[] = 'Approx. ' $this->events_per_year ' events per year';
  165.         }
  166.         //Venues
  167.         if($this->has_venues) {
  168.             $arrAdditionalContent[] = 'Has venues available';
  169.         }
  170.         //Geographic Reach
  171.         $geographicReach StringUtil::deserialize($this->geographic_reachtrue);
  172.         if(!empty($geographicReach)) {
  173.             $arrReach = [];
  174.             foreach($geographicReach as $key) {
  175.                 $arrReach[] =  array_key_exists($key$GLOBALS['TL_LANG']['MSC']) ? $GLOBALS['TL_LANG']['MSC'][$key] : $key;
  176.             }
  177.             $arrAdditionalContent[] = 'Geographic Reach: ' implode(', '$arrReach);
  178.         }
  179.         //Seasons active
  180.         $seasonsActive StringUtil::deserialize($this->seasons_activetrue);
  181.         if(!empty($seasonsActive)) {
  182.             $arrSeasons = [];
  183.             foreach($seasonsActive as $key) {
  184.                 $arrSeasons[] =  $GLOBALS['TL_LANG']['MSC'][$key];
  185.             }
  186.             if(\asort($seasonsActive) == ['fall''spring''summer''winter']) {
  187.                 $arrAdditionalContent[] = 'Seasons active: Year round';
  188.             } else {
  189.                 $arrAdditionalContent[] = 'Seasons active: ' implode(', '$arrSeasons);
  190.             }
  191.         }
  192.         return $arrAdditionalContent;
  193.     }
  194.     /**
  195.      * Get the related Primary Disciplines
  196.      * @return Discipline
  197.      * @throws Exception
  198.      */
  199.     public function getPrimaryDiscipline()
  200.     {
  201.         try {
  202.             return $this->getRelated('primary_discipline') ?: null;
  203.         } catch (Exception $e) { }
  204.         return null;
  205.     }
  206.     /**
  207.      * Get the related Disciplines
  208.      * @param bool $blnRemovePrimary
  209.      * @return array
  210.      * @throws Exception
  211.      */
  212.     public function getDisciplines($blnRemovePrimary false)
  213.     {
  214.         try {
  215.             $objDiscCollection =  $this->getRelated('disciplines');
  216.             if($blnRemovePrimary) {
  217.                 $arrDisciplines = [];
  218.                 while($objDiscCollection->next()) {
  219.                     if($objDiscCollection->current()->id !== $this->primary_discipline) {
  220.                         $arrDisciplines[] = $objDiscCollection->current();
  221.                     }
  222.                 }
  223.                 return $arrDisciplines;
  224.             }
  225.             return $objDiscCollection !== null $objDiscCollection->getModels() : [];
  226.         } catch (Exception $e) { }
  227.         return [];
  228.     }
  229.     /**
  230.      * Get the related Activities
  231.      * @return array
  232.      * @throws Exception
  233.      */
  234.     public function getActivities()
  235.     {
  236.         try {
  237.             $objActCollection =  $this->getRelated('activities');
  238.             return $objActCollection !== null $objActCollection->getModels() : [];
  239.         } catch (Exception $e) { }
  240.         return [];
  241.     }
  242.     /**
  243.      * Return whether or not this profile has links
  244.      * @return bool
  245.      */
  246.     public function hasLinks()
  247.     {
  248.         return strlen($this->website) || strlen($this->facebook) || strlen($this->twitter) || strlen($this->instagram);
  249.     }
  250.     /**
  251.      * Get the address
  252.      * @param bool $blnFormatLines
  253.      * @return string
  254.      */
  255.     public function getAddress($blnFormatLines false)
  256.     {
  257.         return ProfileHelper::formatAddress($this->street$this->street2$this->city$this->state$this->postal$blnFormatLines);
  258.     }
  259.     /**
  260.      * Get the address
  261.      * @param bool $blnFormatLines
  262.      * @return string
  263.      */
  264.     public function getContactInfo($blnFormatLines false$combineAddressInfo false)
  265.     {
  266.         $strContact ProfileHelper::formatContactInfo($this->contact_name$this->contact_title$this->phone$this->email$this->fax$blnFormatLines);
  267.         $strContactAddress ProfileHelper::formatAddress($this->mailing_street_1$this->mailing_street_2$this->mailing_city$this->mailing_state$this->mailing_zip$blnFormatLines);
  268.         $strContactBlock $strContact $strContactAddress;
  269.         if($combineAddressInfo) {
  270.             $strContactBlock str_replace('</ul>'''$strContact) . str_replace('<ul>'''$strContactAddress);
  271.         }
  272.         return $strContactBlock;
  273.     }
  274.     /**
  275.      * Get some vids
  276.      * @return array
  277.      */
  278.     public function getVideos() {
  279.         $arrVids StringUtil::deserialize($this->video_urlstrue);
  280.         foreach($arrVids as $k => $vid) {
  281.             if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/\s]{11})%i'$vid['link'], $match)) {
  282.                 $video_id $match[1];
  283.                 $arrVids[$k]['thumbnail'] = 'https://img.youtube.com/vi/'.$video_id.'/mqdefault.jpg';
  284.                 $arrVids[$k]['embedHTML'] = '<iframe src="https://www.youtube.com/embed/'.$video_id.'?rel=0&modestbranding=1" width="640" height ="360" frameborder="0" allowfullscreen></iframe>';
  285.             }
  286.             if(preg_match('/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/'$vid['link'], $match)) {
  287.                 $video_id $match[1];
  288.                 $jsonData json_decodeGeneralHelper::curlGet('http://vimeo.com/api/oembed.json?url=' $vid['link'] . '&width=640'));
  289.                 if($jsonData === null) {
  290.                     unset($arrVids[$k]);
  291.                 } else {
  292.                     $arrVids[$k]['thumbnail'] = $jsonData->thumbnail_url_with_play_button;
  293.                     $arrVids[$k]['embedHTML'] = $jsonData->html;
  294.                 }
  295.             }
  296.         }
  297.         return $arrVids;
  298.     }
  299.     /**
  300.      * Get the alias key
  301.      * @return string
  302.      */
  303.     public function getPageTitle()
  304.     {
  305.         $strType $this->getInstitutionType() !== null $this->getInstitutionType()->name 'Arts Organization';
  306.         return $this->name ' | ' $strType ' | ArtsHub of Western Massachusetts';
  307.     }
  308.     /**
  309.      * Get the alias key
  310.      * @return string
  311.      */
  312.     public function getPageDescription()
  313.     {
  314.         $strDesc strlen($this->description) > StringUtil::substr(strip_tags($this->description), 100) : 'Information about ' $this->name;
  315.         return $strDesc ' Visit the ArtsHub of Western Massachusetts to learn more about '$this->name .' and other arts organizations in western MA.';
  316.     }
  317.     /**
  318.      * Return the unique form ID for the item
  319.      *
  320.      * @return string
  321.      */
  322.     public function getFormId()
  323.     {
  324.         return $this->strFormId;
  325.     }
  326.     /**
  327.      * Get the alias key
  328.      * @return string
  329.      */
  330.     public static function getAliasKey()
  331.     {
  332.         return 'detail';
  333.     }
  334.     /**
  335.      * Find all published items
  336.      *
  337.      * @param array $arrOptions
  338.      *
  339.      * @return Collection|Item[]|null
  340.      */
  341.     public static function findPublished(array $arrOptions = array())
  342.     {
  343.         return static::findPublishedBy(array(), array(), $arrOptions);
  344.     }
  345.     /**
  346.      * Find a single item by its ID or alias
  347.      *
  348.      * @param mixed $varId      The ID or alias
  349.      * @param array $arrOptions An optional options array
  350.      *
  351.      * @return Item|Collection|null
  352.      */
  353.     public static function findPublishedByIdOrAlias($varId, array $arrOptions = array())
  354.     {
  355.         $t = static::$strTable;
  356.         $arrColumns = array("($t.id=? OR $t.alias=?)");
  357.         $arrValues  = array(is_numeric($varId) ? $varId 0$varId);
  358.         $arrOptions array_merge(
  359.             array(
  360.                 'limit'     => 1,
  361.                 'return'    => 'Model'
  362.             ),
  363.             $arrOptions
  364.         );
  365.         return static::findPublishedBy($arrColumns$arrValues$arrOptions);
  366.     }
  367.     /**
  368.      * Find published items by condition
  369.      *
  370.      * @param mixed $arrColumns
  371.      * @param mixed $arrValues
  372.      * @param array $arrOptions
  373.      *
  374.      * @return Collection|null
  375.      */
  376.     public static function findPublishedBy($arrColumns$arrValues, array $arrOptions = array())
  377.     {
  378.         $t = static::$strTable;
  379.         $arrValues = (array) $arrValues;
  380.         if (!is_array($arrColumns)) {
  381.             $arrColumns = array(static::$strTable '.' $arrColumns '=?');
  382.         }
  383.         // Add publish check to $arrColumns as the first item to enable SQL keys
  384.         if (BE_USER_LOGGED_IN !== true) {
  385.             array_unshift(
  386.                 $arrColumns,
  387.                 "$t.published='1'"
  388.             );
  389.         }
  390.         return static::findBy($arrColumns$arrValues$arrOptions);
  391.     }
  392.     /**
  393.      * @inheritdoc
  394.      */
  395.     public function getCategories($blnPublished false)
  396.     {
  397.         $c Discipline::getTable();
  398.         $key = ($blnPublished 'published' 'all');
  399.         if (null === $this->arrCategories || !isset($this->arrCategories[$key])) {
  400.             if ($blnPublished) {
  401.                 $options          Discipline::getFindByPidForPublishedPagesOptions($this->id);
  402.                 $options['table'] = Discipline::getTable();
  403.                 $query            QueryBuilder::find($options);
  404.                 $values           = (array) $options['value'];
  405.             } else {
  406.                 $query  "SELECT page_id FROM $c WHERE pid=?";
  407.                 $values = array($this->id);
  408.             }
  409.             $objCategories Database::getInstance()->prepare($query)->execute($values);
  410.             $this->arrCategories[$key] = $objCategories->fetchEach('page_id');
  411.             // Sort categories by the backend drag&drop
  412.             $arrOrder StringUtil::deserialize($this->orderPages);
  413.             if (!empty($arrOrder) && is_array($arrOrder)) {
  414.                 $this->arrCategories[$key] = array_unique(
  415.                     array_merge(
  416.                         array_intersect(
  417.                             $arrOrder,
  418.                             $this->arrCategories[$key]
  419.                         ),
  420.                         $this->arrCategories[$key]
  421.                     )
  422.                 );
  423.             }
  424.         }
  425.         return $this->arrCategories[$key];
  426.     }
  427.     /**
  428.      * Return collection of published items by categories
  429.      *
  430.      * @param array $arrCategories
  431.      * @param array $arrOptions
  432.      *
  433.      * @return Collection|Item[]|null
  434.      */
  435.     public static function findPublishedByCategories(array $arrCategories, array $arrOptions = array())
  436.     {
  437.         return static::findPublishedBy(
  438.             array('c.page_id IN (' implode(','array_map('intval'$arrCategories)) . ')'),
  439.             null,
  440.             $arrOptions
  441.         );
  442.     }
  443.     /**
  444.      * Find a single published item by its ID or alias
  445.      *
  446.      * @param mixed $varId      The ID or alias
  447.      * @param array $arrOptions An optional options array
  448.      *
  449.      * @return Item|null     The model or null if the result is empty
  450.      */
  451.     public static function findAvailableByIdOrAlias($varId, array $arrOptions = array())
  452.     {
  453.         $objItem = static::findPublishedByIdOrAlias($varId$arrOptions);
  454.         if (null === $objItem) {
  455.             return null;
  456.         }
  457.         return $objItem;
  458.     }
  459. }