parse() публичный Метод

Add a hook to modify the template output
public parse ( ) : string
Результат string The template markup
 /**
  * Compile the current element
  */
 protected function compile()
 {
     /**
      * Check if module template should be overwritten
      */
     if ($this->gcs_modTemplate != $this->strTemplate && !empty($this->gcs_modTemplate)) {
         $this->Template = new \FrontendTemplate($this->gcs_modTemplate);
     }
     /**
      * Check if javascript is already included
      * **There is no possibility to use 2 JS custom searches at once**
      */
     if (!$GLOBALS['gcs']['jsAdded']) {
         $GLOBALS['gcs']['jsAdded'] = true;
         $objJSTemplate = new FrontendTemplate('js_gcs_searchEngine');
         $objJSTemplate->gcs_engineID = $this->gcs_engineID;
         $this->Template->gcs_js = $objJSTemplate->parse();
     } else {
         $this->Template->gcs_js = null;
     }
     /**
      * Create an SearchEngine DataContainer
      * and feed it with the ModuleModel
      */
     $objSearchEngine = new DCSearchEngine();
     $objSearchEngine->setDataFromModel($this->objModel);
     // assign the SearchEngine to the Template
     $this->Template->GSE = $objSearchEngine;
 }
Пример #2
0
 /**
  * Generate the content element
  */
 protected function compile()
 {
     $arrMediaPlatforms = array('ivvimeo' => array('template' => 'inlinemedia_vimeo', 'media' => $this->inlinemedia_media_vi, 'width' => deserialize($this->inlinemedia_width), 'height' => deserialize($this->inlinemedia_height), 'autoplay' => $this->inlinemedia_autoplay, 'color' => $this->inlinemedia_color, 'loop' => $this->inlinemedia_loop, 'params' => $this->inlinemedia_params, 'videocaption' => $this->inlinemedia_videocaption), 'ivyoutube' => array('template' => 'inlinemedia_youtube', 'media' => $this->inlinemedia_media_yt, 'width' => deserialize($this->inlinemedia_width), 'height' => deserialize($this->inlinemedia_height), 'autoplay' => $this->inlinemedia_autoplay, 'suggest' => $this->inlinemedia_suggest, 'url' => $this->inlinemedia_privacy ? 'http://www.youtube-nocookie.com' : 'http://www.youtube.com', 'params' => $this->inlinemedia_params, 'videocaption' => $this->inlinemedia_videocaption), 'ivdailymotion' => array('template' => 'inlinemedia_dailymotion', 'media' => $this->inlinemedia_media_dm, 'width' => deserialize($this->inlinemedia_width), 'height' => deserialize($this->inlinemedia_height), 'color' => $this->inlinemedia_color, 'color_background' => $this->inlinemedia_backgroundcolor, 'color_highlight' => $this->inlinemedia_highlightcolor, 'mediainfos' => $this->inlinemedia_mediainfos, 'logo' => $this->inlinemedia_logo, 'quality' => $this->inlinemedia_quality, 'params' => $this->inlinemedia_params, 'videocaption' => $this->inlinemedia_videocaption), 'ivsoundcloud' => array('template' => 'inlinemedia_soundcloud', 'media' => $this->inlinemedia_media_sc, 'autoplay' => $this->inlinemedia_autoplay, 'color' => $this->inlinemedia_color, 'artwork' => $this->inlinemedia_artwork, 'params' => $this->inlinemedia_params, 'videocaption' => $this->inlinemedia_videocaption));
     $objMediaPlayerTemplate = new FrontendTemplate($arrMediaPlatforms[$this->inlinemedia_source]['template']);
     unset($arrMediaPlatforms[$this->inlinemedia_source]['template']);
     $objMediaPlayerTemplate->setData($arrMediaPlatforms[$this->inlinemedia_source]);
     $this->Template->media = $objMediaPlayerTemplate->parse();
     $this->Template->videocaption = $this->inlinemedia_videocaption;
 }
 /**
  * Generate the widget and return it as string
  *
  * @return string The widget markup
  */
 public function generate()
 {
     $this->bindDateTimePickerFileAndScript();
     $template = new FrontendTemplate('form_bootstrap_calendar_field');
     $template->input = parent::generate();
     $template->id = $this->id;
     $template->icon = $this->bsDateImage;
     $template->name = $this->name;
     return $template->parse();
 }
Пример #4
0
 protected function compile()
 {
     \System::loadLanguageFile('fe_swatchbook');
     $swTemplate = new \FrontendTemplate($this->swatchbook_Template);
     $arrIds = deserialize($this->colorSources, true);
     if (count($arrIds) < 1) {
         $swTemplate->noResult = $GLOBALS['TL_LANG']['FE']['swatchbook']['noResult'];
         $this->Template->element = $swTemplate->parse();
     } else {
         $GLOBALS['TL_CSS'][] = 'bundles/swatchbook/css/style.css';
         $GLOBALS['TL_CSS'][] = 'bundles/swatchbook/css/divElements.css';
         $GLOBALS['TL_HEAD'][] = '<script src="bundles/swatchbook/js/modernizr.custom.79639.js"></script>';
         $GLOBALS['TL_JQUERY'][] = '<script src="bundles/swatchbook/js/jquery.swatchbook.js"></script>';
         $GLOBALS['TL_MOOTOOLS'] = '<script src="bundles/swatchbook/js/jquery-2.1.4.min.js"></script>';
         $source = SwatchbookModel::findMultipleByIds($arrIds);
         while ($source->next()) {
             $arrSource[$source->id] = $source->title;
         }
         $swTemplate->id = $this->id;
         $swTemplate->sources = $arrSource;
         $swTemplate->href = $this->Environment->requestUri;
         $swTemplate->cssID = $this->cssID[0];
         $swTemplate->class = $this->cssID[1];
         $swTemplate->countPallets = count($source);
         $swTemplate->palletText = $GLOBALS['TL_LANG']['FE']['swatchbook']['fe_pallet'];
         if (\Input::post('id') == NULL) {
             reset($arrSource);
             $id = key($arrSource);
         } else {
             $id = \Input::post('id');
         }
         /* Load Colors */
         $objTemplate = new \FrontendTemplate('swc_swatchbookItems');
         $objElements = SwatchbookColorsModel::getColorList($id);
         while ($objElements->next()) {
             $childList[$objElements->id] = $objElements->title;
         }
         // Palette Message
         $paletteMsg = SwatchbookModel::getPalletMessage($id);
         $objTemplate->id = $id;
         $objTemplate->child_list = $childList;
         $objTemplate->text = $paletteMsg->text;
         $objTemplate->advice = $paletteMsg->advice;
         $swTemplate->colorsPalette = $objTemplate->parse();
         $this->Template->element = $swTemplate->parse();
     }
 }
Пример #5
0
 protected function compile()
 {
     $arrIds = deserialize($this->colorSources, true);
     if (count($arrIds) < 1) {
         $this->Template->noResult = $GLOBALS['TL_LANG']['FE']['swatchBook']['noResult'];
     } else {
         /**
          * Load Backend or Frontend
          *  CSS/JavaScript
          */
         if (TL_MODE == 'FE') {
             $GLOBALS['TL_HEAD'][] = '<script src="system/modules/swatchBook/assets/js/modernizr.custom.79639.js"></script>';
             $GLOBALS['TL_JQUERY'][] = '<script src="system/modules/swatchBook/assets/js/jquery.swatchbook.js"></script>';
             $GLOBALS['TL_CSS'][] = 'system/modules/swatchBook/assets/css/style.css';
             $GLOBALS['TL_CSS'][] = 'system/modules/swatchBook/assets/css/divElements.css';
         }
         $source = SwatchBookModel::findMultipleByIds($arrIds);
         while ($source->next()) {
             $arrSource[$source->id] = $source->title;
         }
         $this->Template->id = $this->id;
         $this->Template->sources = $arrSource;
         $this->Template->href = $this->Environment->requestUri;
         $this->Template->countPalettes = count($source);
         if (\Input::post('id') == NULL) {
             reset($arrSource);
             $id = key($arrSource);
         } else {
             $id = \Input::post('id');
         }
         /* Load Colors */
         $objTemplate = new \FrontendTemplate('ce_swatchBookItems');
         $objElements = SwatchBookColorsModel::getColorList($id);
         while ($objElements->next()) {
             $childList[$objElements->id] = $objElements->title;
         }
         // Palette Message
         $paletteMsg = SwatchBookModel::getPaletteMessage($id);
         $objTemplate->id = $id;
         $objTemplate->linkId = $id;
         $objTemplate->child_list = $childList;
         $objTemplate->text = $paletteMsg->text;
         $objTemplate->advice = $paletteMsg->advice;
         $this->Template->colorsPalette = $objTemplate->parse();
     }
 }
Пример #6
0
 protected function compile()
 {
     $db = \Database::getInstance();
     $intID = Input::get('companyID');
     $objCompany = CompanyModel::findByPk($intID);
     if ($objCompany) {
         global $objPage;
         $objPage->pageTitle = $objCompany->company;
         $objTemplate = new FrontendTemplate('company_detail');
         $objFile = FilesModel::findByPk($objCompany->logo);
         $arrSize = deserialize($this->imgSize);
         // Get Categories
         $strCategory = '';
         $arrCategories = deserialize($objCompany->category);
         if (count($arrCategories) > 0) {
             $arrCategory = array();
             $objCompanyCategories = $db->prepare("SELECT * FROM tl_company_category WHERE id IN(" . implode(',', $arrCategories) . ")")->execute();
             while ($objCompanyCategories->next()) {
                 $arrCategory[] = $objCompanyCategories->title;
             }
             $strCategory = implode(', ', $arrCategory);
         }
         $objTemplate->company = $objCompany->company;
         $objTemplate->contact_person = $objCompany->contact_person;
         $objTemplate->category = $strCategory;
         $objTemplate->street = $objCompany->street;
         $objTemplate->postal_code = $objCompany->postal_code;
         $objTemplate->city = $objCompany->city;
         $objTemplate->phone = $objCompany->phone;
         $objTemplate->fax = $objCompany->fax;
         $objTemplate->email = $objCompany->email;
         $objTemplate->homepage = $objCompany->homepage;
         $objTemplate->lat = $objCompany->lat;
         $objTemplate->lng = $objCompany->lng;
         $objTemplate->logo = \Image::get($objFile->path, $arrSize[0], $arrSize[1], $arrSize[2]);
         $objTemplate->imageWidth = $arrSize[0];
         $objTemplate->imageHeight = $arrSize[1];
         $objTemplate->information = $objCompany->information;
         $this->Template->strHtml = $objTemplate->parse();
     }
 }
Пример #7
0
 /**
  * Add comments to a template
  *
  * @param FrontendTemplate|object $objTemplate
  * @param \stdClass               $objConfig
  * @param string                  $strSource
  * @param integer                 $intParent
  * @param mixed                   $varNotifies
  */
 public function addCommentsToTemplate(FrontendTemplate $objTemplate, \stdClass $objConfig, $strSource, $intParent, $varNotifies)
 {
     /** @var PageModel $objPage */
     global $objPage;
     $limit = 0;
     $offset = 0;
     $total = 0;
     $gtotal = 0;
     $arrComments = array();
     $objTemplate->comments = array();
     // see #4064
     // Pagination
     if ($objConfig->perPage > 0) {
         // Get the total number of comments
         $intTotal = \CommentsModel::countPublishedBySourceAndParent($strSource, $intParent);
         $total = $gtotal = $intTotal;
         // Calculate the key (e.g. tl_form_field becomes page_cff12)
         $key = '';
         $chunks = explode('_', substr($strSource, strncmp($strSource, 'tl_', 3) === 0 ? 3 : 0));
         foreach ($chunks as $chunk) {
             $key .= substr($chunk, 0, 1);
         }
         // Get the current page
         $id = 'page_c' . $key . $intParent;
         // see #4141
         $page = \Input::get($id) !== null ? \Input::get($id) : 1;
         // Do not index or cache the page if the page number is outside the range
         if ($page < 1 || $page > max(ceil($total / $objConfig->perPage), 1)) {
             throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
         }
         // Set limit and offset
         $limit = $objConfig->perPage;
         $offset = ($page - 1) * $objConfig->perPage;
         // Initialize the pagination menu
         $objPagination = new \Pagination($total, $objConfig->perPage, \Config::get('maxPaginationLinks'), $id);
         $objTemplate->pagination = $objPagination->generate("\n  ");
     }
     $objTemplate->allowComments = true;
     // Get all published comments
     if ($limit) {
         $objComments = \CommentsModel::findPublishedBySourceAndParent($strSource, $intParent, $objConfig->order == 'descending', $limit, $offset);
     } else {
         $objComments = \CommentsModel::findPublishedBySourceAndParent($strSource, $intParent, $objConfig->order == 'descending');
     }
     // Parse the comments
     if ($objComments !== null && ($total = $objComments->count()) > 0) {
         $count = 0;
         if ($objConfig->template == '') {
             $objConfig->template = 'com_default';
         }
         /** @var FrontendTemplate|object $objPartial */
         $objPartial = new \FrontendTemplate($objConfig->template);
         while ($objComments->next()) {
             $objPartial->setData($objComments->row());
             // Clean the RTE output
             $objPartial->comment = \StringUtil::toHtml5($objComments->comment);
             $objPartial->comment = trim(str_replace(array('{{', '}}'), array('&#123;&#123;', '&#125;&#125;'), $objPartial->comment));
             $objPartial->datim = \Date::parse($objPage->datimFormat, $objComments->date);
             $objPartial->date = \Date::parse($objPage->dateFormat, $objComments->date);
             $objPartial->class = ($count < 1 ? ' first' : '') . ($count >= $total - 1 ? ' last' : '') . ($count % 2 == 0 ? ' even' : ' odd');
             $objPartial->by = $GLOBALS['TL_LANG']['MSC']['com_by'];
             $objPartial->id = 'c' . $objComments->id;
             $objPartial->timestamp = $objComments->date;
             $objPartial->datetime = date('Y-m-d\\TH:i:sP', $objComments->date);
             $objPartial->addReply = false;
             // Reply
             if ($objComments->addReply && $objComments->reply != '') {
                 if (($objAuthor = $objComments->getRelated('author')) instanceof UserModel) {
                     $objPartial->addReply = true;
                     $objPartial->rby = $GLOBALS['TL_LANG']['MSC']['com_reply'];
                     $objPartial->reply = $this->replaceInsertTags($objComments->reply);
                     $objPartial->author = $objAuthor;
                     // Clean the RTE output
                     $objPartial->reply = \StringUtil::toHtml5($objPartial->reply);
                 }
             }
             $arrComments[] = $objPartial->parse();
             ++$count;
         }
     }
     $objTemplate->comments = $arrComments;
     $objTemplate->addComment = $GLOBALS['TL_LANG']['MSC']['addComment'];
     $objTemplate->name = $GLOBALS['TL_LANG']['MSC']['com_name'];
     $objTemplate->email = $GLOBALS['TL_LANG']['MSC']['com_email'];
     $objTemplate->website = $GLOBALS['TL_LANG']['MSC']['com_website'];
     $objTemplate->commentsTotal = $limit ? $gtotal : $total;
     // Add a form to create new comments
     $this->renderCommentForm($objTemplate, $objConfig, $strSource, $intParent, $varNotifies);
 }
