_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q243200 | Idna.encode | validation | public static function encode($strDomain)
{
if ($strDomain == '')
{
return '';
}
$objPunycode = new Punycode();
try
{
return $objPunycode->encode($strDomain);
}
catch (LabelOutOfBoundsException $e)
{
return '';
}
} | php | {
"resource": ""
} |
q243201 | Idna.decode | validation | public static function decode($strDomain)
{
if ($strDomain == '')
{
return '';
}
$objPunycode = new Punycode();
try
{
return $objPunycode->decode($strDomain);
}
catch (LabelOutOfBoundsException $e)
{
return '';
}
} | php | {
"resource": ""
} |
q243202 | Idna.encodeEmail | validation | public static function encodeEmail($strEmail)
{
if ($strEmail == '')
{
return '';
}
if (strpos($strEmail, '@') === false)
{
return $strEmail; // see #6241
}
$arrChunks = explode('@', $strEmail);
$strHost = static::encode(array_pop($arrChunks));
if ($strHost == '')
{
return '';
}
return implode('@', $arrChunks) . '@' . $strHost;
} | php | {
"resource": ""
} |
q243203 | Idna.decodeEmail | validation | public static function decodeEmail($strEmail)
{
if ($strEmail == '')
{
return '';
}
if (strpos($strEmail, '@') === false)
{
return $strEmail; // see #6241
}
$arrChunks = explode('@', $strEmail);
$strHost = static::decode(array_pop($arrChunks));
if ($strHost == '')
{
return '';
}
return implode('@', $arrChunks) . '@' . $strHost;
} | php | {
"resource": ""
} |
q243204 | Idna.encodeUrl | validation | public static function encodeUrl($strUrl)
{
if ($strUrl == '')
{
return '';
}
// Empty anchor (see #3555) or insert tag
if ($strUrl == '#' || strncmp($strUrl, '{{', 2) === 0)
{
return $strUrl;
}
// E-mail address
if (strncmp($strUrl, 'mailto:', 7) === 0)
{
return static::encodeEmail($strUrl);
}
$arrUrl = parse_url($strUrl);
if (!isset($arrUrl['scheme']))
{
throw new \InvalidArgumentException(sprintf('Expected a FQDN, got "%s"', $strUrl));
}
// Scheme
if (isset($arrUrl['scheme']))
{
$arrUrl['scheme'] .= ((substr($strUrl, \strlen($arrUrl['scheme']), 3) == '://') ? '://' : ':');
}
// User
if (isset($arrUrl['user']))
{
$arrUrl['user'] .= isset($arrUrl['pass']) ? ':' : '@';
}
// Password
if (isset($arrUrl['pass']))
{
$arrUrl['pass'] .= '@';
}
// Host
if (isset($arrUrl['host']))
{
$arrUrl['host'] = static::encode($arrUrl['host']);
}
// Port
if (isset($arrUrl['port']))
{
$arrUrl['port'] = ':' . $arrUrl['port'];
}
// Path does not have to be altered
// Query
if (isset($arrUrl['query']))
{
$arrUrl['query'] = '?' . $arrUrl['query'];
}
// Anchor
if (isset($arrUrl['fragment']))
{
$arrUrl['fragment'] = '#' . $arrUrl['fragment'];
}
$strReturn = '';
foreach (array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment') as $key)
{
if (isset($arrUrl[$key]))
{
$strReturn .= $arrUrl[$key];
}
}
return $strReturn;
} | php | {
"resource": ""
} |
q243205 | Idna.decodeUrl | validation | public static function decodeUrl($strUrl)
{
if ($strUrl == '')
{
return '';
}
// Empty anchor (see #3555) or insert tag
if ($strUrl == '#' || strncmp($strUrl, '{{', 2) === 0)
{
return $strUrl;
}
// E-mail address
if (strncmp($strUrl, 'mailto:', 7) === 0)
{
return static::decodeEmail($strUrl);
}
$arrUrl = parse_url($strUrl);
if (!isset($arrUrl['scheme']))
{
throw new \InvalidArgumentException(sprintf('Expected a FQDN, got "%s"', $strUrl));
}
// Scheme
if (isset($arrUrl['scheme']))
{
$arrUrl['scheme'] .= ((substr($strUrl, \strlen($arrUrl['scheme']), 3) == '://') ? '://' : ':');
}
// User
if (isset($arrUrl['user']))
{
$arrUrl['user'] .= isset($arrUrl['pass']) ? ':' : '@';
}
// Password
if (isset($arrUrl['pass']))
{
$arrUrl['pass'] .= '@';
}
// Host
if (isset($arrUrl['host']))
{
$arrUrl['host'] = static::decode($arrUrl['host']);
}
// Port
if (isset($arrUrl['port']))
{
$arrUrl['port'] = ':' . $arrUrl['port'];
}
// Path does not have to be altered
// Query
if (isset($arrUrl['query']))
{
$arrUrl['query'] = '?' . $arrUrl['query'];
}
// Anchor
if (isset($arrUrl['fragment']))
{
$arrUrl['fragment'] = '#' . $arrUrl['fragment'];
}
$strReturn = '';
foreach (array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment') as $key)
{
if (isset($arrUrl[$key]))
{
$strReturn .= $arrUrl[$key];
}
}
return $strReturn;
} | php | {
"resource": ""
} |
q243206 | ModuleRandomImage.generate | validation | public function generate()
{
$this->multiSRC = StringUtil::deserialize($this->multiSRC);
if (empty($this->multiSRC) || !\is_array($this->multiSRC))
{
return '';
}
$this->objFiles = FilesModel::findMultipleByUuids($this->multiSRC);
if ($this->objFiles === null)
{
return '';
}
return parent::generate();
} | php | {
"resource": ""
} |
q243207 | FilesModel.findByPk | validation | public static function findByPk($varValue, array $arrOptions=array())
{
if (static::$strPk == 'id')
{
return static::findById($varValue, $arrOptions);
}
return parent::findByPk($varValue, $arrOptions);
} | php | {
"resource": ""
} |
q243208 | FilesModel.findById | validation | public static function findById($intId, array $arrOptions=array())
{
if (Validator::isUuid($intId))
{
return static::findByUuid($intId, $arrOptions);
}
return static::findOneBy('id', $intId, $arrOptions);
} | php | {
"resource": ""
} |
q243209 | FilesModel.findByPid | validation | public static function findByPid($intPid, array $arrOptions=array())
{
$t = static::$strTable;
// Convert UUIDs to binary
if (Validator::isStringUuid($intPid))
{
$intPid = StringUtil::uuidToBin($intPid);
}
return static::findBy(array("$t.pid=UNHEX(?)"), bin2hex($intPid), $arrOptions);
} | php | {
"resource": ""
} |
q243210 | FilesModel.findMultipleByIds | validation | public static function findMultipleByIds($arrIds, array $arrOptions=array())
{
if (empty($arrIds) || !\is_array($arrIds))
{
return null;
}
if (Validator::isUuid(current($arrIds)))
{
return static::findMultipleByUuids($arrIds, $arrOptions);
}
return parent::findMultipleByIds($arrIds, $arrOptions);
} | php | {
"resource": ""
} |
q243211 | FilesModel.findByUuid | validation | public static function findByUuid($strUuid, array $arrOptions=array())
{
$t = static::$strTable;
// Convert UUIDs to binary
if (Validator::isStringUuid($strUuid))
{
$strUuid = StringUtil::uuidToBin($strUuid);
}
// Check the model registry (does not work by default due to UNHEX())
if (empty($arrOptions))
{
/** @var FilesModel $objModel */
$objModel = Registry::getInstance()->fetch(static::$strTable, $strUuid, 'uuid');
if ($objModel !== null)
{
return $objModel;
}
}
return static::findOneBy(array("$t.uuid=UNHEX(?)"), bin2hex($strUuid), $arrOptions);
} | php | {
"resource": ""
} |
q243212 | FilesModel.findMultipleByUuids | validation | public static function findMultipleByUuids($arrUuids, array $arrOptions=array())
{
if (empty($arrUuids) || !\is_array($arrUuids))
{
return null;
}
$t = static::$strTable;
foreach ($arrUuids as $k=>$v)
{
// Convert UUIDs to binary
if (Validator::isStringUuid($v))
{
$v = StringUtil::uuidToBin($v);
}
$arrUuids[$k] = "UNHEX('" . bin2hex($v) . "')";
}
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = "$t.uuid!=" . implode(", $t.uuid!=", $arrUuids);
}
return static::findBy(array("$t.uuid IN(" . implode(",", $arrUuids) . ")"), null, $arrOptions);
} | php | {
"resource": ""
} |
q243213 | FilesModel.findByPath | validation | public static function findByPath($path, array $arrOptions=array())
{
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
if (strncmp($path, $rootDir . '/', \strlen($rootDir) + 1) === 0)
{
$path = substr($path, \strlen($rootDir) + 1);
}
return static::findOneBy('path', $path, $arrOptions);
} | php | {
"resource": ""
} |
q243214 | FilesModel.findMultipleByPaths | validation | public static function findMultipleByPaths($arrPaths, array $arrOptions=array())
{
if (empty($arrPaths) || !\is_array($arrPaths))
{
return null;
}
$t = static::$strTable;
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = Database::getInstance()->findInSet("$t.path", $arrPaths);
}
return static::findBy(array("$t.path IN(" . implode(',', array_fill(0, \count($arrPaths), '?')) . ")"), $arrPaths, $arrOptions);
} | php | {
"resource": ""
} |
q243215 | FilesModel.findMultipleByUuidsAndExtensions | validation | public static function findMultipleByUuidsAndExtensions($arrUuids, $arrExtensions, array $arrOptions=array())
{
if (empty($arrUuids) || empty($arrExtensions) || !\is_array($arrUuids) || !\is_array($arrExtensions))
{
return null;
}
foreach ($arrExtensions as $k=>$v)
{
if (!preg_match('/^[a-z0-9]{2,5}$/i', $v))
{
unset($arrExtensions[$k]);
}
}
$t = static::$strTable;
foreach ($arrUuids as $k=>$v)
{
// Convert UUIDs to binary
if (Validator::isStringUuid($v))
{
$v = StringUtil::uuidToBin($v);
}
$arrUuids[$k] = "UNHEX('" . bin2hex($v) . "')";
}
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = "$t.uuid!=" . implode(", $t.uuid!=", $arrUuids);
}
return static::findBy(array("$t.uuid IN(" . implode(",", $arrUuids) . ") AND $t.extension IN('" . implode("','", $arrExtensions) . "')"), null, $arrOptions);
} | php | {
"resource": ""
} |
q243216 | FilesModel.findMultipleFilesByFolder | validation | public static function findMultipleFilesByFolder($strPath, array $arrOptions=array())
{
$t = static::$strTable;
$strPath = str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $strPath);
return static::findBy(array("$t.type='file' AND $t.path LIKE ? AND $t.path NOT LIKE ?"), array($strPath.'/%', $strPath.'/%/%'), $arrOptions);
} | php | {
"resource": ""
} |
q243217 | FilesModel.findMultipleFoldersByFolder | validation | public static function findMultipleFoldersByFolder($strPath, array $arrOptions=array())
{
$t = static::$strTable;
$strPath = str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $strPath);
return static::findBy(array("$t.type='folder' AND $t.path LIKE ? AND $t.path NOT LIKE ?"), array($strPath.'/%', $strPath.'/%/%'), $arrOptions);
} | php | {
"resource": ""
} |
q243218 | PreviewUrlCreateListener.onPreviewUrlCreate | validation | public function onPreviewUrlCreate(PreviewUrlCreateEvent $event): void
{
if (!$this->framework->isInitialized() || 'news' !== $event->getKey()) {
return;
}
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
throw new \RuntimeException('The request stack did not contain a request');
}
// Return on the news archive list page
if ('tl_news' === $request->query->get('table') && !$request->query->has('act')) {
return;
}
if (null === ($newsModel = $this->getNewsModel($this->getId($event, $request)))) {
return;
}
$event->setQuery('news='.$newsModel->id);
} | php | {
"resource": ""
} |
q243219 | Message.add | validation | public static function add($strMessage, $strType, $strScope=TL_MODE)
{
if ($strMessage == '')
{
return;
}
if (!\in_array($strType, static::getTypes()))
{
throw new \Exception("Invalid message type $strType");
}
System::getContainer()->get('session')->getFlashBag()->add(static::getFlashBagKey($strType, $strScope), $strMessage);
} | php | {
"resource": ""
} |
q243220 | Message.generate | validation | public static function generate($strScope=TL_MODE)
{
$strMessages = static::generateUnwrapped($strScope);
if ($strMessages != '')
{
$strMessages = '<div class="tl_message">' . $strMessages . '</div>';
}
return $strMessages;
} | php | {
"resource": ""
} |
q243221 | Message.generateUnwrapped | validation | public static function generateUnwrapped($strScope=TL_MODE, $blnRaw=false)
{
$session = System::getContainer()->get('session');
if (!$session->isStarted())
{
return '';
}
$strMessages = '';
$flashBag = $session->getFlashBag();
foreach (static::getTypes() as $strType)
{
$strClass = strtolower($strType);
$arrMessages = $flashBag->get(static::getFlashBagKey($strType, $strScope));
foreach (array_unique($arrMessages) as $strMessage)
{
if ($strType == 'TL_RAW' || $blnRaw)
{
$strMessages .= $strMessage;
}
else
{
$strMessages .= '<p class="' . $strClass . '">' . $strMessage . '</p>';
}
}
}
return trim($strMessages);
} | php | {
"resource": ""
} |
q243222 | Message.reset | validation | public static function reset()
{
$session = System::getContainer()->get('session');
if (!$session->isStarted())
{
return;
}
$session->getFlashBag()->clear();
} | php | {
"resource": ""
} |
q243223 | Message.hasError | validation | public static function hasError($strScope=TL_MODE)
{
$session = System::getContainer()->get('session');
if (!$session->isStarted())
{
return false;
}
return $session->getFlashBag()->has(static::getFlashBagKey('error', $strScope));
} | php | {
"resource": ""
} |
q243224 | Message.hasMessages | validation | public static function hasMessages($strScope=TL_MODE)
{
return static::hasError($strScope) || static::hasConfirmation($strScope) || static::hasNew($strScope) || static::hasInfo($strScope) || static::hasRaw($strScope);
} | php | {
"resource": ""
} |
q243225 | ImageSizes.getAllOptions | validation | public function getAllOptions(): array
{
$this->loadOptions();
$event = new ImageSizesEvent($this->options);
$this->eventDispatcher->dispatch(ContaoCoreEvents::IMAGE_SIZES_ALL, $event);
return $event->getImageSizes();
} | php | {
"resource": ""
} |
q243226 | ImageSizes.getOptionsForUser | validation | public function getOptionsForUser(BackendUser $user): array
{
$this->loadOptions();
if ($user->isAdmin) {
$event = new ImageSizesEvent($this->options, $user);
} else {
$options = array_map(
static function ($val) {
return is_numeric($val) ? (int) $val : $val;
},
StringUtil::deserialize($user->imageSizes, true)
);
$event = new ImageSizesEvent($this->filterOptions($options), $user);
}
$this->eventDispatcher->dispatch(ContaoCoreEvents::IMAGE_SIZES_USER, $event);
return $event->getImageSizes();
} | php | {
"resource": ""
} |
q243227 | ImageSizes.loadOptions | validation | private function loadOptions(): void
{
if (null !== $this->options) {
return;
}
// The framework is required to have the TL_CROP options available
$this->framework->initialize();
$this->options = $GLOBALS['TL_CROP'];
$rows = $this->connection->fetchAll(
'SELECT id, name, width, height FROM tl_image_size ORDER BY pid, name'
);
foreach ($rows as $imageSize) {
$this->options['image_sizes'][$imageSize['id']] = sprintf(
'%s (%sx%s)',
$imageSize['name'],
$imageSize['width'],
$imageSize['height']
);
}
} | php | {
"resource": ""
} |
q243228 | ImageSizes.filterOptions | validation | private function filterOptions(array $allowedSizes): array
{
if (empty($allowedSizes)) {
return [];
}
$filteredSizes = [];
foreach ($this->options as $group => $sizes) {
if ('image_sizes' === $group) {
$this->filterImageSizes($sizes, $allowedSizes, $filteredSizes, $group);
} else {
$this->filterResizeModes($sizes, $allowedSizes, $filteredSizes, $group);
}
}
return $filteredSizes;
} | php | {
"resource": ""
} |
q243229 | Frontend.getRootPageFromUrl | validation | public static function getRootPageFromUrl()
{
$host = Environment::get('host');
$logger = System::getContainer()->get('monolog.logger.contao');
$accept_language = Environment::get('httpAcceptLanguage');
// The language is set in the URL
if (!empty($_GET['language']) && Config::get('addLanguageToUrl'))
{
$strUri = Environment::get('url') . '/' . Input::get('language') . '/';
$strError = 'No root page found (host "' . $host . '", language "'. Input::get('language') .'")';
}
// No language given
else
{
// Always load the language fall back root if "doNotRedirectEmpty" is enabled
if (Config::get('addLanguageToUrl') && Config::get('doNotRedirectEmpty'))
{
$accept_language = '-';
}
$strUri = Environment::get('url') . '/';
$strError = 'No root page found (host "' . Environment::get('host') . '", languages "' . implode(', ', Environment::get('httpAcceptLanguage')) . '")';
}
try
{
$objRequest = Request::create($strUri);
$objRequest->headers->set('Accept-Language', $accept_language);
$arrParameters = System::getContainer()->get('contao.routing.nested_matcher')->matchRequest($objRequest);
$objRootPage = $arrParameters['pageModel'] ?? null;
if (!$objRootPage instanceof PageModel)
{
throw new MissingMandatoryParametersException('Every Contao route must have a "pageModel" parameter');
}
}
catch (RoutingExceptionInterface $exception)
{
$logger->log(LogLevel::ERROR, $strError, array('contao' => new ContaoContext(__METHOD__, 'ERROR')));
throw new NoRootPageFoundException('No root page found', 0, $exception);
}
// Redirect to the website root or language root (e.g. en/)
if (Environment::get('relativeRequest') == '')
{
if (Config::get('addLanguageToUrl') && !Config::get('doNotRedirectEmpty'))
{
$arrParams = array('_locale' => $objRootPage->language);
$strUrl = System::getContainer()->get('router')->generate('contao_index', $arrParams);
$strUrl = substr($strUrl, \strlen(Environment::get('path')) + 1);
static::redirect($strUrl, 301);
}
// Redirect if the page alias is not "index" or "/" (see #8498, #8560 and #1210)
elseif ($objRootPage->type !== 'root' && !\in_array($objRootPage->alias, array('index', '/')))
{
static::redirect($objRootPage->getAbsoluteUrl(), 302);
}
}
if ($objRootPage->type != 'root')
{
return PageModel::findByPk($objRootPage->rootId);
}
return $objRootPage;
} | php | {
"resource": ""
} |
q243230 | Frontend.addToUrl | validation | public static function addToUrl($strRequest, $blnIgnoreParams=false, $arrUnset=array())
{
$arrGet = $blnIgnoreParams ? array() : $_GET;
// Clean the $_GET values (thanks to thyon)
foreach (array_keys($arrGet) as $key)
{
$arrGet[$key] = Input::get($key, true, true);
}
$arrFragments = preg_split('/&(amp;)?/i', $strRequest);
// Merge the new request string
foreach ($arrFragments as $strFragment)
{
list($key, $value) = explode('=', $strFragment);
if ($value == '')
{
unset($arrGet[$key]);
}
else
{
$arrGet[$key] = $value;
}
}
// Unset the language parameter
if (Config::get('addLanguageToUrl'))
{
unset($arrGet['language']);
}
$strParams = '';
$strConnector = '/';
$strSeparator = '/';
// Compile the parameters string
foreach ($arrGet as $k=>$v)
{
// Omit the key if it is an auto_item key (see #5037)
if (Config::get('useAutoItem') && ($k == 'auto_item' || \in_array($k, $GLOBALS['TL_AUTO_ITEM'])))
{
$strParams = $strConnector . urlencode($v) . $strParams;
}
else
{
$strParams .= $strConnector . urlencode($k) . $strSeparator . urlencode($v);
}
}
/** @var PageModel $objPage */
global $objPage;
$pageId = $objPage->alias ?: $objPage->id;
// Get the page ID from URL if not set
if (empty($pageId))
{
$pageId = static::getPageIdFromUrl();
}
$arrParams = array();
$arrParams['alias'] = $pageId . $strParams;
if (Config::get('addLanguageToUrl'))
{
$arrParams['_locale'] = $objPage->rootLanguage;
}
$strUrl = System::getContainer()->get('router')->generate('contao_frontend', $arrParams);
$strUrl = substr($strUrl, \strlen(Environment::get('path')) + 1);
return $strUrl;
} | php | {
"resource": ""
} |
q243231 | Frontend.jumpToOrReload | validation | protected function jumpToOrReload($intId, $strParams=null, $strForceLang=null)
{
if ($strForceLang !== null)
{
@trigger_error('Using Frontend::jumpToOrReload() with $strForceLang has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
}
/** @var PageModel $objPage */
global $objPage;
// Always redirect if there are additional arguments (see #5734)
$blnForceRedirect = ($strParams !== null || $strForceLang !== null);
if (\is_array($intId))
{
$intId = $intId['id'] ?? 0;
}
if ($intId > 0 && ($intId != $objPage->id || $blnForceRedirect) && ($objNextPage = PageModel::findPublishedById($intId)) !== null)
{
$this->redirect($objNextPage->getFrontendUrl($strParams, $strForceLang));
}
$this->reload();
} | php | {
"resource": ""
} |
q243232 | Frontend.getLoginStatus | validation | protected function getLoginStatus($strCookie)
{
@trigger_error('Using Frontend::getLoginStatus() has been deprecated and will no longer work in Contao 5.0. Use Symfony security instead.', E_USER_DEPRECATED);
$objTokenChecker = System::getContainer()->get('contao.security.token_checker');
if ($strCookie == 'BE_USER_AUTH' && $objTokenChecker->hasBackendUser())
{
// Always return false if we are not in preview mode (show hidden elements)
if (TL_MODE == 'FE' && !$objTokenChecker->isPreviewMode())
{
return false;
}
return true;
}
if ($strCookie == 'FE_USER_AUTH' && $objTokenChecker->hasFrontendUser())
{
return true;
}
return false;
} | php | {
"resource": ""
} |
q243233 | Frontend.getMetaData | validation | public static function getMetaData($strData, $strLanguage)
{
if (empty($strLanguage))
{
return array();
}
$arrData = StringUtil::deserialize($strData);
// Convert the language to a locale (see #5678)
$strLanguage = str_replace('-', '_', $strLanguage);
if (!\is_array($arrData) || !isset($arrData[$strLanguage]))
{
return array();
}
return $arrData[$strLanguage];
} | php | {
"resource": ""
} |
q243234 | Frontend.prepareMetaDescription | validation | protected function prepareMetaDescription($strText)
{
$strText = $this->replaceInsertTags($strText, false);
$strText = strip_tags($strText);
$strText = str_replace("\n", ' ', $strText);
$strText = StringUtil::substr($strText, 320);
return trim($strText);
} | php | {
"resource": ""
} |
q243235 | Frontend.indexPageIfApplicable | validation | public static function indexPageIfApplicable(Response $objResponse)
{
global $objPage;
if ($objPage === null)
{
return;
}
// Index page if searching is allowed and there is no back end user
if (Config::get('enableSearch') && $objResponse->getStatusCode() == 200 && !BE_USER_LOGGED_IN && !$objPage->noSearch)
{
// Index protected pages if enabled
if (Config::get('indexProtected') || (!FE_USER_LOGGED_IN && !$objPage->protected))
{
$blnIndex = true;
// Do not index the page if certain parameters are set
foreach (array_keys($_GET) as $key)
{
if (\in_array($key, $GLOBALS['TL_NOINDEX_KEYS']) || strncmp($key, 'page_', 5) === 0)
{
$blnIndex = false;
break;
}
}
if ($blnIndex)
{
$arrData = array(
'url' => Environment::get('base') . Environment::get('relativeRequest'),
'content' => $objResponse->getContent(),
'title' => $objPage->pageTitle ?: $objPage->title,
'protected' => ($objPage->protected ? '1' : ''),
'groups' => $objPage->groups,
'pid' => $objPage->id,
'language' => $objPage->language
);
Search::indexPage($arrData);
}
}
}
} | php | {
"resource": ""
} |
q243236 | Feed.generateRss | validation | public function generateRss()
{
$this->adjustPublicationDate();
$xml = '<?xml version="1.0" encoding="' . Config::get('characterSet') . '"?>';
$xml .= '<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/" xmlns:atom="http://www.w3.org/2005/Atom">';
$xml .= '<channel>';
$xml .= '<title>' . StringUtil::specialchars($this->title) . '</title>';
$xml .= '<description>' . StringUtil::specialchars($this->description) . '</description>';
$xml .= '<link>' . StringUtil::specialchars($this->link) . '</link>';
$xml .= '<language>' . $this->language . '</language>';
$xml .= '<pubDate>' . date('r', $this->published) . '</pubDate>';
$xml .= '<generator>Contao Open Source CMS</generator>';
$xml .= '<atom:link href="' . StringUtil::specialchars(Environment::get('base') . 'share/' . $this->strName) . '.xml" rel="self" type="application/rss+xml" />';
foreach ($this->arrItems as $objItem)
{
$xml .= '<item>';
$xml .= '<title>' . StringUtil::specialchars(strip_tags(StringUtil::stripInsertTags($objItem->title))) . '</title>';
$xml .= '<description><![CDATA[' . preg_replace('/[\n\r]+/', ' ', $objItem->description) . ']]></description>';
$xml .= '<link>' . StringUtil::specialchars($objItem->link) . '</link>';
$xml .= '<pubDate>' . date('r', $objItem->published) . '</pubDate>';
// Add the GUID
if ($objItem->guid)
{
// Add the isPermaLink attribute if the guid is not a link (see #4930)
if (strncmp($objItem->guid, 'http://', 7) !== 0 && strncmp($objItem->guid, 'https://', 8) !== 0)
{
$xml .= '<guid isPermaLink="false">' . $objItem->guid . '</guid>';
}
else
{
$xml .= '<guid>' . $objItem->guid . '</guid>';
}
}
else
{
$xml .= '<guid>' . StringUtil::specialchars($objItem->link) . '</guid>';
}
// Enclosures
if (\is_array($objItem->enclosure))
{
foreach ($objItem->enclosure as $arrEnclosure)
{
if (!empty($arrEnclosure['media']) && $arrEnclosure['media'] == 'media:content')
{
$xml .= '<media:content url="' . $arrEnclosure['url'] . '" type="' . $arrEnclosure['type'] . '" />';
}
else
{
$xml .= '<enclosure url="' . $arrEnclosure['url'] . '" length="' . $arrEnclosure['length'] . '" type="' . $arrEnclosure['type'] . '" />';
}
}
}
$xml .= '</item>';
}
$xml .= '</channel>';
$xml .= '</rss>';
return $xml;
} | php | {
"resource": ""
} |
q243237 | Feed.adjustPublicationDate | validation | protected function adjustPublicationDate()
{
if (!empty($this->arrItems) && $this->arrItems[0]->published > $this->published)
{
$this->published = $this->arrItems[0]->published;
}
} | php | {
"resource": ""
} |
q243238 | ParameterDumper.dump | validation | public function dump(): void
{
if (
empty($this->parameters['parameters']['secret']) ||
'ThisTokenIsNotSoSecretChangeIt' === $this->parameters['parameters']['secret']
) {
$this->parameters['parameters']['secret'] = bin2hex(random_bytes(32));
}
if (isset($this->parameters['parameters']['database_port'])) {
$this->parameters['parameters']['database_port'] = (int) $this->parameters['parameters']['database_port'];
}
$this->filesystem->dumpFile(
$this->rootDir.'/app/config/parameters.yml',
"# This file has been auto-generated during installation\n".Yaml::dump($this->getEscapedValues())
);
} | php | {
"resource": ""
} |
q243239 | LanguageResolver.getLocale | validation | public function getLocale(): string
{
foreach ($this->getAcceptedLocales() as $locale) {
if (file_exists($this->translationsDir.'/messages.'.$locale.'.xlf')) {
return $locale;
}
}
return 'en';
} | php | {
"resource": ""
} |
q243240 | LanguageResolver.getAcceptedLocales | validation | private function getAcceptedLocales(): array
{
$accepted = [];
$locales = [];
// The implementation differs from the original implementation and also works with .jp browsers
preg_match_all(
'/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.\d+))?/i',
$this->requestStack->getCurrentRequest()->headers->get('accept-language'),
$accepted
);
// Remove all invalid locales
foreach ($accepted[1] as $v) {
$chunks = explode('-', $v);
// Language plus dialect, e.g. "en-US" or "fr-FR"
if (isset($chunks[1])) {
$locale = $chunks[0].'-'.strtoupper($chunks[1]);
if (preg_match('/^[a-z]{2}(\-[A-Z]{2})?$/', $locale)) {
$locales[] = $locale;
}
}
// Language only, e.g. "en" or "fr"
if (preg_match('/^[a-z]{2}$/', $chunks[0])) {
$locales[] = $chunks[0];
}
}
return \array_slice(array_unique($locales), 0, 8);
} | php | {
"resource": ""
} |
q243241 | BackendCsvImportController.fetchData | validation | private function fetchData(FileUpload $uploader, string $separator, callable $callback): array
{
$data = [];
$files = $this->getFiles($uploader);
$delimiter = $this->getDelimiter($separator);
foreach ($files as $file) {
$fp = fopen($file, 'r');
while (false !== ($row = fgetcsv($fp, 0, $delimiter))) {
$data = $callback($data, $row);
}
}
return $data;
} | php | {
"resource": ""
} |
q243242 | BackendCsvImportController.getFiles | validation | private function getFiles(FileUpload $uploader): array
{
$files = $uploader->uploadTo('system/tmp');
if (\count($files) < 1) {
throw new \RuntimeException($this->translator->trans('ERR.all_fields', [], 'contao_default'));
}
foreach ($files as &$file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if ('csv' !== $extension) {
throw new \RuntimeException(
sprintf($this->translator->trans('ERR.filetype', [], 'contao_default'), $extension)
);
}
$file = $this->projectDir.'/'.$file;
}
return $files;
} | php | {
"resource": ""
} |
q243243 | PackageUtil.getVersion | validation | public static function getVersion(string $packageName): string
{
$version = Versions::getVersion($packageName);
return static::parseVersion($version);
} | php | {
"resource": ""
} |
q243244 | PackageUtil.getNormalizedVersion | validation | public static function getNormalizedVersion(string $packageName): string
{
$chunks = explode('.', static::getVersion($packageName));
$chunks += [0, 0, 0];
if (\count($chunks) > 3) {
$chunks = \array_slice($chunks, 0, 3);
}
return implode('.', $chunks);
} | php | {
"resource": ""
} |
q243245 | FormTextField.addAttributes | validation | public function addAttributes($arrAttributes)
{
parent::addAttributes($arrAttributes);
if ($this->type != 'number')
{
return;
}
foreach (array('minlength', 'minval', 'maxlength', 'maxval') as $name)
{
if (isset($arrAttributes[$name]))
{
$this->$name = $arrAttributes[$name];
}
}
} | php | {
"resource": ""
} |
q243246 | ModuleUnsubscribe.validateForm | validation | protected function validateForm(Widget $objWidget=null)
{
// Validate the e-mail address
$varInput = Idna::encodeEmail(Input::post('email', true));
if (!Validator::isEmail($varInput))
{
$this->Template->mclass = 'error';
$this->Template->message = $GLOBALS['TL_LANG']['ERR']['email'];
return false;
}
$this->Template->email = $varInput;
// Validate the channel selection
$arrChannels = Input::post('channels');
if (!\is_array($arrChannels))
{
$this->Template->mclass = 'error';
$this->Template->message = $GLOBALS['TL_LANG']['ERR']['noChannels'];
return false;
}
$arrChannels = array_intersect($arrChannels, $this->nl_channels); // see #3240
if (empty($arrChannels) || !\is_array($arrChannels))
{
$this->Template->mclass = 'error';
$this->Template->message = $GLOBALS['TL_LANG']['ERR']['noChannels'];
return false;
}
$this->Template->selectedChannels = $arrChannels;
// Check if there are any new subscriptions
$arrSubscriptions = array();
if (($objSubscription = NewsletterRecipientsModel::findBy(array("email=? AND active='1'"), $varInput)) !== null)
{
$arrSubscriptions = $objSubscription->fetchEach('pid');
}
$arrChannels = array_intersect($arrChannels, $arrSubscriptions);
if (empty($arrChannels))
{
$this->Template->mclass = 'error';
$this->Template->message = $GLOBALS['TL_LANG']['ERR']['unsubscribed'];
return false;
}
// Validate the captcha
if ($objWidget !== null)
{
$objWidget->validate();
if ($objWidget->hasErrors())
{
return false;
}
}
return array($varInput, $arrChannels);
} | php | {
"resource": ""
} |
q243247 | ModuleUnsubscribe.removeRecipient | validation | protected function removeRecipient($strEmail, $arrRemove)
{
// Remove the subscriptions
if (($objRemove = NewsletterRecipientsModel::findByEmailAndPids($strEmail, $arrRemove)) !== null)
{
while ($objRemove->next())
{
$strHash = md5($objRemove->email);
// Add a blacklist entry (see #4999)
if (($objBlacklist = NewsletterBlacklistModel::findByHashAndPid($strHash, $objRemove->pid)) === null)
{
$objBlacklist = new NewsletterBlacklistModel();
$objBlacklist->pid = $objRemove->pid;
$objBlacklist->hash = $strHash;
$objBlacklist->save();
}
$objRemove->delete();
}
}
// Get the channels
$objChannels = NewsletterChannelModel::findByIds($arrRemove);
$arrChannels = $objChannels->fetchEach('title');
// HOOK: post unsubscribe callback
if (isset($GLOBALS['TL_HOOKS']['removeRecipient']) && \is_array($GLOBALS['TL_HOOKS']['removeRecipient']))
{
foreach ($GLOBALS['TL_HOOKS']['removeRecipient'] as $callback)
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($strEmail, $arrRemove);
}
}
// Prepare the simple token data
$arrData = array();
$arrData['domain'] = Idna::decode(Environment::get('host'));
$arrData['channel'] = $arrData['channels'] = implode("\n", $arrChannels);
// Confirmation e-mail
$objEmail = new Email();
$objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
$objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
$objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['nl_subject'], Idna::decode(Environment::get('host')));
$objEmail->text = StringUtil::parseSimpleTokens($this->nl_unsubscribe, $arrData);
$objEmail->sendTo($strEmail);
// Redirect to the jumpTo page
if (($objTarget = $this->objModel->getRelated('jumpTo')) instanceof PageModel)
{
/** @var PageModel $objTarget */
$this->redirect($objTarget->getFrontendUrl());
}
System::getContainer()->get('session')->getFlashBag()->set('nl_removed', $GLOBALS['TL_LANG']['MSC']['nl_removed']);
$this->reload();
} | php | {
"resource": ""
} |
q243248 | ExceptionConverterListener.onKernelException | validation | public function onKernelException(GetResponseForExceptionEvent $event): void
{
$exception = $event->getException();
if ($exception->getPrevious() instanceof ResourceNotFoundException && !$this->hasRootPages()) {
$exception = new NoRootPageFoundException('No root page found', 0, $exception);
}
$class = $this->getTargetClass($exception);
if (null === $class) {
return;
}
if (null !== ($httpException = $this->convertToHttpException($exception, $class))) {
$event->setException($httpException);
}
} | php | {
"resource": ""
} |
q243249 | Translator.loadLanguageFile | validation | private function loadLanguageFile(string $name): void
{
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile($name);
} | php | {
"resource": ""
} |
q243250 | GlobalsMapListener.onInitializeSystem | validation | public function onInitializeSystem(): void
{
foreach ($this->globals as $key => $value) {
if (\is_array($value) && isset($GLOBALS[$key]) && \is_array($GLOBALS[$key])) {
$GLOBALS[$key] = array_replace_recursive($GLOBALS[$key], $value);
} else {
$GLOBALS[$key] = $value;
}
}
} | php | {
"resource": ""
} |
q243251 | InitializeController.indexAction | validation | public function indexAction(): InitializeControllerResponse
{
@trigger_error('Custom entry points are deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
$masterRequest = $this->get('request_stack')->getMasterRequest();
if (null === $masterRequest) {
throw new \RuntimeException('The request stack did not contain a master request.');
}
$realRequest = Request::createFromGlobals();
// Necessary to generate the correct base path
foreach (['REQUEST_URI', 'SCRIPT_NAME', 'SCRIPT_FILENAME', 'PHP_SELF'] as $name) {
$realRequest->server->set(
$name,
str_replace(TL_SCRIPT, 'index.php', $realRequest->server->get($name))
);
}
$realRequest->attributes->replace($masterRequest->attributes->all());
// Initialize the framework with the real request
$this->get('request_stack')->push($realRequest);
$this->get('contao.framework')->initialize();
// Add the master request again. When Kernel::handle() is finished,
// it will pop the current request, resulting in the real request being active.
$this->get('request_stack')->push($masterRequest);
return new InitializeControllerResponse('', 204);
} | php | {
"resource": ""
} |
q243252 | CalendarFeedModel.findByCalendar | validation | public static function findByCalendar($intId, array $arrOptions=array())
{
$t = static::$strTable;
return static::findBy(array("$t.calendars LIKE '%\"" . (int) $intId . "\"%'"), null, $arrOptions);
} | php | {
"resource": ""
} |
q243253 | ClassLoader.addNamespace | validation | public static function addNamespace($name)
{
@trigger_error('Using ClassLoader::addNamespace() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
if (\in_array($name, self::$namespaces))
{
return;
}
array_unshift(self::$namespaces, $name);
} | php | {
"resource": ""
} |
q243254 | ClassLoader.addNamespaces | validation | public static function addNamespaces($names)
{
@trigger_error('Using ClassLoader::addNamespaces() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
foreach ($names as $name)
{
self::addNamespace($name);
}
} | php | {
"resource": ""
} |
q243255 | ClassLoader.addClasses | validation | public static function addClasses($classes)
{
@trigger_error('Using ClassLoader::addClasses() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
foreach ($classes as $class=>$file)
{
self::addClass($class, $file);
}
} | php | {
"resource": ""
} |
q243256 | ClassLoader.load | validation | public static function load($class)
{
if (class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false))
{
return;
}
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
// The class file is set in the mapper
if (isset(self::$classes[$class]))
{
if (Config::get('debugMode'))
{
$GLOBALS['TL_DEBUG']['classes_set'][$class] = $class;
}
include $rootDir . '/' . self::$classes[$class];
}
// Find the class in the registered namespaces
elseif (($namespaced = self::findClass($class)) !== null)
{
if (!class_exists($namespaced, false) && !interface_exists($namespaced, false) && !trait_exists($namespaced, false))
{
if (Config::get('debugMode'))
{
$GLOBALS['TL_DEBUG']['classes_aliased'][$class] = $namespaced;
}
include $rootDir . '/' . self::$classes[$namespaced];
}
class_alias($namespaced, $class);
}
// Try to map the class to a Contao class loaded via Composer
elseif (strncmp($class, 'Contao\\', 7) !== 0)
{
$namespaced = 'Contao\\' . $class;
if (class_exists($namespaced) || interface_exists($namespaced) || trait_exists($namespaced))
{
if (Config::get('debugMode'))
{
$GLOBALS['TL_DEBUG']['classes_composerized'][$class] = $namespaced;
}
if (!class_exists($class, false) && !interface_exists($class, false) && !trait_exists($class, false))
{
class_alias($namespaced, $class);
}
}
}
// Pass the request to other autoloaders (e.g. Swift)
} | php | {
"resource": ""
} |
q243257 | FileUpload.generateMarkup | validation | public function generateMarkup()
{
$return = '
<div>
<input type="file" name="' . $this->strName . '[]" class="tl_upload_field" onfocus="Backend.getScrollOffset()" multiple required>
</div>';
if (isset($GLOBALS['TL_LANG']['tl_files']['fileupload'][1]))
{
$return .= '
<p class="tl_help tl_tip">' . sprintf($GLOBALS['TL_LANG']['tl_files']['fileupload'][1], System::getReadableSize(static::getMaxUploadSize()), Config::get('gdMaxImgWidth') . 'x' . Config::get('gdMaxImgHeight')) . '</p>';
}
return $return;
} | php | {
"resource": ""
} |
q243258 | FileUpload.resizeUploadedImage | validation | protected function resizeUploadedImage($strImage)
{
// The feature is disabled
if (Config::get('imageWidth') < 1 && Config::get('imageHeight') < 1)
{
return false;
}
$objFile = new File($strImage);
// Not an image
if (!$objFile->isSvgImage && !$objFile->isGdImage)
{
return false;
}
$arrImageSize = $objFile->imageSize;
// The image is too big to be handled by the GD library
if ($objFile->isGdImage && ($arrImageSize[0] > Config::get('gdMaxImgWidth') || $arrImageSize[1] > Config::get('gdMaxImgHeight')))
{
Message::addInfo(sprintf($GLOBALS['TL_LANG']['MSC']['fileExceeds'], $objFile->basename));
$this->log('File "' . $strImage . '" is too big to be resized automatically', __METHOD__, TL_FILES);
return false;
}
$blnResize = false;
// The image exceeds the maximum image width
if ($arrImageSize[0] > Config::get('imageWidth'))
{
$blnResize = true;
$intWidth = Config::get('imageWidth');
$intHeight = round(Config::get('imageWidth') * $arrImageSize[1] / $arrImageSize[0]);
$arrImageSize = array($intWidth, $intHeight);
}
// The image exceeds the maximum image height
if ($arrImageSize[1] > Config::get('imageHeight'))
{
$blnResize = true;
$intWidth = round(Config::get('imageHeight') * $arrImageSize[0] / $arrImageSize[1]);
$intHeight = Config::get('imageHeight');
$arrImageSize = array($intWidth, $intHeight);
}
// Resized successfully
if ($blnResize)
{
$container = System::getContainer();
$rootDir = $container->getParameter('kernel.project_dir');
$container->get('contao.image.image_factory')->create($rootDir . '/' . $strImage, array($arrImageSize[0], $arrImageSize[1]), $rootDir . '/' . $strImage);
Message::addInfo(sprintf($GLOBALS['TL_LANG']['MSC']['fileResized'], $objFile->basename));
$this->log('File "' . $strImage . '" was scaled down to the maximum dimensions', __METHOD__, TL_FILES);
$this->blnHasResized = true;
return true;
}
return false;
} | php | {
"resource": ""
} |
q243259 | ContaoCoreExtension.setImagineService | validation | private function setImagineService(array $config, ContainerBuilder $container): void
{
$imagineServiceId = $config['image']['imagine_service'];
// Generate if not present
if (null === $imagineServiceId) {
$class = $this->getImagineImplementation();
$imagineServiceId = 'contao.image.imagine.'.ContainerBuilder::hash($class);
$container->setDefinition($imagineServiceId, new Definition($class));
}
$container->setAlias('contao.image.imagine', $imagineServiceId)->setPublic(true);
} | php | {
"resource": ""
} |
q243260 | ContaoCoreExtension.overwriteImageTargetDir | validation | private function overwriteImageTargetDir(array $config, ContainerBuilder $container): void
{
if (!isset($config['image']['target_path'])) {
return;
}
$container->setParameter(
'contao.image.target_dir',
$container->getParameter('kernel.project_dir').'/'.$config['image']['target_path']
);
@trigger_error('Using the contao.image.target_path parameter has been deprecated and will no longer work in Contao 5.0. Use the contao.image.target_dir parameter instead.', E_USER_DEPRECATED);
} | php | {
"resource": ""
} |
q243261 | ModuleFaq.getSearchablePages | validation | public function getSearchablePages($arrPages, $intRoot=0, $blnIsSitemap=false)
{
$arrRoot = array();
if ($intRoot > 0)
{
$arrRoot = $this->Database->getChildRecords($intRoot, 'tl_page');
}
$arrProcessed = array();
$time = Date::floorToMinute();
// Get all categories
$objFaq = FaqCategoryModel::findAll();
// Walk through each category
if ($objFaq !== null)
{
while ($objFaq->next())
{
// Skip FAQs without target page
if (!$objFaq->jumpTo)
{
continue;
}
// Skip FAQs outside the root nodes
if (!empty($arrRoot) && !\in_array($objFaq->jumpTo, $arrRoot))
{
continue;
}
// Get the URL of the jumpTo page
if (!isset($arrProcessed[$objFaq->jumpTo]))
{
$objParent = PageModel::findWithDetails($objFaq->jumpTo);
// The target page does not exist
if ($objParent === null)
{
continue;
}
// The target page has not been published (see #5520)
if (!$objParent->published || ($objParent->start != '' && $objParent->start > $time) || ($objParent->stop != '' && $objParent->stop <= ($time + 60)))
{
continue;
}
if ($blnIsSitemap)
{
// The target page is protected (see #8416)
if ($objParent->protected)
{
continue;
}
// The target page is exempt from the sitemap (see #6418)
if ($objParent->sitemap == 'map_never')
{
continue;
}
}
// Generate the URL
$arrProcessed[$objFaq->jumpTo] = $objParent->getAbsoluteUrl(Config::get('useAutoItem') ? '/%s' : '/items/%s');
}
$strUrl = $arrProcessed[$objFaq->jumpTo];
// Get the items
$objItems = FaqModel::findPublishedByPid($objFaq->id);
if ($objItems !== null)
{
while ($objItems->next())
{
$arrPages[] = sprintf(preg_replace('/%(?!s)/', '%%', $strUrl), ($objItems->alias ?: $objItems->id));
}
}
}
}
return $arrPages;
} | php | {
"resource": ""
} |
q243262 | PageModel.findPublishedByPid | validation | public static function findPublishedByPid($intPid, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.pid=?");
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::findBy($arrColumns, $intPid, $arrOptions);
} | php | {
"resource": ""
} |
q243263 | PageModel.findFirstPublishedRootByHostAndLanguage | validation | public static function findFirstPublishedRootByHostAndLanguage($strHost, $varLanguage, array $arrOptions=array())
{
@trigger_error('Using PageModel::findFirstPublishedRootByHostAndLanguage() has been deprecated and will no longer work Contao 5.0.', E_USER_DEPRECATED);
$t = static::$strTable;
$objDatabase = Database::getInstance();
if (\is_array($varLanguage))
{
$arrColumns = array("$t.type='root' AND ($t.dns=? OR $t.dns='')");
if (!empty($varLanguage))
{
$arrColumns[] = "($t.language IN('". implode("','", $varLanguage) ."') OR $t.fallback='1')";
}
else
{
$arrColumns[] = "$t.fallback='1'";
}
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = "$t.dns DESC" . (!empty($varLanguage) ? ", " . $objDatabase->findInSet("$t.language", array_reverse($varLanguage)) . " DESC" : "") . ", $t.sorting";
}
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, $strHost, $arrOptions);
}
else
{
$arrColumns = array("$t.type='root' AND ($t.dns=? OR $t.dns='') AND ($t.language=? OR $t.fallback='1')");
$arrValues = array($strHost, $varLanguage);
if (!isset($arrOptions['order']))
{
$arrOptions['order'] = "$t.dns DESC, $t.fallback";
}
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": ""
} |
q243264 | PageModel.findFirstPublishedByPid | validation | public static function findFirstPublishedByPid($intPid, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.pid=? AND $t.type!='root' AND $t.type!='error_401' AND $t.type!='error_403' AND $t.type!='error_404'");
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::findOneBy($arrColumns, $intPid, $arrOptions);
} | php | {
"resource": ""
} |
q243265 | PageModel.findByAliases | validation | public static function findByAliases($arrAliases, array $arrOptions=array())
{
if (empty($arrAliases) || !\is_array($arrAliases))
{
return null;
}
// Remove everything that is not an alias
$arrAliases = array_filter(array_map(function ($v) { return preg_match('/^[\w\/.-]+$/u', $v) ? $v : null; }, $arrAliases));
// Return if nothing is left
if (empty($arrAliases))
{
return null;
}
$t = static::$strTable;
$arrColumns = array("$t.alias IN('" . implode("','", array_filter($arrAliases)) . "')");
// Check the publication status (see #4652)
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'] = Database::getInstance()->findInSet("$t.alias", $arrAliases);
}
return static::findBy($arrColumns, null, $arrOptions);
} | php | {
"resource": ""
} |
q243266 | PageModel.findPublishedByIdOrAlias | validation | public static function findPublishedByIdOrAlias($varId, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = !preg_match('/^[1-9]\d*$/', $varId) ? array("$t.alias=?") : array("$t.id=?");
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::findBy($arrColumns, $varId, $arrOptions);
} | php | {
"resource": ""
} |
q243267 | PageModel.findPublishedSubpagesWithoutGuestsByPid | validation | public static function findPublishedSubpagesWithoutGuestsByPid($intPid, $blnShowHidden=false, $blnIsSitemap=false)
{
$time = Date::floorToMinute();
$objSubpages = Database::getInstance()->prepare("SELECT p1.*, (SELECT COUNT(*) FROM tl_page p2 WHERE p2.pid=p1.id AND p2.type!='root' AND p2.type!='error_401' AND p2.type!='error_403' AND p2.type!='error_404'" . (!$blnShowHidden ? ($blnIsSitemap ? " AND (p2.hide='' OR sitemap='map_always')" : " AND p2.hide=''") : "") . (FE_USER_LOGGED_IN ? " AND p2.guests=''" : "") . (!BE_USER_LOGGED_IN ? " AND (p2.start='' OR p2.start<='$time') AND (p2.stop='' OR p2.stop>'" . ($time + 60) . "') AND p2.published='1'" : "") . ") AS subpages FROM tl_page p1 WHERE p1.pid=? AND p1.type!='root' AND p1.type!='error_401' AND p1.type!='error_403' AND p1.type!='error_404'" . (!$blnShowHidden ? ($blnIsSitemap ? " AND (p1.hide='' OR sitemap='map_always')" : " AND p1.hide=''") : "") . (FE_USER_LOGGED_IN ? " AND p1.guests=''" : "") . (!BE_USER_LOGGED_IN ? " AND (p1.start='' OR p1.start<='$time') AND (p1.stop='' OR p1.stop>'" . ($time + 60) . "') AND p1.published='1'" : "") . " ORDER BY p1.sorting")
->execute($intPid);
if ($objSubpages->numRows < 1)
{
return null;
}
return static::createCollectionFromDbResult($objSubpages, 'tl_page');
} | php | {
"resource": ""
} |
q243268 | PageModel.findPublishedRegularWithoutGuestsByIds | validation | public static function findPublishedRegularWithoutGuestsByIds($arrIds, array $arrOptions=array())
{
if (empty($arrIds) || !\is_array($arrIds))
{
return null;
}
$t = static::$strTable;
$arrColumns = array("$t.id IN(" . implode(',', array_map('\intval', $arrIds)) . ") AND $t.type!='error_401' AND $t.type!='error_403' AND $t.type!='error_404'");
if (empty($arrOptions['includeRoot']))
{
$arrColumns[] = "$t.type!='root'";
}
if (FE_USER_LOGGED_IN)
{
$arrColumns[] = "$t.guests=''";
}
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'] = Database::getInstance()->findInSet("$t.id", $arrIds);
}
return static::findBy($arrColumns, null, $arrOptions);
} | php | {
"resource": ""
} |
q243269 | PageModel.findPublishedRegularWithoutGuestsByPid | validation | public static function findPublishedRegularWithoutGuestsByPid($intPid, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.pid=? AND $t.type!='root' AND $t.type!='error_401' AND $t.type!='error_403' AND $t.type!='error_404'");
if (FE_USER_LOGGED_IN)
{
$arrColumns[] = "$t.guests=''";
}
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, $intPid, $arrOptions);
} | php | {
"resource": ""
} |
q243270 | PageModel.findPublishedFallbackByHostname | validation | public static function findPublishedFallbackByHostname($strHost, array $arrOptions=array())
{
// Try to load from the registry (see #8544)
if (empty($arrOptions))
{
$objModel = Registry::getInstance()->fetch(static::$strTable, $strHost, 'contao.dns-fallback');
if ($objModel !== null)
{
return $objModel;
}
}
$t = static::$strTable;
$arrColumns = array("$t.dns=? AND $t.fallback='1'");
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, $strHost, $arrOptions);
} | php | {
"resource": ""
} |
q243271 | PageModel.findPublishedRootPages | validation | public static function findPublishedRootPages(array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = array("$t.type=?");
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::findBy($arrColumns, 'root', $arrOptions);
} | php | {
"resource": ""
} |
q243272 | PageModel.findParentsById | validation | public static function findParentsById($intId)
{
$arrModels = array();
while ($intId > 0 && ($objPage = static::findByPk($intId)) !== null)
{
$intId = $objPage->pid;
$arrModels[] = $objPage;
}
if (empty($arrModels))
{
return null;
}
return static::createCollection($arrModels, 'tl_page');
} | php | {
"resource": ""
} |
q243273 | PageModel.findFirstActiveByMemberGroups | validation | public static function findFirstActiveByMemberGroups($arrIds)
{
if (empty($arrIds) || !\is_array($arrIds))
{
return null;
}
$time = Date::floorToMinute();
$objDatabase = Database::getInstance();
$arrIds = array_map('\intval', $arrIds);
$objResult = $objDatabase->prepare("SELECT p.* FROM tl_member_group g LEFT JOIN tl_page p ON g.jumpTo=p.id WHERE g.id IN(" . implode(',', $arrIds) . ") AND g.jumpTo>0 AND g.redirect='1' AND g.disable!='1' AND (g.start='' OR g.start<='$time') AND (g.stop='' OR g.stop>'" . ($time + 60) . "') AND p.published='1' AND (p.start='' OR p.start<='$time') AND (p.stop='' OR p.stop>'" . ($time + 60) . "') ORDER BY " . $objDatabase->findInSet('g.id', $arrIds))
->limit(1)
->execute();
if ($objResult->numRows < 1)
{
return null;
}
$objRegistry = Registry::getInstance();
/** @var PageModel|Model $objPage */
if ($objPage = $objRegistry->fetch('tl_page', $objResult->id))
{
return $objPage;
}
return new static($objResult);
} | php | {
"resource": ""
} |
q243274 | PageModel.findWithDetails | validation | public static function findWithDetails($intId)
{
$objPage = static::findByPk($intId);
if ($objPage === null)
{
return null;
}
return $objPage->loadDetails();
} | php | {
"resource": ""
} |
q243275 | PageModel.onRegister | validation | public function onRegister(Registry $registry)
{
parent::onRegister($registry);
// Register this model as being the fallback page for a given dns
if ($this->fallback && $this->type == 'root' && !$registry->isRegisteredAlias($this, 'contao.dns-fallback', $this->dns))
{
$registry->registerAlias($this, 'contao.dns-fallback', $this->dns);
}
} | php | {
"resource": ""
} |
q243276 | PageModel.onUnregister | validation | public function onUnregister(Registry $registry)
{
parent::onUnregister($registry);
// Unregister the fallback page
if ($this->fallback && $this->type == 'root' && $registry->isRegisteredAlias($this, 'contao.dns-fallback', $this->dns))
{
$registry->unregisterAlias($this, 'contao.dns-fallback', $this->dns);
}
} | php | {
"resource": ""
} |
q243277 | PageModel.getAbsoluteUrl | validation | public function getAbsoluteUrl($strParams=null)
{
$this->loadDetails();
$objUrlGenerator = System::getContainer()->get('contao.routing.url_generator');
$strUrl = $objUrlGenerator->generate
(
($this->alias ?: $this->id) . $strParams,
array
(
'_locale' => $this->rootLanguage,
'_domain' => $this->domain,
'_ssl' => (bool) $this->rootUseSSL,
),
UrlGeneratorInterface::ABSOLUTE_URL
);
$strUrl = $this->applyLegacyLogic($strUrl, $strParams);
return $strUrl;
} | php | {
"resource": ""
} |
q243278 | PageModel.getSlugOptions | validation | public function getSlugOptions()
{
$slugOptions = array('locale'=>$this->language);
if ($this->validAliasCharacters)
{
$slugOptions['validChars'] = $this->validAliasCharacters;
}
return $slugOptions;
} | php | {
"resource": ""
} |
q243279 | PageModel.applyLegacyLogic | validation | private function applyLegacyLogic($strUrl, $strParams)
{
// Decode sprintf placeholders
if (strpos($strParams, '%') !== false)
{
@trigger_error('Using sprintf placeholders in URLs has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
$arrMatches = array();
preg_match_all('/%([sducoxXbgGeEfF])/', $strParams, $arrMatches);
foreach (array_unique($arrMatches[1]) as $v)
{
$strUrl = str_replace('%25' . $v, '%' . $v, $strUrl);
}
}
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['generateFrontendUrl']) && \is_array($GLOBALS['TL_HOOKS']['generateFrontendUrl']))
{
@trigger_error('Using the "generateFrontendUrl" hook has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
foreach ($GLOBALS['TL_HOOKS']['generateFrontendUrl'] as $callback)
{
$strUrl = System::importStatic($callback[0])->{$callback[1]}($this->row(), $strParams, $strUrl);
}
return $strUrl;
}
return $strUrl;
} | php | {
"resource": ""
} |
q243280 | PictureFactory.createConfig | validation | private function createConfig($size): array
{
if (!\is_array($size)) {
$size = [0, 0, $size];
}
$config = new PictureConfiguration();
$attributes = [];
if (!isset($size[2]) || !is_numeric($size[2])) {
$resizeConfig = new ResizeConfiguration();
if (!empty($size[0])) {
$resizeConfig->setWidth((int) $size[0]);
}
if (!empty($size[1])) {
$resizeConfig->setHeight((int) $size[1]);
}
if (!empty($size[2])) {
$resizeConfig->setMode($size[2]);
}
$configItem = new PictureConfigurationItem();
$configItem->setResizeConfig($resizeConfig);
if ($this->defaultDensities) {
$configItem->setDensities($this->defaultDensities);
}
$config->setSize($configItem);
return [$config, $attributes];
}
/** @var ImageSizeModel $imageSizeModel */
$imageSizeModel = $this->framework->getAdapter(ImageSizeModel::class);
$imageSizes = $imageSizeModel->findByPk($size[2]);
$config->setSize($this->createConfigItem($imageSizes));
if ($imageSizes && $imageSizes->cssClass) {
$attributes['class'] = $imageSizes->cssClass;
}
/** @var ImageSizeItemModel $imageSizeItemModel */
$imageSizeItemModel = $this->framework->getAdapter(ImageSizeItemModel::class);
$imageSizeItems = $imageSizeItemModel->findVisibleByPid($size[2], ['order' => 'sorting ASC']);
if (null !== $imageSizeItems) {
$configItems = [];
foreach ($imageSizeItems as $imageSizeItem) {
$configItems[] = $this->createConfigItem($imageSizeItem);
}
$config->setSizeItems($configItems);
}
return [$config, $attributes];
} | php | {
"resource": ""
} |
q243281 | PictureFactory.createConfigItem | validation | private function createConfigItem($imageSize): PictureConfigurationItem
{
$configItem = new PictureConfigurationItem();
$resizeConfig = new ResizeConfiguration();
if (null !== $imageSize) {
$resizeConfig
->setWidth($imageSize->width)
->setHeight($imageSize->height)
->setMode($imageSize->resizeMode)
->setZoomLevel($imageSize->zoom)
;
$configItem
->setResizeConfig($resizeConfig)
->setSizes($imageSize->sizes)
->setDensities($imageSize->densities)
;
if (isset($imageSize->media)) {
$configItem->setMedia($imageSize->media);
}
}
return $configItem;
} | php | {
"resource": ""
} |
q243282 | SymlinkUtil.symlink | validation | public static function symlink(string $target, string $link, string $rootDir): void
{
static::validateSymlink($target, $link, $rootDir);
$fs = new Filesystem();
if (!$fs->isAbsolutePath($target)) {
$target = $rootDir.'/'.$target;
}
if (!$fs->isAbsolutePath($link)) {
$link = $rootDir.'/'.$link;
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$fs->symlink($target, $link);
} else {
$fs->symlink(rtrim($fs->makePathRelative($target, \dirname($link)), '/'), $link);
}
} | php | {
"resource": ""
} |
q243283 | SymlinkUtil.validateSymlink | validation | public static function validateSymlink(string $target, string $link, string $rootDir): void
{
if ('' === $target) {
throw new \InvalidArgumentException('The symlink target must not be empty.');
}
if ('' === $link) {
throw new \InvalidArgumentException('The symlink path must not be empty.');
}
if (false !== strpos($link, '../')) {
throw new \InvalidArgumentException('The symlink path must not be relative.');
}
$fs = new Filesystem();
if ($fs->exists($rootDir.'/'.$link) && !is_link($rootDir.'/'.$link)) {
throw new \LogicException(sprintf('The path "%s" exists and is not a symlink.', $link));
}
} | php | {
"resource": ""
} |
q243284 | NewsletterRecipientsModel.findByEmailAndPids | validation | public static function findByEmailAndPids($strEmail, $arrPids, array $arrOptions=array())
{
if (empty($arrPids) || !\is_array($arrPids))
{
return null;
}
$t = static::$strTable;
return static::findBy(array("$t.email=? AND $t.pid IN(" . implode(',', array_map('\intval', $arrPids)) . ")"), $strEmail, $arrOptions);
} | php | {
"resource": ""
} |
q243285 | ConnectionFactory.create | validation | public static function create(array $parameters): ?Connection
{
$params = [
'driver' => 'pdo_mysql',
'host' => $parameters['parameters']['database_host'],
'port' => $parameters['parameters']['database_port'],
'user' => $parameters['parameters']['database_user'],
'password' => $parameters['parameters']['database_password'],
'dbname' => $parameters['parameters']['database_name'],
];
try {
return DriverManager::getConnection($params);
} catch (DBALException $e) {
// ignore
}
return null;
} | php | {
"resource": ""
} |
q243286 | ContentCode.generate | validation | public function generate()
{
if (TL_MODE == 'BE')
{
$return = '<pre>'. htmlspecialchars($this->code) .'</pre>';
if ($this->headline != '')
{
$return = '<'. $this->hl .'>'. $this->headline .'</'. $this->hl .'>'. $return;
}
return $return;
}
return parent::generate();
} | php | {
"resource": ""
} |
q243287 | AbstractLockedCommand.getTempDir | validation | private function getTempDir(): string
{
$container = $this->getContainer();
$tmpDir = sys_get_temp_dir().'/'.md5($container->getParameter('kernel.project_dir'));
if (!is_dir($tmpDir)) {
$container->get('filesystem')->mkdir($tmpDir);
}
return $tmpDir;
} | php | {
"resource": ""
} |
q243288 | DoctrineSchemaListener.onSchemaIndexDefinition | validation | public function onSchemaIndexDefinition(SchemaIndexDefinitionEventArgs $event): void
{
// Skip for doctrine/dbal >= 2.9
if (method_exists(AbstractPlatform::class, 'supportsColumnLengthIndexes')) {
return;
}
$connection = $event->getConnection();
if (!$connection->getDatabasePlatform() instanceof MySqlPlatform) {
return;
}
$data = $event->getTableIndex();
// Ignore primary keys
if ('PRIMARY' === $data['name']) {
return;
}
$columns = [];
$query = sprintf("SHOW INDEX FROM %s WHERE Key_name='%s'", $event->getTable(), $data['name']);
$result = $connection->executeQuery($query);
while ($row = $result->fetch()) {
if (null !== $row['Sub_part']) {
$columns[] = sprintf('%s(%s)', $row['Column_name'], $row['Sub_part']);
} else {
$columns[] = $row['Column_name'];
}
}
$event->setIndex(
new Index(
$data['name'],
$columns,
$data['unique'],
$data['primary'],
$data['flags'],
$data['options']
)
);
$event->preventDefault();
} | php | {
"resource": ""
} |
q243289 | ContaoTableHandler.createStatement | validation | private function createStatement(): void
{
if (null !== $this->statement) {
return;
}
if (null === $this->container || !$this->container->has($this->dbalServiceName)) {
throw new \RuntimeException('The container has not been injected or the database service is missing');
}
/** @var Connection $connection */
$connection = $this->container->get($this->dbalServiceName);
$this->statement = $connection->prepare('
INSERT INTO
tl_log
(tstamp, source, action, username, text, func, browser)
VALUES
(:tstamp, :source, :action, :username, :text, :func, :browser)
');
} | php | {
"resource": ""
} |
q243290 | ContaoTableHandler.executeHook | validation | private function executeHook(string $message, ContaoContext $context): void
{
if (null === $this->container || !$this->container->has('contao.framework')) {
return;
}
$framework = $this->container->get('contao.framework');
if (!$this->hasAddLogEntryHook() || !$framework->isInitialized()) {
return;
}
@trigger_error('Using the addLogEntry hook has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
/** @var System $system */
$system = $framework->getAdapter(System::class);
// Must create variables to allow modification-by-reference in hook
$func = $context->getFunc();
$action = $context->getAction();
foreach ($GLOBALS['TL_HOOKS']['addLogEntry'] as $callback) {
$system->importStatic($callback[0])->{$callback[1]}($message, $func, $action);
}
} | php | {
"resource": ""
} |
q243291 | FrontendUser.findBy | validation | public function findBy($strColumn, $varValue)
{
if (parent::findBy($strColumn, $varValue) === false)
{
return false;
}
$this->arrGroups = $this->groups;
return true;
} | php | {
"resource": ""
} |
q243292 | FrontendUser.save | validation | public function save()
{
$groups = $this->groups;
$this->arrData['groups'] = $this->arrGroups;
parent::save();
$this->groups = $groups;
} | php | {
"resource": ""
} |
q243293 | Picture.create | validation | public static function create($file, $size=null)
{
if (\is_string($file))
{
$file = new File(rawurldecode($file));
}
$imageSize = null;
$picture = new static($file);
// tl_image_size ID as resize mode
if (\is_array($size) && !empty($size[2]) && is_numeric($size[2]))
{
$size = (int) $size[2];
}
$imageSize = null;
if (!\is_array($size))
{
$imageSize = ImageSizeModel::findByPk($size);
if ($imageSize === null)
{
$size = array();
}
}
if (\is_array($size))
{
$size += array(0, 0, 'crop');
$imageSize = new \stdClass();
$imageSize->width = $size[0];
$imageSize->height = $size[1];
$imageSize->resizeMode = $size[2];
$imageSize->zoom = 0;
}
$picture->setImageSize($imageSize);
if ($imageSize !== null && !empty($imageSize->id))
{
$picture->setImageSizeItems(ImageSizeItemModel::findVisibleByPid($imageSize->id, array('order'=>'sorting ASC')));
}
$fileRecord = FilesModel::findByPath($file->path);
if ($fileRecord !== null && $fileRecord->importantPartWidth && $fileRecord->importantPartHeight)
{
$picture->setImportantPart(array
(
'x' => (int) $fileRecord->importantPartX,
'y' => (int) $fileRecord->importantPartY,
'width' => (int) $fileRecord->importantPartWidth,
'height' => (int) $fileRecord->importantPartHeight,
));
}
return $picture;
} | php | {
"resource": ""
} |
q243294 | Picture.getTemplateData | validation | public function getTemplateData()
{
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
$image = System::getContainer()->get('contao.image.image_factory')->create($rootDir . '/' . $this->image->getOriginalPath());
$config = new PictureConfiguration();
$config->setSize($this->getConfigurationItem($this->imageSize));
$sizeItems = array();
foreach ($this->imageSizeItems as $imageSizeItem)
{
$sizeItems[] = $this->getConfigurationItem($imageSizeItem);
}
$config->setSizeItems($sizeItems);
$importantPart = $this->image->getImportantPart();
$image->setImportantPart(
new ImportantPart(
new Point($importantPart['x'], $importantPart['y']),
new Box($importantPart['width'], $importantPart['height'])
)
);
$container = System::getContainer();
$staticUrl = $container->get('contao.assets.files_context')->getStaticUrl();
$picture = $container
->get('contao.image.picture_generator')
->generate(
$image,
$config,
(new ResizeOptions())
->setImagineOptions($container->getParameter('contao.image.imagine_options'))
->setBypassCache($container->getParameter('contao.image.bypass_cache'))
)
;
return array
(
'img' => $picture->getImg($rootDir, $staticUrl),
'sources' => $picture->getSources($rootDir, $staticUrl),
);
} | php | {
"resource": ""
} |
q243295 | Picture.getConfigurationItem | validation | protected function getConfigurationItem($imageSize)
{
$configItem = new PictureConfigurationItem();
$resizeConfig = new ResizeConfiguration();
$mode = $imageSize->resizeMode;
if (substr_count($mode, '_') === 1)
{
$importantPart = $this->image->setImportantPart(null)->getImportantPart();
$mode = explode('_', $mode);
if ($mode[0] === 'left')
{
$importantPart['width'] = 1;
}
elseif ($mode[0] === 'right')
{
$importantPart['x'] = $importantPart['width'] - 1;
$importantPart['width'] = 1;
}
if ($mode[1] === 'top')
{
$importantPart['height'] = 1;
}
elseif ($mode[1] === 'bottom')
{
$importantPart['y'] = $importantPart['height'] - 1;
$importantPart['height'] = 1;
}
$this->image->setImportantPart($importantPart);
$mode = ResizeConfiguration::MODE_CROP;
}
$resizeConfig
->setWidth($imageSize->width)
->setHeight($imageSize->height)
->setZoomLevel($imageSize->zoom)
;
if ($mode)
{
$resizeConfig->setMode($mode);
}
$configItem->setResizeConfig($resizeConfig);
if (isset($imageSize->sizes))
{
$configItem->setSizes($imageSize->sizes);
}
if (isset($imageSize->densities))
{
$configItem->setDensities($imageSize->densities);
}
if (isset($imageSize->media))
{
$configItem->setMedia($imageSize->media);
}
return $configItem;
} | php | {
"resource": ""
} |
q243296 | SectionWizard.validator | validation | protected function validator($varInput)
{
$arrTitles = array();
$arrIds = array();
$arrSections = array();
foreach ($varInput as $arrSection)
{
// Title and ID are required
if ((!empty($arrSection['title']) && empty($arrSection['id'])) || (empty($arrSection['title']) && !empty($arrSection['id'])))
{
$this->addError($GLOBALS['TL_LANG']['ERR']['emptyTitleOrId']);
}
// Check for duplicate section titles
if (\in_array($arrSection['title'], $arrTitles))
{
$this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['duplicateSectionTitle'], $arrSection['title']));
}
$arrSection['id'] = StringUtil::standardize($arrSection['id'], true);
// Add a suffix to reserved names (see #301)
if (\in_array($arrSection['id'], array('top', 'wrapper', 'header', 'container', 'main', 'left', 'right', 'footer')))
{
$arrSection['id'] .= '-custom';
}
// Check for duplicate section IDs
if (\in_array($arrSection['id'], $arrIds))
{
$this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['duplicateSectionId'], $arrSection['id']));
}
$arrTitles[] = $arrSection['title'];
$arrIds[] = $arrSection['id'];
$arrSections[] = $arrSection;
}
return $arrSections;
} | php | {
"resource": ""
} |
q243297 | tl_page.setRootType | validation | public function setRootType(Contao\DataContainer $dc)
{
if (Contao\Input::get('act') != 'create')
{
return;
}
// Insert into
if (Contao\Input::get('pid') == 0)
{
$GLOBALS['TL_DCA']['tl_page']['fields']['type']['default'] = 'root';
}
elseif (Contao\Input::get('mode') == 1)
{
$objPage = $this->Database->prepare("SELECT * FROM " . $dc->table . " WHERE id=?")
->limit(1)
->execute(Contao\Input::get('pid'));
if ($objPage->pid == 0)
{
$GLOBALS['TL_DCA']['tl_page']['fields']['type']['default'] = 'root';
}
}
} | php | {
"resource": ""
} |
q243298 | tl_page.checkRootType | validation | public function checkRootType($varValue, Contao\DataContainer $dc)
{
if ($varValue != 'root' && $dc->activeRecord->pid == 0)
{
throw new Exception($GLOBALS['TL_LANG']['ERR']['topLevelRoot']);
}
return $varValue;
} | php | {
"resource": ""
} |
q243299 | tl_page.makeRedirectPageMandatory | validation | public function makeRedirectPageMandatory(Contao\DataContainer $dc)
{
$objPage = $this->Database->prepare("SELECT * FROM " . $dc->table . " WHERE id=?")
->limit(1)
->execute($dc->id);
if ($objPage->numRows && $objPage->type == 'logout')
{
$GLOBALS['TL_DCA']['tl_page']['fields']['jumpTo']['eval']['mandatory'] = true;
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.