_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q243400 | Updater.run210Update | validation | public function run210Update()
{
$this->Database->query("ALTER TABLE `tl_style` ADD `positioning` char(1) NOT NULL default ''");
$this->Database->query("UPDATE `tl_style` SET `positioning`=`size`");
$this->Database->query("UPDATE `tl_module` SET `guests`=1 WHERE `type`='lostPassword' OR `type`='registration'");
$this->Database->query("UPDATE `tl_news` SET `teaser`=CONCAT('<p>', teaser, '</p>') WHERE `teaser`!='' AND `teaser` NOT LIKE '<p>%'");
} | php | {
"resource": ""
} |
q243401 | Updater.run32Update | validation | public function run32Update()
{
// Adjust the custom layout sections (see #2885)
$this->Database->query("ALTER TABLE `tl_layout` CHANGE `sections` `sections` varchar(1022) NOT NULL default ''");
$objLayout = $this->Database->query("SELECT id, sections FROM tl_layout WHERE sections!=''");
while ($objLayout->next())
{
$strSections = '';
$tmp = StringUtil::deserialize($objLayout->sections);
if (!empty($tmp) && \is_array($tmp))
{
$strSections = implode(', ', $tmp);
}
$this->Database->prepare("UPDATE tl_layout SET sections=? WHERE id=?")
->execute($strSections, $objLayout->id);
}
// Check whether there are UUIDs
if (!$this->Database->fieldExists('uuid', 'tl_files'))
{
// Adjust the DB structure
$this->Database->query("ALTER TABLE `tl_files` ADD `uuid` binary(16) NULL");
$this->Database->query("ALTER TABLE `tl_files` ADD UNIQUE KEY `uuid` (`uuid`)");
// Backup the pid column and change the column type
$this->Database->query("ALTER TABLE `tl_files` ADD `pid_backup` int(10) unsigned NOT NULL default 0");
$this->Database->query("UPDATE `tl_files` SET `pid_backup`=`pid`");
$this->Database->query("ALTER TABLE `tl_files` CHANGE `pid` `pid` binary(16) NULL");
$this->Database->query("UPDATE `tl_files` SET `pid`=NULL");
$this->Database->query("UPDATE `tl_files` SET `pid`=NULL WHERE `pid_backup`=0");
$objFiles = $this->Database->query("SELECT id FROM tl_files");
// Generate the UUIDs
while ($objFiles->next())
{
$this->Database->prepare("UPDATE tl_files SET uuid=? WHERE id=?")
->execute($this->Database->getUuid(), $objFiles->id);
}
$objFiles = $this->Database->query("SELECT pid_backup FROM tl_files WHERE pid_backup>0 GROUP BY pid_backup");
// Adjust the parent IDs
while ($objFiles->next())
{
$objParent = $this->Database->prepare("SELECT uuid FROM tl_files WHERE id=?")
->execute($objFiles->pid_backup);
if ($objParent->numRows < 1)
{
throw new \Exception('Invalid parent ID ' . $objFiles->pid_backup);
}
$this->Database->prepare("UPDATE tl_files SET pid=? WHERE pid_backup=?")
->execute($objParent->uuid, $objFiles->pid_backup);
}
// Drop the pid_backup column
$this->Database->query("ALTER TABLE `tl_files` DROP `pid_backup`");
}
// Update the fields
$this->updateFileTreeFields();
} | php | {
"resource": ""
} |
q243402 | Updater.run33Update | validation | public function run33Update()
{
$objLayout = $this->Database->query("SELECT id, framework FROM tl_layout WHERE framework!=''");
while ($objLayout->next())
{
$strFramework = '';
$tmp = StringUtil::deserialize($objLayout->framework);
if (!empty($tmp) && \is_array($tmp))
{
if (($key = array_search('layout.css', $tmp)) !== false)
{
array_insert($tmp, $key + 1, 'responsive.css');
}
$strFramework = serialize(array_values(array_unique($tmp)));
}
$this->Database->prepare("UPDATE tl_layout SET framework=? WHERE id=?")
->execute($strFramework, $objLayout->id);
}
// Add the "viewport" field (triggers the version 3.3 update)
$this->Database->query("ALTER TABLE `tl_layout` ADD `viewport` varchar(64) NOT NULL default ''");
} | php | {
"resource": ""
} |
q243403 | Updater.run35Update | validation | public function run35Update()
{
$this->Database->query("ALTER TABLE `tl_member` CHANGE `username` `username` varchar(64) COLLATE utf8_bin NULL");
$this->Database->query("UPDATE `tl_member` SET username=NULL WHERE username=''");
$this->Database->query("ALTER TABLE `tl_member` DROP INDEX `username`, ADD UNIQUE KEY `username` (`username`)");
} | php | {
"resource": ""
} |
q243404 | Updater.run40Update | validation | public function run40Update()
{
// Adjust the framework agnostic scripts
$this->Database->query("ALTER TABLE `tl_layout` ADD `scripts` text NULL");
$objLayout = $this->Database->query("SELECT id, addJQuery, jquery, addMooTools, mootools FROM tl_layout WHERE framework!=''");
while ($objLayout->next())
{
$arrScripts = array();
// Check whether j_slider is enabled
if ($objLayout->addJQuery)
{
$jquery = StringUtil::deserialize($objLayout->jquery);
if (!empty($jquery) && \is_array($jquery))
{
if (($key = array_search('j_slider', $jquery)) !== false)
{
$arrScripts[] = 'js_slider';
unset($jquery[$key]);
$this->Database->prepare("UPDATE tl_layout SET jquery=? WHERE id=?")
->execute(serialize(array_values($jquery)), $objLayout->id);
}
}
}
// Check whether moo_slider is enabled
if ($objLayout->addMooTools)
{
$mootools = StringUtil::deserialize($objLayout->mootools);
if (!empty($mootools) && \is_array($mootools))
{
if (($key = array_search('moo_slider', $mootools)) !== false)
{
$arrScripts[] = 'js_slider';
unset($mootools[$key]);
$this->Database->prepare("UPDATE tl_layout SET mootools=? WHERE id=?")
->execute(serialize(array_values($mootools)), $objLayout->id);
}
}
}
// Enable the js_slider template
if (!empty($arrScripts))
{
$this->Database->prepare("UPDATE tl_layout SET scripts=? WHERE id=?")
->execute(serialize(array_values(array_unique($arrScripts))), $objLayout->id);
}
}
} | php | {
"resource": ""
} |
q243405 | Updater.convertSingleField | validation | public static function convertSingleField($table, $field)
{
$objDatabase = Database::getInstance();
// Get the non-empty rows
$objRow = $objDatabase->query("SELECT id, $field FROM $table WHERE $field!=''");
// Check the column type
$objDesc = $objDatabase->query("DESC $table $field");
// Change the column type
if ($objDesc->Type != 'binary(16)')
{
$objDatabase->query("ALTER TABLE `$table` CHANGE `$field` `$field` binary(16) NULL");
$objDatabase->query("UPDATE `$table` SET `$field`=NULL WHERE `$field`='' OR `$field`=0");
}
while ($objRow->next())
{
$objHelper = static::generateHelperObject($objRow->$field);
// UUID already
if ($objHelper->isUuid)
{
continue;
}
// Numeric ID to UUID
if ($objHelper->isNumeric)
{
$objFile = FilesModel::findByPk($objHelper->value);
$objDatabase->prepare("UPDATE $table SET $field=? WHERE id=?")
->execute($objFile->uuid, $objRow->id);
}
// Path to UUID
else
{
$objFile = FilesModel::findByPath($objHelper->value);
$objDatabase->prepare("UPDATE $table SET $field=? WHERE id=?")
->execute($objFile->uuid, $objRow->id);
}
}
} | php | {
"resource": ""
} |
q243406 | Updater.convertMultiField | validation | public static function convertMultiField($table, $field)
{
$objDatabase = Database::getInstance();
// Get the non-empty rows
$objRow = $objDatabase->query("SELECT id, $field FROM $table WHERE $field!=''");
// Check the column type
$objDesc = $objDatabase->query("DESC $table $field");
// Change the column type
if ($objDesc->Type != 'blob')
{
$objDatabase->query("ALTER TABLE `$table` CHANGE `$field` `$field` blob NULL");
$objDatabase->query("UPDATE `$table` SET `$field`=NULL WHERE `$field`=''");
}
while ($objRow->next())
{
$arrValues = StringUtil::deserialize($objRow->$field, true);
if (empty($arrValues))
{
continue;
}
$objHelper = static::generateHelperObject($arrValues);
// UUID already
if ($objHelper->isUuid)
{
continue;
}
foreach ($arrValues as $k=>$v)
{
// Numeric ID to UUID
if ($objHelper->isNumeric)
{
$objFile = FilesModel::findByPk($objHelper->value[$k]);
$arrValues[$k] = $objFile->uuid;
}
// Path to UUID
else
{
$objFile = FilesModel::findByPath($objHelper->value[$k]);
$arrValues[$k] = $objFile->uuid;
}
}
$objDatabase->prepare("UPDATE $table SET $field=? WHERE id=?")
->execute(serialize($arrValues), $objRow->id);
}
} | php | {
"resource": ""
} |
q243407 | Updater.convertOrderField | validation | public static function convertOrderField($table, $field)
{
$objDatabase = Database::getInstance();
// Get the non-empty rows
$objRow = $objDatabase->query("SELECT id, $field FROM $table WHERE $field LIKE '%,%'");
// Convert the comma separated lists into serialized arrays
while ($objRow->next())
{
$objDatabase->prepare("UPDATE $table SET $field=? WHERE id=?")
->execute(serialize(explode(',', $objRow->$field)), $objRow->id);
}
static::convertMultiField($table, $field);
} | php | {
"resource": ""
} |
q243408 | Updater.generateHelperObject | validation | protected static function generateHelperObject($value)
{
$return = new \stdClass();
if (!\is_array($value))
{
$return->value = rtrim($value, "\x00");
$return->isUuid = (\strlen($value) == 16 && !is_numeric($return->value) && strncmp($return->value, Config::get('uploadPath') . '/', \strlen(Config::get('uploadPath')) + 1) !== 0);
$return->isNumeric = (is_numeric($return->value) && $return->value > 0);
}
else
{
$return->value = array_map(function ($var) { return rtrim($var, "\x00"); }, $value);
$return->isUuid = (\strlen($value[0]) == 16 && !is_numeric($return->value[0]) && strncmp($return->value[0], Config::get('uploadPath') . '/', \strlen(Config::get('uploadPath')) + 1) !== 0);
$return->isNumeric = (is_numeric($return->value[0]) && $return->value[0] > 0);
}
return $return;
} | php | {
"resource": ""
} |
q243409 | Updater.createContentElement | validation | protected function createContentElement(Result $objElement, $strPtable, $strField)
{
$set = array
(
'pid' => $objElement->id,
'ptable' => $strPtable,
'sorting' => 128,
'tstamp' => $objElement->tstamp,
'type' => 'text',
'text' => $objElement->$strField,
'addImage' => $objElement->addImage,
'singleSRC' => $objElement->singleSRC,
'alt' => $objElement->alt,
'size' => $objElement->size,
'imagemargin' => $objElement->imagemargin,
'imageUrl' => $objElement->imageUrl,
'fullsize' => $objElement->fullsize,
'caption' => $objElement->caption,
'floating' => $objElement->floating
);
$this->Database->prepare("INSERT INTO tl_content %s")->set($set)->execute();
} | php | {
"resource": ""
} |
q243410 | InstallationController.acceptLicense | validation | private function acceptLicense(): Response
{
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
if ('tl_license' !== $request->request->get('FORM_SUBMIT')) {
return $this->render('license.html.twig');
}
$this->container->get('contao.install_tool')->persistConfig('licenseAccepted', true);
return $this->getRedirectResponse();
} | php | {
"resource": ""
} |
q243411 | InstallationController.setPassword | validation | private function setPassword(): Response
{
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
if ('tl_password' !== $request->request->get('FORM_SUBMIT')) {
return $this->render('password.html.twig');
}
$password = $request->request->get('password');
$confirmation = $request->request->get('confirmation');
// The passwords do not match
if ($password !== $confirmation) {
return $this->render('password.html.twig', [
'error' => $this->trans('password_confirmation_mismatch'),
]);
}
$installTool = $this->container->get('contao.install_tool');
$minlength = $installTool->getConfig('minPasswordLength');
// The passwords is too short
if (Utf8::strlen($password) < $minlength) {
return $this->render('password.html.twig', [
'error' => sprintf($this->trans('password_too_short'), $minlength),
]);
}
$installTool->persistConfig('installPassword', password_hash($password, PASSWORD_DEFAULT));
$this->container->get('contao.install_tool_user')->setAuthenticated(true);
return $this->getRedirectResponse();
} | php | {
"resource": ""
} |
q243412 | InstallationController.login | validation | private function login(): Response
{
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
if ('tl_login' !== $request->request->get('FORM_SUBMIT')) {
return $this->render('login.html.twig');
}
$installTool = $this->container->get('contao.install_tool');
$verified = password_verify(
$request->request->get('password'),
$installTool->getConfig('installPassword')
);
if (!$verified) {
$installTool->increaseLoginCount();
return $this->render('login.html.twig', [
'error' => $this->trans('invalid_password'),
]);
}
$installTool->resetLoginCount();
$this->container->get('contao.install_tool_user')->setAuthenticated(true);
return $this->getRedirectResponse();
} | php | {
"resource": ""
} |
q243413 | InstallationController.purgeSymfonyCache | validation | private function purgeSymfonyCache(): void
{
$filesystem = new Filesystem();
$cacheDir = $this->getContainerParameter('kernel.cache_dir');
$ref = new \ReflectionObject($this->container);
$containerDir = basename(\dirname($ref->getFileName()));
/** @var SplFileInfo[] $finder */
$finder = Finder::create()
->depth(0)
->exclude($containerDir)
->in($cacheDir)
;
foreach ($finder as $file) {
$filesystem->remove($file->getPathname());
}
if (\function_exists('opcache_reset')) {
opcache_reset();
}
if (\function_exists('apc_clear_cache') && !ini_get('apc.stat')) {
apc_clear_cache();
}
} | php | {
"resource": ""
} |
q243414 | InstallationController.warmUpSymfonyCache | validation | private function warmUpSymfonyCache(): void
{
$cacheDir = $this->getContainerParameter('kernel.cache_dir');
if (file_exists($cacheDir.'/contao/config/config.php')) {
return;
}
$warmer = $this->container->get('cache_warmer');
if (!$this->getContainerParameter('kernel.debug')) {
$warmer->enableOptionalWarmers();
}
$warmer->warmUp($cacheDir);
if (\function_exists('opcache_reset')) {
opcache_reset();
}
if (\function_exists('apc_clear_cache') && !ini_get('apc.stat')) {
apc_clear_cache();
}
} | php | {
"resource": ""
} |
q243415 | InstallationController.setUpDatabaseConnection | validation | private function setUpDatabaseConnection(): Response
{
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
// Only warn the user if the connection fails and the env component is used
if (false !== getenv('DATABASE_URL')) {
return $this->render('misconfigured_database_url.html.twig');
}
$parameters = [
'parameters' => [
'database_host' => $this->getContainerParameter('database_host'),
'database_port' => $this->getContainerParameter('database_port'),
'database_user' => $this->getContainerParameter('database_user'),
'database_password' => $this->getContainerParameter('database_password'),
'database_name' => $this->getContainerParameter('database_name'),
],
];
if ('tl_database_login' !== $request->request->get('FORM_SUBMIT')) {
return $this->render('database.html.twig', $parameters);
}
$parameters = [
'parameters' => [
'database_host' => $request->request->get('dbHost'),
'database_port' => $request->request->get('dbPort'),
'database_user' => $request->request->get('dbUser'),
'database_password' => $this->getContainerParameter('database_password'),
'database_name' => $request->request->get('dbName'),
],
];
if ('*****' !== $request->request->get('dbPassword')) {
$parameters['parameters']['database_password'] = $request->request->get('dbPassword');
}
if (false !== strpos($parameters['parameters']['database_name'], '.')) {
return $this->render('database.html.twig', array_merge(
$parameters,
['database_error' => $this->trans('database_dot_in_dbname')]
));
}
$installTool = $this->container->get('contao.install_tool');
$installTool->setConnection(ConnectionFactory::create($parameters));
if (!$installTool->canConnectToDatabase($parameters['parameters']['database_name'])) {
return $this->render('database.html.twig', array_merge(
$parameters,
['database_error' => $this->trans('database_could_not_connect')]
));
}
$dumper = new ParameterDumper($this->getContainerParameter('kernel.project_dir'));
$dumper->setParameters($parameters);
$dumper->dump();
$this->purgeSymfonyCache();
return $this->getRedirectResponse();
} | php | {
"resource": ""
} |
q243416 | InstallationController.adjustDatabaseTables | validation | private function adjustDatabaseTables(): ?RedirectResponse
{
$this->container->get('contao.install_tool')->handleRunOnce();
$installer = $this->container->get('contao.installer');
$this->context['sql_form'] = $installer->getCommands();
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
if ('tl_database_update' !== $request->request->get('FORM_SUBMIT')) {
return null;
}
$sql = $request->request->get('sql');
if (!empty($sql) && \is_array($sql)) {
foreach ($sql as $hash) {
$installer->execCommand($hash);
}
}
return $this->getRedirectResponse();
} | php | {
"resource": ""
} |
q243417 | InstallationController.importExampleWebsite | validation | private function importExampleWebsite(): ?RedirectResponse
{
$installTool = $this->container->get('contao.install_tool');
$templates = $installTool->getTemplates();
$this->context['templates'] = $templates;
if ($installTool->getConfig('exampleWebsite')) {
$this->context['import_date'] = date('Y-m-d H:i', $installTool->getConfig('exampleWebsite'));
}
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
if ('tl_template_import' !== $request->request->get('FORM_SUBMIT')) {
return null;
}
$template = $request->request->get('template');
if ('' === $template || !\in_array($template, $templates, true)) {
$this->context['import_error'] = $this->trans('import_empty_source');
return null;
}
try {
$installTool->importTemplate($template, '1' === $request->request->get('preserve'));
} catch (DBALException $e) {
$installTool->persistConfig('exampleWebsite', null);
$installTool->logException($e);
$this->context['import_error'] = $this->trans('import_exception');
return null;
}
$installTool->persistConfig('exampleWebsite', time());
return $this->getRedirectResponse();
} | php | {
"resource": ""
} |
q243418 | InstallationController.getRedirectResponse | validation | private function getRedirectResponse(): RedirectResponse
{
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
return new RedirectResponse($request->getRequestUri());
} | php | {
"resource": ""
} |
q243419 | InstallationController.addDefaultsToContext | validation | private function addDefaultsToContext(array $context): array
{
$context = array_merge($this->context, $context);
if (!isset($context['request_token'])) {
$context['request_token'] = $this->getRequestToken();
}
if (!isset($context['language'])) {
$context['language'] = $this->container->get('translator')->getLocale();
}
if (!isset($context['ua'])) {
$context['ua'] = $this->getUserAgentString();
}
if (!isset($context['path'])) {
$request = $this->container->get('request_stack')->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
$context['host'] = $request->getHost();
$context['path'] = $request->getBasePath();
}
return $context;
} | php | {
"resource": ""
} |
q243420 | SymlinksCommand.generateSymlinks | validation | private function generateSymlinks(): void
{
$fs = new Filesystem();
// Remove the base folders in the document root
$fs->remove($this->rootDir.'/'.$this->webDir.'/'.$this->uploadPath);
$fs->remove($this->rootDir.'/'.$this->webDir.'/system/modules');
$fs->remove($this->rootDir.'/'.$this->webDir.'/vendor');
$this->symlinkFiles($this->uploadPath);
$this->symlinkModules();
$this->symlinkThemes();
// Symlink the assets and themes directory
$this->symlink('assets', $this->webDir.'/assets');
$this->symlink('system/themes', $this->webDir.'/system/themes');
// Symlinks the logs directory
$this->symlink($this->getRelativePath($this->logsDir), 'system/logs');
$this->triggerSymlinkEvent();
} | php | {
"resource": ""
} |
q243421 | SymlinksCommand.findIn | validation | private function findIn(string $path): Finder
{
return Finder::create()
->ignoreDotFiles(false)
->sort(
static function (SplFileInfo $a, SplFileInfo $b): int {
$countA = substr_count(strtr($a->getRelativePath(), '\\', '/'), '/');
$countB = substr_count(strtr($b->getRelativePath(), '\\', '/'), '/');
return $countA <=> $countB;
}
)
->followLinks()
->in($path)
;
} | php | {
"resource": ""
} |
q243422 | SymlinksCommand.filterNestedPaths | validation | private function filterNestedPaths(Finder $finder, string $prepend): array
{
$parents = [];
$files = iterator_to_array($finder);
foreach ($files as $key => $file) {
$path = rtrim(strtr($prepend.'/'.$file->getRelativePath(), '\\', '/'), '/');
if (!empty($parents)) {
$parent = \dirname($path);
while (false !== strpos($parent, '/')) {
if (\in_array($parent, $parents, true)) {
$this->rows[] = [
sprintf(
'<fg=yellow;options=bold>%s</>',
'\\' === \DIRECTORY_SEPARATOR ? 'WARNING' : '!'
),
$this->webDir.'/'.$path,
sprintf('<comment>Skipped because %s will be symlinked.</comment>', $parent),
];
unset($files[$key]);
break;
}
$parent = \dirname($parent);
}
}
$parents[] = $path;
}
return array_values($files);
} | php | {
"resource": ""
} |
q243423 | tl_image_size_item.listImageSizeItem | validation | public function listImageSizeItem($row)
{
$html = '<div class="tl_content_left">';
$html .= $row['media'];
if ($row['width'] || $row['height'])
{
$html .= ' <span style="padding-left:3px">' . $row['width'] . 'x' . $row['height'] . '</span>';
}
if ($row['zoom'])
{
$html .= ' <span style="color:#999;padding-left:3px">(' . $row['zoom'] . '%)</span>';
}
$html .= "</div>\n";
return $html;
} | php | {
"resource": ""
} |
q243424 | BackendMenuBuilder.create | validation | public function create(): ItemInterface
{
$tree = $this->factory->createItem('root');
$this->eventDispatcher->dispatch(ContaoCoreEvents::BACKEND_MENU_BUILD, new MenuEvent($this->factory, $tree));
return $tree;
} | php | {
"resource": ""
} |
q243425 | Events.getAllEvents | validation | protected function getAllEvents($arrCalendars, $intStart, $intEnd)
{
if (!\is_array($arrCalendars))
{
return array();
}
$this->arrEvents = array();
foreach ($arrCalendars as $id)
{
// Get the events of the current period
$objEvents = CalendarEventsModel::findCurrentByPid($id, $intStart, $intEnd);
if ($objEvents === null)
{
continue;
}
while ($objEvents->next())
{
$this->addEvent($objEvents, $objEvents->startTime, $objEvents->endTime, $intStart, $intEnd, $id);
// Recurring events
if ($objEvents->recurring)
{
$arrRepeat = StringUtil::deserialize($objEvents->repeatEach);
if (!\is_array($arrRepeat) || !isset($arrRepeat['unit']) || !isset($arrRepeat['value']) || $arrRepeat['value'] < 1)
{
continue;
}
$count = 0;
$intStartTime = $objEvents->startTime;
$intEndTime = $objEvents->endTime;
$strtotime = '+ ' . $arrRepeat['value'] . ' ' . $arrRepeat['unit'];
while ($intEndTime < $intEnd)
{
if ($objEvents->recurrences > 0 && $count++ >= $objEvents->recurrences)
{
break;
}
$intStartTime = strtotime($strtotime, $intStartTime);
$intEndTime = strtotime($strtotime, $intEndTime);
// Stop if the upper boundary is reached (see #8445)
if ($intStartTime === false || $intEndTime === false)
{
break;
}
// Skip events outside the scope
if ($intEndTime < $intStart || $intStartTime > $intEnd)
{
continue;
}
$this->addEvent($objEvents, $intStartTime, $intEndTime, $intStart, $intEnd, $id);
}
}
}
}
// Sort the array
foreach (array_keys($this->arrEvents) as $key)
{
ksort($this->arrEvents[$key]);
}
// HOOK: modify the result set
if (isset($GLOBALS['TL_HOOKS']['getAllEvents']) && \is_array($GLOBALS['TL_HOOKS']['getAllEvents']))
{
foreach ($GLOBALS['TL_HOOKS']['getAllEvents'] as $callback)
{
$this->import($callback[0]);
$this->arrEvents = $this->{$callback[0]}->{$callback[1]}($this->arrEvents, $arrCalendars, $intStart, $intEnd, $this);
}
}
return $this->arrEvents;
} | php | {
"resource": ""
} |
q243426 | InitializeApplicationListener.onInitialize | validation | public function onInitialize(InitializeApplicationEvent $event): void
{
$this->installAssets($event);
$this->installContao($event);
$this->createSymlinks($event);
} | php | {
"resource": ""
} |
q243427 | Registry.fetch | validation | public function fetch($strTable, $varKey, $strAlias=null)
{
/** @var Model $strClass */
$strClass = Model::getClassFromTable($strTable);
$strPk = $strClass::getPk();
// Search by PK (most common case)
if ($strAlias === null || $strAlias == $strPk)
{
if (isset($this->arrRegistry[$strTable][$varKey]))
{
return $this->arrRegistry[$strTable][$varKey];
}
return null;
}
// Try to find the model by one of its aliases
return $this->fetchByAlias($strTable, $strAlias, $varKey);
} | php | {
"resource": ""
} |
q243428 | Registry.fetchByAlias | validation | public function fetchByAlias($strTable, $strAlias, $varValue)
{
if (isset($this->arrAliases[$strTable][$strAlias][$varValue]))
{
$strPk = $this->arrAliases[$strTable][$strAlias][$varValue];
if (isset($this->arrRegistry[$strTable][$strPk]))
{
return $this->arrRegistry[$strTable][$strPk];
}
}
return null;
} | php | {
"resource": ""
} |
q243429 | Registry.register | validation | public function register(Model $objModel)
{
$intObjectId = spl_object_hash($objModel);
// The model has been registered already
if (isset($this->arrIdentities[$intObjectId]))
{
return;
}
$strTable = $objModel->getTable();
if (!\is_array($this->arrAliases[$strTable]))
{
$this->arrAliases[$strTable] = array();
}
if (!\is_array($this->arrRegistry[$strTable]))
{
$this->arrRegistry[$strTable] = array();
}
$strPk = $objModel->getPk();
$varPk = $objModel->$strPk;
if ($varPk === null)
{
throw new \RuntimeException('The primary key has not been set');
}
// Another model object is pointing to the DB record already
if (isset($this->arrRegistry[$strTable][$varPk]))
{
throw new \RuntimeException("The registry already contains an instance for $strTable::$strPk($varPk)");
}
$this->arrIdentities[$intObjectId] = $objModel;
$this->arrRegistry[$strTable][$varPk] = $objModel;
// Allow the model to modify the registry
$objModel->onRegister($this);
} | php | {
"resource": ""
} |
q243430 | Registry.unregister | validation | public function unregister(Model $objModel)
{
$intObjectId = spl_object_hash($objModel);
// The model is not registered
if (!isset($this->arrIdentities[$intObjectId]))
{
return;
}
$strTable = $objModel->getTable();
$strPk = $objModel->getPk();
$intPk = $objModel->$strPk;
unset($this->arrIdentities[$intObjectId]);
unset($this->arrRegistry[$strTable][$intPk]);
// Allow the model to modify the registry
$objModel->onUnregister($this);
} | php | {
"resource": ""
} |
q243431 | Registry.isRegistered | validation | public function isRegistered(Model $objModel)
{
$intObjectId = spl_object_hash($objModel);
return isset($this->arrIdentities[$intObjectId]);
} | php | {
"resource": ""
} |
q243432 | Registry.registerAlias | validation | public function registerAlias(Model $objModel, $strAlias, $varValue)
{
$strTable = $objModel->getTable();
$strPk = $objModel->getPk();
$varPk = $objModel->$strPk;
if (isset($this->arrAliases[$strTable][$strAlias][$varValue]))
{
throw new \RuntimeException("The registry already contains an alias for $strTable::$strPk($varPk) ($strAlias/$varValue)");
}
$this->arrAliases[$strTable][$strAlias][$varValue] = $varPk;
} | php | {
"resource": ""
} |
q243433 | Registry.isRegisteredAlias | validation | public function isRegisteredAlias(Model $objModel, $strAlias, $varValue)
{
$strTable = $objModel->getTable();
return isset($this->arrAliases[$strTable][$strAlias][$varValue]);
} | php | {
"resource": ""
} |
q243434 | ModuleRegistration.sendActivationMail | validation | protected function sendActivationMail($arrData)
{
/** @var OptIn $optIn */
$optIn = System::getContainer()->get('contao.opt-in');
$optInToken = $optIn->create('reg', $arrData['email'], array('tl_member'=>array($arrData['id'])));
// Prepare the simple token data
$arrTokenData = $arrData;
$arrTokenData['activation'] = $optInToken->getIdentifier();
$arrTokenData['domain'] = Idna::decode(Environment::get('host'));
$arrTokenData['link'] = Idna::decode(Environment::get('base')) . Environment::get('request') . ((strpos(Environment::get('request'), '?') !== false) ? '&' : '?') . 'token=' . $optInToken->getIdentifier();
$arrTokenData['channels'] = '';
$bundles = System::getContainer()->getParameter('kernel.bundles');
if (isset($bundles['ContaoNewsletterBundle']))
{
// Make sure newsletter is an array
if (!\is_array($arrData['newsletter']))
{
if ($arrData['newsletter'] != '')
{
$arrData['newsletter'] = array($arrData['newsletter']);
}
else
{
$arrData['newsletter'] = array();
}
}
// Replace the wildcard
if (!empty($arrData['newsletter']))
{
$objChannels = NewsletterChannelModel::findByIds($arrData['newsletter']);
if ($objChannels !== null)
{
$arrTokenData['channels'] = implode("\n", $objChannels->fetchEach('title'));
}
}
}
// Deprecated since Contao 4.0, to be removed in Contao 5.0
$arrTokenData['channel'] = $arrTokenData['channels'];
// Send the token
$optInToken->send(sprintf($GLOBALS['TL_LANG']['MSC']['emailSubject'], Idna::decode(Environment::get('host'))), StringUtil::parseSimpleTokens($this->reg_text, $arrTokenData));
} | php | {
"resource": ""
} |
q243435 | ModuleRegistration.activateAcount | validation | protected function activateAcount()
{
$this->strTemplate = 'mod_message';
$this->Template = new FrontendTemplate($this->strTemplate);
/** @var OptIn $optIn */
$optIn = System::getContainer()->get('contao.opt-in');
// Find an unconfirmed token with only one related record
if ((!$optInToken = $optIn->find(Input::get('token'))) || !$optInToken->isValid() || \count($arrRelated = $optInToken->getRelatedRecords()) != 1 || key($arrRelated) != 'tl_member' || \count($arrIds = current($arrRelated)) != 1 || (!$objMember = MemberModel::findByPk($arrIds[0])))
{
$this->Template->type = 'error';
$this->Template->message = $GLOBALS['TL_LANG']['MSC']['invalidToken'];
return;
}
if ($optInToken->isConfirmed())
{
$this->Template->type = 'error';
$this->Template->message = $GLOBALS['TL_LANG']['MSC']['tokenConfirmed'];
return;
}
if ($optInToken->getEmail() != $objMember->email)
{
$this->Template->type = 'error';
$this->Template->message = $GLOBALS['TL_LANG']['MSC']['tokenEmailMismatch'];
return;
}
$objMember->disable = '';
$objMember->save();
$optInToken->confirm();
// HOOK: post activation callback
if (isset($GLOBALS['TL_HOOKS']['activateAccount']) && \is_array($GLOBALS['TL_HOOKS']['activateAccount']))
{
foreach ($GLOBALS['TL_HOOKS']['activateAccount'] as $callback)
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($objMember, $this);
}
}
// Log activity
$this->log('User account ID ' . $objMember->id . ' (' . Idna::decodeEmail($objMember->email) . ') has been activated', __METHOD__, TL_ACCESS);
// Redirect to the jumpTo page
if (($objTarget = $this->objModel->getRelated('reg_jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
$this->redirect($objTarget->getFrontendUrl());
}
// Confirm activation
$this->Template->type = 'confirm';
$this->Template->message = $GLOBALS['TL_LANG']['MSC']['accountActivated'];
} | php | {
"resource": ""
} |
q243436 | ModuleRegistration.resendActivationMail | validation | protected function resendActivationMail(MemberModel $objMember)
{
if ($objMember->disable == '')
{
return;
}
$this->strTemplate = 'mod_message';
$this->Template = new FrontendTemplate($this->strTemplate);
/** @var OptIn $optIn */
$optIn = System::getContainer()->get('contao.opt-in');
$optInToken = null;
$models = OptInModel::findByRelatedTableAndIds('tl_member', array($objMember->id));
foreach ($models as $model)
{
// Look for a valid, unconfirmed token
if (($token = $optIn->find($model->token)) && $token->isValid() && !$token->isConfirmed())
{
$optInToken = $token;
break;
}
}
if ($optInToken === null)
{
return;
}
$optInToken->send();
// Confirm activation
$this->Template->type = 'confirm';
$this->Template->message = $GLOBALS['TL_LANG']['MSC']['resendActivation'];
} | php | {
"resource": ""
} |
q243437 | ModuleRegistration.sendAdminNotification | validation | 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 == '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);
} | php | {
"resource": ""
} |
q243438 | AuthenticationSuccessHandler.onAuthenticationSuccess | validation | public function onAuthenticationSuccess(Request $request, TokenInterface $token): RedirectResponse
{
$this->user = $token->getUser();
if (!$this->user instanceof User) {
return $this->getRedirectResponse($request);
}
$this->user->lastLogin = $this->user->currentLogin;
$this->user->currentLogin = time();
$this->user->save();
if (null !== $this->logger) {
$this->logger->info(
sprintf('User "%s" has logged in', $this->user->username),
['contao' => new ContaoContext(__METHOD__, ContaoContext::ACCESS, $this->user->username)]
);
}
$this->triggerPostLoginHook();
return $this->getRedirectResponse($request);
} | php | {
"resource": ""
} |
q243439 | ArticleModel.findByIdOrAliasAndPid | validation | public static function findByIdOrAliasAndPid($varId, $intPid, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = !preg_match('/^[1-9]\d*$/', $varId) ? array("$t.alias=?") : array("$t.id=?");
$arrValues = array($varId);
if ($intPid)
{
$arrColumns[] = "$t.pid=?";
$arrValues[] = $intPid;
}
return static::findOneBy($arrColumns, $arrValues, $arrOptions);
} | php | {
"resource": ""
} |
q243440 | ArticleModel.findPublishedByIdOrAliasAndPid | validation | public static function findPublishedByIdOrAliasAndPid($varId, $intPid, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = !preg_match('/^[1-9]\d*$/', $varId) ? array("$t.alias=?") : array("$t.id=?");
$arrValues = array($varId);
if ($intPid)
{
$arrColumns[] = "$t.pid=?";
$arrValues[] = $intPid;
}
if (!static::isPreviewMode($arrOptions))
{
$time = Date::floorToMinute();
$arrColumns[] = "($t.start='' OR $t.start<='$time') AND ($t.stop='' OR $t.stop>'" . ($time + 60) . "') AND $t.published='1'";
}
return static::findOneBy($arrColumns, $arrValues, $arrOptions);
} | php | {
"resource": ""
} |
q243441 | ArticleModel.findPublishedByPidAndColumn | validation | public static function findPublishedByPidAndColumn($intPid, $strColumn, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.pid=? AND $t.inColumn=?");
$arrValues = array($intPid, $strColumn);
if (!static::isPreviewMode($arrOptions))
{
$time = Date::floorToMinute();
$arrColumns[] = "($t.start='' OR $t.start<='$time') AND ($t.stop='' OR $t.stop>'" . ($time + 60) . "') AND $t.published='1'";
}
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = "$t.sorting";
}
return static::findBy($arrColumns, $arrValues, $arrOptions);
} | php | {
"resource": ""
} |
q243442 | Input.initialize | validation | public static function initialize()
{
$_GET = static::cleanKey($_GET);
$_POST = static::cleanKey($_POST);
$_COOKIE = static::cleanKey($_COOKIE);
} | php | {
"resource": ""
} |
q243443 | Input.stripTags | validation | public static function stripTags($varValue, $strAllowedTags='')
{
if ($varValue === null || $varValue == '')
{
return $varValue;
}
// Recursively clean arrays
if (\is_array($varValue))
{
foreach ($varValue as $k=>$v)
{
$varValue[$k] = static::stripTags($v, $strAllowedTags);
}
return $varValue;
}
// Encode opening arrow brackets (see #3998)
$varValue = preg_replace_callback('@</?([^\s<>/]*)@', function ($matches) use ($strAllowedTags)
{
if ($matches[1] == '' || stripos($strAllowedTags, '<' . strtolower($matches[1]) . '>') === false)
{
$matches[0] = str_replace('<', '<', $matches[0]);
}
return $matches[0];
}, $varValue);
// Strip the tags and restore HTML comments
$varValue = strip_tags($varValue, $strAllowedTags);
$varValue = str_replace(array('<!--', '<!['), array('<!--', '<!['), $varValue);
// Recheck for encoded null bytes
while (strpos($varValue, '\\0') !== false)
{
$varValue = str_replace('\\0', '', $varValue);
}
return $varValue;
} | php | {
"resource": ""
} |
q243444 | Input.decodeEntities | validation | public static function decodeEntities($varValue)
{
if ($varValue === null || $varValue == '')
{
return $varValue;
}
// Recursively clean arrays
if (\is_array($varValue))
{
foreach ($varValue as $k=>$v)
{
$varValue[$k] = static::decodeEntities($v);
}
return $varValue;
}
// Preserve basic entities
$varValue = static::preserveBasicEntities($varValue);
$varValue = html_entity_decode($varValue, ENT_QUOTES, Config::get('characterSet'));
return $varValue;
} | php | {
"resource": ""
} |
q243445 | Input.encodeSpecialChars | validation | public static function encodeSpecialChars($varValue)
{
if ($varValue === null || $varValue == '')
{
return $varValue;
}
// Recursively clean arrays
if (\is_array($varValue))
{
foreach ($varValue as $k=>$v)
{
$varValue[$k] = static::encodeSpecialChars($v);
}
return $varValue;
}
$arrSearch = array('#', '<', '>', '(', ')', '\\', '=');
$arrReplace = array('#', '<', '>', '(', ')', '\', '=');
return str_replace($arrSearch, $arrReplace, $varValue);
} | php | {
"resource": ""
} |
q243446 | Input.findPost | validation | public static function findPost($strKey)
{
if (isset($_POST[$strKey]))
{
return $_POST[$strKey];
}
$request = System::getContainer()->get('request_stack')->getMasterRequest();
// Return if the session has not been started before
if ($request === null || !$request->hasPreviousSession())
{
return null;
}
if (isset($_SESSION['FORM_DATA'][$strKey]))
{
return ($strKey == 'FORM_SUBMIT') ? preg_replace('/^auto_/i', '', $_SESSION['FORM_DATA'][$strKey]) : $_SESSION['FORM_DATA'][$strKey];
}
return null;
} | php | {
"resource": ""
} |
q243447 | ModuleLogout.generate | validation | public function generate()
{
if (TL_MODE == 'BE')
{
$objTemplate = new BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ' . Utf8::strtoupper($GLOBALS['TL_LANG']['FMD']['logout'][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();
}
// Set last page visited
if ($this->redirectBack)
{
$_SESSION['LAST_PAGE_VISITED'] = $this->getReferer();
}
$strLogoutUrl = System::getContainer()->get('security.logout_url_generator')->getLogoutUrl();
$strRedirect = Environment::get('base');
// Redirect to last page visited
if ($this->redirectBack && !empty($_SESSION['LAST_PAGE_VISITED']))
{
$strRedirect = $_SESSION['LAST_PAGE_VISITED'];
}
// Redirect to jumpTo page
elseif (($objTarget = $this->objModel->getRelated('jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
$strRedirect = $objTarget->getAbsoluteUrl();
}
$uri = Http::createFromString($strLogoutUrl);
// Add the redirect= parameter to the logout URL
$query = new Query($uri->getQuery());
$query = $query->merge('redirect=' . $strRedirect);
$this->redirect((string) $uri->withQuery((string) $query));
return '';
} | php | {
"resource": ""
} |
q243448 | ModuleEventMenu.compileYearlyMenu | validation | protected function compileYearlyMenu()
{
$arrData = array();
$arrAllEvents = $this->getAllEvents($this->cal_calendar, 0, 2145913200);
foreach ($arrAllEvents as $intDay=>$arrDay)
{
foreach ($arrDay as $arrEvents)
{
$arrData[substr($intDay, 0, 4)] += \count($arrEvents);
}
}
// Sort data
($this->cal_order == 'ascending') ? ksort($arrData) : krsort($arrData);
$arrItems = array();
$count = 0;
$limit = \count($arrData);
// Prepare navigation
foreach ($arrData as $intYear=>$intCount)
{
$intDate = $intYear;
$quantity = sprintf((($intCount < 2) ? $GLOBALS['TL_LANG']['MSC']['entry'] : $GLOBALS['TL_LANG']['MSC']['entries']), $intCount);
$arrItems[$intYear]['date'] = $intDate;
$arrItems[$intYear]['link'] = $intYear;
$arrItems[$intYear]['href'] = $this->strLink . '?year=' . $intDate;
$arrItems[$intYear]['title'] = StringUtil::specialchars($intYear . ' (' . $quantity . ')');
$arrItems[$intYear]['class'] = trim(((++$count == 1) ? 'first ' : '') . (($count == $limit) ? 'last' : ''));
$arrItems[$intYear]['isActive'] = (Input::get('year') == $intDate);
$arrItems[$intYear]['quantity'] = $quantity;
}
$this->Template->yearly = true;
$this->Template->items = $arrItems;
$this->Template->showQuantity = ($this->cal_showQuantity != '') ? true : false;
} | php | {
"resource": ""
} |
q243449 | Result.__isset | validation | public function __isset($strKey)
{
if (empty($this->arrCache))
{
$this->next();
}
return isset($this->arrCache[$strKey]);
} | php | {
"resource": ""
} |
q243450 | Result.fetchRow | validation | public function fetchRow()
{
if ($this->intIndex >= $this->count() - 1)
{
return false;
}
$this->arrCache = array_values($this->resultSet[++$this->intIndex]);
return $this->arrCache;
} | php | {
"resource": ""
} |
q243451 | Result.fetchAssoc | validation | public function fetchAssoc()
{
if ($this->intIndex >= $this->count() - 1)
{
return false;
}
$this->arrCache = $this->resultSet[++$this->intIndex];
return $this->arrCache;
} | php | {
"resource": ""
} |
q243452 | Result.fetchEach | validation | public function fetchEach($strKey)
{
$this->reset();
$arrReturn = array();
while (($arrRow = $this->fetchAssoc()) !== false)
{
if ($strKey != 'id' && isset($arrRow['id']))
{
$arrReturn[$arrRow['id']] = $arrRow[$strKey];
}
else
{
$arrReturn[] = $arrRow[$strKey];
}
}
return $arrReturn;
} | php | {
"resource": ""
} |
q243453 | Result.fetchField | validation | public function fetchField($intOffset=0)
{
$arrFields = array_values($this->resultSet[$this->intIndex]);
return $arrFields[$intOffset];
} | php | {
"resource": ""
} |
q243454 | Result.first | validation | public function first()
{
$this->intIndex = 0;
$this->blnDone = false;
$this->arrCache = $this->resultSet[$this->intIndex];
return $this;
} | php | {
"resource": ""
} |
q243455 | Result.prev | validation | public function prev()
{
if ($this->intIndex < 1)
{
return false;
}
$this->blnDone = false;
$this->arrCache = $this->resultSet[--$this->intIndex];
return $this;
} | php | {
"resource": ""
} |
q243456 | Result.next | validation | public function next()
{
if ($this->blnDone)
{
return false;
}
if ($this->fetchAssoc() !== false)
{
return $this;
}
$this->blnDone = true;
return false;
} | php | {
"resource": ""
} |
q243457 | Result.last | validation | public function last()
{
$this->intIndex = $this->count() - 1;
$this->blnDone = true;
$this->arrCache = $this->resultSet[$this->intIndex];
return $this;
} | php | {
"resource": ""
} |
q243458 | tl_module_newsletter.getChannels | validation | public function getChannels()
{
if (!$this->User->isAdmin && !\is_array($this->User->newsletters))
{
return array();
}
$arrChannels = array();
$objChannels = $this->Database->execute("SELECT id, title FROM tl_newsletter_channel ORDER BY title");
while ($objChannels->next())
{
if ($this->User->hasAccess($objChannels->id, 'newsletters'))
{
$arrChannels[$objChannels->id] = $objChannels->title;
}
}
return $arrChannels;
} | php | {
"resource": ""
} |
q243459 | tl_form_field.getFields | validation | public function getFields()
{
$arrFields = $GLOBALS['TL_FFL'];
// Add the translation
foreach (array_keys($arrFields) as $key)
{
$arrFields[$key] = $GLOBALS['TL_LANG']['FFL'][$key][0];
}
return $arrFields;
} | php | {
"resource": ""
} |
q243460 | NewsModel.countPublishedByPids | validation | public static function countPublishedByPids($arrPids, $blnFeatured=null, array $arrOptions=array())
{
if (empty($arrPids) || !\is_array($arrPids))
{
return 0;
}
$t = static::$strTable;
$arrColumns = array("$t.pid IN(" . implode(',', array_map('\intval', $arrPids)) . ")");
if ($blnFeatured === true)
{
$arrColumns[] = "$t.featured='1'";
}
elseif ($blnFeatured === false)
{
$arrColumns[] = "$t.featured=''";
}
if (!static::isPreviewMode($arrOptions))
{
$time = Date::floorToMinute();
$arrColumns[] = "($t.start='' OR $t.start<='$time') AND ($t.stop='' OR $t.stop>'" . ($time + 60) . "') AND $t.published='1'";
}
return static::countBy($arrColumns, null, $arrOptions);
} | php | {
"resource": ""
} |
q243461 | NewsModel.findPublishedDefaultByPid | validation | public static function findPublishedDefaultByPid($intPid, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.pid=? AND $t.source='default'");
if (!static::isPreviewMode($arrOptions))
{
$time = Date::floorToMinute();
$arrColumns[] = "($t.start='' OR $t.start<='$time') AND ($t.stop='' OR $t.stop>'" . ($time + 60) . "') AND $t.published='1'";
}
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = "$t.date DESC";
}
return static::findBy($arrColumns, $intPid, $arrOptions);
} | php | {
"resource": ""
} |
q243462 | NewsModel.findPublishedFromToByPids | validation | public static function findPublishedFromToByPids($intFrom, $intTo, $arrPids, $intLimit=0, $intOffset=0, array $arrOptions=array())
{
if (empty($arrPids) || !\is_array($arrPids))
{
return null;
}
$t = static::$strTable;
$arrColumns = array("$t.date>=? AND $t.date<=? AND $t.pid IN(" . implode(',', array_map('\intval', $arrPids)) . ")");
if (!static::isPreviewMode($arrOptions))
{
$time = Date::floorToMinute();
$arrColumns[] = "($t.start='' OR $t.start<='$time') AND ($t.stop='' OR $t.stop>'" . ($time + 60) . "') AND $t.published='1'";
}
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = "$t.date DESC";
}
$arrOptions['limit'] = $intLimit;
$arrOptions['offset'] = $intOffset;
return static::findBy($arrColumns, array($intFrom, $intTo), $arrOptions);
} | php | {
"resource": ""
} |
q243463 | NewsModel.countPublishedFromToByPids | validation | public static function countPublishedFromToByPids($intFrom, $intTo, $arrPids, array $arrOptions=array())
{
if (empty($arrPids) || !\is_array($arrPids))
{
return null;
}
$t = static::$strTable;
$arrColumns = array("$t.date>=? AND $t.date<=? AND $t.pid IN(" . implode(',', array_map('\intval', $arrPids)) . ")");
if (!static::isPreviewMode($arrOptions))
{
$time = Date::floorToMinute();
$arrColumns[] = "($t.start='' OR $t.start<='$time') AND ($t.stop='' OR $t.stop>'" . ($time + 60) . "') AND $t.published='1'";
}
return static::countBy($arrColumns, array($intFrom, $intTo), $arrOptions);
} | php | {
"resource": ""
} |
q243464 | tl_theme.doGetTemplateFolders | validation | protected function doGetTemplateFolders($path, $level=0)
{
$return = array();
$rootDir = Contao\System::getContainer()->getParameter('kernel.project_dir');
foreach (scan($rootDir . '/' . $path) as $file)
{
if (is_dir($rootDir . '/' . $path . '/' . $file))
{
$return[$path . '/' . $file] = str_repeat(' ', $level) . $file;
$return = array_merge($return, $this->doGetTemplateFolders($path . '/' . $file, $level+1));
}
}
return $return;
} | php | {
"resource": ""
} |
q243465 | tl_theme.editCss | validation | public function editCss($row, $href, $label, $title, $icon, $attributes)
{
return $this->User->hasAccess('css', 'themes') ? '<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": ""
} |
q243466 | PrettyErrorScreenListener.onKernelException | validation | public function onKernelException(GetResponseForExceptionEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
if ('html' !== $request->getRequestFormat()) {
return;
}
if (!AcceptHeader::fromString($request->headers->get('Accept'))->has('text/html')) {
return;
}
$this->handleException($event);
} | php | {
"resource": ""
} |
q243467 | PrettyErrorScreenListener.renderErrorScreenByException | validation | private function renderErrorScreenByException(GetResponseForExceptionEvent $event): void
{
$exception = $event->getException();
$statusCode = $this->getStatusCodeForException($exception);
$template = null;
$this->logException($exception);
// Look for a template
do {
if ($exception instanceof \Exception) {
$template = $this->getTemplateForException($exception);
}
} while (null === $template && null !== ($exception = $exception->getPrevious()));
$this->renderTemplate($template ?: 'error', $statusCode, $event);
} | php | {
"resource": ""
} |
q243468 | tl_faq_category.editHeader | validation | public function editHeader($row, $href, $label, $title, $icon, $attributes)
{
return $this->User->canEditFieldsOf('tl_faq_category') ? '<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": ""
} |
q243469 | tl_templates.addBreadcrumb | validation | public function addBreadcrumb()
{
/** @var Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface $objSessionBag */
$objSessionBag = Contao\System::getContainer()->get('session')->getBag('contao_backend');
// Set a new node
if (isset($_GET['fn']))
{
// Check the path (thanks to Arnaud Buchoux)
if (Contao\Validator::isInsecurePath(Contao\Input::get('fn', true)))
{
throw new RuntimeException('Insecure path ' . Contao\Input::get('fn', true));
}
$objSessionBag->set('tl_templates_node', Contao\Input::get('fn', true));
$this->redirect(preg_replace('/(&|\?)fn=[^&]*/', '', Contao\Environment::get('request')));
}
$strNode = $objSessionBag->get('tl_templates_node');
if ($strNode == '')
{
return;
}
// Check the path (thanks to Arnaud Buchoux)
if (Contao\Validator::isInsecurePath($strNode))
{
throw new RuntimeException('Insecure path ' . $strNode);
}
$rootDir = Contao\System::getContainer()->getParameter('kernel.project_dir');
// Currently selected folder does not exist
if (!is_dir($rootDir . '/' . $strNode))
{
$objSessionBag->set('tl_templates_node', '');
return;
}
$strPath = 'templates';
$arrNodes = explode('/', preg_replace('/^templates\//', '', $strNode));
$arrLinks = array();
// Add root link
$arrLinks[] = Contao\Image::getHtml('filemounts.svg') . ' <a href="' . $this->addToUrl('fn=') . '" title="'.Contao\StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['selectAllNodes']).'">' . $GLOBALS['TL_LANG']['MSC']['filterAll'] . '</a>';
// Generate breadcrumb trail
foreach ($arrNodes as $strFolder)
{
$strPath .= '/' . $strFolder;
// No link for the active folder
if ($strFolder == basename($strNode))
{
$arrLinks[] = Contao\Image::getHtml('folderC.svg') . ' ' . $strFolder;
}
else
{
$arrLinks[] = Contao\Image::getHtml('folderC.svg') . ' <a href="' . $this->addToUrl('fn='.$strPath) . '" title="'.Contao\StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['selectNode']).'">' . $strFolder . '</a>';
}
}
// Limit tree
$GLOBALS['TL_DCA']['tl_templates']['list']['sorting']['root'] = array($strNode);
// Insert breadcrumb menu
$GLOBALS['TL_DCA']['tl_templates']['list']['sorting']['breadcrumb'] .= '
<nav aria-label="' . $GLOBALS['TL_LANG']['MSC']['breadcrumbMenu'] . '">
<ul id="tl_breadcrumb">
<li>' . implode(' › </li><li>', $arrLinks) . '</li>
</ul>
</nav>';
} | php | {
"resource": ""
} |
q243470 | tl_templates.dragFile | validation | public function dragFile($row, $href, $label, $title, $icon, $attributes)
{
return '<button type="button" title="'.Contao\StringUtil::specialchars($title).'" '.$attributes.'>'.Contao\Image::getHtml($icon, $label).'</button> ';
} | php | {
"resource": ""
} |
q243471 | tl_templates.getTargetFolders | validation | protected function getTargetFolders($strFolder, $intLevel=1)
{
$strFolders = '';
$strPath = Contao\System::getContainer()->getParameter('kernel.project_dir') .'/'. $strFolder;
foreach (scan($strPath) as $strFile)
{
if (!is_dir($strPath .'/'. $strFile) || strncmp($strFile, '.', 1) === 0)
{
continue;
}
$strRelPath = $strFolder .'/'. $strFile;
$strFolders .= sprintf('<option value="%s"%s>%s%s</option>', $strRelPath, ((Contao\Input::post('target') == $strRelPath) ? ' selected="selected"' : ''), str_repeat(' ', $intLevel), basename($strRelPath));
$strFolders .= $this->getTargetFolders($strRelPath, ($intLevel + 1));
}
return $strFolders;
} | php | {
"resource": ""
} |
q243472 | UserAwareTrait.hasUser | validation | protected function hasUser(): bool
{
$user = $this->tokenStorage->getToken();
if (null === $user) {
return false;
}
return !($user instanceof AnonymousToken);
} | php | {
"resource": ""
} |
q243473 | BackendSwitch.getDatalistOptions | validation | protected function getDatalistOptions()
{
$strGroups = '';
if (!$this->User->isAdmin)
{
// No allowed member groups
if (empty($this->User->amg) || !\is_array($this->User->amg))
{
header('Content-type: application/json');
die(json_encode(array()));
}
$arrGroups = array();
foreach ($this->User->amg as $intGroup)
{
$arrGroups[] = '%"' . (int) $intGroup . '"%';
}
$strGroups = " AND (groups LIKE '" . implode("' OR GROUPS LIKE '", $arrGroups) . "')";
}
$arrUsers = array();
$time = Date::floorToMinute();
// Get the active front end users
$objUsers = $this->Database->prepare("SELECT username FROM tl_member WHERE username LIKE ?$strGroups AND login='1' 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));
} | php | {
"resource": ""
} |
q243474 | tl_undo.checkPermission | validation | public function checkPermission()
{
if ($this->User->isAdmin)
{
return;
}
// Show only own undo steps
$objSteps = $this->Database->prepare("SELECT id FROM tl_undo WHERE pid=?")
->execute($this->User->id);
// Restrict the list
$GLOBALS['TL_DCA']['tl_undo']['list']['sorting']['root'] = $objSteps->numRows ? $objSteps->fetchEach('id') : array(0);
// Redirect if there is an error
if (Contao\Input::get('act') && !\in_array(Contao\Input::get('id'), $GLOBALS['TL_DCA']['tl_undo']['list']['sorting']['root']))
{
throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to ' . Contao\Input::get('act') . ' undo step ID ' . Contao\Input::get('id') . '.');
}
} | php | {
"resource": ""
} |
q243475 | tl_undo.showDeletedRecords | validation | public function showDeletedRecords($data, $row)
{
$arrData = Contao\StringUtil::deserialize($row['data']);
foreach ($arrData as $strTable=>$arrTableData)
{
Contao\System::loadLanguageFile($strTable);
Contao\Controller::loadDataContainer($strTable);
foreach ($arrTableData as $arrRow)
{
$arrBuffer = array();
foreach ($arrRow as $i=>$v)
{
if (\is_array(Contao\StringUtil::deserialize($v)))
{
continue;
}
// Get the field label
if (isset($GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label']))
{
$label = \is_array($GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label']) ? $GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label'][0] : $GLOBALS['TL_DCA'][$strTable]['fields'][$i]['label'];
}
else
{
$label = \is_array($GLOBALS['TL_LANG']['MSC'][$i]) ? $GLOBALS['TL_LANG']['MSC'][$i][0] : $GLOBALS['TL_LANG']['MSC'][$i];
}
if (!$label)
{
$label = $i;
}
$arrBuffer[$label] = $v;
}
$data[$strTable][] = $arrBuffer;
}
}
return $data;
} | php | {
"resource": ""
} |
q243476 | GeneratePageListener.onGeneratePage | validation | public function onGeneratePage(PageModel $pageModel, LayoutModel $layoutModel): void
{
$calendarfeeds = StringUtil::deserialize($layoutModel->calendarfeeds);
if (empty($calendarfeeds) || !\is_array($calendarfeeds)) {
return;
}
$this->framework->initialize();
/** @var CalendarFeedModel $adapter */
$adapter = $this->framework->getAdapter(CalendarFeedModel::class);
if (!($feeds = $adapter->findByIds($calendarfeeds)) instanceof Collection) {
return;
}
/** @var Template $template */
$template = $this->framework->getAdapter(Template::class);
/** @var Environment $environment */
$environment = $this->framework->getAdapter(Environment::class);
foreach ($feeds as $feed) {
$GLOBALS['TL_HEAD'][] = $template->generateFeedTag(
sprintf('%sshare/%s.xml', ($feed->feedBase ?: $environment->get('base')), $feed->alias),
$feed->format,
$feed->title
);
}
} | php | {
"resource": ""
} |
q243477 | ModuleArticle.generate | validation | public function generate($blnNoMarkup=false)
{
if (TL_MODE == 'FE' && !BE_USER_LOGGED_IN && (!$this->published || ($this->start != '' && $this->start > time()) || ($this->stop != '' && $this->stop < time())))
{
return '';
}
$this->type = 'article';
$this->blnNoMarkup = $blnNoMarkup;
// Tag response
if (System::getContainer()->has('fos_http_cache.http.symfony_response_tagger'))
{
/** @var ResponseTagger $responseTagger */
$responseTagger = System::getContainer()->get('fos_http_cache.http.symfony_response_tagger');
$responseTagger->addTags(array('contao.db.tl_article.' . $this->id));
}
return parent::generate();
} | php | {
"resource": ""
} |
q243478 | ModuleArticle.generatePdf | validation | public function generatePdf()
{
$this->headline = $this->title;
$this->printable = false;
// Generate article
$strArticle = $this->replaceInsertTags($this->generate(), false);
$strArticle = html_entity_decode($strArticle, ENT_QUOTES, Config::get('characterSet'));
$strArticle = $this->convertRelativeUrls($strArticle, '', true);
// Remove form elements and JavaScript links
$arrSearch = array
(
'@<form.*</form>@Us',
'@<a [^>]*href="[^"]*javascript:[^>]+>.*</a>@Us'
);
$strArticle = preg_replace($arrSearch, '', $strArticle);
if (empty($GLOBALS['TL_HOOKS']['printArticleAsPdf']))
{
throw new \Exception('No PDF extension found. Did you forget to install contao/tcpdf-bundle?');
}
// HOOK: allow individual PDF routines
if (isset($GLOBALS['TL_HOOKS']['printArticleAsPdf']) && \is_array($GLOBALS['TL_HOOKS']['printArticleAsPdf']))
{
foreach ($GLOBALS['TL_HOOKS']['printArticleAsPdf'] as $callback)
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($strArticle, $this);
}
}
} | php | {
"resource": ""
} |
q243479 | Plugin.handlePrependLocale | validation | private function handlePrependLocale(array $extensionConfigs, ContainerBuilder $container): array
{
if (!$container->hasParameter('prepend_locale')) {
return $extensionConfigs;
}
foreach ($extensionConfigs as $extensionConfig) {
if (isset($extensionConfig['prepend_locale'])) {
return $extensionConfigs;
}
}
@trigger_error('Defining the "prepend_locale" parameter in the parameters.yml file has been deprecated and will no longer work in Contao 5.0. Define the "contao.prepend_locale" parameter in the config.yml file instead.', E_USER_DEPRECATED);
$extensionConfigs[] = [
'prepend_locale' => '%prepend_locale%',
];
return $extensionConfigs;
} | php | {
"resource": ""
} |
q243480 | Plugin.addDefaultServerVersion | validation | private function addDefaultServerVersion(array $extensionConfigs, ContainerBuilder $container): array
{
$params = [];
foreach ($extensionConfigs as $extensionConfig) {
if (isset($extensionConfig['dbal']['connections']['default'])) {
$params[] = $extensionConfig['dbal']['connections']['default'];
}
}
if (!empty($params)) {
$params = array_merge(...$params);
}
$parameterBag = $container->getParameterBag();
foreach ($params as $key => $value) {
$params[$key] = $parameterBag->resolveValue($value);
}
// If there are no DB credentials yet (install tool), we have to set
// the server version to prevent a DBAL exception (see #1422)
try {
$connection = DriverManager::getConnection($params);
$connection->connect();
$connection->close();
} catch (DriverException $e) {
$extensionConfigs[] = [
'dbal' => [
'connections' => [
'default' => [
'server_version' => '5.5',
],
],
],
];
}
return $extensionConfigs;
} | php | {
"resource": ""
} |
q243481 | Controller.getTemplateGroup | validation | public static function getTemplateGroup($strPrefix)
{
$arrTemplates = array();
// Get the default templates
foreach (TemplateLoader::getPrefixedFiles($strPrefix) as $strTemplate)
{
$arrTemplates[$strTemplate][] = 'root';
}
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
$arrCustomized = self::braceGlob($rootDir . '/templates/' . $strPrefix . '*.html5');
// Add the customized templates
if (\is_array($arrCustomized))
{
foreach ($arrCustomized as $strFile)
{
$strTemplate = basename($strFile, strrchr($strFile, '.'));
$arrTemplates[$strTemplate][] = $GLOBALS['TL_LANG']['MSC']['global'];
}
}
// Do not look for back end templates in theme folders (see #5379)
if ($strPrefix != 'be_' && $strPrefix != 'mail_')
{
// Try to select the themes (see #5210)
try
{
$objTheme = ThemeModel::findAll(array('order'=>'name'));
}
catch (\Exception $e)
{
$objTheme = null;
}
// Add the theme templates
if ($objTheme !== null)
{
while ($objTheme->next())
{
if ($objTheme->templates != '')
{
$arrThemeTemplates = self::braceGlob($rootDir . '/' . $objTheme->templates . '/' . $strPrefix . '*.html5');
if (\is_array($arrThemeTemplates))
{
foreach ($arrThemeTemplates as $strFile)
{
$strTemplate = basename($strFile, strrchr($strFile, '.'));
$arrTemplates[$strTemplate][] = $objTheme->name;
}
}
}
}
}
}
// Show the template sources (see #6875)
foreach ($arrTemplates as $k=>$v)
{
$v = array_filter($v, function ($a) {
return $a != 'root';
});
if (empty($v))
{
$arrTemplates[$k] = $k;
}
else
{
$arrTemplates[$k] = $k . ' (' . implode(', ', $v) . ')';
}
}
// Sort the template names
ksort($arrTemplates);
return $arrTemplates;
} | php | {
"resource": ""
} |
q243482 | Controller.getArticle | validation | public static function getArticle($varId, $blnMultiMode=false, $blnIsInsertTag=false, $strColumn='main')
{
/** @var PageModel $objPage */
global $objPage;
if (\is_object($varId))
{
$objRow = $varId;
}
else
{
if (!$varId)
{
return '';
}
$objRow = ArticleModel::findByIdOrAliasAndPid($varId, (!$blnIsInsertTag ? $objPage->id : null));
if ($objRow === null)
{
return false;
}
}
// Check the visibility (see #6311)
if (!static::isVisibleElement($objRow))
{
return '';
}
// Print the article as PDF
if (isset($_GET['pdf']) && Input::get('pdf') == $objRow->id)
{
// Deprecated since Contao 4.0, to be removed in Contao 5.0
if ($objRow->printable == 1)
{
@trigger_error('Setting tl_article.printable to "1" has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
$objArticle = new ModuleArticle($objRow);
$objArticle->generatePdf();
}
elseif ($objRow->printable != '')
{
$options = StringUtil::deserialize($objRow->printable);
if (\is_array($options) && \in_array('pdf', $options))
{
$objArticle = new ModuleArticle($objRow);
$objArticle->generatePdf();
}
}
}
$objRow->headline = $objRow->title;
$objRow->multiMode = $blnMultiMode;
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['getArticle']) && \is_array($GLOBALS['TL_HOOKS']['getArticle']))
{
foreach ($GLOBALS['TL_HOOKS']['getArticle'] as $callback)
{
static::importStatic($callback[0])->{$callback[1]}($objRow);
}
}
$objArticle = new ModuleArticle($objRow, $strColumn);
$strBuffer = $objArticle->generate($blnIsInsertTag);
// Disable indexing if protected
if ($objArticle->protected && !preg_match('/^\s*<!-- indexer::stop/', $strBuffer))
{
$strBuffer = "\n<!-- indexer::stop -->". $strBuffer ."<!-- indexer::continue -->\n";
}
return $strBuffer;
} | php | {
"resource": ""
} |
q243483 | Controller.getContentElement | validation | public static function getContentElement($intId, $strColumn='main')
{
if (\is_object($intId))
{
$objRow = $intId;
}
else
{
if (!\strlen($intId) || $intId < 1)
{
return '';
}
$objRow = ContentModel::findByPk($intId);
if ($objRow === null)
{
return '';
}
}
// Check the visibility (see #6311)
if (!static::isVisibleElement($objRow))
{
return '';
}
$strClass = ContentElement::findClass($objRow->type);
// Return if the class does not exist
if (!class_exists($strClass))
{
static::log('Content element class "'.$strClass.'" (content element "'.$objRow->type.'") does not exist', __METHOD__, TL_ERROR);
return '';
}
$objRow->typePrefix = 'ce_';
/** @var ContentElement $objElement */
$objElement = new $strClass($objRow, $strColumn);
$strBuffer = $objElement->generate();
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['getContentElement']) && \is_array($GLOBALS['TL_HOOKS']['getContentElement']))
{
foreach ($GLOBALS['TL_HOOKS']['getContentElement'] as $callback)
{
$strBuffer = static::importStatic($callback[0])->{$callback[1]}($objRow, $strBuffer, $objElement);
}
}
// Disable indexing if protected
if ($objElement->protected && !preg_match('/^\s*<!-- indexer::stop/', $strBuffer))
{
$strBuffer = "\n<!-- indexer::stop -->". $strBuffer ."<!-- indexer::continue -->\n";
}
return $strBuffer;
} | php | {
"resource": ""
} |
q243484 | Controller.getForm | validation | public static function getForm($varId, $strColumn='main', $blnModule=false)
{
if (\is_object($varId))
{
$objRow = $varId;
}
else
{
if ($varId == '')
{
return '';
}
$objRow = FormModel::findByIdOrAlias($varId);
if ($objRow === null)
{
return '';
}
}
$strClass = $blnModule ? Module::findClass('form') : ContentElement::findClass('form');
if (!class_exists($strClass))
{
static::log('Form class "'.$strClass.'" does not exist', __METHOD__, TL_ERROR);
return '';
}
$objRow->typePrefix = $blnModule ? 'mod_' : 'ce_';
$objRow->form = $objRow->id;
/** @var Form $objElement */
$objElement = new $strClass($objRow, $strColumn);
$strBuffer = $objElement->generate();
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['getForm']) && \is_array($GLOBALS['TL_HOOKS']['getForm']))
{
foreach ($GLOBALS['TL_HOOKS']['getForm'] as $callback)
{
$strBuffer = static::importStatic($callback[0])->{$callback[1]}($objRow, $strBuffer, $objElement);
}
}
return $strBuffer;
} | php | {
"resource": ""
} |
q243485 | Controller.getSpellcheckerString | validation | protected function getSpellcheckerString()
{
System::loadLanguageFile('languages');
$return = array();
$langs = scan(__DIR__ . '/../../languages');
array_unshift($langs, $GLOBALS['TL_LANGUAGE']);
foreach ($langs as $lang)
{
$lang = substr($lang, 0, 2);
if (isset($GLOBALS['TL_LANG']['LNG'][$lang]))
{
$return[$lang] = $GLOBALS['TL_LANG']['LNG'][$lang] . '=' . $lang;
}
}
return '+' . implode(',', array_unique($return));
} | php | {
"resource": ""
} |
q243486 | Controller.getPageStatusIcon | validation | public static function getPageStatusIcon($objPage)
{
$sub = 0;
$image = $objPage->type.'.svg';
// Page not published or not active
if (!$objPage->published || ($objPage->start != '' && $objPage->start > time()) || ($objPage->stop != '' && $objPage->stop < time()))
{
++$sub;
}
// Page hidden from menu
if ($objPage->hide && !\in_array($objPage->type, array('root', 'error_401', 'error_403', 'error_404')))
{
$sub += 2;
}
// Page protected
if ($objPage->protected && !\in_array($objPage->type, array('root', 'error_401', 'error_403', 'error_404')))
{
$sub += 4;
}
// Get the image name
if ($sub > 0)
{
$image = $objPage->type.'_'.$sub.'.svg';
}
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['getPageStatusIcon']) && \is_array($GLOBALS['TL_HOOKS']['getPageStatusIcon']))
{
foreach ($GLOBALS['TL_HOOKS']['getPageStatusIcon'] as $callback)
{
$image = static::importStatic($callback[0])->{$callback[1]}($objPage, $image);
}
}
return $image;
} | php | {
"resource": ""
} |
q243487 | Controller.isVisibleElement | validation | public static function isVisibleElement(Model $objElement)
{
$blnReturn = true;
// Only apply the restrictions in the front end
if (TL_MODE == 'FE')
{
// Protected element
if ($objElement->protected)
{
if (!FE_USER_LOGGED_IN)
{
$blnReturn = false;
}
else
{
$objUser = FrontendUser::getInstance();
if (!\is_array($objUser->groups))
{
$blnReturn = false;
}
else
{
$groups = StringUtil::deserialize($objElement->groups);
if (empty($groups) || !\is_array($groups) || !\count(array_intersect($groups, $objUser->groups)))
{
$blnReturn = false;
}
}
}
}
// Show to guests only
elseif ($objElement->guests && FE_USER_LOGGED_IN)
{
$blnReturn = false;
}
}
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['isVisibleElement']) && \is_array($GLOBALS['TL_HOOKS']['isVisibleElement']))
{
foreach ($GLOBALS['TL_HOOKS']['isVisibleElement'] as $callback)
{
$blnReturn = static::importStatic($callback[0])->{$callback[1]}($objElement, $blnReturn);
}
}
return $blnReturn;
} | php | {
"resource": ""
} |
q243488 | Controller.generateMargin | validation | public static function generateMargin($arrValues, $strType='margin')
{
// Initialize an empty array (see #5217)
if (!\is_array($arrValues))
{
$arrValues = array('top'=>'', 'right'=>'', 'bottom'=>'', 'left'=>'', 'unit'=>'');
}
$top = $arrValues['top'];
$right = $arrValues['right'];
$bottom = $arrValues['bottom'];
$left = $arrValues['left'];
// Try to shorten the definition
if ($top != '' && $right != '' && $bottom != '' && $left != '')
{
if ($top == $right && $top == $bottom && $top == $left)
{
return $strType . ':' . $top . $arrValues['unit'] . ';';
}
elseif ($top == $bottom && $right == $left)
{
return $strType . ':' . $top . $arrValues['unit'] . ' ' . $left . $arrValues['unit'] . ';';
}
elseif ($top != $bottom && $right == $left)
{
return $strType . ':' . $top . $arrValues['unit'] . ' ' . $right . $arrValues['unit'] . ' ' . $bottom . $arrValues['unit'] . ';';
}
else
{
return $strType . ':' . $top . $arrValues['unit'] . ' ' . $right . $arrValues['unit'] . ' ' . $bottom . $arrValues['unit'] . ' ' . $left . $arrValues['unit'] . ';';
}
}
$return = array();
$arrDir = compact('top', 'right', 'bottom', 'left');
foreach ($arrDir as $k=>$v)
{
if ($v != '')
{
$return[] = $strType . '-' . $k . ':' . $v . $arrValues['unit'] . ';';
}
}
return implode($return);
} | php | {
"resource": ""
} |
q243489 | Controller.addToUrl | validation | public static function addToUrl($strRequest, $blnAddRef=true, $arrUnset=array())
{
/** @var Query $query */
$query = new Query(Environment::get('queryString'));
// Remove the request token and referer ID
$query = $query->withoutPairs(array_merge(array('rt', 'ref'), $arrUnset));
// Merge the request string to be added
$query = $query->merge(str_replace('&', '&', $strRequest));
// Add the referer ID
if (isset($_GET['ref']) || ($strRequest != '' && $blnAddRef))
{
$query = $query->merge('ref=' . System::getContainer()->get('request_stack')->getCurrentRequest()->attributes->get('_contao_referer_id'));
}
$uri = $query->getUriComponent();
// The query parser automatically converts %2B to +, so re-convert it here
if (strpos($strRequest, '%2B') !== false)
{
$uri = str_replace('+', '%2B', $uri);
}
return TL_SCRIPT . ampersand($uri);
} | php | {
"resource": ""
} |
q243490 | Controller.redirect | validation | public static function redirect($strLocation, $intStatus=303)
{
$strLocation = str_replace('&', '&', $strLocation);
$strLocation = static::replaceOldBePaths($strLocation);
// Make the location an absolute URL
if (!preg_match('@^https?://@i', $strLocation))
{
$strLocation = Environment::get('base') . ltrim($strLocation, '/');
}
// Ajax request
if (Environment::get('isAjaxRequest'))
{
throw new AjaxRedirectResponseException($strLocation);
}
throw new RedirectResponseException($strLocation, $intStatus);
} | php | {
"resource": ""
} |
q243491 | Controller.replaceOldBePaths | validation | protected static function replaceOldBePaths($strContext)
{
$router = System::getContainer()->get('router');
$generate = function ($route) use ($router)
{
return substr($router->generate($route), \strlen(Environment::get('path')) + 1);
};
$arrMapper = array
(
'contao/confirm.php' => $generate('contao_backend_confirm'),
'contao/file.php' => $generate('contao_backend_file'),
'contao/help.php' => $generate('contao_backend_help'),
'contao/index.php' => $generate('contao_backend_login'),
'contao/main.php' => $generate('contao_backend'),
'contao/page.php' => $generate('contao_backend_page'),
'contao/password.php' => $generate('contao_backend_password'),
'contao/popup.php' => $generate('contao_backend_popup'),
'contao/preview.php' => $generate('contao_backend_preview'),
'contao/switch.php' => $generate('contao_backend_switch')
);
return str_replace(array_keys($arrMapper), $arrMapper, $strContext);
} | php | {
"resource": ""
} |
q243492 | Controller.convertRelativeUrls | validation | public static function convertRelativeUrls($strContent, $strBase='', $blnHrefOnly=false)
{
if ($strBase == '')
{
$strBase = Environment::get('base');
}
$search = $blnHrefOnly ? 'href' : 'href|src';
$arrUrls = preg_split('/(('.$search.')="([^"]+)")/i', $strContent, -1, PREG_SPLIT_DELIM_CAPTURE);
$strContent = '';
for ($i=0, $c=\count($arrUrls); $i<$c; $i+=4)
{
$strContent .= $arrUrls[$i];
if (!isset($arrUrls[$i+2]))
{
continue;
}
$strAttribute = $arrUrls[$i+2];
$strUrl = $arrUrls[$i+3];
if (!preg_match('@^(?:[a-z0-9]+:|#)@i', $strUrl))
{
$strUrl = $strBase . (($strUrl != '/') ? $strUrl : '');
}
$strContent .= $strAttribute . '="' . $strUrl . '"';
}
return $strContent;
} | php | {
"resource": ""
} |
q243493 | Controller.redirectToFrontendPage | validation | protected function redirectToFrontendPage($intPage, $strArticle=null, $blnReturn=false)
{
if (($intPage = (int) $intPage) <= 0)
{
return '';
}
$objPage = PageModel::findWithDetails($intPage);
if ($objPage === null)
{
return '';
}
$strParams = null;
// Add the /article/ fragment (see #673)
if ($strArticle !== null && ($objArticle = ArticleModel::findByAlias($strArticle)) !== null)
{
$strParams = '/articles/' . (($objArticle->inColumn != 'main') ? $objArticle->inColumn . ':' : '') . $strArticle;
}
$strUrl = $objPage->getFrontendUrl($strParams);
// Make sure the URL is absolute (see #4332)
if (strncmp($strUrl, 'http://', 7) !== 0 && strncmp($strUrl, 'https://', 8) !== 0)
{
$strUrl = Environment::get('base') . $strUrl;
}
if (!$blnReturn)
{
$this->redirect($strUrl);
}
return $strUrl;
} | php | {
"resource": ""
} |
q243494 | Controller.getParentEntries | validation | protected function getParentEntries($strTable, $intId)
{
// No parent table
if (!isset($GLOBALS['TL_DCA'][$strTable]['config']['ptable']))
{
return '';
}
$arrParent = array();
do
{
// Get the pid
$objParent = $this->Database->prepare("SELECT pid FROM " . $strTable . " WHERE id=?")
->limit(1)
->execute($intId);
if ($objParent->numRows < 1)
{
break;
}
// Store the parent table information
$strTable = $GLOBALS['TL_DCA'][$strTable]['config']['ptable'];
$intId = $objParent->pid;
// Add the log entry
$arrParent[] = $strTable .'.id=' . $intId;
// Load the data container of the parent table
$this->loadDataContainer($strTable);
}
while ($intId && isset($GLOBALS['TL_DCA'][$strTable]['config']['ptable']));
if (empty($arrParent))
{
return '';
}
return ' (parent records: ' . implode(', ', $arrParent) . ')';
} | php | {
"resource": ""
} |
q243495 | Controller.eliminateNestedPaths | validation | protected function eliminateNestedPaths($arrPaths)
{
$arrPaths = array_filter($arrPaths);
if (empty($arrPaths) || !\is_array($arrPaths))
{
return array();
}
$nested = array();
foreach ($arrPaths as $path)
{
$nested[] = preg_grep('/^' . preg_quote($path, '/') . '\/.+/', $arrPaths);
}
if (!empty($nested))
{
$nested = array_merge(...$nested);
}
return array_values(array_diff($arrPaths, $nested));
} | php | {
"resource": ""
} |
q243496 | Controller.eliminateNestedPages | validation | protected function eliminateNestedPages($arrPages, $strTable=null, $blnSorting=false)
{
if (empty($arrPages) || !\is_array($arrPages))
{
return array();
}
if (!$strTable)
{
$strTable = 'tl_page';
}
// Thanks to Andreas Schempp (see #2475 and #3423)
$arrPages = array_intersect($arrPages, $this->Database->getChildRecords(0, $strTable, $blnSorting));
$arrPages = array_values(array_diff($arrPages, $this->Database->getChildRecords($arrPages, $strTable, $blnSorting)));
return $arrPages;
} | php | {
"resource": ""
} |
q243497 | Controller.setStaticUrls | validation | public static function setStaticUrls()
{
if (\defined('TL_FILES_URL'))
{
return;
}
if (\func_num_args() > 0)
{
@trigger_error('Using Controller::setStaticUrls() has been deprecated and will no longer work in Contao 5.0. Use the asset contexts instead.', E_USER_DEPRECATED);
if (!isset($GLOBALS['objPage']))
{
$GLOBALS['objPage'] = func_get_arg(0);
}
}
\define('TL_ASSETS_URL', System::getContainer()->get('contao.assets.assets_context')->getStaticUrl());
\define('TL_FILES_URL', System::getContainer()->get('contao.assets.files_context')->getStaticUrl());
// Deprecated since Contao 4.0, to be removed in Contao 5.0
\define('TL_SCRIPT_URL', TL_ASSETS_URL);
\define('TL_PLUGINS_URL', TL_ASSETS_URL);
} | php | {
"resource": ""
} |
q243498 | Controller.addStaticUrlTo | validation | public static function addStaticUrlTo($script, ContaoContext $context = null)
{
// Absolute URLs
if (preg_match('@^https?://@', $script))
{
return $script;
}
if ($context === null)
{
$context = System::getContainer()->get('contao.assets.assets_context');
}
if ($strStaticUrl = $context->getStaticUrl())
{
return $strStaticUrl . $script;
}
return $script;
} | php | {
"resource": ""
} |
q243499 | Controller.prepareForWidget | validation | protected function prepareForWidget($arrData, $strName, $varValue=null, $strField='', $strTable='')
{
@trigger_error('Using Controller::prepareForWidget() has been deprecated and will no longer work in Contao 5.0. Use Widget::getAttributesFromDca() instead.', E_USER_DEPRECATED);
return Widget::getAttributesFromDca($arrData, $strName, $varValue, $strField, $strTable);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.