Пример #8
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $items = array();
     $groups = array();
     // Get all groups of the current front end user
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $groups = $this->User->groups;
     }
     // Get all active pages
     $objPages = \PageModel::findPublishedRegularWithoutGuestsByIds($this->pages);
     // Return if there are no pages
     if ($objPages === null) {
         return;
     }
     $arrPages = array();
     // Sort the array keys according to the given order
     if ($this->orderPages != '') {
         $tmp = \StringUtil::deserialize($this->orderPages);
         if (!empty($tmp) && is_array($tmp)) {
             $arrPages = array_map(function () {
             }, array_flip($tmp));
         }
     }
     // Add the items to the pre-sorted array
     while ($objPages->next()) {
         $arrPages[$objPages->id] = $objPages->current();
     }
     $arrPages = array_values(array_filter($arrPages));
     // Set default template
     if ($this->navigationTpl == '') {
         $this->navigationTpl = 'nav_default';
     }
     /** @var FrontendTemplate|object $objTemplate */
     $objTemplate = new \FrontendTemplate($this->navigationTpl);
     $objTemplate->type = get_class($this);
     $objTemplate->cssID = $this->cssID;
     // see #4897 and 6129
     $objTemplate->level = 'level_1';
     /** @var PageModel[] $arrPages */
     foreach ($arrPages as $objModel) {
         $_groups = \StringUtil::deserialize($objModel->groups);
         // Do not show protected pages unless a back end or front end user is logged in
         if (!$objModel->protected || BE_USER_LOGGED_IN || is_array($_groups) && count(array_intersect($_groups, $groups)) || $this->showProtected) {
             // Get href
             switch ($objModel->type) {
                 case 'redirect':
                     $href = $objModel->url;
                     break;
                 case 'forward':
                     if (($objNext = $objModel->getRelated('jumpTo')) instanceof PageModel) {
                         /** @var PageModel $objNext */
                         $href = $objNext->getFrontendUrl();
                         break;
                     }
                     // DO NOT ADD A break; STATEMENT
                 // DO NOT ADD A break; STATEMENT
                 default:
                     $href = $objModel->getFrontendUrl();
                     break;
             }
             $trail = in_array($objModel->id, $objPage->trail);
             // Active page
             if ($objPage->id == $objModel->id && $href == \Environment::get('request')) {
                 $strClass = trim($objModel->cssClass);
                 $row = $objModel->row();
                 $row['isActive'] = true;
                 $row['isTrail'] = false;
                 $row['class'] = trim('active ' . $strClass);
                 $row['title'] = \StringUtil::specialchars($objModel->title, true);
                 $row['pageTitle'] = \StringUtil::specialchars($objModel->pageTitle, true);
                 $row['link'] = $objModel->title;
                 $row['href'] = $href;
                 $row['nofollow'] = strncmp($objModel->robots, 'noindex,nofollow', 16) === 0;
                 $row['target'] = '';
                 $row['description'] = str_replace(array("\n", "\r"), array(' ', ''), $objModel->description);
                 // Override the link target
                 if ($objModel->type == 'redirect' && $objModel->target) {
                     $row['target'] = ' target="_blank"';
                 }
                 $items[] = $row;
             } else {
                 $strClass = trim($objModel->cssClass . ($trail ? ' trail' : ''));
                 $row = $objModel->row();
                 $row['isActive'] = false;
                 $row['isTrail'] = $trail;
                 $row['class'] = $strClass;
                 $row['title'] = \StringUtil::specialchars($objModel->title, true);
                 $row['pageTitle'] = \StringUtil::specialchars($objModel->pageTitle, true);
                 $row['link'] = $objModel->title;
                 $row['href'] = $href;
                 $row['nofollow'] = strncmp($objModel->robots, 'noindex,nofollow', 16) === 0;
                 $row['target'] = '';
                 $row['description'] = str_replace(array("\n", "\r"), array(' ', ''), $objModel->description);
                 // Override the link target
                 if ($objModel->type == 'redirect' && $objModel->target) {
                     $row['target'] = ' target="_blank"';
                 }
                 $items[] = $row;
             }
         }
     }
     // Add classes first and last
     $items[0]['class'] = trim($items[0]['class'] . ' first');
     $last = count($items) - 1;
     $items[$last]['class'] = trim($items[$last]['class'] . ' last');
     $objTemplate->items = $items;
     $this->Template->request = \Environment::get('indexFreeRequest');
     $this->Template->skipId = 'skipNavigation' . $this->id;
     $this->Template->skipNavigation = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['skipNavigation']);
     $this->Template->items = !empty($items) ? $objTemplate->parse() : '';
 }
 /**
  * Render a news.
  *
  * @param GetNewsEvent             $event           The event.
  *
  * @param string                   $eventName       The event name.
  *
  * @param EventDispatcherInterface $eventDispatcher The event dispatcher.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function handleNews(GetNewsEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
 {
     if ($event->getNewsHtml()) {
         return;
     }
     $newsArchiveCollection = NewsArchiveModel::findAll();
     $newsArchiveIds = $newsArchiveCollection ? $newsArchiveCollection->fetchEach('id') : array();
     $newsModel = NewsModel::findPublishedByParentAndIdOrAlias($event->getNewsId(), $newsArchiveIds);
     if (!$newsModel) {
         return;
     }
     $newsModel = $newsModel->current();
     $newsArchiveModel = $newsModel->getRelated('pid');
     $objPage = PageModel::findWithDetails($newsArchiveModel->jumpTo);
     $objTemplate = new FrontendTemplate($event->getTemplate());
     $objTemplate->setData($newsModel->row());
     $objTemplate->class = $newsModel->cssClass != '' ? ' ' . $newsModel->cssClass : '';
     $objTemplate->newsHeadline = $newsModel->headline;
     $objTemplate->subHeadline = $newsModel->subheadline;
     $objTemplate->hasSubHeadline = $newsModel->subheadline ? true : false;
     $objTemplate->linkHeadline = $this->generateLink($eventDispatcher, $newsModel->headline, $newsModel);
     $objTemplate->more = $this->generateLink($eventDispatcher, $GLOBALS['TL_LANG']['MSC']['more'], $newsModel, false, true);
     $objTemplate->link = $this->generateNewsUrl($eventDispatcher, $newsModel);
     $objTemplate->archive = $newsModel->getRelated('pid');
     $objTemplate->count = 0;
     $objTemplate->text = '';
     // Clean the RTE output.
     if ($newsModel->teaser != '') {
         if ($objPage->outputFormat == 'xhtml') {
             $objTemplate->teaser = StringHelper::toXhtml($newsModel->teaser);
         } else {
             $objTemplate->teaser = StringHelper::toHtml5($newsModel->teaser);
         }
         $objTemplate->teaser = StringHelper::encodeEmail($objTemplate->teaser);
     }
     // Display the "read more" button for external/article links.
     if ($newsModel->source != 'default') {
         $objTemplate->text = true;
     } else {
         // Compile the news text.
         $objElement = ContentModel::findPublishedByPidAndTable($newsModel->id, 'tl_news');
         if ($objElement !== null) {
             while ($objElement->next()) {
                 $getContentElementEvent = new GetContentElementEvent($objElement->id);
                 $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GET_CONTENT_ELEMENT, $getContentElementEvent);
                 $objTemplate->text .= $getContentElementEvent->getContentElementHtml();
             }
         }
     }
     $arrMeta = $this->getMetaFields($newsModel);
     // Add the meta information.
     $objTemplate->date = $arrMeta['date'];
     $objTemplate->hasMetaFields = !empty($arrMeta);
     $objTemplate->numberOfComments = $arrMeta['ccount'];
     $objTemplate->commentCount = $arrMeta['comments'];
     $objTemplate->timestamp = $newsModel->date;
     $objTemplate->author = $arrMeta['author'];
     $objTemplate->datetime = date('Y-m-d\\TH:i:sP', $newsModel->date);
     $objTemplate->addImage = false;
     // Add an image.
     if ($newsModel->addImage && $newsModel->singleSRC != '') {
         $objModel = FilesModel::findByUuid($newsModel->singleSRC);
         if ($objModel === null) {
             if (!Validator::isUuid($newsModel->singleSRC)) {
                 $objTemplate->text = '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>';
             }
         } elseif (is_file(TL_ROOT . '/' . $objModel->path)) {
             // Do not override the field now that we have a model registry (see #6303).
             $arrArticle = $newsModel->row();
             // Override the default image size.
             // This is always false!
             if ($this->imgSize != '') {
                 $size = deserialize($this->imgSize);
                 if ($size[0] > 0 || $size[1] > 0) {
                     $arrArticle['size'] = $this->imgSize;
                 }
             }
             $arrArticle['singleSRC'] = $objModel->path;
             $addImageToTemplateEvent = new AddImageToTemplateEvent($arrArticle, $objTemplate);
             $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_IMAGE_TO_TEMPLATE, $addImageToTemplateEvent);
         }
     }
     $objTemplate->enclosure = array();
     // Add enclosures.
     if ($newsModel->addEnclosure) {
         $addEnclosureToTemplateEvent = new AddEnclosureToTemplateEvent($newsModel->row(), $objTemplate);
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_ENCLOSURE_TO_TEMPLATE, $addEnclosureToTemplateEvent);
     }
     $news = $objTemplate->parse();
     $event->setNewsHtml($news);
 }
Пример #10
0
 /**
  * Create all footer scripts
  *
  * @param \LayoutModel $objLayout
  */
 protected function createFooterScripts($objLayout)
 {
     $strScripts = '';
     // jQuery
     if ($objLayout->addJQuery) {
         $arrJquery = deserialize($objLayout->jquery, true);
         foreach ($arrJquery as $strTemplate) {
             if ($strTemplate != '') {
                 $objTemplate = new \FrontendTemplate($strTemplate);
                 $strScripts .= $objTemplate->parse();
             }
         }
         // Add a placeholder for dynamic scripts (see #4203)
         $strScripts .= '[[TL_JQUERY]]';
     }
     // MooTools
     if ($objLayout->addMooTools) {
         $arrMootools = deserialize($objLayout->mootools, true);
         foreach ($arrMootools as $strTemplate) {
             if ($strTemplate != '') {
                 $objTemplate = new \FrontendTemplate($strTemplate);
                 $strScripts .= $objTemplate->parse();
             }
         }
         // Add a placeholder for dynamic scripts (see #4203)
         $strScripts .= '[[TL_MOOTOOLS]]';
     }
     // Add the framework agnostic JavaScripts
     if ($objLayout->scripts != '') {
         $arrScripts = deserialize($objLayout->scripts, true);
         foreach ($arrScripts as $strTemplate) {
             if ($strTemplate != '') {
                 $objTemplate = new \FrontendTemplate($strTemplate);
                 $strScripts .= $objTemplate->parse();
             }
         }
     }
     // Add a placeholder for dynamic scripts (see #4203, #5583)
     $strScripts .= '[[TL_BODY]]';
     // Add the custom JavaScript
     if ($objLayout->script != '') {
         $strScripts .= "\n" . trim($objLayout->script) . "\n";
     }
     // Add the analytics scripts
     if ($objLayout->analytics != '') {
         $arrAnalytics = deserialize($objLayout->analytics, true);
         foreach ($arrAnalytics as $strTemplate) {
             if ($strTemplate != '') {
                 $objTemplate = new \FrontendTemplate($strTemplate);
                 $strScripts .= $objTemplate->parse();
             }
         }
     }
     $this->Template->mootools = $strScripts;
 }
 /**
  * Render a calendar event.
  *
  * @param GetCalendarEventEvent    $event           The event.
  *
  * @param string                   $eventName       The event name.
  *
  * @param EventDispatcherInterface $eventDispatcher The event dispatcher.
  *
  * @return void
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function handleEvent(GetCalendarEventEvent $event, $eventName, EventDispatcherInterface $eventDispatcher)
 {
     if ($event->getCalendarEventHtml()) {
         return;
     }
     $calendarCollection = CalendarModel::findAll();
     if (!$calendarCollection) {
         return;
     }
     $calendarIds = $calendarCollection->fetchEach('id');
     $eventModel = CalendarEventsModel::findPublishedByParentAndIdOrAlias($event->getCalendarEventId(), $calendarIds);
     if (!$eventModel) {
         return;
     }
     $calendarModel = $eventModel->getRelated('pid');
     $objPage = PageModel::findWithDetails($calendarModel->jumpTo);
     if ($event->getDateTime()) {
         $selectedStartDateTime = clone $event->getDateTime();
         $selectedStartDateTime->setTime(date('H', $eventModel->startTime), date('i', $eventModel->startTime), date('s', $eventModel->startTime));
         $secondsBetweenStartAndEndTime = $eventModel->endTime - $eventModel->startTime;
         $intStartTime = $selectedStartDateTime->getTimestamp();
         $intEndTime = $intStartTime + $secondsBetweenStartAndEndTime;
     } else {
         $intStartTime = $eventModel->startTime;
         $intEndTime = $eventModel->endTime;
     }
     $span = Calendar::calculateSpan($intStartTime, $intEndTime);
     // Do not show dates in the past if the event is recurring (see #923).
     if ($eventModel->recurring) {
         $arrRange = deserialize($eventModel->repeatEach);
         while ($intStartTime < time() && $intEndTime < $eventModel->repeatEnd) {
             $intStartTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intStartTime);
             $intEndTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intEndTime);
         }
     }
     if ($objPage->outputFormat == 'xhtml') {
         $strTimeStart = '';
         $strTimeEnd = '';
         $strTimeClose = '';
     } else {
         $strTimeStart = '';
         $strTimeEnd = '';
         $strTimeClose = '';
         // @codingStandardsIgnoreStart
         /*
         TODO $this->date and $this->time is used in the <a> title attribute and cannot contain HTML!
         $strTimeStart = '<time datetime="' . date('Y-m-d\TH:i:sP', $intStartTime) . '">';
         $strTimeEnd   = '<time datetime="' . date('Y-m-d\TH:i:sP', $intEndTime) . '">';
         $strTimeClose = '</time>';
         */
         // @codingStandardsIgnoreEnd
     }
     // Get date.
     if ($span > 0) {
         $date = $strTimeStart . Date::parse($eventModel->addTime ? $objPage->datimFormat : $objPage->dateFormat, $intStartTime) . $strTimeClose . ' - ' . $strTimeEnd . Date::parse($eventModel->addTime ? $objPage->datimFormat : $objPage->dateFormat, $intEndTime) . $strTimeClose;
     } elseif ($intStartTime == $intEndTime) {
         $date = $strTimeStart . Date::parse($objPage->dateFormat, $intStartTime) . ($eventModel->addTime ? ' (' . Date::parse($objPage->timeFormat, $intStartTime) . ')' : '') . $strTimeClose;
     } else {
         $date = $strTimeStart . Date::parse($objPage->dateFormat, $intStartTime) . ($eventModel->addTime ? ' (' . Date::parse($objPage->timeFormat, $intStartTime) . $strTimeClose . ' - ' . $strTimeEnd . Date::parse($objPage->timeFormat, $intEndTime) . ')' : '') . $strTimeClose;
     }
     $until = '';
     $recurring = '';
     // Recurring event.
     if ($eventModel->recurring) {
         $arrRange = deserialize($eventModel->repeatEach);
         $strKey = 'cal_' . $arrRange['unit'];
         $recurring = sprintf($GLOBALS['TL_LANG']['MSC'][$strKey], $arrRange['value']);
         if ($eventModel->recurrences > 0) {
             $until = sprintf($GLOBALS['TL_LANG']['MSC']['cal_until'], Date::parse($objPage->dateFormat, $eventModel->repeatEnd));
         }
     }
     // Override the default image size.
     // This is always false.
     if ($this->imgSize != '') {
         $size = deserialize($this->imgSize);
         if ($size[0] > 0 || $size[1] > 0) {
             $eventModel->size = $this->imgSize;
         }
     }
     $objTemplate = new FrontendTemplate($event->getTemplate());
     $objTemplate->setData($eventModel->row());
     $objTemplate->date = $date;
     $objTemplate->start = $intStartTime;
     $objTemplate->end = $intEndTime;
     $objTemplate->class = $eventModel->cssClass != '' ? ' ' . $eventModel->cssClass : '';
     $objTemplate->recurring = $recurring;
     $objTemplate->until = $until;
     $objTemplate->locationLabel = $GLOBALS['TL_LANG']['MSC']['location'];
     $objTemplate->details = '';
     $objElement = ContentModel::findPublishedByPidAndTable($eventModel->id, 'tl_calendar_events');
     if ($objElement !== null) {
         while ($objElement->next()) {
             $getContentElementEvent = new GetContentElementEvent($objElement->id);
             $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GET_CONTENT_ELEMENT, $getContentElementEvent);
             $objTemplate->details .= $getContentElementEvent->getContentElementHtml();
         }
         $objTemplate->hasDetails = true;
     }
     $objTemplate->addImage = false;
     // Add an image.
     if ($eventModel->addImage && $eventModel->singleSRC != '') {
         $objModel = FilesModel::findByUuid($eventModel->singleSRC);
         if ($objModel === null) {
             if (!Validator::isUuid($eventModel->singleSRC)) {
                 $objTemplate->text = '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>';
             }
         } elseif (is_file(TL_ROOT . '/' . $objModel->path)) {
             // Do not override the field now that we have a model registry (see #6303).
             $arrEvent = $eventModel->row();
             $arrEvent['singleSRC'] = $objModel->path;
             $addImageToTemplateEvent = new AddImageToTemplateEvent($arrEvent, $objTemplate);
             $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_IMAGE_TO_TEMPLATE, $addImageToTemplateEvent);
         }
     }
     $objTemplate->enclosure = array();
     // Add enclosures.
     if ($eventModel->addEnclosure) {
         $addEnclosureToTemplateEvent = new AddEnclosureToTemplateEvent($eventModel->row(), $objTemplate);
         $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_ENCLOSURE_TO_TEMPLATE, $addEnclosureToTemplateEvent);
     }
     $calendarEvent = $objTemplate->parse();
     $event->setCalendarEventHtml($calendarEvent);
 }
 /**
  * @param array $items
  *
  * @return string
  */
 protected function generateNavigationTemplate(array $items)
 {
     RowClass::withKey('class')->addFirstLast()->applyTo($items);
     $objTemplate = new FrontendTemplate($this->navigationTpl ?: 'nav_default');
     $objTemplate->setData($this->arrData);
     $objTemplate->level = 'level_1';
     $objTemplate->items = $items;
     return $objTemplate->parse();
 }
