Usage: $short = StringUtil::substr($str, 32); $html = StringUtil::substrHtml($str, 32); $xhtml = StringUtil::toXhtml($html5);
Example #1
0
 /**
  * Run the controller and parse the login template
  *
  * @return Response
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_login');
     $strHeadline = sprintf($GLOBALS['TL_LANG']['MSC']['loginTo'], \Config::get('websiteTitle'));
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->messages = \Message::generate();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->languages = \System::getLanguages(true);
     $objTemplate->title = \StringUtil::specialchars($strHeadline);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->userLanguage = $GLOBALS['TL_LANG']['tl_user']['language'][0];
     $objTemplate->headline = $strHeadline;
     $objTemplate->curLanguage = \Input::post('language') ?: str_replace('-', '_', $GLOBALS['TL_LANGUAGE']);
     $objTemplate->curUsername = \Input::post('username') ?: '';
     $objTemplate->uClass = $_POST && empty($_POST['username']) ? ' class="login_error"' : '';
     $objTemplate->pClass = $_POST && empty($_POST['password']) ? ' class="login_error"' : '';
     $objTemplate->loginButton = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['loginBT']);
     $objTemplate->username = $GLOBALS['TL_LANG']['tl_user']['username'][0];
     $objTemplate->password = $GLOBALS['TL_LANG']['MSC']['password'][0];
     $objTemplate->feLink = $GLOBALS['TL_LANG']['MSC']['feLink'];
     $objTemplate->default = $GLOBALS['TL_LANG']['MSC']['default'];
     $objTemplate->jsDisabled = $GLOBALS['TL_LANG']['MSC']['jsDisabled'];
     return $objTemplate->getResponse();
 }
Example #2
0
 /**
  * Display a wildcard in the back end
  *
  * @return string
  */
 public function generate()
 {
     if (TL_MODE == 'BE') {
         /** @var BackendTemplate|object $objTemplate */
         $objTemplate = new \BackendTemplate('be_wildcard');
         $objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['FMD']['rssReader'][0]) . ' ###';
         $objTemplate->title = $this->headline;
         $objTemplate->id = $this->id;
         $objTemplate->link = $this->name;
         $objTemplate->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
         return $objTemplate->parse();
     }
     $this->objFeed = new \SimplePie();
     $arrUrls = \StringUtil::trimsplit('[\\n\\t ]', trim($this->rss_feed));
     if (count($arrUrls) > 1) {
         $this->objFeed->set_feed_url($arrUrls);
     } else {
         $this->objFeed->set_feed_url($arrUrls[0]);
     }
     $this->objFeed->set_output_encoding(\Config::get('characterSet'));
     $this->objFeed->set_cache_location(TL_ROOT . '/system/tmp');
     $this->objFeed->enable_cache(false);
     if ($this->rss_cache > 0) {
         $this->objFeed->enable_cache(true);
         $this->objFeed->set_cache_duration($this->rss_cache);
     }
     if (!$this->objFeed->init()) {
         $this->log('Error importing RSS feed "' . $this->rss_feed . '"', __METHOD__, TL_ERROR);
         return '';
     }
     $this->objFeed->handle_content_type();
     return parent::generate();
 }
Example #3
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     if (!strlen($this->inColumn)) {
         $this->inColumn = 'main';
     }
     $intCount = 0;
     $articles = array();
     $id = $objPage->id;
     $this->Template->request = \Environment::get('request');
     // Show the articles of a different page
     if ($this->defineRoot && $this->rootPage > 0) {
         if (($objTarget = $this->objModel->getRelated('rootPage')) instanceof PageModel) {
             $id = $objTarget->id;
             /** @var PageModel $objTarget */
             $this->Template->request = $objTarget->getFrontendUrl();
         }
     }
     // Get published articles
     $objArticles = \ArticleModel::findPublishedByPidAndColumn($id, $this->inColumn);
     if ($objArticles === null) {
         return;
     }
     while ($objArticles->next()) {
         // Skip first article
         if (++$intCount <= intval($this->skipFirst)) {
             continue;
         }
         $cssID = \StringUtil::deserialize($objArticles->cssID, true);
         $articles[] = array('link' => $objArticles->title, 'title' => \StringUtil::specialchars($objArticles->title), 'id' => $cssID[0] ?: 'article-' . $objArticles->id, 'articleId' => $objArticles->id);
     }
     $this->Template->articles = $articles;
 }
 public function split_and_fix($size, $scss, $grid, $width, $paddingTop, $paddingBottom, $default)
 {
     if ($size == 'XS') {
         $grid = '90';
         $unitGrid = '%';
         $width = '90';
         $unitWidth = '%';
     } else {
         $gridvar = is_array($grid) ? $grid : \Contao\StringUtil::deserialize($grid);
         $widthvar = is_array($width) ? $width : \Contao\StringUtil::deserialize($width);
         $paddingTopvar = is_array($paddingTop) ? $paddingTop : \Contao\StringUtil::deserialize($paddingTop);
         $paddingBottomvar = is_array($paddingBottom) ? $paddingBottom : \Contao\StringUtil::deserialize($paddingBottom);
         $grid = empty($gridvar['value']) ? $default['Grid'][$size] : $gridvar['value'];
         $unitGrid = empty($gridvar['unit']) ? $default['GridUnit'][$size] : $gridvar['unit'];
         $width = empty($widthvar['value']) ? $default['Width'][$size] : $widthvar['value'];
         $unitWidth = empty($widthvar['unit']) ? $default['WidthUnit'][$size] : $widthvar['unit'];
     }
     $paddingTop = empty($paddingTopvar['value']) ? $default['PaddingTop'][$size] : $paddingTopvar['value'];
     $unitPadingTop = empty($paddingTopvar['unit']) ? $default['PaddingTopUnit'][$size] : $paddingTopvar['unit'];
     $paddingBottom = empty($paddingBottomvar['value']) ? $default['PaddingBottom'][$size] : $paddingBottomvar['value'];
     $unitPadingBottom = empty($paddingBottomvar['unit']) ? $default['PaddingBottomUnit'][$size] : $paddingBottomvar['unit'];
     $grid1 = (int) $grid - 1;
     $scss = str_replace('[[grid' . $size . ']]', $grid . $unitGrid, $scss);
     $scss = str_replace('[[grid' . $size . '1]]', $grid1 . $unitGrid, $scss);
     $scss = str_replace('[[width' . $size . ']]', $width . $unitWidth, $scss);
     $scss = str_replace('[[paddingTop' . $size . ']]', $paddingTop . $unitPadingTop, $scss);
     $scss = str_replace('[[paddingBottom' . $size . ']]', $paddingBottom . $unitPadingBottom, $scss);
     return $scss;
 }
Example #5
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     $objFaq = \FaqModel::findPublishedByPids($this->faq_categories);
     if ($objFaq === null) {
         $this->Template->faq = array();
         return;
     }
     $arrFaq = array_fill_keys($this->faq_categories, array());
     // Add FAQs
     while ($objFaq->next()) {
         $arrTemp = $objFaq->row();
         $arrTemp['title'] = \StringUtil::specialchars($objFaq->question, true);
         $arrTemp['href'] = $this->generateFaqLink($objFaq);
         /** @var FaqCategoryModel $objPid */
         $objPid = $objFaq->getRelated('pid');
         $arrFaq[$objFaq->pid]['items'][] = $arrTemp;
         $arrFaq[$objFaq->pid]['headline'] = $objPid->headline;
         $arrFaq[$objFaq->pid]['title'] = $objPid->title;
     }
     $arrFaq = array_values(array_filter($arrFaq));
     $cat_count = 0;
     $cat_limit = count($arrFaq);
     // Add classes
     foreach ($arrFaq as $k => $v) {
         $count = 0;
         $limit = count($v['items']);
         for ($i = 0; $i < $limit; $i++) {
             $arrFaq[$k]['items'][$i]['class'] = trim((++$count == 1 ? ' first' : '') . ($count >= $limit ? ' last' : '') . ($count % 2 == 0 ? ' odd' : ' even'));
         }
         $arrFaq[$k]['class'] = trim((++$cat_count == 1 ? ' first' : '') . ($cat_count >= $cat_limit ? ' last' : '') . ($cat_count % 2 == 0 ? ' odd' : ' even'));
     }
     $this->Template->faq = $arrFaq;
 }
 /**
  * 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;
 }
Example #7
0
 /**
  * Display a wildcard in the back end
  *
  * @return string
  */
 public function generate()
 {
     if (TL_MODE == 'BE') {
         /** @var BackendTemplate|object $objTemplate */
         $objTemplate = new \BackendTemplate('be_wildcard');
         $objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['FMD']['newsarchive'][0]) . ' ###';
         $objTemplate->title = $this->headline;
         $objTemplate->id = $this->id;
         $objTemplate->link = $this->name;
         $objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;
         return $objTemplate->parse();
     }
     $this->news_archives = $this->sortOutProtected(\StringUtil::deserialize($this->news_archives));
     // No news archives available
     if (!is_array($this->news_archives) || empty($this->news_archives)) {
         return '';
     }
     // Show the news reader if an item has been selected
     if ($this->news_readerModule > 0 && (isset($_GET['items']) || \Config::get('useAutoItem') && isset($_GET['auto_item']))) {
         return $this->getFrontendModule($this->news_readerModule, $this->strColumn);
     }
     // Hide the module if no period has been selected
     if ($this->news_jumpToCurrent == 'hide_module' && !isset($_GET['year']) && !isset($_GET['month']) && !isset($_GET['day'])) {
         return '';
     }
     return parent::generate();
 }
Example #8
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     // Set the trail and level
     if ($this->defineRoot && $this->rootPage > 0) {
         $trail = array($this->rootPage);
         $level = 0;
     } else {
         $trail = $objPage->trail;
         $level = $this->levelOffset > 0 ? $this->levelOffset : 0;
     }
     $lang = null;
     $host = null;
     // Overwrite the domain and language if the reference page belongs to a differnt root page (see #3765)
     if ($this->defineRoot && $this->rootPage > 0) {
         $objRootPage = \PageModel::findWithDetails($this->rootPage);
         // Set the language
         if (\Config::get('addLanguageToUrl') && $objRootPage->rootLanguage != $objPage->rootLanguage) {
             $lang = $objRootPage->rootLanguage;
         }
         // Set the domain
         if ($objRootPage->rootId != $objPage->rootId && $objRootPage->domain != '' && $objRootPage->domain != $objPage->domain) {
             $host = $objRootPage->domain;
         }
     }
     $this->Template->request = ampersand(\Environment::get('indexFreeRequest'));
     $this->Template->skipId = 'skipNavigation' . $this->id;
     $this->Template->skipNavigation = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['skipNavigation']);
     $this->Template->items = $this->renderNavigation($trail[$level], 1, $host, $lang);
 }
 /**
  * {@inheritdoc}
  */
 protected function write(array $record)
 {
     $this->createStatement();
     /** @var \DateTime $date */
     $date = $record['datetime'];
     /** @var ContaoContext $context */
     $context = $record['extra']['contao'];
     $this->statement->execute(['tstamp' => $date->format('U'), 'text' => StringUtil::specialchars((string) $record['formatted']), 'source' => (string) $context->getSource(), 'action' => (string) $context->getAction(), 'username' => (string) $context->getUsername(), 'func' => (string) $context->getFunc(), 'ip' => (string) $context->getIp(), 'browser' => (string) $context->getBrowser()]);
 }
