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

Parse a date format string and translate textual representations
public static parse ( string $strFormat, integer $intTstamp = null ) : string
$strFormat string The date format string
$intTstamp integer An optional timestamp
Результат string The textual representation of the date
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $arrJumpTo = array();
     $arrNewsletter = array();
     $strRequest = ampersand(\Environment::get('request'), true);
     $objNewsletter = \NewsletterModel::findSentByPids($this->nl_channels);
     if ($objNewsletter !== null) {
         while ($objNewsletter->next()) {
             /** @var NewsletterChannelModel $objTarget */
             if (!($objTarget = $objNewsletter->getRelated('pid')) instanceof NewsletterChannelModel) {
                 continue;
             }
             $jumpTo = intval($objTarget->jumpTo);
             // A jumpTo page is not mandatory for newsletter channels (see #6521) but required for the list module
             if ($jumpTo < 1) {
                 throw new \Exception("Newsletter channels without redirect page cannot be used in a newsletter list");
             }
             $strUrl = $strRequest;
             if (!isset($arrJumpTo[$objTarget->jumpTo])) {
                 if (($objJumpTo = $objTarget->getRelated('jumpTo')) instanceof PageModel) {
                     /** @var PageModel $objJumpTo */
                     $arrJumpTo[$objTarget->jumpTo] = $objJumpTo->getFrontendUrl(\Config::get('useAutoItem') ? '/%s' : '/items/%s');
                 } else {
                     $arrJumpTo[$objTarget->jumpTo] = $strUrl;
                 }
             }
             $strUrl = $arrJumpTo[$objTarget->jumpTo];
             $strAlias = $objNewsletter->alias ?: $objNewsletter->id;
             $arrNewsletter[] = array('subject' => $objNewsletter->subject, 'title' => \StringUtil::stripInsertTags($objNewsletter->subject), 'href' => sprintf($strUrl, $strAlias), 'date' => \Date::parse($objPage->dateFormat, $objNewsletter->date), 'datim' => \Date::parse($objPage->datimFormat, $objNewsletter->date), 'time' => \Date::parse($objPage->timeFormat, $objNewsletter->date), 'channel' => $objNewsletter->pid);
         }
     }
     $this->Template->newsletters = $arrNewsletter;
 }
Пример #2
0
 public function addTypeIcon($row, $label, DataContainer $dc, $args = null)
 {
     $args[0] = \Image::getHtml(\Image::get('system/modules/mail_to/assets/mail-open-image.png', 16, 16));
     $objFile = FilesModel::findByUuid($row['folder']);
     $args[2] = $objFile !== null ? $objFile->path : '-';
     $args[5] = Date::parse(Date::getFormatFromRgxp('datim'), $row['lastrun']);
     return $args;
 }
 /**
  * @inheritdoc
  *
  * @param CalendarEventsModel   $current
  * @param CalendarEventsModel[] $models
  */
 protected function formatOptions(Model $current, Model\Collection $models)
 {
     $options = [];
     foreach ($models as $model) {
         $options[$model->id] = sprintf('%s [%s]', $model->title, Date::parse($GLOBALS['TL_CONFIG']['datimFormat'], $model->startTime));
     }
     return $options;
 }
Пример #4
0
 /**
  * @inheritdoc
  *
  * @param NewsModel   $current
  * @param NewsModel[] $models
  */
 protected function formatOptions(Model $current, Model\Collection $models)
 {
     $sameDay = $GLOBALS['TL_LANG']['tl_product']['sameDay'];
     $otherDay = $GLOBALS['TL_LANG']['tl_product']['otherDay'];
     $dayBegin = strtotime('0:00', $current->date);
     $options = [$sameDay => [], $otherDay => []];
     foreach ($models as $model) {
         $group = strtotime('0:00', $model->date) === $dayBegin ? $sameDay : $otherDay;
         $options[$group][$model->id] = sprintf('%s (%s) [%s]', $model->title, $model->code, Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $model->date));
     }
     return $options;
 }
Пример #5
0
 public static function getSeparatedNumericDateTimeInterval($intStartDate = null, $intEndDate = null, $intStartTime = null, $intEndTime = null, $strIntervalDelimiter = ' &ndash; ', $strDelimiter = ', ')
 {
     $strStartDate = \Contao\Date::parse(\Contao\Date::getNumericDateFormat(), $intStartDate);
     $strEndDate = \Contao\Date::parse(\Contao\Date::getNumericDateFormat(), $intEndDate);
     $strStartTime = \Contao\Date::parse(\Contao\Date::getNumericTimeFormat(), $intStartTime);
     $strEndTime = \Contao\Date::parse(\Contao\Date::getNumericTimeFormat(), $intEndTime);
     $strResult = $strStartDate;
     if ($intEndDate > 0 && $intEndDate > $intStartDate && $strStartDate != $strEndDate) {
         $strResult .= $strIntervalDelimiter . $strEndDate;
     }
     if ($intStartTime > 0) {
         if ($intEndTime > $intStartTime && $strStartTime != $strEndTime) {
             $strResult .= $strDelimiter . $strStartTime . $strIntervalDelimiter . $strEndTime;
         } else {
             $strResult .= $strDelimiter . $strStartTime;
         }
     }
     return $strResult;
 }
Пример #6
0
 /**
  * Import the example website
  */
 protected function importExampleWebsite()
 {
     /** @var \SplFileInfo[] $objFiles */
     $objFiles = new \RecursiveIteratorIterator(new \Filter\SqlFiles(new \RecursiveDirectoryIterator(TL_ROOT . '/templates', \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS)));
     $arrTemplates = array();
     // Add the relative paths
     foreach ($objFiles as $objFile) {
         $arrTemplates[] = str_replace(TL_ROOT . '/templates/', '', $objFile->getPathname());
     }
     $strTemplates = '<option value="">-</option>';
     // Build the select options
     foreach ($arrTemplates as $strTemplate) {
         $strTemplates .= sprintf('<option value="%s">%s</option>', $strTemplate, specialchars($strTemplate));
     }
     $this->Template->templates = $strTemplates;
     // Process the request after the select menu has been generated
     // so the options show up even if the import throws an Exception
     if (\Input::post('FORM_SUBMIT') == 'tl_tutorial') {
         $this->Template->emptySelection = true;
         $strTemplate = \Input::post('template');
         // Template selected
         if ($strTemplate != '' && in_array($strTemplate, $arrTemplates)) {
             $tables = preg_grep('/^tl_/i', $this->Database->listTables());
             // Truncate tables
             if (!isset($_POST['preserve'])) {
                 foreach ($tables as $table) {
                     // Preserve the repository tables (see #6037)
                     if (isset($_POST['override']) || $table != 'tl_repository_installs' && $table != 'tl_repository_instfiles') {
                         $this->Database->execute("TRUNCATE TABLE " . $table);
                     }
                 }
             }
             // Import data
             $file = file(TL_ROOT . '/templates/' . $strTemplate);
             $sql = preg_grep('/^INSERT /', $file);
             foreach ($sql as $query) {
                 // Skip the repository tables (see #6037)
                 if (isset($_POST['override']) || strpos($query, '`tl_repository_installs`') === false && strpos($query, '`tl_repository_instfiles`') === false) {
                     $this->Database->execute($query);
                 }
             }
             \Config::persist('exampleWebsite', time());
             $this->reload();
         }
     }
     $this->Template->dateImported = \Date::parse(\Config::get('datimFormat'), \Config::get('exampleWebsite'));
 }