Пример #13
0
 /**
  * Replace insert tags with their values
  *
  * @param string  $strBuffer The text with the tags to be replaced
  * @param boolean $blnCache  If false, non-cacheable tags will be replaced
  *
  * @return string The text with the replaced tags
  */
 protected function doReplace($strBuffer, $blnCache)
 {
     /** @var PageModel $objPage */
     global $objPage;
     // Preserve insert tags
     if (\Config::get('disableInsertTags')) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $tags = preg_split('/{{([^{}]+)}}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
     if (count($tags) < 2) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $strBuffer = '';
     // Create one cache per cache setting (see #7700)
     static $arrItCache;
     $arrCache =& $arrItCache[$blnCache];
     for ($_rit = 0, $_cnt = count($tags); $_rit < $_cnt; $_rit += 2) {
         $strBuffer .= $tags[$_rit];
         $strTag = $tags[$_rit + 1];
         // Skip empty tags
         if ($strTag == '') {
             continue;
         }
         $flags = explode('|', $strTag);
         $tag = array_shift($flags);
         $elements = explode('::', $tag);
         // Load the value from cache
         if (isset($arrCache[$strTag]) && !in_array('refresh', $flags)) {
             $strBuffer .= $arrCache[$strTag];
             continue;
         }
         // Skip certain elements if the output will be cached
         if ($blnCache) {
             if ($elements[0] == 'date' || $elements[0] == 'ua' || $elements[0] == 'post' || $elements[0] == 'file' && !\Validator::isStringUuid($elements[1]) || $elements[1] == 'back' || $elements[1] == 'referer' || $elements[0] == 'request_token' || $elements[0] == 'toggle_view' || strncmp($elements[0], 'cache_', 6) === 0 || in_array('uncached', $flags)) {
                 /** @var FragmentHandler $fragmentHandler */
                 $fragmentHandler = \System::getContainer()->get('fragment.handler');
                 $strBuffer .= $fragmentHandler->render(new ControllerReference('contao.controller.insert_tags:renderAction', ['insertTag' => '{{' . $strTag . '}}']), 'esi');
                 continue;
             }
         }
         $arrCache[$strTag] = '';
         // Replace the tag
         switch (strtolower($elements[0])) {
             // Date
             case 'date':
                 $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('dateFormat'));
                 break;
                 // Accessibility tags
             // Accessibility tags
             case 'lang':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '</span>';
                 } else {
                     $arrCache[$strTag] = $arrCache[$strTag] = '<span lang="' . \StringUtil::specialchars($elements[1]) . '">';
                 }
                 break;
                 // Line break
             // Line break
             case 'br':
                 $arrCache[$strTag] = '<br>';
                 break;
                 // E-mail addresses
             // E-mail addresses
             case 'email':
             case 'email_open':
             case 'email_url':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $strEmail = \StringUtil::encodeEmail($elements[1]);
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'email':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" class="email">' . preg_replace('/\\?.*$/', '', $strEmail) . '</a>';
                         break;
                     case 'email_open':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" title="' . $strEmail . '" class="email">';
                         break;
                     case 'email_url':
                         $arrCache[$strTag] = $strEmail;
                         break;
                 }
                 break;
                 // Label tags
             // Label tags
             case 'label':
                 $keys = explode(':', $elements[1]);
                 if (count($keys) < 2) {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $file = $keys[0];
                 // Map the key (see #7217)
                 switch ($file) {
                     case 'CNT':
                         $file = 'countries';
                         break;
                     case 'LNG':
                         $file = 'languages';
                         break;
                     case 'MOD':
                     case 'FMD':
                         $file = 'modules';
                         break;
                     case 'FFL':
                         $file = 'tl_form_field';
                         break;
                     case 'CACHE':
                         $file = 'tl_page';
                         break;
                     case 'XPL':
                         $file = 'explain';
                         break;
                     case 'XPT':
                         $file = 'exception';
                         break;
                     case 'MSC':
                     case 'ERR':
                     case 'CTE':
                     case 'PTY':
                     case 'FOP':
                     case 'CHMOD':
                     case 'DAYS':
                     case 'MONTHS':
                     case 'UNITS':
                     case 'CONFIRM':
                     case 'DP':
                     case 'COLS':
                         $file = 'default';
                         break;
                 }
                 \System::loadLanguageFile($file);
                 if (count($keys) == 2) {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]];
                 } else {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]][$keys[2]];
                 }
                 break;
                 // Front end user
             // Front end user
             case 'user':
                 if (FE_USER_LOGGED_IN) {
                     $this->import('FrontendUser', 'User');
                     $value = $this->User->{$elements[1]};
                     if ($value == '') {
                         $arrCache[$strTag] = $value;
                         break;
                     }
                     $this->loadDataContainer('tl_member');
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['inputType'] == 'password') {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $value = \StringUtil::deserialize($value);
                     // Decrypt the value
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['encrypt']) {
                         $value = \Encryption::decrypt($value);
                     }
                     $rgxp = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['rgxp'];
                     $opts = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['options'];
                     $rfrc = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['reference'];
                     if ($rgxp == 'date') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('dateFormat'), $value);
                     } elseif ($rgxp == 'time') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('timeFormat'), $value);
                     } elseif ($rgxp == 'datim') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('datimFormat'), $value);
                     } elseif (is_array($value)) {
                         $arrCache[$strTag] = implode(', ', $value);
                     } elseif (is_array($opts) && array_is_assoc($opts)) {
                         $arrCache[$strTag] = isset($opts[$value]) ? $opts[$value] : $value;
                     } elseif (is_array($rfrc)) {
                         $arrCache[$strTag] = isset($rfrc[$value]) ? is_array($rfrc[$value]) ? $rfrc[$value][0] : $rfrc[$value] : $value;
                     } else {
                         $arrCache[$strTag] = $value;
                     }
                     // Convert special characters (see #1890)
                     $arrCache[$strTag] = \StringUtil::specialchars($arrCache[$strTag]);
                 }
                 break;
                 // Link
             // Link
             case 'link':
             case 'link_open':
             case 'link_url':
             case 'link_title':
             case 'link_target':
             case 'link_name':
                 $strTarget = null;
                 // Back link
                 if ($elements[1] == 'back') {
                     $strUrl = 'javascript:history.go(-1)';
                     $strTitle = $GLOBALS['TL_LANG']['MSC']['goBack'];
                     // No language files if the page is cached
                     if (!strlen($strTitle)) {
                         $strTitle = 'Go back';
                     }
                     $strName = $strTitle;
                 } elseif (strncmp($elements[1], 'http://', 7) === 0 || strncmp($elements[1], 'https://', 8) === 0) {
                     $strUrl = $elements[1];
                     $strTitle = $elements[1];
                     $strName = str_replace(array('http://', 'https://'), '', $elements[1]);
                 } else {
                     // User login page
                     if ($elements[1] == 'login') {
                         if (!FE_USER_LOGGED_IN) {
                             break;
                         }
                         $this->import('FrontendUser', 'User');
                         $elements[1] = $this->User->loginPage;
                     }
                     $objNextPage = \PageModel::findByIdOrAlias($elements[1]);
                     if ($objNextPage === null) {
                         break;
                     }
                     // Page type specific settings (thanks to Andreas Schempp)
                     switch ($objNextPage->type) {
                         case 'redirect':
                             $strUrl = $objNextPage->url;
                             if (strncasecmp($strUrl, 'mailto:', 7) === 0) {
                                 $strUrl = \StringUtil::encodeEmail($strUrl);
                             }
                             break;
                         case 'forward':
                             if ($objNextPage->jumpTo) {
                                 /** @var PageModel $objNext */
                                 $objNext = $objNextPage->getRelated('jumpTo');
                             } else {
                                 $objNext = \PageModel::findFirstPublishedRegularByPid($objNextPage->id);
                             }
                             if ($objNext instanceof PageModel) {
                                 $strUrl = $objNext->getFrontendUrl();
                                 break;
                             }
                             // DO NOT ADD A break; STATEMENT
                         // DO NOT ADD A break; STATEMENT
                         default:
                             $strUrl = $objNextPage->getFrontendUrl();
                             break;
                     }
                     $strName = $objNextPage->title;
                     $strTarget = $objNextPage->target ? ' target="_blank"' : '';
                     $strTitle = $objNextPage->pageTitle ?: $objNextPage->title;
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'link':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>%s</a>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget, $strName);
                         break;
                     case 'link_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget);
                         break;
                     case 'link_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'link_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($strTitle);
                         break;
                     case 'link_target':
                         $arrCache[$strTag] = $strTarget;
                         break;
                     case 'link_name':
                         $arrCache[$strTag] = $strName;
                         break;
                 }
                 break;
                 // Closing link tag
             // Closing link tag
             case 'link_close':
             case 'email_close':
                 $arrCache[$strTag] = '</a>';
                 break;
                 // Insert article
             // Insert article
             case 'insert_article':
                 if (($strOutput = $this->getArticle($elements[1], false, true)) !== false) {
                     $arrCache[$strTag] = ltrim($strOutput);
                 } else {
                     $arrCache[$strTag] = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], $elements[1]) . '</p>';
                 }
                 break;
                 // Insert content element
             // Insert content element
             case 'insert_content':
                 $arrCache[$strTag] = $this->getContentElement($elements[1]);
                 break;
                 // Insert module
             // Insert module
             case 'insert_module':
                 $arrCache[$strTag] = $this->getFrontendModule($elements[1]);
                 break;
                 // Insert form
             // Insert form
             case 'insert_form':
                 $arrCache[$strTag] = $this->getForm($elements[1]);
                 break;
                 // Article
             // Article
             case 'article':
             case 'article_open':
             case 'article_url':
             case 'article_title':
                 if (($objArticle = \ArticleModel::findByIdOrAlias($elements[1])) === null || !($objPid = $objArticle->getRelated('pid')) instanceof PageModel) {
                     break;
                 }
                 /** @var PageModel $objPid */
                 $strUrl = $objPid->getFrontendUrl('/articles/' . ($objArticle->alias ?: $objArticle->id));
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'article':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, \StringUtil::specialchars($objArticle->title), $objArticle->title);
                         break;
                     case 'article_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, \StringUtil::specialchars($objArticle->title));
                         break;
                     case 'article_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'article_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($objArticle->title);
                         break;
                 }
                 break;
                 // Article teaser
             // Article teaser
             case 'article_teaser':
                 $objTeaser = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     $arrCache[$strTag] = \StringUtil::toHtml5($objTeaser->teaser);
                 }
                 break;
                 // Last update
             // Last update
             case 'last_update':
                 $strQuery = "SELECT MAX(tstamp) AS tc";
                 $bundles = \System::getContainer()->getParameter('kernel.bundles');
                 if (isset($bundles['ContaoNewsBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_news) AS tn";
                 }
                 if (isset($bundles['ContaoCalendarBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_calendar_events) AS te";
                 }
                 $strQuery .= " FROM tl_content";
                 $objUpdate = \Database::getInstance()->query($strQuery);
                 if ($objUpdate->numRows) {
                     $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('datimFormat'), max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
                 }
                 break;
                 // Version
             // Version
             case 'version':
                 $arrCache[$strTag] = VERSION . '.' . BUILD;
                 break;
                 // Request token
             // Request token
             case 'request_token':
                 $arrCache[$strTag] = REQUEST_TOKEN;
                 break;
                 // POST data
             // POST data
             case 'post':
                 $arrCache[$strTag] = \Input::post($elements[1]);
                 break;
                 // Mobile/desktop toggle (see #6469)
             // Mobile/desktop toggle (see #6469)
             case 'toggle_view':
                 $strUrl = ampersand(\Environment::get('request'));
                 $strGlue = strpos($strUrl, '?') === false ? '?' : '&amp;';
                 if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=desktop" class="toggle_desktop" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleDesktop'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleDesktop'][0] . '</a>';
                 } else {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=mobile" class="toggle_mobile" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleMobile'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleMobile'][0] . '</a>';
                 }
                 break;
                 // Conditional tags (if)
             // Conditional tags (if)
             case 'iflng':
                 if ($elements[1] != '' && $elements[1] != $objPage->language) {
                     for (; $_rit < $_cnt; $_rit += 2) {
                         if ($tags[$_rit + 1] == 'iflng' || $tags[$_rit + 1] == 'iflng::' . $objPage->language) {
                             break;
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Conditional tags (if not)
             // Conditional tags (if not)
             case 'ifnlng':
                 if ($elements[1] != '') {
                     $langs = \StringUtil::trimsplit(',', $elements[1]);
                     if (in_array($objPage->language, $langs)) {
                         for (; $_rit < $_cnt; $_rit += 2) {
                             if ($tags[$_rit + 1] == 'ifnlng') {
                                 break;
                             }
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Environment
             // Environment
             case 'env':
                 switch ($elements[1]) {
                     case 'host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('host'));
                         break;
                     case 'http_host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('httpHost'));
                         break;
                     case 'url':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('url'));
                         break;
                     case 'path':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('base'));
                         break;
                     case 'request':
                         $arrCache[$strTag] = \Environment::get('indexFreeRequest');
                         break;
                     case 'ip':
                         $arrCache[$strTag] = \Environment::get('ip');
                         break;
                     case 'referer':
                         $arrCache[$strTag] = $this->getReferer(true);
                         break;
                     case 'files_url':
                         $arrCache[$strTag] = TL_FILES_URL;
                         break;
                     case 'assets_url':
                     case 'plugins_url':
                     case 'script_url':
                         $arrCache[$strTag] = TL_ASSETS_URL;
                         break;
                     case 'base_url':
                         $arrCache[$strTag] = \System::getContainer()->get('request_stack')->getCurrentRequest()->getBaseUrl();
                         break;
                 }
                 break;
                 // Page
             // Page
             case 'page':
                 if ($elements[1] == 'pageTitle' && $objPage->pageTitle == '') {
                     $elements[1] = 'title';
                 } elseif ($elements[1] == 'parentPageTitle' && $objPage->parentPageTitle == '') {
                     $elements[1] = 'parentTitle';
                 } elseif ($elements[1] == 'mainPageTitle' && $objPage->mainPageTitle == '') {
                     $elements[1] = 'mainTitle';
                 }
                 // Do not use \StringUtil::specialchars() here (see #4687)
                 $arrCache[$strTag] = $objPage->{$elements[1]};
                 break;
                 // User agent
             // User agent
             case 'ua':
                 $ua = \Environment::get('agent');
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = $ua->{$elements[1]};
                 } else {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Abbreviations
             // Abbreviations
             case 'abbr':
             case 'acronym':
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = '<abbr title="' . \StringUtil::specialchars($elements[1]) . '">';
                 } else {
                     $arrCache[$strTag] = '</abbr>';
                 }
                 break;
                 // Images
             // Images
             case 'image':
             case 'picture':
                 $width = null;
                 $height = null;
                 $alt = '';
                 $class = '';
                 $rel = '';
                 $strFile = $elements[1];
                 $mode = '';
                 $size = null;
                 $strTemplate = 'picture_default';
                 // Take arguments
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]), 2);
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         list($key, $value) = explode('=', $strParam);
                         switch ($key) {
                             case 'width':
                                 $width = $value;
                                 break;
                             case 'height':
                                 $height = $value;
                                 break;
                             case 'alt':
                                 $alt = $value;
                                 break;
                             case 'class':
                                 $class = $value;
                                 break;
                             case 'rel':
                                 $rel = $value;
                                 break;
                             case 'mode':
                                 $mode = $value;
                                 break;
                             case 'size':
                                 $size = (int) $value;
                                 break;
                             case 'template':
                                 $strTemplate = preg_replace('/[^a-z0-9_]/i', '', $value);
                                 break;
                         }
                     }
                     $strFile = $arrChunks[0];
                 }
                 if (\Validator::isUuid($strFile)) {
                     // Handle UUIDs
                     $objFile = \FilesModel::findByUuid($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } elseif (is_numeric($strFile)) {
                     // Handle numeric IDs (see #4805)
                     $objFile = \FilesModel::findByPk($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } else {
                     // Check the path
                     if (\Validator::isInsecurePath($strFile)) {
                         throw new \RuntimeException('Invalid path ' . $strFile);
                     }
                 }
                 // Check the maximum image width
                 if (\Config::get('maxImageWidth') > 0 && $width > \Config::get('maxImageWidth')) {
                     $width = \Config::get('maxImageWidth');
                     $height = null;
                 }
                 // Generate the thumbnail image
                 try {
                     // Image
                     if (strtolower($elements[0]) == 'image') {
                         $dimensions = '';
                         $src = \System::getContainer()->get('contao.image.image_factory')->create(TL_ROOT . '/' . rawurldecode($strFile), array($width, $height, $mode))->getUrl(TL_ROOT);
                         $objFile = new \File(rawurldecode($src));
                         // Add the image dimensions
                         if (($imgSize = $objFile->imageSize) !== false) {
                             $dimensions = ' width="' . \StringUtil::specialchars($imgSize[0]) . '" height="' . \StringUtil::specialchars($imgSize[1]) . '"';
                         }
                         $arrCache[$strTag] = '<img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . \StringUtil::specialchars($alt) . '"' . ($class != '' ? ' class="' . \StringUtil::specialchars($class) . '"' : '') . '>';
                     } else {
                         $picture = \System::getContainer()->get('contao.image.picture_factory')->create(TL_ROOT . '/' . $strFile, $size);
                         $picture = array('img' => $picture->getImg(TL_ROOT), 'sources' => $picture->getSources(TL_ROOT));
                         $picture['alt'] = $alt;
                         $picture['class'] = $class;
                         $pictureTemplate = new \FrontendTemplate($strTemplate);
                         $pictureTemplate->setData($picture);
                         $arrCache[$strTag] = $pictureTemplate->parse();
                     }
                     // Add a lightbox link
                     if ($rel != '') {
                         if (strncmp($rel, 'lightbox', 8) !== 0) {
                             $attribute = ' rel="' . \StringUtil::specialchars($rel) . '"';
                         } else {
                             $attribute = ' data-lightbox="' . \StringUtil::specialchars(substr($rel, 8)) . '"';
                         }
                         $arrCache[$strTag] = '<a href="' . TL_FILES_URL . $strFile . '"' . ($alt != '' ? ' title="' . \StringUtil::specialchars($alt) . '"' : '') . $attribute . '>' . $arrCache[$strTag] . '</a>';
                     }
                 } catch (\Exception $e) {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Files (UUID or template path)
             // Files (UUID or template path)
             case 'file':
                 if (\Validator::isUuid($elements[1])) {
                     $objFile = \FilesModel::findByUuid($elements[1]);
                     if ($objFile !== null) {
                         $arrCache[$strTag] = $objFile->path;
                         break;
                     }
                 }
                 $arrGet = $_GET;
                 \Input::resetCache();
                 $strFile = $elements[1];
                 // Take arguments and add them to the $_GET array
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]));
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         $arrParam = explode('=', $strParam);
                         $_GET[$arrParam[0]] = $arrParam[1];
                     }
                     $strFile = $arrChunks[0];
                 }
                 // Check the path
                 if (\Validator::isInsecurePath($strFile)) {
                     throw new \RuntimeException('Invalid path ' . $strFile);
                 }
                 // Include .php, .tpl, .xhtml and .html5 files
                 if (preg_match('/\\.(php|tpl|xhtml|html5)$/', $strFile) && file_exists(TL_ROOT . '/templates/' . $strFile)) {
                     ob_start();
                     include TL_ROOT . '/templates/' . $strFile;
                     $arrCache[$strTag] = ob_get_clean();
                 }
                 $_GET = $arrGet;
                 \Input::resetCache();
                 break;
                 // HOOK: pass unknown tags to callback functions
             // HOOK: pass unknown tags to callback functions
             default:
                 if (isset($GLOBALS['TL_HOOKS']['replaceInsertTags']) && is_array($GLOBALS['TL_HOOKS']['replaceInsertTags'])) {
                     foreach ($GLOBALS['TL_HOOKS']['replaceInsertTags'] as $callback) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback[0]}->{$callback[1]}($tag, $blnCache, $arrCache[$strTag], $flags, $tags, $arrCache, $_rit, $_cnt);
                         // see #6672
                         // Replace the tag and stop the loop
                         if ($varValue !== false) {
                             $arrCache[$strTag] = $varValue;
                             break;
                         }
                     }
                 }
                 \System::getContainer()->get('monolog.logger.contao')->log(LogLevel::INFO, 'Unknown insert tag: ' . $strTag);
                 break;
         }
         // Handle the flags
         if (!empty($flags)) {
             foreach ($flags as $flag) {
                 switch ($flag) {
                     case 'addslashes':
                     case 'standardize':
                     case 'ampersand':
                     case 'specialchars':
                     case 'nl2br':
                     case 'nl2br_pre':
                     case 'strtolower':
                     case 'utf8_strtolower':
                     case 'strtoupper':
                     case 'utf8_strtoupper':
                     case 'ucfirst':
                     case 'lcfirst':
                     case 'ucwords':
                     case 'trim':
                     case 'rtrim':
                     case 'ltrim':
                     case 'utf8_romanize':
                     case 'urlencode':
                     case 'rawurlencode':
                         $arrCache[$strTag] = $flag($arrCache[$strTag]);
                         break;
                     case 'encodeEmail':
                         $arrCache[$strTag] = \StringUtil::$flag($arrCache[$strTag]);
                         break;
                     case 'number_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 0);
                         break;
                     case 'currency_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 2);
                         break;
                     case 'readable_size':
                         $arrCache[$strTag] = \System::getReadableSize($arrCache[$strTag]);
                         break;
                     case 'flatten':
                         if (!is_array($arrCache[$strTag])) {
                             break;
                         }
                         $it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arrCache[$strTag]));
                         $result = array();
                         foreach ($it as $leafValue) {
                             $keys = array();
                             foreach (range(0, $it->getDepth()) as $depth) {
                                 $keys[] = $it->getSubIterator($depth)->key();
                             }
                             $result[] = implode('.', $keys) . ': ' . $leafValue;
                         }
                         $arrCache[$strTag] = implode(', ', $result);
                         break;
                         // HOOK: pass unknown flags to callback functions
                     // HOOK: pass unknown flags to callback functions
                     default:
                         if (isset($GLOBALS['TL_HOOKS']['insertTagFlags']) && is_array($GLOBALS['TL_HOOKS']['insertTagFlags'])) {
                             foreach ($GLOBALS['TL_HOOKS']['insertTagFlags'] as $callback) {
                                 $this->import($callback[0]);
                                 $varValue = $this->{$callback[0]}->{$callback[1]}($flag, $tag, $arrCache[$strTag], $flags, $blnCache, $tags, $arrCache, $_rit, $_cnt);
                                 // see #5806
                                 // Replace the tag and stop the loop
                                 if ($varValue !== false) {
                                     $arrCache[$strTag] = $varValue;
                                     break;
                                 }
                             }
                         }
                         \System::getContainer()->get('monolog.logger.contao')->log(LogLevel::INFO, 'Unknown insert tag flag: ' . $flag);
                         break;
                 }
             }
         }
         $strBuffer .= $arrCache[$strTag];
     }
     return \StringUtil::restoreBasicEntities($strBuffer);
 }