Example #10
0
 /**
  * Show the raw markdown code in the back end
  *
  * @return string
  */
 public function generate()
 {
     if (TL_MODE == 'BE') {
         $return = '<pre>' . \StringUtil::specialchars($this->code) . '</pre>';
         if ($this->headline != '') {
             $return = '<' . $this->hl . '>' . $this->headline . '</' . $this->hl . '>' . $return;
         }
         return $return;
     }
     return parent::generate();
 }
Example #11
0
 /**
  * Run the controller and parse the template
  *
  * @return Response
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_alerts');
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['systemMessages']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->messages = \Message::generateUnwrapped() . \Backend::getSystemMessages();
     return $objTemplate->getResponse();
 }
Example #12
0
 public function scopeUuid(Builder $query, $uuid)
 {
     if (is_array($uuid)) {
         $uuid = array_map(function ($uuid) {
             return Validator::isStringUuid($uuid) ? StringUtil::uuidToBin($uuid) : $uuid;
         }, $uuid);
         return $query->whereIn('uuid', $uuid);
     }
     if (Validator::isStringUuid($uuid)) {
         $uuid = StringUtil::uuidToBin($uuid);
     }
     return $query->where('uuid', $uuid);
 }
 private function setContaoFile($file)
 {
     if (is_array($file)) {
         return serialize(array_map([__CLASS__, 'setContaoFile'], $file));
     }
     if ($file instanceof FilesModel) {
         return $file->uuid;
     }
     if (Validator::isStringUuid($file)) {
         return StringUtil::uuidToBin($file);
     }
     return $file;
 }
 /**
  * Adds the feeds to the page header.
  *
  * @param PageModel          $objPage
  * @param LayoutModel|object $objLayout
  */
 public function onGeneratePage(PageModel $objPage, LayoutModel $objLayout)
 {
     $newsfeeds = StringUtil::deserialize($objLayout->newsfeeds);
     if (empty($newsfeeds) || !is_array($newsfeeds)) {
         return;
     }
     $this->framework->initialize();
     /** @var NewsFeedModel $adapter */
     $adapter = $this->framework->getAdapter(NewsFeedModel::class);
     if (!($feeds = $adapter->findByIds($newsfeeds)) instanceof Collection) {
         return;
     }
     $this->addFeedMarkupToPageHeader($feeds);
 }
Example #15
0
    /**
     * Tests the StringUtil::extactEmail() method.
     */
    public function testExtractEmail()
    {
        $text = <<<EOF
This is a niceandsimple@example.com and this a very.common@example.com. Another little.lengthy.but.fine@dept.example.com and also a disposable.style.email.with+symbol@example.com or an other.email-with-dash@example.com. There are "*****@*****.**"@example.com and "very.(),:;<>[]\\".VERY.\\"very@\\ \\"very\\".unusual"@strange.example.com and even !#\$%&'*+-/=?^_`{}|~@example.org or "()<>[]:,;@\\"!#\$%&'*+-/=?^_`{}|~.a"@example.org but they are all valid.
IP addresses as in user@[255.255.255.255], user@[IPv6:2001:db8:1ff::a0b:dbd0], user@[IPv6:2001:0db8:85a3:08d3:1319:8a2e:0370:7344], user@[IPv6:2001::7344] or user@[IPv6:1111:2222:3333:4444:5555:6666:255.255.255.255] are valid, too.
We also support IDNA domains as in test@exรคmple.com, test@รค-.xe, test@subexample.wizard, test@wรคhwรคhwรคh.รผmlรครผts.de or "tes@t"@wรคhwรคhwรคh.รผmlรครผts.de. And we support new TLDs as in test@example.photography or test@sub-domain.example.photography.
And we support unicode characters in the local part (RFC 6531) as in niceรคndsimple@example.com, vรฉry.รงommon@example.com, a.lรฎttle.lengthy.but.fiรฑe@dept.example.com, dรฎsposable.style.รฉmail.with+symbol@example.com, other.รฉmail-with-dash@example.com, "verรฎ.uรฑusual.@.uรฑusual.com"@example.com, "verรฎ.(),:;<>[]\\".VERรŽ.\\"verรฎ@\\ \\"verรฎ\\".unรผsual"@strange.example.com, รผรฑรฎรงรธรฐรฉ@example.com, "รผรฑรฎรงรธรฐรฉ"@example.com or ว…วผเฉงเฐ˜โ…งโ’‡เงช@example.com.
Of course also with IP addresses: รผser@[255.255.255.255], รผser@[IPv6:2001:db8:1ff::a0b:dbd0], รผser@[IPv6:2001:0db8:85a3:08d3:1319:8a2e:0370:7344], รผser@[IPv6:2001::7344] or รผser@[IPv6:1111:2222:3333:4444:5555:6666:255.255.255.255] and unicode characters in the local part: tรฉst@exรคmple.com, tรฉst@รค-.xe, tรฉst@subexample.wizard, tรฉst@wรคhwรคhwรคh.รผmlรครผts.de, "tรฉs@t"@wรคhwรคhwรคh.รผmlรครผts.de. New TLDs? No problem: tรฉst@example.photography or tรฉst@sub-domain.example.photography.
And hopefully we do not match invalid addresses such as test..child@example.com, test@sub.-example.com, test@_smtp_.example.com, test@sub..example.com, test@subexamplecom, Abc.example.com, a"b(c)d,e:f;gi[j\\k]l@example.com, this is"not\\allowed@example.com, this\\ still\\"not\\allowed@example.com, (comment)test@iana.org, test@[1.2.3.4, @ or test@.
EOF;
        $expected = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '"*****@*****.**"@example.com', '"very.(),:;<>[]\\".VERY.\\"very@\\ \\"very\\".unusual"@strange.example.com', '!#$%&\'*+-/=?^_`{}|~@example.org', '"()<>[]:,;@\\"!#$%&\'*+-/=?^_`{}|~.a"@example.org', 'user@[255.255.255.255]', 'user@[IPv6:2001:db8:1ff::a0b:dbd0]', 'user@[IPv6:2001:0db8:85a3:08d3:1319:8a2e:0370:7344]', 'user@[IPv6:2001::7344]', 'user@[IPv6:1111:2222:3333:4444:5555:6666:255.255.255.255]', 'test@exรคmple.com', 'test@รค-.xe', '*****@*****.**', 'test@wรคhwรคhwรคh.รผmlรครผts.de', '"tes@t"@wรคhwรคhwรคh.รผmlรครผts.de', '*****@*****.**', '*****@*****.**', 'niceรคndsimple@example.com', 'vรฉry.รงommon@example.com', 'a.lรฎttle.lengthy.but.fiรฑe@dept.example.com', 'dรฎsposable.style.รฉmail.with+symbol@example.com', 'other.รฉmail-with-dash@example.com', '"verรฎ.uรฑusual.@.uรฑusual.com"@example.com', '"verรฎ.(),:;<>[]\\".VERรŽ.\\"verรฎ@\\ \\"verรฎ\\".unรผsual"@strange.example.com', 'รผรฑรฎรงรธรฐรฉ@example.com', '"รผรฑรฎรงรธรฐรฉ"@example.com', 'ว…วผเฉงเฐ˜โ…งโ’‡เงช@example.com', 'รผser@[255.255.255.255]', 'รผser@[IPv6:2001:db8:1ff::a0b:dbd0]', 'รผser@[IPv6:2001:0db8:85a3:08d3:1319:8a2e:0370:7344]', 'รผser@[IPv6:2001::7344]', 'รผser@[IPv6:1111:2222:3333:4444:5555:6666:255.255.255.255]', 'tรฉst@exรคmple.com', 'tรฉst@รค-.xe', 'tรฉst@subexample.wizard', 'tรฉst@wรคhwรคhwรคh.รผmlรครผts.de', '"tรฉs@t"@wรคhwรคhwรคh.รผmlรครผts.de', 'tรฉst@example.photography', 'tรฉst@sub-domain.example.photography'];
        $actual = StringUtil::extractEmail($text);
        sort($actual);
        sort($expected);
        $this->assertEquals($expected, $actual);
    }
Example #16
0
 /**
  * Display a wildcard in the back end
  *
  * @return string
  */
 public function generate()
 {
     if (TL_MODE == 'BE') {
         /** @var BackendTemplate|object $objTemplate */
         $objTemplate = new \BackendTemplate('be_wildcard');
         $objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['FMD']['newslist'][0]) . ' ###';
         $objTemplate->title = $this->headline;
         $objTemplate->id = $this->id;
         $objTemplate->link = $this->name;
         $objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;
         return $objTemplate->parse();
     }
     $this->news_archives = $this->sortOutProtected(\StringUtil::deserialize($this->news_archives));
     // Return if there are no archives
     if (!is_array($this->news_archives) || empty($this->news_archives)) {
         return '';
     }
     return parent::generate();
 }