Пример #7
0
 /**
  * @param $strTable
  * @param $strLanguage
  * @param $strName
  * @param $varValue
  * @return string
  */
 protected function renderParameterValue($strTable, $strLanguage, $strName, $varValue)
 {
     if ($varValue == '') {
         return '';
     }
     $this->loadLanguageFile('default', $strLanguage, true);
     $this->loadLanguageFile($strTable, $strLanguage, true);
     $this->loadDataContainer($strTable);
     if ($GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['inputType'] == 'password') {
         return '';
     }
     $varValue = deserialize($varValue);
     $rgxp = $GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['eval']['rgxp'];
     $opts = $GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['options'];
     $rfrc = $GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['reference'];
     if ($rgxp == 'date') {
         $varValue = Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $varValue);
     } elseif ($rgxp == 'time') {
         $varValue = Date::parse($GLOBALS['TL_CONFIG']['timeFormat'], $varValue);
     } elseif ($rgxp == 'datim') {
         $varValue = Date::parse($GLOBALS['TL_CONFIG']['datimFormat'], $varValue);
     } elseif (is_array($varValue)) {
         $varValue = implode(', ', $varValue);
     } elseif (is_array($opts) && array_is_assoc($opts)) {
         $varValue = isset($opts[$varValue]) ? $opts[$varValue] : $varValue;
     } elseif (is_array($rfrc)) {
         $varValue = isset($rfrc[$varValue]) ? is_array($rfrc[$varValue]) ? $rfrc[$varValue][0] : $rfrc[$varValue] : $varValue;
     }
     $varValue = specialchars($varValue);
     return (string) $varValue;
 }
Пример #8
0
    /**
     * Render the versions dropdown menu
     *
     * @return string
     */
    public function renderDropdown()
    {
        $objVersion = $this->Database->prepare("SELECT tstamp, version, username, active FROM tl_version WHERE fromTable=? AND pid=? ORDER BY version DESC")->execute($this->strTable, $this->intPid);
        if ($objVersion->numRows < 2) {
            return '';
        }
        $versions = '';
        while ($objVersion->next()) {
            $versions .= '
  <option value="' . $objVersion->version . '"' . ($objVersion->active ? ' selected="selected"' : '') . '>' . $GLOBALS['TL_LANG']['MSC']['version'] . ' ' . $objVersion->version . ' (' . \Date::parse(\Config::get('datimFormat'), $objVersion->tstamp) . ') ' . $objVersion->username . '</option>';
        }
        return '
<div class="tl_version_panel">

<form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_version" class="tl_form" method="post">
<div class="tl_formbody">
<input type="hidden" name="FORM_SUBMIT" value="tl_version">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">
<select name="version" class="tl_select">' . $versions . '
</select>
<button type="submit" name="showVersion" id="showVersion" class="tl_submit">' . $GLOBALS['TL_LANG']['MSC']['restore'] . '</button>
<a href="' . \Backend::addToUrl('versions=1&amp;popup=1') . '" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']) . '" onclick="Backend.openModalIframe({\'width\':768,\'title\':\'' . \StringUtil::specialchars(str_replace("'", "\\'", sprintf($GLOBALS['TL_LANG']['MSC']['recordOfTable'], $this->intPid, $this->strTable))) . '\',\'url\':this.href});return false">' . \Image::getHtml('diff.svg') . '</a>
</div>
</form>

</div>
';
    }
Пример #9
0
 /**
  * Format a value
  *
  * @param string  $k
  * @param mixed   $value
  * @param boolean $blnListSingle
  *
  * @return mixed
  */
 protected function formatValue($k, $value, $blnListSingle = false)
 {
     $value = \StringUtil::deserialize($value);
     // Return if empty
     if (empty($value)) {
         return '';
     }
     /** @var PageModel $objPage */
     global $objPage;
     // Array
     if (is_array($value)) {
         $value = implode(', ', $value);
     } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'date') {
         $value = \Date::parse($objPage->dateFormat, $value);
     } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'time') {
         $value = \Date::parse($objPage->timeFormat, $value);
     } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'datim') {
         $value = \Date::parse($objPage->datimFormat, $value);
     } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'url' && preg_match('@^(https?://|ftp://)@i', $value)) {
         $value = \Idna::decode($value);
         // see #5946
         $value = '<a href="' . $value . '" target="_blank">' . $value . '</a>';
     } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'email') {
         $value = \StringUtil::encodeEmail(\Idna::decode($value));
         // see #5946
         $value = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $value . '">' . $value . '</a>';
     } elseif (is_array($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['reference'])) {
         $value = $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['reference'][$value];
     } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['options'])) {
         if ($blnListSingle) {
             $value = $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['options'][$value];
         } else {
             $value = '<span class="value">[' . $value . ']</span> ' . $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['options'][$value];
         }
     }
     return $value;
 }
Пример #10
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $limit = null;
     $offset = 0;
     $intBegin = 0;
     $intEnd = 0;
     $intYear = \Input::get('year');
     $intMonth = \Input::get('month');
     $intDay = \Input::get('day');
     // Jump to the current period
     if (!isset($_GET['year']) && !isset($_GET['month']) && !isset($_GET['day']) && $this->news_jumpToCurrent != 'all_items') {
         switch ($this->news_format) {
             case 'news_year':
                 $intYear = date('Y');
                 break;
             default:
             case 'news_month':
                 $intMonth = date('Ym');
                 break;
             case 'news_day':
                 $intDay = date('Ymd');
                 break;
         }
     }
     // Create the date object
     try {
         if ($intYear) {
             $strDate = $intYear;
             $objDate = new \Date($strDate, 'Y');
             $intBegin = $objDate->yearBegin;
             $intEnd = $objDate->yearEnd;
             $this->headline .= ' ' . date('Y', $objDate->tstamp);
         } elseif ($intMonth) {
             $strDate = $intMonth;
             $objDate = new \Date($strDate, 'Ym');
             $intBegin = $objDate->monthBegin;
             $intEnd = $objDate->monthEnd;
             $this->headline .= ' ' . \Date::parse('F Y', $objDate->tstamp);
         } elseif ($intDay) {
             $strDate = $intDay;
             $objDate = new \Date($strDate, 'Ymd');
             $intBegin = $objDate->dayBegin;
             $intEnd = $objDate->dayEnd;
             $this->headline .= ' ' . \Date::parse($objPage->dateFormat, $objDate->tstamp);
         } elseif ($this->news_jumpToCurrent == 'all_items') {
             $intBegin = 0;
             $intEnd = time();
         }
     } catch (\OutOfBoundsException $e) {
         throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
     }
     $this->Template->articles = array();
     // Split the result
     if ($this->perPage > 0) {
         // Get the total number of items
         $intTotal = \NewsModel::countPublishedFromToByPids($intBegin, $intEnd, $this->news_archives);
         if ($intTotal > 0) {
             $total = $intTotal;
             // Get the current page
             $id = 'page_a' . $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
             $limit = $this->perPage;
             $offset = (max($page, 1) - 1) * $this->perPage;
             // Add the pagination menu
             $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id);
             $this->Template->pagination = $objPagination->generate("\n  ");
         }
     }
     // Get the news items
     if (isset($limit)) {
         $objArticles = \NewsModel::findPublishedFromToByPids($intBegin, $intEnd, $this->news_archives, $limit, $offset);
     } else {
         $objArticles = \NewsModel::findPublishedFromToByPids($intBegin, $intEnd, $this->news_archives);
     }
     // Add the articles
     if ($objArticles !== null) {
         $this->Template->articles = $this->parseArticles($objArticles);
     }
     $this->Template->headline = trim($this->headline);
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     $this->Template->empty = $GLOBALS['TL_LANG']['MSC']['empty'];
 }