Пример #14
0
 /**
  * Generate the content element
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $images = array();
     $auxDate = array();
     $objFiles = $this->objFiles;
     // Get all images
     while ($objFiles->next()) {
         // Continue if the files has been processed or does not exist
         if (isset($images[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path)) {
             continue;
         }
         // Single files
         if ($objFiles->type == 'file') {
             $objFile = new \File($objFiles->path);
             if (!$objFile->isImage) {
                 continue;
             }
             $arrMeta = $this->getMetaData($objFiles->meta, $objPage->language);
             if (empty($arrMeta)) {
                 if ($this->metaIgnore) {
                     continue;
                 } elseif ($objPage->rootFallbackLanguage !== null) {
                     $arrMeta = $this->getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
                 }
             }
             // Use the file name as title if none is given
             if ($arrMeta['title'] == '') {
                 $arrMeta['title'] = \StringUtil::specialchars($objFile->basename);
             }
             // Add the image
             $images[$objFiles->path] = array('id' => $objFiles->id, 'uuid' => $objFiles->uuid, 'name' => $objFile->basename, 'singleSRC' => $objFiles->path, 'title' => \StringUtil::specialchars($arrMeta['title']), 'alt' => \StringUtil::specialchars($arrMeta['alt']), 'imageUrl' => $arrMeta['link'], 'caption' => $arrMeta['caption']);
             $auxDate[] = $objFile->mtime;
         } else {
             $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
             if ($objSubfiles === null) {
                 continue;
             }
             while ($objSubfiles->next()) {
                 // Skip subfolders
                 if ($objSubfiles->type == 'folder') {
                     continue;
                 }
                 $objFile = new \File($objSubfiles->path);
                 if (!$objFile->isImage) {
                     continue;
                 }
                 $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->language);
                 if (empty($arrMeta)) {
                     if ($this->metaIgnore) {
                         continue;
                     } elseif ($objPage->rootFallbackLanguage !== null) {
                         $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->rootFallbackLanguage);
                     }
                 }
                 // Use the file name as title if none is given
                 if ($arrMeta['title'] == '') {
                     $arrMeta['title'] = \StringUtil::specialchars($objFile->basename);
                 }
                 // Add the image
                 $images[$objSubfiles->path] = array('id' => $objSubfiles->id, 'uuid' => $objSubfiles->uuid, 'name' => $objFile->basename, 'singleSRC' => $objSubfiles->path, 'title' => \StringUtil::specialchars($arrMeta['title']), 'alt' => \StringUtil::specialchars($arrMeta['alt']), 'imageUrl' => $arrMeta['link'], 'caption' => $arrMeta['caption']);
                 $auxDate[] = $objFile->mtime;
             }
         }
     }
     // Sort array
     switch ($this->sortBy) {
         default:
         case 'name_asc':
             uksort($images, 'basename_natcasecmp');
             break;
         case 'name_desc':
             uksort($images, 'basename_natcasercmp');
             break;
         case 'date_asc':
             array_multisort($images, SORT_NUMERIC, $auxDate, SORT_ASC);
             break;
         case 'date_desc':
             array_multisort($images, SORT_NUMERIC, $auxDate, SORT_DESC);
             break;
             // Deprecated since Contao 4.0, to be removed in Contao 5.0
         // Deprecated since Contao 4.0, to be removed in Contao 5.0
         case 'meta':
             @trigger_error('The "meta" key in ContentGallery::compile() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
             // no break;
         // no break;
         case 'custom':
             if ($this->orderSRC != '') {
                 $tmp = \StringUtil::deserialize($this->orderSRC);
                 if (!empty($tmp) && is_array($tmp)) {
                     // Remove all values
                     $arrOrder = array_map(function () {
                     }, array_flip($tmp));
                     // Move the matching elements to their position in $arrOrder
                     foreach ($images as $k => $v) {
                         if (array_key_exists($v['uuid'], $arrOrder)) {
                             $arrOrder[$v['uuid']] = $v;
                             unset($images[$k]);
                         }
                     }
                     // Append the left-over images at the end
                     if (!empty($images)) {
                         $arrOrder = array_merge($arrOrder, array_values($images));
                     }
                     // Remove empty (unreplaced) entries
                     $images = array_values(array_filter($arrOrder));
                     unset($arrOrder);
                 }
             }
             break;
         case 'random':
             shuffle($images);
             $this->Template->isRandomOrder = true;
             break;
     }
     $images = array_values($images);
     // Limit the total number of items (see #2652)
     if ($this->numberOfItems > 0) {
         $images = array_slice($images, 0, $this->numberOfItems);
     }
     $offset = 0;
     $total = count($images);
     $limit = $total;
     // Paginate the result of not randomly sorted (see #8033)
     if ($this->perPage > 0 && $this->sortBy != 'random') {
         // Get the current page
         $id = 'page_g' . $this->id;
         $page = \Input::get($id) !== null ? \Input::get($id) : 1;
         // Do not index or cache the page if the page number is outside the range
         if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) {
             throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
         }
         // Set limit and offset
         $offset = ($page - 1) * $this->perPage;
         $limit = min($this->perPage + $offset, $total);
         $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id);
         $this->Template->pagination = $objPagination->generate("\n  ");
     }
     $rowcount = 0;
     $colwidth = floor(100 / $this->perRow);
     $intMaxWidth = TL_MODE == 'BE' ? floor(640 / $this->perRow) : floor(\Config::get('maxImageWidth') / $this->perRow);
     $strLightboxId = 'lightbox[lb' . $this->id . ']';
     $body = array();
     // Rows
     for ($i = $offset; $i < $limit; $i = $i + $this->perRow) {
         $class_tr = '';
         if ($rowcount == 0) {
             $class_tr .= ' row_first';
         }
         if ($i + $this->perRow >= $limit) {
             $class_tr .= ' row_last';
         }
         $class_eo = $rowcount % 2 == 0 ? ' even' : ' odd';
         // Columns
         for ($j = 0; $j < $this->perRow; $j++) {
             $class_td = '';
             if ($j == 0) {
                 $class_td .= ' col_first';
             }
             if ($j == $this->perRow - 1) {
                 $class_td .= ' col_last';
             }
             $objCell = new \stdClass();
             $key = 'row_' . $rowcount . $class_tr . $class_eo;
             // Empty cell
             if (!is_array($images[$i + $j]) || $j + $i >= $limit) {
                 $objCell->colWidth = $colwidth . '%';
                 $objCell->class = 'col_' . $j . $class_td;
             } else {
                 // Add size and margin
                 $images[$i + $j]['size'] = $this->size;
                 $images[$i + $j]['imagemargin'] = $this->imagemargin;
                 $images[$i + $j]['fullsize'] = $this->fullsize;
                 $this->addImageToTemplate($objCell, $images[$i + $j], $intMaxWidth, $strLightboxId);
                 // Add column width and class
                 $objCell->colWidth = $colwidth . '%';
                 $objCell->class = 'col_' . $j . $class_td;
             }
             $body[$key][$j] = $objCell;
         }
         ++$rowcount;
     }
     $strTemplate = 'gallery_default';
     // Use a custom template
     if (TL_MODE == 'FE' && $this->galleryTpl != '') {
         $strTemplate = $this->galleryTpl;
     }
     /** @var FrontendTemplate|object $objTemplate */
     $objTemplate = new \FrontendTemplate($strTemplate);
     $objTemplate->setData($this->arrData);
     $objTemplate->body = $body;
     $objTemplate->headline = $this->headline;
     // see #1603
     $this->Template->images = $objTemplate->parse();
 }