Example #17
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $intActive = null;
     $articles = array();
     $intCount = 1;
     foreach ($this->objArticles as $objArticle) {
         $strAlias = $objArticle->alias ?: $objArticle->id;
         // Active article
         if (\Input::get('articles') == $strAlias) {
             $articles[] = array('isActive' => true, 'href' => $objPage->getFrontendUrl('/articles/' . $strAlias), 'title' => \StringUtil::specialchars($objArticle->title, true), 'link' => $intCount);
             $intActive = $intCount - 1;
         } else {
             $articles[] = array('isActive' => false, 'href' => $objPage->getFrontendUrl('/articles/' . $strAlias), 'title' => \StringUtil::specialchars($objArticle->title, true), 'link' => $intCount);
         }
         ++$intCount;
     }
     $this->Template->articles = $articles;
     $total = count($articles);
     // Link to first element
     if ($intActive > 1) {
         $this->Template->first = array('href' => $articles[0]['href'], 'title' => $articles[0]['title'], 'link' => $GLOBALS['TL_LANG']['MSC']['first']);
     }
     $key = $intActive - 1;
     // Link to previous element
     if ($intCount > 1 && $key >= 0) {
         $this->Template->previous = array('href' => $articles[$key]['href'], 'title' => $articles[$key]['title'], 'link' => $GLOBALS['TL_LANG']['MSC']['previous']);
     }
     $key = $intActive + 1;
     // Link to next element
     if ($intCount > 1 && $key < $total) {
         $this->Template->next = array('href' => $articles[$key]['href'], 'title' => $articles[$key]['title'], 'link' => $GLOBALS['TL_LANG']['MSC']['next']);
     }
     $key = $total - 1;
     // Link to last element
     if ($intCount > 1 && $intActive < $key - 1) {
         $this->Template->last = array('href' => $articles[$key]['href'], 'title' => $articles[$key]['title'], 'link' => $GLOBALS['TL_LANG']['MSC']['last']);
     }
 }
 /**
  * Run the controller and parse the template
  *
  * @return Response
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_preview');
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['fePreview']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->site = \Input::get('site', true);
     $objTemplate->switchHref = \System::getContainer()->get('router')->generate('contao_backend_switch');
     $strUrl = null;
     if (\Input::get('url')) {
         $strUrl = \Environment::get('base') . \Input::get('url');
     } elseif (\Input::get('page')) {
         $strUrl = $this->redirectToFrontendPage(\Input::get('page'), \Input::get('article'), true);
     } else {
         $event = new PreviewUrlConvertEvent();
         \System::getContainer()->get('event_dispatcher')->dispatch(ContaoCoreEvents::PREVIEW_URL_CONVERT, $event);
         $strUrl = $event->getUrl();
     }
     if ($strUrl === null) {
         $strUrl = \System::getContainer()->get('router')->generate('contao_root', [], UrlGeneratorInterface::ABSOLUTE_URL);
     }
     $objTemplate->url = $strUrl;
     // Switch to a particular member (see #6546)
     if (\Input::get('user') && $this->User->isAdmin) {
         $objUser = \MemberModel::findByUsername(\Input::get('user'));
         if ($objUser !== null) {
             $strHash = $this->getSessionHash('FE_USER_AUTH');
             // Remove old sessions
             $this->Database->prepare("DELETE FROM tl_session WHERE tstamp<? OR hash=?")->execute(time() - \Config::get('sessionTimeout'), $strHash);
             // Insert the new session
             $this->Database->prepare("INSERT INTO tl_session (pid, tstamp, name, sessionID, ip, hash) VALUES (?, ?, ?, ?, ?, ?)")->execute($objUser->id, time(), 'FE_USER_AUTH', \System::getContainer()->get('session')->getId(), \Environment::get('ip'), $strHash);
             // Set the cookie
             $this->setCookie('FE_USER_AUTH', $strHash, time() + \Config::get('sessionTimeout'), null, null, false, true);
             $objTemplate->user = \Input::post('user');
         }
     }
     return $objTemplate->getResponse();
 }
Example #19
0
 /**
  * Run the controller and parse the password template
  *
  * @return Response
  */
 public function run()
 {
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_password');
     if (\Input::post('FORM_SUBMIT') == 'tl_password') {
         $pw = \Input::postUnsafeRaw('password');
         $cnf = \Input::postUnsafeRaw('confirm');
         // The passwords do not match
         if ($pw != $cnf) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['passwordMatch']);
         } elseif (Utf8::strlen($pw) < \Config::get('minPasswordLength')) {
             \Message::addError(sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], \Config::get('minPasswordLength')));
         } elseif ($pw == $this->User->username) {
             \Message::addError($GLOBALS['TL_LANG']['ERR']['passwordName']);
         } else {
             // Make sure the password has been changed
             if (\Encryption::verify($pw, $this->User->password)) {
                 \Message::addError($GLOBALS['TL_LANG']['MSC']['pw_change']);
             } else {
                 $this->loadDataContainer('tl_user');
                 // Trigger the save_callback
                 if (is_array($GLOBALS['TL_DCA']['tl_user']['fields']['password']['save_callback'])) {
                     foreach ($GLOBALS['TL_DCA']['tl_user']['fields']['password']['save_callback'] as $callback) {
                         if (is_array($callback)) {
                             $this->import($callback[0]);
                             $pw = $this->{$callback[0]}->{$callback[1]}($pw);
                         } elseif (is_callable($callback)) {
                             $pw = $callback($pw);
                         }
                     }
                 }
                 $objUser = \UserModel::findByPk($this->User->id);
                 $objUser->pwChange = '';
                 $objUser->password = \Encryption::hash($pw);
                 $objUser->save();
                 \Message::addConfirmation($GLOBALS['TL_LANG']['MSC']['pw_changed']);
                 $this->redirect('contao/main.php');
             }
         }
         $this->reload();
     }
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->messages = \Message::generate();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['pw_new']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['MSC']['pw_change'];
     $objTemplate->submitButton = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['continue']);
     $objTemplate->password = $GLOBALS['TL_LANG']['MSC']['password'][0];
     $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['confirm'][0];
     return $objTemplate->getResponse();
 }
 /**
  * getArticle hook
  *
  * insert custom template when
  * getArticle hook is called
  *
  */
 public function insertCustomTemplate($tpl, $data, $article)
 {
     global $objPage;
     $layoutID = $objPage->layout;
     $objLayout = \LayoutModel::findByID($layoutID);
     if ($objLayout->activateCArticles) {
         $template = new \FrontendTemplate('mod_customarticle');
         $count = count($tpl->elements);
         $containertype = 'container';
         $article_color = \Contao\StringUtil::deserialize($tpl->article_color);
         $article_width = \Contao\StringUtil::deserialize($tpl->article_width);
         $article_minheight = \Contao\StringUtil::deserialize($tpl->article_minheight);
         $article_image = $tpl->article_image;
         $article_image_position = $tpl->article_image_position;
         $article_image_repeat = $tpl->article_image_repeat;
         $article_image_cover = $tpl->article_image_cover;
         $article_image_fixed = $tpl->article_image_fixed;
         $inner_article_width = \Contao\StringUtil::deserialize($tpl->inner_article_width);
         $inner_article_space = $tpl->inner_article_space;
         $inner_article_overflow = $tpl->inner_article_overflow;
         $inner_article_color = \Contao\StringUtil::deserialize($tpl->inner_article_color);
         $inner_article_float = $tpl->inner_article_float;
         $inner_article_minheight = \Contao\StringUtil::deserialize($tpl->inner_article_minheight);
         if ($tpl->article_visible != '') {
             $tmpclasses = $article->cssID;
             $article_visible = @unserialize($tpl->article_visible);
             if ($article_visible === 'b:0;' || $article_visible !== false) {
                 foreach (\Contao\StringUtil::deserialize($tpl->article_hidden) as $key => $value) {
                     $tmpclasses[1] .= ' ' . $value;
                 }
             } else {
                 $tmpclasses[1] .= ' ' . $tpl->article_visible;
             }
             $article->cssID = $tmpclasses;
         }
         if ($tpl->article_hidden != '') {
             $tmpclasses = $article->cssID;
             $article_hidden = @unserialize($tpl->article_hidden);
             if ($article_hidden === 'b:0;' || $article_hidden !== false) {
                 foreach (\Contao\StringUtil::deserialize($tpl->article_hidden) as $key => $value) {
                     $tmpclasses[1] .= ' ' . $value;
                 }
             } else {
                 $tmpclasses[1] .= ' ' . $tpl->article_hidden;
             }
             $article->cssID = $tmpclasses;
         }
         $customstyle = ".mod_article.customarticle_{$tpl->id} { ";
         if (isset($article_width['value']) && $article_width['value'] != '') {
             if ($article_width['value'] == 100 && $article_width['unit'] == "%") {
                 $containertype = 'container-fluid';
             } else {
                 $containertype = 'container';
             }
             $customstyle .= "width:" . $article_width['value'] . $article_width['unit'] . " !important;";
             $customstyle .= "max-width:" . $article_width['value'] . $article_width['unit'] . " !important;";
         }
         if (isset($article_minheight['value']) && $article_minheight['value'] != '') {
             $customstyle .= "min-height:" . $article_minheight['value'] . $article_minheight['unit'] . " !important;";
         }
         if (isset($article_color[0]) && $article_color[0] != '') {
             $customstyle .= "background-color:" . $this->cHex2rgba($article_color[0], $article_color[1]) . " !important;";
         }
         if (isset($article_image) && $article_image != '') {
             $customstyle .= "background-image:url('" . $article_image . "') !important;";
         }
         if (isset($article_image_repeat) && $article_image_repeat != '') {
             $customstyle .= "background-repeat:" . $article_image_repeat . " !important;";
         }
         if (isset($article_image_position) && $article_image_position != '') {
             $customstyle .= "background-position:" . $article_image_position . " !important;";
         }
         if ($article_image_cover) {
             $customstyle .= "\n\t\t\t\t\t\t-webkit-background-size: cover;\n\t\t\t\t\t\t-moz-background-size: cover;\n\t\t\t\t\t\t-o-background-size: cover;\n\t\t\t\t\t\tbackground-size: cover;\n\t\t\t\t\t\tfilter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src={$img}-uri, sizingMethod='scale');\n\t\t\t\t\t\t-ms-filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src={$img}-uri, sizingMethod='scale') !important;";
             if ($article_image_fixed) {
                 $customstyle .= "background-attachment: fixed";
             } else {
                 $customstyle .= "background-attachment: initial";
             }
         }
         $customstyle .= "\t}";
         $customstyle .= ".mod_article.customarticle_{$tpl->id} .outer { ";
         if (isset($inner_article_color[0]) && $inner_article_color[0] != '') {
             $customstyle .= "background-color:" . $this->cHex2rgba($inner_article_color[0], $inner_article_color[1]) . " !important;";
         }
         if (isset($inner_article_width['value']) && $inner_article_width['value'] != '') {
             $customstyle .= "width:" . $inner_article_width['value'] . $inner_article_width['unit'] . " !important;";
             $customstyle .= "max-width:" . $inner_article_width['value'] . $inner_article_width['unit'] . " !important;";
         }
         if (isset($inner_article_height['value']) && $inner_article_height['value'] != '') {
             $customstyle .= "min-height:" . $inner_article_height['value'] . $inner_article_height['unit'] . " !important;";
         }
         $customstyle .= "\t}";
         $customstyle .= ".mod_article.customarticle_{$tpl->id} .inner { ";
         if (isset($inner_article_space) && $inner_article_space != '') {
             if ($inner_article_space == 'top_spaceing') {
                 $customstyle .= "padding-bottom:0 !important;";
             }
             if ($inner_article_space == 'bottom_spaceing') {
                 $customstyle .= "padding-top:0 !important;";
             }
             if ($inner_article_space == 'no_spaceing') {
                 $customstyle .= "padding-bottom:0 !important;";
                 $customstyle .= "padding-top:0 !important;";
             }
         }
         if (isset($inner_article_overflow) && $inner_article_overflow != '') {
             if ($inner_article_overflow == 'overflow_hidden') {
                 $customstyle .= "overflow:hidden !important;";
             }
             if ($inner_article_overflow == 'overflow_visible') {
                 $customstyle .= "overflow:visible !important;";
             }
         }
         $customstyle .= "\t}";
         $tpl->customstyle = $customstyle;
         $tpl->gridcount = $count;
         $tpl->containertype = $containertype;
         $template->setData($tpl->getData());
         $article->Template = $template;
     }
 }