Пример #11
0
 /**
  * Send an admin notification e-mail
  *
  * @param integer $intId
  * @param array   $arrData
  */
 protected function sendAdminNotification($intId, $arrData)
 {
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['adminSubject'], \Idna::decode(\Environment::get('host')));
     $strData = "\n\n";
     // Add user details
     foreach ($arrData as $k => $v) {
         if ($k == 'password' || $k == 'tstamp' || $k == 'activation' || $k == 'dateAdded') {
             continue;
         }
         $v = \StringUtil::deserialize($v);
         if ($k == 'dateOfBirth' && strlen($v)) {
             $v = \Date::parse(\Config::get('dateFormat'), $v);
         }
         $strData .= $GLOBALS['TL_LANG']['tl_member'][$k][0] . ': ' . (is_array($v) ? implode(', ', $v) : $v) . "\n";
     }
     $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['adminText'], $intId, $strData . "\n") . "\n";
     $objEmail->sendTo($GLOBALS['TL_ADMIN_EMAIL']);
     $this->log('A new user (ID ' . $intId . ') has registered on the website', __METHOD__, TL_ACCESS);
 }
Пример #12
0
 /**
  * Parse a date format string and translate textual representations
  *
  * @param string  $strFormat The date format string
  * @param integer $intTstamp An optional timestamp
  *
  * @return string The textual representation of the date
  *
  * @deprecated Deprecated since Contao 4.0, to be removed in Contao 5.0.
  *             Use Date::parse() instead.
  */
 public static function parseDate($strFormat, $intTstamp = null)
 {
     @trigger_error('Using System::parseDate() has been deprecated and will no longer work in Contao 5.0. Use Date::parse() instead.', E_USER_DEPRECATED);
     return \Date::parse($strFormat, $intTstamp);
 }
Пример #13
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     $this->Template->referer = 'javascript:history.go(-1)';
     $objFaq = \FaqModel::findPublishedByParentAndIdOrAlias(\Input::get('items'), $this->faq_categories);
     if (null === $objFaq) {
         throw new PageNotFoundException('Page not found');
     }
     // Overwrite the page title and description (see #2853 and #4955)
     if ($objFaq->question != '') {
         $objPage->pageTitle = strip_tags(strip_insert_tags($objFaq->question));
         $objPage->description = $this->prepareMetaDescription($objFaq->question);
     }
     $this->Template->question = $objFaq->question;
     // Clean the RTE output
     $objFaq->answer = \StringUtil::toHtml5($objFaq->answer);
     $this->Template->answer = \StringUtil::encodeEmail($objFaq->answer);
     $this->Template->addImage = false;
     // Add image
     if ($objFaq->addImage && $objFaq->singleSRC != '') {
         $objModel = \FilesModel::findByUuid($objFaq->singleSRC);
         if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) {
             // Do not override the field now that we have a model registry (see #6303)
             $arrFaq = $objFaq->row();
             $arrFaq['singleSRC'] = $objModel->path;
             $this->addImageToTemplate($this->Template, $arrFaq);
         }
     }
     $this->Template->enclosure = array();
     // Add enclosure
     if ($objFaq->addEnclosure) {
         $this->addEnclosuresToTemplate($this->Template, $objFaq->row());
     }
     $strAuthor = '';
     // Add the author
     if (($objAuthor = $objFaq->getRelated('author')) !== null) {
         $strAuthor = $objAuthor->name;
     }
     $this->Template->info = sprintf($GLOBALS['TL_LANG']['MSC']['faqCreatedBy'], \Date::parse($objPage->dateFormat, $objFaq->tstamp), $strAuthor);
     $bundles = \System::getContainer()->getParameter('kernel.bundles');
     // HOOK: comments extension required
     if ($objFaq->noComments || !isset($bundles['ContaoCommentsBundle'])) {
         $this->Template->allowComments = false;
         return;
     }
     /** @var FaqCategoryModel $objCategory */
     $objCategory = $objFaq->getRelated('pid');
     $this->Template->allowComments = $objCategory->allowComments;
     // Comments are not allowed
     if (!$objCategory->allowComments) {
         return;
     }
     // Adjust the comments headline level
     $intHl = min(intval(str_replace('h', '', $this->hl)), 5);
     $this->Template->hlc = 'h' . ($intHl + 1);
     $this->import('Comments');
     $arrNotifies = array();
     // Notify the system administrator
     if ($objCategory->notify != 'notify_author') {
         $arrNotifies[] = $GLOBALS['TL_ADMIN_EMAIL'];
     }
     // Notify the author
     if ($objCategory->notify != 'notify_admin') {
         /** @var UserModel $objAuthor */
         if (($objAuthor = $objFaq->getRelated('author')) !== null && $objAuthor->email != '') {
             $arrNotifies[] = $objAuthor->email;
         }
     }
     $objConfig = new \stdClass();
     $objConfig->perPage = $objCategory->perPage;
     $objConfig->order = $objCategory->sortOrder;
     $objConfig->template = $this->com_template;
     $objConfig->requireLogin = $objCategory->requireLogin;
     $objConfig->disableCaptcha = $objCategory->disableCaptcha;
     $objConfig->bbcode = $objCategory->bbcode;
     $objConfig->moderate = $objCategory->moderate;
     $this->Comments->addCommentsToTemplate($this->Template, $objConfig, 'tl_faq', $objFaq->id, $arrNotifies);
 }