Пример #15
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     // Mark the x and y parameter as used (see #4277)
     if (isset($_GET['x'])) {
         \Input::get('x');
         \Input::get('y');
     }
     // Trigger the search module from a custom form
     if (!isset($_GET['keywords']) && \Input::post('FORM_SUBMIT') == 'tl_search') {
         $_GET['keywords'] = \Input::post('keywords');
         $_GET['query_type'] = \Input::post('query_type');
         $_GET['per_page'] = \Input::post('per_page');
     }
     $blnFuzzy = $this->fuzzy;
     $strQueryType = \Input::get('query_type') ?: $this->queryType;
     $strKeywords = trim(\Input::get('keywords'));
     $this->Template->uniqueId = $this->id;
     $this->Template->queryType = $strQueryType;
     $this->Template->keyword = \StringUtil::specialchars($strKeywords);
     $this->Template->keywordLabel = $GLOBALS['TL_LANG']['MSC']['keywords'];
     $this->Template->optionsLabel = $GLOBALS['TL_LANG']['MSC']['options'];
     $this->Template->search = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['searchLabel']);
     $this->Template->matchAll = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['matchAll']);
     $this->Template->matchAny = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['matchAny']);
     $this->Template->action = ampersand(\Environment::get('indexFreeRequest'));
     $this->Template->advanced = $this->searchType == 'advanced';
     // Redirect page
     if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) instanceof PageModel) {
         /** @var PageModel $objTarget */
         $this->Template->action = $objTarget->getFrontendUrl();
     }
     $this->Template->pagination = '';
     $this->Template->results = '';
     // Execute the search if there are keywords
     if ($strKeywords != '' && $strKeywords != '*' && !$this->jumpTo) {
         // Reference page
         if ($this->rootPage > 0) {
             $intRootId = $this->rootPage;
             $arrPages = $this->Database->getChildRecords($this->rootPage, 'tl_page');
             array_unshift($arrPages, $this->rootPage);
         } else {
             /** @var PageModel $objPage */
             global $objPage;
             $intRootId = $objPage->rootId;
             $arrPages = $this->Database->getChildRecords($objPage->rootId, 'tl_page');
         }
         // HOOK: add custom logic (see #5223)
         if (isset($GLOBALS['TL_HOOKS']['customizeSearch']) && is_array($GLOBALS['TL_HOOKS']['customizeSearch'])) {
             foreach ($GLOBALS['TL_HOOKS']['customizeSearch'] as $callback) {
                 $this->import($callback[0]);
                 $this->{$callback[0]}->{$callback[1]}($arrPages, $strKeywords, $strQueryType, $blnFuzzy);
             }
         }
         // Return if there are no pages
         if (!is_array($arrPages) || empty($arrPages)) {
             return;
         }
         $strCachePath = str_replace(TL_ROOT . DIRECTORY_SEPARATOR, '', \System::getContainer()->getParameter('kernel.cache_dir'));
         $arrResult = null;
         $strChecksum = md5($strKeywords . $strQueryType . $intRootId . $blnFuzzy);
         $query_starttime = microtime(true);
         $strCacheFile = $strCachePath . '/contao/search/' . $strChecksum . '.json';
         // Load the cached result
         if (file_exists(TL_ROOT . '/' . $strCacheFile)) {
             $objFile = new \File($strCacheFile);
             if ($objFile->mtime > time() - 1800) {
                 $arrResult = json_decode($objFile->getContent(), true);
             } else {
                 $objFile->delete();
             }
         }
         // Cache the result
         if ($arrResult === null) {
             try {
                 $objSearch = \Search::searchFor($strKeywords, $strQueryType == 'or', $arrPages, 0, 0, $blnFuzzy);
                 $arrResult = $objSearch->fetchAllAssoc();
             } catch (\Exception $e) {
                 $this->log('Website search failed: ' . $e->getMessage(), __METHOD__, TL_ERROR);
                 $arrResult = array();
             }
             \File::putContent($strCacheFile, json_encode($arrResult));
         }
         $query_endtime = microtime(true);
         // Sort out protected pages
         if (\Config::get('indexProtected') && !BE_USER_LOGGED_IN) {
             $this->import('FrontendUser', 'User');
             foreach ($arrResult as $k => $v) {
                 if ($v['protected']) {
                     if (!FE_USER_LOGGED_IN) {
                         unset($arrResult[$k]);
                     } else {
                         $groups = \StringUtil::deserialize($v['groups']);
                         if (!is_array($groups) || empty($groups) || !count(array_intersect($groups, $this->User->groups))) {
                             unset($arrResult[$k]);
                         }
                     }
                 }
             }
             $arrResult = array_values($arrResult);
         }
         $count = count($arrResult);
         $this->Template->count = $count;
         $this->Template->page = null;
         $this->Template->keywords = $strKeywords;
         // No results
         if ($count < 1) {
             $this->Template->header = sprintf($GLOBALS['TL_LANG']['MSC']['sEmpty'], $strKeywords);
             $this->Template->duration = substr($query_endtime - $query_starttime, 0, 6) . ' ' . $GLOBALS['TL_LANG']['MSC']['seconds'];
             return;
         }
         $from = 1;
         $to = $count;
         // Pagination
         if ($this->perPage > 0) {
             $id = 'page_s' . $this->id;
             $page = \Input::get($id) !== null ? \Input::get($id) : 1;
             $per_page = \Input::get('per_page') ?: $this->perPage;
             // Do not index or cache the page if the page number is outside the range
             if ($page < 1 || $page > max(ceil($count / $per_page), 1)) {
                 throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
             }
             $from = ($page - 1) * $per_page + 1;
             $to = $from + $per_page > $count ? $count : $from + $per_page - 1;
             // Pagination menu
             if ($to < $count || $from > 1) {
                 $objPagination = new \Pagination($count, $per_page, \Config::get('maxPaginationLinks'), $id);
                 $this->Template->pagination = $objPagination->generate("\n  ");
             }
             $this->Template->page = $page;
         }
         // Get the results
         for ($i = $from - 1; $i < $to && $i < $count; $i++) {
             /** @var FrontendTemplate|object $objTemplate */
             $objTemplate = new \FrontendTemplate($this->searchTpl);
             $objTemplate->url = $arrResult[$i]['url'];
             $objTemplate->link = $arrResult[$i]['title'];
             $objTemplate->href = $arrResult[$i]['url'];
             $objTemplate->title = \StringUtil::specialchars($arrResult[$i]['title']);
             $objTemplate->class = ($i == $from - 1 ? 'first ' : '') . ($i == $to - 1 || $i == $count - 1 ? 'last ' : '') . ($i % 2 == 0 ? 'even' : 'odd');
             $objTemplate->relevance = sprintf($GLOBALS['TL_LANG']['MSC']['relevance'], number_format($arrResult[$i]['relevance'] / $arrResult[0]['relevance'] * 100, 2) . '%');
             $objTemplate->filesize = $arrResult[$i]['filesize'];
             $objTemplate->matches = $arrResult[$i]['matches'];
             $arrContext = array();
             $arrMatches = \StringUtil::trimsplit(',', $arrResult[$i]['matches']);
             // Get the context
             foreach ($arrMatches as $strWord) {
                 $arrChunks = array();
                 preg_match_all('/(^|\\b.{0,' . $this->contextLength . '}\\PL)' . str_replace('+', '\\+', $strWord) . '(\\PL.{0,' . $this->contextLength . '}\\b|$)/ui', $arrResult[$i]['text'], $arrChunks);
                 foreach ($arrChunks[0] as $strContext) {
                     $arrContext[] = ' ' . $strContext . ' ';
                 }
             }
             // Shorten the context and highlight all keywords
             if (!empty($arrContext)) {
                 $objTemplate->context = trim(\StringUtil::substrHtml(implode('…', $arrContext), $this->totalLength));
                 $objTemplate->context = preg_replace('/(\\PL)(' . implode('|', $arrMatches) . ')(\\PL)/ui', '$1<mark class="highlight">$2</mark>$3', $objTemplate->context);
                 $objTemplate->hasContext = true;
             }
             $this->Template->results .= $objTemplate->parse();
         }
         $this->Template->header = vsprintf($GLOBALS['TL_LANG']['MSC']['sResults'], array($from, $to, $count, $strKeywords));
         $this->Template->duration = substr($query_endtime - $query_starttime, 0, 6) . ' ' . $GLOBALS['TL_LANG']['MSC']['seconds'];
     }
 }