Example #21
0
    /**
     * List all records of the current table and return them as HTML string
     *
     * @return string
     */
    protected function listView()
    {
        $return = '';
        $table = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 6 ? $this->ptable : $this->strTable;
        $orderBy = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['fields'];
        $firstOrderBy = preg_replace('/\\s+.*$/', '', $orderBy[0]);
        if (is_array($this->orderBy) && $this->orderBy[0] != '') {
            $orderBy = $this->orderBy;
            $firstOrderBy = $this->firstOrderBy;
        }
        $query = "SELECT * FROM " . $this->strTable;
        if (!empty($this->procedure)) {
            $query .= " WHERE " . implode(' AND ', $this->procedure);
        }
        if (!empty($this->root) && is_array($this->root)) {
            $query .= (!empty($this->procedure) ? " AND " : " WHERE ") . "id IN(" . implode(',', array_map('intval', $this->root)) . ")";
        }
        if (is_array($orderBy) && $orderBy[0] != '') {
            foreach ($orderBy as $k => $v) {
                list($key, $direction) = explode(' ', $v, 2);
                if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['eval']['findInSet']) {
                    if (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['options_callback'])) {
                        $strClass = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['options_callback'][0];
                        $strMethod = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['options_callback'][1];
                        $this->import($strClass);
                        $keys = $this->{$strClass}->{$strMethod}($this);
                    } elseif (is_callable($GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['options_callback'])) {
                        $keys = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['options_callback']($this);
                    } else {
                        $keys = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['options'];
                    }
                    if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['eval']['isAssociative'] || array_is_assoc($keys)) {
                        $keys = array_keys($keys);
                    }
                    $orderBy[$k] = $this->Database->findInSet($v, $keys);
                } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$key]['flag'], array(5, 6, 7, 8, 9, 10))) {
                    $orderBy[$k] = "CAST({$key} AS SIGNED)" . ($direction ? " {$direction}" : "");
                    // see #5503
                }
            }
            if ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 3) {
                $firstOrderBy = 'pid';
                $showFields = $GLOBALS['TL_DCA'][$table]['list']['label']['fields'];
                $query .= " ORDER BY (SELECT " . $showFields[0] . " FROM " . $this->ptable . " WHERE " . $this->ptable . ".id=" . $this->strTable . ".pid), " . implode(', ', $orderBy);
                // Set the foreignKey so that the label is translated
                if ($GLOBALS['TL_DCA'][$table]['fields']['pid']['foreignKey'] == '') {
                    $GLOBALS['TL_DCA'][$table]['fields']['pid']['foreignKey'] = $this->ptable . '.' . $showFields[0];
                }
                // Remove the parent field from label fields
                array_shift($showFields);
                $GLOBALS['TL_DCA'][$table]['list']['label']['fields'] = $showFields;
            } else {
                $query .= " ORDER BY " . implode(', ', $orderBy);
            }
        }
        if ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 1 && $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['flag'] % 2 == 0) {
            $query .= " DESC";
        }
        $objRowStmt = $this->Database->prepare($query);
        if ($this->limit != '') {
            $arrLimit = explode(',', $this->limit);
            $objRowStmt->limit($arrLimit[1], $arrLimit[0]);
        }
        $objRow = $objRowStmt->execute($this->values);
        $this->bid = $return != '' ? $this->bid : 'tl_buttons';
        // Display buttos
        if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['closed'] || !empty($GLOBALS['TL_DCA'][$this->strTable]['list']['global_operations'])) {
            $return .= '

<div id="' . $this->bid . '">' . (\Input::get('act') == 'select' || $this->ptable ? '
<a href="' . $this->getReferer(true, $this->ptable) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a> ' : (isset($GLOBALS['TL_DCA'][$this->strTable]['config']['backlink']) ? '
<a href="contao/main.php?' . $GLOBALS['TL_DCA'][$this->strTable]['config']['backlink'] . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a> ' : '')) . (\Input::get('act') != 'select' && !$GLOBALS['TL_DCA'][$this->strTable]['config']['closed'] && !$GLOBALS['TL_DCA'][$this->strTable]['config']['notCreatable'] ? '
<a href="' . ($this->ptable != '' ? $this->addToUrl('act=create' . ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] < 4 ? '&amp;mode=2' : '') . '&amp;pid=' . $this->intId) : $this->addToUrl('act=create')) . '" class="header_new" title="' . specialchars($GLOBALS['TL_LANG'][$this->strTable]['new'][1]) . '" accesskey="n" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG'][$this->strTable]['new'][0] . '</a> ' : '') . $this->generateGlobalButtons() . '
</div>' . \Message::generate(true);
        }
        // Return "no records found" message
        if ($objRow->numRows < 1) {
            $return .= '
<p class="tl_empty">' . $GLOBALS['TL_LANG']['MSC']['noResult'] . '</p>';
        } else {
            $result = $objRow->fetchAllAssoc();
            $return .= (\Input::get('act') == 'select' ? '

<form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_select" class="tl_form' . (\Input::get('act') == 'select' ? ' unselectable' : '') . '" method="post" novalidate>
<div class="tl_formbody">
<input type="hidden" name="FORM_SUBMIT" value="tl_select">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">' : '') . '

<div class="tl_listing_container list_view">' . (\Input::get('act') == 'select' ? '

<div class="tl_select_trigger">
<label for="tl_select_trigger" class="tl_select_label">' . $GLOBALS['TL_LANG']['MSC']['selectAll'] . '</label> <input type="checkbox" id="tl_select_trigger" onclick="Backend.toggleCheckboxes(this)" class="tl_tree_checkbox">
</div>' : '') . '

<table class="tl_listing' . ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['showColumns'] ? ' showColumns' : '') . '">';
            // Automatically add the "order by" field as last column if we do not have group headers
            if ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['showColumns']) {
                $blnFound = false;
                // Extract the real key and compare it to $firstOrderBy
                foreach ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['fields'] as $f) {
                    if (strpos($f, ':') !== false) {
                        list($f) = explode(':', $f, 2);
                    }
                    if ($firstOrderBy == $f) {
                        $blnFound = true;
                        break;
                    }
                }
                if (!$blnFound) {
                    $GLOBALS['TL_DCA'][$this->strTable]['list']['label']['fields'][] = $firstOrderBy;
                }
            }
            // Generate the table header if the "show columns" option is active
            if ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['showColumns']) {
                $return .= '
  <tr>';
                foreach ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['fields'] as $f) {
                    if (strpos($f, ':') !== false) {
                        list($f) = explode(':', $f, 2);
                    }
                    $return .= '
    <th class="tl_folder_tlist col_' . $f . ($f == $firstOrderBy ? ' ordered_by' : '') . '">' . (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$f]['label']) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$f]['label'][0] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$f]['label']) . '</th>';
                }
                $return .= '
    <th class="tl_folder_tlist tl_right_nowrap">&nbsp;</th>
  </tr>';
            }
            // Process result and add label and buttons
            $remoteCur = false;
            $groupclass = 'tl_folder_tlist';
            $eoCount = -1;
            foreach ($result as $row) {
                $args = array();
                $this->current[] = $row['id'];
                $showFields = $GLOBALS['TL_DCA'][$table]['list']['label']['fields'];
                // Label
                foreach ($showFields as $k => $v) {
                    // Decrypt the value
                    if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['encrypt']) {
                        $row[$v] = \Encryption::decrypt(deserialize($row[$v]));
                    }
                    if (strpos($v, ':') !== false) {
                        list($strKey, $strTable) = explode(':', $v);
                        list($strTable, $strField) = explode('.', $strTable);
                        $objRef = $this->Database->prepare("SELECT " . $strField . " FROM " . $strTable . " WHERE id=?")->limit(1)->execute($row[$strKey]);
                        $args[$k] = $objRef->numRows ? $objRef->{$strField} : '';
                    } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['flag'], array(5, 6, 7, 8, 9, 10))) {
                        if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['rgxp'] == 'date') {
                            $args[$k] = $row[$v] ? \Date::parse(\Config::get('dateFormat'), $row[$v]) : '-';
                        } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['rgxp'] == 'time') {
                            $args[$k] = $row[$v] ? \Date::parse(\Config::get('timeFormat'), $row[$v]) : '-';
                        } else {
                            $args[$k] = $row[$v] ? \Date::parse(\Config::get('datimFormat'), $row[$v]) : '-';
                        }
                    } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['multiple']) {
                        $args[$k] = $row[$v] != '' ? $GLOBALS['TL_DCA'][$table]['fields'][$v]['label'][0] : '';
                    } else {
                        $row_v = deserialize($row[$v]);
                        if (is_array($row_v)) {
                            $args_k = array();
                            foreach ($row_v as $option) {
                                $args_k[] = $GLOBALS['TL_DCA'][$table]['fields'][$v]['reference'][$option] ?: $option;
                            }
                            $args[$k] = implode(', ', $args_k);
                        } elseif (isset($GLOBALS['TL_DCA'][$table]['fields'][$v]['reference'][$row[$v]])) {
                            $args[$k] = is_array($GLOBALS['TL_DCA'][$table]['fields'][$v]['reference'][$row[$v]]) ? $GLOBALS['TL_DCA'][$table]['fields'][$v]['reference'][$row[$v]][0] : $GLOBALS['TL_DCA'][$table]['fields'][$v]['reference'][$row[$v]];
                        } elseif (($GLOBALS['TL_DCA'][$table]['fields'][$v]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$table]['fields'][$v]['options'])) && isset($GLOBALS['TL_DCA'][$table]['fields'][$v]['options'][$row[$v]])) {
                            $args[$k] = $GLOBALS['TL_DCA'][$table]['fields'][$v]['options'][$row[$v]];
                        } else {
                            $args[$k] = $row[$v];
                        }
                    }
                }
                // Shorten the label it if it is too long
                $label = vsprintf($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['format'] ?: '%s', $args);
                if ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['maxCharacters'] > 0 && $GLOBALS['TL_DCA'][$this->strTable]['list']['label']['maxCharacters'] < strlen(strip_tags($label))) {
                    $label = trim(\StringUtil::substrHtml($label, $GLOBALS['TL_DCA'][$this->strTable]['list']['label']['maxCharacters'])) . ' โ€ฆ';
                }
                // Remove empty brackets (), [], {}, <> and empty tags from the label
                $label = preg_replace('/\\( *\\) ?|\\[ *\\] ?|\\{ *\\} ?|< *> ?/', '', $label);
                $label = preg_replace('/<[^>]+>\\s*<\\/[^>]+>/', '', $label);
                // Build the sorting groups
                if ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] > 0) {
                    $current = $row[$firstOrderBy];
                    $orderBy = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['fields'];
                    $sortingMode = count($orderBy) == 1 && $firstOrderBy == $orderBy[0] && $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['flag'] != '' && $GLOBALS['TL_DCA'][$this->strTable]['fields'][$firstOrderBy]['flag'] == '' ? $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['flag'] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$firstOrderBy]['flag'];
                    $remoteNew = $this->formatCurrentValue($firstOrderBy, $current, $sortingMode);
                    // Add the group header
                    if (!$GLOBALS['TL_DCA'][$this->strTable]['list']['label']['showColumns'] && !$GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['disableGrouping'] && ($remoteNew != $remoteCur || $remoteCur === false)) {
                        $eoCount = -1;
                        $group = $this->formatGroupHeader($firstOrderBy, $remoteNew, $sortingMode, $row);
                        $remoteCur = $remoteNew;
                        $return .= '
  <tr>
    <td colspan="2" class="' . $groupclass . '">' . $group . '</td>
  </tr>';
                        $groupclass = 'tl_folder_list';
                    }
                }
                $return .= '
  <tr class="' . (++$eoCount % 2 == 0 ? 'even' : 'odd') . ' click2edit toggle_select hover-row">
    ';
                $colspan = 1;
                // Call the label_callback ($row, $label, $this)
                if (is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['label_callback']) || is_callable($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['label_callback'])) {
                    if (is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['label_callback'])) {
                        $strClass = $GLOBALS['TL_DCA'][$this->strTable]['list']['label']['label_callback'][0];
                        $strMethod = $GLOBALS['TL_DCA'][$this->strTable]['list']['label']['label_callback'][1];
                        $this->import($strClass);
                        $args = $this->{$strClass}->{$strMethod}($row, $label, $this, $args);
                    } elseif (is_callable($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['label_callback'])) {
                        $args = $GLOBALS['TL_DCA'][$this->strTable]['list']['label']['label_callback']($row, $label, $this, $args);
                    }
                    // Handle strings and arrays
                    if (!$GLOBALS['TL_DCA'][$this->strTable]['list']['label']['showColumns']) {
                        $label = is_array($args) ? implode(' ', $args) : $args;
                    } elseif (!is_array($args)) {
                        $args = array($args);
                        $colspan = count($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['fields']);
                    }
                }
                // Show columns
                if ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['showColumns']) {
                    foreach ($args as $j => $arg) {
                        $return .= '<td colspan="' . $colspan . '" class="tl_file_list col_' . $GLOBALS['TL_DCA'][$this->strTable]['list']['label']['fields'][$j] . ($GLOBALS['TL_DCA'][$this->strTable]['list']['label']['fields'][$j] == $firstOrderBy ? ' ordered_by' : '') . '">' . ($arg ?: '-') . '</td>';
                    }
                } else {
                    $return .= '<td class="tl_file_list">' . $label . '</td>';
                }
                // Buttons ($row, $table, $root, $blnCircularReference, $childs, $previous, $next)
                $return .= (\Input::get('act') == 'select' ? '
    <td class="tl_file_list tl_right_nowrap"><input type="checkbox" name="IDS[]" id="ids_' . $row['id'] . '" class="tl_tree_checkbox" value="' . $row['id'] . '"></td>' : '
    <td class="tl_file_list tl_right_nowrap">' . $this->generateButtons($row, $this->strTable, $this->root) . '</td>') . '
  </tr>';
            }
            // Close the table
            $return .= '