Пример #14
0
 /**
  * Generate the stats data
  *
  * @return array|null
  */
 public static function generateStats()
 {
     if (!Stats::hasData()) {
         return null;
     }
     $totalLimit = Stats::get(Stats::TOTAL_LIMIT);
     $resetTime = Stats::get(Stats::LIMIT_RESET_TIME);
     $limitReset = $resetTime < time();
     $currentLimit = $limitReset ? $totalLimit : Stats::get(Stats::CURRENT_LIMIT);
     return ['totalLimit' => $totalLimit, 'currentLimit' => $currentLimit, 'limitReset' => $limitReset ? '' : Date::parse(Config::get('datimFormat'), $resetTime), 'canRun' => $currentLimit > 0 || $limitReset];
 }
 /**
  * Return the meta fields of a news article as array.
  *
  * @param NewsModel $objArticle The model.
  *
  * @return array
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.Superglobals)
  * @SuppressWarnings(PHPMD.CamelCaseVariableName)
  */
 protected function getMetaFields($objArticle)
 {
     $meta = deserialize($this->news_metaFields);
     if (!is_array($meta)) {
         return array();
     }
     $return = array();
     foreach ($meta as $field) {
         switch ($field) {
             case 'date':
                 $return['date'] = Date::parse($GLOBALS['objPage']->datimFormat, $objArticle->date);
                 break;
             case 'author':
                 if (($objAuthor = $objArticle->getRelated('author')) !== null) {
                     if ($objAuthor->google != '') {
                         $return['author'] = $GLOBALS['TL_LANG']['MSC']['by'] . ' <a href="https://plus.google.com/' . $objAuthor->google . '" rel="author" target="_blank">' . $objAuthor->name . '</a>';
                     } else {
                         $return['author'] = $GLOBALS['TL_LANG']['MSC']['by'] . ' ' . $objAuthor->name;
                     }
                 }
                 break;
             case 'comments':
                 if ($objArticle->noComments || $objArticle->source != 'default') {
                     break;
                 }
                 $intTotal = CommentsModel::countPublishedBySourceAndParent('tl_news', $objArticle->id);
                 $return['ccount'] = $intTotal;
                 $return['comments'] = sprintf($GLOBALS['TL_LANG']['MSC']['commentCount'], $intTotal);
                 break;
             default:
         }
     }
     return $return;
 }
Пример #16
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     $objFaq = \FaqModel::findPublishedByPids($this->faq_categories);
     if ($objFaq === null) {
         $this->Template->faq = array();
         return;
     }
     /** @var PageModel $objPage */
     global $objPage;
     $arrFaqs = array_fill_keys($this->faq_categories, array());
     // Add FAQs
     while ($objFaq->next()) {
         /** @var FaqModel $objFaq */
         $objTemp = (object) $objFaq->row();
         // Clean the RTE output
         $objTemp->answer = \StringUtil::toHtml5($objFaq->answer);
         $objTemp->answer = \StringUtil::encodeEmail($objTemp->answer);
         $objTemp->addImage = false;
         // Add an image
         if ($objFaq->addImage && $objFaq->singleSRC != '') {
             $objModel = \FilesModel::findByUuid($objFaq->singleSRC);
             if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) {
                 // Do not override the field now that we have a model registry (see #6303)
                 $arrFaq = $objFaq->row();
                 $arrFaq['singleSRC'] = $objModel->path;
                 $strLightboxId = 'lightbox[' . substr(md5('mod_faqpage_' . $objFaq->id), 0, 6) . ']';
                 // see #5810
                 $this->addImageToTemplate($objTemp, $arrFaq, null, $strLightboxId);
             }
         }
         $objTemp->enclosure = array();
         // Add enclosure
         if ($objFaq->addEnclosure) {
             $this->addEnclosuresToTemplate($objTemp, $objFaq->row());
         }
         /** @var UserModel $objAuthor */
         $objAuthor = $objFaq->getRelated('author');
         $objTemp->info = sprintf($GLOBALS['TL_LANG']['MSC']['faqCreatedBy'], \Date::parse($objPage->dateFormat, $objFaq->tstamp), $objAuthor->name);
         /** @var FaqCategoryModel $objPid */
         $objPid = $objFaq->getRelated('pid');
         // Order by PID
         $arrFaqs[$objFaq->pid]['items'][] = $objTemp;
         $arrFaqs[$objFaq->pid]['headline'] = $objPid->headline;
         $arrFaqs[$objFaq->pid]['title'] = $objPid->title;
     }
     $arrFaqs = array_values(array_filter($arrFaqs));
     $limit_i = count($arrFaqs) - 1;
     // Add classes first, last, even and odd
     for ($i = 0; $i <= $limit_i; $i++) {
         $class = ($i == 0 ? 'first ' : '') . ($i == $limit_i ? 'last ' : '') . ($i % 2 == 0 ? 'even' : 'odd');
         $arrFaqs[$i]['class'] = trim($class);
         $limit_j = count($arrFaqs[$i]['items']) - 1;
         for ($j = 0; $j <= $limit_j; $j++) {
             $class = ($j == 0 ? 'first ' : '') . ($j == $limit_j ? 'last ' : '') . ($j % 2 == 0 ? 'even' : 'odd');
             $arrFaqs[$i]['items'][$j]->class = trim($class);
         }
     }
     $this->Template->faq = $arrFaqs;
     $this->Template->request = \Environment::get('indexFreeRequest');
     $this->Template->topLink = $GLOBALS['TL_LANG']['MSC']['backToTop'];
 }
Пример #17
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);
 }
Пример #18
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);
 }
Пример #19
0
 /**
  * Run the controller and parse the template
  *
  * @return Response
  */
 public function run()
 {
     if ($this->strFile == '') {
         die('No file given');
     }
     // Make sure there are no attempts to hack the file system
     if (preg_match('@^\\.+@i', $this->strFile) || preg_match('@\\.+/@i', $this->strFile) || preg_match('@(://)+@i', $this->strFile)) {
         die('Invalid file name');
     }
     // Limit preview to the files directory
     if (!preg_match('@^' . preg_quote(\Config::get('uploadPath'), '@') . '@i', $this->strFile)) {
         die('Invalid path');
     }
     // Check whether the file exists
     if (!file_exists(TL_ROOT . '/' . $this->strFile)) {
         die('File not found');
     }
     // Check whether the file is mounted (thanks to Marko Cupic)
     if (!$this->User->hasAccess($this->strFile, 'filemounts')) {
         die('Permission denied');
     }
     // Open the download dialogue
     if (\Input::get('download')) {
         $objFile = new \File($this->strFile);
         $objFile->sendToBrowser();
     }
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_popup');
     // Add the resource (see #6880)
     if (($objModel = \FilesModel::findByPath($this->strFile)) === null) {
         if (\Dbafs::shouldBeSynchronized($this->strFile)) {
             $objModel = \Dbafs::addResource($this->strFile);
         }
     }
     if ($objModel !== null) {
         $objTemplate->uuid = \StringUtil::binToUuid($objModel->uuid);
         // see #5211
     }
     // Add the file info
     if (is_dir(TL_ROOT . '/' . $this->strFile)) {
         $objFile = new \Folder($this->strFile);
         $objTemplate->filesize = $this->getReadableSize($objFile->size) . ' (' . number_format($objFile->size, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)';
     } else {
         $objFile = new \File($this->strFile);
         // Image
         if ($objFile->isImage) {
             $objTemplate->isImage = true;
             $objTemplate->width = $objFile->width;
             $objTemplate->height = $objFile->height;
             $objTemplate->src = $this->urlEncode($this->strFile);
         }
         $objTemplate->href = ampersand(\Environment::get('request'), true) . '&amp;download=1';
         $objTemplate->filesize = $this->getReadableSize($objFile->filesize) . ' (' . number_format($objFile->filesize, 0, $GLOBALS['TL_LANG']['MSC']['decimalSeparator'], $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']) . ' Byte)';
     }
     $objTemplate->icon = $objFile->icon;
     $objTemplate->mime = $objFile->mime;
     $objTemplate->ctime = \Date::parse(\Config::get('datimFormat'), $objFile->ctime);
     $objTemplate->mtime = \Date::parse(\Config::get('datimFormat'), $objFile->mtime);
     $objTemplate->atime = \Date::parse(\Config::get('datimFormat'), $objFile->atime);
     $objTemplate->path = specialchars($this->strFile);
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = specialchars($this->strFile);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->label_uuid = $GLOBALS['TL_LANG']['MSC']['fileUuid'];
     $objTemplate->label_imagesize = $GLOBALS['TL_LANG']['MSC']['fileImageSize'];
     $objTemplate->label_filesize = $GLOBALS['TL_LANG']['MSC']['fileSize'];
     $objTemplate->label_ctime = $GLOBALS['TL_LANG']['MSC']['fileCreated'];
     $objTemplate->label_mtime = $GLOBALS['TL_LANG']['MSC']['fileModified'];
     $objTemplate->label_atime = $GLOBALS['TL_LANG']['MSC']['fileAccessed'];
     $objTemplate->label_path = $GLOBALS['TL_LANG']['MSC']['filePath'];
     $objTemplate->download = specialchars($GLOBALS['TL_LANG']['MSC']['fileDownload']);
     return $objTemplate->getResponse();
 }