Пример #16
0
 /**
  * Initialize the form in the current session
  *
  * @param string $formId
  */
 protected function initializeSession($formId)
 {
     if (\Input::post('FORM_SUBMIT') != $formId) {
         return;
     }
     $arrMessageBox = array('TL_ERROR', 'TL_CONFIRM', 'TL_INFO');
     $_SESSION['FORM_DATA'] = is_array($_SESSION['FORM_DATA']) ? $_SESSION['FORM_DATA'] : array();
     foreach ($arrMessageBox as $tl) {
         if (is_array($_SESSION[$formId][$tl])) {
             $_SESSION[$formId][$tl] = array_unique($_SESSION[$formId][$tl]);
             foreach ($_SESSION[$formId][$tl] as $message) {
                 /** @var FrontendTemplate|object $objTemplate */
                 $objTemplate = new \FrontendTemplate('form_message');
                 $objTemplate->message = $message;
                 $objTemplate->class = strtolower($tl);
                 $this->Template->fields .= $objTemplate->parse() . "\n";
             }
             $_SESSION[$formId][$tl] = array();
         }
     }
 }
Пример #17
0
 /**
  *
  * {{fmView::fm_tablename::8::template=fm_view::hl=h2&class=myClass&id=jsID}}
  *
  * @param $arrSplit
  * @return string
  */
 private function generateTemplate($arrSplit)
 {
     if ($arrSplit[1] && $arrSplit[2]) {
         // objPage
         global $objPage;
         $this->import('FrontendUser', 'User');
         // tablename
         $tablename = $arrSplit[1];
         // id
         $id = $arrSplit[2];
         // get parameter & parse parameter
         $params = $arrSplit[3] ? $arrSplit[3] : '';
         parse_str($params, $qRow);
         $template = $qRow['template'] ? $qRow['template'] : 'fm_view';
         $headline = $qRow['hl'] ? $qRow['hl'] : 'h3';
         $className = $qRow['class'] ? $qRow['class'] . ' ' : '';
         $jsID = $qRow['id'] ? $qRow['id'] : '';
         // check if table exist
         if (!$this->Database->tableExists($tablename)) {
             return 'table does not exist';
         }
         // get data
         $qProtectedStr = 'published = "1"';
         //  check for preview mode
         if (HelperModel::previewMode()) {
             $qProtectedStr = '';
         }
         // build query
         $sqlQuery = 'SELECT * FROM ' . $tablename . '_data WHERE id = ' . $id . ' AND ' . $qProtectedStr . ' LIMIT 1';
         if ($id == 'RAND') {
             $sqlQuery = 'SELECT * FROM ' . $tablename . '_data WHERE ' . $qProtectedStr . ' ORDER BY RAND() LIMIT 1';
         }
         $moduleDB = $this->Database->prepare('SELECT tl_fmodules.id AS moduleID, tl_fmodules.*, tl_fmodules_filters.*  FROM tl_fmodules LEFT JOIN tl_fmodules_filters ON tl_fmodules.id = tl_fmodules_filters.pid WHERE tablename = ? ORDER BY tl_fmodules_filters.sorting')->execute($tablename);
         $maps = array();
         $widgets = array();
         $arrCleanOptions = array();
         // search for item
         $viewDB = $this->Database->prepare($sqlQuery)->execute();
         // check if item exist
         if (!$viewDB->count()) {
             return 'no item found';
         }
         $item = $this->parseItem($viewDB, $tablename);
         while ($moduleDB->next()) {
             $moduleInputFields = $moduleDB->row();
             // get map
             if ($moduleInputFields['type'] == 'map_field') {
                 $maps[] = $this->findMapAndSet($moduleInputFields);
             }
             if ($moduleInputFields['type'] == 'widget') {
                 $widgets[] = $this->findWidgetAndSet($moduleInputFields);
             }
             // has options
             if ($moduleInputFields['type'] == 'simple_choice' || $moduleInputFields['type'] == 'multi_choice') {
                 $dcaHelper = new DCAHelper();
                 // später durch statische methode austauschen!
                 $arrCleanOptions[$moduleInputFields['fieldID']] = $dcaHelper->getOptions($moduleInputFields, $tablename, $item['pid']);
             }
         }
         // prepare for rendering
         $strTemplate = '';
         $objTemplate = new FrontendTemplate($template);
         // parse css & id
         $cssClass = $item['cssID'][1] ? $item['cssID'][1] . ' ' : '';
         $item['cssClass'] = $cssClass . $className;
         $item['jsID'] = $jsID ? $jsID : $item['cssID'][0];
         $item['templateName'] = $template;
         $item['tableName'] = $tablename;
         // parse headline
         $item['hl'] = $headline;
         // parse image
         if ($item['addImage']) {
             $item['fullsize'] = '';
             // disable full size
             $objTemplate->addImageToTemplate($objTemplate, $item);
             $item['picture'] = $objTemplate->picture;
         }
         // parse Gallery
         if ($item['addGallery']) {
             $objGallery = new GalleryGenerator();
             $objGallery->id = $item['id'];
             $objGallery->sortBy = $item['sortBy'];
             $objGallery->orderSRC = $item['orderSRC'];
             $objGallery->metaIgnore = $item['metaIgnore'];
             $objGallery->numberOfItems = $item['numberOfItems'];
             $objGallery->perPage = $item['perPageGallery'];
             $objGallery->perRow = $item['perRow'];
             $objGallery->size = $item['size'];
             $objGallery->fullsize = $item['fullsize'];
             $objGallery->galleryTpl = $item['galleryTpl'];
             $objGallery->getAllImages($item['multiSRC']);
             $item['gallery'] = $objGallery->renderGallery();
         }
         // parse enclosure
         $objTemplate->enclosure = array();
         if ($item['addEnclosure']) {
             $objTemplate->addEnclosuresToTemplate($objTemplate, $item);
         }
         $item['enclosure'] = $objTemplate->enclosure;
         // parse map
         if (!empty($maps)) {
             foreach ($maps as $map) {
                 $objMapTemplate = new FrontendTemplate($map['template']);
                 $item['mapSettings'] = $map;
                 $objMapTemplate->setData($item);
                 $item[$map['fieldID']] = $objMapTemplate->parse();
             }
         }
         // field
         if (!empty($widgets)) {
             $arrayAsValue = array('list.blank', 'list.keyValue', 'table.blank');
             foreach ($widgets as $widget) {
                 $id = $widget['fieldID'];
                 $tplName = $widget['widgetTemplate'];
                 $type = $widget['widgetType'];
                 $value = $item[$id];
                 if (in_array($type, $arrayAsValue)) {
                     $value = deserialize($value);
                 }
                 // unserialize
                 $objFieldTemplate = new FrontendTemplate($tplName);
                 $objFieldTemplate->setData(array('value' => $value, 'type' => $type, 'item' => $item));
                 $item[$id . 'AsTemplate'] = $objFieldTemplate->parse();
             }
         }
         // set clean options
         if (!empty($arrCleanOptions)) {
             $item['cleanOptions'] = $arrCleanOptions;
             // overwrite clean options
             foreach ($arrCleanOptions as $fieldID => $options) {
                 if ($item[$fieldID] && is_string($item[$fieldID])) {
                     $arrValues = explode(',', $item[$fieldID]);
                     $arrTemp = array();
                     if (is_array($arrValues)) {
                         foreach ($arrValues as $val) {
                             $arrTemp[$val] = $options[$val];
                         }
                     }
                     $item[$fieldID] = $arrTemp;
                 }
             }
         }
         // set data to template
         $objTemplate->setData($item);
         // parse template
         $strTemplate .= $objTemplate->parse();
         // set js files
         if ($this->loadMapScript) {
             $language = $objPage->language ? $objPage->language : 'en';
             $GLOBALS['TL_HEAD']['mapJS'] = DiverseFunction::setMapJs($language);
         }
         // replace insertTags
         $strTemplate = $this->replaceInsertTags($strTemplate);
         // return template
         return $strTemplate;
     }
     return 'no valid arguments';
 }
 /**
  * Generates template markup of links for the page header.
  *
  * @param string $templateName
  *
  * @return string
  */
 public function generate($templateName = 'block_alternate_links')
 {
     if (0 === count($this->links)) {
         return '';
     }
     $template = new FrontendTemplate($templateName);
     $template->links = $this->links;
     return $template->parse();
 }
Пример #19
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     // Create the date object
     try {
         if (\Input::get('month')) {
             $this->Date = new \Date(\Input::get('month'), 'Ym');
         } elseif (\Input::get('day')) {
             $this->Date = new \Date(\Input::get('day'), 'Ymd');
         } else {
             $this->Date = new \Date();
         }
     } catch (\OutOfBoundsException $e) {
         throw new PageNotFoundException('Page not found');
     }
     $time = \Date::floorToMinute();
     // Find the boundaries
     $objMinMax = $this->Database->query("SELECT MIN(startTime) AS dateFrom, MAX(endTime) AS dateTo, MAX(repeatEnd) AS repeatUntil FROM tl_calendar_events WHERE pid IN(" . implode(',', array_map('intval', $this->cal_calendar)) . ")" . (!BE_USER_LOGGED_IN ? " AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'" : ""));
     /** @var FrontendTemplate|object $objTemplate */
     $objTemplate = new \FrontendTemplate($this->cal_ctemplate);
     // Store year and month
     $intYear = date('Y', $this->Date->tstamp);
     $intMonth = date('m', $this->Date->tstamp);
     $objTemplate->intYear = $intYear;
     $objTemplate->intMonth = $intMonth;
     // Previous month
     $prevMonth = $intMonth == 1 ? 12 : $intMonth - 1;
     $prevYear = $intMonth == 1 ? $intYear - 1 : $intYear;
     $lblPrevious = $GLOBALS['TL_LANG']['MONTHS'][$prevMonth - 1] . ' ' . $prevYear;
     $intPrevYm = intval($prevYear . str_pad($prevMonth, 2, 0, STR_PAD_LEFT));
     // Only generate a link if there are events (see #4160)
     if ($objMinMax->dateFrom !== null && $intPrevYm >= date('Ym', $objMinMax->dateFrom)) {
         $objTemplate->prevHref = $this->strUrl . '?month=' . $intPrevYm;
         $objTemplate->prevTitle = specialchars($lblPrevious);
         $objTemplate->prevLink = $GLOBALS['TL_LANG']['MSC']['cal_previous'] . ' ' . $lblPrevious;
         $objTemplate->prevLabel = $GLOBALS['TL_LANG']['MSC']['cal_previous'];
     }
     // Current month
     $objTemplate->current = $GLOBALS['TL_LANG']['MONTHS'][date('m', $this->Date->tstamp) - 1] . ' ' . date('Y', $this->Date->tstamp);
     // Next month
     $nextMonth = $intMonth == 12 ? 1 : $intMonth + 1;
     $nextYear = $intMonth == 12 ? $intYear + 1 : $intYear;
     $lblNext = $GLOBALS['TL_LANG']['MONTHS'][$nextMonth - 1] . ' ' . $nextYear;
     $intNextYm = $nextYear . str_pad($nextMonth, 2, 0, STR_PAD_LEFT);
     // Only generate a link if there are events (see #4160)
     if ($objMinMax->dateTo !== null && $intNextYm <= date('Ym', max($objMinMax->dateTo, $objMinMax->repeatUntil))) {
         $objTemplate->nextHref = $this->strUrl . '?month=' . $intNextYm;
         $objTemplate->nextTitle = specialchars($lblNext);
         $objTemplate->nextLink = $lblNext . ' ' . $GLOBALS['TL_LANG']['MSC']['cal_next'];
         $objTemplate->nextLabel = $GLOBALS['TL_LANG']['MSC']['cal_next'];
     }
     // Set the week start day
     if (!$this->cal_startDay) {
         $this->cal_startDay = 0;
     }
     $objTemplate->days = $this->compileDays();
     $objTemplate->weeks = $this->compileWeeks();
     $objTemplate->substr = $GLOBALS['TL_LANG']['MSC']['dayShortLength'];
     $this->Template->calendar = $objTemplate->parse();
 }