</table>

</div>';
            // Close the form
            if (\Input::get('act') == 'select') {
                // Submit buttons
                $arrButtons = array();
                if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notDeletable']) {
                    $arrButtons['delete'] = '<button type="submit" name="delete" id="delete" class="tl_submit" accesskey="d" onclick="return confirm(\'' . $GLOBALS['TL_LANG']['MSC']['delAllConfirm'] . '\')">' . $GLOBALS['TL_LANG']['MSC']['deleteSelected'] . '</button>';
                }
                if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notCopyable']) {
                    $arrButtons['copy'] = '<button type="submit" name="copy" id="copy" class="tl_submit" accesskey="c">' . $GLOBALS['TL_LANG']['MSC']['copySelected'] . '</button>';
                }
                if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notEditable']) {
                    $arrButtons['override'] = '<button type="submit" name="override" id="override" class="tl_submit" accesskey="v">' . $GLOBALS['TL_LANG']['MSC']['overrideSelected'] . '</button>';
                    $arrButtons['edit'] = '<button type="submit" name="edit" id="edit" class="tl_submit" accesskey="s">' . $GLOBALS['TL_LANG']['MSC']['editSelected'] . '</button>';
                }
                // Call the buttons_callback (see #4691)
                if (is_array($GLOBALS['TL_DCA'][$this->strTable]['select']['buttons_callback'])) {
                    foreach ($GLOBALS['TL_DCA'][$this->strTable]['select']['buttons_callback'] as $callback) {
                        if (is_array($callback)) {
                            $this->import($callback[0]);
                            $arrButtons = $this->{$callback[0]}->{$callback[1]}($arrButtons, $this);
                        } elseif (is_callable($callback)) {
                            $arrButtons = $callback($arrButtons, $this);
                        }
                    }
                }
                $return .= '

<div class="tl_formbody_submit" style="text-align:right">

<div class="tl_submit_container">
  ' . implode(' ', $arrButtons) . '
</div>