Пример #20
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     // Show logout form
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $this->Template->logout = true;
         $this->Template->formId = 'tl_logout_' . $this->id;
         $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['logout']);
         $this->Template->loggedInAs = sprintf($GLOBALS['TL_LANG']['MSC']['loggedInAs'], $this->User->username);
         $this->Template->action = ampersand(\Environment::get('indexFreeRequest'));
         if ($this->User->lastLogin > 0) {
             /** @var PageModel $objPage */
             global $objPage;
             $this->Template->lastLogin = sprintf($GLOBALS['TL_LANG']['MSC']['lastLogin'][1], \Date::parse($objPage->datimFormat, $this->User->lastLogin));
         }
         return;
     }
     $blnHasError = false;
     if (isset($_SESSION['MESSAGES'][TL_MODE]['TL_ERROR'])) {
         $blnHasError = true;
         $_SESSION['LOGIN_ERROR'] = $_SESSION['MESSAGES'][TL_MODE]['TL_ERROR'][0];
         unset($_SESSION['MESSAGES'][TL_MODE]['TL_ERROR']);
     }
     if (isset($_SESSION['LOGIN_ERROR'])) {
         $blnHasError = true;
         $this->Template->message = $_SESSION['LOGIN_ERROR'];
     }
     $this->Template->hasError = $blnHasError;
     $this->Template->username = $GLOBALS['TL_LANG']['MSC']['username'];
     $this->Template->password = $GLOBALS['TL_LANG']['MSC']['password'][0];
     $this->Template->action = ampersand(\Environment::get('indexFreeRequest'));
     $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['login']);
     $this->Template->value = \StringUtil::specialchars(\Input::post('username'));
     $this->Template->formId = 'tl_login_' . $this->id;
     $this->Template->autologin = $this->autologin && \Config::get('autologin') > 0;
     $this->Template->autoLabel = $GLOBALS['TL_LANG']['MSC']['autologin'];
 }
Пример #21
0
 /**
  * Check the account status and return true if it is active
  *
  * @return boolean True if the account is active
  */
 protected function checkAccountStatus()
 {
     $time = time();
     // Check whether the account is locked
     if ($this->locked + \Config::get('lockPeriod') > $time) {
         \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['accountLocked'], ceil(($this->locked + \Config::get('lockPeriod') - $time) / 60)));
         return false;
     } elseif ($this->disable) {
         \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
         $this->log('The account has been disabled', __METHOD__, TL_ACCESS);
         return false;
     } elseif ($this instanceof FrontendUser && !$this->login) {
         \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
         $this->log('User "' . $this->username . '" is not allowed to log in', __METHOD__, TL_ACCESS);
         return false;
     } elseif ($this->start != '' || $this->stop != '') {
         $time = \Date::floorToMinute($time);
         if ($this->start != '' && $this->start > $time) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
             $this->log('The account was not active yet (activation date: ' . \Date::parse(\Config::get('dateFormat'), $this->start) . ')', __METHOD__, TL_ACCESS);
             return false;
         }
         if ($this->stop != '' && $this->stop <= $time + 60) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['invalidLogin']);
             $this->log('The account was not active anymore (deactivation date: ' . \Date::parse(\Config::get('dateFormat'), $this->stop) . ')', __METHOD__, TL_ACCESS);
             return false;
         }
     }
     return true;
 }
