_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q243100 | Files.copy | validation | public function copy($strSource, $strDestination)
{
$this->validate($strSource, $strDestination);
return copy($this->strRootDir . '/' . $strSource, $this->strRootDir . '/' . $strDestination);
} | php | {
"resource": ""
} |
q243101 | Files.rcopy | validation | public function rcopy($strSource, $strDestination)
{
$this->validate($strSource, $strDestination);
$this->mkdir($strDestination);
$arrFiles = scan($this->strRootDir . '/' . $strSource, true);
foreach ($arrFiles as $strFile)
{
if (is_dir($this->strRootDir . '/' . $strSource . '/' . $strFile))
{
$this->rcopy($strSource . '/' . $strFile, $strDestination . '/' . $strFile);
}
else
{
$this->copy($strSource . '/' . $strFile, $strDestination . '/' . $strFile);
}
}
} | php | {
"resource": ""
} |
q243102 | Files.chmod | validation | public function chmod($strFile, $varMode)
{
$this->validate($strFile);
return chmod($this->strRootDir . '/' . $strFile, $varMode);
} | php | {
"resource": ""
} |
q243103 | Files.move_uploaded_file | validation | public function move_uploaded_file($strSource, $strDestination)
{
$this->validate($strSource, $strDestination);
return move_uploaded_file($strSource, $this->strRootDir . '/' . $strDestination);
} | php | {
"resource": ""
} |
q243104 | Files.validate | validation | protected function validate()
{
foreach (\func_get_args() as $strPath)
{
if ($strPath == '') // see #5795
{
throw new \RuntimeException('No file or folder name given');
}
elseif (Validator::isInsecurePath($strPath))
{
throw new \RuntimeException('Invalid file or folder name ' . $strPath);
}
}
} | php | {
"resource": ""
} |
q243105 | ClearSessionDataListener.onKernelResponse | validation | public function onKernelResponse(FilterResponseEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
if ($request->isMethod('POST')) {
return;
}
if (null === ($session = $request->getSession()) || !$session->isStarted()) {
return;
}
$this->clearLegacyAttributeBags('FE_DATA');
$this->clearLegacyAttributeBags('BE_DATA');
$this->clearLegacyFormData();
} | php | {
"resource": ""
} |
q243106 | tl_newsletter.addSenderPlaceholder | validation | public function addSenderPlaceholder($varValue, Contao\DataContainer $dc)
{
if ($dc->activeRecord && $dc->activeRecord->pid)
{
$objChannel = $this->Database->prepare("SELECT sender FROM tl_newsletter_channel WHERE id=?")
->execute($dc->activeRecord->pid);
$GLOBALS['TL_DCA'][$dc->table]['fields'][$dc->field]['eval']['placeholder'] = $objChannel->sender;
}
return $varValue;
} | php | {
"resource": ""
} |
q243107 | tl_newsletter.addSenderNamePlaceholder | validation | public function addSenderNamePlaceholder($varValue, Contao\DataContainer $dc)
{
if ($dc->activeRecord && $dc->activeRecord->pid)
{
$objChannel = $this->Database->prepare("SELECT senderName FROM tl_newsletter_channel WHERE id=?")
->execute($dc->activeRecord->pid);
$GLOBALS['TL_DCA'][$dc->table]['fields'][$dc->field]['eval']['placeholder'] = $objChannel->senderName;
}
return $varValue;
} | php | {
"resource": ""
} |
q243108 | ContaoUserProvider.validateSessionLifetime | validation | private function validateSessionLifetime(User $user): void
{
if (!$this->session->isStarted()) {
return;
}
/** @var Config $config */
$config = $this->framework->getAdapter(Config::class);
$timeout = (int) $config->get('sessionTimeout');
if ($timeout > 0 && (time() - $this->session->getMetadataBag()->getLastUsed()) < $timeout) {
return;
}
if (null !== $this->logger) {
$this->logger->info(
sprintf('User "%s" has been logged out automatically due to inactivity', $user->username),
['contao' => new ContaoContext(__METHOD__, ContaoContext::ACCESS, $user->username)]
);
}
throw new UsernameNotFoundException(
sprintf('User "%s" has been logged out automatically due to inactivity.', $user->username)
);
} | php | {
"resource": ""
} |
q243109 | Messages.maintenanceCheck | validation | public function maintenanceCheck()
{
$this->import(BackendUser::class, 'User');
if (!$this->User->hasAccess('maintenance', 'modules'))
{
return '';
}
try
{
if (System::getContainer()->get('lexik_maintenance.driver.factory')->getDriver()->isExists())
{
return '<p class="tl_error">' . $GLOBALS['TL_LANG']['MSC']['maintenanceEnabled'] . '</p>';
}
}
catch (\Exception $e)
{
// ignore
}
return '';
} | php | {
"resource": ""
} |
q243110 | PhpFileLoader.parseFile | validation | private function parseFile(string $file): array
{
$code = '';
$namespace = '';
$buffer = false;
$stream = new \PHP_Token_Stream($file);
foreach ($stream as $token) {
switch (true) {
case $token instanceof \PHP_Token_OPEN_TAG:
case $token instanceof \PHP_Token_CLOSE_TAG:
// remove
break;
case false !== $buffer:
$buffer .= $token;
if (';' === (string) $token) {
$code .= $this->handleDeclare($buffer);
$buffer = false;
}
break;
case $token instanceof \PHP_Token_NAMESPACE:
if ('{' === $token->getName()) {
$namespace = false;
$code .= $token;
} else {
$namespace = $token->getName();
$stream->seek($token->getEndTokenId());
}
break;
case $token instanceof \PHP_Token_DECLARE:
$buffer = (string) $token;
break;
default:
$code .= $token;
}
}
return [$code, $namespace];
} | php | {
"resource": ""
} |
q243111 | WebsiteRootsConfigProvider.isCorsRequest | validation | private function isCorsRequest(Request $request): bool
{
return $request->headers->has('Origin')
&& $request->headers->get('Origin') !== $request->getSchemeAndHttpHost()
;
} | php | {
"resource": ""
} |
q243112 | FileSelector.generateAjax | validation | public function generateAjax($strFolder, $strField, $level, $mount=false)
{
if (!Environment::get('isAjaxRequest'))
{
return '';
}
$this->strField = $strField;
$this->loadDataContainer($this->strTable);
// Load the current values
switch ($GLOBALS['TL_DCA'][$this->strTable]['config']['dataContainer'])
{
case 'File':
if (Config::get($this->strField) != '')
{
$this->varValue = Config::get($this->strField);
}
break;
case 'Table':
$this->import(Database::class, 'Database');
if (!$this->Database->fieldExists($this->strField, $this->strTable))
{
break;
}
$objField = $this->Database->prepare("SELECT " . Database::quoteIdentifier($this->strField) . " FROM " . $this->strTable . " WHERE id=?")
->limit(1)
->execute($this->strId);
if ($objField->numRows)
{
$this->varValue = StringUtil::deserialize($objField->{$this->strField});
}
break;
}
$this->convertValuesToPaths();
if ($this->extensions != '')
{
$this->arrValidFileTypes = StringUtil::trimsplit(',', $this->extensions);
}
return $this->renderFiletree(System::getContainer()->getParameter('kernel.project_dir') . '/' . $strFolder, ($level * 20), $mount, $this->isProtectedPath($strFolder));
} | php | {
"resource": ""
} |
q243113 | FileSelector.convertValuesToPaths | validation | protected function convertValuesToPaths()
{
if (empty($this->varValue))
{
return;
}
if (!\is_array($this->varValue))
{
$this->varValue = array($this->varValue);
}
elseif (empty($this->varValue[0]))
{
$this->varValue = array();
}
if (empty($this->varValue))
{
return;
}
// TinyMCE will pass the path instead of the ID
if (strpos($this->varValue[0], Config::get('uploadPath') . '/') === 0)
{
return;
}
// Ignore the numeric IDs when in switch mode (TinyMCE)
if (Input::get('switch'))
{
return;
}
// Return if the custom path is not within the upload path (see #8562)
if ($this->path != '' && strpos($this->path, Config::get('uploadPath') . '/') !== 0)
{
return;
}
$objFiles = FilesModel::findMultipleByIds($this->varValue);
if ($objFiles !== null)
{
$this->varValue = array_values($objFiles->fetchEach('path'));
}
} | php | {
"resource": ""
} |
q243114 | AddAssetsPackagesPass.addBundles | validation | private function addBundles(ContainerBuilder $container): void
{
$packages = $container->getDefinition('assets.packages');
$context = new Reference('contao.assets.assets_context');
if ($container->hasDefinition('assets._version_default')) {
$version = new Reference('assets._version_default');
} else {
$version = new Reference('assets.empty_version_strategy');
}
$bundles = $container->getParameter('kernel.bundles');
$meta = $container->getParameter('kernel.bundles_metadata');
foreach ($bundles as $name => $class) {
if (!is_dir($meta[$name]['path'].'/Resources/public')) {
continue;
}
$packageVersion = $version;
$packageName = $this->getBundlePackageName($name);
$serviceId = 'assets._package_'.$packageName;
$basePath = 'bundles/'.preg_replace('/bundle$/', '', strtolower($name));
if (is_file($meta[$name]['path'].'/Resources/public/manifest.json')) {
$def = new ChildDefinition('assets.json_manifest_version_strategy');
$def->replaceArgument(0, $meta[$name]['path'].'/Resources/public/manifest.json');
$container->setDefinition('assets._version_'.$packageName, $def);
$packageVersion = new Reference('assets._version_'.$packageName);
}
$container->setDefinition($serviceId, $this->createPackageDefinition($basePath, $packageVersion, $context));
$packages->addMethodCall('addPackage', [$packageName, new Reference($serviceId)]);
}
} | php | {
"resource": ""
} |
q243115 | AddAssetsPackagesPass.addComponents | validation | private function addComponents(ContainerBuilder $container): void
{
$packages = $container->getDefinition('assets.packages');
$context = new Reference('contao.assets.assets_context');
foreach (Versions::VERSIONS as $name => $version) {
if (0 !== strncmp('contao-components/', $name, 18)) {
continue;
}
$serviceId = 'assets._package_'.$name;
$basePath = 'assets/'.substr($name, 18);
$version = $this->createVersionStrategy($container, $version, $name);
$container->setDefinition($serviceId, $this->createPackageDefinition($basePath, $version, $context));
$packages->addMethodCall('addPackage', [$name, new Reference($serviceId)]);
}
} | php | {
"resource": ""
} |
q243116 | AddAssetsPackagesPass.getBundlePackageName | validation | private function getBundlePackageName(string $className): string
{
if ('Bundle' === substr($className, -6)) {
$className = substr($className, 0, -6);
}
return Container::underscore($className);
} | php | {
"resource": ""
} |
q243117 | DC_Folder.create | validation | public function create()
{
if ($GLOBALS['TL_DCA'][$this->strTable]['config']['notCreatable'])
{
throw new InternalServerErrorException('Table "' . $this->strTable . '" is not creatable.');
}
$this->import(Files::class, 'Files');
$strFolder = Input::get('pid', true);
if ($strFolder == '' || !file_exists($this->strRootDir . '/' . $strFolder) || !$this->isMounted($strFolder))
{
throw new AccessDeniedException('Folder "' . $strFolder . '" is not mounted or is not a directory.');
}
/** @var Session $objSession */
$objSession = System::getContainer()->get('session');
// Empty clipboard
$arrClipboard = $objSession->get('CLIPBOARD');
$arrClipboard[$this->strTable] = array();
$objSession->set('CLIPBOARD', $arrClipboard);
$this->Files->mkdir($strFolder . '/__new__');
$this->redirect(html_entity_decode($this->switchToEdit($strFolder . '/__new__')));
} | php | {
"resource": ""
} |
q243118 | DC_Folder.delete | validation | public function delete($source=null)
{
if ($GLOBALS['TL_DCA'][$this->strTable]['config']['notDeletable'])
{
throw new InternalServerErrorException('Table "' . $this->strTable . '" is not deletable.');
}
$blnDoNotRedirect = ($source !== null);
if ($source === null)
{
$source = $this->intId;
}
$this->isValid($source);
// Delete the file or folder
if (!file_exists($this->strRootDir . '/' . $source) || !$this->isMounted($source))
{
throw new AccessDeniedException('File or folder "' . $source . '" is not mounted or cannot be found.');
}
// Call the ondelete_callback
if (\is_array($GLOBALS['TL_DCA'][$this->strTable]['config']['ondelete_callback']))
{
foreach ($GLOBALS['TL_DCA'][$this->strTable]['config']['ondelete_callback'] as $callback)
{
if (\is_array($callback))
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($source, $this);
}
elseif (\is_callable($callback))
{
$callback($source, $this);
}
}
}
$this->import(Files::class, 'Files');
// Delete the folder or file
if (is_dir($this->strRootDir . '/' . $source))
{
$this->Files->rrdir($source);
$strWebDir = StringUtil::stripRootDir(System::getContainer()->getParameter('contao.web_dir'));
// Also delete the symlink (see #710)
if (is_link($this->strRootDir . '/' . $strWebDir . '/' . $source))
{
$this->Files->delete($strWebDir. '/' . $source);
}
}
else
{
$this->Files->delete($source);
}
// Update the database AFTER the resource has been deleted
if ($this->blnIsDbAssisted && Dbafs::shouldBeSynchronized($source))
{
Dbafs::deleteResource($source);
}
// Add a log entry
$this->log('File or folder "' . $source . '" has been deleted', __METHOD__, TL_FILES);
// Redirect
if (!$blnDoNotRedirect)
{
$this->redirect($this->getReferer());
}
} | php | {
"resource": ""
} |
q243119 | DC_Folder.deleteAll | validation | public function deleteAll()
{
if ($GLOBALS['TL_DCA'][$this->strTable]['config']['notDeletable'])
{
throw new InternalServerErrorException('Table "' . $this->strTable . '" is not deletable.');
}
/** @var Session $objSession */
$objSession = System::getContainer()->get('session');
$session = $objSession->all();
$ids = $session['CURRENT']['IDS'];
if (!empty($ids) && \is_array($ids))
{
$ids = $this->eliminateNestedPaths($ids); // see #941
foreach ($ids as $id)
{
$this->delete($id); // do not urldecode() here (see #6840)
}
}
$this->redirect($this->getReferer());
} | php | {
"resource": ""
} |
q243120 | DC_Folder.protect | validation | public function protect()
{
@trigger_error('Using DC_Folder::protect() has been deprecated and will no longer work in Contao 5.0. Use Contao\Folder::protect() and Contao\Folder::unprotect() instead.', E_USER_DEPRECATED);
if (!is_dir($this->strRootDir . '/' . $this->intId))
{
throw new InternalServerErrorException('Resource "' . $this->intId . '" is not a directory.');
}
// Protect or unprotect the folder
if (file_exists($this->strRootDir . '/' . $this->intId . '/.public'))
{
$objFolder = new Folder($this->intId);
$objFolder->protect();
$this->import(Automator::class, 'Automator');
$this->Automator->generateSymlinks();
$this->log('Folder "'.$this->intId.'" has been protected', __METHOD__, TL_FILES);
}
else
{
$objFolder = new Folder($this->intId);
$objFolder->unprotect();
$this->import(Automator::class, 'Automator');
$this->Automator->generateSymlinks();
$this->log('The protection from folder "'.$this->intId.'" has been removed', __METHOD__, TL_FILES);
}
$this->redirect($this->getReferer());
} | php | {
"resource": ""
} |
q243121 | DC_Folder.isMounted | validation | protected function isMounted($strFolder)
{
if ($strFolder == '')
{
return false;
}
if (empty($this->arrFilemounts))
{
return true;
}
$path = $strFolder;
while (\is_array($this->arrFilemounts) && substr_count($path, '/') > 0)
{
if (\in_array($path, $this->arrFilemounts))
{
return true;
}
$path = \dirname($path);
}
return false;
} | php | {
"resource": ""
} |
q243122 | DC_Folder.isValid | validation | protected function isValid($strFile)
{
$strFolder = Input::get('pid', true);
// Check the path
if (Validator::isInsecurePath($strFile))
{
throw new AccessDeniedException('Invalid file name "' . $strFile . '" (hacking attempt).');
}
elseif (Validator::isInsecurePath($strFolder))
{
throw new AccessDeniedException('Invalid folder name "' . $strFolder . '" (hacking attempt).');
}
// Check for valid file types
if (!empty($this->arrValidFileTypes) && is_file($this->strRootDir . '/' . $strFile))
{
$fileinfo = preg_replace('/.*\.(.*)$/u', '$1', $strFile);
if (!\in_array(strtolower($fileinfo), $this->arrValidFileTypes))
{
throw new AccessDeniedException('File "' . $strFile . '" is not an allowed file type.');
}
}
// Check whether the file is within the files directory
if (!preg_match('/^'.preg_quote(Config::get('uploadPath'), '/').'/i', $strFile))
{
throw new AccessDeniedException('File or folder "' . $strFile . '" is not within the files directory.');
}
// Check whether the parent folder is within the files directory
if ($strFolder && !preg_match('/^'.preg_quote(Config::get('uploadPath'), '/').'/i', $strFolder))
{
throw new AccessDeniedException('Parent folder "' . $strFolder . '" is not within the files directory.');
}
// Do not allow file operations on root folders
if (Input::get('act') == 'edit' || Input::get('act') == 'paste' || Input::get('act') == 'delete')
{
$this->import(BackendUser::class, 'User');
if (!$this->User->isAdmin && \in_array($strFile, $this->User->filemounts))
{
throw new AccessDeniedException('Attempt to edit, copy, move or delete the root folder "' . $strFile . '".');
}
}
return true;
} | php | {
"resource": ""
} |
q243123 | DC_Folder.getMD5Folders | validation | protected function getMD5Folders($strPath)
{
$arrFiles = array();
foreach (scan($this->strRootDir . '/' . $strPath) as $strFile)
{
if (!is_dir($this->strRootDir . '/' . $strPath . '/' . $strFile))
{
continue;
}
$arrFiles[substr(md5($this->strRootDir . '/' . $strPath . '/' . $strFile), 0, 8)] = 1;
// Do not use array_merge() here (see #8105)
foreach ($this->getMD5Folders($strPath . '/' . $strFile) as $k=>$v)
{
$arrFiles[$k] = $v;
}
}
return $arrFiles;
} | php | {
"resource": ""
} |
q243124 | QueryBuilder.find | validation | public static function find(array $arrOptions)
{
$objBase = DcaExtractor::getInstance($arrOptions['table']);
if (!$objBase->hasRelations())
{
$strQuery = "SELECT * FROM " . $arrOptions['table'];
}
else
{
$arrJoins = array();
$arrFields = array($arrOptions['table'] . ".*");
$intCount = 0;
foreach ($objBase->getRelations() as $strKey=>$arrConfig)
{
// Automatically join the single-relation records
if ($arrConfig['load'] == 'eager' || $arrOptions['eager'])
{
if ($arrConfig['type'] == 'hasOne' || $arrConfig['type'] == 'belongsTo')
{
++$intCount;
$objRelated = DcaExtractor::getInstance($arrConfig['table']);
foreach (array_keys($objRelated->getFields()) as $strField)
{
$arrFields[] = 'j' . $intCount . '.' . Database::quoteIdentifier($strField) . ' AS ' . $strKey . '__' . $strField;
}
$arrJoins[] = " LEFT JOIN " . $arrConfig['table'] . " j$intCount ON " . $arrOptions['table'] . "." . Database::quoteIdentifier($strKey) . "=j$intCount." . $arrConfig['field'];
}
}
}
// Generate the query
$strQuery = "SELECT " . implode(', ', $arrFields) . " FROM " . $arrOptions['table'] . implode("", $arrJoins);
}
// Where condition
if (isset($arrOptions['column']))
{
$strQuery .= " WHERE " . (\is_array($arrOptions['column']) ? implode(" AND ", $arrOptions['column']) : $arrOptions['table'] . '.' . Database::quoteIdentifier($arrOptions['column']) . "=?");
}
// Group by
if (isset($arrOptions['group']))
{
$strQuery .= " GROUP BY " . $arrOptions['group'];
}
// Having (see #6446)
if (isset($arrOptions['having']))
{
$strQuery .= " HAVING " . $arrOptions['having'];
}
// Order by
if (isset($arrOptions['order']))
{
$strQuery .= " ORDER BY " . $arrOptions['order'];
}
return $strQuery;
} | php | {
"resource": ""
} |
q243125 | QueryBuilder.count | validation | public static function count(array $arrOptions)
{
$strQuery = "SELECT COUNT(*) AS count FROM " . $arrOptions['table'];
if ($arrOptions['column'] !== null)
{
$strQuery .= " WHERE " . (\is_array($arrOptions['column']) ? implode(" AND ", $arrOptions['column']) : $arrOptions['table'] . '.' . Database::quoteIdentifier($arrOptions['column']) . "=?");
}
return $strQuery;
} | php | {
"resource": ""
} |
q243126 | Pagination.getItemsAsString | validation | public function getItemsAsString($strSeparator=' ')
{
$arrLinks = array();
foreach ($this->getItemsAsArray() as $arrItem)
{
if ($arrItem['href'] === null)
{
$arrLinks[] = sprintf('<li><strong class="active">%s</strong></li>', $arrItem['page']);
}
else
{
$arrLinks[] = sprintf('<li><a href="%s" class="link" title="%s">%s</a></li>', $arrItem['href'], $arrItem['title'], $arrItem['page']);
}
}
return implode($strSeparator, $arrLinks);
} | php | {
"resource": ""
} |
q243127 | Pagination.getItemsAsArray | validation | public function getItemsAsArray()
{
$arrLinks = array();
$intNumberOfLinks = floor($this->intNumberOfLinks / 2);
$intFirstOffset = $this->intPage - $intNumberOfLinks - 1;
if ($intFirstOffset > 0)
{
$intFirstOffset = 0;
}
$intLastOffset = $this->intPage + $intNumberOfLinks - $this->intTotalPages;
if ($intLastOffset < 0)
{
$intLastOffset = 0;
}
$intFirstLink = $this->intPage - $intNumberOfLinks - $intLastOffset;
if ($intFirstLink < 1)
{
$intFirstLink = 1;
}
$intLastLink = $this->intPage + $intNumberOfLinks - $intFirstOffset;
if ($intLastLink > $this->intTotalPages)
{
$intLastLink = $this->intTotalPages;
}
for ($i=$intFirstLink; $i<=$intLastLink; $i++)
{
if ($i == $this->intPage)
{
$arrLinks[] = array
(
'page' => $i,
'href' => null,
'title' => null
);
}
else
{
$arrLinks[] = array
(
'page' => $i,
'href' => $this->linkToPage($i),
'title' => StringUtil::specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['goToPage'], $i))
);
}
}
return $arrLinks;
} | php | {
"resource": ""
} |
q243128 | Pagination.linkToPage | validation | protected function linkToPage($intPage)
{
if ($intPage <= 1 && !$this->blnForceParam)
{
return ampersand($this->strUrl);
}
else
{
return ampersand($this->strUrl) . $this->strVarConnector . $this->strParameter . '=' . $intPage;
}
} | php | {
"resource": ""
} |
q243129 | PageSelector.generateAjax | validation | public function generateAjax($id, $strField, $level)
{
if (!Environment::get('isAjaxRequest'))
{
return '';
}
$this->strField = $strField;
$this->loadDataContainer($this->strTable);
// Load current values
switch ($GLOBALS['TL_DCA'][$this->strTable]['config']['dataContainer'])
{
case 'File':
if (Config::get($this->strField) != '')
{
$this->varValue = Config::get($this->strField);
}
break;
case 'Table':
if (!$this->Database->fieldExists($this->strField, $this->strTable))
{
break;
}
$objField = $this->Database->prepare("SELECT " . Database::quoteIdentifier($this->strField) . " FROM " . $this->strTable . " WHERE id=?")
->limit(1)
->execute($this->strId);
if ($objField->numRows)
{
$this->varValue = StringUtil::deserialize($objField->{$this->strField});
}
break;
}
$this->getPathNodes();
// Load the requested nodes
$tree = '';
$level *= 20;
$objPage = $this->Database->prepare("SELECT id FROM tl_page WHERE pid=? ORDER BY sorting")
->execute($id);
while ($objPage->next())
{
$tree .= $this->renderPagetree($objPage->id, $level);
}
return $tree;
} | php | {
"resource": ""
} |
q243130 | PageSelector.getPathNodes | validation | protected function getPathNodes()
{
if (!$this->varValue)
{
return;
}
if (!\is_array($this->varValue))
{
$this->varValue = array($this->varValue);
}
foreach ($this->varValue as $id)
{
$arrPids = $this->Database->getParentRecords($id, 'tl_page');
array_shift($arrPids); // the first element is the ID of the page itself
$this->arrNodes = array_merge($this->arrNodes, $arrPids);
}
} | php | {
"resource": ""
} |
q243131 | HtaccessAnalyzer.grantsAccess | validation | public function grantsAccess(): bool
{
$content = array_filter(file((string) $this->file));
foreach ($content as $line) {
if ($this->hasRequireGranted($line)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q243132 | HtaccessAnalyzer.hasRequireGranted | validation | private function hasRequireGranted(string $line): bool
{
if ($this->isComment($line)) {
return false;
}
return (false !== stripos($line, 'Allow from all')) || (false !== stripos($line, 'Require all granted'));
} | php | {
"resource": ""
} |
q243133 | SyncExclude.accept | validation | public function accept()
{
// The resource is to be ignored
if (strncmp($this->current()->getFilename(), '.', 1) === 0)
{
return false;
}
$strPath = $this->current()->getPathname();
if (is_file($strPath))
{
$strPath = \dirname($strPath);
}
$objFolder = new Folder(StringUtil::stripRootDir($strPath));
return !$objFolder->isUnsynchronized();
} | php | {
"resource": ""
} |
q243134 | AuthenticationFailureHandler.onAuthenticationFailure | validation | public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
{
if (null === $this->logger) {
return parent::onAuthenticationFailure($request, $exception);
}
if ($exception instanceof AccountStatusException && ($user = $exception->getUser()) instanceof UserInterface) {
$username = $user->getUsername();
} else {
$username = $request->request->get('username');
}
$this->logger->info(
$exception->getMessage(),
['contao' => new ContaoContext(__METHOD__, ContaoContext::ACCESS, $username)]
);
return parent::onAuthenticationFailure($request, $exception);
} | php | {
"resource": ""
} |
q243135 | ContentImage.generate | validation | public function generate()
{
if ($this->singleSRC == '')
{
return '';
}
$objFile = FilesModel::findByUuid($this->singleSRC);
if ($objFile === null || !is_file(System::getContainer()->getParameter('kernel.project_dir') . '/' . $objFile->path))
{
return '';
}
$this->singleSRC = $objFile->path;
$this->objFilesModel = $objFile;
return parent::generate();
} | php | {
"resource": ""
} |
q243136 | InstallWebDirCommand.addHtaccess | validation | private function addHtaccess(string $webDir): void
{
$htaccess = __DIR__.'/../Resources/skeleton/web/.htaccess';
if (!file_exists($webDir.'/.htaccess')) {
$this->fs->copy($htaccess, $webDir.'/.htaccess', true);
$this->io->writeln('Added the <comment>web/.htaccess</comment> file.');
return;
}
$existingContent = file_get_contents($webDir.'/.htaccess');
// Return if there already is a rewrite rule
if (preg_match('/^\s*RewriteRule\s/im', $existingContent)) {
return;
}
$this->fs->dumpFile($webDir.'/.htaccess', $existingContent."\n\n".file_get_contents($htaccess));
$this->io->writeln('Updated the <comment>web/.htaccess</comment> file.');
} | php | {
"resource": ""
} |
q243137 | InstallWebDirCommand.purgeOldFiles | validation | private function purgeOldFiles(string $webDir): void
{
if (file_exists($webDir.'/app_dev.php')) {
$this->fs->remove($webDir.'/app_dev.php');
$this->io->writeln('Deleted the <comment>web/app_dev.php</comment> file.');
}
if (file_exists($webDir.'/install.php')) {
$this->fs->remove($webDir.'/install.php');
$this->io->writeln('Deleted the <comment>web/install.php</comment> file.');
}
} | php | {
"resource": ""
} |
q243138 | InstallWebDirCommand.isExistingOptionalFile | validation | private function isExistingOptionalFile(SplFileInfo $file, string $webDir): bool
{
$path = $file->getRelativePathname();
return 'robots.txt' === $path && $this->fs->exists($webDir.'/'.$path);
} | php | {
"resource": ""
} |
q243139 | UserChecker.checkIfAccountIsActive | validation | private function checkIfAccountIsActive(User $user): void
{
/** @var Config $config */
$config = $this->framework->getAdapter(Config::class);
$start = (int) $user->start;
$stop = (int) $user->stop;
$time = Date::floorToMinute(time());
$notActiveYet = $start && $start > $time;
$notActiveAnymore = $stop && $stop <= ($time + 60);
$logMessage = '';
if ($notActiveYet) {
$logMessage = sprintf(
'The account is not active yet (activation date: %s)',
Date::parse($config->get('dateFormat'), $start)
);
}
if ($notActiveAnymore) {
$logMessage = sprintf(
'The account is not active anymore (deactivation date: %s)',
Date::parse($config->get('dateFormat'), $stop)
);
}
if ('' === $logMessage) {
return;
}
$ex = new DisabledException($logMessage);
$ex->setUser($user);
throw $ex;
} | php | {
"resource": ""
} |
q243140 | ImageFactory.createConfig | validation | private function createConfig($size, ImageInterface $image): array
{
if (!\is_array($size)) {
$size = [0, 0, $size];
}
$config = new ResizeConfiguration();
if (isset($size[2]) && is_numeric($size[2])) {
/** @var ImageSizeModel $imageModel */
$imageModel = $this->framework->getAdapter(ImageSizeModel::class);
$imageSize = $imageModel->findByPk($size[2]);
if (null !== $imageSize) {
$config
->setWidth($imageSize->width)
->setHeight($imageSize->height)
->setMode($imageSize->resizeMode)
->setZoomLevel($imageSize->zoom)
;
}
return [$config, null];
}
if (!empty($size[0])) {
$config->setWidth($size[0]);
}
if (!empty($size[1])) {
$config->setHeight($size[1]);
}
if (!isset($size[2]) || 1 !== substr_count($size[2], '_')) {
if (!empty($size[2])) {
$config->setMode($size[2]);
}
return [$config, null];
}
$config->setMode(ResizeConfigurationInterface::MODE_CROP);
return [$config, $this->getImportantPartFromLegacyMode($image, $size[2])];
} | php | {
"resource": ""
} |
q243141 | ImageFactory.createImportantPart | validation | private function createImportantPart(ImageInterface $image): ?ImportantPart
{
/** @var FilesModel $filesModel */
$filesModel = $this->framework->getAdapter(FilesModel::class);
$file = $filesModel->findByPath($image->getPath());
if (null === $file || !$file->importantPartWidth || !$file->importantPartHeight) {
return null;
}
$imageSize = $image->getDimensions()->getSize();
if (
$file->importantPartX + $file->importantPartWidth > $imageSize->getWidth()
|| $file->importantPartY + $file->importantPartHeight > $imageSize->getHeight()
) {
return null;
}
return new ImportantPart(
new Point((int) $file->importantPartX, (int) $file->importantPartY),
new Box((int) $file->importantPartWidth, (int) $file->importantPartHeight)
);
} | php | {
"resource": ""
} |
q243142 | FormSelectMenu.validate | validation | public function validate()
{
$mandatory = $this->mandatory;
$options = $this->getPost($this->strName);
// Check if there is at least one value
if ($mandatory && \is_array($options))
{
foreach ($options as $option)
{
if (\strlen($option))
{
$this->mandatory = false;
break;
}
}
}
$varInput = $this->validator($options);
// Check for a valid option (see #4383)
if (!empty($varInput) && !$this->isValidOption($varInput))
{
$this->addError($GLOBALS['TL_LANG']['ERR']['invalid']);
}
// Add class "error"
if ($this->hasErrors())
{
$this->class = 'error';
}
else
{
$this->varValue = $varInput;
}
// Reset the property
if ($mandatory)
{
$this->mandatory = true;
}
} | php | {
"resource": ""
} |
q243143 | Statement.prepare | validation | public function prepare($strQuery)
{
if ($strQuery == '')
{
throw new \Exception('Empty query string');
}
$this->strQuery = trim($strQuery);
// Auto-generate the SET/VALUES subpart
if (strncasecmp($this->strQuery, 'INSERT', 6) === 0 || strncasecmp($this->strQuery, 'UPDATE', 6) === 0)
{
$this->strQuery = str_replace('%s', '%p', $this->strQuery);
}
// Replace wildcards
$arrChunks = preg_split("/('[^']*')/", $this->strQuery, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
foreach ($arrChunks as $k=>$v)
{
if (substr($v, 0, 1) == "'")
{
continue;
}
$arrChunks[$k] = str_replace('?', '%s', $v);
}
$this->strQuery = implode('', $arrChunks);
return $this;
} | php | {
"resource": ""
} |
q243144 | Statement.limit | validation | public function limit($intRows, $intOffset=0)
{
if ($intRows <= 0)
{
$intRows = 30;
}
if ($intOffset < 0)
{
$intOffset = 0;
}
if (strncasecmp($this->strQuery, 'SELECT', 6) === 0)
{
$this->strQuery .= ' LIMIT ' . $intOffset . ',' . $intRows;
}
else
{
$this->strQuery .= ' LIMIT ' . $intRows;
}
return $this;
} | php | {
"resource": ""
} |
q243145 | Statement.execute | validation | public function execute()
{
$arrParams = \func_get_args();
if (!empty($arrParams) && \is_array($arrParams[0]))
{
$arrParams = array_values($arrParams[0]);
}
$this->replaceWildcards($arrParams);
return $this->query();
} | php | {
"resource": ""
} |
q243146 | Statement.query | validation | public function query($strQuery='')
{
if (!empty($strQuery))
{
$this->strQuery = trim($strQuery);
}
// Make sure there is a query string
if ($this->strQuery == '')
{
throw new \Exception('Empty query string');
}
// Execute the query
$this->statement = $this->resConnection->executeQuery($this->strQuery);
// No result set available
if ($this->statement->columnCount() < 1)
{
return $this;
}
// Instantiate a result object
return new Result($this->statement, $this->strQuery);
} | php | {
"resource": ""
} |
q243147 | Statement.replaceWildcards | validation | protected function replaceWildcards($arrValues)
{
$arrValues = $this->escapeParams($arrValues);
$this->strQuery = preg_replace('/(?<!%)%([^bcdufosxX%])/', '%%$1', $this->strQuery);
// Replace wildcards
if (!$this->strQuery = @vsprintf($this->strQuery, $arrValues))
{
throw new \Exception('Too few arguments to build the query string');
}
} | php | {
"resource": ""
} |
q243148 | Statement.escapeParams | validation | protected function escapeParams($arrValues)
{
foreach ($arrValues as $k=>$v)
{
switch (\gettype($v))
{
case 'string':
$arrValues[$k] = $this->resConnection->quote($v);
break;
case 'boolean':
$arrValues[$k] = ($v === true) ? 1 : 0;
break;
case 'object':
$arrValues[$k] = $this->resConnection->quote(serialize($v));
break;
case 'array':
$arrValues[$k] = $this->resConnection->quote(serialize($v));
break;
default:
$arrValues[$k] = $v ?? 'NULL';
break;
}
}
return $arrValues;
} | php | {
"resource": ""
} |
q243149 | ModelArgumentResolver.getArgumentName | validation | private function getArgumentName(Request $request, ArgumentMetadata $argument): ?string
{
if ($request->attributes->has($argument->getName())) {
return $argument->getName();
}
$className = lcfirst($this->stripNamespace($argument->getType()));
if ($request->attributes->has($className)) {
return $className;
}
return null;
} | php | {
"resource": ""
} |
q243150 | ModelArgumentResolver.stripNamespace | validation | private function stripNamespace(string $fqcn): string
{
if (false !== ($pos = strrpos($fqcn, '\\'))) {
return substr($fqcn, $pos + 1);
}
return $fqcn;
} | php | {
"resource": ""
} |
q243151 | AbstractFragmentController.createTemplate | validation | protected function createTemplate(Model $model, string $templateName): Template
{
if (isset($this->options['template'])) {
$templateName = $this->options['template'];
}
if ($model->customTpl) {
$templateName = $model->customTpl;
}
$template = $this->get('contao.framework')->createInstance(FrontendTemplate::class, [$templateName]);
$template->setData($model->row());
return $template;
} | php | {
"resource": ""
} |
q243152 | AbstractFragmentController.getType | validation | protected function getType(): string
{
if (isset($this->options['type'])) {
return $this->options['type'];
}
$className = ltrim(strrchr(static::class, '\\'), '\\');
if ('Controller' === substr($className, -10)) {
$className = substr($className, 0, -10);
}
return Container::underscore($className);
} | php | {
"resource": ""
} |
q243153 | BackendController.pickerAction | validation | public function pickerAction(Request $request): RedirectResponse
{
$extras = [];
if ($request->query->has('extras')) {
$extras = $request->query->get('extras');
if (!\is_array($extras)) {
throw new BadRequestHttpException('Invalid picker extras');
}
}
$config = new PickerConfig($request->query->get('context'), $extras, $request->query->get('value'));
$picker = $this->get('contao.picker.builder')->create($config);
if (null === $picker) {
throw new BadRequestHttpException('Unsupported picker context');
}
return new RedirectResponse($picker->getCurrentUrl());
} | php | {
"resource": ""
} |
q243154 | FormCaptcha.generateCaptcha | validation | protected function generateCaptcha()
{
if ($this->arrCaptcha)
{
return;
}
$int1 = random_int(1, 9);
$int2 = random_int(1, 9);
$this->arrCaptcha = array
(
'int1' => $int1,
'int2' => $int2,
'sum' => $int1 + $int2,
'key' => $this->strCaptchaKey,
'hashes' => $this->generateHashes($int1 + $int2)
);
} | php | {
"resource": ""
} |
q243155 | FormCaptcha.generateHashes | validation | protected function generateHashes($sum)
{
// Round the time to 30 minutes
$time = (int) round(time() / 60 / 30);
return array_map(
function ($hashTime) use ($sum)
{
return hash_hmac('sha256', $sum . "\0" . $hashTime, System::getContainer()->getParameter('kernel.secret'));
},
array($time, $time - 1)
);
} | php | {
"resource": ""
} |
q243156 | FormCaptcha.getQuestion | validation | protected function getQuestion()
{
$this->generateCaptcha();
$question = $GLOBALS['TL_LANG']['SEC']['question' . random_int(1, 3)];
$question = sprintf($question, $this->arrCaptcha['int1'], $this->arrCaptcha['int2']);
$strEncoded = '';
$arrCharacters = Utf8::str_split($question);
foreach ($arrCharacters as $strCharacter)
{
$strEncoded .= sprintf('&#%s;', Utf8::ord($strCharacter));
}
return $strEncoded;
} | php | {
"resource": ""
} |
q243157 | FormCaptcha.generateQuestion | validation | public function generateQuestion()
{
return sprintf('<span id="captcha_text_%s" class="captcha_text%s">%s</span>',
$this->strId,
(($this->strClass != '') ? ' ' . $this->strClass : ''),
$this->getQuestion());
} | php | {
"resource": ""
} |
q243158 | NewsFeedModel.findByArchive | validation | public static function findByArchive($intId, array $arrOptions=array())
{
$t = static::$strTable;
return static::findBy(array("$t.archives LIKE '%\"" . (int) $intId . "\"%'"), null, $arrOptions);
} | php | {
"resource": ""
} |
q243159 | NewsFeedModel.findByIds | validation | public static function findByIds($arrIds, array $arrOptions=array())
{
if (empty($arrIds) || !\is_array($arrIds))
{
return null;
}
$t = static::$strTable;
return static::findBy(array("$t.id IN(" . implode(',', array_map('\intval', $arrIds)) . ")"), null, $arrOptions);
} | php | {
"resource": ""
} |
q243160 | DcaSchemaProvider.appendToSchema | validation | public function appendToSchema(Schema $schema): void
{
$config = $this->getSqlDefinitions();
foreach ($config as $tableName => $definitions) {
$table = $schema->createTable($tableName);
// Parse the table options first
if (isset($definitions['TABLE_OPTIONS'])) {
if (preg_match('/ENGINE=([^ ]+)/i', $definitions['TABLE_OPTIONS'], $match)) {
$table->addOption('engine', $match[1]);
}
if (preg_match('/DEFAULT CHARSET=([^ ]+)/i', $definitions['TABLE_OPTIONS'], $match)) {
$table->addOption('charset', $match[1]);
$table->addOption('collate', $match[1].'_general_ci');
}
if (preg_match('/COLLATE ([^ ]+)/i', $definitions['TABLE_OPTIONS'], $match)) {
$table->addOption('collate', $match[1]);
}
}
// The default InnoDB row format before MySQL 5.7.9 is "Compact" but innodb_large_prefix requires "DYNAMIC"
if ($table->hasOption('engine') && 'InnoDB' === $table->getOption('engine')) {
$table->addOption('row_format', 'DYNAMIC');
}
if (isset($definitions['SCHEMA_FIELDS'])) {
foreach ($definitions['SCHEMA_FIELDS'] as $fieldName => $config) {
$options = $config;
unset($options['name'], $options['type']);
// Use the binary collation if the "case_sensitive" option is set
if ($this->isCaseSensitive($config)) {
$options['platformOptions']['collation'] = $this->getBinaryCollation($table);
}
$table->addColumn($config['name'], $config['type'], $options);
}
}
if (isset($definitions['TABLE_FIELDS'])) {
foreach ($definitions['TABLE_FIELDS'] as $fieldName => $sql) {
$this->parseColumnSql($table, $fieldName, substr($sql, \strlen($fieldName) + 3));
}
}
if (isset($definitions['TABLE_CREATE_DEFINITIONS'])) {
foreach ($definitions['TABLE_CREATE_DEFINITIONS'] as $keyName => $sql) {
$this->parseIndexSql($table, $keyName, strtolower($sql));
}
}
}
} | php | {
"resource": ""
} |
q243161 | DcaSchemaProvider.getSqlDefinitions | validation | private function getSqlDefinitions(): array
{
$this->framework->initialize();
/** @var Installer $installer */
$installer = $this->framework->createInstance(Installer::class);
$sqlTarget = $installer->getFromDca();
$sqlLegacy = $installer->getFromFile();
// Manually merge the legacy definitions (see #4766)
if (!empty($sqlLegacy)) {
foreach ($sqlLegacy as $table => $categories) {
foreach ($categories as $category => $fields) {
if (\is_array($fields)) {
foreach ($fields as $name => $sql) {
$sqlTarget[$table][$category][$name] = $sql;
}
} else {
$sqlTarget[$table][$category] = $fields;
}
}
}
}
// Apply the schema filter (see contao/installation-bundle#78)
if ($filter = $this->doctrine->getConnection()->getConfiguration()->getFilterSchemaAssetsExpression()) {
foreach (array_keys($sqlTarget) as $key) {
if (!preg_match($filter, $key)) {
unset($sqlTarget[$key]);
}
}
}
return $sqlTarget;
} | php | {
"resource": ""
} |
q243162 | DcaSchemaProvider.getIndexLength | validation | private function getIndexLength(Table $table, string $column): ?int
{
$col = $table->getColumn($column);
// Not a text field
if (null === ($length = $col->getLength())) {
return null;
}
// Return if the field is shorter than the shortest possible index
// length (utf8mb4 on InnoDB without large prefixes)
if ($length <= 191) {
return null;
}
if ($col->hasPlatformOption('collation')) {
$collation = $col->getPlatformOption('collation');
} else {
$collation = $table->getOption('collate');
}
$defaultLength = $this->getDefaultIndexLength($table);
$bytes = 0 === strncmp($collation, 'utf8mb4', 7) ? 4 : 3;
$indexLength = (int) floor($defaultLength / $bytes);
// Return if the field is shorter than the index length
if ($length <= $indexLength) {
return null;
}
return $indexLength;
} | php | {
"resource": ""
} |
q243163 | GdImage.fromFile | validation | public static function fromFile(File $file)
{
$extension = strtolower($file->extension);
$function = null;
if ($extension === 'jpg')
{
$extension = 'jpeg';
}
if (\in_array($extension, array('gif', 'jpeg', 'png')))
{
$function = 'imagecreatefrom' . $extension;
}
if ($function === null || !\is_callable($function))
{
throw new \InvalidArgumentException('Image type "' . $file->extension . '" cannot be processed by GD');
}
$image = $function(System::getContainer()->getParameter('kernel.project_dir') . '/' . $file->path);
if ($image === false)
{
throw new \RuntimeException('Image "' . $file->path . '" failed to be processed by GD');
}
return new static($image);
} | php | {
"resource": ""
} |
q243164 | GdImage.fromDimensions | validation | public static function fromDimensions($width, $height)
{
$image = imagecreatetruecolor($width, $height);
$arrGdInfo = gd_info();
$strGdVersion = preg_replace('/[^0-9.]+/', '', $arrGdInfo['GD Version']);
// Handle transparency (GDlib >= 2.0 required)
if (version_compare($strGdVersion, '2.0', '>='))
{
imagealphablending($image, false);
imagefill($image, 0, 0, imagecolorallocatealpha($image, 0, 0, 0, 127));
imagesavealpha($image, true);
}
return new static($image);
} | php | {
"resource": ""
} |
q243165 | GdImage.setResource | validation | public function setResource($gdResource)
{
if (!\is_resource($gdResource) || get_resource_type($gdResource) !== 'gd')
{
throw new \InvalidArgumentException('$gdResource is not a valid GD resource');
}
$this->gdResource = $gdResource;
return $this;
} | php | {
"resource": ""
} |
q243166 | GdImage.convertToPaletteImage | validation | public function convertToPaletteImage()
{
if (!imageistruecolor($this->gdResource))
{
return $this;
}
$width = imagesx($this->gdResource);
$height = imagesy($this->gdResource);
$transparentColor = null;
if ($this->countColors(256) <= 256)
{
$paletteImage = imagecreate($width, $height);
$colors = array();
$isTransparent = false;
for ($x = 0; $x < $width; $x++)
{
for ($y = 0; $y < $height; $y++)
{
$color = imagecolorat($this->gdResource, $x, $y);
// Check if the pixel is fully transparent
if ((($color >> 24) & 0x7F) === 127)
{
$isTransparent = true;
}
else
{
$colors[$color & 0xFFFFFF] = true;
}
}
}
$colors = array_keys($colors);
foreach ($colors as $index => $color)
{
imagecolorset($paletteImage, $index, ($color >> 16) & 0xFF, ($color >> 8) & 0xFF, $color & 0xFF);
}
if ($isTransparent)
{
$transparentColor = imagecolorallocate($paletteImage, 0, 0, 0);
imagecolortransparent($paletteImage, $transparentColor);
}
imagecopy($paletteImage, $this->gdResource, 0, 0, 0, 0, $width, $height);
}
else
{
$paletteImage = imagecreatetruecolor($width, $height);
imagealphablending($paletteImage, false);
imagesavealpha($paletteImage, true);
imagecopy($paletteImage, $this->gdResource, 0, 0, 0, 0, $width, $height);
// 256 minus 1 for the transparent color
imagetruecolortopalette($paletteImage, false, 255);
$transparentColor = imagecolorallocate($paletteImage, 0, 0, 0);
imagecolortransparent($paletteImage, $transparentColor);
}
if ($transparentColor !== null)
{
// Fix fully transparent pixels
for ($x = 0; $x < $width; $x++)
{
for ($y = 0; $y < $height; $y++)
{
// Check if the pixel is fully transparent
if (((imagecolorat($this->gdResource, $x, $y) >> 24) & 0x7F) === 127)
{
imagefilledrectangle($paletteImage, $x, $y, $x, $y, $transparentColor);
}
}
}
}
imagedestroy($this->gdResource);
$this->gdResource = $paletteImage;
return $this;
} | php | {
"resource": ""
} |
q243167 | GdImage.countColors | validation | public function countColors($max = null)
{
if (!imageistruecolor($this->gdResource))
{
return imagecolorstotal($this->gdResource);
}
$colors = array();
$width = imagesx($this->gdResource);
$height = imagesy($this->gdResource);
for ($x = 0; $x < $width; $x++)
{
for ($y = 0; $y < $height; $y++)
{
$colors[imagecolorat($this->gdResource, $x, $y)] = true;
if ($max !== null && \count($colors) > $max)
{
break 2;
}
}
}
return \count($colors);
} | php | {
"resource": ""
} |
q243168 | GdImage.isSemitransparent | validation | public function isSemitransparent()
{
if (!imageistruecolor($this->gdResource))
{
return false;
}
$width = imagesx($this->gdResource);
$height = imagesy($this->gdResource);
for ($x = 0; $x < $width; $x++)
{
for ($y = 0; $y < $height; $y++)
{
// Check if the pixel is semitransparent
$alpha = (imagecolorat($this->gdResource, $x, $y) >> 24) & 0x7F;
if ($alpha > 0 && $alpha < 127)
{
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q243169 | InputUnit.validator | validation | protected function validator($varInput)
{
foreach ($varInput as $k=>$v)
{
if ($k != 'unit')
{
$varInput[$k] = parent::validator($v);
}
}
return $varInput;
} | php | {
"resource": ""
} |
q243170 | ContentMarkdown.generate | validation | public function generate()
{
if (TL_MODE == 'BE')
{
$return = '<pre>'. StringUtil::specialchars($this->code) .'</pre>';
if ($this->headline != '')
{
$return = '<'. $this->hl .'>'. $this->headline .'</'. $this->hl .'>'. $return;
}
return $return;
}
return parent::generate();
} | php | {
"resource": ""
} |
q243171 | Email.attachFile | validation | public function attachFile($strFile, $strMime='application/octet-stream')
{
$this->objMessage->attach(\Swift_Attachment::fromPath($strFile, $strMime)->setFilename(basename($strFile)));
} | php | {
"resource": ""
} |
q243172 | Email.attachFileFromString | validation | public function attachFileFromString($strContent, $strFilename, $strMime='application/octet-stream')
{
$this->objMessage->attach(new \Swift_Attachment($strContent, $strFilename, $strMime));
} | php | {
"resource": ""
} |
q243173 | BackendTemplate.parse | validation | public function parse()
{
$strBuffer = parent::parse();
// HOOK: add custom parse filters
if (isset($GLOBALS['TL_HOOKS']['parseBackendTemplate']) && \is_array($GLOBALS['TL_HOOKS']['parseBackendTemplate']))
{
foreach ($GLOBALS['TL_HOOKS']['parseBackendTemplate'] as $callback)
{
$this->import($callback[0]);
$strBuffer = $this->{$callback[0]}->{$callback[1]}($strBuffer, $this->strTemplate);
}
}
return $strBuffer;
} | php | {
"resource": ""
} |
q243174 | BackendTemplate.getLocaleString | validation | protected function getLocaleString()
{
$container = System::getContainer();
return
'var Contao={'
. 'theme:"' . Backend::getTheme() . '",'
. 'lang:{'
. 'close:"' . $GLOBALS['TL_LANG']['MSC']['close'] . '",'
. 'collapse:"' . $GLOBALS['TL_LANG']['MSC']['collapseNode'] . '",'
. 'expand:"' . $GLOBALS['TL_LANG']['MSC']['expandNode'] . '",'
. 'loading:"' . $GLOBALS['TL_LANG']['MSC']['loadingData'] . '",'
. 'apply:"' . $GLOBALS['TL_LANG']['MSC']['apply'] . '"'
. '},'
. 'script_url:"' . $container->get('contao.assets.assets_context')->getStaticUrl() . '",'
. 'path:"' . Environment::get('path') . '",'
. 'request_token:"' . REQUEST_TOKEN . '",'
. 'referer_id:"' . $container->get('request_stack')->getCurrentRequest()->attributes->get('_contao_referer_id') . '"'
. '};';
} | php | {
"resource": ""
} |
q243175 | BackendTemplate.getDateString | validation | protected function getDateString()
{
return
'Locale.define("en-US","Date",{'
. 'months:["' . implode('","', $GLOBALS['TL_LANG']['MONTHS']) . '"],'
. 'days:["' . implode('","', $GLOBALS['TL_LANG']['DAYS']) . '"],'
. 'months_abbr:["' . implode('","', $GLOBALS['TL_LANG']['MONTHS_SHORT']) . '"],'
. 'days_abbr:["' . implode('","', $GLOBALS['TL_LANG']['DAYS_SHORT']) . '"]'
. '});'
. 'Locale.define("en-US","DatePicker",{'
. 'select_a_time:"' . $GLOBALS['TL_LANG']['DP']['select_a_time'] . '",'
. 'use_mouse_wheel:"' . $GLOBALS['TL_LANG']['DP']['use_mouse_wheel'] . '",'
. 'time_confirm_button:"' . $GLOBALS['TL_LANG']['DP']['time_confirm_button'] . '",'
. 'apply_range:"' . $GLOBALS['TL_LANG']['DP']['apply_range'] . '",'
. 'cancel:"' . $GLOBALS['TL_LANG']['DP']['cancel'] . '",'
. 'week:"' . $GLOBALS['TL_LANG']['DP']['week'] . '"'
. '});';
} | php | {
"resource": ""
} |
q243176 | PageForward.generate | validation | public function generate($objPage)
{
$this->redirect($this->getForwardUrl($objPage), $this->getRedirectStatusCode($objPage));
} | php | {
"resource": ""
} |
q243177 | PageForward.getForwardUrl | validation | protected function getForwardUrl($objPage)
{
if ($objPage->jumpTo)
{
$objNextPage = PageModel::findPublishedById($objPage->jumpTo);
}
else
{
$objNextPage = PageModel::findFirstPublishedRegularByPid($objPage->id);
}
// Forward page does not exist
if (!$objNextPage instanceof PageModel)
{
$this->log('Forward page ID "' . $objPage->jumpTo . '" does not exist', __METHOD__, TL_ERROR);
throw new ForwardPageNotFoundException('Forward page not found');
}
$strGet = '';
$strQuery = Environment::get('queryString');
$arrQuery = array();
// Extract the query string keys (see #5867)
if ($strQuery != '')
{
$arrChunks = explode('&', $strQuery);
foreach ($arrChunks as $strChunk)
{
list($k) = explode('=', $strChunk, 2);
$arrQuery[] = $k;
}
}
// Add $_GET parameters
if (!empty($_GET))
{
foreach (array_keys($_GET) as $key)
{
if (Config::get('addLanguageToUrl') && $key == 'language')
{
continue;
}
// Ignore the query string parameters (see #5867)
if (\in_array($key, $arrQuery))
{
continue;
}
// Ignore the auto_item parameter (see #5886)
if ($key == 'auto_item')
{
$strGet .= '/' . Input::get($key);
}
else
{
$strGet .= '/' . $key . '/' . Input::get($key);
}
}
}
// Append the query string (see #5867)
if ($strQuery != '')
{
$strQuery = '?' . $strQuery;
}
return $objNextPage->getAbsoluteUrl($strGet) . $strQuery;
} | php | {
"resource": ""
} |
q243178 | FilePickerProvider.convertValueToPath | validation | private function convertValueToPath(string $value): string
{
/** @var FilesModel $filesAdapter */
$filesAdapter = $this->framework->getAdapter(FilesModel::class);
if (Validator::isUuid($value) && ($filesModel = $filesAdapter->findByUuid($value)) instanceof FilesModel) {
return $filesModel->path;
}
return $value;
} | php | {
"resource": ""
} |
q243179 | tl_newsletter_channel.adjustPermissions | validation | public function adjustPermissions($insertId)
{
// The oncreate_callback passes $insertId as second argument
if (\func_num_args() == 4)
{
$insertId = func_get_arg(1);
}
if ($this->User->isAdmin)
{
return;
}
// Set root IDs
if (empty($this->User->newsletters) || !\is_array($this->User->newsletters))
{
$root = array(0);
}
else
{
$root = $this->User->newsletters;
}
// The channel is enabled already
if (\in_array($insertId, $root))
{
return;
}
/** @var Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface $objSessionBag */
$objSessionBag = Contao\System::getContainer()->get('session')->getBag('contao_backend');
$arrNew = $objSessionBag->get('new_records');
if (\is_array($arrNew['tl_newsletter_channel']) && \in_array($insertId, $arrNew['tl_newsletter_channel']))
{
// Add the permissions on group level
if ($this->User->inherit != 'custom')
{
$objGroup = $this->Database->execute("SELECT id, newsletters, newsletterp FROM tl_user_group WHERE id IN(" . implode(',', array_map('\intval', $this->User->groups)) . ")");
while ($objGroup->next())
{
$arrNewsletterp = Contao\StringUtil::deserialize($objGroup->newsletterp);
if (\is_array($arrNewsletterp) && \in_array('create', $arrNewsletterp))
{
$arrNewsletters = Contao\StringUtil::deserialize($objGroup->newsletters, true);
$arrNewsletters[] = $insertId;
$this->Database->prepare("UPDATE tl_user_group SET newsletters=? WHERE id=?")
->execute(serialize($arrNewsletters), $objGroup->id);
}
}
}
// Add the permissions on user level
if ($this->User->inherit != 'group')
{
$objUser = $this->Database->prepare("SELECT newsletters, newsletterp FROM tl_user WHERE id=?")
->limit(1)
->execute($this->User->id);
$arrNewsletterp = Contao\StringUtil::deserialize($objUser->newsletterp);
if (\is_array($arrNewsletterp) && \in_array('create', $arrNewsletterp))
{
$arrNewsletters = Contao\StringUtil::deserialize($objUser->newsletters, true);
$arrNewsletters[] = $insertId;
$this->Database->prepare("UPDATE tl_user SET newsletters=? WHERE id=?")
->execute(serialize($arrNewsletters), $this->User->id);
}
}
// Add the new element to the user object
$root[] = $insertId;
$this->User->newsletter = $root;
}
} | php | {
"resource": ""
} |
q243180 | tl_newsletter_recipients.clearOptInData | validation | public function clearOptInData(Contao\DataContainer $dc)
{
$this->Database->prepare("UPDATE tl_newsletter_recipients SET addedOn='' WHERE id=?")
->execute($dc->id);
} | php | {
"resource": ""
} |
q243181 | tl_newsletter_recipients.checkUniqueRecipient | validation | public function checkUniqueRecipient($varValue, Contao\DataContainer $dc)
{
$objRecipient = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_newsletter_recipients WHERE email=? AND pid=(SELECT pid FROM tl_newsletter_recipients WHERE id=?) AND id!=?")
->execute($varValue, $dc->id, $dc->id);
if ($objRecipient->count > 0)
{
throw new Exception(sprintf($GLOBALS['TL_LANG']['ERR']['unique'], $GLOBALS['TL_LANG'][$dc->table][$dc->field][0]));
}
return $varValue;
} | php | {
"resource": ""
} |
q243182 | tl_newsletter_recipients.checkBlacklistedRecipient | validation | public function checkBlacklistedRecipient($varValue, Contao\DataContainer $dc)
{
$objBlacklist = $this->Database->prepare("SELECT COUNT(*) AS count FROM tl_newsletter_blacklist WHERE hash=? AND pid=(SELECT pid FROM tl_newsletter_recipients WHERE id=?) AND id!=?")
->execute(md5($varValue), $dc->id, $dc->id);
if ($objBlacklist->count > 0)
{
throw new Exception($GLOBALS['TL_LANG']['ERR']['blacklisted']);
}
return $varValue;
} | php | {
"resource": ""
} |
q243183 | tl_newsletter_recipients.listRecipient | validation | public function listRecipient($row)
{
$label = Contao\Idna::decodeEmail($row['email']);
if ($row['addedOn'])
{
$label .= ' <span style="color:#999;padding-left:3px">(' . sprintf($GLOBALS['TL_LANG']['tl_newsletter_recipients']['subscribed'], Contao\Date::parse(Contao\Config::get('datimFormat'), $row['addedOn'])) . ')</span>';
}
else
{
$label .= ' <span style="color:#999;padding-left:3px">(' . $GLOBALS['TL_LANG']['tl_newsletter_recipients']['manually'] . ')</span>';
}
return sprintf('<div class="tl_content_left"><div class="list_icon" style="background-image:url(\'%ssystem/themes/%s/icons/%s.svg\')" data-icon="member.svg" data-icon-disabled="member_.svg">%s</div></div>', Contao\System::getContainer()->get('contao.assets.assets_context')->getStaticUrl(), Contao\Backend::getTheme(), ($row['active'] ? 'member' : 'member_'), $label) . "\n";
} | php | {
"resource": ""
} |
q243184 | AssetListener.onReplaceInsertTags | validation | public function onReplaceInsertTags(string $tag)
{
$chunks = explode('::', $tag);
if ('asset' !== $chunks[0]) {
return false;
}
$url = $this->packages->getUrl($chunks[1], $chunks[2] ?? null);
// Contao paths are relative to the <base> tag, so remove leading slashes
return ltrim($url, '/');
} | php | {
"resource": ""
} |
q243185 | FrontendTemplate.section | validation | public function section($key, $template=null)
{
if (empty($this->sections[$key]))
{
return;
}
$this->id = $key;
$this->content = $this->sections[$key];
if ($template === null)
{
$template = 'block_section';
foreach ($this->positions as $position)
{
if (isset($position[$key]['template']))
{
$template = $position[$key]['template'];
}
}
}
include $this->getTemplate($template);
} | php | {
"resource": ""
} |
q243186 | FrontendTemplate.sections | validation | public function sections($key=null, $template=null)
{
if (!array_filter($this->sections))
{
return;
}
// The key does not match
if ($key && !isset($this->positions[$key]))
{
return;
}
$matches = array();
foreach ($this->positions[$key] as $id=>$section)
{
if (!empty($this->sections[$id]))
{
$section['content'] = $this->sections[$id];
$matches[$id] = $section;
}
}
// Return if the section is empty (see #1115)
if (empty($matches))
{
return;
}
$this->matches = $matches;
if ($template === null)
{
$template = 'block_sections';
}
include $this->getTemplate($template);
} | php | {
"resource": ""
} |
q243187 | FrontendTemplate.getCustomSections | validation | public function getCustomSections($strKey=null)
{
@trigger_error('Using FrontendTemplate::getCustomSections() has been deprecated and will no longer work in Contao 5.0. Use FrontendTemplate::sections() instead.', E_USER_DEPRECATED);
if ($strKey != '' && !isset($this->positions[$strKey]))
{
return '';
}
$tag = 'div';
// Use the section tag for the main column
if ($strKey == 'main')
{
$tag = 'section';
}
$sections = '';
// Standardize the IDs (thanks to Tsarma) (see #4251)
foreach ($this->positions[$strKey] as $sect)
{
if (isset($this->sections[$sect['id']]))
{
$sections .= "\n" . '<' . $tag . ' id="' . StringUtil::standardize($sect['id'], true) . '">' . "\n" . '<div class="inside">' . "\n" . $this->sections[$sect['id']] . "\n" . '</div>' . "\n" . '</' . $tag . '>' . "\n";
}
}
if ($sections == '')
{
return '';
}
return '<div class="custom">' . "\n" . $sections . "\n" . '</div>' . "\n";
} | php | {
"resource": ""
} |
q243188 | FrontendTemplate.setCacheHeaders | validation | private function setCacheHeaders(Response $response)
{
/** @var PageModel $objPage */
global $objPage;
if (($objPage->cache === false || $objPage->cache < 1) && ($objPage->clientCache === false || $objPage->clientCache < 1))
{
$response->headers->addCacheControlDirective('no-cache');
$response->headers->addCacheControlDirective('no-store');
return $response->setPrivate();
}
// Do not cache the response if a user is logged in or the page is protected
// TODO: Add support for proxies so they can vary on member context
if (FE_USER_LOGGED_IN === true || BE_USER_LOGGED_IN === true || $objPage->protected || $this->hasAuthenticatedBackendUser())
{
$response->headers->addCacheControlDirective('no-cache');
$response->headers->addCacheControlDirective('no-store');
return $response->setPrivate();
}
if ($objPage->clientCache > 0)
{
$response->setMaxAge($objPage->clientCache);
}
if ($objPage->cache > 0)
{
$response->setSharedMaxAge($objPage->cache);
}
// Tag the 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_page.' . $objPage->id));
}
return $response;
} | php | {
"resource": ""
} |
q243189 | PageRedirect.generate | validation | public function generate($objPage)
{
$this->redirect($this->replaceInsertTags($objPage->url, false), $this->getRedirectStatusCode($objPage));
} | php | {
"resource": ""
} |
q243190 | tl_opt_in.showRelatedRecords | validation | public function showRelatedRecords($data, $row)
{
Contao\System::loadLanguageFile('tl_opt_in_related');
Contao\Controller::loadDataContainer('tl_opt_in_related');
$objRelated = $this->Database->prepare("SELECT * FROM tl_opt_in_related WHERE pid=?")
->execute($row['id']);
while ($objRelated->next())
{
$arrAdd = array();
$arrRow = $objRelated->row();
foreach ($arrRow as $k=>$v)
{
$label = \is_array($GLOBALS['TL_DCA']['tl_opt_in_related']['fields'][$k]['label']) ? $GLOBALS['TL_DCA']['tl_opt_in_related']['fields'][$k]['label'][0] : $GLOBALS['TL_DCA']['tl_opt_in_related']['fields'][$k]['label'];
$arrAdd[$label] = $v;
}
$data['tl_opt_in_related'][] = $arrAdd;
}
return $data;
} | php | {
"resource": ""
} |
q243191 | tl_opt_in.resendToken | validation | public function resendToken(Contao\DataContainer $dc)
{
$model = Contao\OptInModel::findByPk($dc->id);
Contao\System::getContainer()->get('contao.opt-in')->find($model->token)->send();
Contao\Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['MSC']['resendToken'], $model->email));
Contao\Controller::redirect($this->getReferer());
} | php | {
"resource": ""
} |
q243192 | tl_opt_in.resendButton | validation | public function resendButton($row, $href, $label, $title, $icon, $attributes)
{
return (!$row['confirmedOn'] &&!$row['invalidatedThrough'] && $row['emailSubject'] && $row['emailText'] && $row['createdOn'] > strtotime('-24 hours')) ? '<a href="'.$this->addToUrl($href.'&id='.$row['id']).'" title="'.Contao\StringUtil::specialchars($title).'"'.$attributes.'>'.Contao\Image::getHtml($icon, $label).'</a> ' : '';
} | php | {
"resource": ""
} |
q243193 | CommentsNotifyModel.findBySourceParentAndEmail | validation | public static function findBySourceParentAndEmail($strSource, $intParent, $strEmail, array $arrOptions=array())
{
$t = static::$strTable;
return static::findOneBy(array("$t.source=? AND $t.parent=? AND $t.email=?"), array($strSource, $intParent, $strEmail), $arrOptions);
} | php | {
"resource": ""
} |
q243194 | CommentsNotifyModel.findActiveBySourceAndParent | validation | public static function findActiveBySourceAndParent($strSource, $intParent, array $arrOptions=array())
{
$t = static::$strTable;
return static::findBy(array("$t.source=? AND $t.parent=? AND $t.active='1'"), array($strSource, $intParent), $arrOptions);
} | php | {
"resource": ""
} |
q243195 | CommentsNotifyModel.findExpiredSubscriptions | validation | public static function findExpiredSubscriptions(array $arrOptions=array())
{
$t = static::$strTable;
$objDatabase = Database::getInstance();
$objResult = $objDatabase->prepare("SELECT * FROM $t WHERE active='' AND EXISTS (SELECT * FROM tl_opt_in_related r LEFT JOIN tl_opt_in o ON r.pid=o.id WHERE r.relTable='$t' AND r.relId=$t.id AND o.createdOn<=? AND o.confirmedOn=0)")
->execute(strtotime('-24 hours'));
if ($objResult->numRows < 1)
{
return null;
}
return static::createCollectionFromDbResult($objResult, $t);
} | php | {
"resource": ""
} |
q243196 | tl_layout.getStyleSheets | validation | public function getStyleSheets(Contao\DataContainer $dc)
{
$intPid = $dc->activeRecord->pid;
if (Contao\Input::get('act') == 'overrideAll')
{
$intPid = Contao\Input::get('id');
}
$objStyleSheet = $this->Database->prepare("SELECT id, name FROM tl_style_sheet WHERE pid=?")
->execute($intPid);
if ($objStyleSheet->numRows < 1)
{
return array();
}
$return = array();
while ($objStyleSheet->next())
{
$return[$objStyleSheet->id] = $objStyleSheet->name;
}
return $return;
} | php | {
"resource": ""
} |
q243197 | tl_layout.styleSheetLink | validation | public function styleSheetLink(Contao\DataContainer $dc)
{
return ' <a href="contao/main.php?do=themes&table=tl_style_sheet&id=' . $dc->activeRecord->pid . '&popup=1&nb=1&rt=' . REQUEST_TOKEN . '" title="' . Contao\StringUtil::specialchars($GLOBALS['TL_LANG']['tl_layout']['edit_styles']) . '" onclick="Backend.openModalIframe({\'title\':\''.Contao\StringUtil::specialchars(str_replace("'", "\\'", $GLOBALS['TL_LANG']['tl_layout']['edit_styles'])).'\',\'url\':this.href});return false">' . Contao\Image::getHtml('edit.svg') . '</a>';
} | php | {
"resource": ""
} |
q243198 | ContentVimeo.generate | validation | public function generate()
{
if ($this->vimeo == '')
{
return '';
}
if (TL_MODE == 'BE')
{
$return = '<p><a href="https://vimeo.com/' . $this->vimeo . '" target="_blank" rel="noreferrer noopener">vimeo.com/' . $this->vimeo . '</a></p>';
if ($this->headline != '')
{
$return = '<'. $this->hl .'>'. $this->headline .'</'. $this->hl .'>'. $return;
}
return $return;
}
return parent::generate();
} | php | {
"resource": ""
} |
q243199 | AutomatorCommand.getTaskFromInput | validation | private function getTaskFromInput(InputInterface $input, OutputInterface $output): string
{
$commands = $this->getCommands();
$task = $input->getArgument('task');
if (null !== $task) {
if (!\in_array($task, $commands, true)) {
throw new \InvalidArgumentException(sprintf('Invalid task "%s"', $task)); // no full stop here
}
return $task;
}
$question = new ChoiceQuestion('Please select a task:', $commands);
$question->setMaxAttempts(1);
/** @var QuestionHelper $helper */
$helper = $this->getHelper('question');
return $helper->ask($input, $output, $question);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.