</div>
</div>
</form>';
            }
        }
        return $return;
    }
 /**
  * Recursively render the filetree
  *
  * @param string  $path
  * @param integer $intMargin
  * @param boolean $mount
  * @param boolean $blnProtected
  * @param array   $arrFound
  *
  * @return string
  */
 protected function renderFiletree($path, $intMargin, $mount = false, $blnProtected = true, $arrFound = array())
 {
     // Invalid path
     if (!is_dir($path)) {
         return '';
     }
     // Make sure that $this->varValue is an array (see #3369)
     if (!is_array($this->varValue)) {
         $this->varValue = array($this->varValue);
     }
     static $session;
     /** @var AttributeBagInterface $objSessionBag */
     $objSessionBag = \System::getContainer()->get('session')->getBag('contao_backend');
     $session = $objSessionBag->all();
     $flag = substr($this->strField, 0, 2);
     $node = 'tree_' . $this->strTable . '_' . $this->strField;
     $xtnode = 'tree_' . $this->strTable . '_' . $this->strName;
     // Get session data and toggle nodes
     if (\Input::get($flag . 'tg')) {
         $session[$node][\Input::get($flag . 'tg')] = isset($session[$node][\Input::get($flag . 'tg')]) && $session[$node][\Input::get($flag . 'tg')] == 1 ? 0 : 1;
         $objSessionBag->replace($session);
         $this->redirect(preg_replace('/(&(amp;)?|\\?)' . $flag . 'tg=[^& ]*/i', '', \Environment::get('request')));
     }
     $return = '';
     $intSpacing = 20;
     $files = array();
     $folders = array();
     $level = $intMargin / $intSpacing + 1;
     // Mount folder
     if ($mount) {
         $folders = array($path);
     } else {
         foreach (scan($path) as $v) {
             if (strncmp($v, '.', 1) === 0) {
                 continue;
             }
             if (is_dir($path . '/' . $v)) {
                 $folders[] = $path . '/' . $v;
             } else {
                 $files[] = $path . '/' . $v;
             }
         }
     }
     natcasesort($folders);
     $folders = array_values($folders);
     natcasesort($files);
     $files = array_values($files);
     // Sort descending (see #4072)
     if ($this->sort == 'desc') {
         $folders = array_reverse($folders);
         $files = array_reverse($files);
     }
     $folderClass = $this->files || $this->filesOnly ? 'tl_folder' : 'tl_file';
     // Process folders
     for ($f = 0, $c = count($folders); $f < $c; $f++) {
         $content = scan($folders[$f]);
         $currentFolder = str_replace(TL_ROOT . '/', '', $folders[$f]);
         $countFiles = count($content);
         // Check whether there are subfolders or files
         foreach ($content as $file) {
             if (strncmp($file, '.', 1) === 0) {
                 --$countFiles;
             } elseif (!$this->files && !$this->filesOnly && is_file($folders[$f] . '/' . $file)) {
                 --$countFiles;
             } elseif (!empty($arrFound) && !in_array($currentFolder . '/' . $file, $arrFound) && !preg_grep('/^' . preg_quote($currentFolder . '/' . $file, '/') . '\\//', $arrFound)) {
                 --$countFiles;
             }
         }
         if (!empty($arrFound) && $countFiles < 1 && !in_array($currentFolder, $arrFound)) {
             continue;
         }
         $tid = md5($folders[$f]);
         $folderAttribute = 'style="margin-left:20px"';
         $session[$node][$tid] = is_numeric($session[$node][$tid]) ? $session[$node][$tid] : 0;
         $currentFolder = str_replace(TL_ROOT . '/', '', $folders[$f]);
         $blnIsOpen = !empty($arrFound) || $session[$node][$tid] == 1 || count(preg_grep('/^' . preg_quote($currentFolder, '/') . '\\//', $this->varValue)) > 0;
         $return .= "\n    " . '<li class="' . $folderClass . ' toggle_select hover-div"><div class="tl_left" style="padding-left:' . $intMargin . 'px">';
         // Add a toggle button if there are childs
         if ($countFiles > 0) {
             $folderAttribute = '';
             $img = $blnIsOpen ? 'folMinus.svg' : 'folPlus.svg';
             $alt = $blnIsOpen ? $GLOBALS['TL_LANG']['MSC']['collapseNode'] : $GLOBALS['TL_LANG']['MSC']['expandNode'];
             $return .= '<a href="' . \Backend::addToUrl($flag . 'tg=' . $tid) . '" title="' . \StringUtil::specialchars($alt) . '" onclick="return AjaxRequest.toggleFiletree(this,\'' . $xtnode . '_' . $tid . '\',\'' . $currentFolder . '\',\'' . $this->strField . '\',\'' . $this->strName . '\',' . $level . ')">' . \Image::getHtml($img, '', 'style="margin-right:2px"') . '</a>';
         }
         $protected = $blnProtected;
         // Check whether the folder is public
         if ($protected === true && array_search('.public', $content) !== false) {
             $protected = false;
         }
         $folderImg = $protected ? 'folderCP.svg' : 'folderC.svg';
         $folderLabel = $this->files || $this->filesOnly ? '<strong>' . \StringUtil::specialchars(basename($currentFolder)) . '</strong>' : \StringUtil::specialchars(basename($currentFolder));
         // Add the current folder
         $return .= \Image::getHtml($folderImg, '', $folderAttribute) . ' <a href="' . \Backend::addToUrl('fn=' . $this->urlEncode($currentFolder)) . '" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['selectNode']) . '">' . $folderLabel . '</a></div> <div class="tl_right">';
         // Add a checkbox or radio button
         if (!$this->filesOnly) {
             switch ($this->fieldType) {
                 case 'checkbox':
                     $return .= '<input type="checkbox" name="' . $this->strName . '[]" id="' . $this->strName . '_' . md5($currentFolder) . '" class="tl_tree_checkbox" value="' . \StringUtil::specialchars($currentFolder) . '" onfocus="Backend.getScrollOffset()"' . $this->optionChecked($currentFolder, $this->varValue) . '>';
                     break;
                 case 'radio':
                     $return .= '<input type="radio" name="' . $this->strName . '" id="' . $this->strName . '_' . md5($currentFolder) . '" class="tl_tree_radio" value="' . \StringUtil::specialchars($currentFolder) . '" onfocus="Backend.getScrollOffset()"' . $this->optionChecked($currentFolder, $this->varValue) . '>';
                     break;
             }
         }
         $return .= '</div><div style="clear:both"></div></li>';
         // Call the next node
         if ($blnIsOpen) {
             $return .= '<li class="parent" id="' . $xtnode . '_' . $tid . '"><ul class="level_' . $level . '">';
             $return .= $this->renderFiletree($folders[$f], $intMargin + $intSpacing, false, $protected, $arrFound);
             $return .= '</ul></li>';
         }
     }
     // Process files
     if ($this->files || $this->filesOnly) {
         for ($h = 0, $c = count($files); $h < $c; $h++) {
             $thumbnail = '';
             $currentFile = str_replace(TL_ROOT . '/', '', $files[$h]);
             $currentEncoded = $this->urlEncode($currentFile);
             $objFile = new \File($currentFile);
             if (!empty($this->arrValidFileTypes) && !in_array($objFile->extension, $this->arrValidFileTypes)) {
                 continue;
             }
             // Ignore files not matching the search criteria
             if (!empty($arrFound) && !in_array($currentFile, $arrFound)) {
                 continue;
             }
             $return .= "\n    " . '<li class="tl_file toggle_select hover-div"><div class="tl_left" style="padding-left:' . ($intMargin + $intSpacing) . 'px">';
             $thumbnail .= ' <span class="tl_gray">(' . $this->getReadableSize($objFile->filesize);
             if ($objFile->width && $objFile->height) {
                 $thumbnail .= ', ' . $objFile->width . 'x' . $objFile->height . ' px';
             }
             $thumbnail .= ')</span>';
             // Generate thumbnail
             if ($objFile->isImage && $objFile->viewHeight > 0 && \Config::get('thumbnails') && ($objFile->isSvgImage || $objFile->height <= \Config::get('gdMaxImgHeight') && $objFile->width <= \Config::get('gdMaxImgWidth'))) {
                 $imageObj = \Image::create($currentEncoded, array(400, $objFile->height && $objFile->height < 50 ? $objFile->height : 50, 'box'));
                 $importantPart = $imageObj->getImportantPart();
                 $thumbnail .= '<br>' . \Image::getHtml($imageObj->executeResize()->getResizedPath(), '', 'style="margin:0 0 2px -19px"');
                 if ($importantPart['x'] > 0 || $importantPart['y'] > 0 || $importantPart['width'] < $objFile->width || $importantPart['height'] < $objFile->height) {
                     $thumbnail .= ' ' . \Image::getHtml($imageObj->setZoomLevel(100)->setTargetWidth(320)->setTargetHeight($objFile->height && $objFile->height < 40 ? $objFile->height : 40)->executeResize()->getResizedPath(), '', 'style="margin:0 0 2px 0;vertical-align:bottom"');
                 }
             }
             $return .= \Image::getHtml($objFile->icon, $objFile->mime) . ' ' . \StringUtil::convertEncoding(\StringUtil::specialchars(basename($currentFile)), \Config::get('characterSet')) . $thumbnail . '</div> <div class="tl_right">';
             // Add checkbox or radio button
             switch ($this->fieldType) {
                 case 'checkbox':
                     $return .= '<input type="checkbox" name="' . $this->strName . '[]" id="' . $this->strName . '_' . md5($currentFile) . '" class="tl_tree_checkbox" value="' . \StringUtil::specialchars($currentFile) . '" onfocus="Backend.getScrollOffset()"' . $this->optionChecked($currentFile, $this->varValue) . '>';
                     break;
                 case 'radio':
                     $return .= '<input type="radio" name="' . $this->strName . '" id="' . $this->strName . '_' . md5($currentFile) . '" class="tl_tree_radio" value="' . \StringUtil::specialchars($currentFile) . '" onfocus="Backend.getScrollOffset()"' . $this->optionChecked($currentFile, $this->varValue) . '>';
                     break;
             }
             $return .= '</div><div style="clear:both"></div></li>';
         }
     }
     return $return;
 }
Example #23
0
 /**
  * Run the controller and parse the template
  *
  * @return Response
  */
 public function run()
 {
     /** @var SessionInterface $objSession */
     $objSession = \System::getContainer()->get('session');
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_picker');
     $objTemplate->main = '';
     // Ajax request
     if ($_POST && \Environment::get('isAjaxRequest')) {
         $this->objAjax = new \Ajax(\Input::post('action'));
         $this->objAjax->executePreActions();
     }
     $strTable = \Input::get('table');
     $strField = \Input::get('field');
     // Define the current ID
     define('CURRENT_ID', \Input::get('table') ? $objSession->get('CURRENT_ID') : \Input::get('id'));
     $this->loadDataContainer($strTable);
     $strDriver = 'DC_' . $GLOBALS['TL_DCA'][$strTable]['config']['dataContainer'];
     $objDca = new $strDriver($strTable);
     $objDca->field = $strField;
     // Set the active record
     if ($this->Database->tableExists($strTable)) {
         /** @var Model $strModel */
         $strModel = \Model::getClassFromTable($strTable);
         if (class_exists($strModel)) {
             $objModel = $strModel::findByPk(\Input::get('id'));
             if ($objModel !== null) {
                 $objDca->activeRecord = $objModel;
             }
         }
     }
     // AJAX request
     if ($_POST && \Environment::get('isAjaxRequest')) {
         $this->objAjax->executePostActions($objDca);
     }
     $objSession->set('filePickerRef', \Environment::get('request'));
     $arrValues = array_filter(explode(',', \Input::get('value')));
     // Convert UUIDs to binary
     foreach ($arrValues as $k => $v) {
         // Can be a UUID or a path
         if (\Validator::isStringUuid($v)) {
             $arrValues[$k] = \StringUtil::uuidToBin($v);
         }
     }
     // Call the load_callback
     if (is_array($GLOBALS['TL_DCA'][$strTable]['fields'][$strField]['load_callback'])) {
         foreach ($GLOBALS['TL_DCA'][$strTable]['fields'][$strField]['load_callback'] as $callback) {
             if (is_array($callback)) {
                 $this->import($callback[0]);
                 $arrValues = $this->{$callback[0]}->{$callback[1]}($arrValues, $objDca);
             } elseif (is_callable($callback)) {
                 $arrValues = $callback($arrValues, $objDca);
             }
         }
     }
     /** @var FileSelector $strClass */
     $strClass = $GLOBALS['BE_FFL']['fileSelector'];
     /** @var FileSelector $objFileTree */
     $objFileTree = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$strTable]['fields'][$strField], $strField, $arrValues, $strField, $strTable, $objDca));
     /** @var AttributeBagInterface $objSessionBag */
     $objSessionBag = $objSession->getBag('contao_backend');
     $objTemplate->main = $objFileTree->generate();
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->title = specialchars($GLOBALS['TL_LANG']['MSC']['filepicker']);
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->addSearch = true;
     $objTemplate->search = $GLOBALS['TL_LANG']['MSC']['search'];
     $objTemplate->searchExclude = $GLOBALS['TL_LANG']['MSC']['searchExclude'];
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->value = $objSessionBag->get('file_selector_search');
     $objTemplate->manager = $GLOBALS['TL_LANG']['MSC']['fileManager'];
     $objTemplate->managerHref = 'contao/main.php?do=files&amp;popup=1';
     $objTemplate->breadcrumb = $GLOBALS['TL_DCA']['tl_files']['list']['sorting']['breadcrumb'];
     if (\Input::get('switch')) {
         $objTemplate->switch = $GLOBALS['TL_LANG']['MSC']['pagePicker'];
         $objTemplate->switchHref = str_replace('contao/file?', 'contao/page?', ampersand(\Environment::get('request')));
     }
     return $objTemplate->getResponse();
 }