Пример #20
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $items = array();
     $groups = array();
     // Get all groups of the current front end user
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $groups = $this->User->groups;
     }
     // Get all active pages
     $objPages = \PageModel::findPublishedRegularWithoutGuestsByIds($this->pages);
     // Return if there are no pages
     if ($objPages === null) {
         return;
     }
     $arrPages = array();
     // Sort the array keys according to the given order
     if ($this->orderPages != '') {
         $tmp = deserialize($this->orderPages);
         if (!empty($tmp) && is_array($tmp)) {
             $arrPages = array_map(function () {
             }, array_flip($tmp));
         }
     }
     // Add the items to the pre-sorted array
     while ($objPages->next()) {
         /** @var PageModel $objPages */
         $objModel = $objPages->current();
         $arrPages[$objPages->id] = $objModel->loadDetails()->row();
         // see #3765
     }
     // Set default template
     if ($this->navigationTpl == '') {
         $this->navigationTpl = 'nav_default';
     }
     /** @var FrontendTemplate|object $objTemplate */
     $objTemplate = new \FrontendTemplate($this->navigationTpl);
     $objTemplate->type = get_class($this);
     $objTemplate->cssID = $this->cssID;
     // see #4897 and 6129
     $objTemplate->level = 'level_1';
     foreach ($arrPages as $arrPage) {
         // Skip hidden pages (see #5832)
         if (!is_array($arrPage)) {
             continue;
         }
         $_groups = deserialize($arrPage['groups']);
         // Do not show protected pages unless a back end or front end user is logged in
         if (!$arrPage['protected'] || BE_USER_LOGGED_IN || is_array($_groups) && count(array_intersect($_groups, $groups)) || $this->showProtected) {
             // Get href
             switch ($arrPage['type']) {
                 case 'redirect':
                     $href = $arrPage['url'];
                     break;
                 case 'forward':
                     if (($objNext = \PageModel::findPublishedById($arrPage['jumpTo'])) !== null) {
                         $strForceLang = null;
                         $objNext->loadDetails();
                         // Check the target page language (see #4706)
                         if (\Config::get('addLanguageToUrl')) {
                             $strForceLang = $objNext->language;
                         }
                         $href = $this->generateFrontendUrl($objNext->row(), null, $strForceLang, true);
                         break;
                     }
                     // DO NOT ADD A break; STATEMENT
                 // DO NOT ADD A break; STATEMENT
                 default:
                     $href = $this->generateFrontendUrl($arrPage, null, $arrPage['rootLanguage'], true);
                     break;
             }
             $trail = in_array($arrPage['id'], $objPage->trail);
             // Active page
             if ($objPage->id == $arrPage['id'] && $href == \Environment::get('request')) {
                 $strClass = trim($arrPage['cssClass']);
                 $row = $arrPage;
                 $row['isActive'] = true;
                 $row['isTrail'] = false;
                 $row['class'] = trim('active ' . $strClass);
                 $row['title'] = specialchars($arrPage['title'], true);
                 $row['pageTitle'] = specialchars($arrPage['pageTitle'], true);
                 $row['link'] = $arrPage['title'];
                 $row['href'] = $href;
                 $row['nofollow'] = strncmp($arrPage['robots'], 'noindex', 7) === 0;
                 $row['target'] = '';
                 $row['description'] = str_replace(array("\n", "\r"), array(' ', ''), $arrPage['description']);
                 // Override the link target
                 if ($arrPage['type'] == 'redirect' && $arrPage['target']) {
                     $row['target'] = ' target="_blank"';
                 }
                 $items[] = $row;
             } else {
                 $strClass = trim($arrPage['cssClass'] . ($trail ? ' trail' : ''));
                 $row = $arrPage;
                 $row['isActive'] = false;
                 $row['isTrail'] = $trail;
                 $row['class'] = $strClass;
                 $row['title'] = specialchars($arrPage['title'], true);
                 $row['pageTitle'] = specialchars($arrPage['pageTitle'], true);
                 $row['link'] = $arrPage['title'];
                 $row['href'] = $href;
                 $row['nofollow'] = strncmp($arrPage['robots'], 'noindex', 7) === 0;
                 $row['target'] = '';
                 $row['description'] = str_replace(array("\n", "\r"), array(' ', ''), $arrPage['description']);
                 // Override the link target
                 if ($arrPage['type'] == 'redirect' && $arrPage['target']) {
                     $row['target'] = ' target="_blank"';
                 }
                 $items[] = $row;
             }
         }
     }
     // Add classes first and last
     $items[0]['class'] = trim($items[0]['class'] . ' first');
     $last = count($items) - 1;
     $items[$last]['class'] = trim($items[$last]['class'] . ' last');
     $objTemplate->items = $items;
     $this->Template->request = \Environment::get('indexFreeRequest');
     $this->Template->skipId = 'skipNavigation' . $this->id;
     $this->Template->skipNavigation = specialchars($GLOBALS['TL_LANG']['MSC']['skipNavigation']);
     $this->Template->items = !empty($items) ? $objTemplate->parse() : '';
 }
