_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q243300 | tl_page.generateSitemap | validation | public function generateSitemap()
{
/** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
$objSession = Contao\System::getContainer()->get('session');
$session = $objSession->get('sitemap_updater');
if (empty($session) || !\is_array($session))
{
return;
}
$this->import('Contao\Automator', 'Automator');
foreach ($session as $id)
{
$this->Automator->generateSitemap($id);
}
$objSession->set('sitemap_updater', null);
} | php | {
"resource": ""
} |
q243301 | tl_page.scheduleUpdate | validation | public function scheduleUpdate(Contao\DataContainer $dc)
{
// Return if there is no ID
if (!$dc->activeRecord || !$dc->activeRecord->id || Contao\Input::get('act') == 'copy')
{
return;
}
/** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
$objSession = Contao\System::getContainer()->get('session');
// Store the ID in the session
$session = $objSession->get('sitemap_updater');
$session[] = Contao\PageModel::findWithDetails($dc->activeRecord->id)->rootId;
$objSession->set('sitemap_updater', array_unique($session));
} | php | {
"resource": ""
} |
q243302 | tl_page.generateAlias | validation | public function generateAlias($varValue, Contao\DataContainer $dc)
{
$objPage = Contao\PageModel::findWithDetails($dc->id);
$aliasExists = function (string $alias) use ($dc, $objPage): bool
{
$objAliasIds = $this->Database->prepare("SELECT id FROM tl_page WHERE alias=? AND id!=?")
->execute($alias, $dc->id);
if (!$objAliasIds->numRows)
{
return false;
}
$strCurrentDomain = $objPage->domain;
$strCurrentLanguage = $objPage->rootLanguage;
if ($objPage->type == 'root')
{
$strCurrentDomain = Contao\Input::post('dns');
$strCurrentLanguage = Contao\Input::post('language');
}
while ($objAliasIds->next())
{
$objAliasPage = Contao\PageModel::findWithDetails($objAliasIds->id);
if ($objAliasPage->domain != $strCurrentDomain)
{
continue;
}
if (Contao\Config::get('addLanguageToUrl') && $objAliasPage->rootLanguage != $strCurrentLanguage)
{
continue;
}
// Duplicate alias found
return true;
}
return false;
};
// Generate an alias if there is none
if ($varValue == '')
{
$varValue = Contao\System::getContainer()->get('contao.slug')->generate
(
$dc->activeRecord->title,
$dc->activeRecord->id,
function ($alias) use ($objPage, $aliasExists)
{
return $aliasExists((Contao\Config::get('folderUrl') ? $objPage->folderUrl : '') . $alias);
}
);
// Generate folder URL aliases (see #4933)
if (Contao\Config::get('folderUrl') && $objPage->folderUrl != '')
{
$varValue = $objPage->folderUrl . $varValue;
}
}
elseif ($aliasExists($varValue))
{
throw new Exception(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $varValue));
}
return $varValue;
} | php | {
"resource": ""
} |
q243303 | tl_page.generateArticle | validation | public function generateArticle(Contao\DataContainer $dc)
{
// Return if there is no active record (override all)
if (!$dc->activeRecord)
{
return;
}
// No title or not a regular page
if ($dc->activeRecord->title == '' || !\in_array($dc->activeRecord->type, array('regular', 'error_401', 'error_403', 'error_404')))
{
return;
}
/** @var Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface $objSessionBag */
$objSessionBag = Contao\System::getContainer()->get('session')->getBag('contao_backend');
$new_records = $objSessionBag->get('new_records');
// Not a new page
if (!$new_records || !\is_array($new_records[$dc->table]) || !\in_array($dc->id, $new_records[$dc->table]))
{
return;
}
// Check whether there are articles (e.g. on copied pages)
$objTotal = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_article WHERE pid=?")
->execute($dc->id);
if ($objTotal->count > 0)
{
return;
}
// Create article
$arrSet['pid'] = $dc->id;
$arrSet['sorting'] = 128;
$arrSet['tstamp'] = time();
$arrSet['author'] = $this->User->id;
$arrSet['inColumn'] = 'main';
$arrSet['title'] = $dc->activeRecord->title;
$arrSet['alias'] = str_replace('/', '-', $dc->activeRecord->alias); // see #5168
$arrSet['published'] = $dc->activeRecord->published;
$this->Database->prepare("INSERT INTO tl_article %s")->set($arrSet)->execute();
} | php | {
"resource": ""
} |
q243304 | tl_page.purgeSearchIndex | validation | public function purgeSearchIndex(Contao\DataContainer $dc)
{
if (!$dc->id)
{
return;
}
$objResult = $this->Database->prepare("SELECT id FROM tl_search WHERE pid=?")
->execute($dc->id);
while ($objResult->next())
{
$this->Database->prepare("DELETE FROM tl_search WHERE id=?")
->execute($objResult->id);
$this->Database->prepare("DELETE FROM tl_search_index WHERE pid=?")
->execute($objResult->id);
}
} | php | {
"resource": ""
} |
q243305 | tl_page.checkFeedAlias | validation | public function checkFeedAlias($varValue, Contao\DataContainer $dc)
{
// No change or empty value
if ($varValue == $dc->value || $varValue == '')
{
return $varValue;
}
$varValue = Contao\StringUtil::standardize($varValue); // see #5096
$this->import('Contao\Automator', 'Automator');
$arrFeeds = $this->Automator->purgeXmlFiles(true);
// Alias exists
if (\in_array($varValue, $arrFeeds))
{
throw new Exception(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $varValue));
}
return $varValue;
} | php | {
"resource": ""
} |
q243306 | tl_page.checkJumpTo | validation | public function checkJumpTo($varValue, Contao\DataContainer $dc)
{
if ($varValue == $dc->id)
{
throw new Exception($GLOBALS['TL_LANG']['ERR']['circularReference']);
}
return $varValue;
} | php | {
"resource": ""
} |
q243307 | tl_page.getPageTypes | validation | public function getPageTypes(Contao\DataContainer $dc)
{
$arrOptions = array();
foreach (array_keys($GLOBALS['TL_PTY']) as $pty)
{
// Root pages are allowed on the first level only (see #6360)
if ($pty == 'root' && $dc->activeRecord && $dc->activeRecord->pid > 0)
{
continue;
}
// Allow the currently selected option and anything the user has access to
if ($pty == $dc->value || $this->User->hasAccess($pty, 'alpty'))
{
$arrOptions[] = $pty;
}
}
return $arrOptions;
} | php | {
"resource": ""
} |
q243308 | tl_page.getPageLayouts | validation | public function getPageLayouts()
{
$objLayout = $this->Database->execute("SELECT l.id, l.name, t.name AS theme FROM tl_layout l LEFT JOIN tl_theme t ON l.pid=t.id ORDER BY t.name, l.name");
if ($objLayout->numRows < 1)
{
return array();
}
$return = array();
while ($objLayout->next())
{
$return[$objLayout->theme][$objLayout->id] = $objLayout->name;
}
return $return;
} | php | {
"resource": ""
} |
q243309 | tl_page.copyPageWithSubpages | validation | public function copyPageWithSubpages($row, $href, $label, $title, $icon, $attributes, $table)
{
if ($GLOBALS['TL_DCA'][$table]['config']['closed'])
{
return '';
}
$objSubpages = Contao\PageModel::findByPid($row['id']);
return ($objSubpages !== null && $objSubpages->count() > 0 && $this->User->hasAccess($row['type'], 'alpty') && $this->User->isAllowed(Contao\BackendUser::CAN_EDIT_PAGE_HIERARCHY, $row)) ? '<a href="'.$this->addToUrl($href.'&id='.$row['id']).'" title="'.Contao\StringUtil::specialchars($title).'"'.$attributes.'>'.Contao\Image::getHtml($icon, $label).'</a> ' : Contao\Image::getHtml(preg_replace('/\.svg$/i', '_.svg', $icon)).' ';
} | php | {
"resource": ""
} |
q243310 | tl_page.cutPage | validation | public function cutPage($row, $href, $label, $title, $icon, $attributes)
{
return ($this->User->hasAccess($row['type'], 'alpty') && $this->User->isAllowed(Contao\BackendUser::CAN_EDIT_PAGE_HIERARCHY, $row)) ? '<a href="'.$this->addToUrl($href.'&id='.$row['id']).'" title="'.Contao\StringUtil::specialchars($title).'"'.$attributes.'>'.Contao\Image::getHtml($icon, $label).'</a> ' : Contao\Image::getHtml(preg_replace('/\.svg$/i', '_.svg', $icon)).' ';
} | php | {
"resource": ""
} |
q243311 | tl_page.deletePage | validation | public function deletePage($row, $href, $label, $title, $icon, $attributes)
{
$root = func_get_arg(7);
return ($this->User->hasAccess($row['type'], 'alpty') && $this->User->isAllowed(Contao\BackendUser::CAN_DELETE_PAGE, $row) && ($this->User->isAdmin || !\in_array($row['id'], $root))) ? '<a href="'.$this->addToUrl($href.'&id='.$row['id']).'" title="'.Contao\StringUtil::specialchars($title).'"'.$attributes.'>'.Contao\Image::getHtml($icon, $label).'</a> ' : Contao\Image::getHtml(preg_replace('/\.svg$/i', '_.svg', $icon)).' ';
} | php | {
"resource": ""
} |
q243312 | ModuleEventReader.getDateAndTime | validation | private function getDateAndTime(CalendarEventsModel $objEvent, PageModel $objPage, $intStartTime, $intEndTime, $span)
{
$strDate = Date::parse($objPage->dateFormat, $intStartTime);
if ($span > 0)
{
$strDate = Date::parse($objPage->dateFormat, $intStartTime) . $GLOBALS['TL_LANG']['MSC']['cal_timeSeparator'] . Date::parse($objPage->dateFormat, $intEndTime);
}
$strTime = '';
if ($objEvent->addTime)
{
if ($span > 0)
{
$strDate = Date::parse($objPage->datimFormat, $intStartTime) . $GLOBALS['TL_LANG']['MSC']['cal_timeSeparator'] . Date::parse($objPage->datimFormat, $intEndTime);
}
elseif ($intStartTime == $intEndTime)
{
$strTime = Date::parse($objPage->timeFormat, $intStartTime);
}
else
{
$strTime = Date::parse($objPage->timeFormat, $intStartTime) . $GLOBALS['TL_LANG']['MSC']['cal_timeSeparator'] . Date::parse($objPage->timeFormat, $intEndTime);
}
}
return array($strDate, $strTime);
} | php | {
"resource": ""
} |
q243313 | tl_news_feed.getAllowedArchives | validation | public function getAllowedArchives()
{
if ($this->User->isAdmin)
{
$objArchive = Contao\NewsArchiveModel::findAll();
}
else
{
$objArchive = Contao\NewsArchiveModel::findMultipleByIds($this->User->news);
}
$return = array();
if ($objArchive !== null)
{
while ($objArchive->next())
{
$return[$objArchive->id] = $objArchive->title;
}
}
return $return;
} | php | {
"resource": ""
} |
q243314 | tl_form.getAllTables | validation | public function getAllTables()
{
$arrTables = $this->Database->listTables();
$arrViews = Contao\System::getContainer()->get('database_connection')->getSchemaManager()->listViews();
if (!empty($arrViews))
{
$arrTables = array_merge($arrTables, array_keys($arrViews));
natsort($arrTables);
}
return array_values($arrTables);
} | php | {
"resource": ""
} |
q243315 | Automator.purgeSearchTables | validation | public function purgeSearchTables()
{
$objDatabase = Database::getInstance();
// Truncate the tables
$objDatabase->execute("TRUNCATE TABLE tl_search");
$objDatabase->execute("TRUNCATE TABLE tl_search_index");
$strCachePath = StringUtil::stripRootDir(System::getContainer()->getParameter('kernel.cache_dir'));
// Purge the cache folder
$objFolder = new Folder($strCachePath . '/contao/search');
$objFolder->purge();
// Add a log entry
$this->log('Purged the search tables', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243316 | Automator.purgeVersionTable | validation | public function purgeVersionTable()
{
$objDatabase = Database::getInstance();
// Truncate the table
$objDatabase->execute("TRUNCATE TABLE tl_version");
// Add a log entry
$this->log('Purged the version table', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243317 | Automator.purgeImageCache | validation | public function purgeImageCache()
{
$container = System::getContainer();
$strTargetPath = StringUtil::stripRootDir($container->getParameter('contao.image.target_dir'));
$strRootDir = $container->getParameter('kernel.project_dir');
// Walk through the subfolders
foreach (scan($strRootDir . '/' . $strTargetPath) as $dir)
{
if (strncmp($dir, '.', 1) !== 0)
{
$objFolder = new Folder($strTargetPath . '/' . $dir);
$objFolder->purge();
}
}
// Also empty the page cache so there are no links to deleted images
$this->purgePageCache();
// Add a log entry
$this->log('Purged the image cache', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243318 | Automator.purgeScriptCache | validation | public function purgeScriptCache()
{
// assets/js and assets/css
foreach (array('assets/js', 'assets/css') as $dir)
{
// Purge the folder
$objFolder = new Folder($dir);
$objFolder->purge();
}
// Recreate the internal style sheets
$this->import(StyleSheets::class, 'StyleSheets');
$this->StyleSheets->updateStyleSheets();
// Also empty the page cache so there are no links to deleted scripts
$this->purgePageCache();
// Add a log entry
$this->log('Purged the script cache', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243319 | Automator.purgePageCache | validation | public function purgePageCache()
{
$strCacheDir = StringUtil::stripRootDir(System::getContainer()->getParameter('kernel.cache_dir'));
$objFolder = new Folder($strCacheDir . '/http_cache');
$objFolder->purge();
// Add a log entry
$this->log('Purged the page cache', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243320 | Automator.purgeInternalCache | validation | public function purgeInternalCache()
{
$container = System::getContainer();
$clearer = $container->get('contao.cache.clear_internal');
$clearer->clear($container->getParameter('kernel.cache_dir'));
// Add a log entry
$this->log('Purged the internal cache', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243321 | Automator.purgeRegistrations | validation | public function purgeRegistrations()
{
$objMember = MemberModel::findExpiredRegistrations();
if ($objMember === null)
{
return;
}
while ($objMember->next())
{
$objMember->delete();
}
// Add a log entry
$this->log('Purged the unactivated member registrations', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243322 | Automator.purgeOptInTokens | validation | public function purgeOptInTokens()
{
/** @var OptIn $optIn */
$optIn = System::getContainer()->get('contao.opt-in');
$optIn->purgeTokens();
// Add a log entry
$this->log('Purged the expired double opt-in tokens', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243323 | Automator.generateXmlFiles | validation | public function generateXmlFiles()
{
// Sitemaps
$this->generateSitemap();
// HOOK: add custom jobs
if (isset($GLOBALS['TL_HOOKS']['generateXmlFiles']) && \is_array($GLOBALS['TL_HOOKS']['generateXmlFiles']))
{
foreach ($GLOBALS['TL_HOOKS']['generateXmlFiles'] as $callback)
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}();
}
}
// Also empty the page cache so there are no links to deleted files
$this->purgePageCache();
// Add a log entry
$this->log('Regenerated the XML files', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243324 | Automator.generateInternalCache | validation | public function generateInternalCache()
{
$container = System::getContainer();
$warmer = $container->get('contao.cache.warm_internal');
$warmer->warmUp($container->getParameter('kernel.cache_dir'));
// Add a log entry
$this->log('Generated the internal cache', __METHOD__, TL_CRON);
} | php | {
"resource": ""
} |
q243325 | Automator.rotateLogs | validation | public function rotateLogs()
{
@trigger_error('Using Automator::rotateLogs() has been deprecated and will no longer work in Contao 5.0. Use the logger service instead, which rotates its log files automatically.', E_USER_DEPRECATED);
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
$arrFiles = preg_grep('/\.log$/', scan($rootDir . '/system/logs'));
foreach ($arrFiles as $strFile)
{
$objFile = new File('system/logs/' . $strFile . '.9');
// Delete the oldest file
if ($objFile->exists())
{
$objFile->delete();
}
// Rotate the files (e.g. error.log.4 becomes error.log.5)
for ($i=8; $i>0; $i--)
{
$strGzName = 'system/logs/' . $strFile . '.' . $i;
if (file_exists($rootDir . '/' . $strGzName))
{
$objFile = new File($strGzName);
$objFile->renameTo('system/logs/' . $strFile . '.' . ($i+1));
}
}
// Add .1 to the latest file
$objFile = new File('system/logs/' . $strFile);
$objFile->renameTo('system/logs/' . $strFile . '.1');
}
} | php | {
"resource": ""
} |
q243326 | TemplateLoader.addFiles | validation | public static function addFiles($files)
{
foreach ($files as $name=>$file)
{
self::addFile($name, $file);
}
} | php | {
"resource": ""
} |
q243327 | TemplateLoader.getPath | validation | public static function getPath($template, $format, $custom='templates')
{
$file = $template . '.' . $format;
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
// Check the theme folder first
if (file_exists($rootDir . '/' . $custom . '/' . $file))
{
return $rootDir . '/' . $custom . '/' . $file;
}
// Then check the global templates directory (see #5547)
if ($custom != 'templates')
{
if (file_exists($rootDir . '/templates/' . $file))
{
return $rootDir . '/templates/' . $file;
}
}
return static::getDefaultPath($template, $format);
} | php | {
"resource": ""
} |
q243328 | TemplateLoader.getDefaultPath | validation | public static function getDefaultPath($template, $format)
{
$file = $template . '.' . $format;
$container = System::getContainer();
$rootDir = $container->getParameter('kernel.project_dir');
if (isset(self::$files[$template]))
{
return $rootDir . '/' . self::$files[$template] . '/' . $file;
}
$strPath = null;
try
{
// Search for the template if it is not in the lookup array (last match wins)
foreach ($container->get('contao.resource_finder')->findIn('templates')->name($file) as $file)
{
/** @var SplFileInfo $file */
$strPath = $file->getPathname();
}
}
catch (\InvalidArgumentException $e) {}
if ($strPath !== null)
{
return $strPath;
}
throw new \Exception('Could not find template "' . $template . '"');
} | php | {
"resource": ""
} |
q243329 | TemplateLoader.initialize | validation | public static function initialize()
{
$objFilesystem = new Filesystem();
$container = System::getContainer();
$strCacheDir = $container->getParameter('kernel.cache_dir');
// Try to load from cache
if (file_exists($strCacheDir . '/contao/config/templates.php'))
{
self::addFiles(include $strCacheDir . '/contao/config/templates.php');
}
else
{
try
{
foreach (System::getContainer()->get('contao.resource_finder')->findIn('templates')->name('*.html5') as $file)
{
/** @var SplFileInfo $file */
self::addFile($file->getBasename('.html5'), rtrim($objFilesystem->makePathRelative($file->getPath(), $container->getParameter('kernel.project_dir')), '/'));
}
}
catch (\InvalidArgumentException $e) {}
}
} | php | {
"resource": ""
} |
q243330 | CommentsModel.findPublishedBySourceAndParent | validation | public static function findPublishedBySourceAndParent($strSource, $intParent, $blnDesc=false, $intLimit=0, $intOffset=0, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.source=? AND $t.parent=?");
if (!static::isPreviewMode($arrOptions))
{
$arrColumns[] = "$t.published='1'";
}
$arrOptions['limit'] = $intLimit;
$arrOptions['offset'] = $intOffset;
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = ($blnDesc ? "$t.date DESC" : "$t.date");
}
return static::findBy($arrColumns, array($strSource, (int) $intParent), $arrOptions);
} | php | {
"resource": ""
} |
q243331 | CommentsModel.countPublishedBySourceAndParent | validation | public static function countPublishedBySourceAndParent($strSource, $intParent, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.source=? AND $t.parent=?");
if (!static::isPreviewMode($arrOptions))
{
$arrColumns[] = "$t.published='1'";
}
return static::countBy($arrColumns, array($strSource, (int) $intParent));
} | php | {
"resource": ""
} |
q243332 | Form.generate | validation | public function generate()
{
if (TL_MODE == 'BE')
{
$objTemplate = new BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['CTE']['form'][0]) . ' ###';
$objTemplate->id = $this->id;
$objTemplate->link = $this->title;
$objTemplate->href = 'contao/main.php?do=form&table=tl_form_field&id=' . $this->id;
return $objTemplate->parse();
}
if ($this->customTpl != '' && TL_MODE == 'FE')
{
$this->strTemplate = $this->customTpl;
}
return parent::generate();
} | php | {
"resource": ""
} |
q243333 | Form.initializeSession | validation | protected function initializeSession($formId)
{
if (Input::post('FORM_SUBMIT') != $formId)
{
return;
}
$arrMessageBox = array('TL_ERROR', 'TL_CONFIRM', 'TL_INFO');
$_SESSION['FORM_DATA'] = \is_array($_SESSION['FORM_DATA']) ? $_SESSION['FORM_DATA'] : array();
foreach ($arrMessageBox as $tl)
{
if (\is_array($_SESSION[$formId][$tl]))
{
$_SESSION[$formId][$tl] = array_unique($_SESSION[$formId][$tl]);
foreach ($_SESSION[$formId][$tl] as $message)
{
$objTemplate = new FrontendTemplate('form_message');
$objTemplate->message = $message;
$objTemplate->class = strtolower($tl);
$this->Template->fields .= $objTemplate->parse() . "\n";
}
$_SESSION[$formId][$tl] = array();
}
}
} | php | {
"resource": ""
} |
q243334 | FormPassword.validator | validation | protected function validator($varInput)
{
$this->blnSubmitInput = false;
if (!\strlen($varInput) && (\strlen($this->varValue) || !$this->mandatory))
{
return '';
}
// Check password length either from DCA or use Config as fallback (#1087)
$intLength = $this->minlength ?: Config::get('minPasswordLength');
if (Utf8::strlen($varInput) < $intLength)
{
$this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['passwordLength'], $intLength));
}
if ($varInput != $this->getPost($this->strName . '_confirm'))
{
$this->addError($GLOBALS['TL_LANG']['ERR']['passwordMatch']);
}
$varInput = parent::validator($varInput);
if (!$this->hasErrors())
{
$this->blnSubmitInput = true;
return password_hash($varInput, PASSWORD_DEFAULT);
}
return '';
} | php | {
"resource": ""
} |
q243335 | ScopeAwareTrait.isScope | validation | private function isScope(string $scope): bool
{
if (
null === $this->container
|| null === ($request = $this->container->get('request_stack')->getCurrentRequest())
) {
return false;
}
$matcher = $this->container->get('contao.routing.scope_matcher');
if (ContaoCoreBundle::SCOPE_BACKEND === $scope) {
return $matcher->isBackendRequest($request);
}
if (ContaoCoreBundle::SCOPE_FRONTEND === $scope) {
return $matcher->isFrontendRequest($request);
}
return false;
} | php | {
"resource": ""
} |
q243336 | Date.createDateRanges | validation | protected function createDateRanges()
{
if (!empty($this->arrRange))
{
return;
}
$intYear = date('Y', $this->strDate);
$intMonth = date('m', $this->strDate);
$intDay = date('d', $this->strDate);
$this->arrRange['day']['begin'] = mktime(0, 0, 0, $intMonth, $intDay, $intYear);
$this->arrRange['day']['end'] = mktime(23, 59, 59, $intMonth, $intDay, $intYear);
$this->arrRange['month']['begin'] = mktime(0, 0, 0, $intMonth, 1, $intYear);
$this->arrRange['month']['end'] = mktime(23, 59, 59, $intMonth, date('t', $this->strDate), $intYear);
$this->arrRange['year']['begin'] = mktime(0, 0, 0, 1, 1, $intYear);
$this->arrRange['year']['end'] = mktime(23, 59, 59, 12, 31, $intYear);
} | php | {
"resource": ""
} |
q243337 | Date.getWeekBegin | validation | public function getWeekBegin($intStartDay=0)
{
$intOffset = date('w', $this->strDate) - $intStartDay;
if ($intOffset < 0)
{
$intOffset += 7;
}
return strtotime('-' . $intOffset . ' days', $this->strDate);
} | php | {
"resource": ""
} |
q243338 | Date.getRegexp | validation | public static function getRegexp($strFormat=null)
{
if ($strFormat === null)
{
$strFormat = static::getNumericDateFormat();
}
if (!static::isNumericFormat($strFormat))
{
throw new \Exception(sprintf('Invalid date format "%s"', $strFormat));
}
return preg_replace_callback('/[a-zA-Z]/', function ($matches)
{
// Thanks to Christian Labuda
$arrRegexp = array
(
'a' => '(?P<a>am|pm)',
'A' => '(?P<A>AM|PM)',
'd' => '(?P<d>0[1-9]|[12][0-9]|3[01])',
'g' => '(?P<g>[1-9]|1[0-2])',
'G' => '(?P<G>[0-9]|1[0-9]|2[0-3])',
'h' => '(?P<h>0[1-9]|1[0-2])',
'H' => '(?P<H>[01][0-9]|2[0-3])',
'i' => '(?P<i>[0-5][0-9])',
'j' => '(?P<j>[1-9]|[12][0-9]|3[01])',
'm' => '(?P<m>0[1-9]|1[0-2])',
'n' => '(?P<n>[1-9]|1[0-2])',
's' => '(?P<s>[0-5][0-9])',
'Y' => '(?P<Y>[0-9]{4})',
'y' => '(?P<y>[0-9]{2})',
);
return $arrRegexp[$matches[0]] ?? $matches[0];
}, preg_quote($strFormat));
} | php | {
"resource": ""
} |
q243339 | Date.formatToJs | validation | public static function formatToJs($strFormat)
{
$chunks = str_split($strFormat);
foreach ($chunks as $k=>$v)
{
switch ($v)
{
case 'D': $chunks[$k] = 'a'; break;
case 'j': $chunks[$k] = 'e'; break;
case 'l': $chunks[$k] = 'A'; break;
case 'S': $chunks[$k] = 'o'; break;
case 'F': $chunks[$k] = 'B'; break;
case 'M': $chunks[$k] = 'b'; break;
case 'a': $chunks[$k] = 'p'; break;
case 'A': $chunks[$k] = 'p'; break;
case 'g': $chunks[$k] = 'l'; break;
case 'G': $chunks[$k] = 'k'; break;
case 'h': $chunks[$k] = 'I'; break;
case 'i': $chunks[$k] = 'M'; break;
case 's': $chunks[$k] = 'S'; break;
case 'U': $chunks[$k] = 's'; break;
}
}
return preg_replace('/([a-zA-Z])/', '%$1', implode('', $chunks));
} | php | {
"resource": ""
} |
q243340 | Date.getNumericDateFormat | validation | public static function getNumericDateFormat()
{
if (TL_MODE == 'FE')
{
/** @var PageModel $objPage */
global $objPage;
if ($objPage->dateFormat != '' && static::isNumericFormat($objPage->dateFormat))
{
return $objPage->dateFormat;
}
}
return Config::get('dateFormat');
} | php | {
"resource": ""
} |
q243341 | Date.getNumericTimeFormat | validation | public static function getNumericTimeFormat()
{
if (TL_MODE == 'FE')
{
/** @var PageModel $objPage */
global $objPage;
if ($objPage->timeFormat != '' && static::isNumericFormat($objPage->timeFormat))
{
return $objPage->timeFormat;
}
}
return Config::get('timeFormat');
} | php | {
"resource": ""
} |
q243342 | Date.getNumericDatimFormat | validation | public static function getNumericDatimFormat()
{
if (TL_MODE == 'FE')
{
/** @var PageModel $objPage */
global $objPage;
if ($objPage->datimFormat != '' && static::isNumericFormat($objPage->datimFormat))
{
return $objPage->datimFormat;
}
}
return Config::get('datimFormat');
} | php | {
"resource": ""
} |
q243343 | Date.resolveCustomModifiers | validation | protected static function resolveCustomModifiers($strDate)
{
if (strpos($strDate, '::') === false)
{
return $strDate;
}
System::loadLanguageFile('default');
if (!$GLOBALS['TL_LANG']['MSC']['dayShortLength'])
{
$GLOBALS['TL_LANG']['MSC']['dayShortLength'] = 3;
}
if (!$GLOBALS['TL_LANG']['MSC']['monthShortLength'])
{
$GLOBALS['TL_LANG']['MSC']['monthShortLength'] = 3;
}
$strReturn = '';
$chunks = preg_split("/([0-9]{1,2}::[1-4])/", $strDate, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($chunks as $chunk)
{
list($index, $flag) = explode('::', $chunk);
switch ($flag)
{
case 1:
$strReturn .= $GLOBALS['TL_LANG']['DAYS'][$index];
break;
case 2:
$strReturn .= $GLOBALS['TL_LANG']['DAYS_SHORT'][$index];
break;
case 3:
$strReturn .= $GLOBALS['TL_LANG']['MONTHS'][($index - 1)];
break;
case 4:
$strReturn .= $GLOBALS['TL_LANG']['MONTHS_SHORT'][($index - 1)];
break;
default:
$strReturn .= $chunk;
break;
}
}
return $strReturn;
} | php | {
"resource": ""
} |
q243344 | InstallTool.hasOldDatabase | validation | public function hasOldDatabase(): bool
{
if (!$this->hasTable('tl_layout')) {
return false;
}
$sql = $this->connection
->getDatabasePlatform()
->getListTableColumnsSQL('tl_layout', $this->connection->getDatabase())
;
$columns = $this->connection->fetchAll($sql);
foreach ($columns as $column) {
if ('sections' === $column['Field']) {
return !\in_array($column['Type'], ['varchar(1022)', 'blob'], true);
}
}
return false;
} | php | {
"resource": ""
} |
q243345 | InstallTool.getTemplates | validation | public function getTemplates(): array
{
/** @var SplFileInfo[] $finder */
$finder = Finder::create()
->files()
->name('*.sql')
->in($this->rootDir.'/templates')
;
$templates = [];
foreach ($finder as $file) {
$templates[] = $file->getRelativePathname();
}
return $templates;
} | php | {
"resource": ""
} |
q243346 | ModuleFaqList.generateFaqLink | validation | protected function generateFaqLink($objFaq)
{
/** @var FaqCategoryModel $objCategory */
$objCategory = $objFaq->getRelated('pid');
$jumpTo = (int) $objCategory->jumpTo;
// A jumpTo page is not mandatory for FAQ categories (see #6226) but required for the FAQ list module
if ($jumpTo < 1)
{
throw new \Exception("FAQ categories without redirect page cannot be used in an FAQ list");
}
// Get the URL from the jumpTo page of the category
if (!isset($this->arrTargets[$jumpTo]))
{
$this->arrTargets[$jumpTo] = ampersand(Environment::get('request'), true);
if ($jumpTo > 0 && ($objTarget = PageModel::findByPk($jumpTo)) !== null)
{
/** @var PageModel $objTarget */
$this->arrTargets[$jumpTo] = ampersand($objTarget->getFrontendUrl(Config::get('useAutoItem') ? '/%s' : '/items/%s'));
}
}
return sprintf(preg_replace('/%(?!s)/', '%%', $this->arrTargets[$jumpTo]), ($objFaq->alias ?: $objFaq->id));
} | php | {
"resource": ""
} |
q243347 | FormModel.getMaxUploadFileSize | validation | public function getMaxUploadFileSize()
{
$objResult = Database::getInstance()->prepare("SELECT MAX(maxlength) AS maxlength FROM tl_form_field WHERE pid=? AND invisible='' AND type='upload' AND maxlength>0")
->execute($this->id);
if ($objResult->numRows > 0 && $objResult->maxlength > 0)
{
return $objResult->maxlength;
}
else
{
return Config::get('maxFileSize');
}
} | php | {
"resource": ""
} |
q243348 | OptInModel.findOneByRelatedTableAndId | validation | public static function findOneByRelatedTableAndId($strTable, $intId, array $arrOptions=array())
{
@trigger_error('Using the Contao\OptInModel::findOneByRelatedTableAndIds() method has been deprecated and will no longer work in Contao 5.0. Use the Contao\OptInModel::findByRelatedTableAndIds() method instead.', E_USER_DEPRECATED);
$t = static::$strTable;
$objDatabase = Database::getInstance();
$objResult = $objDatabase->prepare("SELECT * FROM $t WHERE id IN (SELECT pid FROM tl_opt_in_related WHERE relTable=? AND relId=?)")
->execute($strTable, $intId);
if ($objResult->numRows < 1)
{
return null;
}
$objRegistry = Registry::getInstance();
/** @var OptInModel|Model $objOptIn */
if ($objOptIn = $objRegistry->fetch($t, $objResult->id))
{
return $objOptIn;
}
return new static($objResult);
} | php | {
"resource": ""
} |
q243349 | OptInModel.findByRelatedTableAndIds | validation | public static function findByRelatedTableAndIds($strTable, array $arrIds, array $arrOptions=array())
{
$t = static::$strTable;
$objDatabase = Database::getInstance();
$objResult = $objDatabase->prepare("SELECT * FROM $t WHERE $t.id IN (SELECT pid FROM tl_opt_in_related WHERE relTable=? AND relId IN(" . implode(',', array_map('\intval', $arrIds)) . ")) ORDER BY $t.createdOn DESC")
->execute($strTable, $arrIds);
if ($objResult->numRows < 1)
{
return null;
}
$arrModels = array();
$objRegistry = Registry::getInstance();
while ($objResult->next())
{
/** @var OptInModel|Model $objOptIn */
if ($objOptIn = $objRegistry->fetch($t, $objResult->id))
{
$arrModels[] = $objOptIn;
}
else
{
$arrModels[] = new static($objResult->row());
}
}
return static::createCollection($arrModels, $t);
} | php | {
"resource": ""
} |
q243350 | OptInModel.getRelatedRecords | validation | public function getRelatedRecords()
{
$arrRelated = array();
$objDatabase = Database::getInstance();
$objRelated = $objDatabase->prepare("SELECT * FROM tl_opt_in_related WHERE pid=?")
->execute($this->id);
while ($objRelated->next())
{
$arrRelated[$objRelated->relTable][] = $objRelated->relId;
}
return $arrRelated;
} | php | {
"resource": ""
} |
q243351 | OptInModel.setRelatedRecords | validation | public function setRelatedRecords(array $arrRelated)
{
$objDatabase = Database::getInstance();
$objCount = $objDatabase->prepare("SELECT COUNT(*) AS count FROM tl_opt_in_related WHERE pid=?")
->execute($this->id);
if ($objCount->count > 0)
{
throw new \LogicException(sprintf('Token "%s" already contains related records', $this->token));
}
foreach ($arrRelated as $strTable=>$arrIds)
{
foreach ($arrIds as $intId)
{
$objDatabase->prepare("INSERT INTO tl_opt_in_related (pid, relTable, relId) VALUES (?, ?, ?)")
->execute($this->id, $strTable, $intId);
}
}
} | php | {
"resource": ""
} |
q243352 | UserPasswordCommand.askForPassword | validation | private function askForPassword(string $label, InputInterface $input, OutputInterface $output): string
{
$question = new Question($label);
$question->setHidden(true);
$question->setMaxAttempts(3);
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
return $helper->ask($input, $output, $question);
} | php | {
"resource": ""
} |
q243353 | PageError404.generate | validation | public function generate()
{
/** @var PageModel $objPage */
global $objPage;
$obj404 = $this->prepare();
$objPage = $obj404->loadDetails();
/** @var PageRegular $objHandler */
$objHandler = new $GLOBALS['TL_PTY']['regular']();
header('HTTP/1.1 404 Not Found');
$objHandler->generate($objPage);
} | php | {
"resource": ""
} |
q243354 | ModuleArticlenav.generate | validation | public function generate()
{
if (TL_MODE == 'BE')
{
$objTemplate = new BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['FMD']['articlenav'][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();
}
/** @var PageModel $objPage */
global $objPage;
$this->objArticles = ArticleModel::findPublishedWithTeaserByPidAndColumn($objPage->id, $this->strColumn);
// Return if there are no articles
if ($this->objArticles === null)
{
return '';
}
// Redirect to the first article if no article is selected
if (!Input::get('articles'))
{
if (!$this->loadFirst)
{
return '';
}
/** @var ArticleModel $objArticle */
$objArticle = $this->objArticles->current();
$strAlias = $objArticle->alias ?: $objArticle->id;
$this->redirect($objPage->getFrontendUrl('/articles/' . $strAlias));
}
return parent::generate();
} | php | {
"resource": ""
} |
q243355 | BackendMenuListener.onBuild | validation | public function onBuild(MenuEvent $event): void
{
$token = $this->tokenStorage->getToken();
if (null === $token) {
return;
}
$user = $token->getUser();
if (!$user instanceof BackendUser) {
return;
}
$factory = $event->getFactory();
$tree = $event->getTree();
$modules = $user->navigation();
foreach ($modules as $categoryName => $categoryData) {
$categoryNode = $tree->getChild($categoryName);
if (!$categoryNode) {
$categoryNode = $this->createNode($factory, $categoryName, $categoryData);
if (isset($categoryData['class']) && preg_match('/\bnode-collapsed\b/', $categoryData['class'])) {
$categoryNode->setDisplayChildren(false);
}
$tree->addChild($categoryNode);
}
// Create the child nodes
foreach ($categoryData['modules'] as $moduleName => $moduleData) {
$moduleNode = $this->createNode($factory, $moduleName, $moduleData);
$moduleNode->setCurrent((bool) $moduleData['isActive']);
$categoryNode->addChild($moduleNode);
}
}
} | php | {
"resource": ""
} |
q243356 | ContaoContext.getFieldValue | validation | private function getFieldValue(?PageModel $page): string
{
if (null === $page) {
return '';
}
return (string) $page->{$this->field};
} | php | {
"resource": ""
} |
q243357 | tl_user_group.addTemplateWarning | validation | public function addTemplateWarning()
{
if (Contao\Input::get('act') && Contao\Input::get('act') != 'select')
{
return;
}
$objResult = $this->Database->query("SELECT COUNT(*) AS cnt FROM tl_user_group WHERE modules LIKE '%\"tpl_editor\"%'");
if ($objResult->cnt > 0)
{
Contao\Message::addInfo($GLOBALS['TL_LANG']['MSC']['groupTemplateEditor']);
}
} | php | {
"resource": ""
} |
q243358 | tl_user_group.getExcludedFields | validation | public function getExcludedFields()
{
$processed = array();
/** @var SplFileInfo[] $files */
$files = Contao\System::getContainer()->get('contao.resource_finder')->findIn('dca')->depth(0)->files()->name('*.php');
foreach ($files as $file)
{
if (\in_array($file->getBasename(), $processed))
{
continue;
}
$processed[] = $file->getBasename();
$strTable = $file->getBasename('.php');
Contao\System::loadLanguageFile($strTable);
$this->loadDataContainer($strTable);
}
$arrReturn = array();
// Get all excluded fields
foreach ($GLOBALS['TL_DCA'] as $k=>$v)
{
if (\is_array($v['fields']))
{
foreach ($v['fields'] as $kk=>$vv)
{
// Hide the "admin" field if the user is not an admin (see #184)
if ($k == 'tl_user' && $kk == 'admin' && !$this->User->isAdmin)
{
continue;
}
if ($vv['exclude'] || $vv['orig_exclude'])
{
$arrReturn[$k][Contao\StringUtil::specialchars($k.'::'.$kk)] = isset($vv['label'][0]) ? $vv['label'][0] . ' <span style="color:#999;padding-left:3px">[' . $kk . ']</span>' : $kk;
}
}
}
}
ksort($arrReturn);
return $arrReturn;
} | php | {
"resource": ""
} |
q243359 | Installer.generateSqlForm | validation | public function generateSqlForm()
{
@trigger_error('Using the Installer::generateSqlForm() method has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
$count = 0;
$return = '';
$sql_command = $this->compileCommands();
if (empty($sql_command))
{
return '';
}
$_SESSION['sql_commands'] = array();
$arrOperations = array
(
'CREATE' => $GLOBALS['TL_LANG']['tl_install']['CREATE'],
'ALTER_ADD' => $GLOBALS['TL_LANG']['tl_install']['ALTER_ADD'],
'ALTER_CHANGE' => $GLOBALS['TL_LANG']['tl_install']['ALTER_CHANGE'],
'ALTER_DROP' => $GLOBALS['TL_LANG']['tl_install']['ALTER_DROP'],
'DROP' => $GLOBALS['TL_LANG']['tl_install']['DROP']
);
foreach ($arrOperations as $command=>$label)
{
if (\is_array($sql_command[$command]))
{
// Headline
$return .= '
<tr>
<td colspan="2" class="tl_col_0">'.$label.'</td>
</tr>';
// Check all
$return .= '
<tr>
<td class="tl_col_1"><input type="checkbox" id="check_all_' . $count . '" class="tl_checkbox" onclick="Backend.toggleCheckboxElements(this, \'' . strtolower($command) . '\')"></td>
<td class="tl_col_2"><label for="check_all_' . $count . '" style="color:#a6a6a6"><em>' . $GLOBALS['TL_LANG']['MSC']['selectAll'] . '</em></label></td>
</tr>';
// Fields
foreach ($sql_command[$command] as $vv)
{
$key = md5($vv);
$_SESSION['sql_commands'][$key] = $vv;
$return .= '
<tr>
<td class="tl_col_1"><input type="checkbox" name="sql[]" id="sql_'.$count.'" class="tl_checkbox ' . strtolower($command) . '" value="'.$key.'"'.((stripos($command, 'DROP') === false) ? ' checked="checked"' : '').'></td>
<td class="tl_col_2"><pre><label for="sql_'.$count++.'">'.$vv.'</label></pre></td>
</tr>';
}
}
}
return '
<div id="sql_wrapper">
<table id="sql_table">'.$return.'
</table>
</div>';
} | php | {
"resource": ""
} |
q243360 | Installer.getFromDca | validation | public function getFromDca()
{
$return = array();
$processed = array();
/** @var SplFileInfo[] $files */
$files = System::getContainer()->get('contao.resource_finder')->findIn('dca')->depth(0)->files()->name('*.php');
foreach ($files as $file)
{
if (\in_array($file->getBasename(), $processed))
{
continue;
}
$processed[] = $file->getBasename();
$strTable = $file->getBasename('.php');
$objExtract = DcaExtractor::getInstance($strTable);
if ($objExtract->isDbTable())
{
$return[$strTable] = $objExtract->getDbInstallerArray();
}
}
ksort($return);
// HOOK: allow third-party developers to modify the array (see #6425)
if (isset($GLOBALS['TL_HOOKS']['sqlGetFromDca']) && \is_array($GLOBALS['TL_HOOKS']['sqlGetFromDca']))
{
foreach ($GLOBALS['TL_HOOKS']['sqlGetFromDca'] as $callback)
{
$this->import($callback[0]);
$return = $this->{$callback[0]}->{$callback[1]}($return);
}
}
return $return;
} | php | {
"resource": ""
} |
q243361 | Installer.getFromFile | validation | public function getFromFile()
{
$return = array();
/** @var SplFileInfo[] $files */
$files = System::getContainer()->get('contao.resource_finder')->findIn('config')->depth(0)->files()->name('database.sql');
foreach ($files as $file)
{
$return = array_replace_recursive($return, SqlFileParser::parse($file));
}
ksort($return);
// HOOK: allow third-party developers to modify the array (see #3281)
if (isset($GLOBALS['TL_HOOKS']['sqlGetFromFile']) && \is_array($GLOBALS['TL_HOOKS']['sqlGetFromFile']))
{
foreach ($GLOBALS['TL_HOOKS']['sqlGetFromFile'] as $callback)
{
$this->import($callback[0]);
$return = $this->{$callback[0]}->{$callback[1]}($return);
}
}
return $return;
} | php | {
"resource": ""
} |
q243362 | ModuleLoader.getActive | validation | public static function getActive()
{
@trigger_error('Using ModuleLoader::getActive() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
$bundles = array_keys(System::getContainer()->getParameter('kernel.bundles'));
foreach (static::$legacy as $bundleName => $module)
{
if (\in_array($bundleName, $bundles))
{
$bundles[] = $module;
}
}
return $bundles;
} | php | {
"resource": ""
} |
q243363 | Combiner.add | validation | public function add($strFile, $strVersion=null, $strMedia='all')
{
$strType = strrchr($strFile, '.');
// Check the file type
if ($strType != self::CSS && $strType != self::JS && $strType != self::SCSS && $strType != self::LESS)
{
throw new \InvalidArgumentException("Invalid file $strFile");
}
$strMode = ($strType == self::JS) ? self::JS : self::CSS;
// Set the operation mode
if ($this->strMode === null)
{
$this->strMode = $strMode;
}
elseif ($this->strMode != $strMode)
{
throw new \LogicException('You cannot mix different file types. Create another Combiner object instead.');
}
// Check the source file
if (!file_exists($this->strRootDir . '/' . $strFile))
{
// Handle public bundle resources in web/
if (file_exists($this->strRootDir . '/' . $this->strWebDir . '/' . $strFile))
{
$strFile = $this->strWebDir . '/' . $strFile;
}
else
{
return;
}
}
// Prevent duplicates
if (isset($this->arrFiles[$strFile]))
{
return;
}
// Default version
if ($strVersion === null)
{
$strVersion = filemtime($this->strRootDir . '/' . $strFile);
}
// Store the file
$arrFile = array
(
'name' => $strFile,
'version' => $strVersion,
'media' => $strMedia,
'extension' => $strType
);
$this->arrFiles[$strFile] = $arrFile;
$this->strKey .= '-f' . $strFile . '-v' . $strVersion . '-m' . $strMedia;
} | php | {
"resource": ""
} |
q243364 | Combiner.addMultiple | validation | public function addMultiple(array $arrFiles, $strVersion=null, $strMedia='screen')
{
foreach ($arrFiles as $strFile)
{
$this->add($strFile, $strVersion, $strMedia);
}
} | php | {
"resource": ""
} |
q243365 | Combiner.getFileUrls | validation | public function getFileUrls()
{
$return = array();
$strTarget = substr($this->strMode, 1);
foreach ($this->arrFiles as $arrFile)
{
// Compile SCSS/LESS files into temporary files
if ($arrFile['extension'] == self::SCSS || $arrFile['extension'] == self::LESS)
{
$strPath = 'assets/' . $strTarget . '/' . str_replace('/', '_', $arrFile['name']) . $this->strMode;
if (Config::get('debugMode') || !file_exists($this->strRootDir . '/' . $strPath))
{
$objFile = new File($strPath);
$objFile->write($this->handleScssLess(file_get_contents($this->strRootDir . '/' . $arrFile['name']), $arrFile));
$objFile->close();
}
$return[] = $strPath . '|' . $arrFile['version'];
}
else
{
$name = $arrFile['name'];
// Strip the web/ prefix (see #328)
if (strncmp($name, $this->strWebDir . '/', \strlen($this->strWebDir) + 1) === 0)
{
$name = substr($name, \strlen($this->strWebDir) + 1);
}
// Add the media query (see #7070)
if ($this->strMode == self::CSS && $arrFile['media'] != '' && $arrFile['media'] != 'all' && !$this->hasMediaTag($arrFile['name']))
{
$name .= '|' . $arrFile['media'];
}
$return[] = $name . '|' . $arrFile['version'];
}
}
return $return;
} | php | {
"resource": ""
} |
q243366 | Combiner.getDebugMarkup | validation | protected function getDebugMarkup()
{
$return = $this->getFileUrls();
foreach ($return as $k=>$v)
{
$options = StringUtil::resolveFlaggedUrl($v);
$return[$k] = $v;
if ($options->mtime)
{
$return[$k] .= '?v=' . substr(md5($options->mtime), 0, 8);
}
if ($options->media)
{
$return[$k] .= '" media="' . $options->media;
}
}
if ($this->strMode == self::JS)
{
return implode('"></script><script src="', $return);
}
return implode('"><link rel="stylesheet" href="', $return);
} | php | {
"resource": ""
} |
q243367 | Combiner.handleCss | validation | protected function handleCss($content, $arrFile)
{
$content = $this->fixPaths($content, $arrFile);
// Add the media type if there is no @media command in the code
if ($arrFile['media'] != '' && $arrFile['media'] != 'all' && strpos($content, '@media') === false)
{
$content = '@media ' . $arrFile['media'] . "{\n" . $content . "\n}";
}
return $content;
} | php | {
"resource": ""
} |
q243368 | Combiner.fixPaths | validation | protected function fixPaths($content, $arrFile)
{
$strName = $arrFile['name'];
// Strip the web/ prefix
if (strpos($strName, $this->strWebDir .'/') === 0)
{
$strName = substr($strName, \strlen($this->strWebDir) + 1);
}
$strDirname = \dirname($strName);
$strGlue = ($strDirname != '.') ? $strDirname . '/' : '';
return preg_replace_callback(
'/url\(("[^"\n]+"|\'[^\'\n]+\'|[^"\'\s()]+)\)/',
function ($matches) use ($strDirname, $strGlue)
{
$strData = $matches[1];
if ($strData[0] == '"' || $strData[0] == "'")
{
$strData = substr($strData, 1, -1);
}
// Skip absolute links and embedded images (see #5082)
if (strncmp($strData, 'data:', 5) === 0 || strncmp($strData, 'http://', 7) === 0 || strncmp($strData, 'https://', 8) === 0 || strncmp($strData, '/', 1) === 0 || strncmp($strData, 'assets/css3pie/', 15) === 0)
{
return $matches[0];
}
// Make the paths relative to the root (see #4161)
if (strncmp($strData, '../', 3) !== 0)
{
$strData = '../../' . $strGlue . $strData;
}
else
{
$dir = $strDirname;
// Remove relative paths
while (strncmp($strData, '../', 3) === 0)
{
$dir = \dirname($dir);
$strData = substr($strData, 3);
}
$glue = ($dir != '.') ? $dir . '/' : '';
$strData = '../../' . $glue . $strData;
}
$strQuote = '';
if ($matches[1][0] == "'" || $matches[1][0] == '"')
{
$strQuote = $matches[1][0];
}
if (preg_match('/[(),\s"\']/', $strData))
{
if ($matches[1][0] == "'")
{
$strData = str_replace("'", "\\'", $strData);
}
else
{
$strQuote = '"';
$strData = str_replace('"', '\"', $strData);
}
}
return 'url(' . $strQuote . $strData . $strQuote . ')';
},
$content
);
} | php | {
"resource": ""
} |
q243369 | TemplateInheritance.endblock | validation | public function endblock()
{
// Check for open blocks
if (empty($this->arrBlockNames))
{
throw new \Exception('You must start a block before you can end it');
}
// Get the block name
$name = array_pop($this->arrBlockNames);
// Root template
if ($this->strParent === null)
{
// Handle nested blocks
if ($this->arrBlocks[$name] != '[[TL_PARENT]]')
{
// Output everything after the first TL_PARENT tag
if (strpos($this->arrBlocks[$name], '[[TL_PARENT]]') !== false)
{
list(, $content) = explode('[[TL_PARENT]]', $this->arrBlocks[$name], 2);
echo $content;
}
// Remove the overwritten content
else
{
ob_end_clean();
--$this->intBufferLevel;
}
}
}
// Child template
else
{
// Capture the block content
$this->arrBlocks[$name][] = ob_get_clean();
// Start a new output buffer
ob_start();
}
} | php | {
"resource": ""
} |
q243370 | Config.initialize | validation | protected function initialize()
{
if (static::$blnHasLcf === null)
{
static::preload();
}
$strCacheDir = System::getContainer()->getParameter('kernel.cache_dir');
if (file_exists($strCacheDir . '/contao/config/config.php'))
{
include $strCacheDir . '/contao/config/config.php';
}
else
{
try
{
$files = System::getContainer()->get('contao.resource_locator')->locate('config/config.php', null, false);
}
catch (\InvalidArgumentException $e)
{
$files = array();
}
foreach ($files as $file)
{
include $file;
}
}
// Include the local configuration file again
if (static::$blnHasLcf)
{
include $this->strRootDir . '/system/config/localconfig.php';
}
static::loadParameters();
} | php | {
"resource": ""
} |
q243371 | Config.markModified | validation | protected function markModified()
{
// Return if marked as modified already
if ($this->blnIsModified === true)
{
return;
}
$this->blnIsModified = true;
// Reset the top and bottom content (see #344)
$this->strTop = '';
$this->strBottom = '';
// Import the Files object (required in the destructor)
$this->Files = Files::getInstance();
// Parse the local configuration file
if (static::$blnHasLcf)
{
$strMode = 'top';
$resFile = fopen($this->strRootDir . '/system/config/localconfig.php', 'rb');
while (!feof($resFile))
{
$strLine = fgets($resFile);
$strTrim = trim($strLine);
if ($strTrim == '?>')
{
continue;
}
if ($strTrim == '### INSTALL SCRIPT START ###')
{
$strMode = 'data';
continue;
}
if ($strTrim == '### INSTALL SCRIPT STOP ###')
{
$strMode = 'bottom';
continue;
}
if ($strMode == 'top')
{
$this->strTop .= $strLine;
}
elseif ($strMode == 'bottom')
{
$this->strBottom .= $strLine;
}
elseif ($strTrim != '')
{
$arrChunks = array_map('trim', explode('=', $strLine, 2));
$this->arrData[$arrChunks[0]] = $arrChunks[1];
}
}
fclose($resFile);
}
} | php | {
"resource": ""
} |
q243372 | Config.save | validation | public function save()
{
if ($this->strTop == '')
{
$this->strTop = '<?php';
}
$strFile = trim($this->strTop) . "\n\n";
$strFile .= "### INSTALL SCRIPT START ###\n";
foreach ($this->arrData as $k=>$v)
{
$strFile .= "$k = $v\n";
}
$strFile .= "### INSTALL SCRIPT STOP ###\n";
$this->strBottom = trim($this->strBottom);
if ($this->strBottom != '')
{
$strFile .= "\n" . $this->strBottom . "\n";
}
$strTemp = md5(uniqid(mt_rand(), true));
// Write to a temp file first
$objFile = fopen($this->strRootDir . '/system/tmp/' . $strTemp, 'wb');
fwrite($objFile, $strFile);
fclose($objFile);
// Make sure the file has been written (see #4483)
if (!filesize($this->strRootDir . '/system/tmp/' . $strTemp))
{
System::log('The local configuration file could not be written. Have your reached your quota limit?', __METHOD__, TL_ERROR);
return;
}
// Adjust the file permissions (see #8178)
$this->Files->chmod('system/tmp/' . $strTemp, 0666 & ~umask());
// Then move the file to its final destination
$this->Files->rename('system/tmp/' . $strTemp, 'system/config/localconfig.php');
// Reset the Zend OPcache
if (\function_exists('opcache_invalidate'))
{
opcache_invalidate($this->strRootDir . '/system/config/localconfig.php', true);
}
// Recompile the APC file (thanks to Trenker)
if (\function_exists('apc_compile_file') && !ini_get('apc.stat'))
{
apc_compile_file($this->strRootDir . '/system/config/localconfig.php');
}
$this->blnIsModified = false;
} | php | {
"resource": ""
} |
q243373 | Config.add | validation | public function add($strKey, $varValue)
{
$this->markModified();
$this->arrData[$strKey] = $this->escape($varValue) . ';';
} | php | {
"resource": ""
} |
q243374 | Config.persist | validation | public static function persist($strKey, $varValue)
{
$objConfig = static::getInstance();
if (strncmp($strKey, '$GLOBALS', 8) !== 0)
{
$strKey = "\$GLOBALS['TL_CONFIG']['$strKey']";
}
$objConfig->add($strKey, $varValue);
} | php | {
"resource": ""
} |
q243375 | Config.remove | validation | public static function remove($strKey)
{
$objConfig = static::getInstance();
if (strncmp($strKey, '$GLOBALS', 8) !== 0)
{
$strKey = "\$GLOBALS['TL_CONFIG']['$strKey']";
}
$objConfig->delete($strKey);
} | php | {
"resource": ""
} |
q243376 | Config.preload | validation | public static function preload()
{
// Load the default files
include __DIR__ . '/../../config/default.php';
include __DIR__ . '/../../config/agents.php';
include __DIR__ . '/../../config/mimetypes.php';
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
// Include the local configuration file
if (($blnHasLcf = file_exists($rootDir . '/system/config/localconfig.php')) === true)
{
include $rootDir . '/system/config/localconfig.php';
}
static::loadParameters();
static::$blnHasLcf = $blnHasLcf;
} | php | {
"resource": ""
} |
q243377 | Config.loadParameters | validation | protected static function loadParameters()
{
$container = System::getContainer();
if ($container === null)
{
return;
}
if ($container->hasParameter('contao.localconfig') && \is_array($params = $container->getParameter('contao.localconfig')))
{
foreach ($params as $key=>$value)
{
$GLOBALS['TL_CONFIG'][$key] = $value;
}
}
$arrMap = array
(
'dbHost' => 'database_host',
'dbPort' => 'database_port',
'dbUser' => 'database_user',
'dbPass' => 'database_password',
'dbDatabase' => 'database_name',
'smtpHost' => 'mailer_host',
'smtpUser' => 'mailer_user',
'smtpPass' => 'mailer_password',
'smtpPort' => 'mailer_port',
'smtpEnc' => 'mailer_encryption',
'addLanguageToUrl' => 'contao.prepend_locale',
'encryptionKey' => 'contao.encryption_key',
'urlSuffix' => 'contao.url_suffix',
'uploadPath' => 'contao.upload_path',
'debugMode' => 'kernel.debug',
);
foreach ($arrMap as $strKey=>$strParam)
{
if ($container->hasParameter($strParam))
{
$GLOBALS['TL_CONFIG'][$strKey] = $container->getParameter($strParam);
}
}
if ($container->hasParameter('contao.image.valid_extensions'))
{
$GLOBALS['TL_CONFIG']['validImageTypes'] = implode(',', $container->getParameter('contao.image.valid_extensions'));
}
if ($container->hasParameter('contao.image.imagine_options'))
{
$GLOBALS['TL_CONFIG']['jpgQuality'] = $container->getParameter('contao.image.imagine_options')['jpeg_quality'];
}
} | php | {
"resource": ""
} |
q243378 | Config.escape | validation | protected function escape($varValue)
{
if (is_numeric($varValue) && !preg_match('/e|^[+-]?0[^.]/', $varValue) && $varValue < PHP_INT_MAX)
{
return $varValue;
}
if (\is_bool($varValue))
{
return $varValue ? 'true' : 'false';
}
if ($varValue == 'true')
{
return 'true';
}
if ($varValue == 'false')
{
return 'false';
}
return "'" . str_replace('\\"', '"', preg_replace('/[\n\r\t ]+/', ' ', addslashes($varValue))) . "'";
} | php | {
"resource": ""
} |
q243379 | InsecureInstallationListener.onKernelRequest | validation | public function onKernelRequest(GetResponseEvent $event): void
{
$request = $event->getRequest();
// Skip the check on localhost
if (\in_array($request->getClientIp(), ['127.0.0.1', 'fe80::1', '::1'], true)) {
return;
}
// The document root is not in a subdirectory
if ('' === $request->getBasePath()) {
return;
}
throw new InsecureInstallationException(
'Your installation is not secure. Please set the document root to the /web subfolder.'
);
} | php | {
"resource": ""
} |
q243380 | MergeHttpHeadersListener.onKernelResponse | validation | public function onKernelResponse(FilterResponseEvent $event): void
{
if (!$this->framework->isInitialized()) {
return;
}
// Fetch remaining headers and add them to the response
$this->fetchHttpHeaders();
$this->setResponseHeaders($event->getResponse());
} | php | {
"resource": ""
} |
q243381 | MergeHttpHeadersListener.fetchHttpHeaders | validation | private function fetchHttpHeaders(): void
{
$this->headers = array_merge($this->headers, $this->headerStorage->all());
$this->headerStorage->clear();
} | php | {
"resource": ""
} |
q243382 | UserSessionListener.onKernelResponse | validation | public function onKernelResponse(FilterResponseEvent $event): void
{
if (!$this->scopeMatcher->isContaoMasterRequest($event)) {
return;
}
$token = $this->tokenStorage->getToken();
if (null === $token || $this->authenticationTrustResolver->isAnonymous($token)) {
return;
}
$user = $token->getUser();
if (!$user instanceof User) {
return;
}
/** @var AttributeBagInterface $sessionBag */
$sessionBag = $this->getSessionBag($event->getRequest());
$data = $sessionBag->all();
$this->connection->update($user->getTable(), ['session' => serialize($data)], ['id' => $user->id]);
} | php | {
"resource": ""
} |
q243383 | UserSessionListener.getSessionBag | validation | private function getSessionBag(Request $request): SessionBagInterface
{
if (!$request->hasSession() || null === ($session = $request->getSession())) {
throw new \RuntimeException('The request did not contain a session.');
}
$name = 'contao_frontend';
if ($this->scopeMatcher->isBackendRequest($request)) {
$name = 'contao_backend';
}
return $session->getBag($name);
} | php | {
"resource": ""
} |
q243384 | PageError403.generate | validation | public function generate($objRootPage=null)
{
/** @var PageModel $objPage */
global $objPage;
$obj403 = $this->prepare($objRootPage);
$objPage = $obj403->loadDetails();
/** @var PageRegular $objHandler */
$objHandler = new $GLOBALS['TL_PTY']['regular']();
header('HTTP/1.1 403 Forbidden');
$objHandler->generate($objPage);
} | php | {
"resource": ""
} |
q243385 | AuthenticationProvider.onBadCredentials | validation | public function onBadCredentials(User $user, AuthenticationException $exception): AuthenticationException
{
--$user->loginCount;
if ($user->loginCount > 0) {
$user->save();
return new BadCredentialsException(
sprintf('Invalid password submitted for username "%s"', $user->username),
$exception->getCode(),
$exception
);
}
$user->locked = time() + $this->options['lock_period'];
$user->loginCount = $this->options['login_attempts'];
$user->save();
$lockedSeconds = $user->locked - time();
$lockedMinutes = (int) ceil($lockedSeconds / 60);
$exception = new LockedException(
$lockedSeconds,
sprintf('User "%s" has been locked for %s minutes', $user->username, $lockedMinutes),
0,
$exception
);
$exception->setUser($user);
return $exception;
} | php | {
"resource": ""
} |
q243386 | InsertTags.replace | validation | public function replace($strBuffer, $blnCache=true)
{
$strBuffer = $this->doReplace($strBuffer, $blnCache);
// Run the replacement recursively (see #8172)
while (strpos($strBuffer, '{{') !== false && ($strTmp = $this->doReplace($strBuffer, $blnCache)) != $strBuffer)
{
$strBuffer = $strTmp;
}
return $strBuffer;
} | php | {
"resource": ""
} |
q243387 | Newsletter.generateEmailObject | validation | protected function generateEmailObject(Result $objNewsletter, $arrAttachments)
{
$objEmail = new Email();
$objEmail->from = $objNewsletter->sender;
$objEmail->subject = $objNewsletter->subject;
// Add sender name
if ($objNewsletter->senderName != '')
{
$objEmail->fromName = $objNewsletter->senderName;
}
$objEmail->embedImages = !$objNewsletter->externalImages;
$objEmail->logFile = TL_NEWSLETTER . '_' . $objNewsletter->id;
// Attachments
if (!empty($arrAttachments) && \is_array($arrAttachments))
{
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
foreach ($arrAttachments as $strAttachment)
{
$objEmail->attachFile($rootDir . '/' . $strAttachment);
}
}
return $objEmail;
} | php | {
"resource": ""
} |
q243388 | Newsletter.sendNewsletter | validation | protected function sendNewsletter(Email $objEmail, Result $objNewsletter, $arrRecipient, $text, $html, $css=null)
{
// Prepare the text content
$objEmail->text = StringUtil::parseSimpleTokens($text, $arrRecipient);
if (!$objNewsletter->sendText)
{
// Default template
if ($objNewsletter->template == '')
{
$objNewsletter->template = 'mail_default';
}
$objTemplate = new BackendTemplate($objNewsletter->template);
$objTemplate->setData($objNewsletter->row());
$objTemplate->title = $objNewsletter->subject;
$objTemplate->body = StringUtil::parseSimpleTokens($html, $arrRecipient);
$objTemplate->charset = Config::get('characterSet');
$objTemplate->recipient = $arrRecipient['email'];
// Deprecated since Contao 4.0, to be removed in Contao 5.0
$objTemplate->css = $css;
// Parse template
$objEmail->html = $objTemplate->parse();
$objEmail->imageDir = System::getContainer()->getParameter('kernel.project_dir') . '/';
}
// Deactivate invalid addresses
try
{
$objEmail->sendTo($arrRecipient['email']);
}
catch (\Swift_RfcComplianceException $e)
{
$_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
}
// Rejected recipients
if ($objEmail->hasFailures())
{
$_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
}
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['sendNewsletter']) && \is_array($GLOBALS['TL_HOOKS']['sendNewsletter']))
{
foreach ($GLOBALS['TL_HOOKS']['sendNewsletter'] as $callback)
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($objEmail, $objNewsletter, $arrRecipient, $text, $html);
}
}
} | php | {
"resource": ""
} |
q243389 | Newsletter.removeSubscriptions | validation | public function removeSubscriptions($intUser, $strMode)
{
if (!$intUser)
{
return;
}
// Delete or deactivate
if ($strMode == 'close_delete')
{
$this->Database->prepare("DELETE FROM tl_newsletter_recipients WHERE email=(SELECT email FROM tl_member WHERE id=?)")
->execute($intUser);
}
else
{
$this->Database->prepare("UPDATE tl_newsletter_recipients SET active='' WHERE email=(SELECT email FROM tl_member WHERE id=?)")
->execute($intUser);
}
} | php | {
"resource": ""
} |
q243390 | Newsletter.createNewUser | validation | public function createNewUser($intUser, $arrData)
{
$arrNewsletters = StringUtil::deserialize($arrData['newsletter'], true);
// Return if there are no newsletters
if (!\is_array($arrNewsletters))
{
return;
}
$time = time();
// Add recipients
foreach ($arrNewsletters as $intNewsletter)
{
$intNewsletter = (int) $intNewsletter;
if ($intNewsletter < 1)
{
continue;
}
$objRecipient = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_newsletter_recipients WHERE pid=? AND email=?")
->execute($intNewsletter, $arrData['email']);
if ($objRecipient->count < 1)
{
$this->Database->prepare("INSERT INTO tl_newsletter_recipients SET pid=?, tstamp=$time, email=?, addedOn=$time")
->execute($intNewsletter, $arrData['email']);
}
}
} | php | {
"resource": ""
} |
q243391 | Newsletter.activateAccount | validation | public function activateAccount($objUser)
{
$arrNewsletters = StringUtil::deserialize($objUser->newsletter, true);
// Return if there are no newsletters
if (!\is_array($arrNewsletters))
{
return;
}
// Activate e-mail addresses
foreach ($arrNewsletters as $intNewsletter)
{
$intNewsletter = (int) $intNewsletter;
if ($intNewsletter < 1)
{
continue;
}
$this->Database->prepare("UPDATE tl_newsletter_recipients SET active='1' WHERE pid=? AND email=?")
->execute($intNewsletter, $objUser->email);
}
} | php | {
"resource": ""
} |
q243392 | Newsletter.onToggleVisibility | validation | public function onToggleVisibility($blnDisabled, DataContainer $dc)
{
if (!$dc->id)
{
return $blnDisabled;
}
$objUser = $this->Database->prepare("SELECT email FROM tl_member WHERE id=?")
->limit(1)
->execute($dc->id);
if ($objUser->numRows)
{
$this->Database->prepare("UPDATE tl_newsletter_recipients SET tstamp=?, active=? WHERE email=?")
->execute(time(), ($blnDisabled ? '' : '1'), $objUser->email);
}
return $blnDisabled;
} | php | {
"resource": ""
} |
q243393 | Newsletter.synchronize | validation | public function synchronize($varValue, $objUser, $objModule=null)
{
// Return if there is no user (e.g. upon registration)
if ($objUser === null)
{
return $varValue;
}
$blnIsFrontend = true;
// If called from the back end, the second argument is a DataContainer object
if ($objUser instanceof DataContainer)
{
$objUser = $this->Database->prepare("SELECT * FROM tl_member WHERE id=?")
->limit(1)
->execute($objUser->id);
if ($objUser->numRows < 1)
{
return $varValue;
}
$blnIsFrontend = false;
}
// Nothing has changed or e-mail address is empty
if ($varValue == $objUser->newsletter || $objUser->email == '')
{
return $varValue;
}
$time = time();
$varValue = StringUtil::deserialize($varValue, true);
// Get all channel IDs (thanks to Andreas Schempp)
if ($blnIsFrontend && $objModule instanceof Module)
{
$arrChannel = StringUtil::deserialize($objModule->newsletters, true);
}
else
{
$arrChannel = $this->Database->query("SELECT id FROM tl_newsletter_channel")->fetchEach('id');
}
$arrDelete = array_values(array_diff($arrChannel, $varValue));
// Delete existing recipients
if (!empty($arrDelete) && \is_array($arrDelete))
{
$this->Database->prepare("DELETE FROM tl_newsletter_recipients WHERE pid IN(" . implode(',', array_map('\intval', $arrDelete)) . ") AND email=?")
->execute($objUser->email);
}
// Add recipients
foreach ($varValue as $intId)
{
$intId = (int) $intId;
if ($intId < 1)
{
continue;
}
$objRecipient = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_newsletter_recipients WHERE pid=? AND email=?")
->execute($intId, $objUser->email);
if ($objRecipient->count < 1)
{
$this->Database->prepare("INSERT INTO tl_newsletter_recipients SET pid=?, tstamp=$time, email=?, active=?, addedOn=?")
->execute($intId, $objUser->email, ($objUser->disable ? '' : 1), ($blnIsFrontend ? $time : ''));
}
}
return serialize($varValue);
} | php | {
"resource": ""
} |
q243394 | Newsletter.updateAccount | validation | public function updateAccount()
{
$intUser = Input::get('id');
// Front end call
if (TL_MODE == 'FE')
{
$this->import(FrontendUser::class, 'User');
$intUser = $this->User->id;
}
// Return if there is no user (e.g. upon registration)
if (!$intUser)
{
return;
}
// Edit account
if (TL_MODE == 'FE' || Input::get('act') == 'edit')
{
$objUser = $this->Database->prepare("SELECT email, disable FROM tl_member WHERE id=?")
->limit(1)
->execute($intUser);
if ($objUser->numRows)
{
$strEmail = Input::post('email', true);
// E-mail address has changed
if (!empty($_POST) && $strEmail != '' && $strEmail != $objUser->email)
{
$objCount = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_newsletter_recipients WHERE email=?")
->execute($strEmail);
// Delete the old subscription if the new e-mail address exists (see #19)
if ($objCount->count > 0)
{
$this->Database->prepare("DELETE FROM tl_newsletter_recipients WHERE email=?")
->execute($objUser->email);
}
else
{
$this->Database->prepare("UPDATE tl_newsletter_recipients SET email=? WHERE email=?")
->execute($strEmail, $objUser->email);
}
$objUser->email = $strEmail;
}
$objSubscriptions = $this->Database->prepare("SELECT pid FROM tl_newsletter_recipients WHERE email=?")
->execute($objUser->email);
if ($objSubscriptions->numRows)
{
$strNewsletters = serialize($objSubscriptions->fetchEach('pid'));
}
else
{
$strNewsletters = '';
}
$this->Database->prepare("UPDATE tl_member SET newsletter=? WHERE id=?")
->execute($strNewsletters, $intUser);
// Update the front end user object
if (TL_MODE == 'FE')
{
$this->User->newsletter = $strNewsletters;
}
// Check activation status
elseif (!empty($_POST) && Input::post('disable') != $objUser->disable)
{
$this->Database->prepare("UPDATE tl_newsletter_recipients SET active=? WHERE email=?")
->execute((Input::post('disable') ? '' : 1), $objUser->email);
$objUser->disable = Input::post('disable');
}
}
}
// Delete account
elseif (Input::get('act') == 'delete')
{
$objUser = $this->Database->prepare("SELECT email FROM tl_member WHERE id=?")
->limit(1)
->execute($intUser);
if ($objUser->numRows)
{
$this->Database->prepare("DELETE FROM tl_newsletter_recipients WHERE email=?")
->execute($objUser->email);
}
}
} | php | {
"resource": ""
} |
q243395 | Newsletter.getNewsletters | validation | public function getNewsletters($objModule)
{
$objNewsletter = NewsletterChannelModel::findAll();
if ($objNewsletter === null)
{
return array();
}
$arrNewsletters = array();
// Return all channels if $objModule is null (see #5874)
if ($objModule === null || TL_MODE == 'BE')
{
while ($objNewsletter->next())
{
$arrNewsletters[$objNewsletter->id] = $objNewsletter->title;
}
}
else
{
$newsletters = StringUtil::deserialize($objModule->newsletters, true);
if (empty($newsletters) || !\is_array($newsletters))
{
return array();
}
while ($objNewsletter->next())
{
if (\in_array($objNewsletter->id, $newsletters))
{
$arrNewsletters[$objNewsletter->id] = $objNewsletter->title;
}
}
}
natsort($arrNewsletters); // see #7864
return $arrNewsletters;
} | php | {
"resource": ""
} |
q243396 | Newsletter.getSearchablePages | validation | 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;
}
if ($blnIsSitemap)
{
// The target page is protected (see #8416)
if ($objParent->protected)
{
continue;
}
// The target page is exempt from the sitemap (see #6418)
if ($objParent->sitemap == 'map_never')
{
continue;
}
}
// Generate the URL
$arrProcessed[$objNewsletter->jumpTo] = $objParent->getAbsoluteUrl(Config::get('useAutoItem') ? '/%s' : '/items/%s');
}
$strUrl = $arrProcessed[$objNewsletter->jumpTo];
// Get the items
$objItem = NewsletterModel::findSentByPid($objNewsletter->id);
if ($objItem !== null)
{
while ($objItem->next())
{
$arrPages[] = sprintf(preg_replace('/%(?!s)/', '%%', $strUrl), ($objItem->alias ?: $objItem->id));
}
}
}
}
return $arrPages;
} | php | {
"resource": ""
} |
q243397 | TextStore.validator | validation | protected function validator($varInput)
{
if ($varInput == '*****')
{
$this->blnSubmitInput = false;
return true;
}
return parent::validator($varInput);
} | php | {
"resource": ""
} |
q243398 | ContentYouTube.generate | validation | public function generate()
{
if ($this->youtube == '')
{
return '';
}
if (TL_MODE == 'BE')
{
$return = '<p><a href="https://youtu.be/' . $this->youtube . '" target="_blank" rel="noreferrer noopener">youtu.be/' . $this->youtube . '</a></p>';
if ($this->headline != '')
{
$return = '<'. $this->hl .'>'. $this->headline .'</'. $this->hl .'>'. $return;
}
return $return;
}
return parent::generate();
} | php | {
"resource": ""
} |
q243399 | Updater.run292Update | validation | public function run292Update()
{
$this->Database->query("ALTER TABLE `tl_calendar_events` CHANGE `startTime` `startTime` int(10) unsigned NULL");
$this->Database->query("ALTER TABLE `tl_calendar_events` CHANGE `endTime` `endTime` int(10) unsigned NULL");
$this->Database->query("ALTER TABLE `tl_calendar_events` CHANGE `startDate` `startDate` int(10) unsigned NULL");
$this->Database->query("ALTER TABLE `tl_calendar_events` CHANGE `endDate` `endDate` int(10) unsigned NULL");
$this->Database->query("UPDATE tl_calendar_events SET endDate=null WHERE endDate=0");
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.