_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q243600 | TokenChecker.isPreviewMode | validation | public function isPreviewMode(): bool
{
$token = $this->getToken(FrontendUser::SECURITY_SESSION_KEY);
return $token instanceof FrontendPreviewToken && $token->showUnpublished();
} | php | {
"resource": ""
} |
q243601 | MemberGroupModel.findPublishedById | validation | public static function findPublishedById($intId, array $arrOptions=array())
{
$t = static::$strTable;
$arrColumns = 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.disable=''";
}
return static::findOneBy($arrColumns, $intId, $arrOptions);
} | php | {
"resource": ""
} |
q243602 | MemberGroupModel.findAllActive | validation | public static function findAllActive(array $arrOptions=array())
{
$t = static::$strTable;
$time = Date::floorToMinute();
return static::findBy(array("$t.disable='' AND ($t.start='' OR $t.start<='$time') AND ($t.stop='' OR $t.stop>'" . ($time + 60) . "')"), null, $arrOptions);
} | php | {
"resource": ""
} |
q243603 | MemberGroupModel.findFirstActiveWithJumpToByIds | validation | public static function findFirstActiveWithJumpToByIds($arrIds)
{
@trigger_error('Using MemberGroupModel::findFirstActiveWithJumpToByIds() has been deprecated and will no longer work in Contao 5.0. Use PageModel::findFirstActiveByMemberGroups() instead.', E_USER_DEPRECATED);
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;
}
return new static($objResult);
} | php | {
"resource": ""
} |
q243604 | StringUtil.decodeEntities | validation | public static function decodeEntities($strString, $strQuoteStyle=ENT_COMPAT, $strCharset=null)
{
if ($strString == '')
{
return '';
}
if ($strCharset === null)
{
$strCharset = Config::get('characterSet');
}
$strString = preg_replace('/(&#*\w+)[\x00-\x20]+;/i', '$1;', $strString);
$strString = preg_replace('/(&#x*)([0-9a-f]+);/i', '$1$2;', $strString);
return html_entity_decode($strString, $strQuoteStyle, $strCharset);
} | php | {
"resource": ""
} |
q243605 | StringUtil.generateAlias | validation | public static function generateAlias($strString)
{
$strString = static::decodeEntities($strString);
$strString = static::restoreBasicEntities($strString);
$strString = static::standardize(strip_tags($strString));
// Remove the prefix if the alias is not numeric (see #707)
if (strncmp($strString, 'id-', 3) === 0 && !is_numeric($strSubstr = substr($strString, 3)))
{
$strString = $strSubstr;
}
return $strString;
} | php | {
"resource": ""
} |
q243606 | StringUtil.prepareSlug | validation | public static function prepareSlug($strSlug)
{
$strSlug = static::stripInsertTags($strSlug);
$strSlug = static::restoreBasicEntities($strSlug);
$strSlug = static::decodeEntities($strSlug);
return $strSlug;
} | php | {
"resource": ""
} |
q243607 | StringUtil.censor | validation | public static function censor($strString, $varWords, $strReplace='')
{
foreach ((array) $varWords as $strWord)
{
$strString = preg_replace('/\b(' . str_replace('\*', '\w*?', preg_quote($strWord, '/')) . ')\b/i', $strReplace, $strString);
}
return $strString;
} | php | {
"resource": ""
} |
q243608 | StringUtil.encodeEmail | validation | public static function encodeEmail($strString)
{
if (strpos($strString, '@') === false)
{
return $strString;
}
$arrEmails = static::extractEmail($strString, Config::get('allowedTags'));
foreach ($arrEmails as $strEmail)
{
$strEncoded = '';
$arrCharacters = Utf8::str_split($strEmail);
foreach ($arrCharacters as $strCharacter)
{
$strEncoded .= sprintf((random_int(0, 1) ? '&#x%X;' : '&#%s;'), Utf8::ord($strCharacter));
}
$strString = str_replace($strEmail, $strEncoded, $strString);
}
return str_replace('mailto:', 'mailto:', $strString);
} | php | {
"resource": ""
} |
q243609 | StringUtil.extractEmail | validation | public static function extractEmail($strString, $strAllowedTags='')
{
$arrEmails = array();
if (strpos($strString, '@') === false)
{
return $arrEmails;
}
// Find all mailto: addresses
preg_match_all('/mailto:(?:[^\x00-\x20\x22\x40\x7F]{1,64}+|\x22[^\x00-\x1F\x7F]{1,64}?\x22)@(?:\[(?:IPv)?[a-f0-9.:]{1,47}\]|[\w.-]{1,252}\.[a-z]{2,63}\b)/u', $strString, $matches);
foreach ($matches[0] as &$strEmail)
{
$strEmail = str_replace('mailto:', '', $strEmail);
if (Validator::isEmail($strEmail))
{
$arrEmails[] = $strEmail;
}
}
unset($strEmail);
// Encode opening arrow brackets (see #3998)
$strString = preg_replace_callback('@</?([^\s<>/]*)@', function ($matches) use ($strAllowedTags)
{
if ($matches[1] == '' || stripos($strAllowedTags, '<' . strtolower($matches[1]) . '>') === false)
{
$matches[0] = str_replace('<', '<', $matches[0]);
}
return $matches[0];
}, $strString);
// Find all addresses in the plain text
preg_match_all('/(?:[^\x00-\x20\x22\x40\x7F]{1,64}|\x22[^\x00-\x1F\x7F]{1,64}?\x22)@(?:\[(?:IPv)?[a-f0-9.:]{1,47}\]|[\w.-]{1,252}\.[a-z]{2,63}\b)/u', strip_tags($strString), $matches);
foreach ($matches[0] as &$strEmail)
{
$strEmail = str_replace('<', '<', $strEmail);
if (Validator::isEmail($strEmail))
{
$arrEmails[] = $strEmail;
}
}
return array_unique($arrEmails);
} | php | {
"resource": ""
} |
q243610 | StringUtil.splitFriendlyEmail | validation | public static function splitFriendlyEmail($strEmail)
{
if (strpos($strEmail, '<') !== false)
{
return array_map('trim', explode(' <', str_replace('>', '', $strEmail)));
}
elseif (strpos($strEmail, '[') !== false)
{
return array_map('trim', explode(' [', str_replace(']', '', $strEmail)));
}
else
{
return array('', $strEmail);
}
} | php | {
"resource": ""
} |
q243611 | StringUtil.highlight | validation | public static function highlight($strString, $strPhrase, $strOpeningTag='<strong>', $strClosingTag='</strong>')
{
if ($strString == '' || $strPhrase == '')
{
return $strString;
}
return preg_replace('/(' . preg_quote($strPhrase, '/') . ')/i', $strOpeningTag . '\\1' . $strClosingTag, $strString);
} | php | {
"resource": ""
} |
q243612 | StringUtil.splitCsv | validation | public static function splitCsv($strString, $strDelimiter=',')
{
$arrValues = preg_split('/'.$strDelimiter.'(?=(?:[^"]*"[^"]*")*(?![^"]*"))/', $strString);
foreach ($arrValues as $k=>$v)
{
$arrValues[$k] = trim($v, ' "');
}
return $arrValues;
} | php | {
"resource": ""
} |
q243613 | StringUtil.toXhtml | validation | public static function toXhtml($strString)
{
$arrPregReplace = array
(
'/<(br|hr|img)([^>]*)>/i' => '<$1$2 />', // Close stand-alone tags
'/ border="[^"]*"/' => '' // Remove deprecated attributes
);
$arrStrReplace = array
(
'/ />' => ' />', // Fix incorrectly closed tags
'<b>' => '<strong>', // Replace <b> with <strong>
'</b>' => '</strong>',
'<i>' => '<em>', // Replace <i> with <em>
'</i>' => '</em>',
'<u>' => '<span style="text-decoration:underline">',
'</u>' => '</span>',
' target="_self"' => '',
' target="_blank"' => ' onclick="return !window.open(this.href)"'
);
$strString = preg_replace(array_keys($arrPregReplace), $arrPregReplace, $strString);
$strString = str_ireplace(array_keys($arrStrReplace), $arrStrReplace, $strString);
return $strString;
} | php | {
"resource": ""
} |
q243614 | StringUtil.toHtml5 | validation | public static function toHtml5($strString)
{
$arrPregReplace = array
(
'/<(br|hr|img)([^>]*) \/>/i' => '<$1$2>', // Close stand-alone tags
'/ (cellpadding|cellspacing|border)="[^"]*"/' => '', // Remove deprecated attributes
'/ rel="lightbox(\[([^\]]+)\])?"/' => ' data-lightbox="$2"' // see #4073
);
$arrStrReplace = array
(
'<u>' => '<span style="text-decoration:underline">',
'</u>' => '</span>',
' target="_self"' => '',
' onclick="window.open(this.href); return false"' => ' target="_blank"',
' onclick="window.open(this.href);return false"' => ' target="_blank"',
' onclick="window.open(this.href); return false;"' => ' target="_blank"'
);
$strString = preg_replace(array_keys($arrPregReplace), $arrPregReplace, $strString);
$strString = str_ireplace(array_keys($arrStrReplace), $arrStrReplace, $strString);
return $strString;
} | php | {
"resource": ""
} |
q243615 | StringUtil.srcToInsertTag | validation | public static function srcToInsertTag($data)
{
$return = '';
$paths = preg_split('/((src|href)="([^"]+)")/i', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i=0, $c=\count($paths); $i<$c; $i+=4)
{
$return .= $paths[$i];
if (!isset($paths[$i+1]))
{
continue;
}
$file = FilesModel::findByPath($paths[$i+3]);
if ($file !== null)
{
$return .= $paths[$i+2] . '="{{file::' . static::binToUuid($file->uuid) . '}}"';
}
else
{
$return .= $paths[$i+2] . '="' . $paths[$i+3] . '"';
}
}
return $return;
} | php | {
"resource": ""
} |
q243616 | StringUtil.insertTagToSrc | validation | public static function insertTagToSrc($data)
{
$return = '';
$paths = preg_split('/((src|href)="([^"]*)\{\{file::([^"\}]+)\}\}")/i', $data, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i=0, $c=\count($paths); $i<$c; $i+=5)
{
$return .= $paths[$i];
if (!isset($paths[$i+1]))
{
continue;
}
$file = FilesModel::findByUuid($paths[$i+4]);
if ($file !== null)
{
$return .= $paths[$i+2] . '="' . $paths[$i+3] . $file->path . '"';
}
else
{
$return .= $paths[$i+2] . '="' . $paths[$i+3] . $paths[$i+4] . '"';
}
}
return $return;
} | php | {
"resource": ""
} |
q243617 | StringUtil.sanitizeFileName | validation | public static function sanitizeFileName($strName)
{
// Remove invisible control characters and unused code points
$strName = preg_replace('/[\pC]/u', '', $strName);
if ($strName === null)
{
throw new \InvalidArgumentException('The file name could not be sanitzied');
}
// Remove special characters not supported on e.g. Windows
$strName = str_replace(array('\\', '/', ':', '*', '?', '"', '<', '>', '|'), '-', $strName);
return $strName;
} | php | {
"resource": ""
} |
q243618 | StringUtil.convertEncoding | validation | public static function convertEncoding($str, $to, $from=null)
{
if ($str == '')
{
return '';
}
if (!$from)
{
$from = mb_detect_encoding($str, 'ASCII,ISO-2022-JP,UTF-8,EUC-JP,ISO-8859-1');
}
if ($from == $to)
{
return $str;
}
if ($from == 'UTF-8' && $to == 'ISO-8859-1')
{
return utf8_decode($str);
}
if ($from == 'ISO-8859-1' && $to == 'UTF-8')
{
return utf8_encode($str);
}
return mb_convert_encoding($str, $to, $from);
} | php | {
"resource": ""
} |
q243619 | StringUtil.specialchars | validation | public static function specialchars($strString, $blnStripInsertTags=false, $blnDoubleEncode=false)
{
if ($blnStripInsertTags)
{
$strString = static::stripInsertTags($strString);
}
// Use ENT_COMPAT here (see #4889)
return htmlspecialchars($strString, ENT_COMPAT, Config::get('characterSet'), $blnDoubleEncode);
} | php | {
"resource": ""
} |
q243620 | StringUtil.deserialize | validation | public static function deserialize($varValue, $blnForceArray=false)
{
// Already an array
if (\is_array($varValue))
{
return $varValue;
}
// Null
if ($varValue === null)
{
return $blnForceArray ? array() : null;
}
// Not a string
if (!\is_string($varValue))
{
return $blnForceArray ? array($varValue) : $varValue;
}
// Empty string
if (trim($varValue) == '')
{
return $blnForceArray ? array() : '';
}
// Not a serialized array (see #1486)
if (strncmp($varValue, 'a:', 2) !== 0)
{
return $blnForceArray ? array($varValue) : $varValue;
}
// Potentially including an object (see #6724)
if (preg_match('/[OoC]:\+?[0-9]+:"/', $varValue))
{
trigger_error('StringUtil::deserialize() does not allow serialized objects', E_USER_WARNING);
return $blnForceArray ? array($varValue) : $varValue;
}
$varUnserialized = @unserialize($varValue, array('allowed_classes' => false));
if (\is_array($varUnserialized))
{
$varValue = $varUnserialized;
}
elseif ($blnForceArray)
{
$varValue = array($varValue);
}
return $varValue;
} | php | {
"resource": ""
} |
q243621 | StringUtil.trimsplit | validation | public static function trimsplit($strPattern, $strString)
{
// Split
if (\strlen($strPattern) == 1)
{
$arrFragments = array_map('trim', explode($strPattern, $strString));
}
else
{
$arrFragments = array_map('trim', preg_split('/'.$strPattern.'/ui', $strString));
}
// Empty array
if (\count($arrFragments) < 2 && !\strlen($arrFragments[0]))
{
$arrFragments = array();
}
return $arrFragments;
} | php | {
"resource": ""
} |
q243622 | StringUtil.stripRootDir | validation | public static function stripRootDir($path)
{
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
$length = \strlen($rootDir);
if (strncmp($path, $rootDir, $length) !== 0 || \strlen($path) <= $length || ($path[$length] !== '/' && $path[$length] !== '\\'))
{
throw new \InvalidArgumentException(sprintf('Path "%s" is not inside the Contao root dir "%s"', $path, $rootDir));
}
return (string) substr($path, $length + 1);
} | php | {
"resource": ""
} |
q243623 | FaqModel.findPublishedByParentAndIdOrAlias | validation | public static function findPublishedByParentAndIdOrAlias($varId, $arrPids, array $arrOptions=array())
{
if (empty($arrPids) || !\is_array($arrPids))
{
return null;
}
$t = static::$strTable;
$arrColumns = !preg_match('/^[1-9]\d*$/', $varId) ? array("$t.alias=?") : array("$t.id=?");
$arrColumns[] = "$t.pid IN(" . implode(',', array_map('\intval', $arrPids)) . ")";
if (!static::isPreviewMode($arrOptions))
{
$arrColumns[] = "$t.published='1'";
}
return static::findOneBy($arrColumns, $varId, $arrOptions);
} | php | {
"resource": ""
} |
q243624 | RefererIdListener.onKernelRequest | validation | public function onKernelRequest(GetResponseEvent $event): void
{
if (!$this->scopeMatcher->isBackendMasterRequest($event)) {
return;
}
$request = $event->getRequest();
if (null === $this->token) {
$this->token = $this->tokenManager->refreshToken('contao_referer_id');
}
$request->attributes->set('_contao_referer_id', $this->token->getValue());
} | php | {
"resource": ""
} |
q243625 | ResponseExceptionListener.onKernelException | validation | public function onKernelException(GetResponseForExceptionEvent $event): void
{
$exception = $event->getException();
if (!$exception instanceof ResponseException) {
return;
}
$event->allowCustomResponseCode();
$event->setResponse($exception->getResponse());
} | php | {
"resource": ""
} |
q243626 | PaletteManipulator.addLegend | validation | public function addLegend(string $name, $parent, string $position = self::POSITION_AFTER, $hide = false): self
{
$this->validatePosition($position);
$this->legends[] = [
'name' => $name,
'parents' => (array) $parent,
'position' => $position,
'hide' => (bool) $hide,
];
return $this;
} | php | {
"resource": ""
} |
q243627 | PaletteManipulator.removeField | validation | public function removeField($name, string $legend = null): self
{
$this->removes[] = [
'fields' => (array) $name,
'parents' => (array) $legend,
];
return $this;
} | php | {
"resource": ""
} |
q243628 | PaletteManipulator.explode | validation | private function explode(string $palette): array
{
if ('' === $palette) {
return [];
}
$legendCount = 0;
$legendMap = [];
$groups = StringUtil::trimsplit(';', $palette);
foreach ($groups as $group) {
if ('' === $group) {
continue;
}
$hide = false;
$fields = StringUtil::trimsplit(',', $group);
if (preg_match('#\{(.+?)(:hide)?\}#', $fields[0], $matches)) {
$legend = $matches[1];
$hide = \count($matches) > 2 && ':hide' === $matches[2];
array_shift($fields);
} else {
$legend = $legendCount++;
}
$legendMap[$legend] = compact('fields', 'hide');
}
return $legendMap;
} | php | {
"resource": ""
} |
q243629 | PaletteManipulator.implode | validation | private function implode(array $config): string
{
$palette = '';
foreach ($config as $legend => $group) {
if (\count($group['fields']) < 1) {
continue;
}
if ('' !== $palette) {
$palette .= ';';
}
if (!\is_int($legend)) {
$palette .= sprintf('{%s%s},', $legend, ($group['hide'] ? ':hide' : ''));
}
$palette .= implode(',', $group['fields']);
}
return $palette;
} | php | {
"resource": ""
} |
q243630 | PaletteManipulator.applyFallback | validation | private function applyFallback(array &$config, array $action, bool $skipLegends = false): void
{
if (\is_callable($action['fallback'])) {
$action['fallback']($config, $action, $skipLegends);
} else {
$this->applyFallbackPalette($config, $action);
}
} | php | {
"resource": ""
} |
q243631 | PaletteManipulator.findLegendForField | validation | private function findLegendForField(array &$config, string $field)
{
foreach ($config as $legend => $group) {
if (\in_array($field, $group['fields'], true)) {
return $legend;
}
}
return false;
} | php | {
"resource": ""
} |
q243632 | tl_calendar_feed.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->calendarfeeds) || !\is_array($this->User->calendarfeeds))
{
$root = array(0);
}
else
{
$root = $this->User->calendarfeeds;
}
// The calendar feed 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_calendar_feed']) && \in_array($insertId, $arrNew['tl_calendar_feed']))
{
// Add the permissions on group level
if ($this->User->inherit != 'custom')
{
$objGroup = $this->Database->execute("SELECT id, calendarfeeds, calendarfeedp FROM tl_user_group WHERE id IN(" . implode(',', array_map('\intval', $this->User->groups)) . ")");
while ($objGroup->next())
{
$arrCalendarfeedp = Contao\StringUtil::deserialize($objGroup->calendarfeedp);
if (\is_array($arrCalendarfeedp) && \in_array('create', $arrCalendarfeedp))
{
$arrCalendarfeeds = Contao\StringUtil::deserialize($objGroup->calendarfeeds, true);
$arrCalendarfeeds[] = $insertId;
$this->Database->prepare("UPDATE tl_user_group SET calendarfeeds=? WHERE id=?")
->execute(serialize($arrCalendarfeeds), $objGroup->id);
}
}
}
// Add the permissions on user level
if ($this->User->inherit != 'group')
{
$objUser = $this->Database->prepare("SELECT calendarfeeds, calendarfeedp FROM tl_user WHERE id=?")
->limit(1)
->execute($this->User->id);
$arrCalendarfeedp = Contao\StringUtil::deserialize($objUser->calendarfeedp);
if (\is_array($arrCalendarfeedp) && \in_array('create', $arrCalendarfeedp))
{
$arrCalendarfeeds = Contao\StringUtil::deserialize($objUser->calendarfeeds, true);
$arrCalendarfeeds[] = $insertId;
$this->Database->prepare("UPDATE tl_user SET calendarfeeds=? WHERE id=?")
->execute(serialize($arrCalendarfeeds), $this->User->id);
}
}
// Add the new element to the user object
$root[] = $insertId;
$this->User->calendarfeeds = $root;
}
} | php | {
"resource": ""
} |
q243633 | tl_calendar_feed.getAllowedCalendars | validation | public function getAllowedCalendars()
{
if ($this->User->isAdmin)
{
$objCalendar = Contao\CalendarModel::findAll();
}
else
{
$objCalendar = Contao\CalendarModel::findMultipleByIds($this->User->calendars);
}
$return = array();
if ($objCalendar !== null)
{
while ($objCalendar->next())
{
$return[$objCalendar->id] = $objCalendar->title;
}
}
return $return;
} | php | {
"resource": ""
} |
q243634 | ZipWriter.addFile | validation | public function addFile($strFile, $strName=null)
{
if (!file_exists($this->strRootDir . '/' . $strFile))
{
throw new \Exception("File $strFile does not exist");
}
// Remove leading slashes (see #4502)
if (strncmp($strName, '/', 1) === 0)
{
$strName = substr($strName, 1);
}
$this->addString(file_get_contents($this->strRootDir . '/' . $strFile), $strName ?: $strFile, filemtime($this->strRootDir . '/' . $strFile));
} | php | {
"resource": ""
} |
q243635 | ZipWriter.addString | validation | public function addString($strData, $strName, $intTime=0)
{
++$this->intCount;
$strName = strtr($strName, '\\', '/');
// Start file
$arrFile['file_signature'] = self::FILE_SIGNATURE;
$arrFile['version_needed_to_extract'] = "\x14\x00";
$arrFile['general_purpose_bit_flag'] = "\x00\x00";
$arrFile['compression_method'] = "\x08\x00";
$arrFile['last_mod_file_hex'] = $this->unixToHex($intTime);
$arrFile['crc-32'] = pack('V', crc32($strData));
$intUncompressed = \strlen($strData);
// Compress data
$strData = gzcompress($strData);
$strData = substr(substr($strData, 0, -4), 2);
$intCompressed = \strlen($strData);
// Continue file
$arrFile['compressed_size'] = pack('V', $intCompressed);
$arrFile['uncompressed_size'] = pack('V', $intUncompressed);
$arrFile['file_name_length'] = pack('v', \strlen($strName));
$arrFile['extra_field_length'] = "\x00\x00";
$arrFile['file_name'] = $strName;
$arrFile['extra_field'] = '';
// Store file offset
$intOffset = @ftell($this->resFile);
// Add file to archive
fwrite($this->resFile, implode('', $arrFile));
fwrite($this->resFile, $strData);
// Start central directory
$arrHeader['header_signature'] = self::CENTRAL_DIR_START;
$arrHeader['version_made_by'] = "\x00\x00";
$arrHeader['version_needed_to_extract'] = $arrFile['version_needed_to_extract'];
$arrHeader['general_purpose_bit_flag'] = $arrFile['general_purpose_bit_flag'];
$arrHeader['compression_method'] = $arrFile['compression_method'];
$arrHeader['last_mod_file_hex'] = $arrFile['last_mod_file_hex'];
$arrHeader['crc-32'] = $arrFile['crc-32'];
$arrHeader['compressed_size'] = $arrFile['compressed_size'];
$arrHeader['uncompressed_size'] = $arrFile['uncompressed_size'];
$arrHeader['file_name_length'] = $arrFile['file_name_length'];
$arrHeader['extra_field_length'] = $arrFile['extra_field_length'];
$arrHeader['file_comment_length'] = "\x00\x00";
$arrHeader['disk_number_start'] = "\x00\x00";
$arrHeader['internal_file_attributes'] = "\x00\x00";
$arrHeader['external_file_attributes'] = pack('V', 32);
$arrHeader['offset_of_local_header'] = pack('V', $intOffset);
$arrHeader['file_name'] = $arrFile['file_name'];
$arrHeader['extra_field'] = $arrFile['extra_field'];
$arrHeader['file_comment'] = '';
// Add entry to central directory
$this->strCentralDir .= implode('', $arrHeader);
} | php | {
"resource": ""
} |
q243636 | ZipWriter.close | validation | public function close()
{
// Add archive header
$arrArchive['archive_signature'] = self::CENTRAL_DIR_END;
$arrArchive['number_of_this_disk'] = "\x00\x00";
$arrArchive['number_of_disk_with_cd'] = "\x00\x00";
$arrArchive['total_cd_entries_disk'] = pack('v', $this->intCount);
$arrArchive['total_cd_entries'] = pack('v', $this->intCount);
$arrArchive['size_of_cd'] = pack('V', \strlen($this->strCentralDir));
$arrArchive['offset_start_cd'] = pack('V', @ftell($this->resFile));
$arrArchive['zipfile_comment_length'] = "\x00\x00";
$arrArchive['zipfile_comment'] = '';
// Add central directory and archive header (do not change this order)
fwrite($this->resFile, $this->strCentralDir);
fwrite($this->resFile, implode('', $arrArchive));
// Close the file before renaming it
fclose($this->resFile);
// Check if target file exists
if (!file_exists($this->strRootDir . '/' . $this->strFile))
{
// Handle open_basedir restrictions
if (($strFolder = \dirname($this->strFile)) == '.')
{
$strFolder = '';
}
// Create folder
if (!is_dir($this->strRootDir . '/' . $strFolder))
{
new Folder($strFolder);
}
}
// Rename file
Files::getInstance()->rename(self::TEMPORARY_FOLDER . '/' . basename($this->strTemp), $this->strFile);
} | php | {
"resource": ""
} |
q243637 | ZipWriter.unixToHex | validation | protected function unixToHex($intTime=0)
{
$arrTime = $intTime ? getdate($intTime) : getdate();
$hexTime = dechex
(
(($arrTime['year'] - 1980) << 25) |
($arrTime['mon'] << 21) |
($arrTime['mday'] << 16) |
($arrTime['hours'] << 11) |
($arrTime['minutes'] << 5) |
($arrTime['seconds'] >> 1)
);
return pack("H*", $hexTime[6] . $hexTime[7] . $hexTime[4] . $hexTime[5] . $hexTime[2] . $hexTime[3] . $hexTime[0] . $hexTime[1]);
} | php | {
"resource": ""
} |
q243638 | Comments.parseBbCode | validation | public function parseBbCode($strComment)
{
$arrSearch = array
(
'@\[b\](.*)\[/b\]@Uis',
'@\[i\](.*)\[/i\]@Uis',
'@\[u\](.*)\[/u\]@Uis',
'@\s*\[code\](.*)\[/code\]\s*@Uis',
'@\[color=([^\]" ]+)\](.*)\[/color\]@Uis',
'@\s*\[quote\](.*)\[/quote\]\s*@Uis',
'@\s*\[quote=([^\]]+)\](.*)\[/quote\]\s*@Uis',
'@\[img\]\s*([^\[" ]+\.(jpe?g|png|gif|bmp|tiff?|ico))\s*\[/img\]@i',
'@\[url\]\s*([^\[" ]+)\s*\[/url\]@i',
'@\[url=([^\]" ]+)\](.*)\[/url\]@Uis',
'@\[email\]\s*([^\[" ]+)\s*\[/email\]@i',
'@\[email=([^\]" ]+)\](.*)\[/email\]@Uis',
'@href="(([a-z0-9]+\.)*[a-z0-9]+\.([a-z]{2}|asia|biz|com|info|name|net|org|tel)(/|"))@i'
);
$arrReplace = array
(
'<strong>$1</strong>',
'<em>$1</em>',
'<span style="text-decoration:underline">$1</span>',
"\n\n" . '<div class="code"><p>'. $GLOBALS['TL_LANG']['MSC']['com_code'] .'</p><pre>$1</pre></div>' . "\n\n",
'<span style="color:$1">$2</span>',
"\n\n" . '<blockquote>$1</blockquote>' . "\n\n",
"\n\n" . '<blockquote><p>'. sprintf($GLOBALS['TL_LANG']['MSC']['com_quote'], '$1') .'</p>$2</blockquote>' . "\n\n",
'<img src="$1" alt="" />',
'<a href="$1">$1</a>',
'<a href="$1">$2</a>',
'<a href="mailto:$1">$1</a>',
'<a href="mailto:$1">$2</a>',
'href="http://$1'
);
$strComment = preg_replace($arrSearch, $arrReplace, $strComment);
// Encode e-mail addresses
if (strpos($strComment, 'mailto:') !== false)
{
$strComment = StringUtil::encodeEmail($strComment);
}
return $strComment;
} | php | {
"resource": ""
} |
q243639 | Comments.changeSubscriptionStatus | validation | public static function changeSubscriptionStatus(FrontendTemplate $objTemplate)
{
if (strncmp(Input::get('token'), 'com-', 4) === 0)
{
/** @var OptIn $optIn */
$optIn = System::getContainer()->get('contao.opt-in');
// Find an unconfirmed token with only one related record
if ((!$optInToken = $optIn->find(Input::get('token'))) || !$optInToken->isValid() || \count($arrRelated = $optInToken->getRelatedRecords()) != 1 || key($arrRelated) != 'tl_comments_notify' || \count($arrIds = current($arrRelated)) != 1 || (!$objNotify = CommentsNotifyModel::findByPk($arrIds[0])))
{
$objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['invalidToken'];
return;
}
if ($optInToken->isConfirmed())
{
$objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['tokenConfirmed'];
return;
}
if ($optInToken->getEmail() != $objNotify->email)
{
$objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['tokenEmailMismatch'];
return;
}
$objNotify->active = '1';
$objNotify->save();
$optInToken->confirm();
$objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['com_optInConfirm'];
}
elseif (strncmp(Input::get('token'), 'cor-', 4) === 0)
{
$objNotify = CommentsNotifyModel::findOneByTokenRemove(Input::get('token'));
if ($objNotify === null)
{
$objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['invalidToken'];
return;
}
$objNotify->delete();
$objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['com_optInCancel'];
}
} | php | {
"resource": ""
} |
q243640 | Comments.notifyCommentsSubscribers | validation | public static function notifyCommentsSubscribers(CommentsModel $objComment)
{
// Notified already
if ($objComment->notified)
{
return;
}
$objNotify = CommentsNotifyModel::findActiveBySourceAndParent($objComment->source, $objComment->parent);
if ($objNotify !== null)
{
while ($objNotify->next())
{
// Don't notify the commentor about his own comment
if ($objNotify->email == $objComment->email)
{
continue;
}
// Prepare the URL
$strUrl = Idna::decode(Environment::get('base')) . $objNotify->url;
$objEmail = new Email();
$objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
$objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
$objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['com_notifySubject'], Idna::decode(Environment::get('host')));
$objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['com_notifyMessage'], $objNotify->name, $strUrl . '#c' . $objComment->id, $strUrl . '?token=' . $objNotify->tokenRemove);
$objEmail->sendTo($objNotify->email);
}
}
$objComment->notified = '1';
$objComment->save();
} | php | {
"resource": ""
} |
q243641 | Template.output | validation | public function output()
{
@trigger_error('Using Template::output() has been deprecated and will no longer work in Contao 5.0. Use Template::getResponse() instead.', E_USER_DEPRECATED);
$this->compile();
header('Content-Type: ' . $this->strContentType . '; charset=' . Config::get('characterSet'));
echo $this->strBuffer;
// Flush the output buffers (see #6962)
$this->flushAllData();
} | php | {
"resource": ""
} |
q243642 | Template.route | validation | public function route($strName, $arrParams=array())
{
$strUrl = System::getContainer()->get('router')->generate($strName, $arrParams);
$strUrl = substr($strUrl, \strlen(Environment::get('path')) + 1);
return ampersand($strUrl);
} | php | {
"resource": ""
} |
q243643 | Template.previewRoute | validation | public function previewRoute($strName, $arrParams=array())
{
$objRouter = System::getContainer()->get('router');
$objContext = $objRouter->getContext();
$objPreviewContext = clone $objContext;
$objPreviewContext->setBaseUrl('/preview.php');
$objRouter->setContext($objPreviewContext);
$strUrl = $objRouter->generate($strName, $arrParams);
$strUrl = substr($strUrl, \strlen(Environment::get('path')) + 1);
$objRouter->setContext($objContext);
return ampersand($strUrl);
} | php | {
"resource": ""
} |
q243644 | Template.trans | validation | public function trans($strId, array $arrParams=array(), $strDomain='contao_default')
{
return System::getContainer()->get('translator')->trans($strId, $arrParams, $strDomain);
} | php | {
"resource": ""
} |
q243645 | Template.asset | validation | public function asset($path, $packageName = null)
{
$url = System::getContainer()->get('assets.packages')->getUrl($path, $packageName);
// Contao paths are relative to the <base> tag, so remove leading slashes
return ltrim($url, '/');
} | php | {
"resource": ""
} |
q243646 | Template.minifyHtml | validation | public function minifyHtml($strHtml)
{
if (Config::get('debugMode'))
{
return $strHtml;
}
// Split the markup based on the tags that shall be preserved
$arrChunks = preg_split('@(</?pre[^>]*>)|(</?script[^>]*>)|(</?style[^>]*>)|( ?</?textarea[^>]*>)@i', $strHtml, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
$strHtml = '';
$blnPreserveNext = false;
$blnOptimizeNext = false;
$strType = null;
// Check for valid JavaScript types (see #7927)
$isJavaScript = function ($strChunk)
{
$typeMatch = array();
if (preg_match('/\stype\s*=\s*(?:(?J)(["\'])\s*(?<type>.*?)\s*\1|(?<type>[^\s>]+))/i', $strChunk, $typeMatch) && !\in_array(strtolower($typeMatch['type']), static::$validJavaScriptTypes))
{
return false;
}
if (preg_match('/\slanguage\s*=\s*(?:(?J)(["\'])\s*(?<type>.*?)\s*\1|(?<type>[^\s>]+))/i', $strChunk, $typeMatch) && !\in_array('text/' . strtolower($typeMatch['type']), static::$validJavaScriptTypes))
{
return false;
}
return true;
};
// Recombine the markup
foreach ($arrChunks as $strChunk)
{
if (strncasecmp($strChunk, '<pre', 4) === 0 || strncasecmp(ltrim($strChunk), '<textarea', 9) === 0)
{
$blnPreserveNext = true;
}
elseif (strncasecmp($strChunk, '<script', 7) === 0)
{
if ($isJavaScript($strChunk))
{
$blnOptimizeNext = true;
$strType = 'js';
}
else
{
$blnPreserveNext = true;
}
}
elseif (strncasecmp($strChunk, '<style', 6) === 0)
{
$blnOptimizeNext = true;
$strType = 'css';
}
elseif ($blnPreserveNext)
{
$blnPreserveNext = false;
}
elseif ($blnOptimizeNext)
{
$blnOptimizeNext = false;
// Minify inline scripts
if ($strType == 'js')
{
$objMinify = new Minify\JS();
$objMinify->add($strChunk);
$strChunk = $objMinify->minify();
}
elseif ($strType == 'css')
{
$objMinify = new Minify\CSS();
$objMinify->add($strChunk);
$strChunk = $objMinify->minify();
}
}
else
{
// Remove line indentations and trailing spaces
$strChunk = str_replace("\r", '', $strChunk);
$strChunk = preg_replace(array('/^[\t ]+/m', '/[\t ]+$/m', '/\n\n+/'), array('', '', "\n"), $strChunk);
}
$strHtml .= $strChunk;
}
return trim($strHtml);
} | php | {
"resource": ""
} |
q243647 | Template.generateStyleTag | validation | public static function generateStyleTag($href, $media=null, $mtime=false)
{
// Add the filemtime if not given and not an external file
if ($mtime === null && !preg_match('@^https?://@', $href))
{
$container = System::getContainer();
$rootDir = $container->getParameter('kernel.project_dir');
if (file_exists($rootDir . '/' . $href))
{
$mtime = filemtime($rootDir . '/' . $href);
}
else
{
$webDir = StringUtil::stripRootDir($container->getParameter('contao.web_dir'));
// Handle public bundle resources in web/
if (file_exists($rootDir . '/' . $webDir . '/' . $href))
{
$mtime = filemtime($rootDir . '/' . $webDir . '/' . $href);
}
}
}
if ($mtime)
{
$href .= '?v=' . substr(md5($mtime), 0, 8);
}
return '<link rel="stylesheet" href="' . $href . '"' . (($media && $media != 'all') ? ' media="' . $media . '"' : '') . '>';
} | php | {
"resource": ""
} |
q243648 | Template.generateScriptTag | validation | public static function generateScriptTag($src, $async=false, $mtime=false, $hash=null, $crossorigin=null)
{
// Add the filemtime if not given and not an external file
if ($mtime === null && !preg_match('@^https?://@', $src))
{
$container = System::getContainer();
$rootDir = $container->getParameter('kernel.project_dir');
if (file_exists($rootDir . '/' . $src))
{
$mtime = filemtime($rootDir . '/' . $src);
}
else
{
$webDir = StringUtil::stripRootDir($container->getParameter('contao.web_dir'));
// Handle public bundle resources in web/
if (file_exists($rootDir . '/' . $webDir . '/' . $src))
{
$mtime = filemtime($rootDir . '/' . $webDir . '/' . $src);
}
}
}
if ($mtime)
{
$src .= '?v=' . substr(md5($mtime), 0, 8);
}
return '<script src="' . $src . '"' . ($async ? ' async' : '') . ($hash ? ' integrity="' . $hash . '"' : '') . ($crossorigin ? ' crossorigin="' . $crossorigin . '"' : '') . '></script>';
} | php | {
"resource": ""
} |
q243649 | Template.flushAllData | validation | public function flushAllData()
{
@trigger_error('Using Template::flushAllData() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED);
if (\function_exists('fastcgi_finish_request'))
{
fastcgi_finish_request();
}
elseif (PHP_SAPI !== 'cli')
{
$status = ob_get_status(true);
$level = \count($status);
while ($level-- > 0 && (!empty($status[$level]['del']) || (isset($status[$level]['flags']) && ($status[$level]['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE) && ($status[$level]['flags'] & PHP_OUTPUT_HANDLER_FLUSHABLE))))
{
ob_end_flush();
}
flush();
}
} | php | {
"resource": ""
} |
q243650 | DcaExtractor.getInstance | validation | public static function getInstance($strTable)
{
if (!isset(static::$arrInstances[$strTable]))
{
static::$arrInstances[$strTable] = new static($strTable);
}
return static::$arrInstances[$strTable];
} | php | {
"resource": ""
} |
q243651 | DcaExtractor.getDbInstallerArray | validation | public function getDbInstallerArray()
{
$return = array();
// Fields
foreach ($this->arrFields as $k=>$v)
{
if (\is_array($v))
{
if (!isset($v['name']))
{
$v['name'] = $k;
}
$return['SCHEMA_FIELDS'][$k] = $v;
}
else
{
$return['TABLE_FIELDS'][$k] = '`' . $k . '` ' . $v;
}
}
$quote = function ($item) { return '`' . $item . '`'; };
// Keys
foreach ($this->arrKeys as $k=>$v)
{
// Handle multi-column indexes (see #5556)
if (strpos($k, ',') !== false)
{
$f = array_map($quote, StringUtil::trimsplit(',', $k));
$k = str_replace(',', '_', $k);
}
else
{
$f = array($quote($k));
}
if ($v == 'primary')
{
$k = 'PRIMARY';
$v = 'PRIMARY KEY (' . implode(', ', $f) . ')';
}
elseif ($v == 'index')
{
$v = 'KEY `' . $k . '` (' . implode(', ', $f) . ')';
}
else
{
$v = strtoupper($v) . ' KEY `' . $k . '` (' . implode(', ', $f) . ')';
}
$return['TABLE_CREATE_DEFINITIONS'][$k] = $v;
}
$return['TABLE_OPTIONS'] = '';
// Options
foreach ($this->arrMeta as $k=>$v)
{
if ($k == 'engine')
{
$return['TABLE_OPTIONS'] .= ' ENGINE=' . $v;
}
elseif ($k == 'charset')
{
$return['TABLE_OPTIONS'] .= ' DEFAULT CHARSET=' . $v;
}
elseif ($k == 'collate')
{
$return['TABLE_OPTIONS'] .= ' COLLATE ' . $v;
}
}
return $return;
} | php | {
"resource": ""
} |
q243652 | Theme.exportTheme | validation | public function exportTheme(DataContainer $dc)
{
// Get the theme meta data
$objTheme = $this->Database->prepare("SELECT * FROM tl_theme WHERE id=?")
->limit(1)
->execute($dc->id);
if ($objTheme->numRows < 1)
{
return;
}
// Romanize the name
$strName = Utf8::toAscii($objTheme->name);
$strName = strtolower(str_replace(' ', '_', $strName));
$strName = preg_replace('/[^A-Za-z0-9._-]/', '', $strName);
$strName = basename($strName);
// Create a new XML document
$xml = new \DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;
// Root element
$tables = $xml->createElement('tables');
$tables = $xml->appendChild($tables);
// Add the tables
$this->addTableTlTheme($xml, $tables, $objTheme);
$this->addTableTlStyleSheet($xml, $tables, $objTheme);
$this->addTableTlImageSize($xml, $tables, $objTheme);
$this->addTableTlModule($xml, $tables, $objTheme);
$this->addTableTlLayout($xml, $tables, $objTheme);
// Generate the archive
$strTmp = md5(uniqid(mt_rand(), true));
$objArchive = new ZipWriter('system/tmp/'. $strTmp);
// Add the files
$this->addTableTlFiles($xml, $tables, $objTheme, $objArchive);
// Add the template files
$this->addTemplatesToArchive($objArchive, $objTheme->templates);
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['exportTheme']) && \is_array($GLOBALS['TL_HOOKS']['exportTheme']))
{
foreach ($GLOBALS['TL_HOOKS']['exportTheme'] as $callback)
{
System::importStatic($callback[0])->{$callback[1]}($xml, $objArchive, $objTheme->id);
}
}
// Add the XML document
$objArchive->addString($xml->saveXML(), 'theme.xml');
// Close the archive
$objArchive->close();
// Open the "save as …" dialogue
$objFile = new File('system/tmp/'. $strTmp);
$objFile->sendToBrowser($strName . '.cto');
} | php | {
"resource": ""
} |
q243653 | Theme.addTableTlTheme | validation | protected function addTableTlTheme(\DOMDocument $xml, \DOMNode $tables, Result $objTheme)
{
// Add the table
$table = $xml->createElement('table');
$table->setAttribute('name', 'tl_theme');
$table = $tables->appendChild($table);
// Load the DCA
$this->loadDataContainer('tl_theme');
// Get the order fields
$objDcaExtractor = DcaExtractor::getInstance('tl_theme');
$arrOrder = $objDcaExtractor->getOrderFields();
// Add the row
$this->addDataRow($xml, $table, $objTheme->row(), $arrOrder);
} | php | {
"resource": ""
} |
q243654 | Theme.addTableTlStyleSheet | validation | protected function addTableTlStyleSheet(\DOMDocument $xml, \DOMNode $tables, Result $objTheme)
{
// Add the table
$table = $xml->createElement('table');
$table->setAttribute('name', 'tl_style_sheet');
$table = $tables->appendChild($table);
// Load the DCA
$this->loadDataContainer('tl_style_sheet');
// Get the order fields
$objDcaExtractor = DcaExtractor::getInstance('tl_style_sheet');
$arrOrder = $objDcaExtractor->getOrderFields();
// Get all style sheets
$objStyleSheet = $this->Database->prepare("SELECT * FROM tl_style_sheet WHERE pid=? ORDER BY name")
->execute($objTheme->id);
// Add the rows
while ($objStyleSheet->next())
{
$this->addDataRow($xml, $table, $objStyleSheet->row(), $arrOrder);
}
$objStyleSheet->reset();
// Add the child table
$table = $xml->createElement('table');
$table->setAttribute('name', 'tl_style');
$table = $tables->appendChild($table);
// Load the DCA
$this->loadDataContainer('tl_style');
// Get the order fields
$objDcaExtractor = DcaExtractor::getInstance('tl_style');
$arrOrder = $objDcaExtractor->getOrderFields();
// Add the child rows
while ($objStyleSheet->next())
{
// Get all format definitions
$objStyle = $this->Database->prepare("SELECT * FROM tl_style WHERE pid=? ORDER BY sorting")
->execute($objStyleSheet->id);
// Add the rows
while ($objStyle->next())
{
$this->addDataRow($xml, $table, $objStyle->row(), $arrOrder);
}
}
} | php | {
"resource": ""
} |
q243655 | Theme.addTableTlModule | validation | protected function addTableTlModule(\DOMDocument $xml, \DOMNode $tables, Result $objTheme)
{
// Add the table
$table = $xml->createElement('table');
$table->setAttribute('name', 'tl_module');
$table = $tables->appendChild($table);
// Load the DCA
$this->loadDataContainer('tl_module');
// Get the order fields
$objDcaExtractor = DcaExtractor::getInstance('tl_module');
$arrOrder = $objDcaExtractor->getOrderFields();
// Get all modules
$objModule = $this->Database->prepare("SELECT * FROM tl_module WHERE pid=? ORDER BY name")
->execute($objTheme->id);
// Add the rows
while ($objModule->next())
{
$this->addDataRow($xml, $table, $objModule->row(), $arrOrder);
}
} | php | {
"resource": ""
} |
q243656 | Theme.addTableTlImageSize | validation | protected function addTableTlImageSize(\DOMDocument $xml, \DOMNode $tables, Result $objTheme)
{
// Add the tables
$imageSizeTable = $xml->createElement('table');
$imageSizeTable->setAttribute('name', 'tl_image_size');
$imageSizeTable = $tables->appendChild($imageSizeTable);
$imageSizeItemTable = $xml->createElement('table');
$imageSizeItemTable->setAttribute('name', 'tl_image_size_item');
$imageSizeItemTable = $tables->appendChild($imageSizeItemTable);
// Get all sizes
$objSizes = $this->Database->prepare("SELECT * FROM tl_image_size WHERE pid=?")
->execute($objTheme->id);
// Add the rows
while ($objSizes->next())
{
$this->addDataRow($xml, $imageSizeTable, $objSizes->row());
// Get all size items
$objSizeItems = $this->Database->prepare("SELECT * FROM tl_image_size_item WHERE pid=?")
->execute($objSizes->id);
// Add the rows
while ($objSizeItems->next())
{
$this->addDataRow($xml, $imageSizeItemTable, $objSizeItems->row());
}
}
} | php | {
"resource": ""
} |
q243657 | Theme.addTableTlFiles | validation | protected function addTableTlFiles(\DOMDocument $xml, \DOMElement $tables, Result $objTheme, ZipWriter $objArchive)
{
// Add the table
$table = $xml->createElement('table');
$table->setAttribute('name', 'tl_files');
$table = $tables->appendChild($table);
// Load the DCA
$this->loadDataContainer('tl_files');
// Get the order fields
$objDcaExtractor = DcaExtractor::getInstance('tl_files');
$arrOrder = $objDcaExtractor->getOrderFields();
// Add the folders
$arrFolders = StringUtil::deserialize($objTheme->folders);
if (!empty($arrFolders) && \is_array($arrFolders))
{
$objFolders = FilesModel::findMultipleByUuids($arrFolders);
if ($objFolders !== null)
{
foreach ($this->eliminateNestedPaths($objFolders->fetchEach('path')) as $strFolder)
{
$this->addFolderToArchive($objArchive, $strFolder, $xml, $table, $arrOrder);
}
}
}
} | php | {
"resource": ""
} |
q243658 | Theme.addDataRow | validation | protected function addDataRow(\DOMDocument $xml, \DOMElement $table, array $arrRow, array $arrOrder=array())
{
$t = $table->getAttribute('name');
$row = $xml->createElement('row');
$row = $table->appendChild($row);
foreach ($arrRow as $k=>$v)
{
$field = $xml->createElement('field');
$field->setAttribute('name', $k);
$field = $row->appendChild($field);
if ($v === null)
{
$v = 'NULL';
}
// Replace the IDs of singleSRC fields with their path (see #4952)
elseif ($GLOBALS['TL_DCA'][$t]['fields'][$k]['inputType'] == 'fileTree' && !$GLOBALS['TL_DCA'][$t]['fields'][$k]['eval']['multiple'])
{
$objFile = FilesModel::findByUuid($v);
if ($objFile !== null)
{
$v = $this->standardizeUploadPath($objFile->path);
}
else
{
$v = 'NULL';
}
}
// Replace the IDs of multiSRC fields with their paths (see #4952)
elseif ($GLOBALS['TL_DCA'][$t]['fields'][$k]['inputType'] == 'fileTree' || \in_array($k, $arrOrder))
{
$arrFiles = StringUtil::deserialize($v);
if (!empty($arrFiles) && \is_array($arrFiles))
{
$objFiles = FilesModel::findMultipleByUuids($arrFiles);
if ($objFiles !== null)
{
$arrTmp = array();
while ($objFiles->next())
{
$arrTmp[] = $this->standardizeUploadPath($objFiles->path);
}
$v = serialize($arrTmp);
}
else
{
$v = 'NULL';
}
}
}
elseif ($t == 'tl_style' && ($k == 'bgimage' || $k == 'liststyleimage'))
{
$v = $this->standardizeUploadPath($v);
}
$value = $xml->createTextNode($v);
$field->appendChild($value);
}
} | php | {
"resource": ""
} |
q243659 | Theme.addFolderToArchive | validation | protected function addFolderToArchive(ZipWriter $objArchive, $strFolder, \DOMDocument $xml, \DOMElement $table, array $arrOrder=array())
{
// Strip the custom upload folder name
$strFolder = preg_replace('@^'.preg_quote(Config::get('uploadPath'), '@').'/@', '', $strFolder);
// Add the default upload folder name
if ($strFolder == '')
{
$strTarget = 'files';
$strFolder = Config::get('uploadPath');
}
else
{
$strTarget = 'files/' . $strFolder;
$strFolder = Config::get('uploadPath') .'/'. $strFolder;
}
if (Validator::isInsecurePath($strFolder))
{
throw new \RuntimeException('Insecure path ' . $strFolder);
}
// Return if the folder does not exist
if (!is_dir($this->strRootDir .'/'. $strFolder))
{
return;
}
// Recursively add the files and subfolders
foreach (scan($this->strRootDir .'/'. $strFolder) as $strFile)
{
// Skip hidden resources
if (strncmp($strFile, '.', 1) === 0)
{
continue;
}
if (is_dir($this->strRootDir .'/'. $strFolder .'/'. $strFile))
{
$this->addFolderToArchive($objArchive, $strFolder .'/'. $strFile, $xml, $table, $arrOrder);
}
else
{
// Always store files in files and convert the directory upon import
$objArchive->addFile($strFolder .'/'. $strFile, $strTarget .'/'. $strFile);
$arrRow = array();
$objFile = new File($strFolder .'/'. $strFile);
$objModel = FilesModel::findByPath($strFolder .'/'. $strFile);
if ($objModel !== null)
{
$arrRow = $objModel->row();
foreach (array('id', 'pid', 'tstamp', 'uuid', 'type', 'extension', 'found', 'name') as $key)
{
unset($arrRow[$key]);
}
}
// Always use files as directory and convert it upon import
$arrRow['path'] = $strTarget .'/'. $strFile;
$arrRow['hash'] = $objFile->hash;
// Add the row
$this->addDataRow($xml, $table, $arrRow, $arrOrder);
}
}
} | php | {
"resource": ""
} |
q243660 | Theme.addTemplatesToArchive | validation | protected function addTemplatesToArchive(ZipWriter $objArchive, $strFolder)
{
// Strip the templates folder name
$strFolder = preg_replace('@^templates/@', '', $strFolder);
// Re-add the templates folder name
if ($strFolder == '')
{
$strFolder = 'templates';
}
else
{
$strFolder = 'templates/' . $strFolder;
}
if (Validator::isInsecurePath($strFolder))
{
throw new \RuntimeException('Insecure path ' . $strFolder);
}
// Return if the folder does not exist
if (!is_dir($this->strRootDir .'/'. $strFolder))
{
return;
}
// Add all template files to the archive (see #7048)
foreach (scan($this->strRootDir .'/'. $strFolder) as $strFile)
{
if (preg_match('/\.(html5|sql)$/', $strFile) && strncmp($strFile, 'be_', 3) !== 0 && strncmp($strFile, 'nl_', 3) !== 0)
{
$objArchive->addFile($strFolder .'/'. $strFile);
}
}
} | php | {
"resource": ""
} |
q243661 | Dbafs.moveResource | validation | public static function moveResource($strSource, $strDestination)
{
$objFile = FilesModel::findByPath($strSource);
// If there is no entry, directly add the destination
if ($objFile === null)
{
$objFile = static::addResource($strDestination);
}
$strFolder = \dirname($strDestination);
// Set the new parent ID
if ($strFolder == Config::get('uploadPath'))
{
$objFile->pid = null;
}
else
{
$objFolder = FilesModel::findByPath($strFolder);
if ($objFolder === null)
{
$objFolder = static::addResource($strFolder);
}
$objFile->pid = $objFolder->uuid;
}
// Save the resource
$objFile->path = $strDestination;
$objFile->name = basename($strDestination);
$objFile->save();
// Update all child records
if ($objFile->type == 'folder')
{
$objFiles = FilesModel::findMultipleByBasepath($strSource . '/');
if ($objFiles !== null)
{
while ($objFiles->next())
{
$objFiles->path = preg_replace('@^' . preg_quote($strSource, '@') . '/@', $strDestination . '/', $objFiles->path);
$objFiles->save();
}
}
}
// Update the MD5 hash of the parent folders
if (($strPath = \dirname($strSource)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
if (($strPath = \dirname($strDestination)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
return $objFile;
} | php | {
"resource": ""
} |
q243662 | Dbafs.copyResource | validation | public static function copyResource($strSource, $strDestination)
{
$objDatabase = Database::getInstance();
$objFile = FilesModel::findByPath($strSource);
// Add the source entry
if ($objFile === null)
{
$objFile = static::addResource($strSource);
}
$strFolder = \dirname($strDestination);
/** @var FilesModel $objNewFile */
$objNewFile = clone $objFile->current();
// Set the new parent ID
if ($strFolder == Config::get('uploadPath'))
{
$objNewFile->pid = null;
}
else
{
$objFolder = FilesModel::findByPath($strFolder);
if ($objFolder === null)
{
$objFolder = static::addResource($strFolder);
}
$objNewFile->pid = $objFolder->uuid;
}
// Save the resource
$objNewFile->tstamp = time();
$objNewFile->uuid = $objDatabase->getUuid();
$objNewFile->path = $strDestination;
$objNewFile->name = basename($strDestination);
$objNewFile->save();
// Update all child records
if ($objFile->type == 'folder')
{
$objFiles = FilesModel::findMultipleByBasepath($strSource . '/');
if ($objFiles !== null)
{
while ($objFiles->next())
{
/** @var FilesModel $objNew */
$objNew = clone $objFiles->current();
$objNew->pid = $objNewFile->uuid;
$objNew->tstamp = time();
$objNew->uuid = $objDatabase->getUuid();
$objNew->path = str_replace($strSource . '/', $strDestination . '/', $objFiles->path);
$objNew->save();
}
}
}
// Update the MD5 hash of the parent folders
if (($strPath = \dirname($strSource)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
if (($strPath = \dirname($strDestination)) != Config::get('uploadPath'))
{
static::updateFolderHashes($strPath);
}
return $objNewFile;
} | php | {
"resource": ""
} |
q243663 | Dbafs.deleteResource | validation | public static function deleteResource($strResource)
{
$objModel = FilesModel::findByPath($strResource);
// Remove the resource
if ($objModel !== null)
{
$objModel->delete();
}
// Look for subfolders and files
$objFiles = FilesModel::findMultipleByBasepath($strResource . '/');
// Remove subfolders and files as well
if ($objFiles !== null)
{
while ($objFiles->next())
{
$objFiles->delete();
}
}
static::updateFolderHashes(\dirname($strResource));
return null;
} | php | {
"resource": ""
} |
q243664 | Dbafs.updateFolderHashes | validation | public static function updateFolderHashes($varResource)
{
$arrPaths = array();
if (!\is_array($varResource))
{
$varResource = array($varResource);
}
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
foreach ($varResource as $strResource)
{
$arrChunks = explode('/', $strResource);
$strPath = array_shift($arrChunks);
// Do not check files
if (is_file($rootDir . '/' . $strResource))
{
array_pop($arrChunks);
}
// Build the paths
while (\count($arrChunks))
{
$strPath .= '/' . array_shift($arrChunks);
$arrPaths[] = $strPath;
}
unset($arrChunks);
}
$arrPaths = array_values(array_unique($arrPaths));
// Store the hash of each folder
foreach (array_reverse($arrPaths) as $strPath)
{
$objModel = FilesModel::findByPath($strPath);
// The DB entry does not yet exist
if ($objModel === null)
{
$objModel = static::addResource($strPath, false);
}
$objModel->hash = static::getFolderHash($strPath);
$objModel->save();
}
} | php | {
"resource": ""
} |
q243665 | Dbafs.getFolderHash | validation | public static function getFolderHash($strPath)
{
$strPath = str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $strPath);
$arrHash = array();
$objChildren = Database::getInstance()
->prepare("SELECT hash, name FROM tl_files WHERE path LIKE ? AND path NOT LIKE ? ORDER BY name")
->execute($strPath.'/%', $strPath.'/%/%')
;
if ($objChildren !== null)
{
while ($objChildren->next())
{
$arrHash[] = $objChildren->hash . $objChildren->name;
}
}
return md5(implode("\0", $arrHash));
} | php | {
"resource": ""
} |
q243666 | Dbafs.shouldBeSynchronized | validation | public static function shouldBeSynchronized($strPath)
{
if (!isset(static::$arrShouldBeSynchronized[$strPath]) || !\is_bool(static::$arrShouldBeSynchronized[$strPath]))
{
static::$arrShouldBeSynchronized[$strPath] = !static::isFileSyncExclude($strPath);
}
return static::$arrShouldBeSynchronized[$strPath];
} | php | {
"resource": ""
} |
q243667 | Dbafs.isFileSyncExclude | validation | protected static function isFileSyncExclude($strPath)
{
if (Config::get('uploadPath') == 'templates')
{
return true;
}
$rootDir = System::getContainer()->getParameter('kernel.project_dir');
// Look for an existing parent folder (see #410)
while ($strPath != '.' && !is_dir($rootDir . '/' . $strPath))
{
$strPath = \dirname($strPath);
}
if ($strPath == '.')
{
return true;
}
$uploadPath = System::getContainer()->getParameter('contao.upload_path');
// Outside the files directory
if (strncmp($strPath . '/', $uploadPath . '/', \strlen($uploadPath) + 1) !== 0)
{
return true;
}
return (new Folder($strPath))->isUnsynchronized();
} | php | {
"resource": ""
} |
q243668 | BackendMenuListener.onBuild | validation | public function onBuild(MenuEvent $event): void
{
if (null === $this->managerPath || !$this->isAdminUser()) {
return;
}
$categoryNode = $event->getTree()->getChild('system');
if (null === $categoryNode) {
return;
}
$item = $event->getFactory()->createItem(
'contao_manager',
[
'label' => 'Contao Manager',
'attributes' => [
'title' => 'Contao Manager',
'href' => '/'.$this->managerPath,
'class' => 'navigation contao_manager',
],
]
);
$categoryNode->addChild($item);
} | php | {
"resource": ""
} |
q243669 | FrontendCron.hasToWait | validation | protected function hasToWait()
{
$return = true;
// Get the timestamp without seconds (see #5775)
$time = strtotime(date('Y-m-d H:i'));
// Lock the table
$this->Database->lockTables(array('tl_cron'=>'WRITE'));
// Get the last execution date
$objCron = $this->Database->prepare("SELECT * FROM tl_cron WHERE name='lastrun'")
->limit(1)
->execute();
// Add the cron entry
if ($objCron->numRows < 1)
{
$this->Database->query("INSERT INTO tl_cron (name, value) VALUES ('lastrun', $time)");
$return = false;
}
// Check the last execution time
elseif ($objCron->value <= ($time - $this->getCronTimeout()))
{
$this->Database->query("UPDATE tl_cron SET value=$time WHERE name='lastrun'");
$return = false;
}
$this->Database->unlockTables();
return $return;
} | php | {
"resource": ""
} |
q243670 | ScriptHandler.initializeApplication | validation | public static function initializeApplication(Event $event): void
{
$webDir = self::getWebDir($event);
static::purgeCacheFolder();
static::addAppDirectory();
static::executeCommand('contao:install-web-dir', $event);
static::executeCommand('cache:clear --no-warmup', $event);
static::executeCommand('cache:warmup', $event);
static::executeCommand(sprintf('assets:install %s --symlink --relative', $webDir), $event);
static::executeCommand(sprintf('contao:install %s', $webDir), $event);
static::executeCommand(sprintf('contao:symlinks %s', $webDir), $event);
$event->getIO()->write('<info>Done! Please open the Contao install tool and make sure the database is up-to-date.</info>');
} | php | {
"resource": ""
} |
q243671 | tl_style_sheet.listStyleSheet | validation | public function listStyleSheet($row)
{
$cc = '';
$media = Contao\StringUtil::deserialize($row['media']);
if ($row['cc'] != '')
{
$cc = ' <!--['. $row['cc'] .']>';
}
if ($row['mediaQuery'] != '')
{
return '<div class="tl_content_left">'. $row['name'] .' <span style="color:#999;padding-left:3px">@media '. $row['mediaQuery'] . $cc .'</span>' . "</div>\n";
}
elseif (!empty($media) && \is_array($media))
{
return '<div class="tl_content_left">'. $row['name'] .' <span style="color:#999;padding-left:3px">@media '. implode(', ', $media) . $cc .'</span>' . "</div>\n";
}
else
{
return '<div class="tl_content_left">'. $row['name'] . $cc ."</div>\n";
}
} | php | {
"resource": ""
} |
q243672 | tl_style.checkCategory | validation | public function checkCategory($varValue)
{
// Do not change the value if it has been set already
if (\strlen($varValue) || Contao\Input::post('FORM_SUBMIT') == 'tl_style')
{
return $varValue;
}
/** @var Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface $objSessionBag */
$objSessionBag = Contao\System::getContainer()->get('session')->getBag('contao_backend');
$key = 'tl_style_' . CURRENT_ID;
$filter = $objSessionBag->get('filter');
// Return the current category
if (\strlen($filter[$key]['category']))
{
return $filter[$key]['category'];
}
return '';
} | php | {
"resource": ""
} |
q243673 | tl_style.updateAfterRestore | validation | public function updateAfterRestore($id, $table, $data)
{
if ($table != 'tl_style')
{
return;
}
// Update the timestamp of the style sheet
$this->Database->prepare("UPDATE tl_style_sheet SET tstamp=? WHERE id=?")
->execute(time(), $data['pid']);
// Update the CSS file
$this->import('Contao\StyleSheets', 'StyleSheets');
$this->StyleSheets->updateStyleSheet($data['pid']);
} | php | {
"resource": ""
} |
q243674 | Session.get | validation | public function get($strKey)
{
// Map the referer (see #281)
if (\in_array($strKey, $this->mappedKeys))
{
return $this->session->get($strKey);
}
return $this->sessionBag->get($strKey);
} | php | {
"resource": ""
} |
q243675 | Session.set | validation | public function set($strKey, $varValue)
{
// Map the referer (see #281)
if (\in_array($strKey, $this->mappedKeys))
{
$this->session->set($strKey, $varValue);
}
else
{
$this->sessionBag->set($strKey, $varValue);
}
} | php | {
"resource": ""
} |
q243676 | Session.remove | validation | public function remove($strKey)
{
// Map the referer (see #281)
if (\in_array($strKey, $this->mappedKeys))
{
$this->session->remove($strKey);
}
else
{
$this->sessionBag->remove($strKey);
}
} | php | {
"resource": ""
} |
q243677 | Session.getData | validation | public function getData()
{
$data = $this->sessionBag->all();
// Map the referer (see #281)
foreach ($this->mappedKeys as $strKey)
{
unset($data[$strKey]);
if ($this->session->has($strKey))
{
$data[$strKey] = $this->session->get($strKey);
}
}
return $data;
} | php | {
"resource": ""
} |
q243678 | Session.setData | validation | public function setData($arrData)
{
if (!\is_array($arrData))
{
throw new \Exception('Array required to set session data');
}
// Map the referer (see #281)
foreach ($this->mappedKeys as $strKey)
{
if (isset($arrData[$strKey]))
{
$this->session->set($strKey, $arrData[$strKey]);
unset($arrData[$strKey]);
}
}
$this->sessionBag->replace($arrData);
} | php | {
"resource": ""
} |
q243679 | Session.appendData | validation | public function appendData($varData)
{
if (\is_object($varData))
{
$varData = get_object_vars($varData);
}
if (!\is_array($varData))
{
throw new \Exception('Array or object required to append session data');
}
foreach ($varData as $k=>$v)
{
// Map the referer (see #281)
if (\in_array($k, $this->mappedKeys))
{
$this->session->set($k, $v);
}
else
{
$this->sessionBag->set($k, $v);
}
}
} | php | {
"resource": ""
} |
q243680 | PickerConfig.cloneForCurrent | validation | public function cloneForCurrent(string $current): self
{
return new self($this->context, $this->extras, $this->value, $current);
} | php | {
"resource": ""
} |
q243681 | PickerConfig.urlEncode | validation | public function urlEncode(): string
{
$data = json_encode($this);
if (\function_exists('gzencode') && false !== ($encoded = @gzencode($data))) {
$data = $encoded;
}
return strtr(base64_encode($data), '+/=', '-_,');
} | php | {
"resource": ""
} |
q243682 | PickerConfig.urlDecode | validation | public static function urlDecode(string $data): self
{
$decoded = base64_decode(strtr($data, '-_,', '+/='), true);
if (\function_exists('gzdecode') && false !== ($uncompressed = @gzdecode($decoded))) {
$decoded = $uncompressed;
}
$json = @json_decode($decoded, true);
if (null === $json) {
throw new \InvalidArgumentException('Invalid JSON data');
}
return new self($json['context'], $json['extras'], $json['value'], $json['current']);
} | php | {
"resource": ""
} |
q243683 | AbstractPickerProvider.getUser | validation | protected function getUser(): BackendUser
{
if (null === $this->tokenStorage) {
throw new \RuntimeException('No token storage provided');
}
$token = $this->tokenStorage->getToken();
if (null === $token) {
throw new \RuntimeException('No token provided');
}
$user = $token->getUser();
if (!$user instanceof BackendUser) {
throw new \RuntimeException('The token does not contain a back end user object');
}
return $user;
} | php | {
"resource": ""
} |
q243684 | Encryption.encrypt | validation | public static function encrypt($varValue, $strKey=null)
{
// Recursively encrypt arrays
if (\is_array($varValue))
{
foreach ($varValue as $k=>$v)
{
$varValue[$k] = static::encrypt($v);
}
return $varValue;
}
elseif ($varValue == '')
{
return '';
}
// Initialize the module
if (static::$resTd === null)
{
static::initialize();
}
if (!$strKey)
{
$strKey = System::getContainer()->getParameter('contao.encryption_key');
}
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size(static::$resTd));
mcrypt_generic_init(static::$resTd, md5($strKey), $iv);
$strEncrypted = mcrypt_generic(static::$resTd, $varValue);
$strEncrypted = base64_encode($iv.$strEncrypted);
mcrypt_generic_deinit(static::$resTd);
return $strEncrypted;
} | php | {
"resource": ""
} |
q243685 | Encryption.decrypt | validation | public static function decrypt($varValue, $strKey=null)
{
// Recursively decrypt arrays
if (\is_array($varValue))
{
foreach ($varValue as $k=>$v)
{
$varValue[$k] = static::decrypt($v);
}
return $varValue;
}
elseif ($varValue == '')
{
return '';
}
// Initialize the module
if (static::$resTd === null)
{
static::initialize();
}
$varValue = base64_decode($varValue);
$ivsize = mcrypt_enc_get_iv_size(static::$resTd);
$iv = substr($varValue, 0, $ivsize);
$varValue = substr($varValue, $ivsize);
if ($varValue == '')
{
return '';
}
if (!$strKey)
{
$strKey = System::getContainer()->getParameter('contao.encryption_key');
}
mcrypt_generic_init(static::$resTd, md5($strKey), $iv);
$strDecrypted = mdecrypt_generic(static::$resTd, $varValue);
mcrypt_generic_deinit(static::$resTd);
return $strDecrypted;
} | php | {
"resource": ""
} |
q243686 | Encryption.initialize | validation | protected static function initialize()
{
if (!\in_array('mcrypt', get_loaded_extensions()))
{
throw new \Exception('The PHP mcrypt extension is not installed');
}
if (!self::$resTd = mcrypt_module_open(Config::get('encryptionCipher'), '', Config::get('encryptionMode'), ''))
{
throw new \Exception('Error initializing encryption module');
}
} | php | {
"resource": ""
} |
q243687 | tl_comments.checkPermission | validation | public function checkPermission()
{
switch (Contao\Input::get('act'))
{
case 'select':
case 'show':
// Allow
break;
case 'edit':
case 'delete':
case 'toggle':
$objComment = $this->Database->prepare("SELECT id, parent, source FROM tl_comments WHERE id=?")
->limit(1)
->execute(Contao\Input::get('id'));
if ($objComment->numRows < 1)
{
throw new Contao\CoreBundle\Exception\AccessDeniedException('Invalid comment ID ' . Contao\Input::get('id') . '.');
}
if (!$this->isAllowedToEditComment($objComment->parent, $objComment->source))
{
throw new Contao\CoreBundle\Exception\AccessDeniedException('Not enough permissions to ' . Contao\Input::get('act') . ' comment ID ' . Contao\Input::get('id') . ' (parent element: ' . $objComment->source . ' ID ' . $objComment->parent . ').');
}
break;
case 'editAll':
case 'deleteAll':
case 'overrideAll':
/** @var Symfony\Component\HttpFoundation\Session\SessionInterface $objSession */
$objSession = Contao\System::getContainer()->get('session');
$session = $objSession->all();
if (empty($session['CURRENT']['IDS']) || !\is_array($session['CURRENT']['IDS']))
{
break;
}
$objComment = $this->Database->execute("SELECT id, parent, source FROM tl_comments WHERE id IN(" . implode(',', array_map('\intval', $session['CURRENT']['IDS'])) . ")");
while ($objComment->next())
{
if (!$this->isAllowedToEditComment($objComment->parent, $objComment->source) && ($key = array_search($objComment->id, $session['CURRENT']['IDS'])) !== false)
{
unset($session['CURRENT']['IDS'][$key]);
}
}
$session['CURRENT']['IDS'] = array_values($session['CURRENT']['IDS']);
$objSession->replace($session);
break;
default:
if (\strlen(Contao\Input::get('act')))
{
throw new Contao\CoreBundle\Exception\AccessDeniedException('Invalid command "' . Contao\Input::get('act') . '.');
}
break;
}
} | php | {
"resource": ""
} |
q243688 | tl_comments.notifyOfReply | validation | public function notifyOfReply(Contao\DataContainer $dc)
{
// Return if there is no active record (override all) or no reply or the notification has been sent already
if (!$dc->activeRecord || !$dc->activeRecord->addReply || $dc->activeRecord->notifyReply)
{
return;
}
$objNotify = Contao\CommentsNotifyModel::findActiveBySourceAndParent($dc->activeRecord->source, $dc->activeRecord->parent);
if ($objNotify !== null)
{
while ($objNotify->next())
{
// Prepare the URL
$strUrl = Contao\Idna::decode(Contao\Environment::get('base')) . $objNotify->url;
$objEmail = new Contao\Email();
$objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
$objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
$objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['com_notifyReplySubject'], Contao\Idna::decode(Contao\Environment::get('host')));
$objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['com_notifyReplyMessage'], $objNotify->name, $strUrl . '#c' . $dc->id, $strUrl . '?token=' . $objNotify->tokenRemove);
$objEmail->sendTo($objNotify->email);
}
}
$this->Database->prepare("UPDATE tl_comments SET notifiedReply='1' WHERE id=?")->execute($dc->id);
} | php | {
"resource": ""
} |
q243689 | tl_comments.sendNotifications | validation | public function sendNotifications($varValue)
{
if ($varValue)
{
Contao\Comments::notifyCommentsSubscribers(Contao\CommentsModel::findByPk(Contao\Input::get('id')));
}
return $varValue;
} | php | {
"resource": ""
} |
q243690 | tl_comments.editComment | validation | public function editComment($row, $href, $label, $title, $icon, $attributes)
{
return $this->isAllowedToEditComment($row['parent'], $row['source']) ? '<a href="'.$this->addToUrl($href.'&id='.$row['id']).'" title="'.Contao\StringUtil::specialchars($title).'"'.$attributes.'>'.Contao\Image::getHtml($icon, $label).'</a> ' : Contao\Image::getHtml(preg_replace('/\.svg/i', '_.svg', $icon)).' ';
} | php | {
"resource": ""
} |
q243691 | tl_comments.invalidateSourceCacheTag | validation | public function invalidateSourceCacheTag(Contao\DataContainer $dc, array $tags)
{
$commentModel = Contao\CommentsModel::findByPk($dc->id);
if (null !== $commentModel)
{
$tags[] = sprintf('contao.comments.%s.%s', $commentModel->source, $commentModel->parent);
}
return $tags;
} | php | {
"resource": ""
} |
q243692 | LocaleListener.onKernelRequest | validation | public function onKernelRequest(GetResponseEvent $event): void
{
if (!$this->scopeMatcher->isContaoRequest($event->getRequest())) {
return;
}
$request = $event->getRequest();
$request->attributes->set('_locale', $this->getLocale($request));
} | php | {
"resource": ""
} |
q243693 | LocaleListener.getLocale | validation | private function getLocale(Request $request): string
{
if (null !== $request->attributes->get('_locale')) {
return $this->formatLocaleId($request->attributes->get('_locale'));
}
return $request->getPreferredLanguage($this->availableLocales);
} | php | {
"resource": ""
} |
q243694 | NewsletterBlacklistModel.findByHashAndPid | validation | public static function findByHashAndPid($strHash, $intPid, array $arrOptions=array())
{
$t = static::$strTable;
return static::findOneBy(array("($t.hash=? AND $t.pid=?)"), array($strHash, $intPid), $arrOptions);
} | php | {
"resource": ""
} |
q243695 | DC_Table.showAll | validation | public function showAll()
{
$return = '';
$this->limit = '';
/** @var Session $objSession */
$objSession = System::getContainer()->get('session');
$undoPeriod = (int) Config::get('undoPeriod');
$logPeriod = (int) Config::get('logPeriod');
// Clean up old tl_undo and tl_log entries
if ($this->strTable == 'tl_undo' && $undoPeriod > 0)
{
$this->Database->prepare("DELETE FROM tl_undo WHERE tstamp<?")
->execute(time() - $undoPeriod);
}
elseif ($this->strTable == 'tl_log' && $logPeriod > 0)
{
$this->Database->prepare("DELETE FROM tl_log WHERE tstamp<?")
->execute(time() - $logPeriod);
}
$this->reviseTable();
// Add to clipboard
if (Input::get('act') == 'paste')
{
$arrClipboard = $objSession->get('CLIPBOARD');
$arrClipboard[$this->strTable] = array
(
'id' => Input::get('id'),
'childs' => Input::get('childs'),
'mode' => Input::get('mode')
);
$objSession->set('CLIPBOARD', $arrClipboard);
}
// Custom filter
if (!empty($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['filter']) && \is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['filter']))
{
foreach ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['filter'] as $filter)
{
$this->procedure[] = $filter[0];
$this->values[] = $filter[1];
}
}
// Render view
if ($this->treeView)
{
$return .= $this->panel();
$return .= $this->treeView();
}
else
{
if (Input::get('table') && $this->ptable && $this->Database->fieldExists('pid', $this->strTable))
{
$this->procedure[] = 'pid=?';
$this->values[] = CURRENT_ID;
}
$return .= $this->panel();
$return .= ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 4) ? $this->parentView() : $this->listView();
// Add another panel at the end of the page
if (strpos($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['panelLayout'], 'limit') !== false)
{
$return .= $this->paginationMenu();
}
}
return $return;
} | php | {
"resource": ""
} |
q243696 | DC_Table.copyAll | validation | public function copyAll()
{
if ($GLOBALS['TL_DCA'][$this->strTable]['config']['notCopyable'])
{
throw new InternalServerErrorException('Table "' . $this->strTable . '" is not copyable.');
}
/** @var Session $objSession */
$objSession = System::getContainer()->get('session');
$arrClipboard = $objSession->get('CLIPBOARD');
if (isset($arrClipboard[$this->strTable]) && \is_array($arrClipboard[$this->strTable]['id']))
{
foreach ($arrClipboard[$this->strTable]['id'] as $id)
{
$this->intId = $id;
$id = $this->copy(true);
Input::setGet('pid', $id);
Input::setGet('mode', 1);
}
}
$this->redirect($this->getReferer());
} | php | {
"resource": ""
} |
q243697 | DC_Table.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 (\is_array($ids) && \strlen($ids[0]))
{
foreach ($ids as $id)
{
$this->intId = $id;
$this->delete(true);
}
}
$this->redirect($this->getReferer());
} | php | {
"resource": ""
} |
q243698 | DC_Table.deleteChilds | validation | public function deleteChilds($table, $id, &$delete)
{
$cctable = array();
$ctable = $GLOBALS['TL_DCA'][$table]['config']['ctable'];
if (!\is_array($ctable))
{
return;
}
// Walk through each child table
foreach ($ctable as $v)
{
$this->loadDataContainer($v);
$cctable[$v] = $GLOBALS['TL_DCA'][$v]['config']['ctable'];
// Consider the dynamic parent table (see #4867)
if ($GLOBALS['TL_DCA'][$v]['config']['dynamicPtable'])
{
$ptable = $GLOBALS['TL_DCA'][$v]['config']['ptable'];
$cond = ($ptable == 'tl_article') ? "(ptable=? OR ptable='')" : "ptable=?";
$objDelete = $this->Database->prepare("SELECT id FROM $v WHERE pid=? AND $cond")
->execute($id, $ptable);
}
else
{
$objDelete = $this->Database->prepare("SELECT id FROM $v WHERE pid=?")
->execute($id);
}
if (!$GLOBALS['TL_DCA'][$v]['config']['doNotDeleteRecords'] && \strlen($v) && $objDelete->numRows)
{
foreach ($objDelete->fetchAllAssoc() as $row)
{
$delete[$v][] = $row['id'];
if (!empty($cctable[$v]))
{
$this->deleteChilds($v, $row['id'], $delete);
}
}
}
}
} | php | {
"resource": ""
} |
q243699 | DC_Table.undo | validation | public function undo()
{
$objRecords = $this->Database->prepare("SELECT * FROM " . $this->strTable . " WHERE id=?")
->limit(1)
->execute($this->intId);
// Check whether there is a record
if ($objRecords->numRows < 1)
{
$this->redirect($this->getReferer());
}
$error = false;
$query = $objRecords->query;
$data = StringUtil::deserialize($objRecords->data);
if (!\is_array($data))
{
$this->redirect($this->getReferer());
}
$arrFields = array();
// Restore the data
foreach ($data as $table=>$fields)
{
$this->loadDataContainer($table);
// Get the currently available fields
if (!isset($arrFields[$table]))
{
$arrFields[$table] = array_flip($this->Database->getFieldNames($table));
}
foreach ($fields as $row)
{
// Unset fields that no longer exist in the database
$row = array_intersect_key($row, $arrFields[$table]);
// Re-insert the data
$objInsertStmt = $this->Database->prepare("INSERT INTO " . $table . " %s")
->set($row)
->execute();
// Do not delete record from tl_undo if there is an error
if ($objInsertStmt->affectedRows < 1)
{
$error = true;
}
// Trigger the undo_callback
if (\is_array($GLOBALS['TL_DCA'][$table]['config']['onundo_callback']))
{
foreach ($GLOBALS['TL_DCA'][$table]['config']['onundo_callback'] as $callback)
{
if (\is_array($callback))
{
$this->import($callback[0]);
$this->{$callback[0]}->{$callback[1]}($table, $row, $this);
}
elseif (\is_callable($callback))
{
$callback($table, $row, $this);
}
}
}
}
}
// Add log entry and delete record from tl_undo if there was no error
if (!$error)
{
$this->log('Undone '. $query, __METHOD__, TL_GENERAL);
$this->Database->prepare("DELETE FROM " . $this->strTable . " WHERE id=?")
->limit(1)
->execute($this->intId);
}
$this->redirect($this->getReferer());
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.