The class converts arbitrary date strings to Unix timestamps and provides
extended information like the begin or end of the day, week, month or year.
Usage:
$date = new Date();
echo $date->datim;
$date = new Date('2011-09-18', 'Y-m-d');
echo $date->monthBegin;
Date::formatToJs('m/d/Y H:i');
/** * 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; }
/** * Obtain the correct date/time string. * * @return string */ private function determineDateFormat() { if ($format = trim($this->get('dateformat'))) { return $format; } return Date::getFormatFromRgxp($this->get('timetype')); }
/** * Generate the module */ protected function compile() { // Create the date object try { if (\Input::get('month')) { $this->Date = new \Date(\Input::get('month'), 'Ym'); } elseif (\Input::get('day')) { $this->Date = new \Date(\Input::get('day'), 'Ymd'); } else { $this->Date = new \Date(); } } catch (\OutOfBoundsException $e) { throw new PageNotFoundException('Page not found'); } $time = \Date::floorToMinute(); // Find the boundaries $objMinMax = $this->Database->query("SELECT MIN(startTime) AS dateFrom, MAX(endTime) AS dateTo, MAX(repeatEnd) AS repeatUntil FROM tl_calendar_events WHERE pid IN(" . implode(',', array_map('intval', $this->cal_calendar)) . ")" . (!BE_USER_LOGGED_IN ? " AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'" : "")); /** @var FrontendTemplate|object $objTemplate */ $objTemplate = new \FrontendTemplate($this->cal_ctemplate); // Store year and month $intYear = date('Y', $this->Date->tstamp); $intMonth = date('m', $this->Date->tstamp); $objTemplate->intYear = $intYear; $objTemplate->intMonth = $intMonth; // Previous month $prevMonth = $intMonth == 1 ? 12 : $intMonth - 1; $prevYear = $intMonth == 1 ? $intYear - 1 : $intYear; $lblPrevious = $GLOBALS['TL_LANG']['MONTHS'][$prevMonth - 1] . ' ' . $prevYear; $intPrevYm = intval($prevYear . str_pad($prevMonth, 2, 0, STR_PAD_LEFT)); // Only generate a link if there are events (see #4160) if ($objMinMax->dateFrom !== null && $intPrevYm >= date('Ym', $objMinMax->dateFrom)) { $objTemplate->prevHref = $this->strUrl . '?month=' . $intPrevYm; $objTemplate->prevTitle = specialchars($lblPrevious); $objTemplate->prevLink = $GLOBALS['TL_LANG']['MSC']['cal_previous'] . ' ' . $lblPrevious; $objTemplate->prevLabel = $GLOBALS['TL_LANG']['MSC']['cal_previous']; } // Current month $objTemplate->current = $GLOBALS['TL_LANG']['MONTHS'][date('m', $this->Date->tstamp) - 1] . ' ' . date('Y', $this->Date->tstamp); // Next month $nextMonth = $intMonth == 12 ? 1 : $intMonth + 1; $nextYear = $intMonth == 12 ? $intYear + 1 : $intYear; $lblNext = $GLOBALS['TL_LANG']['MONTHS'][$nextMonth - 1] . ' ' . $nextYear; $intNextYm = $nextYear . str_pad($nextMonth, 2, 0, STR_PAD_LEFT); // Only generate a link if there are events (see #4160) if ($objMinMax->dateTo !== null && $intNextYm <= date('Ym', max($objMinMax->dateTo, $objMinMax->repeatUntil))) { $objTemplate->nextHref = $this->strUrl . '?month=' . $intNextYm; $objTemplate->nextTitle = specialchars($lblNext); $objTemplate->nextLink = $lblNext . ' ' . $GLOBALS['TL_LANG']['MSC']['cal_next']; $objTemplate->nextLabel = $GLOBALS['TL_LANG']['MSC']['cal_next']; } // Set the week start day if (!$this->cal_startDay) { $this->cal_startDay = 0; } $objTemplate->days = $this->compileDays(); $objTemplate->weeks = $this->compileWeeks(); $objTemplate->substr = $GLOBALS['TL_LANG']['MSC']['dayShortLength']; $this->Template->calendar = $objTemplate->parse(); }
/** * @inheritdoc * * @param CalendarEventsModel $current * @param CalendarEventsModel[] $models */ protected function formatOptions(Model $current, Model\Collection $models) { $options = []; foreach ($models as $model) { $options[$model->id] = sprintf('%s [%s]', $model->title, Date::parse($GLOBALS['TL_CONFIG']['datimFormat'], $model->startTime)); } return $options; }
public function addTypeIcon($row, $label, DataContainer $dc, $args = null) { $args[0] = \Image::getHtml(\Image::get('system/modules/mail_to/assets/mail-open-image.png', 16, 16)); $objFile = FilesModel::findByUuid($row['folder']); $args[2] = $objFile !== null ? $objFile->path : '-'; $args[5] = Date::parse(Date::getFormatFromRgxp('datim'), $row['lastrun']); return $args; }
public function scopeActive(Builder $query) { $time = Date::floorToMinute(); return $query->where('disable', '')->where(function (Builder $query) use($time) { return $query->where('start', '')->orWhere('start', '<=', $time); })->where(function (Builder $query) use($time) { return $query->where('stop', '')->orWhere('stop', '>', $time + 60); }); }
/** * @inheritdoc * * @param NewsModel $current * @param NewsModel[] $models */ protected function formatOptions(Model $current, Model\Collection $models) { $sameDay = $GLOBALS['TL_LANG']['tl_product']['sameDay']; $otherDay = $GLOBALS['TL_LANG']['tl_product']['otherDay']; $dayBegin = strtotime('0:00', $current->date); $options = [$sameDay => [], $otherDay => []]; foreach ($models as $model) { $group = strtotime('0:00', $model->date) === $dayBegin ? $sameDay : $otherDay; $options[$group][$model->id] = sprintf('%s (%s) [%s]', $model->title, $model->code, Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $model->date)); } return $options; }
public function scopePublished(Builder $query, $ignoreFePreview = false) { // mimic behavior of contao models who never apply the pusblished filter when Backenduser is logged in if ($ignoreFePreview || BE_USER_LOGGED_IN) { return $query; } $time = Date::floorToMinute(); return $query->where('published', 1)->where(function (Builder $query) use($time) { return $query->where('start', '')->orWhere('start', '<=', $time); })->where(function (Builder $query) use($time) { return $query->where('stop', '')->orWhere('stop', '>', $time + 60); }); }
/** * Run the test * * @param array $data * @param string $table * * @throws ErrorException * @throws WarningException */ public function run(array $data, $table) { switch ($table) { case 'tl_calendar_events': case 'tl_news': $this->check($data['teaser']); break; case 'tl_page': $time = Date::floorToMinute(); if ($data['type'] === 'regular' && $data['robots'] !== 'noindex,nofollow' && $data['published'] && (!$data['start'] || $data['start'] <= $time) && (!$data['stop'] || $data['stop'] > $time)) { $this->check($data['description']); } break; } }
/** * Process a custom date regexp on a widget. * * @param string $rgxp The rgxp being evaluated. * * @param string $value The value to check. * * @param Widget $widget The widget to process. * * @return void * * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) */ public static function processCustomDateRegexp($rgxp, $value, $widget) { if ('MetaModelsFilterRangeDateRgXp' !== $rgxp) { return; } $format = $widget->dateformat; if (!preg_match('~^' . Date::getRegexp($format) . '$~i', $value)) { $widget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['date'], Date::getInputFormat($format))); } else { // Validate the date (see https://github.com/contao/core/issues/5086) try { new Date($value, $format); } catch (\OutOfBoundsException $e) { $widget->addError(sprintf($GLOBALS['TL_LANG']['ERR']['invalidDate'], $value)); } } }
public static function getSeparatedNumericDateTimeInterval($intStartDate = null, $intEndDate = null, $intStartTime = null, $intEndTime = null, $strIntervalDelimiter = ' – ', $strDelimiter = ', ') { $strStartDate = \Contao\Date::parse(\Contao\Date::getNumericDateFormat(), $intStartDate); $strEndDate = \Contao\Date::parse(\Contao\Date::getNumericDateFormat(), $intEndDate); $strStartTime = \Contao\Date::parse(\Contao\Date::getNumericTimeFormat(), $intStartTime); $strEndTime = \Contao\Date::parse(\Contao\Date::getNumericTimeFormat(), $intEndTime); $strResult = $strStartDate; if ($intEndDate > 0 && $intEndDate > $intStartDate && $strStartDate != $strEndDate) { $strResult .= $strIntervalDelimiter . $strEndDate; } if ($intStartTime > 0) { if ($intEndTime > $intStartTime && $strStartTime != $strEndTime) { $strResult .= $strDelimiter . $strStartTime . $strIntervalDelimiter . $strEndTime; } else { $strResult .= $strDelimiter . $strStartTime; } } return $strResult; }
/** * Render the versions dropdown menu * * @return string */ public function renderDropdown() { $objVersion = $this->Database->prepare("SELECT tstamp, version, username, active FROM tl_version WHERE fromTable=? AND pid=? ORDER BY version DESC")->execute($this->strTable, $this->intPid); if ($objVersion->numRows < 2) { return ''; } $versions = ''; while ($objVersion->next()) { $versions .= ' <option value="' . $objVersion->version . '"' . ($objVersion->active ? ' selected="selected"' : '') . '>' . $GLOBALS['TL_LANG']['MSC']['version'] . ' ' . $objVersion->version . ' (' . \Date::parse(\Config::get('datimFormat'), $objVersion->tstamp) . ') ' . $objVersion->username . '</option>'; } return ' <div class="tl_version_panel"> <form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_version" class="tl_form" method="post"> <div class="tl_formbody"> <input type="hidden" name="FORM_SUBMIT" value="tl_version"> <input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '"> <select name="version" class="tl_select">' . $versions . ' </select> <button type="submit" name="showVersion" id="showVersion" class="tl_submit">' . $GLOBALS['TL_LANG']['MSC']['restore'] . '</button> <a href="' . \Backend::addToUrl('versions=1&popup=1') . '" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['showDifferences']) . '" onclick="Backend.openModalIframe({\'width\':768,\'title\':\'' . \StringUtil::specialchars(str_replace("'", "\\'", sprintf($GLOBALS['TL_LANG']['MSC']['recordOfTable'], $this->intPid, $this->strTable))) . '\',\'url\':this.href});return false">' . \Image::getHtml('diff.svg') . '</a> </div> </form> </div> '; }
/** * Generate the module */ protected function compile() { // Show logout form if (FE_USER_LOGGED_IN) { $this->import('FrontendUser', 'User'); $this->Template->logout = true; $this->Template->formId = 'tl_logout_' . $this->id; $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['logout']); $this->Template->loggedInAs = sprintf($GLOBALS['TL_LANG']['MSC']['loggedInAs'], $this->User->username); $this->Template->action = ampersand(\Environment::get('indexFreeRequest')); if ($this->User->lastLogin > 0) { /** @var PageModel $objPage */ global $objPage; $this->Template->lastLogin = sprintf($GLOBALS['TL_LANG']['MSC']['lastLogin'][1], \Date::parse($objPage->datimFormat, $this->User->lastLogin)); } return; } $flashBag = \System::getContainer()->get('session')->getFlashBag(); if ($flashBag->has($this->strFlashType)) { $this->Template->hasError = true; $this->Template->message = $flashBag->get($this->strFlashType)[0]; } $this->Template->username = $GLOBALS['TL_LANG']['MSC']['username']; $this->Template->password = $GLOBALS['TL_LANG']['MSC']['password'][0]; $this->Template->action = ampersand(\Environment::get('indexFreeRequest')); $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['login']); $this->Template->value = \StringUtil::specialchars(\Input::post('username')); $this->Template->formId = 'tl_login_' . $this->id; $this->Template->autologin = $this->autologin && \Config::get('autologin') > 0; $this->Template->autoLabel = $GLOBALS['TL_LANG']['MSC']['autologin']; }
/** * Format a value * * @param string $k * @param mixed $value * @param boolean $blnListSingle * * @return mixed */ protected function formatValue($k, $value, $blnListSingle = false) { $value = \StringUtil::deserialize($value); // Return if empty if (empty($value)) { return ''; } /** @var PageModel $objPage */ global $objPage; // Array if (is_array($value)) { $value = implode(', ', $value); } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'date') { $value = \Date::parse($objPage->dateFormat, $value); } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'time') { $value = \Date::parse($objPage->timeFormat, $value); } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'datim') { $value = \Date::parse($objPage->datimFormat, $value); } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'url' && preg_match('@^(https?://|ftp://)@i', $value)) { $value = \Idna::decode($value); // see #5946 $value = '<a href="' . $value . '" target="_blank">' . $value . '</a>'; } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'] == 'email') { $value = \StringUtil::encodeEmail(\Idna::decode($value)); // see #5946 $value = '<a href="mailto:' . $value . '">' . $value . '</a>'; } elseif (is_array($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['reference'])) { $value = $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['reference'][$value]; } elseif ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['options'])) { if ($blnListSingle) { $value = $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['options'][$value]; } else { $value = '<span class="value">[' . $value . ']</span> ' . $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['options'][$value]; } } return $value; }
/** * Generate the module */ protected function compile() { /** @var PageModel $objPage */ global $objPage; $blnClearInput = false; $intYear = \Input::get('year'); $intMonth = \Input::get('month'); $intDay = \Input::get('day'); // Jump to the current period if (!isset($_GET['year']) && !isset($_GET['month']) && !isset($_GET['day'])) { switch ($this->cal_format) { case 'cal_year': $intYear = date('Y'); break; case 'cal_month': $intMonth = date('Ym'); break; case 'cal_day': $intDay = date('Ymd'); break; } $blnClearInput = true; } $blnDynamicFormat = !$this->cal_ignoreDynamic && in_array($this->cal_format, array('cal_day', 'cal_month', 'cal_year')); // Create the date object try { if ($blnDynamicFormat && $intYear) { $this->Date = new \Date($intYear, 'Y'); $this->cal_format = 'cal_year'; $this->headline .= ' ' . date('Y', $this->Date->tstamp); } elseif ($blnDynamicFormat && $intMonth) { $this->Date = new \Date($intMonth, 'Ym'); $this->cal_format = 'cal_month'; $this->headline .= ' ' . \Date::parse('F Y', $this->Date->tstamp); } elseif ($blnDynamicFormat && $intDay) { $this->Date = new \Date($intDay, 'Ymd'); $this->cal_format = 'cal_day'; $this->headline .= ' ' . \Date::parse($objPage->dateFormat, $this->Date->tstamp); } else { $this->Date = new \Date(); } } catch (\OutOfBoundsException $e) { throw new PageNotFoundException('Page not found'); } list($strBegin, $strEnd, $strEmpty) = $this->getDatesFromFormat($this->Date, $this->cal_format); // Get all events $arrAllEvents = $this->getAllEvents($this->cal_calendar, $strBegin, $strEnd); $sort = $this->cal_order == 'descending' ? 'krsort' : 'ksort'; // Sort the days $sort($arrAllEvents); // Sort the events foreach (array_keys($arrAllEvents) as $key) { $sort($arrAllEvents[$key]); } $arrEvents = array(); $dateBegin = date('Ymd', $strBegin); $dateEnd = date('Ymd', $strEnd); // Remove events outside the scope foreach ($arrAllEvents as $key => $days) { if ($key < $dateBegin || $key > $dateEnd) { continue; } foreach ($days as $day => $events) { foreach ($events as $event) { $event['firstDay'] = $GLOBALS['TL_LANG']['DAYS'][date('w', $day)]; $event['firstDate'] = \Date::parse($objPage->dateFormat, $day); $arrEvents[] = $event; } } } unset($arrAllEvents); $total = count($arrEvents); $limit = $total; $offset = 0; // Overall limit if ($this->cal_limit > 0) { $total = min($this->cal_limit, $total); $limit = $total; } // Pagination if ($this->perPage > 0) { $id = 'page_e' . $this->id; $page = \Input::get($id) !== null ? \Input::get($id) : 1; // Do not index or cache the page if the page number is outside the range if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) { throw new PageNotFoundException('Page not found'); } $offset = ($page - 1) * $this->perPage; $limit = min($this->perPage + $offset, $total); $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id); $this->Template->pagination = $objPagination->generate("\n "); } $strMonth = ''; $strDate = ''; $strEvents = ''; $dayCount = 0; $eventCount = 0; $headerCount = 0; $imgSize = false; // Override the default image size if ($this->imgSize != '') { $size = deserialize($this->imgSize); if ($size[0] > 0 || $size[1] > 0 || is_numeric($size[2])) { $imgSize = $this->imgSize; } } // Parse events for ($i = $offset; $i < $limit; $i++) { $event = $arrEvents[$i]; $blnIsLastEvent = false; // Last event on the current day if ($i + 1 == $limit || !isset($arrEvents[$i + 1]['firstDate']) || $event['firstDate'] != $arrEvents[$i + 1]['firstDate']) { $blnIsLastEvent = true; } /** @var FrontendTemplate|object $objTemplate */ $objTemplate = new \FrontendTemplate($this->cal_template); $objTemplate->setData($event); // Month header if ($strMonth != $event['month']) { $objTemplate->newMonth = true; $strMonth = $event['month']; } // Day header if ($strDate != $event['firstDate']) { $headerCount = 0; $objTemplate->header = true; $objTemplate->classHeader = ($dayCount % 2 == 0 ? ' even' : ' odd') . ($dayCount == 0 ? ' first' : '') . ($event['firstDate'] == $arrEvents[$limit - 1]['firstDate'] ? ' last' : ''); $strDate = $event['firstDate']; ++$dayCount; } // Show the teaser text of redirect events (see #6315) if (is_bool($event['details'])) { $objTemplate->hasDetails = false; } // Add the template variables $objTemplate->classList = $event['class'] . ($headerCount % 2 == 0 ? ' even' : ' odd') . ($headerCount == 0 ? ' first' : '') . ($blnIsLastEvent ? ' last' : '') . ' cal_' . $event['parent']; $objTemplate->classUpcoming = $event['class'] . ($eventCount % 2 == 0 ? ' even' : ' odd') . ($eventCount == 0 ? ' first' : '') . ($offset + $eventCount + 1 >= $limit ? ' last' : '') . ' cal_' . $event['parent']; $objTemplate->readMore = specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['readMore'], $event['title'])); $objTemplate->more = $GLOBALS['TL_LANG']['MSC']['more']; $objTemplate->locationLabel = $GLOBALS['TL_LANG']['MSC']['location']; // Short view if ($this->cal_noSpan) { $objTemplate->day = $event['day']; $objTemplate->date = $event['date']; } else { $objTemplate->day = $event['firstDay']; $objTemplate->date = $event['firstDate']; } $objTemplate->addImage = false; // Add an image if ($event['addImage'] && $event['singleSRC'] != '') { $objModel = \FilesModel::findByUuid($event['singleSRC']); if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) { if ($imgSize) { $event['size'] = $imgSize; } $event['singleSRC'] = $objModel->path; $this->addImageToTemplate($objTemplate, $event); } } $objTemplate->enclosure = array(); // Add enclosure if ($event['addEnclosure']) { $this->addEnclosuresToTemplate($objTemplate, $event); } $strEvents .= $objTemplate->parse(); ++$eventCount; ++$headerCount; } // No events found if ($strEvents == '') { $strEvents = "\n" . '<div class="empty">' . $strEmpty . '</div>' . "\n"; } // See #3672 $this->Template->headline = $this->headline; $this->Template->events = $strEvents; // Clear the $_GET array (see #2445) if ($blnClearInput) { \Input::setGet('year', null); \Input::setGet('month', null); \Input::setGet('day', null); } }
/** * Generate the module */ protected function compile() { /** @var PageModel $objPage */ global $objPage; $limit = null; $offset = 0; $intBegin = 0; $intEnd = 0; $intYear = \Input::get('year'); $intMonth = \Input::get('month'); $intDay = \Input::get('day'); // Jump to the current period if (!isset($_GET['year']) && !isset($_GET['month']) && !isset($_GET['day']) && $this->news_jumpToCurrent != 'all_items') { switch ($this->news_format) { case 'news_year': $intYear = date('Y'); break; default: case 'news_month': $intMonth = date('Ym'); break; case 'news_day': $intDay = date('Ymd'); break; } } // Create the date object try { if ($intYear) { $strDate = $intYear; $objDate = new \Date($strDate, 'Y'); $intBegin = $objDate->yearBegin; $intEnd = $objDate->yearEnd; $this->headline .= ' ' . date('Y', $objDate->tstamp); } elseif ($intMonth) { $strDate = $intMonth; $objDate = new \Date($strDate, 'Ym'); $intBegin = $objDate->monthBegin; $intEnd = $objDate->monthEnd; $this->headline .= ' ' . \Date::parse('F Y', $objDate->tstamp); } elseif ($intDay) { $strDate = $intDay; $objDate = new \Date($strDate, 'Ymd'); $intBegin = $objDate->dayBegin; $intEnd = $objDate->dayEnd; $this->headline .= ' ' . \Date::parse($objPage->dateFormat, $objDate->tstamp); } elseif ($this->news_jumpToCurrent == 'all_items') { $intBegin = 0; $intEnd = time(); } } catch (\OutOfBoundsException $e) { throw new PageNotFoundException('Page not found: ' . \Environment::get('uri')); } $this->Template->articles = array(); // Split the result if ($this->perPage > 0) { // Get the total number of items $intTotal = \NewsModel::countPublishedFromToByPids($intBegin, $intEnd, $this->news_archives); if ($intTotal > 0) { $total = $intTotal; // Get the current page $id = 'page_a' . $this->id; $page = \Input::get($id) !== null ? \Input::get($id) : 1; // Do not index or cache the page if the page number is outside the range if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) { throw new PageNotFoundException('Page not found: ' . \Environment::get('uri')); } // Set limit and offset $limit = $this->perPage; $offset = (max($page, 1) - 1) * $this->perPage; // Add the pagination menu $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id); $this->Template->pagination = $objPagination->generate("\n "); } } // Get the news items if (isset($limit)) { $objArticles = \NewsModel::findPublishedFromToByPids($intBegin, $intEnd, $this->news_archives, $limit, $offset); } else { $objArticles = \NewsModel::findPublishedFromToByPids($intBegin, $intEnd, $this->news_archives); } // Add the articles if ($objArticles !== null) { $this->Template->articles = $this->parseArticles($objArticles); } $this->Template->headline = trim($this->headline); $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack']; $this->Template->empty = $GLOBALS['TL_LANG']['MSC']['empty']; }
/** * Generate the dayil menu */ protected function compileDailyMenu() { $arrData = array(); $time = \Date::floorToMinute(); // Get the dates $objDates = $this->Database->query("SELECT FROM_UNIXTIME(date, '%Y%m%d') AS day, COUNT(*) AS count FROM tl_news WHERE pid IN(" . implode(',', array_map('intval', $this->news_archives)) . ")" . (!BE_USER_LOGGED_IN || TL_MODE == 'BE' ? " AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'" : "") . " GROUP BY day ORDER BY day DESC"); while ($objDates->next()) { $arrData[$objDates->day] = $objDates->count; } // Sort the data krsort($arrData); // Create the date object try { $this->Date = \Input::get('day') ? new \Date(\Input::get('day'), 'Ymd') : new \Date(); } catch (\OutOfBoundsException $e) { throw new PageNotFoundException('Page not found'); } $intYear = date('Y', $this->Date->tstamp); $intMonth = date('m', $this->Date->tstamp); $this->Template->intYear = $intYear; $this->Template->intMonth = $intMonth; // Previous month $prevMonth = $intMonth == 1 ? 12 : $intMonth - 1; $prevYear = $intMonth == 1 ? $intYear - 1 : $intYear; $lblPrevious = $GLOBALS['TL_LANG']['MONTHS'][$prevMonth - 1] . ' ' . $prevYear; $this->Template->prevHref = $this->strUrl . '?day=' . $prevYear . (strlen($prevMonth) < 2 ? '0' : '') . $prevMonth . '01'; $this->Template->prevTitle = specialchars($lblPrevious); $this->Template->prevLink = $GLOBALS['TL_LANG']['MSC']['news_previous'] . ' ' . $lblPrevious; $this->Template->prevLabel = $GLOBALS['TL_LANG']['MSC']['news_previous']; // Current month $this->Template->current = $GLOBALS['TL_LANG']['MONTHS'][date('m', $this->Date->tstamp) - 1] . ' ' . date('Y', $this->Date->tstamp); // Next month $nextMonth = $intMonth == 12 ? 1 : $intMonth + 1; $nextYear = $intMonth == 12 ? $intYear + 1 : $intYear; $lblNext = $GLOBALS['TL_LANG']['MONTHS'][$nextMonth - 1] . ' ' . $nextYear; $this->Template->nextHref = $this->strUrl . '?day=' . $nextYear . (strlen($nextMonth) < 2 ? '0' : '') . $nextMonth . '01'; $this->Template->nextTitle = specialchars($lblNext); $this->Template->nextLink = $lblNext . ' ' . $GLOBALS['TL_LANG']['MSC']['news_next']; $this->Template->nextLabel = $GLOBALS['TL_LANG']['MSC']['news_next']; // Set week start day if (!$this->news_startDay) { $this->news_startDay = 0; } $this->Template->daily = true; $this->Template->days = $this->compileDays(); $this->Template->weeks = $this->compileWeeks($arrData); $this->Template->showQuantity = $this->news_showQuantity != '' ? true : false; }
/** * Add newsletters to the indexer * * @param array $arrPages * @param integer $intRoot * @param boolean $blnIsSitemap * * @return array */ public function getSearchablePages($arrPages, $intRoot = 0, $blnIsSitemap = false) { $arrRoot = array(); if ($intRoot > 0) { $arrRoot = $this->Database->getChildRecords($intRoot, 'tl_page'); } $arrProcessed = array(); $time = \Date::floorToMinute(); // Get all channels $objNewsletter = \NewsletterChannelModel::findAll(); // Walk through each channel if ($objNewsletter !== null) { while ($objNewsletter->next()) { if (!$objNewsletter->jumpTo) { continue; } // Skip channels outside the root nodes if (!empty($arrRoot) && !in_array($objNewsletter->jumpTo, $arrRoot)) { continue; } // Get the URL of the jumpTo page if (!isset($arrProcessed[$objNewsletter->jumpTo])) { $objParent = \PageModel::findWithDetails($objNewsletter->jumpTo); // The target page does not exist if ($objParent === null) { continue; } // The target page has not been published (see #5520) if (!$objParent->published || $objParent->start != '' && $objParent->start > $time || $objParent->stop != '' && $objParent->stop <= $time + 60) { continue; } // The target page is exempt from the sitemap (see #6418) if ($blnIsSitemap && $objParent->sitemap == 'map_never') { continue; } // Set the domain (see #6421) $domain = ($objParent->rootUseSSL ? 'https://' : 'http://') . ($objParent->domain ?: \Environment::get('host')) . \Environment::get('path') . '/'; // Generate the URL $arrProcessed[$objNewsletter->jumpTo] = $domain . $this->generateFrontendUrl($objParent->row(), \Config::get('useAutoItem') ? '/%s' : '/items/%s', $objParent->language); } $strUrl = $arrProcessed[$objNewsletter->jumpTo]; // Get the items $objItem = \NewsletterModel::findSentByPid($objNewsletter->id); if ($objItem !== null) { while ($objItem->next()) { $arrPages[] = sprintf($strUrl, $objItem->alias ?: $objItem->id); } } } } return $arrPages; }
/** * Set all user properties from a database record */ protected function setUserFromDb() { $this->intId = $this->id; // Unserialize values foreach ($this->arrData as $k => $v) { if (!is_numeric($v)) { $this->{$k} = deserialize($v); } } $GLOBALS['TL_USERNAME'] = $this->username; \System::getContainer()->get('request_stack')->getCurrentRequest()->setLocale($this->language); \System::getContainer()->get('translator')->setLocale($this->language); // Deprecated since Contao 4.0, to be removed in Contao 5.0 $GLOBALS['TL_LANGUAGE'] = str_replace('_', '-', $this->language); \Config::set('showHelp', $this->showHelp); \Config::set('useRTE', $this->useRTE); \Config::set('useCE', $this->useCE); \Config::set('thumbnails', $this->thumbnails); \Config::set('backendTheme', $this->backendTheme); // Inherit permissions $always = array('alexf'); $depends = array('modules', 'themes', 'pagemounts', 'alpty', 'filemounts', 'fop', 'forms', 'formp', 'imageSizes'); // HOOK: Take custom permissions if (!empty($GLOBALS['TL_PERMISSIONS']) && is_array($GLOBALS['TL_PERMISSIONS'])) { $depends = array_merge($depends, $GLOBALS['TL_PERMISSIONS']); } // Overwrite user permissions if only group permissions shall be inherited if ($this->inherit == 'group') { foreach ($depends as $field) { $this->{$field} = array(); } } // Merge permissions $inherit = in_array($this->inherit, array('group', 'extend')) ? array_merge($always, $depends) : $always; $time = \Date::floorToMinute(); foreach ((array) $this->groups as $id) { $objGroup = $this->Database->prepare("SELECT * FROM tl_user_group WHERE id=? AND disable!='1' AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "')")->limit(1)->execute($id); if ($objGroup->numRows > 0) { foreach ($inherit as $field) { $value = deserialize($objGroup->{$field}, true); // The new page/file picker can return integers instead of arrays, so use empty() instead of is_array() and deserialize(true) here if (!empty($value)) { $this->{$field} = array_merge(is_array($this->{$field}) ? $this->{$field} : ($this->{$field} != '' ? array($this->{$field}) : array()), $value); $this->{$field} = array_unique($this->{$field}); } } } } // Make sure pagemounts and filemounts are set! if (!is_array($this->pagemounts)) { $this->pagemounts = array(); } else { $this->pagemounts = array_filter($this->pagemounts); } if (!is_array($this->filemounts)) { $this->filemounts = array(); } else { $this->filemounts = array_filter($this->filemounts); } // Store the numeric file mounts $this->arrFilemountIds = $this->filemounts; // Convert the file mounts into paths if (!$this->isAdmin && !empty($this->filemounts)) { $objFiles = \FilesModel::findMultipleByUuids($this->filemounts); if ($objFiles !== null) { $this->filemounts = $objFiles->fetchEach('path'); } } }
/** * 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; }
/** * 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); }
/** * Parse a date format string and translate textual representations * * @param string $strFormat The date format string * @param integer $intTstamp An optional timestamp * * @return string The textual representation of the date * * @deprecated Deprecated since Contao 4.0, to be removed in Contao 5.0. * Use Date::parse() instead. */ public static function parseDate($strFormat, $intTstamp = null) { @trigger_error('Using System::parseDate() has been deprecated and will no longer work in Contao 5.0. Use Date::parse() instead.', E_USER_DEPRECATED); return \Date::parse($strFormat, $intTstamp); }
/** * @param $strTable * @param $strLanguage * @param $strName * @param $varValue * @return string */ protected function renderParameterValue($strTable, $strLanguage, $strName, $varValue) { if ($varValue == '') { return ''; } $this->loadLanguageFile('default', $strLanguage, true); $this->loadLanguageFile($strTable, $strLanguage, true); $this->loadDataContainer($strTable); if ($GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['inputType'] == 'password') { return ''; } $varValue = deserialize($varValue); $rgxp = $GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['eval']['rgxp']; $opts = $GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['options']; $rfrc = $GLOBALS['TL_DCA'][$strTable]['fields'][$strName]['reference']; if ($rgxp == 'date') { $varValue = Date::parse($GLOBALS['TL_CONFIG']['dateFormat'], $varValue); } elseif ($rgxp == 'time') { $varValue = Date::parse($GLOBALS['TL_CONFIG']['timeFormat'], $varValue); } elseif ($rgxp == 'datim') { $varValue = Date::parse($GLOBALS['TL_CONFIG']['datimFormat'], $varValue); } elseif (is_array($varValue)) { $varValue = implode(', ', $varValue); } elseif (is_array($opts) && array_is_assoc($opts)) { $varValue = isset($opts[$varValue]) ? $opts[$varValue] : $varValue; } elseif (is_array($rfrc)) { $varValue = isset($rfrc[$varValue]) ? is_array($rfrc[$varValue]) ? $rfrc[$varValue][0] : $rfrc[$varValue] : $varValue; } $varValue = specialchars($varValue); return (string) $varValue; }
/** * Add comments to a template * * @param FrontendTemplate|object $objTemplate * @param \stdClass $objConfig * @param string $strSource * @param integer $intParent * @param mixed $varNotifies */ public function addCommentsToTemplate(FrontendTemplate $objTemplate, \stdClass $objConfig, $strSource, $intParent, $varNotifies) { /** @var PageModel $objPage */ global $objPage; $limit = 0; $offset = 0; $total = 0; $gtotal = 0; $arrComments = array(); $objTemplate->comments = array(); // see #4064 // Pagination if ($objConfig->perPage > 0) { // Get the total number of comments $intTotal = \CommentsModel::countPublishedBySourceAndParent($strSource, $intParent); $total = $gtotal = $intTotal; // Calculate the key (e.g. tl_form_field becomes page_cff12) $key = ''; $chunks = explode('_', substr($strSource, strncmp($strSource, 'tl_', 3) === 0 ? 3 : 0)); foreach ($chunks as $chunk) { $key .= substr($chunk, 0, 1); } // Get the current page $id = 'page_c' . $key . $intParent; // see #4141 $page = \Input::get($id) !== null ? \Input::get($id) : 1; // Do not index or cache the page if the page number is outside the range if ($page < 1 || $page > max(ceil($total / $objConfig->perPage), 1)) { throw new PageNotFoundException('Page not found: ' . \Environment::get('uri')); } // Set limit and offset $limit = $objConfig->perPage; $offset = ($page - 1) * $objConfig->perPage; // Initialize the pagination menu $objPagination = new \Pagination($total, $objConfig->perPage, \Config::get('maxPaginationLinks'), $id); $objTemplate->pagination = $objPagination->generate("\n "); } $objTemplate->allowComments = true; // Get all published comments if ($limit) { $objComments = \CommentsModel::findPublishedBySourceAndParent($strSource, $intParent, $objConfig->order == 'descending', $limit, $offset); } else { $objComments = \CommentsModel::findPublishedBySourceAndParent($strSource, $intParent, $objConfig->order == 'descending'); } // Parse the comments if ($objComments !== null && ($total = $objComments->count()) > 0) { $count = 0; if ($objConfig->template == '') { $objConfig->template = 'com_default'; } /** @var FrontendTemplate|object $objPartial */ $objPartial = new \FrontendTemplate($objConfig->template); while ($objComments->next()) { $objPartial->setData($objComments->row()); // Clean the RTE output $objPartial->comment = \StringUtil::toHtml5($objComments->comment); $objPartial->comment = trim(str_replace(array('{{', '}}'), array('{{', '}}'), $objPartial->comment)); $objPartial->datim = \Date::parse($objPage->datimFormat, $objComments->date); $objPartial->date = \Date::parse($objPage->dateFormat, $objComments->date); $objPartial->class = ($count < 1 ? ' first' : '') . ($count >= $total - 1 ? ' last' : '') . ($count % 2 == 0 ? ' even' : ' odd'); $objPartial->by = $GLOBALS['TL_LANG']['MSC']['com_by']; $objPartial->id = 'c' . $objComments->id; $objPartial->timestamp = $objComments->date; $objPartial->datetime = date('Y-m-d\\TH:i:sP', $objComments->date); $objPartial->addReply = false; // Reply if ($objComments->addReply && $objComments->reply != '') { if (($objAuthor = $objComments->getRelated('author')) instanceof UserModel) { $objPartial->addReply = true; $objPartial->rby = $GLOBALS['TL_LANG']['MSC']['com_reply']; $objPartial->reply = $this->replaceInsertTags($objComments->reply); $objPartial->author = $objAuthor; // Clean the RTE output $objPartial->reply = \StringUtil::toHtml5($objPartial->reply); } } $arrComments[] = $objPartial->parse(); ++$count; } } $objTemplate->comments = $arrComments; $objTemplate->addComment = $GLOBALS['TL_LANG']['MSC']['addComment']; $objTemplate->name = $GLOBALS['TL_LANG']['MSC']['com_name']; $objTemplate->email = $GLOBALS['TL_LANG']['MSC']['com_email']; $objTemplate->website = $GLOBALS['TL_LANG']['MSC']['com_website']; $objTemplate->commentsTotal = $limit ? $gtotal : $total; // Add a form to create new comments $this->renderCommentForm($objTemplate, $objConfig, $strSource, $intParent, $varNotifies); }
/** * Generate the Google XML sitemaps * * @param integer $intId The root page ID */ public function generateSitemap($intId = 0) { $time = \Date::floorToMinute(); $objDatabase = \Database::getInstance(); $this->purgeXmlFiles(); // Only root pages should have sitemap names $objDatabase->execute("UPDATE tl_page SET createSitemap='', sitemapName='' WHERE type!='root'"); // Get a particular root page if ($intId > 0) { do { $objRoot = $objDatabase->prepare("SELECT * FROM tl_page WHERE id=?")->limit(1)->execute($intId); if ($objRoot->numRows < 1) { break; } $intId = $objRoot->pid; } while ($objRoot->type != 'root' && $intId > 0); // Make sure the page is published if (!$objRoot->published || $objRoot->start != '' && $objRoot->start > $time || $objRoot->stop != '' && $objRoot->stop <= $time + 60) { return; } // Check the sitemap name if (!$objRoot->createSitemap || !$objRoot->sitemapName) { return; } $objRoot->reset(); } else { $objRoot = $objDatabase->execute("SELECT id, language, sitemapName FROM tl_page WHERE type='root' AND createSitemap='1' AND sitemapName!='' AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'"); } // Return if there are no pages if ($objRoot->numRows < 1) { return; } // Create the XML file while ($objRoot->next()) { $objFile = new \File('web/share/' . $objRoot->sitemapName . '.xml'); $objFile->truncate(); $objFile->append('<?xml version="1.0" encoding="UTF-8"?>'); $objFile->append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'); // Find the searchable pages $arrPages = \Backend::findSearchablePages($objRoot->id, '', true); // HOOK: take additional pages if (isset($GLOBALS['TL_HOOKS']['getSearchablePages']) && is_array($GLOBALS['TL_HOOKS']['getSearchablePages'])) { foreach ($GLOBALS['TL_HOOKS']['getSearchablePages'] as $callback) { $this->import($callback[0]); $arrPages = $this->{$callback[0]}->{$callback[1]}($arrPages, $objRoot->id, true, $objRoot->language); } } // Add pages foreach ($arrPages as $strUrl) { $strUrl = rawurlencode($strUrl); $strUrl = str_replace(array('%2F', '%3F', '%3D', '%26', '%3A//'), array('/', '?', '=', '&', '://'), $strUrl); $strUrl = ampersand($strUrl, true); $objFile->append(' <url><loc>' . $strUrl . '</loc></url>'); } $objFile->append('</urlset>'); $objFile->close(); // Add a log entry $this->log('Generated sitemap "' . $objRoot->sitemapName . '.xml"', __METHOD__, TL_CRON); } }
/** * Find ten matching usernames and return them as JSON */ protected function getDatalistOptions() { if (!$this->User->isAdmin) { header('HTTP/1.1 400 Bad Request'); die('You must be an administrator to use the script'); } $arrUsers = array(); $time = \Date::floorToMinute(); // Get the active front end users $objUsers = $this->Database->prepare("SELECT username FROM tl_member WHERE username LIKE ? AND login='******' AND disable!='1' AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') ORDER BY username")->limit(10)->execute(str_replace('%', '', \Input::post('value')) . '%'); if ($objUsers->numRows) { $arrUsers = $objUsers->fetchEach('username'); } header('Content-type: application/json'); die(json_encode($arrUsers)); }
/** * 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; }
/** * Send an admin notification e-mail * * @param integer $intId * @param array $arrData */ protected function sendAdminNotification($intId, $arrData) { $objEmail = new \Email(); $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL']; $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME']; $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['adminSubject'], \Idna::decode(\Environment::get('host'))); $strData = "\n\n"; // Add user details foreach ($arrData as $k => $v) { if ($k == 'password' || $k == 'tstamp' || $k == 'activation' || $k == 'dateAdded') { continue; } $v = \StringUtil::deserialize($v); if ($k == 'dateOfBirth' && strlen($v)) { $v = \Date::parse(\Config::get('dateFormat'), $v); } $strData .= $GLOBALS['TL_LANG']['tl_member'][$k][0] . ': ' . (is_array($v) ? implode(', ', $v) : $v) . "\n"; } $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['adminText'], $intId, $strData . "\n") . "\n"; $objEmail->sendTo($GLOBALS['TL_ADMIN_EMAIL']); $this->log('A new user (ID ' . $intId . ') has registered on the website', __METHOD__, TL_ACCESS); }
/** * Return the formatted group header as string * * @param string $field * @param mixed $value * @param integer $mode * * @return string */ protected function formatCurrentValue($field, $value, $mode) { $remoteNew = $value; // see #3861 if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) { $remoteNew = $value != '' ? ucfirst($GLOBALS['TL_LANG']['MSC']['yes']) : ucfirst($GLOBALS['TL_LANG']['MSC']['no']); } elseif (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['foreignKey'])) { $key = explode('.', $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['foreignKey'], 2); $objParent = $this->Database->prepare("SELECT " . $key[1] . " AS value FROM " . $key[0] . " WHERE id=?")->limit(1)->execute($value); if ($objParent->numRows) { $remoteNew = $objParent->value; } } elseif (in_array($mode, array(1, 2))) { $remoteNew = $value != '' ? ucfirst(Utf8::substr($value, 0, 1)) : '-'; } elseif (in_array($mode, array(3, 4))) { if (!isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['length'])) { $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['length'] = 2; } $remoteNew = $value != '' ? ucfirst(Utf8::substr($value, 0, $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['length'])) : '-'; } elseif (in_array($mode, array(5, 6))) { $remoteNew = $value != '' ? \Date::parse(\Config::get('dateFormat'), $value) : '-'; } elseif (in_array($mode, array(7, 8))) { $remoteNew = $value != '' ? date('Y-m', $value) : '-'; $intMonth = $value != '' ? date('m', $value) - 1 : '-'; if (isset($GLOBALS['TL_LANG']['MONTHS'][$intMonth])) { $remoteNew = $value != '' ? $GLOBALS['TL_LANG']['MONTHS'][$intMonth] . ' ' . date('Y', $value) : '-'; } } elseif (in_array($mode, array(9, 10))) { $remoteNew = $value != '' ? date('Y', $value) : '-'; } else { if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) { $remoteNew = $value != '' ? $field : ''; } elseif (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'])) { $remoteNew = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['reference'][$value]; } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options'])) { $remoteNew = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['options'][$value]; } else { $remoteNew = $value; } if (is_array($remoteNew)) { $remoteNew = $remoteNew[0]; } if (empty($remoteNew)) { $remoteNew = '-'; } } return $remoteNew; }
/** * Generate the module */ protected function compile() { // Show logout form if (FE_USER_LOGGED_IN) { $this->import('FrontendUser', 'User'); $this->Template->logout = true; $this->Template->formId = 'tl_logout_' . $this->id; $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['logout']); $this->Template->loggedInAs = sprintf($GLOBALS['TL_LANG']['MSC']['loggedInAs'], $this->User->username); $this->Template->action = ampersand(\Environment::get('indexFreeRequest')); if ($this->User->lastLogin > 0) { /** @var PageModel $objPage */ global $objPage; $this->Template->lastLogin = sprintf($GLOBALS['TL_LANG']['MSC']['lastLogin'][1], \Date::parse($objPage->datimFormat, $this->User->lastLogin)); } return; } $blnHasError = false; if (isset($_SESSION['MESSAGES'][TL_MODE]['TL_ERROR'])) { $blnHasError = true; $_SESSION['LOGIN_ERROR'] = $_SESSION['MESSAGES'][TL_MODE]['TL_ERROR'][0]; unset($_SESSION['MESSAGES'][TL_MODE]['TL_ERROR']); } if (isset($_SESSION['LOGIN_ERROR'])) { $blnHasError = true; $this->Template->message = $_SESSION['LOGIN_ERROR']; } $this->Template->hasError = $blnHasError; $this->Template->username = $GLOBALS['TL_LANG']['MSC']['username']; $this->Template->password = $GLOBALS['TL_LANG']['MSC']['password'][0]; $this->Template->action = ampersand(\Environment::get('indexFreeRequest')); $this->Template->slabel = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['login']); $this->Template->value = \StringUtil::specialchars(\Input::post('username')); $this->Template->formId = 'tl_login_' . $this->id; $this->Template->autologin = $this->autologin && \Config::get('autologin') > 0; $this->Template->autoLabel = $GLOBALS['TL_LANG']['MSC']['autologin']; }