Пример #22
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $blnClearInput = false;
     $intYear = \Input::get('year');
     $intMonth = \Input::get('month');
     $intDay = \Input::get('day');
     // Jump to the current period
     if (!isset($_GET['year']) && !isset($_GET['month']) && !isset($_GET['day'])) {
         switch ($this->cal_format) {
             case 'cal_year':
                 $intYear = date('Y');
                 break;
             case 'cal_month':
                 $intMonth = date('Ym');
                 break;
             case 'cal_day':
                 $intDay = date('Ymd');
                 break;
         }
         $blnClearInput = true;
     }
     $blnDynamicFormat = !$this->cal_ignoreDynamic && in_array($this->cal_format, array('cal_day', 'cal_month', 'cal_year'));
     // Create the date object
     try {
         if ($blnDynamicFormat && $intYear) {
             $this->Date = new \Date($intYear, 'Y');
             $this->cal_format = 'cal_year';
             $this->headline .= ' ' . date('Y', $this->Date->tstamp);
         } elseif ($blnDynamicFormat && $intMonth) {
             $this->Date = new \Date($intMonth, 'Ym');
             $this->cal_format = 'cal_month';
             $this->headline .= ' ' . \Date::parse('F Y', $this->Date->tstamp);
         } elseif ($blnDynamicFormat && $intDay) {
             $this->Date = new \Date($intDay, 'Ymd');
             $this->cal_format = 'cal_day';
             $this->headline .= ' ' . \Date::parse($objPage->dateFormat, $this->Date->tstamp);
         } else {
             $this->Date = new \Date();
         }
     } catch (\OutOfBoundsException $e) {
         throw new PageNotFoundException('Page not found');
     }
     list($strBegin, $strEnd, $strEmpty) = $this->getDatesFromFormat($this->Date, $this->cal_format);
     // Get all events
     $arrAllEvents = $this->getAllEvents($this->cal_calendar, $strBegin, $strEnd);
     $sort = $this->cal_order == 'descending' ? 'krsort' : 'ksort';
     // Sort the days
     $sort($arrAllEvents);
     // Sort the events
     foreach (array_keys($arrAllEvents) as $key) {
         $sort($arrAllEvents[$key]);
     }
     $arrEvents = array();
     $dateBegin = date('Ymd', $strBegin);
     $dateEnd = date('Ymd', $strEnd);
     // Remove events outside the scope
     foreach ($arrAllEvents as $key => $days) {
         if ($key < $dateBegin || $key > $dateEnd) {
             continue;
         }
         foreach ($days as $day => $events) {
             foreach ($events as $event) {
                 $event['firstDay'] = $GLOBALS['TL_LANG']['DAYS'][date('w', $day)];
                 $event['firstDate'] = \Date::parse($objPage->dateFormat, $day);
                 $arrEvents[] = $event;
             }
         }
     }
     unset($arrAllEvents);
     $total = count($arrEvents);
     $limit = $total;
     $offset = 0;
     // Overall limit
     if ($this->cal_limit > 0) {
         $total = min($this->cal_limit, $total);
         $limit = $total;
     }
     // Pagination
     if ($this->perPage > 0) {
         $id = 'page_e' . $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');
         }
         $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  ");
     }
     $strMonth = '';
     $strDate = '';
     $strEvents = '';
     $dayCount = 0;
     $eventCount = 0;
     $headerCount = 0;
     $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;
         }
     }
     // Parse events
     for ($i = $offset; $i < $limit; $i++) {
         $event = $arrEvents[$i];
         $blnIsLastEvent = false;
         // Last event on the current day
         if ($i + 1 == $limit || !isset($arrEvents[$i + 1]['firstDate']) || $event['firstDate'] != $arrEvents[$i + 1]['firstDate']) {
             $blnIsLastEvent = true;
         }
         /** @var FrontendTemplate|object $objTemplate */
         $objTemplate = new \FrontendTemplate($this->cal_template);
         $objTemplate->setData($event);
         // Month header
         if ($strMonth != $event['month']) {
             $objTemplate->newMonth = true;
             $strMonth = $event['month'];
         }
         // Day header
         if ($strDate != $event['firstDate']) {
             $headerCount = 0;
             $objTemplate->header = true;
             $objTemplate->classHeader = ($dayCount % 2 == 0 ? ' even' : ' odd') . ($dayCount == 0 ? ' first' : '') . ($event['firstDate'] == $arrEvents[$limit - 1]['firstDate'] ? ' last' : '');
             $strDate = $event['firstDate'];
             ++$dayCount;
         }
         // Show the teaser text of redirect events (see #6315)
         if (is_bool($event['details'])) {
             $objTemplate->hasDetails = false;
         }
         // Add the template variables
         $objTemplate->classList = $event['class'] . ($headerCount % 2 == 0 ? ' even' : ' odd') . ($headerCount == 0 ? ' first' : '') . ($blnIsLastEvent ? ' last' : '') . ' cal_' . $event['parent'];
         $objTemplate->classUpcoming = $event['class'] . ($eventCount % 2 == 0 ? ' even' : ' odd') . ($eventCount == 0 ? ' first' : '') . ($offset + $eventCount + 1 >= $limit ? ' last' : '') . ' cal_' . $event['parent'];
         $objTemplate->readMore = specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['readMore'], $event['title']));
         $objTemplate->more = $GLOBALS['TL_LANG']['MSC']['more'];
         $objTemplate->locationLabel = $GLOBALS['TL_LANG']['MSC']['location'];
         // Short view
         if ($this->cal_noSpan) {
             $objTemplate->day = $event['day'];
             $objTemplate->date = $event['date'];
         } else {
             $objTemplate->day = $event['firstDay'];
             $objTemplate->date = $event['firstDate'];
         }
         $objTemplate->addImage = false;
         // Add an image
         if ($event['addImage'] && $event['singleSRC'] != '') {
             $objModel = \FilesModel::findByUuid($event['singleSRC']);
             if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) {
                 if ($imgSize) {
                     $event['size'] = $imgSize;
                 }
                 $event['singleSRC'] = $objModel->path;
                 $this->addImageToTemplate($objTemplate, $event);
             }
         }
         $objTemplate->enclosure = array();
         // Add enclosure
         if ($event['addEnclosure']) {
             $this->addEnclosuresToTemplate($objTemplate, $event);
         }
         $strEvents .= $objTemplate->parse();
         ++$eventCount;
         ++$headerCount;
     }
     // No events found
     if ($strEvents == '') {
         $strEvents = "\n" . '<div class="empty">' . $strEmpty . '</div>' . "\n";
     }
     // See #3672
     $this->Template->headline = $this->headline;
     $this->Template->events = $strEvents;
     // Clear the $_GET array (see #2445)
     if ($blnClearInput) {
         \Input::setGet('year', null);
         \Input::setGet('month', null);
         \Input::setGet('day', null);
     }
 }
Пример #23
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     if ($this->rss_template != 'rss_default') {
         $this->strTemplate = $this->rss_template;
         /** @var FrontendTemplate|object $objTemplate */
         $objTemplate = new \FrontendTemplate($this->strTemplate);
         $this->Template = $objTemplate;
         $this->Template->setData($this->arrData);
     }
     $this->Template->link = $this->objFeed->get_link();
     $this->Template->title = $this->objFeed->get_title();
     $this->Template->language = $this->objFeed->get_language();
     $this->Template->description = $this->objFeed->get_description();
     $this->Template->copyright = $this->objFeed->get_copyright();
     // Add image
     if ($this->objFeed->get_image_url()) {
         $this->Template->image = true;
         $this->Template->src = $this->objFeed->get_image_url();
         $this->Template->alt = $this->objFeed->get_image_title();
         $this->Template->href = $this->objFeed->get_image_link();
         $this->Template->height = $this->objFeed->get_image_height();
         $this->Template->width = $this->objFeed->get_image_width();
     }
     // Get the items (see #6107)
     $arrItems = array_slice($this->objFeed->get_items(0, intval($this->numberOfItems) + intval($this->skipFirst)), intval($this->skipFirst), intval($this->numberOfItems) ?: null);
     $limit = count($arrItems);
     $offset = 0;
     // Split pages
     if ($this->perPage > 0) {
         // Get the current page
         $id = 'page_r' . $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(count($arrItems) / $this->perPage), 1)) {
             throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
         }
         // Set limit and offset
         $offset = ($page - 1) * $this->perPage;
         $limit = $this->perPage + $offset;
         $objPagination = new \Pagination(count($arrItems), $this->perPage, \Config::get('maxPaginationLinks'), $id);
         $this->Template->pagination = $objPagination->generate("\n  ");
     }
     $items = array();
     $last = min($limit, count($arrItems)) - 1;
     /** @var \SimplePie_Item[] $arrItems */
     for ($i = $offset, $c = count($arrItems); $i < $limit && $i < $c; $i++) {
         $items[$i] = array('link' => $arrItems[$i]->get_link(), 'title' => $arrItems[$i]->get_title(), 'permalink' => $arrItems[$i]->get_permalink(), 'description' => str_replace(array('<?', '?>'), array('&lt;?', '?&gt;'), $arrItems[$i]->get_description()), 'class' => ($i == 0 ? ' first' : '') . ($i == $last ? ' last' : '') . ($i % 2 == 0 ? ' even' : ' odd'), 'pubdate' => \Date::parse($objPage->datimFormat, $arrItems[$i]->get_date('U')), 'category' => $arrItems[$i]->get_category(0), 'object' => $arrItems[$i]);
         // Add author
         if (($objAuthor = $arrItems[$i]->get_author(0)) != false) {
             $items[$i]['author'] = trim($objAuthor->name . ' ' . $objAuthor->email);
         }
         // Add enclosure
         if (($objEnclosure = $arrItems[$i]->get_enclosure(0)) != false) {
             $items[$i]['enclosure'] = $objEnclosure->get_link();
         }
     }
     $this->Template->items = array_values($items);
 }