Example #24
0
 /**
  * Extract the Widget attributes from a Data Container array
  *
  * @param array              $arrData  The field configuration array
  * @param string             $strName  The field name in the form
  * @param mixed              $varValue The field value
  * @param string             $strField The field name in the database
  * @param string             $strTable The table name in the database
  * @param DataContainer|null $objDca   An optional DataContainer object
  *
  * @return array An attributes array that can be passed to a widget
  */
 public static function getAttributesFromDca($arrData, $strName, $varValue = null, $strField = '', $strTable = '', $objDca = null)
 {
     $arrAttributes = $arrData['eval'];
     $arrAttributes['id'] = $strName;
     $arrAttributes['name'] = $strName;
     $arrAttributes['strField'] = $strField;
     $arrAttributes['strTable'] = $strTable;
     $arrAttributes['label'] = ($label = is_array($arrData['label']) ? $arrData['label'][0] : $arrData['label']) != false ? $label : $strField;
     $arrAttributes['description'] = $arrData['label'][1];
     $arrAttributes['type'] = $arrData['inputType'];
     $arrAttributes['dataContainer'] = $objDca;
     // Internet Explorer does not support onchange for checkboxes and radio buttons
     if ($arrData['eval']['submitOnChange']) {
         if ($arrData['inputType'] == 'checkbox' || $arrData['inputType'] == 'checkboxWizard' || $arrData['inputType'] == 'radio' || $arrData['inputType'] == 'radioTable') {
             $arrAttributes['onclick'] = trim($arrAttributes['onclick'] . " Backend.autoSubmit('" . $strTable . "')");
         } else {
             $arrAttributes['onchange'] = trim($arrAttributes['onchange'] . " Backend.autoSubmit('" . $strTable . "')");
         }
     }
     $arrAttributes['allowHtml'] = $arrData['eval']['allowHtml'] || strlen($arrData['eval']['rte']) || $arrData['eval']['preserveTags'] ? true : false;
     // Decode entities if HTML is allowed
     if ($arrAttributes['allowHtml'] || $arrData['inputType'] == 'fileTree') {
         $arrAttributes['decodeEntities'] = true;
     }
     // Add Ajax event
     if ($arrData['inputType'] == 'checkbox' && is_array($GLOBALS['TL_DCA'][$strTable]['subpalettes']) && in_array($strField, array_keys($GLOBALS['TL_DCA'][$strTable]['subpalettes'])) && $arrData['eval']['submitOnChange']) {
         $arrAttributes['onclick'] = "AjaxRequest.toggleSubpalette(this, 'sub_" . $strName . "', '" . $strField . "')";
     }
     // Options callback
     if (is_array($arrData['options_callback'])) {
         $arrCallback = $arrData['options_callback'];
         $arrData['options'] = static::importStatic($arrCallback[0])->{$arrCallback[1]}($objDca);
     } elseif (is_callable($arrData['options_callback'])) {
         $arrData['options'] = $arrData['options_callback']($objDca);
     } elseif (isset($arrData['foreignKey'])) {
         $arrKey = explode('.', $arrData['foreignKey'], 2);
         $objOptions = \Database::getInstance()->query("SELECT id, " . $arrKey[1] . " AS value FROM " . $arrKey[0] . " WHERE tstamp>0 ORDER BY value");
         $arrData['options'] = array();
         while ($objOptions->next()) {
             $arrData['options'][$objOptions->id] = $objOptions->value;
         }
     }
     // Add default option to single checkbox
     if ($arrData['inputType'] == 'checkbox' && !isset($arrData['options']) && !isset($arrData['options_callback']) && !isset($arrData['foreignKey'])) {
         if (TL_MODE == 'FE' && isset($arrAttributes['description'])) {
             $arrAttributes['options'][] = array('value' => 1, 'label' => $arrAttributes['description']);
         } else {
             $arrAttributes['options'][] = array('value' => 1, 'label' => $arrAttributes['label']);
         }
     }
     // Add options
     if (is_array($arrData['options'])) {
         $blnIsAssociative = $arrData['eval']['isAssociative'] || array_is_assoc($arrData['options']);
         $blnUseReference = isset($arrData['reference']);
         if ($arrData['eval']['includeBlankOption'] && !$arrData['eval']['multiple']) {
             $strLabel = isset($arrData['eval']['blankOptionLabel']) ? $arrData['eval']['blankOptionLabel'] : '-';
             $arrAttributes['options'][] = array('value' => '', 'label' => $strLabel);
         }
         foreach ($arrData['options'] as $k => $v) {
             if (!is_array($v)) {
                 $arrAttributes['options'][] = array('value' => $blnIsAssociative ? $k : $v, 'label' => $blnUseReference ? ($ref = is_array($arrData['reference'][$v]) ? $arrData['reference'][$v][0] : $arrData['reference'][$v]) != false ? $ref : $v : $v);
                 continue;
             }
             $key = $blnUseReference ? ($ref = is_array($arrData['reference'][$k]) ? $arrData['reference'][$k][0] : $arrData['reference'][$k]) != false ? $ref : $k : $k;
             $blnIsAssoc = array_is_assoc($v);
             foreach ($v as $kk => $vv) {
                 $arrAttributes['options'][$key][] = array('value' => $blnIsAssoc ? $kk : $vv, 'label' => $blnUseReference ? ($ref = is_array($arrData['reference'][$vv]) ? $arrData['reference'][$vv][0] : $arrData['reference'][$vv]) != false ? $ref : $vv : $vv);
             }
         }
     }
     $arrAttributes['value'] = \StringUtil::deserialize($varValue);
     // Convert timestamps
     if ($varValue != '' && in_array($arrData['eval']['rgxp'], array('date', 'time', 'datim'))) {
         $objDate = new \Date($varValue, \Date::getFormatFromRgxp($arrData['eval']['rgxp']));
         $arrAttributes['value'] = $objDate->{$arrData['eval']['rgxp']};
     }
     // Add the "rootNodes" array as attribute (see #3563)
     if (isset($arrData['rootNodes']) && !isset($arrData['eval']['rootNodes'])) {
         $arrAttributes['rootNodes'] = $arrData['rootNodes'];
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getAttributesFromDca']) && is_array($GLOBALS['TL_HOOKS']['getAttributesFromDca'])) {
         foreach ($GLOBALS['TL_HOOKS']['getAttributesFromDca'] as $callback) {
             $arrAttributes = static::importStatic($callback[0])->{$callback[1]}($arrAttributes, $objDca);
         }
     }
     return $arrAttributes;
 }
 /**
  * Create a new user and redirect
  *
  * @param MemberModel $objMember
  */
 protected function sendPasswordLink($objMember)
 {
     $confirmationId = md5(uniqid(mt_rand(), true));
     // Store the confirmation ID
     $objMember = \MemberModel::findByPk($objMember->id);
     $objMember->activation = $confirmationId;
     $objMember->save();
     // Prepare the simple token data
     $arrData = $objMember->row();
     $arrData['domain'] = \Idna::decode(\Environment::get('host'));
     $arrData['link'] = \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $confirmationId;
     // Send e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['passwordSubject'], \Idna::decode(\Environment::get('host')));
     $objEmail->text = \StringUtil::parseSimpleTokens($this->reg_password, $arrData);
     $objEmail->sendTo($objMember->email);
     $this->log('A new password has been requested for user ID ' . $objMember->id . ' (' . \Idna::decodeEmail($objMember->email) . ')', __METHOD__, TL_ACCESS);
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) instanceof PageModel) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Example #26
0
 /**
  * Generate the content element
  */
 protected function compile()
 {
     /** @var PageModel $objPage */
     global $objPage;
     $images = array();
     $auxDate = array();
     $objFiles = $this->objFiles;
     // Get all images
     while ($objFiles->next()) {
         // Continue if the files has been processed or does not exist
         if (isset($images[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path)) {
             continue;
         }
         // Single files
         if ($objFiles->type == 'file') {
             $objFile = new \File($objFiles->path);
             if (!$objFile->isImage) {
                 continue;
             }
             $arrMeta = $this->getMetaData($objFiles->meta, $objPage->language);
             if (empty($arrMeta)) {
                 if ($this->metaIgnore) {
                     continue;
                 } elseif ($objPage->rootFallbackLanguage !== null) {
                     $arrMeta = $this->getMetaData($objFiles->meta, $objPage->rootFallbackLanguage);
                 }
             }
             // Use the file name as title if none is given
             if ($arrMeta['title'] == '') {
                 $arrMeta['title'] = \StringUtil::specialchars($objFile->basename);
             }
             // Add the image
             $images[$objFiles->path] = array('id' => $objFiles->id, 'uuid' => $objFiles->uuid, 'name' => $objFile->basename, 'singleSRC' => $objFiles->path, 'title' => \StringUtil::specialchars($arrMeta['title']), 'alt' => \StringUtil::specialchars($arrMeta['alt']), 'imageUrl' => $arrMeta['link'], 'caption' => $arrMeta['caption']);
             $auxDate[] = $objFile->mtime;
         } else {
             $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
             if ($objSubfiles === null) {
                 continue;
             }
             while ($objSubfiles->next()) {
                 // Skip subfolders
                 if ($objSubfiles->type == 'folder') {
                     continue;
                 }
                 $objFile = new \File($objSubfiles->path);
                 if (!$objFile->isImage) {
                     continue;
                 }
                 $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->language);
                 if (empty($arrMeta)) {
                     if ($this->metaIgnore) {
                         continue;
                     } elseif ($objPage->rootFallbackLanguage !== null) {
                         $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->rootFallbackLanguage);
                     }
                 }
                 // Use the file name as title if none is given
                 if ($arrMeta['title'] == '') {
                     $arrMeta['title'] = \StringUtil::specialchars($objFile->basename);
                 }
                 // Add the image
                 $images[$objSubfiles->path] = array('id' => $objSubfiles->id, 'uuid' => $objSubfiles->uuid, 'name' => $objFile->basename, 'singleSRC' => $objSubfiles->path, 'title' => \StringUtil::specialchars($arrMeta['title']), 'alt' => \StringUtil::specialchars($arrMeta['alt']), 'imageUrl' => $arrMeta['link'], 'caption' => $arrMeta['caption']);
                 $auxDate[] = $objFile->mtime;
             }
         }
     }
     // Sort array
     switch ($this->sortBy) {
         default:
         case 'name_asc':
             uksort($images, 'basename_natcasecmp');
             break;
         case 'name_desc':
             uksort($images, 'basename_natcasercmp');
             break;
         case 'date_asc':
             array_multisort($images, SORT_NUMERIC, $auxDate, SORT_ASC);
             break;
         case 'date_desc':
             array_multisort($images, SORT_NUMERIC, $auxDate, SORT_DESC);
             break;
             // Deprecated since Contao 4.0, to be removed in Contao 5.0
         // Deprecated since Contao 4.0, to be removed in Contao 5.0
         case 'meta':
             @trigger_error('The "meta" key in ContentGallery::compile() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
             // no break;
         // no break;
         case 'custom':
             if ($this->orderSRC != '') {
                 $tmp = \StringUtil::deserialize($this->orderSRC);
                 if (!empty($tmp) && is_array($tmp)) {
                     // Remove all values
                     $arrOrder = array_map(function () {
                     }, array_flip($tmp));
                     // Move the matching elements to their position in $arrOrder
                     foreach ($images as $k => $v) {
                         if (array_key_exists($v['uuid'], $arrOrder)) {
                             $arrOrder[$v['uuid']] = $v;
                             unset($images[$k]);
                         }
                     }
                     // Append the left-over images at the end
                     if (!empty($images)) {
                         $arrOrder = array_merge($arrOrder, array_values($images));
                     }
                     // Remove empty (unreplaced) entries
                     $images = array_values(array_filter($arrOrder));
                     unset($arrOrder);
                 }
             }
             break;
         case 'random':
             shuffle($images);
             $this->Template->isRandomOrder = true;
             break;
     }
     $images = array_values($images);
     // Limit the total number of items (see #2652)
     if ($this->numberOfItems > 0) {
         $images = array_slice($images, 0, $this->numberOfItems);
     }
     $offset = 0;
     $total = count($images);
     $limit = $total;
     // Paginate the result of not randomly sorted (see #8033)
     if ($this->perPage > 0 && $this->sortBy != 'random') {
         // Get the current page
         $id = 'page_g' . $this->id;
         $page = \Input::get($id) !== null ? \Input::get($id) : 1;
         // Do not index or cache the page if the page number is outside the range
         if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) {
             throw new PageNotFoundException('Page not found: ' . \Environment::get('uri'));
         }
         // Set limit and offset
         $offset = ($page - 1) * $this->perPage;
         $limit = min($this->perPage + $offset, $total);
         $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id);
         $this->Template->pagination = $objPagination->generate("\n  ");
     }
     $rowcount = 0;
     $colwidth = floor(100 / $this->perRow);
     $intMaxWidth = TL_MODE == 'BE' ? floor(640 / $this->perRow) : floor(\Config::get('maxImageWidth') / $this->perRow);
     $strLightboxId = 'lightbox[lb' . $this->id . ']';
     $body = array();
     // Rows
     for ($i = $offset; $i < $limit; $i = $i + $this->perRow) {
         $class_tr = '';
         if ($rowcount == 0) {
             $class_tr .= ' row_first';
         }
         if ($i + $this->perRow >= $limit) {
             $class_tr .= ' row_last';
         }
         $class_eo = $rowcount % 2 == 0 ? ' even' : ' odd';
         // Columns
         for ($j = 0; $j < $this->perRow; $j++) {
             $class_td = '';
             if ($j == 0) {
                 $class_td .= ' col_first';
             }
             if ($j == $this->perRow - 1) {
                 $class_td .= ' col_last';
             }
             $objCell = new \stdClass();
             $key = 'row_' . $rowcount . $class_tr . $class_eo;
             // Empty cell
             if (!is_array($images[$i + $j]) || $j + $i >= $limit) {
                 $objCell->colWidth = $colwidth . '%';
                 $objCell->class = 'col_' . $j . $class_td;
             } else {
                 // Add size and margin
                 $images[$i + $j]['size'] = $this->size;
                 $images[$i + $j]['imagemargin'] = $this->imagemargin;
                 $images[$i + $j]['fullsize'] = $this->fullsize;
                 $this->addImageToTemplate($objCell, $images[$i + $j], $intMaxWidth, $strLightboxId);
                 // Add column width and class
                 $objCell->colWidth = $colwidth . '%';
                 $objCell->class = 'col_' . $j . $class_td;
             }
             $body[$key][$j] = $objCell;
         }
         ++$rowcount;
     }
     $strTemplate = 'gallery_default';
     // Use a custom template
     if (TL_MODE == 'FE' && $this->galleryTpl != '') {
         $strTemplate = $this->galleryTpl;
     }
     /** @var FrontendTemplate|object $objTemplate */
     $objTemplate = new \FrontendTemplate($strTemplate);
     $objTemplate->setData($this->arrData);
     $objTemplate->body = $body;
     $objTemplate->headline = $this->headline;
     // see #1603
     $this->Template->images = $objTemplate->parse();
 }
 /**
  * Returns the template parameters.
  *
  * @param string                       $view       The name of the view
  * @param int                          $statusCode The HTTP status code
  * @param GetResponseForExceptionEvent $event      The event object
  *
  * @return array|null The template parameters or null
  */
 private function getTemplateParameters($view, $statusCode, GetResponseForExceptionEvent $event)
 {
     if (null === ($labels = $this->loadLanguageStrings())) {
         return null;
     }
     /** @var Config $config */
     $config = $this->framework->getAdapter('Contao\\Config');
     $encoded = StringUtil::encodeEmail($config->get('adminEmail'));
     return ['statusCode' => $statusCode, 'statusName' => Response::$statusTexts[$statusCode], 'error' => $labels, 'template' => $view, 'base' => $event->getRequest()->getBasePath(), 'adminEmail' => '&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $encoded, 'exception' => $event->getException()->getMessage()];
 }
Example #28
0
 /**
  * Get the details of a page including inherited parameters
  *
  * @return PageModel The page model
  *
  * @throws NoRootPageFoundException If no root page is found
  */
 public function loadDetails()
 {
     // Loaded already
     if ($this->blnDetailsLoaded) {
         return $this;
     }
     // Set some default values
     $this->protected = (bool) $this->protected;
     $this->groups = $this->protected ? \StringUtil::deserialize($this->groups) : false;
     $this->layout = $this->includeLayout ? $this->layout : false;
     $this->mobileLayout = $this->includeLayout ? $this->mobileLayout : false;
     $this->cache = $this->includeCache ? $this->cache : false;
     $pid = $this->pid;
     $type = $this->type;
     $alias = $this->alias;
     $name = $this->title;
     $title = $this->pageTitle ?: $this->title;
     $folderUrl = '';
     $palias = '';
     $pname = '';
     $ptitle = '';
     $trail = array($this->id, $pid);
     // Inherit the settings
     if ($this->type == 'root') {
         $objParentPage = $this;
         // see #4610
     } else {
         // Load all parent pages
         $objParentPage = \PageModel::findParentsById($pid);
         if ($objParentPage !== null) {
             while ($pid > 0 && $type != 'root' && $objParentPage->next()) {
                 $pid = $objParentPage->pid;
                 $type = $objParentPage->type;
                 // Parent title
                 if ($ptitle == '') {
                     $palias = $objParentPage->alias;
                     $pname = $objParentPage->title;
                     $ptitle = $objParentPage->pageTitle ?: $objParentPage->title;
                 }
                 // Page title
                 if ($type != 'root') {
                     $alias = $objParentPage->alias;
                     $name = $objParentPage->title;
                     $title = $objParentPage->pageTitle ?: $objParentPage->title;
                     $folderUrl = basename($alias) . '/' . $folderUrl;
                     $trail[] = $objParentPage->pid;
                 }
                 // Cache
                 if ($objParentPage->includeCache && $this->cache === false) {
                     $this->cache = $objParentPage->cache;
                 }
                 // Layout
                 if ($objParentPage->includeLayout) {
                     if ($this->layout === false) {
                         $this->layout = $objParentPage->layout;
                     }
                     if ($this->mobileLayout === false) {
                         $this->mobileLayout = $objParentPage->mobileLayout;
                     }
                 }
                 // Protection
                 if ($objParentPage->protected && $this->protected === false) {
                     $this->protected = true;
                     $this->groups = \StringUtil::deserialize($objParentPage->groups);
                 }
             }
         }
         // Set the titles
         $this->mainAlias = $alias;
         $this->mainTitle = $name;
         $this->mainPageTitle = $title;
         $this->parentAlias = $palias;
         $this->parentTitle = $pname;
         $this->parentPageTitle = $ptitle;
         $this->folderUrl = $folderUrl;
     }
     // Set the root ID and title
     if ($objParentPage !== null && $objParentPage->type == 'root') {
         $this->rootId = $objParentPage->id;
         $this->rootAlias = $objParentPage->alias;
         $this->rootTitle = $objParentPage->title;
         $this->rootPageTitle = $objParentPage->pageTitle ?: $objParentPage->title;
         $this->domain = $objParentPage->dns;
         $this->rootLanguage = $objParentPage->language;
         $this->language = $objParentPage->language;
         $this->staticFiles = $objParentPage->staticFiles;
         $this->staticPlugins = $objParentPage->staticPlugins;
         $this->dateFormat = $objParentPage->dateFormat;
         $this->timeFormat = $objParentPage->timeFormat;
         $this->datimFormat = $objParentPage->datimFormat;
         $this->adminEmail = $objParentPage->adminEmail;
         // Store whether the root page has been published
         $time = \Date::floorToMinute();
         $this->rootIsPublic = $objParentPage->published && ($objParentPage->start == '' || $objParentPage->start <= $time) && ($objParentPage->stop == '' || $objParentPage->stop > $time + 60);
         $this->rootIsFallback = true;
         $this->rootUseSSL = $objParentPage->useSSL;
         $this->rootFallbackLanguage = $objParentPage->language;
         // Store the fallback language (see #6874)
         if (!$objParentPage->fallback) {
             $this->rootIsFallback = false;
             $this->rootFallbackLanguage = null;
             $objFallback = static::findPublishedFallbackByHostname($objParentPage->dns);
             if ($objFallback !== null) {
                 $this->rootFallbackLanguage = $objFallback->language;
             }
         }
     } elseif (TL_MODE == 'FE' && $this->type != 'root') {
         \System::log('Page ID "' . $this->id . '" does not belong to a root page', __METHOD__, TL_ERROR);
         throw new NoRootPageFoundException('No root page found');
     }
     $this->trail = array_reverse($trail);
     // Do not cache protected pages
     if ($this->protected) {
         $this->cache = 0;
     }
     // Use the global date format if none is set (see #6104)
     if ($this->dateFormat == '') {
         $this->dateFormat = \Config::get('dateFormat');
     }
     if ($this->timeFormat == '') {
         $this->timeFormat = \Config::get('timeFormat');
     }
     if ($this->datimFormat == '') {
         $this->datimFormat = \Config::get('datimFormat');
     }
     // Prevent saving (see #6506 and #7199)
     $this->preventSaving();
     $this->blnDetailsLoaded = true;
     return $this;
 }
Example #29
0
 /**
  * Generate the markup for an RSS feed tag
  *
  * @param string $href   The script path
  * @param string $format The feed format
  * @param string $title  The feed title
  *
  * @return string The markup string
  */
 public static function generateFeedTag($href, $format, $title)
 {
     return '<link type="application/' . $format . '+xml" rel="alternate" href="' . $href . '" title="' . \StringUtil::specialchars($title) . '">';
 }
 /**
  * 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);
 }