Пример #21
0
 /**
  *
  */
 protected function compile()
 {
     global $objPage;
     $f_display_mode = deserialize($this->f_display_mode);
     $page_taxonomy = deserialize($objPage->page_taxonomy);
     $this->strOrderBy = $this->f_orderby ? mb_strtoupper($this->f_orderby, 'UTF-8') : '';
     $taxonomyFromFE = is_array($f_display_mode) ? $f_display_mode : array();
     $taxonomyFromPage = is_array($page_taxonomy) ? $page_taxonomy : array();
     $tablename = $this->f_select_module;
     $wrapperID = $this->f_select_wrapper;
     $doNotSetByID = array('orderBy', 'sorting_fields', 'pagination');
     $doNotSetByType = array('legend_end', 'legend_start', 'wrapper_field');
     $moduleDB = $this->Database->prepare('SELECT tl_fmodules.id AS moduleID, tl_fmodules.*, tl_fmodules_filters.*  FROM tl_fmodules LEFT JOIN tl_fmodules_filters ON tl_fmodules.id = tl_fmodules_filters.pid WHERE tablename = ? ORDER BY tl_fmodules_filters.sorting')->execute($tablename);
     $arrFields = array();
     $fieldWidgets = array();
     $this->tablename = $tablename;
     $mapFields = array();
     $geoLocatorValues = array();
     $arrCleanOptions = array();
     // map view settings
     $mapSettings = array();
     if ($this->fm_addMap) {
         $mapSettings['mapZoom'] = $this->fm_mapZoom;
         $mapSettings['mapMarker'] = $this->fm_mapMarker;
         $mapSettings['mapInfoBox'] = $this->fm_mapInfoBox;
         $mapSettings['mapType'] = $this->fm_mapType;
         $mapSettings['mapStyle'] = $this->fm_mapStyle;
         $mapSettings['mapScrollWheel'] = $this->fm_mapScrollWheel ? 'true' : 'false';
         $mapSettings['lat'] = $this->fm_center_lat ? $this->fm_center_lat : '0';
         $mapSettings['lng'] = $this->fm_center_lng ? $this->fm_center_lng : '0';
     }
     // get wrapper
     $wrapperDB = $this->Database->prepare('SELECT addDetailPage, title, id, rootPage FROM ' . $tablename . ' WHERE id = ?')->execute($wrapperID)->row();
     // taxonomies
     $blnDetailView = false;
     if (\Input::get('auto_item')) {
         $taxonomyItemDB = $this->Database->prepare('SELECT * FROM ' . $tablename . '_data WHERE published = "1" AND pid = ? AND (alias = ? OR id = ?)')->limit(1)->execute($wrapperID, \Input::get('auto_item'), (int) \Input::get('auto_item'));
         if ($taxonomyItemDB->count()) {
             $blnDetailView = true;
         }
     }
     // set params variables
     $this->strAutoItem = !$blnDetailView ? '' : \Input::get('auto_item');
     $this->strSpecie = !$blnDetailView ? \Input::get('auto_item') : \Input::get('specie');
     $this->strTag = !$blnDetailView ? \Input::get('specie') : \Input::get('tags');
     while ($moduleDB->next()) {
         $arrModule = $moduleDB->row();
         if (in_array($arrModule['fieldID'], $doNotSetByID) || in_array($arrModule['type'], $doNotSetByType)) {
             continue;
         }
         $getFilter = $this->getFilter($arrModule['fieldID'], $arrModule['type']);
         $arrModule['value'] = $getFilter['value'];
         $arrModule['operator'] = $getFilter['operator'];
         $arrModule['overwrite'] = null;
         $arrModule['active'] = null;
         // set auto_page values
         if ($arrModule['fieldID'] == 'auto_page' || $arrModule['autoPage']) {
             $arrModule = $this->setValuesForAutoPageAttribute($arrModule);
         }
         // taxonomies >>
         // set specie value
         if ($arrModule['dataFromTaxonomy'] == '1' && !\Config::get('taxonomyDisable')) {
             $arrModule['type'] = 'taxonomy_field';
             // dyn type
             $arrModule = $this->setValuesForTaxonomySpecieAttribute($arrModule);
         }
         // set tags value
         if ($arrModule['reactToTaxonomy'] == '1' && !\Config::get('taxonomyDisable')) {
             $arrModule['type'] = 'taxonomy_field';
             // dyn type
             $arrModule = $this->setValuesForTaxonomyTagsAttribute($arrModule);
         }
         // << end taxonomies
         $val = QueryModel::isValue($arrModule['value'], $arrModule['type']);
         if ($val) {
             $arrModule['enable'] = true;
         }
         // check if has an wrapper
         if ($arrModule['type'] === 'search_field' && $arrModule['isInteger'] || $arrModule['type'] === 'date_field') {
             $btw = Input::get($arrModule['fieldID'] . '_btw') ? Input::get($arrModule['fieldID'] . '_btw') : '';
             $btwHasValue = QueryModel::isValue($btw, $arrModule['type']);
             if ($btwHasValue && !$val) {
                 $arrModule['enable'] = true;
                 $arrModule['value'] = 0;
             }
         }
         // map
         if ($arrModule['type'] == 'map_field') {
             // set map settings
             $mapFields[] = HelperModel::setGoogleMap($arrModule);
             // set loadMapScript to true
             $this->loadMapScript = true;
             // load map libraries
             if (!$GLOBALS['loadGoogleMapLibraries']) {
                 $GLOBALS['loadGoogleMapLibraries'] = $arrModule['mapInfoBox'] ? true : false;
             }
         }
         // field
         if ($arrModule['type'] == 'widget') {
             $tplName = $arrModule['widgetTemplate'];
             $tpl = '';
             if (!$tplName) {
                 $tplNameType = explode('.', $arrModule['widget_type'])[0];
                 $tplNameArr = $this->getTemplateGroup('fm_field_' . $tplNameType);
                 $tpl = current($tplNameArr);
                 $tpl = $this->parseTemplateName($tpl);
             }
             $fieldWidgets[$arrModule['fieldID']] = array('fieldID' => $arrModule['fieldID'], 'widgetType' => $arrModule['widget_type'], 'widgetTemplate' => $arrModule['widgetTemplate'] ? $arrModule['widgetTemplate'] : $tpl);
         }
         // has options
         if ($arrModule['type'] == 'simple_choice' || $arrModule['type'] == 'multi_choice') {
             $dcaHelper = new DCAHelper();
             $arrCleanOptions[$arrModule['fieldID']] = $dcaHelper->getOptions($arrModule, $tablename, $wrapperID);
         }
         // compass
         if ($arrModule['type'] == 'geo_locator') {
             if ($arrModule['value']) {
                 $geoLocatorValues[$arrModule['locatorType']] = $arrModule['value'];
             }
             // get delimiter
             if ($arrModule['locatorType'] == 'geo_distance') {
                 $geoLocatorValues['geoDistanceDelimiter'] = $arrModule['geoDistanceDelimiter'] ? $arrModule['geoDistanceDelimiter'] : ',';
             }
             continue;
         }
         $arrFields[$arrModule['fieldID']] = $arrModule;
     }
     if (!empty($taxonomyFromFE) || !empty($taxonomyFromPage)) {
         $arrFields = $this->setFilterValues($taxonomyFromFE, $taxonomyFromPage, $arrFields);
     }
     // compass
     $arrLongLatCords = array();
     $strDistanceField = "";
     $strHavingQuery = "";
     if ($geoLocatorValues['geo_street'] || $geoLocatorValues['geo_zip'] || $geoLocatorValues['geo_city']) {
         $this->blnLocatorInvoke = true;
         $strFECountry = $this->fm_geoLocatorCountry ? $this->fm_geoLocatorCountry : '';
         $strCountry = $geoLocatorValues['geo_country'] ? $geoLocatorValues['geo_country'] : $strFECountry;
         $strGeoAddress = sprintf('%s %s %s %s, %s', $geoLocatorValues['geo_street'] ? $geoLocatorValues['geo_street'] : '', $geoLocatorValues['geo_zip'] ? $geoLocatorValues['geo_zip'] : '', $geoLocatorValues['geo_city'] ? $geoLocatorValues['geo_city'] : '', $geoLocatorValues['geo_state'] ? $geoLocatorValues['geo_state'] : '', $strCountry);
         $strGeoAddress = trim($strGeoAddress);
         if (!empty($strGeoAddress)) {
             $objGeoCords = GeoCoding::getInstance();
             $arrLongLatCords = $objGeoCords->getGeoCords($strGeoAddress, $strCountry);
         }
         if ($arrLongLatCords['lat'] == '0' && $arrLongLatCords['lng'] == '0') {
             $arrLongLatCords = array();
         }
         if (!empty($arrLongLatCords)) {
             $strDistance = $geoLocatorValues['geo_distance'] ? $geoLocatorValues['geo_distance'] : '';
             if (\Input::get('_distance')) {
                 $strDistance = \Input::get('_distance');
             }
             if ($this->fm_adaptiveZoomFactor && !empty($mapSettings)) {
                 $intDistance = (int) $strDistance;
                 $strZoom = '12';
                 if ($intDistance >= 25 && $intDistance <= 50) {
                     $strZoom = '10';
                 }
                 if ($intDistance > 50 && $intDistance <= 100) {
                     $strZoom = '8';
                 }
                 if ($intDistance > 100) {
                     $strZoom = '7';
                 }
                 $mapSettings['mapZoom'] = $strDistance ? $strZoom : $mapSettings['mapZoom'];
                 $mapSettings['lat'] = (string) $arrLongLatCords['lat'];
                 $mapSettings['lng'] = (string) $arrLongLatCords['lng'];
             }
             $strDistanceField = "3956 * 1.6 * 2 * ASIN(SQRT( POWER(SIN((" . $arrLongLatCords['lat'] . "-abs(geo_latitude)) * pi()/180 / 2),2) + COS(" . $arrLongLatCords['lat'] . " * pi()/180 ) * COS( abs(geo_latitude) *  pi()/180) * POWER(SIN((" . $arrLongLatCords['lng'] . "-geo_longitude) *  pi()/180 / 2), 2) )) AS _distance";
             $strHavingQuery = $strDistance ? " HAVING _distance < " . $strDistance . "" : "";
         }
     }
     $selectedFields = $strDistanceField ? '*, ' . $strDistanceField : '*';
     $qResult = HelperModel::generateSQLQueryFromFilterArray($arrFields);
     $qStr = $qResult['qStr'];
     $qTextSearch = $qResult['isFulltextSearch'] ? $qResult['$qTextSearch'] : '';
     //get text search results
     $textSearchResults = array();
     if ($qTextSearch) {
         $textSearchResults = QueryModel::getTextSearchResult($qTextSearch, $tablename, $wrapperID, $qResult['searchSettings']);
     }
     // get list view
     $addDetailPage = $wrapperDB['addDetailPage'];
     $rootDB = $this->Database->prepare('SELECT * FROM ' . $tablename . ' JOIN tl_page ON tl_page.id = ' . $tablename . '.rootPage WHERE ' . $tablename . '.id = ?')->execute($wrapperID)->row();
     $qOrderByStr = $this->getOrderBy();
     $qProtectedStr = ' AND published = "1"';
     //  preview mode
     if (HelperModel::previewMode()) {
         $qProtectedStr = '';
     }
     // get all items
     $listDB = $this->Database->prepare('SELECT ' . $selectedFields . ' FROM ' . $tablename . '_data WHERE pid = ' . $wrapperID . $qProtectedStr . $qStr . $strHavingQuery . $qOrderByStr)->query();
     // image size
     $imgSize = false;
     // Override the default image size
     if ($this->imgSize != '') {
         $size = deserialize($this->imgSize);
         if ($size[0] > 0 || $size[1] > 0 || is_numeric($size[2])) {
             $imgSize = $this->imgSize;
         }
     }
     $arrItems = array();
     while ($listDB->next()) {
         $arrItem = $listDB->row();
         if (HelperModel::sortOutProtected($arrItem, $this->User->groups)) {
             continue;
         }
         if (!HelperModel::outSideScope($arrItem['start'], $arrItem['stop'])) {
             continue;
         }
         // image
         $imagePath = $this->generateSingeSrc($listDB);
         if ($imagePath) {
             $arrItem['singleSRC'] = $imagePath;
         }
         if ($imgSize) {
             $arrItem['size'] = $imgSize;
         }
         // create href
         $arrItem['href'] = null;
         if ($addDetailPage == '1' && $listDB->source == 'default') {
             // reset target
             $arrItem['target'] = '';
             $arrItem['href'] = $this->generateUrl($rootDB, $arrItem['alias']);
             // $listDB->alias
         }
         if ($arrItem['source'] == 'external') {
             $arrItem['href'] = $arrItem['url'];
         }
         if ($arrItem['source'] == 'internal') {
             // reset target
             $arrItem['target'] = '';
             $jumpToDB = $this->Database->prepare('SELECT * FROM tl_page WHERE id = ?')->execute($listDB->jumpTo)->row();
             $strTaxonomyUrl = \Config::get('taxonomyDisable') ? '' : $this->generateTaxonomyUrl();
             $arrItem['href'] = $this->generateFrontendUrl($jumpToDB, $strTaxonomyUrl);
         }
         // check for text search
         if ($qTextSearch) {
             if (!$textSearchResults[$arrItem['id']]) {
                 continue;
             }
         }
         //
         $arrItems[] = $arrItem;
     }
     // set random
     if ($this->strOrderBy == 'RAND') {
         shuffle($arrItems);
     }
     //pagination
     $strPagination = '';
     $total = count($arrItems);
     $strPagination = $this->createPagination($total);
     $this->Template->pagination = $strPagination;
     $strResults = '';
     $template = $this->fm_addMap ? $this->fm_map_template : $this->f_list_template;
     $objTemplate = new FrontendTemplate($template);
     for ($i = $this->listViewOffset; $i < $this->listViewLimit; $i++) {
         $item = $arrItems[$i];
         // parse value if map is enabled
         if ($this->fm_addMap) {
             $item['geo_latitude'] = $item['geo_latitude'] ? $item['geo_latitude'] : '0';
             $item['geo_longitude'] = $item['geo_longitude'] ? $item['geo_longitude'] : '0';
             $item['title'] = mb_convert_encoding($item['title'], 'UTF-8');
             $item['description'] = mb_convert_encoding($item['description'], 'UTF-8');
             $item['info'] = mb_convert_encoding($item['info'], 'UTF-8');
         }
         if ($item['addGallery'] && $item['multiSRC'] && !$this->fm_disableGallery) {
             $objGallery = new GalleryGenerator();
             $objGallery->id = $item['id'];
             $objGallery->sortBy = $item['sortBy'];
             $objGallery->orderSRC = $item['orderSRC'];
             $objGallery->metaIgnore = $item['metaIgnore'];
             $objGallery->numberOfItems = $item['numberOfItems'];
             $objGallery->perPage = $item['perPageGallery'];
             $objGallery->perRow = $item['perRow'];
             $objGallery->size = $item['size'];
             $objGallery->fullsize = $item['fullsize'];
             $objGallery->galleryTpl = $item['galleryTpl'];
             $objGallery->getAllImages($item['multiSRC']);
             $item['gallery'] = $objGallery->renderGallery();
         }
         // set css and id
         $item['cssID'] = deserialize($item['cssID']);
         $item['itemID'] = $item['cssID'][0];
         $item['itemCSS'] = $item['cssID'][1] ? ' ' . $item['cssID'][1] : '';
         // set date format
         $date = date('Y-m-d', $item['date']);
         $time = date('H:i', $item['time']);
         $dateTime = $time ? $date . ' ' . $time : $date;
         $item['dateTime'] = $dateTime;
         $item['date'] = $item['date'] ? date($objPage->dateFormat, $item['date']) : '';
         $item['time'] = $item['time'] ? date($objPage->timeFormat, $item['time']) : '';
         // distance
         if ($item['_distance']) {
             $item['_distance'] = number_format($item['_distance'], 2, $geoLocatorValues['geoDistanceDelimiter'], $geoLocatorValues['geoDistanceDelimiter']);
             $item['_distanceLabel'] = $GLOBALS['TL_LANG']['MSC']['fm_distance'];
         }
         // set more
         $item['more'] = $GLOBALS['TL_LANG']['MSC']['more'];
         // get list view ce
         $objCte = ContentModelExtend::findPublishedByPidAndTable($item['id'], $tablename . '_data', array('fview' => 'list'));
         $arrElements = array();
         if ($objCte !== null) {
             $intCount = 0;
             $intLast = $objCte->count() - 1;
             while ($objCte->next()) {
                 $arrCss = array();
                 $objRow = $objCte->current();
                 if ($intCount == 0 || $intCount == $intLast) {
                     if ($intCount == 0) {
                         $arrCss[] = 'first';
                     }
                     if ($intCount == $intLast) {
                         $arrCss[] = 'last';
                     }
                 }
                 $objRow->classes = $arrCss;
                 $arrElements[] = $this->getContentElement($objRow, $this->strColumn);
                 ++$intCount;
             }
         }
         $item['teaser'] = $arrElements;
         // set odd and even classes
         $item['cssClass'] = $i % 2 ? ' even' : ' odd';
         //field
         if (!empty($fieldWidgets)) {
             $arrayAsValue = array('list.blank', 'list.keyValue', 'table.blank');
             foreach ($fieldWidgets as $widget) {
                 $id = $widget['fieldID'];
                 $tplName = $widget['widgetTemplate'];
                 $type = $widget['widgetType'];
                 $value = $item[$id];
                 if (in_array($type, $arrayAsValue)) {
                     $value = deserialize($value);
                 }
                 // unserialize
                 $objFieldTemplate = new FrontendTemplate($tplName);
                 $objFieldTemplate->setData(array('value' => $value, 'type' => $type, 'item' => $item));
                 $item[$id] = $objFieldTemplate->parse();
             }
         }
         // set last first classes
         if ($i == 0) {
             $item['cssClass'] .= ' first';
         }
         if ($i == $this->listViewLimit - 1) {
             $item['cssClass'] .= ' last';
         }
         // create marker path
         if ($item['addMarker'] && $item['markerSRC']) {
             if ($this->markerCache[$item['markerSRC']]) {
                 $item['markerSRC'] = $this->markerCache[$item['markerSRC']];
             } else {
                 $markerDB = $this->Database->prepare('SELECT * FROM tl_files WHERE uuid = ?')->execute($item['markerSRC']);
                 if ($markerDB->count()) {
                     $pathInfo = $markerDB->row()['path'];
                     if ($pathInfo) {
                         $this->markerCache[$item['markerSRC']] = $pathInfo;
                         $item['markerSRC'] = $pathInfo;
                     }
                 }
             }
         }
         // map settings from field
         if (!empty($mapFields)) {
             foreach ($mapFields as $map) {
                 $objMapTemplate = new FrontendTemplate($map['template']);
                 $item['mapSettings'] = $map;
                 $objMapTemplate->setData($item);
                 $item[$map['fieldID']] = $objMapTemplate->parse();
             }
         }
         // mapSettings
         if (!empty($mapSettings)) {
             $item['mapSettings'] = $mapSettings;
         }
         // set fe view id
         $item['feViewID'] = $this->feViewID;
         // set clean options
         if (!empty($arrCleanOptions)) {
             $item['cleanOptions'] = $arrCleanOptions;
             // overwrite clean options
             foreach ($arrCleanOptions as $fieldID => $options) {
                 if ($item[$fieldID] && is_string($item[$fieldID])) {
                     $arrValues = explode(',', $item[$fieldID]);
                     $arrValuesAsString = array();
                     $arrValuesAsArray = array();
                     if (is_array($arrValues)) {
                         foreach ($arrValues as $val) {
                             $arrValuesAsArray[$val] = $options[$val];
                             $arrValuesAsString[] = $options[$val];
                         }
                     }
                     $item[$fieldID . 'AsArray'] = $arrValuesAsArray;
                     $item[$fieldID] = implode(', ', $arrValuesAsString);
                 }
             }
         }
         // floating class
         $item['floatClass'] = 'float_' . $item['floating'];
         //set data
         $objTemplate->setData($item);
         $strTitle = $item['title'];
         //set image
         if ($item['addImage']) {
             $this->addImageToTemplate($objTemplate, array('singleSRC' => $item['singleSRC'], 'alt' => $item['alt'], 'title' => $item['imgTitle'], 'size' => $item['size'], 'fullsize' => $item['fullsize'], 'caption' => $item['caption']));
         }
         // set enclosure
         $objTemplate->enclosure = array();
         if ($item['addEnclosure']) {
             $this->addEnclosuresToTemplate($objTemplate, $item);
         }
         $objTemplate->title = $strTitle;
         // fix title bug
         $objTemplate->addBefore = $item['floatClass'] == 'float_below' ? false : true;
         $strResults .= $objTemplate->parse();
     }
     // set map settings
     if (!empty($mapSettings)) {
         // set map settings array to template
         $this->Template->mapSettings = $mapSettings;
         // set loadMapScript to true
         $this->loadMapScript = true;
         // load map libraries
         if (!$GLOBALS['loadGoogleMapLibraries']) {
             $GLOBALS['loadGoogleMapLibraries'] = $mapSettings['mapInfoBox'] ? true : false;
         }
     }
     // set js files
     if ($this->loadMapScript) {
         $language = $objPage->language ? $objPage->language : 'en';
         $GLOBALS['TL_HEAD']['mapJS'] = DiverseFunction::setMapJs($language);
     }
     $this->Template->feViewID = $this->feViewID;
     $this->Template->results = $total < 1 ? '<p class="no-results">' . $GLOBALS['TL_LANG']['MSC']['noResult'] . '</p>' : $strResults;
 }
Пример #22
0
 /**
  * Return string/html of all companies
  *
  * @param array $arrCompanies
  *        	DB query rows as array
  * @return string
  */
 protected function getCompanies($objCompanies, $objPage = NULL)
 {
     $strHTML = '';
     while ($objCompanies->next()) {
         if ($objCompanies->company != '') {
             $objTemplate = new FrontendTemplate($this->strTemplateCompanyList);
             $objFile = \FilesModel::findByPk($objCompanies->logo);
             $arrSize = deserialize($this->imgSize);
             $objCompanies->logo = \Image::get($objFile->path, $arrSize[0], $arrSize[1], $arrSize[2]);
             $objTemplate->objCompany = $objCompanies;
             if ($objPage) {
                 $objTemplate->link = $this->generateFrontendUrl($objPage->row(), '/companyID/' . $objCompanies->id);
             }
             $strHTML .= $objTemplate->parse();
         }
     }
     return $strHTML;
 }