Пример #24
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     // Show logout form
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $this->Template->logout = true;
         $this->Template->formId = 'tl_logout_' . $this->id;
         $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['logout']);
         $this->Template->loggedInAs = sprintf($GLOBALS['TL_LANG']['MSC']['loggedInAs'], $this->User->username);
         $this->Template->action = ampersand(\Environment::get('indexFreeRequest'));
         if ($this->User->lastLogin > 0) {
             /** @var PageModel $objPage */
             global $objPage;
             $this->Template->lastLogin = sprintf($GLOBALS['TL_LANG']['MSC']['lastLogin'][1], \Date::parse($objPage->datimFormat, $this->User->lastLogin));
         }
         return;
     }
     $flashBag = \System::getContainer()->get('session')->getFlashBag();
     if ($flashBag->has($this->strFlashType)) {
         $this->Template->hasError = true;
         $this->Template->message = $flashBag->get($this->strFlashType)[0];
     }
     $this->Template->username = $GLOBALS['TL_LANG']['MSC']['username'];
     $this->Template->password = $GLOBALS['TL_LANG']['MSC']['password'][0];
     $this->Template->action = ampersand(\Environment::get('indexFreeRequest'));
     $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['login']);
     $this->Template->value = \StringUtil::specialchars(\Input::post('username'));
     $this->Template->formId = 'tl_login_' . $this->id;
     $this->Template->autologin = $this->autologin && \Config::get('autologin') > 0;
     $this->Template->autoLabel = $GLOBALS['TL_LANG']['MSC']['autologin'];
 }
Пример #25
0
 /**
  * Add the welcome screen
  *
  * @return string
  */
 protected function welcomeScreen()
 {
     \System::loadLanguageFile('explain');
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_welcome');
     $objTemplate->messages = \Message::generateUnwrapped() . \Backend::getSystemMessages();
     $objTemplate->loginMsg = $GLOBALS['TL_LANG']['MSC']['firstLogin'];
     // Add the login message
     if ($this->User->lastLogin > 0) {
         $formatter = new DateTimeFormatter(\System::getContainer()->get('translator'));
         $diff = $formatter->formatDiff(new \DateTime(date('Y-m-d H:i:s', $this->User->lastLogin)), new \DateTime());
         $objTemplate->loginMsg = sprintf($GLOBALS['TL_LANG']['MSC']['lastLogin'][1], '<time title="' . \Date::parse(\Config::get('datimFormat'), $this->User->lastLogin) . '">' . $diff . '</time>');
     }
     // Add the versions overview
     \Versions::addToTemplate($objTemplate);
     $objTemplate->welcome = sprintf($GLOBALS['TL_LANG']['MSC']['welcomeTo'], \Config::get('websiteTitle'));
     $objTemplate->showDifferences = \StringUtil::specialchars(str_replace("'", "\\'", $GLOBALS['TL_LANG']['MSC']['showDifferences']));
     $objTemplate->recordOfTable = \StringUtil::specialchars(str_replace("'", "\\'", $GLOBALS['TL_LANG']['MSC']['recordOfTable']));
     $objTemplate->systemMessages = $GLOBALS['TL_LANG']['MSC']['systemMessages'];
     $objTemplate->shortcuts = $GLOBALS['TL_LANG']['MSC']['shortcuts'][0];
     $objTemplate->shortcutsLink = $GLOBALS['TL_LANG']['MSC']['shortcuts'][1];
     $objTemplate->editElement = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['editElement']);
     return $objTemplate->parse();
 }
Пример #26
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $this->Template->event = '';
     $this->Template->referer = 'javascript:history.go(-1)';
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     // Get the current event
     $objEvent = \CalendarEventsModel::findPublishedByParentAndIdOrAlias(\Input::get('events'), $this->cal_calendar);
     if (null === $objEvent) {
         throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
     }
     // Overwrite the page title (see #2853 and #4955)
     if ($objEvent->title != '') {
         $objPage->pageTitle = strip_tags(\StringUtil::stripInsertTags($objEvent->title));
     }
     // Overwrite the page description
     if ($objEvent->teaser != '') {
         $objPage->description = $this->prepareMetaDescription($objEvent->teaser);
     }
     $intStartTime = $objEvent->startTime;
     $intEndTime = $objEvent->endTime;
     $span = \Calendar::calculateSpan($intStartTime, $intEndTime);
     // Do not show dates in the past if the event is recurring (see #923)
     if ($objEvent->recurring) {
         $arrRange = \StringUtil::deserialize($objEvent->repeatEach);
         if (is_array($arrRange) && isset($arrRange['unit']) && isset($arrRange['value'])) {
             while ($intStartTime < time() && $intEndTime < $objEvent->repeatEnd) {
                 $intStartTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intStartTime);
                 $intEndTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intEndTime);
             }
         }
     }
     $strDate = \Date::parse($objPage->dateFormat, $intStartTime);
     if ($span > 0) {
         $strDate = \Date::parse($objPage->dateFormat, $intStartTime) . ' – ' . \Date::parse($objPage->dateFormat, $intEndTime);
     }
     $strTime = '';
     if ($objEvent->addTime) {
         if ($span > 0) {
             $strDate = \Date::parse($objPage->datimFormat, $intStartTime) . ' – ' . \Date::parse($objPage->datimFormat, $intEndTime);
         } elseif ($intStartTime == $intEndTime) {
             $strTime = \Date::parse($objPage->timeFormat, $intStartTime);
         } else {
             $strTime = \Date::parse($objPage->timeFormat, $intStartTime) . ' – ' . \Date::parse($objPage->timeFormat, $intEndTime);
         }
     }
     $until = '';
     $recurring = '';
     // Recurring event
     if ($objEvent->recurring) {
         $arrRange = \StringUtil::deserialize($objEvent->repeatEach);
         if (is_array($arrRange) && isset($arrRange['unit']) && isset($arrRange['value'])) {
             $strKey = 'cal_' . $arrRange['unit'];
             $recurring = sprintf($GLOBALS['TL_LANG']['MSC'][$strKey], $arrRange['value']);
             if ($objEvent->recurrences > 0) {
                 $until = sprintf($GLOBALS['TL_LANG']['MSC']['cal_until'], \Date::parse($objPage->dateFormat, $objEvent->repeatEnd));
             }
         }
     }
     /** @var FrontendTemplate|object $objTemplate */
     $objTemplate = new \FrontendTemplate($this->cal_template);
     $objTemplate->setData($objEvent->row());
     $objTemplate->date = $strDate;
     $objTemplate->time = $strTime;
     $objTemplate->datetime = $objEvent->addTime ? date('Y-m-d\\TH:i:sP', $intStartTime) : date('Y-m-d', $intStartTime);
     $objTemplate->begin = $intStartTime;
     $objTemplate->end = $intEndTime;
     $objTemplate->class = $objEvent->cssClass != '' ? ' ' . $objEvent->cssClass : '';
     $objTemplate->recurring = $recurring;
     $objTemplate->until = $until;
     $objTemplate->locationLabel = $GLOBALS['TL_LANG']['MSC']['location'];
     $objTemplate->details = '';
     $objTemplate->hasDetails = false;
     $objTemplate->hasTeaser = false;
     // Clean the RTE output
     if ($objEvent->teaser != '') {
         $objTemplate->hasTeaser = true;
         $objTemplate->teaser = \StringUtil::toHtml5($objEvent->teaser);
         $objTemplate->teaser = \StringUtil::encodeEmail($objTemplate->teaser);
     }
     // Display the "read more" button for external/article links
     if ($objEvent->source != 'default') {
         $objTemplate->details = true;
         $objTemplate->hasDetails = true;
     } else {
         $id = $objEvent->id;
         $objTemplate->details = function () use($id) {
             $strDetails = '';
             $objElement = \ContentModel::findPublishedByPidAndTable($id, 'tl_calendar_events');
             if ($objElement !== null) {
                 while ($objElement->next()) {
                     $strDetails .= $this->getContentElement($objElement->current());
                 }
             }
             return $strDetails;
         };
         $objTemplate->hasDetails = function () use($id) {
             return \ContentModel::countPublishedByPidAndTable($id, 'tl_calendar_events') > 0;
         };
     }
     $objTemplate->addImage = false;
     // Add an image
     if ($objEvent->addImage && $objEvent->singleSRC != '') {
         $objModel = \FilesModel::findByUuid($objEvent->singleSRC);
         if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) {
             // Do not override the field now that we have a model registry (see #6303)
             $arrEvent = $objEvent->row();
             // Override the default image size
             if ($this->imgSize != '') {
                 $size = \StringUtil::deserialize($this->imgSize);
                 if ($size[0] > 0 || $size[1] > 0 || is_numeric($size[2])) {
                     $arrEvent['size'] = $this->imgSize;
                 }
             }
             $arrEvent['singleSRC'] = $objModel->path;
             $this->addImageToTemplate($objTemplate, $arrEvent);
         }
     }
     $objTemplate->enclosure = array();
     // Add enclosures
     if ($objEvent->addEnclosure) {
         $this->addEnclosuresToTemplate($objTemplate, $objEvent->row());
     }
     $this->Template->event = $objTemplate->parse();
     $bundles = \System::getContainer()->getParameter('kernel.bundles');
     // HOOK: comments extension required
     if ($objEvent->noComments || !isset($bundles['ContaoCommentsBundle'])) {
         $this->Template->allowComments = false;
         return;
     }
     /** @var CalendarModel $objCalendar */
     $objCalendar = $objEvent->getRelated('pid');
     $this->Template->allowComments = $objCalendar->allowComments;
     // Comments are not allowed
     if (!$objCalendar->allowComments) {
         return;
     }
     // Adjust the comments headline level
     $intHl = min(intval(str_replace('h', '', $this->hl)), 5);
     $this->Template->hlc = 'h' . ($intHl + 1);
     $this->import('Comments');
     $arrNotifies = array();
     // Notify the system administrator
     if ($objCalendar->notify != 'notify_author') {
         $arrNotifies[] = $GLOBALS['TL_ADMIN_EMAIL'];
     }
     // Notify the author
     if ($objCalendar->notify != 'notify_admin') {
         /** @var UserModel $objAuthor */
         if (($objAuthor = $objEvent->getRelated('author')) instanceof UserModel && $objAuthor->email != '') {
             $arrNotifies[] = $objAuthor->email;
         }
     }
     $objConfig = new \stdClass();
     $objConfig->perPage = $objCalendar->perPage;
     $objConfig->order = $objCalendar->sortOrder;
     $objConfig->template = $this->com_template;
     $objConfig->requireLogin = $objCalendar->requireLogin;
     $objConfig->disableCaptcha = $objCalendar->disableCaptcha;
     $objConfig->bbcode = $objCalendar->bbcode;
     $objConfig->moderate = $objCalendar->moderate;
     $this->Comments->addCommentsToTemplate($this->Template, $objConfig, 'tl_calendar_events', $objEvent->id, $arrNotifies);
 }
 /**
  * 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);
 }
Пример #28
0
 /**
  * Return the formatted group header as string
  *
  * @param string  $field
  * @param mixed   $value
  * @param integer $mode
  *
  * @return string
  */
 protected function formatCurrentValue($field, $value, $mode)
 {
     $remoteNew = $value;
     // see #3861
     if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) {
         $remoteNew = $value != '' ? ucfirst($GLOBALS['TL_LANG']['MSC']['yes']) : ucfirst($GLOBALS['TL_LANG']['MSC']['no']);
     } elseif (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['foreignKey'])) {
         $key = explode('.', $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['foreignKey'], 2);
         $objParent = $this->Database->prepare("SELECT " . $key[1] . " AS value FROM " . $key[0] . " WHERE id=?")->limit(1)->execute($value);
         if ($objParent->numRows) {
             $remoteNew = $objParent->value;
         }
     } elseif (in_array($mode, array(1, 2))) {
         $remoteNew = $value != '' ? ucfirst(Utf8::substr($value, 0, 1)) : '-';
     } elseif (in_array($mode, array(3, 4))) {
         if (!isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['length'])) {
             $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['length'] = 2;
         }
         $remoteNew = $value != '' ? ucfirst(Utf8::substr($value, 0, $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['length'])) : '-';
     } elseif (in_array($mode, array(5, 6))) {
         $remoteNew = $value != '' ? \Date::parse(\Config::get('dateFormat'), $value) : '-';
     } elseif (in_array($mode, array(7, 8))) {
         $remoteNew = $value != '' ? date('Y-m', $value) : '-';
         $intMonth = $value != '' ? date('m', $value) - 1 : '-';
         if (isset($GLOBALS['TL_LANG']['MONTHS'][$intMonth])) {
             $remoteNew = $value != '' ? $GLOBALS['TL_LANG']['MONTHS'][$intMonth] . ' ' . date('Y', $value) : '-';
         }
     } elseif (in_array($mode, array(9, 10))) {
         $remoteNew = $value != '' ? date('Y', $value) : '-';
     } else {
         if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) {
             $remoteNew = $value != '' ? $field : '';
         } elseif (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'])) {
             $remoteNew = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'][$value];
         } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options'])) {
             $remoteNew = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options'][$value];
         } else {
             $remoteNew = $value;
         }
         if (is_array($remoteNew)) {
             $remoteNew = $remoteNew[0];
         }
         if (empty($remoteNew)) {
             $remoteNew = '-';
         }
     }
     return $remoteNew;
 }
 private function compileModule($parameters, $bridgeNamespace, $module)
 {
     $file = new File($parameters['path'], true);
     $file->truncate();
     $file->putContent($parameters['path'], '<?php ' . "\n" . "\n" . '/**' . "\n" . ' * DESCRIPTION' . "\n" . ' *' . "\n" . ' * Copyright (C) ORGANISE' . "\n" . ' *' . "\n" . ' * @package   PACKAGE NAME' . "\n" . ' * @file      ' . $module . '.php' . "\n" . ' * @author    AUTHOR' . "\n" . ' * @license   GNU/LGPL' . "\n" . ' * @copyright Copyright ' . Date::parse('Y', time()) . ' ORGANISE' . "\n" . ' */' . "\n" . "\n" . "\n" . 'namespace ' . $bridgeNamespace . ';' . "\n" . "\n" . 'class ' . $module . ' extends \\' . $bridgeNamespace . 'Bridge\\' . $module . "\n" . '{' . "\n" . '}');
 }