public function getDownloadElement($strTag) { $params = preg_split('/::/', $strTag); if (is_array($params) && !empty($params)) { if (strpos($params[0], 'download') === 0) { $singleSRC = strip_tags($params[1]); // remove <span> etc, otherwise Validator::isuuid fail $objDownload = new \stdClass(); if (strpos($singleSRC, '/') !== false) { if (($objFile = FilesModel::findByPath($singleSRC)) !== null && $objFile->uuid) { $singleSRC = \StringUtil::binToUuid($objFile->uuid); } } $objDownload->singleSRC = $singleSRC; $objDownload->linkTitle = strip_tags($params[2]); // remove <span> etc $objDownload->cssID[1] = 'inserttag_download ' . strip_tags($params[3]); $objDownload->cssID[0] = strip_tags($params[4]); $objContentDownload = new \ContentDownloadInserttag($objDownload); $output = $objContentDownload->generate(); if ($params[0] == 'download') { return $output; } if ($params[0] == 'download_link') { return $objContentDownload->Template->href; } if ($params[0] == 'download_size') { return $objContentDownload->Template->filesize; } return ''; } } return false; }
/** * Compress images * * @param boolean $arrFiles File array */ public function processPostUpload($arrFiles) { if (is_array($arrFiles) && $GLOBALS['TL_CONFIG']['tinypng_api_key'] != '') { $strUrl = 'https://api.tinypng.com/shrink'; $strKey = $GLOBALS['TL_CONFIG']['tinypng_api_key']; $strAuthorization = 'Basic ' . base64_encode("api:{$strKey}"); foreach ($arrFiles as $file) { $objFile = FilesModel::findByPath($file); if (in_array($objFile->extension, array('png', 'jpg', 'jpeg'))) { $strFile = TL_ROOT . '/' . $file; $objRequest = new Request(); $objRequest->method = 'post'; $objRequest->data = file_get_contents($strFile); $objRequest->setHeader('Content-type', 'image/png'); $objRequest->setHeader('Authorization', $strAuthorization); $objRequest->send($strUrl); $arrResponse = json_decode($objRequest->response); if ($objRequest->code == 201) { file_put_contents($strFile, fopen($arrResponse->output->url, "rb", false)); $objFile->tstamp = time(); $objFile->path = $file; $objFile->hash = md5_file(TL_ROOT . '/' . $file); $objFile->save(); System::log('Compression was successful. (File: ' . $file . ')', __METHOD__, TL_FILES); } else { System::log('Compression failed. (' . $arrResponse->message . ') (File: ' . $file . ')', __METHOD__, TL_FILES); } } } } }
/** * Generate the content element */ protected function compile() { if (($video = $this->getVideo()) === null) { return; } $video->setCustomName($this->vimeo_customName); $video->setPosterSize(deserialize($this->size, true)); // Enable the lightbox if ($this->vimeo_lightbox) { $video->enableLightbox(); // Enable the lightbox autoplay if ($this->vimeo_lightboxAutoplay) { $video->enableLightboxAutoplay(); } } // Enable the link if ($this->vimeo_link) { $video->enableLink(); $video->setLinkUrl($this->url); $video->setLinkTitle($this->titleText); } // Set a custom poster if ($this->vimeo_customPoster) { $fileModel = FilesModel::findByPk($this->singleSRC); if ($fileModel !== null && is_file(TL_ROOT . '/' . $fileModel->path)) { $video->setPoster($fileModel->path); } } $this->Template->buffer = $video->generate(new FrontendTemplate($this->vimeo_template)); }
private function getContaoFile($uuid) { $uuid = StringUtil::deserialize($uuid); if (is_array($uuid)) { return FilesModel::findMultipleByUuids($uuid); } return FilesModel::findByUuid($uuid); }
public function addTypeIcon($row, $label, DataContainer $dc, $args = null) { $args[0] = \Image::getHtml(\Image::get('system/modules/mail_to/assets/mail-open-image.png', 16, 16)); $objFile = FilesModel::findByUuid($row['folder']); $args[2] = $objFile !== null ? $objFile->path : '-'; $args[5] = Date::parse(Date::getFormatFromRgxp('datim'), $row['lastrun']); return $args; }
public function moveFiles(\DataContainer $dc) { $arrPost = Request::getPost(); foreach ($arrPost as $key => $value) { $arrData = $GLOBALS['TL_DCA'][$dc->table]['fields'][$key]; if ($arrData['inputType'] != MultiFileUpload::NAME) { continue; } $arrFiles = deserialize($dc->activeRecord->{$key}); $strUploadFolder = Files::getFolderFromDca($arrData['eval']['uploadFolder'], $dc); if ($strUploadFolder === null) { throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['uploadNoUploadFolderDeclared'], $key, MultiFileUpload::UPLOAD_TMP)); } if (!is_array($arrFiles)) { $arrFiles = array($arrFiles); } $objFileModels = FilesModel::findMultipleByUuids($arrFiles); if ($objFileModels === null) { continue; } $arrPaths = $objFileModels->fetchEach('path'); $arrTargets = array(); // do not loop over $objFileModels as $objFile->close() will pull models away foreach ($arrPaths as $strPath) { $objFile = new \File($strPath); $strName = $objFile->name; $strTarget = $strUploadFolder . '/' . $strName; // upload_path_callback if (is_array($arrData['upload_path_callback'])) { foreach ($arrData['upload_path_callback'] as $callback) { $strTarget = \System::importStatic($callback[0])->{$callback[1]}($strTarget, $objFile, $dc) ?: $strTarget; } } if (StringUtil::startsWith($objFile->path, ltrim($strTarget, '/'))) { continue; } if ($objFile->renameTo($strTarget)) { $arrTargets[] = $strTarget; $objFile->close(); continue; } $arrTargets[] = $strPath; } // HOOK: post upload callback if (isset($GLOBALS['TL_HOOKS']['postUpload']) && is_array($GLOBALS['TL_HOOKS']['postUpload'])) { foreach ($GLOBALS['TL_HOOKS']['postUpload'] as $callback) { if (is_array($callback)) { \System::importStatic($callback[0])->{$callback[1]}($arrTargets); } elseif (is_callable($callback)) { $callback($arrTargets); } } } } }
/** * Initialize the object * * @param string $strTable * @param integer $intPid */ public function __construct($strTable, $intPid) { $this->import('Database'); parent::__construct(); $this->strTable = $strTable; $this->intPid = $intPid; // Store the path if it is an editable file if ($strTable == 'tl_files') { $objFile = \FilesModel::findByPk($intPid); if ($objFile !== null && in_array($objFile->extension, \StringUtil::trimsplit(',', strtolower(\Config::get('editableFiles'))))) { $this->strPath = $objFile->path; } } }
protected function compile() { $db = \Database::getInstance(); $intID = Input::get('companyID'); $objCompany = CompanyModel::findByPk($intID); if ($objCompany) { global $objPage; $objPage->pageTitle = $objCompany->company; $objTemplate = new FrontendTemplate('company_detail'); $objFile = FilesModel::findByPk($objCompany->logo); $arrSize = deserialize($this->imgSize); // Get Categories $strCategory = ''; $arrCategories = deserialize($objCompany->category); if (count($arrCategories) > 0) { $arrCategory = array(); $objCompanyCategories = $db->prepare("SELECT * FROM tl_company_category WHERE id IN(" . implode(',', $arrCategories) . ")")->execute(); while ($objCompanyCategories->next()) { $arrCategory[] = $objCompanyCategories->title; } $strCategory = implode(', ', $arrCategory); } $objTemplate->company = $objCompany->company; $objTemplate->contact_person = $objCompany->contact_person; $objTemplate->category = $strCategory; $objTemplate->street = $objCompany->street; $objTemplate->postal_code = $objCompany->postal_code; $objTemplate->city = $objCompany->city; $objTemplate->phone = $objCompany->phone; $objTemplate->fax = $objCompany->fax; $objTemplate->email = $objCompany->email; $objTemplate->homepage = $objCompany->homepage; $objTemplate->lat = $objCompany->lat; $objTemplate->lng = $objCompany->lng; $objTemplate->logo = \Image::get($objFile->path, $arrSize[0], $arrSize[1], $arrSize[2]); $objTemplate->imageWidth = $arrSize[0]; $objTemplate->imageHeight = $arrSize[1]; $objTemplate->information = $objCompany->information; $this->Template->strHtml = $objTemplate->parse(); } }
/** * @return string */ public function generate() { if (TL_MODE == 'BE') { $objTemplate = new BackendTemplate('be_wildcard'); $objTemplate->wildcard = '### LOGO MODULE ###'; return $objTemplate->parse(); } if ($this->singleSRC == '') { return ''; } $objFile = FilesModel::findByUuid($this->singleSRC); if ($objFile === null) { if (!Validator::isUuid($this->singleSRC)) { return '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>'; } return ''; } if (!is_file(TL_ROOT . '/' . $objFile->path)) { return ''; } $this->singleSRC = $objFile->path; return parent::generate(); }
/** * Gibt den Pfad und die Abmessungen des angepassten Bilds zurück. * @param $strImageId * @param $strSize * @return mixed */ public static function getImageData($strImageId, $strSize) { $objImg = \Contao\FilesModel::findByPk($strImageId); $arrSize = deserialize($strSize); $arrMeta = deserialize($objImg->meta); if ($arrMeta != null && isset($arrMeta[$GLOBALS['TL_LANGUAGE']])) { $arrData['meta'] = $arrMeta[$GLOBALS['TL_LANGUAGE']]; } else { $arrData['meta']['title'] = $objImg->name; } if (!is_array($arrSize)) { $arrSize = getimagesize($objImg->path); $imageObj = \Contao\Image::create($objImg->path, array($arrSize[0], $arrSize[1], $arrSize[2])); $imageObj->executeResize(); $arrData['path'] = $imageObj->getResizedPath(); } if (!isset($arrData['path'])) { $arrData['path'] = $objImg->path; } $arrData['name'] = $objImg->name; $arrData['width'] = $arrSize[0]; $arrData['height'] = $arrSize[1]; return $arrData; }
/** * Generate the content element */ protected function compile() { /** @var PageModel $objPage */ global $objPage; $images = array(); $auxDate = array(); $objFiles = $this->objFiles; // Get all images while ($objFiles->next()) { // Continue if the files has been processed or does not exist if (isset($images[$objFiles->path]) || !file_exists(TL_ROOT . '/' . $objFiles->path)) { continue; } // Single files if ($objFiles->type == 'file') { $objFile = new \File($objFiles->path); if (!$objFile->isImage) { continue; } $arrMeta = $this->getMetaData($objFiles->meta, $objPage->language); if (empty($arrMeta)) { if ($this->metaIgnore) { continue; } elseif ($objPage->rootFallbackLanguage !== null) { $arrMeta = $this->getMetaData($objFiles->meta, $objPage->rootFallbackLanguage); } } // Use the file name as title if none is given if ($arrMeta['title'] == '') { $arrMeta['title'] = \StringUtil::specialchars($objFile->basename); } // Add the image $images[$objFiles->path] = array('id' => $objFiles->id, 'uuid' => $objFiles->uuid, 'name' => $objFile->basename, 'singleSRC' => $objFiles->path, 'title' => \StringUtil::specialchars($arrMeta['title']), 'alt' => \StringUtil::specialchars($arrMeta['alt']), 'imageUrl' => $arrMeta['link'], 'caption' => $arrMeta['caption']); $auxDate[] = $objFile->mtime; } else { $objSubfiles = \FilesModel::findByPid($objFiles->uuid); if ($objSubfiles === null) { continue; } while ($objSubfiles->next()) { // Skip subfolders if ($objSubfiles->type == 'folder') { continue; } $objFile = new \File($objSubfiles->path); if (!$objFile->isImage) { continue; } $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->language); if (empty($arrMeta)) { if ($this->metaIgnore) { continue; } elseif ($objPage->rootFallbackLanguage !== null) { $arrMeta = $this->getMetaData($objSubfiles->meta, $objPage->rootFallbackLanguage); } } // Use the file name as title if none is given if ($arrMeta['title'] == '') { $arrMeta['title'] = \StringUtil::specialchars($objFile->basename); } // Add the image $images[$objSubfiles->path] = array('id' => $objSubfiles->id, 'uuid' => $objSubfiles->uuid, 'name' => $objFile->basename, 'singleSRC' => $objSubfiles->path, 'title' => \StringUtil::specialchars($arrMeta['title']), 'alt' => \StringUtil::specialchars($arrMeta['alt']), 'imageUrl' => $arrMeta['link'], 'caption' => $arrMeta['caption']); $auxDate[] = $objFile->mtime; } } } // Sort array switch ($this->sortBy) { default: case 'name_asc': uksort($images, 'basename_natcasecmp'); break; case 'name_desc': uksort($images, 'basename_natcasercmp'); break; case 'date_asc': array_multisort($images, SORT_NUMERIC, $auxDate, SORT_ASC); break; case 'date_desc': array_multisort($images, SORT_NUMERIC, $auxDate, SORT_DESC); break; // Deprecated since Contao 4.0, to be removed in Contao 5.0 // Deprecated since Contao 4.0, to be removed in Contao 5.0 case 'meta': @trigger_error('The "meta" key in ContentGallery::compile() has been deprecated and will no longer work in Contao 5.0.', E_USER_DEPRECATED); // no break; // no break; case 'custom': if ($this->orderSRC != '') { $tmp = \StringUtil::deserialize($this->orderSRC); if (!empty($tmp) && is_array($tmp)) { // Remove all values $arrOrder = array_map(function () { }, array_flip($tmp)); // Move the matching elements to their position in $arrOrder foreach ($images as $k => $v) { if (array_key_exists($v['uuid'], $arrOrder)) { $arrOrder[$v['uuid']] = $v; unset($images[$k]); } } // Append the left-over images at the end if (!empty($images)) { $arrOrder = array_merge($arrOrder, array_values($images)); } // Remove empty (unreplaced) entries $images = array_values(array_filter($arrOrder)); unset($arrOrder); } } break; case 'random': shuffle($images); $this->Template->isRandomOrder = true; break; } $images = array_values($images); // Limit the total number of items (see #2652) if ($this->numberOfItems > 0) { $images = array_slice($images, 0, $this->numberOfItems); } $offset = 0; $total = count($images); $limit = $total; // Paginate the result of not randomly sorted (see #8033) if ($this->perPage > 0 && $this->sortBy != 'random') { // Get the current page $id = 'page_g' . $this->id; $page = \Input::get($id) !== null ? \Input::get($id) : 1; // Do not index or cache the page if the page number is outside the range if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) { throw new PageNotFoundException('Page not found: ' . \Environment::get('uri')); } // Set limit and offset $offset = ($page - 1) * $this->perPage; $limit = min($this->perPage + $offset, $total); $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id); $this->Template->pagination = $objPagination->generate("\n "); } $rowcount = 0; $colwidth = floor(100 / $this->perRow); $intMaxWidth = TL_MODE == 'BE' ? floor(640 / $this->perRow) : floor(\Config::get('maxImageWidth') / $this->perRow); $strLightboxId = 'lightbox[lb' . $this->id . ']'; $body = array(); // Rows for ($i = $offset; $i < $limit; $i = $i + $this->perRow) { $class_tr = ''; if ($rowcount == 0) { $class_tr .= ' row_first'; } if ($i + $this->perRow >= $limit) { $class_tr .= ' row_last'; } $class_eo = $rowcount % 2 == 0 ? ' even' : ' odd'; // Columns for ($j = 0; $j < $this->perRow; $j++) { $class_td = ''; if ($j == 0) { $class_td .= ' col_first'; } if ($j == $this->perRow - 1) { $class_td .= ' col_last'; } $objCell = new \stdClass(); $key = 'row_' . $rowcount . $class_tr . $class_eo; // Empty cell if (!is_array($images[$i + $j]) || $j + $i >= $limit) { $objCell->colWidth = $colwidth . '%'; $objCell->class = 'col_' . $j . $class_td; } else { // Add size and margin $images[$i + $j]['size'] = $this->size; $images[$i + $j]['imagemargin'] = $this->imagemargin; $images[$i + $j]['fullsize'] = $this->fullsize; $this->addImageToTemplate($objCell, $images[$i + $j], $intMaxWidth, $strLightboxId); // Add column width and class $objCell->colWidth = $colwidth . '%'; $objCell->class = 'col_' . $j . $class_td; } $body[$key][$j] = $objCell; } ++$rowcount; } $strTemplate = 'gallery_default'; // Use a custom template if (TL_MODE == 'FE' && $this->galleryTpl != '') { $strTemplate = $this->galleryTpl; } /** @var FrontendTemplate|object $objTemplate */ $objTemplate = new \FrontendTemplate($strTemplate); $objTemplate->setData($this->arrData); $objTemplate->body = $body; $objTemplate->headline = $this->headline; // see #1603 $this->Template->images = $objTemplate->parse(); }
/** * Generate the module */ protected function compile() { /** @var PageModel $objPage */ global $objPage; $this->Template->event = ''; $this->Template->referer = 'javascript:history.go(-1)'; $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack']; // Get the current event $objEvent = \CalendarEventsModel::findPublishedByParentAndIdOrAlias(\Input::get('events'), $this->cal_calendar); if (null === $objEvent) { throw new PageNotFoundException('Page not found: ' . \Environment::get('uri')); } // Overwrite the page title (see #2853 and #4955) if ($objEvent->title != '') { $objPage->pageTitle = strip_tags(\StringUtil::stripInsertTags($objEvent->title)); } // Overwrite the page description if ($objEvent->teaser != '') { $objPage->description = $this->prepareMetaDescription($objEvent->teaser); } $intStartTime = $objEvent->startTime; $intEndTime = $objEvent->endTime; $span = \Calendar::calculateSpan($intStartTime, $intEndTime); // Do not show dates in the past if the event is recurring (see #923) if ($objEvent->recurring) { $arrRange = \StringUtil::deserialize($objEvent->repeatEach); if (is_array($arrRange) && isset($arrRange['unit']) && isset($arrRange['value'])) { while ($intStartTime < time() && $intEndTime < $objEvent->repeatEnd) { $intStartTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intStartTime); $intEndTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intEndTime); } } } $strDate = \Date::parse($objPage->dateFormat, $intStartTime); if ($span > 0) { $strDate = \Date::parse($objPage->dateFormat, $intStartTime) . ' – ' . \Date::parse($objPage->dateFormat, $intEndTime); } $strTime = ''; if ($objEvent->addTime) { if ($span > 0) { $strDate = \Date::parse($objPage->datimFormat, $intStartTime) . ' – ' . \Date::parse($objPage->datimFormat, $intEndTime); } elseif ($intStartTime == $intEndTime) { $strTime = \Date::parse($objPage->timeFormat, $intStartTime); } else { $strTime = \Date::parse($objPage->timeFormat, $intStartTime) . ' – ' . \Date::parse($objPage->timeFormat, $intEndTime); } } $until = ''; $recurring = ''; // Recurring event if ($objEvent->recurring) { $arrRange = \StringUtil::deserialize($objEvent->repeatEach); if (is_array($arrRange) && isset($arrRange['unit']) && isset($arrRange['value'])) { $strKey = 'cal_' . $arrRange['unit']; $recurring = sprintf($GLOBALS['TL_LANG']['MSC'][$strKey], $arrRange['value']); if ($objEvent->recurrences > 0) { $until = sprintf($GLOBALS['TL_LANG']['MSC']['cal_until'], \Date::parse($objPage->dateFormat, $objEvent->repeatEnd)); } } } /** @var FrontendTemplate|object $objTemplate */ $objTemplate = new \FrontendTemplate($this->cal_template); $objTemplate->setData($objEvent->row()); $objTemplate->date = $strDate; $objTemplate->time = $strTime; $objTemplate->datetime = $objEvent->addTime ? date('Y-m-d\\TH:i:sP', $intStartTime) : date('Y-m-d', $intStartTime); $objTemplate->begin = $intStartTime; $objTemplate->end = $intEndTime; $objTemplate->class = $objEvent->cssClass != '' ? ' ' . $objEvent->cssClass : ''; $objTemplate->recurring = $recurring; $objTemplate->until = $until; $objTemplate->locationLabel = $GLOBALS['TL_LANG']['MSC']['location']; $objTemplate->details = ''; $objTemplate->hasDetails = false; $objTemplate->hasTeaser = false; // Clean the RTE output if ($objEvent->teaser != '') { $objTemplate->hasTeaser = true; $objTemplate->teaser = \StringUtil::toHtml5($objEvent->teaser); $objTemplate->teaser = \StringUtil::encodeEmail($objTemplate->teaser); } // Display the "read more" button for external/article links if ($objEvent->source != 'default') { $objTemplate->details = true; $objTemplate->hasDetails = true; } else { $id = $objEvent->id; $objTemplate->details = function () use($id) { $strDetails = ''; $objElement = \ContentModel::findPublishedByPidAndTable($id, 'tl_calendar_events'); if ($objElement !== null) { while ($objElement->next()) { $strDetails .= $this->getContentElement($objElement->current()); } } return $strDetails; }; $objTemplate->hasDetails = function () use($id) { return \ContentModel::countPublishedByPidAndTable($id, 'tl_calendar_events') > 0; }; } $objTemplate->addImage = false; // Add an image if ($objEvent->addImage && $objEvent->singleSRC != '') { $objModel = \FilesModel::findByUuid($objEvent->singleSRC); if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) { // Do not override the field now that we have a model registry (see #6303) $arrEvent = $objEvent->row(); // Override the default image size if ($this->imgSize != '') { $size = \StringUtil::deserialize($this->imgSize); if ($size[0] > 0 || $size[1] > 0 || is_numeric($size[2])) { $arrEvent['size'] = $this->imgSize; } } $arrEvent['singleSRC'] = $objModel->path; $this->addImageToTemplate($objTemplate, $arrEvent); } } $objTemplate->enclosure = array(); // Add enclosures if ($objEvent->addEnclosure) { $this->addEnclosuresToTemplate($objTemplate, $objEvent->row()); } $this->Template->event = $objTemplate->parse(); $bundles = \System::getContainer()->getParameter('kernel.bundles'); // HOOK: comments extension required if ($objEvent->noComments || !isset($bundles['ContaoCommentsBundle'])) { $this->Template->allowComments = false; return; } /** @var CalendarModel $objCalendar */ $objCalendar = $objEvent->getRelated('pid'); $this->Template->allowComments = $objCalendar->allowComments; // Comments are not allowed if (!$objCalendar->allowComments) { return; } // Adjust the comments headline level $intHl = min(intval(str_replace('h', '', $this->hl)), 5); $this->Template->hlc = 'h' . ($intHl + 1); $this->import('Comments'); $arrNotifies = array(); // Notify the system administrator if ($objCalendar->notify != 'notify_author') { $arrNotifies[] = $GLOBALS['TL_ADMIN_EMAIL']; } // Notify the author if ($objCalendar->notify != 'notify_admin') { /** @var UserModel $objAuthor */ if (($objAuthor = $objEvent->getRelated('author')) instanceof UserModel && $objAuthor->email != '') { $arrNotifies[] = $objAuthor->email; } } $objConfig = new \stdClass(); $objConfig->perPage = $objCalendar->perPage; $objConfig->order = $objCalendar->sortOrder; $objConfig->template = $this->com_template; $objConfig->requireLogin = $objCalendar->requireLogin; $objConfig->disableCaptcha = $objCalendar->disableCaptcha; $objConfig->bbcode = $objCalendar->bbcode; $objConfig->moderate = $objCalendar->moderate; $this->Comments->addCommentsToTemplate($this->Template, $objConfig, 'tl_calendar_events', $objEvent->id, $arrNotifies); }
/** * Translate the file IDs to file paths */ protected function convertValuesToPaths() { if (empty($this->varValue)) { return; } if (!is_array($this->varValue)) { $this->varValue = array($this->varValue); } elseif (empty($this->varValue[0])) { $this->varValue = array(); } if (empty($this->varValue)) { return; } // TinyMCE will pass the path instead of the ID if (strpos($this->varValue[0], \Config::get('uploadPath') . '/') === 0) { return; } // Ignore the numeric IDs when in switch mode (TinyMCE) if (\Input::get('switch')) { return; } // Return if the custom path is not within the upload path (see #8562) if ($this->path != '' && strpos($this->path, \Config::get('uploadPath') . '/') !== 0) { return; } $objFiles = \FilesModel::findMultipleByIds($this->varValue); if ($objFiles !== null) { $this->varValue = array_values($objFiles->fetchEach('path')); } }
/** * Ajax actions that do require a data container object * * @param DataContainer $dc * * @throws NoContentResponseException * @throws ResponseException * @throws BadRequestHttpException */ public function executePostActions(DataContainer $dc) { header('Content-Type: text/html; charset=' . \Config::get('characterSet')); // Bypass any core logic for non-core drivers (see #5957) if (!$dc instanceof DC_File && !$dc instanceof DC_Folder && !$dc instanceof DC_Table) { $this->executePostActionsHook($dc); throw new NoContentResponseException(); } switch ($this->strAction) { // Load nodes of the page structure tree case 'loadStructure': throw new ResponseException($this->convertToResponse($dc->ajaxTreeView($this->strAjaxId, intval(\Input::post('level'))))); // Load nodes of the file manager tree // Load nodes of the file manager tree case 'loadFileManager': throw new ResponseException($this->convertToResponse($dc->ajaxTreeView(\Input::post('folder', true), intval(\Input::post('level'))))); // Load nodes of the page tree // Load nodes of the page tree case 'loadPagetree': $varValue = null; $strField = $dc->field = \Input::post('name'); // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $dc); } } } /** @var PageSelector $strClass */ $strClass = $GLOBALS['BE_FFL']['pageSelector']; /** @var PageSelector $objWidget */ $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->field, $varValue, $strField, $dc->table, $dc)); throw new ResponseException($this->convertToResponse($objWidget->generateAjax($this->strAjaxId, \Input::post('field'), intval(\Input::post('level'))))); // Load nodes of the file tree // Load nodes of the file tree case 'loadFiletree': $varValue = null; $strField = $dc->field = \Input::post('name'); // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $dc); } } } /** @var FileSelector $strClass */ $strClass = $GLOBALS['BE_FFL']['fileSelector']; /** @var FileSelector $objWidget */ $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->field, $varValue, $strField, $dc->table, $dc)); // Load a particular node if (\Input::post('folder', true) != '') { throw new ResponseException($this->convertToResponse($objWidget->generateAjax(\Input::post('folder', true), \Input::post('field'), intval(\Input::post('level'))))); } throw new ResponseException($this->convertToResponse($objWidget->generate())); // Reload the page/file picker // Reload the page/file picker case 'reloadPagetree': case 'reloadFiletree': $intId = \Input::get('id'); $strField = $dc->inputName = \Input::post('name'); // Handle the keys in "edit multiple" mode if (\Input::get('act') == 'editAll') { $intId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', $strField); $strField = preg_replace('/(.*)_[0-9a-zA-Z]+$/', '$1', $strField); } $dc->field = $strField; // The field does not exist if (!isset($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField])) { $this->log('Field "' . $strField . '" does not exist in DCA "' . $dc->table . '"', __METHOD__, TL_ERROR); throw new BadRequestHttpException('Bad request'); } $objRow = null; $varValue = null; // Load the value if (\Input::get('act') != 'overrideAll') { if ($GLOBALS['TL_DCA'][$dc->table]['config']['dataContainer'] == 'File') { $varValue = \Config::get($strField); } elseif ($intId > 0 && $this->Database->tableExists($dc->table)) { $objRow = $this->Database->prepare("SELECT * FROM " . $dc->table . " WHERE id=?")->execute($intId); // The record does not exist if ($objRow->numRows < 1) { $this->log('A record with the ID "' . $intId . '" does not exist in table "' . $dc->table . '"', __METHOD__, TL_ERROR); throw new BadRequestHttpException('Bad request'); } $varValue = $objRow->{$strField}; $dc->activeRecord = $objRow; } } // Call the load_callback if (is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'])) { foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField]['load_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $varValue = $this->{$callback[0]}->{$callback[1]}($varValue, $dc); } elseif (is_callable($callback)) { $varValue = $callback($varValue, $dc); } } } // Set the new value $varValue = \Input::post('value', true); $strKey = $this->strAction == 'reloadPagetree' ? 'pageTree' : 'fileTree'; // Convert the selected values if ($varValue != '') { $varValue = \StringUtil::trimsplit("\t", $varValue); // Automatically add resources to the DBAFS if ($strKey == 'fileTree') { foreach ($varValue as $k => $v) { if (\Dbafs::shouldBeSynchronized($v)) { $objFile = \FilesModel::findByPath($v); if ($objFile === null) { $objFile = \Dbafs::addResource($v); } $varValue[$k] = $objFile->uuid; } } } $varValue = serialize($varValue); } /** @var FileTree|PageTree $strClass */ $strClass = $GLOBALS['BE_FFL'][$strKey]; /** @var FileTree|PageTree $objWidget */ $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$strField], $dc->inputName, $varValue, $strField, $dc->table, $dc)); throw new ResponseException($this->convertToResponse($objWidget->generate())); // Feature/unfeature an element // Feature/unfeature an element case 'toggleFeatured': if (class_exists($dc->table, false)) { $dca = new $dc->table(); if (method_exists($dca, 'toggleFeatured')) { $dca->toggleFeatured(\Input::post('id'), \Input::post('state') == 1 ? true : false); } } throw new NoContentResponseException(); // Toggle subpalettes // Toggle subpalettes case 'toggleSubpalette': $this->import('BackendUser', 'User'); // Check whether the field is a selector field and allowed for regular users (thanks to Fabian Mihailowitsch) (see #4427) if (!is_array($GLOBALS['TL_DCA'][$dc->table]['palettes']['__selector__']) || !in_array(\Input::post('field'), $GLOBALS['TL_DCA'][$dc->table]['palettes']['__selector__']) || $GLOBALS['TL_DCA'][$dc->table]['fields'][\Input::post('field')]['exclude'] && !$this->User->hasAccess($dc->table . '::' . \Input::post('field'), 'alexf')) { $this->log('Field "' . \Input::post('field') . '" is not an allowed selector field (possible SQL injection attempt)', __METHOD__, TL_ERROR); throw new BadRequestHttpException('Bad request'); } if ($dc instanceof DC_Table) { if (\Input::get('act') == 'editAll') { $this->strAjaxId = preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', \Input::post('id')); $this->Database->prepare("UPDATE " . $dc->table . " SET " . \Input::post('field') . "='" . (intval(\Input::post('state') == 1) ? 1 : '') . "' WHERE id=?")->execute($this->strAjaxId); if (\Input::post('load')) { echo $dc->editAll($this->strAjaxId, \Input::post('id')); } } else { $this->Database->prepare("UPDATE " . $dc->table . " SET " . \Input::post('field') . "='" . (intval(\Input::post('state') == 1) ? 1 : '') . "' WHERE id=?")->execute($dc->id); if (\Input::post('load')) { throw new ResponseException($this->convertToResponse($dc->edit(false, \Input::post('id')))); } } } elseif ($dc instanceof DC_File) { $val = intval(\Input::post('state') == 1) ? true : false; \Config::persist(\Input::post('field'), $val); if (\Input::post('load')) { \Config::set(\Input::post('field'), $val); throw new ResponseException($this->convertToResponse($dc->edit(false, \Input::post('id')))); } } throw new NoContentResponseException(); // DropZone file upload // DropZone file upload case 'fileupload': $dc->move(); throw new NoContentResponseException(); // HOOK: pass unknown actions to callback functions // HOOK: pass unknown actions to callback functions default: $this->executePostActionsHook($dc); throw new NoContentResponseException(); } }
/** * Recursively add a folder to the archive * * @param ZipWriter $objArchive * @param string $strFolder * @param \DOMDocument $xml * @param \DOMNode|\DOMElement $table * @param array $arrOrder * * @throws \Exception If the folder path is insecure */ 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(TL_ROOT . '/' . $strFolder)) { return; } // Recursively add the files and subfolders foreach (scan(TL_ROOT . '/' . $strFolder) as $strFile) { // Skip hidden resources if (strncmp($strFile, '.', 1) === 0) { continue; } if (is_dir(TL_ROOT . '/' . $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); } } }
/** * Show header of the parent table and list all records of the current table * * @return string */ protected function parentView() { /** @var SessionInterface $objSession */ $objSession = \System::getContainer()->get('session'); $blnClipboard = false; $arrClipboard = $objSession->get('CLIPBOARD'); $table = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 6 ? $this->ptable : $this->strTable; $blnHasSorting = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['fields'][0] == 'sorting'; $blnMultiboard = false; // Check clipboard if (!empty($arrClipboard[$table])) { $blnClipboard = true; $arrClipboard = $arrClipboard[$table]; if (is_array($arrClipboard['id'])) { $blnMultiboard = true; } } // Load the fonts to display the paste hint \Config::set('loadGoogleFonts', $blnClipboard); // Load the language file and data container array of the parent table \System::loadLanguageFile($this->ptable); $this->loadDataContainer($this->ptable); $return = ' <div id="tl_buttons">' . (\Input::get('nb') ? ' ' : ($this->ptable ? ' <a href="' . $this->getReferer(true, $this->ptable) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>' : (isset($GLOBALS['TL_DCA'][$this->strTable]['config']['backlink']) ? ' <a href="contao/main.php?' . $GLOBALS['TL_DCA'][$this->strTable]['config']['backlink'] . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>' : ''))) . ' ' . (\Input::get('act') != 'select' && !$blnClipboard && !$GLOBALS['TL_DCA'][$this->strTable]['config']['closed'] && !$GLOBALS['TL_DCA'][$this->strTable]['config']['notCreatable'] ? ' <a href="' . $this->addToUrl($blnHasSorting ? 'act=paste&mode=create' : 'act=create&mode=2&pid=' . $this->intId) . '" class="header_new" title="' . specialchars($GLOBALS['TL_LANG'][$this->strTable]['new'][1]) . '" accesskey="n" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG'][$this->strTable]['new'][0] . '</a> ' : '') . ($blnClipboard ? ' <a href="' . $this->addToUrl('clipboard=1') . '" class="header_clipboard" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['clearClipboard']) . '" accesskey="x">' . $GLOBALS['TL_LANG']['MSC']['clearClipboard'] . '</a> ' : $this->generateGlobalButtons()) . ' </div>' . \Message::generate(true); // Get all details of the parent record $objParent = $this->Database->prepare("SELECT * FROM " . $this->ptable . " WHERE id=?")->limit(1)->execute(CURRENT_ID); if ($objParent->numRows < 1) { return $return; } $return .= (\Input::get('act') == 'select' ? ' <form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_select" class="tl_form' . (\Input::get('act') == 'select' ? ' unselectable' : '') . '" method="post" novalidate> <div class="tl_formbody"> <input type="hidden" name="FORM_SUBMIT" value="tl_select"> <input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">' : '') . ($blnClipboard ? ' <div id="paste_hint"> <p>' . $GLOBALS['TL_LANG']['MSC']['selectNewPosition'] . '</p> </div>' : '') . ' <div class="tl_listing_container parent_view"> <div class="tl_header click2edit toggle_select hover-div">'; // List all records of the child table if (!\Input::get('act') || \Input::get('act') == 'paste' || \Input::get('act') == 'select') { $this->import('BackendUser', 'User'); // Header $imagePasteNew = \Image::getHtml('new.gif', $GLOBALS['TL_LANG'][$this->strTable]['pastenew'][0]); $imagePasteAfter = \Image::getHtml('pasteafter.gif', $GLOBALS['TL_LANG'][$this->strTable]['pasteafter'][0]); $imageEditHeader = \Image::getHtml('header.gif', $GLOBALS['TL_LANG'][$this->strTable]['editheader'][0]); $return .= ' <div class="tl_content_right">' . (\Input::get('act') == 'select' ? ' <label for="tl_select_trigger" class="tl_select_label">' . $GLOBALS['TL_LANG']['MSC']['selectAll'] . '</label> <input type="checkbox" id="tl_select_trigger" onclick="Backend.toggleCheckboxes(this)" class="tl_tree_checkbox">' : ($blnClipboard ? ' <a href="' . $this->addToUrl('act=' . $arrClipboard['mode'] . '&mode=2&pid=' . $objParent->id . (!$blnMultiboard ? '&id=' . $arrClipboard['id'] : '')) . '" title="' . specialchars($GLOBALS['TL_LANG'][$this->strTable]['pasteafter'][0]) . '" onclick="Backend.getScrollOffset()">' . $imagePasteAfter . '</a>' : (!$GLOBALS['TL_DCA'][$this->ptable]['config']['notEditable'] && $this->User->canEditFieldsOf($this->ptable) ? ' <a href="' . preg_replace('/&(amp;)?table=[^& ]*/i', $this->ptable != '' ? '&table=' . $this->ptable : '', $this->addToUrl('act=edit')) . '" class="edit" title="' . specialchars(isset($GLOBALS['TL_LANG'][$this->ptable]['editmeta'][1]) ? $GLOBALS['TL_LANG'][$this->ptable]['editmeta'][1] : $GLOBALS['TL_LANG'][$this->strTable]['editheader'][1]) . '">' . $imageEditHeader . '</a>' : '') . ($blnHasSorting && !$GLOBALS['TL_DCA'][$this->strTable]['config']['closed'] && !$GLOBALS['TL_DCA'][$this->strTable]['config']['notCreatable'] ? ' <a href="' . $this->addToUrl('act=create&mode=2&pid=' . $objParent->id . '&id=' . $this->intId) . '" title="' . specialchars($GLOBALS['TL_LANG'][$this->strTable]['pastenew'][0]) . '">' . $imagePasteNew . '</a>' : ''))) . ' </div>'; // Format header fields $add = array(); $headerFields = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['headerFields']; foreach ($headerFields as $v) { $_v = deserialize($objParent->{$v}); // Translate UUIDs to paths if ($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['inputType'] == 'fileTree') { $objFiles = \FilesModel::findMultipleByUuids((array) $_v); if ($objFiles !== null) { $_v = $objFiles->fetchEach('path'); } } if (is_array($_v)) { $_v = implode(', ', $_v); } elseif ($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['eval']['multiple']) { $_v = $_v != '' ? $GLOBALS['TL_LANG']['MSC']['yes'] : $GLOBALS['TL_LANG']['MSC']['no']; } elseif ($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['eval']['rgxp'] == 'date') { $_v = $_v ? \Date::parse(\Config::get('dateFormat'), $_v) : '-'; } elseif ($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['eval']['rgxp'] == 'time') { $_v = $_v ? \Date::parse(\Config::get('timeFormat'), $_v) : '-'; } elseif ($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['eval']['rgxp'] == 'datim') { $_v = $_v ? \Date::parse(\Config::get('datimFormat'), $_v) : '-'; } elseif ($v == 'tstamp') { if ($GLOBALS['TL_DCA'][$this->strTable]['config']['dynamicPtable']) { $ptable = $GLOBALS['TL_DCA'][$this->strTable]['config']['ptable']; $cond = $ptable == 'tl_article' ? "(ptable=? OR ptable='')" : "ptable=?"; $objMaxTstamp = $this->Database->prepare("SELECT MAX(tstamp) AS tstamp FROM " . $this->strTable . " WHERE pid=? AND {$cond}")->execute($objParent->id, $ptable); } else { $objMaxTstamp = $this->Database->prepare("SELECT MAX(tstamp) AS tstamp FROM " . $this->strTable . " WHERE pid=?")->execute($objParent->id); } if (!$objMaxTstamp->tstamp) { $objMaxTstamp->tstamp = $objParent->tstamp; } $_v = \Date::parse(\Config::get('datimFormat'), max($objParent->tstamp, $objMaxTstamp->tstamp)); } elseif (isset($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['foreignKey'])) { $arrForeignKey = explode('.', $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['foreignKey'], 2); $objLabel = $this->Database->prepare("SELECT " . $arrForeignKey[1] . " AS value FROM " . $arrForeignKey[0] . " WHERE id=?")->limit(1)->execute($_v); if ($objLabel->numRows) { $_v = $objLabel->value; } } elseif (is_array($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['reference'][$_v])) { $_v = $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['reference'][$_v][0]; } elseif (isset($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['reference'][$_v])) { $_v = $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['reference'][$_v]; } elseif ($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['eval']['isAssociative'] || array_is_assoc($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['options'])) { $_v = $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['options'][$_v]; } elseif (is_array($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['options_callback'])) { $strClass = $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['options_callback'][0]; $strMethod = $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['options_callback'][1]; $this->import($strClass); $options_callback = $this->{$strClass}->{$strMethod}($this); $_v = $options_callback[$_v]; } elseif (is_callable($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['options_callback'])) { $options_callback = $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['options_callback']($this); $_v = $options_callback[$_v]; } // Add the sorting field if ($_v != '') { if (isset($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['label'])) { $key = is_array($GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['label']) ? $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['label'][0] : $GLOBALS['TL_DCA'][$this->ptable]['fields'][$v]['label']; } else { $key = isset($GLOBALS['TL_LANG'][$this->ptable][$v][0]) ? $GLOBALS['TL_LANG'][$this->ptable][$v][0] : $v; } $add[$key] = $_v; } } // Trigger the header_callback (see #3417) if (is_array($GLOBALS['TL_DCA'][$table]['list']['sorting']['header_callback'])) { $strClass = $GLOBALS['TL_DCA'][$table]['list']['sorting']['header_callback'][0]; $strMethod = $GLOBALS['TL_DCA'][$table]['list']['sorting']['header_callback'][1]; $this->import($strClass); $add = $this->{$strClass}->{$strMethod}($add, $this); } elseif (is_callable($GLOBALS['TL_DCA'][$table]['list']['sorting']['header_callback'])) { $add = $GLOBALS['TL_DCA'][$table]['list']['sorting']['header_callback']($add, $this); } // Output the header data $return .= ' <table class="tl_header_table">'; foreach ($add as $k => $v) { if (is_array($v)) { $v = $v[0]; } $return .= ' <tr> <td><span class="tl_label">' . $k . ':</span> </td> <td>' . $v . '</td> </tr>'; } $return .= ' </table> </div>'; $orderBy = array(); $firstOrderBy = array(); // Add all records of the current table $query = "SELECT * FROM " . $this->strTable; if (is_array($this->orderBy) && strlen($this->orderBy[0])) { $orderBy = $this->orderBy; $firstOrderBy = preg_replace('/\\s+.*$/', '', $orderBy[0]); // Order by the foreign key if (isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$firstOrderBy]['foreignKey'])) { $key = explode('.', $GLOBALS['TL_DCA'][$this->strTable]['fields'][$firstOrderBy]['foreignKey'], 2); $query = "SELECT *, (SELECT " . $key[1] . " FROM " . $key[0] . " WHERE " . $this->strTable . "." . $firstOrderBy . "=" . $key[0] . ".id) AS foreignKey FROM " . $this->strTable; $orderBy[0] = 'foreignKey'; } } elseif (is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['fields'])) { $orderBy = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['fields']; $firstOrderBy = preg_replace('/\\s+.*$/', '', $orderBy[0]); } $arrProcedure = $this->procedure; $arrValues = $this->values; // Support empty ptable fields if ($GLOBALS['TL_DCA'][$this->strTable]['config']['dynamicPtable']) { $arrProcedure[] = $this->ptable == 'tl_article' ? "(ptable=? OR ptable='')" : "ptable=?"; $arrValues[] = $this->ptable; } // WHERE if (!empty($arrProcedure)) { $query .= " WHERE " . implode(' AND ', $arrProcedure); } if (!empty($this->root) && is_array($this->root)) { $query .= (!empty($arrProcedure) ? " AND " : " WHERE ") . "id IN(" . implode(',', array_map('intval', $this->root)) . ")"; } // ORDER BY if (!empty($orderBy) && is_array($orderBy)) { $query .= " ORDER BY " . implode(', ', $orderBy); } $objOrderByStmt = $this->Database->prepare($query); // LIMIT if (strlen($this->limit)) { $arrLimit = explode(',', $this->limit); $objOrderByStmt->limit($arrLimit[1], $arrLimit[0]); } $objOrderBy = $objOrderByStmt->execute($arrValues); if ($objOrderBy->numRows < 1) { return $return . ' <p class="tl_empty_parent_view">' . $GLOBALS['TL_LANG']['MSC']['noResult'] . '</p> </div>'; } // Call the child_record_callback if (is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_callback']) || is_callable($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_callback'])) { $strGroup = ''; $blnIndent = false; $intWrapLevel = 0; $row = $objOrderBy->fetchAllAssoc(); // Make items sortable if ($blnHasSorting) { $return .= ' <ul id="ul_' . CURRENT_ID . '">'; } for ($i = 0, $c = count($row); $i < $c; $i++) { $this->current[] = $row[$i]['id']; $imagePasteAfter = \Image::getHtml('pasteafter.gif', sprintf($GLOBALS['TL_LANG'][$this->strTable]['pasteafter'][1], $row[$i]['id'])); $imagePasteNew = \Image::getHtml('new.gif', sprintf($GLOBALS['TL_LANG'][$this->strTable]['pastenew'][1], $row[$i]['id'])); // Decrypt encrypted value foreach ($row[$i] as $k => $v) { if ($GLOBALS['TL_DCA'][$table]['fields'][$k]['eval']['encrypt']) { $row[$i][$k] = \Encryption::decrypt(deserialize($v)); } } // Make items sortable if ($blnHasSorting) { $return .= ' <li id="li_' . $row[$i]['id'] . '">'; } // Add the group header if (!$GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['disableGrouping'] && $firstOrderBy != 'sorting') { $sortingMode = count($orderBy) == 1 && $firstOrderBy == $orderBy[0] && $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['flag'] != '' && $GLOBALS['TL_DCA'][$this->strTable]['fields'][$firstOrderBy]['flag'] == '' ? $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['flag'] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$firstOrderBy]['flag']; $remoteNew = $this->formatCurrentValue($firstOrderBy, $row[$i][$firstOrderBy], $sortingMode); $group = $this->formatGroupHeader($firstOrderBy, $remoteNew, $sortingMode, $row); if ($group != $strGroup) { $return .= "\n\n" . '<div class="tl_content_header">' . $group . '</div>'; $strGroup = $group; } } $blnWrapperStart = in_array($row[$i]['type'], $GLOBALS['TL_WRAPPERS']['start']); $blnWrapperSeparator = in_array($row[$i]['type'], $GLOBALS['TL_WRAPPERS']['separator']); $blnWrapperStop = in_array($row[$i]['type'], $GLOBALS['TL_WRAPPERS']['stop']); // Closing wrappers if ($blnWrapperStop) { if (--$intWrapLevel < 1) { $blnIndent = false; } } $return .= ' <div class="tl_content' . ($blnWrapperStart ? ' wrapper_start' : '') . ($blnWrapperSeparator ? ' wrapper_separator' : '') . ($blnWrapperStop ? ' wrapper_stop' : '') . ($blnIndent ? ' indent indent_' . $intWrapLevel : '') . ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_class'] != '' ? ' ' . $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_class'] : '') . ($i % 2 == 0 ? ' even' : ' odd') . ' click2edit toggle_select hover-div"> <div class="tl_content_right">'; // Opening wrappers if ($blnWrapperStart) { if (++$intWrapLevel > 0) { $blnIndent = true; } } // Edit multiple if (\Input::get('act') == 'select') { $return .= '<input type="checkbox" name="IDS[]" id="ids_' . $row[$i]['id'] . '" class="tl_tree_checkbox" value="' . $row[$i]['id'] . '">'; } else { $return .= $this->generateButtons($row[$i], $this->strTable, $this->root, false, null, $row[$i - 1]['id'], $row[$i + 1]['id']); // Sortable table if ($blnHasSorting) { // Create new button if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['closed'] && !$GLOBALS['TL_DCA'][$this->strTable]['config']['notCreatable']) { $return .= ' <a href="' . $this->addToUrl('act=create&mode=1&pid=' . $row[$i]['id'] . '&id=' . $objParent->id) . '" title="' . specialchars(sprintf($GLOBALS['TL_LANG'][$this->strTable]['pastenew'][1], $row[$i]['id'])) . '">' . $imagePasteNew . '</a>'; } // Prevent circular references if ($blnClipboard && $arrClipboard['mode'] == 'cut' && $row[$i]['id'] == $arrClipboard['id'] || $blnMultiboard && $arrClipboard['mode'] == 'cutAll' && in_array($row[$i]['id'], $arrClipboard['id'])) { $return .= ' ' . \Image::getHtml('pasteafter_.gif'); } elseif ($blnMultiboard) { $return .= ' <a href="' . $this->addToUrl('act=' . $arrClipboard['mode'] . '&mode=1&pid=' . $row[$i]['id']) . '" title="' . specialchars(sprintf($GLOBALS['TL_LANG'][$this->strTable]['pasteafter'][1], $row[$i]['id'])) . '" onclick="Backend.getScrollOffset()">' . $imagePasteAfter . '</a>'; } elseif ($blnClipboard) { $return .= ' <a href="' . $this->addToUrl('act=' . $arrClipboard['mode'] . '&mode=1&pid=' . $row[$i]['id'] . '&id=' . $arrClipboard['id']) . '" title="' . specialchars(sprintf($GLOBALS['TL_LANG'][$this->strTable]['pasteafter'][1], $row[$i]['id'])) . '" onclick="Backend.getScrollOffset()">' . $imagePasteAfter . '</a>'; } // Drag handle if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notSortable']) { $return .= ' ' . \Image::getHtml('drag.gif', '', 'class="drag-handle" title="' . sprintf($GLOBALS['TL_LANG'][$this->strTable]['cut'][1], $row[$i]['id']) . '"'); } } } if (is_array($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_callback'])) { $strClass = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_callback'][0]; $strMethod = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_callback'][1]; $this->import($strClass); $return .= '</div>' . $this->{$strClass}->{$strMethod}($row[$i]) . '</div>'; } elseif (is_callable($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_callback'])) { $return .= '</div>' . $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['child_record_callback']($row[$i]) . '</div>'; } // Make items sortable if ($blnHasSorting) { $return .= ' </li>'; } } } } // Make items sortable if ($blnHasSorting && !$GLOBALS['TL_DCA'][$this->strTable]['config']['notSortable'] && \Input::get('act') != 'select') { $return .= ' </ul> <script> Backend.makeParentViewSortable("ul_' . CURRENT_ID . '"); </script>'; } $return .= ' </div>'; // Close form if (\Input::get('act') == 'select') { // Submit buttons $arrButtons = array(); if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notDeletable']) { $arrButtons['delete'] = '<button type="submit" name="delete" id="delete" class="tl_submit" accesskey="d" onclick="return confirm(\'' . $GLOBALS['TL_LANG']['MSC']['delAllConfirm'] . '\')">' . $GLOBALS['TL_LANG']['MSC']['deleteSelected'] . '</button>'; } if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notSortable']) { $arrButtons['cut'] = '<button type="submit" name="cut" id="cut" class="tl_submit" accesskey="x">' . $GLOBALS['TL_LANG']['MSC']['moveSelected'] . '</button>'; } if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notCopyable']) { $arrButtons['copy'] = '<button type="submit" name="copy" id="copy" class="tl_submit" accesskey="c">' . $GLOBALS['TL_LANG']['MSC']['copySelected'] . '</button>'; } if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['notEditable']) { $arrButtons['override'] = '<button type="submit" name="override" id="override" class="tl_submit" accesskey="v">' . $GLOBALS['TL_LANG']['MSC']['overrideSelected'] . '</button>'; $arrButtons['edit'] = '<button type="submit" name="edit" id="edit" class="tl_submit" accesskey="s">' . $GLOBALS['TL_LANG']['MSC']['editSelected'] . '</button>'; } // Call the buttons_callback (see #4691) if (is_array($GLOBALS['TL_DCA'][$this->strTable]['select']['buttons_callback'])) { foreach ($GLOBALS['TL_DCA'][$this->strTable]['select']['buttons_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $arrButtons = $this->{$callback[0]}->{$callback[1]}($arrButtons, $this); } elseif (is_callable($callback)) { $arrButtons = $callback($arrButtons, $this); } } } $return .= ' <div class="tl_formbody_submit" style="text-align:right"> <div class="tl_submit_container"> ' . implode(' ', $arrButtons) . ' </div> </div> </div> </form>'; } return $return; }
/** * Render a news. * * @param GetNewsEvent $event The event. * * @param string $eventName The event name. * * @param EventDispatcherInterface $eventDispatcher The event dispatcher. * * @return void * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function handleNews(GetNewsEvent $event, $eventName, EventDispatcherInterface $eventDispatcher) { if ($event->getNewsHtml()) { return; } $newsArchiveCollection = NewsArchiveModel::findAll(); $newsArchiveIds = $newsArchiveCollection ? $newsArchiveCollection->fetchEach('id') : array(); $newsModel = NewsModel::findPublishedByParentAndIdOrAlias($event->getNewsId(), $newsArchiveIds); if (!$newsModel) { return; } $newsModel = $newsModel->current(); $newsArchiveModel = $newsModel->getRelated('pid'); $objPage = PageModel::findWithDetails($newsArchiveModel->jumpTo); $objTemplate = new FrontendTemplate($event->getTemplate()); $objTemplate->setData($newsModel->row()); $objTemplate->class = $newsModel->cssClass != '' ? ' ' . $newsModel->cssClass : ''; $objTemplate->newsHeadline = $newsModel->headline; $objTemplate->subHeadline = $newsModel->subheadline; $objTemplate->hasSubHeadline = $newsModel->subheadline ? true : false; $objTemplate->linkHeadline = $this->generateLink($eventDispatcher, $newsModel->headline, $newsModel); $objTemplate->more = $this->generateLink($eventDispatcher, $GLOBALS['TL_LANG']['MSC']['more'], $newsModel, false, true); $objTemplate->link = $this->generateNewsUrl($eventDispatcher, $newsModel); $objTemplate->archive = $newsModel->getRelated('pid'); $objTemplate->count = 0; $objTemplate->text = ''; // Clean the RTE output. if ($newsModel->teaser != '') { if ($objPage->outputFormat == 'xhtml') { $objTemplate->teaser = StringHelper::toXhtml($newsModel->teaser); } else { $objTemplate->teaser = StringHelper::toHtml5($newsModel->teaser); } $objTemplate->teaser = StringHelper::encodeEmail($objTemplate->teaser); } // Display the "read more" button for external/article links. if ($newsModel->source != 'default') { $objTemplate->text = true; } else { // Compile the news text. $objElement = ContentModel::findPublishedByPidAndTable($newsModel->id, 'tl_news'); if ($objElement !== null) { while ($objElement->next()) { $getContentElementEvent = new GetContentElementEvent($objElement->id); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GET_CONTENT_ELEMENT, $getContentElementEvent); $objTemplate->text .= $getContentElementEvent->getContentElementHtml(); } } } $arrMeta = $this->getMetaFields($newsModel); // Add the meta information. $objTemplate->date = $arrMeta['date']; $objTemplate->hasMetaFields = !empty($arrMeta); $objTemplate->numberOfComments = $arrMeta['ccount']; $objTemplate->commentCount = $arrMeta['comments']; $objTemplate->timestamp = $newsModel->date; $objTemplate->author = $arrMeta['author']; $objTemplate->datetime = date('Y-m-d\\TH:i:sP', $newsModel->date); $objTemplate->addImage = false; // Add an image. if ($newsModel->addImage && $newsModel->singleSRC != '') { $objModel = FilesModel::findByUuid($newsModel->singleSRC); if ($objModel === null) { if (!Validator::isUuid($newsModel->singleSRC)) { $objTemplate->text = '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>'; } } elseif (is_file(TL_ROOT . '/' . $objModel->path)) { // Do not override the field now that we have a model registry (see #6303). $arrArticle = $newsModel->row(); // Override the default image size. // This is always false! if ($this->imgSize != '') { $size = deserialize($this->imgSize); if ($size[0] > 0 || $size[1] > 0) { $arrArticle['size'] = $this->imgSize; } } $arrArticle['singleSRC'] = $objModel->path; $addImageToTemplateEvent = new AddImageToTemplateEvent($arrArticle, $objTemplate); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_IMAGE_TO_TEMPLATE, $addImageToTemplateEvent); } } $objTemplate->enclosure = array(); // Add enclosures. if ($newsModel->addEnclosure) { $addEnclosureToTemplateEvent = new AddEnclosureToTemplateEvent($newsModel->row(), $objTemplate); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_ENCLOSURE_TO_TEMPLATE, $addEnclosureToTemplateEvent); } $news = $objTemplate->parse(); $event->setNewsHtml($news); }
/** * Create a new user and redirect * * @param array $arrData */ protected function createNewUser($arrData) { $arrData['tstamp'] = time(); $arrData['login'] = $this->reg_allowLogin; $arrData['activation'] = md5(uniqid(mt_rand(), true)); $arrData['dateAdded'] = $arrData['tstamp']; // Set default groups if (!array_key_exists('groups', $arrData)) { $arrData['groups'] = $this->reg_groups; } // Disable account $arrData['disable'] = 1; // Send activation e-mail if ($this->reg_activate) { $this->sendActivationMail($arrData); } // Make sure newsletter is an array if (isset($arrData['newsletter']) && !is_array($arrData['newsletter'])) { $arrData['newsletter'] = array($arrData['newsletter']); } // Create the user $objNewUser = new \MemberModel(); $objNewUser->setRow($arrData); $objNewUser->save(); // Assign home directory if ($this->reg_assignDir) { $objHomeDir = \FilesModel::findByUuid($this->reg_homeDir); if ($objHomeDir !== null) { $this->import('Files'); $strUserDir = \StringUtil::standardize($arrData['username']) ?: 'user_' . $objNewUser->id; // Add the user ID if the directory exists while (is_dir(TL_ROOT . '/' . $objHomeDir->path . '/' . $strUserDir)) { $strUserDir .= '_' . $objNewUser->id; } // Create the user folder new \Folder($objHomeDir->path . '/' . $strUserDir); $objUserDir = \FilesModel::findByPath($objHomeDir->path . '/' . $strUserDir); // Save the folder ID $objNewUser->assignDir = 1; $objNewUser->homeDir = $objUserDir->uuid; $objNewUser->save(); } } // HOOK: send insert ID and user data if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser'])) { foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback) { $this->import($callback[0]); $this->{$callback[0]}->{$callback[1]}($objNewUser->id, $arrData, $this); } } // Create the initial version (see #7816) $objVersions = new \Versions('tl_member', $objNewUser->id); $objVersions->setUsername($objNewUser->username); $objVersions->setUserId(0); $objVersions->setEditUrl('contao/main.php?do=member&act=edit&id=%s&rt=1'); $objVersions->initialize(); // Inform admin if no activation link is sent if (!$this->reg_activate) { $this->sendAdminNotification($objNewUser->id, $arrData); } // Check whether there is a jumpTo page if (($objJumpTo = $this->objModel->getRelated('jumpTo')) instanceof PageModel) { $this->jumpToOrReload($objJumpTo->row()); } $this->reload(); }
/** * Generate the module */ protected function compile() { /** @var PageModel $objPage */ global $objPage; $blnClearInput = false; $intYear = \Input::get('year'); $intMonth = \Input::get('month'); $intDay = \Input::get('day'); // Jump to the current period if (!isset($_GET['year']) && !isset($_GET['month']) && !isset($_GET['day'])) { switch ($this->cal_format) { case 'cal_year': $intYear = date('Y'); break; case 'cal_month': $intMonth = date('Ym'); break; case 'cal_day': $intDay = date('Ymd'); break; } $blnClearInput = true; } $blnDynamicFormat = !$this->cal_ignoreDynamic && in_array($this->cal_format, array('cal_day', 'cal_month', 'cal_year')); // Create the date object try { if ($blnDynamicFormat && $intYear) { $this->Date = new \Date($intYear, 'Y'); $this->cal_format = 'cal_year'; $this->headline .= ' ' . date('Y', $this->Date->tstamp); } elseif ($blnDynamicFormat && $intMonth) { $this->Date = new \Date($intMonth, 'Ym'); $this->cal_format = 'cal_month'; $this->headline .= ' ' . \Date::parse('F Y', $this->Date->tstamp); } elseif ($blnDynamicFormat && $intDay) { $this->Date = new \Date($intDay, 'Ymd'); $this->cal_format = 'cal_day'; $this->headline .= ' ' . \Date::parse($objPage->dateFormat, $this->Date->tstamp); } else { $this->Date = new \Date(); } } catch (\OutOfBoundsException $e) { throw new PageNotFoundException('Page not found'); } list($strBegin, $strEnd, $strEmpty) = $this->getDatesFromFormat($this->Date, $this->cal_format); // Get all events $arrAllEvents = $this->getAllEvents($this->cal_calendar, $strBegin, $strEnd); $sort = $this->cal_order == 'descending' ? 'krsort' : 'ksort'; // Sort the days $sort($arrAllEvents); // Sort the events foreach (array_keys($arrAllEvents) as $key) { $sort($arrAllEvents[$key]); } $arrEvents = array(); $dateBegin = date('Ymd', $strBegin); $dateEnd = date('Ymd', $strEnd); // Remove events outside the scope foreach ($arrAllEvents as $key => $days) { if ($key < $dateBegin || $key > $dateEnd) { continue; } foreach ($days as $day => $events) { foreach ($events as $event) { $event['firstDay'] = $GLOBALS['TL_LANG']['DAYS'][date('w', $day)]; $event['firstDate'] = \Date::parse($objPage->dateFormat, $day); $arrEvents[] = $event; } } } unset($arrAllEvents); $total = count($arrEvents); $limit = $total; $offset = 0; // Overall limit if ($this->cal_limit > 0) { $total = min($this->cal_limit, $total); $limit = $total; } // Pagination if ($this->perPage > 0) { $id = 'page_e' . $this->id; $page = \Input::get($id) !== null ? \Input::get($id) : 1; // Do not index or cache the page if the page number is outside the range if ($page < 1 || $page > max(ceil($total / $this->perPage), 1)) { throw new PageNotFoundException('Page not found'); } $offset = ($page - 1) * $this->perPage; $limit = min($this->perPage + $offset, $total); $objPagination = new \Pagination($total, $this->perPage, \Config::get('maxPaginationLinks'), $id); $this->Template->pagination = $objPagination->generate("\n "); } $strMonth = ''; $strDate = ''; $strEvents = ''; $dayCount = 0; $eventCount = 0; $headerCount = 0; $imgSize = false; // Override the default image size if ($this->imgSize != '') { $size = deserialize($this->imgSize); if ($size[0] > 0 || $size[1] > 0 || is_numeric($size[2])) { $imgSize = $this->imgSize; } } // Parse events for ($i = $offset; $i < $limit; $i++) { $event = $arrEvents[$i]; $blnIsLastEvent = false; // Last event on the current day if ($i + 1 == $limit || !isset($arrEvents[$i + 1]['firstDate']) || $event['firstDate'] != $arrEvents[$i + 1]['firstDate']) { $blnIsLastEvent = true; } /** @var FrontendTemplate|object $objTemplate */ $objTemplate = new \FrontendTemplate($this->cal_template); $objTemplate->setData($event); // Month header if ($strMonth != $event['month']) { $objTemplate->newMonth = true; $strMonth = $event['month']; } // Day header if ($strDate != $event['firstDate']) { $headerCount = 0; $objTemplate->header = true; $objTemplate->classHeader = ($dayCount % 2 == 0 ? ' even' : ' odd') . ($dayCount == 0 ? ' first' : '') . ($event['firstDate'] == $arrEvents[$limit - 1]['firstDate'] ? ' last' : ''); $strDate = $event['firstDate']; ++$dayCount; } // Show the teaser text of redirect events (see #6315) if (is_bool($event['details'])) { $objTemplate->hasDetails = false; } // Add the template variables $objTemplate->classList = $event['class'] . ($headerCount % 2 == 0 ? ' even' : ' odd') . ($headerCount == 0 ? ' first' : '') . ($blnIsLastEvent ? ' last' : '') . ' cal_' . $event['parent']; $objTemplate->classUpcoming = $event['class'] . ($eventCount % 2 == 0 ? ' even' : ' odd') . ($eventCount == 0 ? ' first' : '') . ($offset + $eventCount + 1 >= $limit ? ' last' : '') . ' cal_' . $event['parent']; $objTemplate->readMore = specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['readMore'], $event['title'])); $objTemplate->more = $GLOBALS['TL_LANG']['MSC']['more']; $objTemplate->locationLabel = $GLOBALS['TL_LANG']['MSC']['location']; // Short view if ($this->cal_noSpan) { $objTemplate->day = $event['day']; $objTemplate->date = $event['date']; } else { $objTemplate->day = $event['firstDay']; $objTemplate->date = $event['firstDate']; } $objTemplate->addImage = false; // Add an image if ($event['addImage'] && $event['singleSRC'] != '') { $objModel = \FilesModel::findByUuid($event['singleSRC']); if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) { if ($imgSize) { $event['size'] = $imgSize; } $event['singleSRC'] = $objModel->path; $this->addImageToTemplate($objTemplate, $event); } } $objTemplate->enclosure = array(); // Add enclosure if ($event['addEnclosure']) { $this->addEnclosuresToTemplate($objTemplate, $event); } $strEvents .= $objTemplate->parse(); ++$eventCount; ++$headerCount; } // No events found if ($strEvents == '') { $strEvents = "\n" . '<div class="empty">' . $strEmpty . '</div>' . "\n"; } // See #3672 $this->Template->headline = $this->headline; $this->Template->events = $strEvents; // Clear the $_GET array (see #2445) if ($blnClearInput) { \Input::setGet('year', null); \Input::setGet('month', null); \Input::setGet('day', null); } }
/** * Load the source editor * * @return string * * @throws InternalServerErrorException */ public function source() { $this->isValid($this->intId); if (is_dir(TL_ROOT . '/' . $this->intId)) { throw new InternalServerErrorException('Folder "' . $this->intId . '" cannot be edited.'); } elseif (!file_exists(TL_ROOT . '/' . $this->intId)) { throw new InternalServerErrorException('File "' . $this->intId . '" does not exist.'); } $this->import('BackendUser', 'User'); // Check user permission if (!$this->User->hasAccess('f5', 'fop')) { throw new AccessDeniedException('Not enough permissions to edit the file source of file "' . $this->intId . '".'); } $objFile = new \File($this->intId); // Check whether file type is editable if (!in_array($objFile->extension, trimsplit(',', \Config::get('editableFiles')))) { throw new AccessDeniedException('File type "' . $objFile->extension . '" (' . $this->intId . ') is not allowed to be edited.'); } $objMeta = null; $objVersions = null; // Add the versioning routines if ($this->blnIsDbAssisted && \Dbafs::shouldBeSynchronized($this->intId)) { $objMeta = \FilesModel::findByPath($objFile->value); if ($objMeta === null) { $objMeta = \Dbafs::addResource($objFile->value); } $objVersions = new \Versions($this->strTable, $objMeta->id); if (!$GLOBALS['TL_DCA'][$this->strTable]['config']['hideVersionMenu']) { // Compare versions if (\Input::get('versions')) { $objVersions->compare(); } // Restore a version if (\Input::post('FORM_SUBMIT') == 'tl_version' && \Input::post('version') != '') { $objVersions->restore(\Input::post('version')); // Purge the script cache (see #7005) if ($objFile->extension == 'css' || $objFile->extension == 'scss' || $objFile->extension == 'less') { $this->import('Automator'); $this->Automator->purgeScriptCache(); } $this->reload(); } } $objVersions->initialize(); } $strContent = $objFile->getContent(); if ($objFile->extension == 'svgz') { $strContent = gzdecode($strContent); } // Process the request if (\Input::post('FORM_SUBMIT') == 'tl_files') { // Restore the basic entities (see #7170) $strSource = \StringUtil::restoreBasicEntities(\Input::postRaw('source')); // Save the file if (md5($strContent) != md5($strSource)) { if ($objFile->extension == 'svgz') { $strSource = gzencode($strSource); } // Write the file $objFile->write($strSource); $objFile->close(); // Update the database if ($this->blnIsDbAssisted && $objMeta !== null) { /** @var FilesModel $objMeta */ $objMeta->hash = $objFile->hash; $objMeta->save(); $objVersions->create(); } // Purge the script cache (see #7005) if ($objFile->extension == 'css' || $objFile->extension == 'scss' || $objFile->extension == 'less') { $this->import('Automator'); $this->Automator->purgeScriptCache(); } } if (isset($_POST['saveNclose'])) { \System::setCookie('BE_PAGE_OFFSET', 0, 0); $this->redirect($this->getReferer()); } $this->reload(); } $codeEditor = ''; // Prepare the code editor if (\Config::get('useCE')) { /** @var BackendTemplate|object $objTemplate */ $objTemplate = new \BackendTemplate('be_ace'); $objTemplate->selector = 'ctrl_source'; $objTemplate->type = $objFile->extension; $codeEditor = $objTemplate->parse(); } // Versions overview if ($GLOBALS['TL_DCA'][$this->strTable]['config']['enableVersioning'] && !$GLOBALS['TL_DCA'][$this->strTable]['config']['hideVersionMenu'] && $this->blnIsDbAssisted && $objVersions !== null) { $version = $objVersions->renderDropdown(); } else { $version = ''; } // Submit buttons $arrButtons = array(); $arrButtons['save'] = '<button type="submit" name="save" id="save" class="tl_submit" accesskey="s">' . $GLOBALS['TL_LANG']['MSC']['save'] . '</button>'; $arrButtons['saveNclose'] = '<button type="submit" name="saveNclose" id="saveNclose" class="tl_submit" accesskey="c">' . $GLOBALS['TL_LANG']['MSC']['saveNclose'] . '</button>'; // Call the buttons_callback (see #4691) if (is_array($GLOBALS['TL_DCA'][$this->strTable]['edit']['buttons_callback'])) { foreach ($GLOBALS['TL_DCA'][$this->strTable]['edit']['buttons_callback'] as $callback) { if (is_array($callback)) { $this->import($callback[0]); $arrButtons = $this->{$callback[0]}->{$callback[1]}($arrButtons, $this); } elseif (is_callable($callback)) { $arrButtons = $callback($arrButtons, $this); } } } // Add the form return $version . ' <div id="tl_buttons"> <a href="' . $this->getReferer(true) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b" onclick="Backend.getScrollOffset()">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a> </div> ' . \Message::generate() . ' <form action="' . ampersand(\Environment::get('request'), true) . '" id="tl_files" class="tl_form" method="post"> <div class="tl_formbody_edit"> <input type="hidden" name="FORM_SUBMIT" value="tl_files"> <input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '"> <div class="tl_tbox"> <h3><label for="ctrl_source">' . $GLOBALS['TL_LANG']['tl_files']['editor'][0] . '</label></h3> <textarea name="source" id="ctrl_source" class="tl_textarea monospace" rows="12" cols="80" style="height:400px" onfocus="Backend.getScrollOffset()">' . "\n" . htmlspecialchars($strContent) . '</textarea>' . (\Config::get('showHelp') && strlen($GLOBALS['TL_LANG']['tl_files']['editor'][1]) ? ' <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_files']['editor'][1] . '</p>' : '') . ' </div> </div> <div class="tl_formbody_submit"> <div class="tl_submit_container"> ' . implode(' ', $arrButtons) . ' </div> </div> </form>' . "\n\n" . $codeEditor; }
/** * Set the upload path for file uploads * * @param sting $uploadPath The UUID Value from an DBAFS Folder */ public function setUploadPath($uploadPath) { $objFile = FilesModel::findByUuid($uploadPath); $this->uploadPath = $objFile->path; }
/** * Renturn a form to choose an existing style sheet and import it * * @param DataContainer $dc * * @return string */ public function send(DataContainer $dc) { $objNewsletter = $this->Database->prepare("SELECT n.*, c.template AS channelTemplate, c.sender AS channelSender, c.senderName as channelSenderName FROM tl_newsletter n LEFT JOIN tl_newsletter_channel c ON n.pid=c.id WHERE n.id=?")->limit(1)->execute($dc->id); // Return if there is no newsletter if ($objNewsletter->numRows < 1) { return ''; } // Set the template if ($objNewsletter->template == '') { $objNewsletter->template = $objNewsletter->channelTemplate; } // Set the sender address if ($objNewsletter->sender == '') { $objNewsletter->sender = $objNewsletter->channelSender; } // Set the sender name if ($objNewsletter->senderName == '') { $objNewsletter->senderName = $objNewsletter->channelSenderName; } // No sender address given if ($objNewsletter->sender == '') { throw new InternalServerErrorException('No sender address given. Please check the newsletter channel settings.'); } $arrAttachments = array(); // Add attachments if ($objNewsletter->addFile) { $files = deserialize($objNewsletter->files); if (!empty($files) && is_array($files)) { $objFiles = \FilesModel::findMultipleByUuids($files); if ($objFiles !== null) { while ($objFiles->next()) { if (is_file(TL_ROOT . '/' . $objFiles->path)) { $arrAttachments[] = $objFiles->path; } } } } } // Replace insert tags $html = $this->replaceInsertTags($objNewsletter->content, false); $text = $this->replaceInsertTags($objNewsletter->text, false); // Convert relative URLs if ($objNewsletter->externalImages) { $html = $this->convertRelativeUrls($html); } /** @var SessionInterface $objSession */ $objSession = \System::getContainer()->get('session'); // Send newsletter if (\Input::get('token') != '' && \Input::get('token') == $objSession->get('tl_newsletter_send')) { $referer = preg_replace('/&(amp;)?(start|mpc|token|recipient|preview)=[^&]*/', '', \Environment::get('request')); // Preview if (isset($_GET['preview'])) { // Check the e-mail address if (!\Validator::isEmail(\Input::get('recipient', true))) { $_SESSION['TL_PREVIEW_MAIL_ERROR'] = true; $this->redirect($referer); } $arrRecipient['email'] = urldecode(\Input::get('recipient', true)); // Send $objEmail = $this->generateEmailObject($objNewsletter, $arrAttachments); $this->sendNewsletter($objEmail, $objNewsletter, $arrRecipient, $text, $html); // Redirect \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_newsletter']['confirm'], 1)); $this->redirect($referer); } // Get the total number of recipients $objTotal = $this->Database->prepare("SELECT COUNT(DISTINCT email) AS count FROM tl_newsletter_recipients WHERE pid=? AND active=1")->execute($objNewsletter->pid); // Return if there are no recipients if ($objTotal->count < 1) { $objSession->set('tl_newsletter_send', null); \Message::addError($GLOBALS['TL_LANG']['tl_newsletter']['error']); $this->redirect($referer); } $intTotal = $objTotal->count; // Get page and timeout $intTimeout = \Input::get('timeout') > 0 ? \Input::get('timeout') : 1; $intStart = \Input::get('start') ? \Input::get('start') : 0; $intPages = \Input::get('mpc') ? \Input::get('mpc') : 10; // Get recipients $objRecipients = $this->Database->prepare("SELECT *, r.email FROM tl_newsletter_recipients r LEFT JOIN tl_member m ON(r.email=m.email) WHERE r.pid=? AND r.active=1 GROUP BY r.email ORDER BY r.email")->limit($intPages, $intStart)->execute($objNewsletter->pid); echo '<div style="font-family:Verdana,sans-serif;font-size:11px;line-height:16px;margin-bottom:12px">'; // Send newsletter if ($objRecipients->numRows > 0) { // Update status if ($intStart == 0) { $this->Database->prepare("UPDATE tl_newsletter SET sent=1, date=? WHERE id=?")->execute(time(), $objNewsletter->id); $_SESSION['REJECTED_RECIPIENTS'] = array(); } while ($objRecipients->next()) { $objEmail = $this->generateEmailObject($objNewsletter, $arrAttachments); $this->sendNewsletter($objEmail, $objNewsletter, $objRecipients->row(), $text, $html); echo 'Sending newsletter to <strong>' . $objRecipients->email . '</strong><br>'; } } echo '<div style="margin-top:12px">'; // Redirect back home if ($objRecipients->numRows < 1 || $intStart + $intPages >= $intTotal) { $objSession->set('tl_newsletter_send', null); // Deactivate rejected addresses if (!empty($_SESSION['REJECTED_RECIPIENTS'])) { $intRejected = count($_SESSION['REJECTED_RECIPIENTS']); \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_newsletter']['rejected'], $intRejected)); $intTotal -= $intRejected; foreach ($_SESSION['REJECTED_RECIPIENTS'] as $strRecipient) { $this->Database->prepare("UPDATE tl_newsletter_recipients SET active='' WHERE email=?")->execute($strRecipient); $this->log('Recipient address "' . $strRecipient . '" was rejected and has been deactivated', __METHOD__, TL_ERROR); } } \Message::addConfirmation(sprintf($GLOBALS['TL_LANG']['tl_newsletter']['confirm'], $intTotal)); echo '<script>setTimeout(\'window.location="' . \Environment::get('base') . $referer . '"\',1000)</script>'; echo '<a href="' . \Environment::get('base') . $referer . '">Please click here to proceed if you are not using JavaScript</a>'; } else { $url = preg_replace('/&(amp;)?(start|mpc|recipient)=[^&]*/', '', \Environment::get('request')) . '&start=' . ($intStart + $intPages) . '&mpc=' . $intPages; echo '<script>setTimeout(\'window.location="' . \Environment::get('base') . $url . '"\',' . $intTimeout * 1000 . ')</script>'; echo '<a href="' . \Environment::get('base') . $url . '">Please click here to proceed if you are not using JavaScript</a>'; } echo '</div></div>'; exit; } $strToken = md5(uniqid(mt_rand(), true)); $objSession->set('tl_newsletter_send', $strToken); $sprintf = $objNewsletter->senderName != '' ? $objNewsletter->senderName . ' <%s>' : '%s'; $this->import('BackendUser', 'User'); // Preview newsletter $return = ' <div id="tl_buttons"> <a href="' . $this->getReferer(true) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '" accesskey="b">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a> </div> ' . \Message::generate() . ' <form action="' . TL_SCRIPT . '" id="tl_newsletter_send" class="tl_form" method="get"> <div class="tl_formbody_edit tl_newsletter_send"> <input type="hidden" name="do" value="' . \Input::get('do') . '"> <input type="hidden" name="table" value="' . \Input::get('table') . '"> <input type="hidden" name="key" value="' . \Input::get('key') . '"> <input type="hidden" name="id" value="' . \Input::get('id') . '"> <input type="hidden" name="token" value="' . $strToken . '"> <table class="prev_header"> <tr class="row_0"> <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['from'] . '</td> <td class="col_1">' . sprintf($sprintf, $objNewsletter->sender) . '</td> </tr> <tr class="row_1"> <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['subject'][0] . '</td> <td class="col_1">' . $objNewsletter->subject . '</td> </tr> <tr class="row_2"> <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['template'][0] . '</td> <td class="col_1">' . $objNewsletter->template . '</td> </tr>' . (!empty($arrAttachments) && is_array($arrAttachments) ? ' <tr class="row_3"> <td class="col_0">' . $GLOBALS['TL_LANG']['tl_newsletter']['attachments'] . '</td> <td class="col_1">' . implode(', ', $arrAttachments) . '</td> </tr>' : '') . ' </table>' . (!$objNewsletter->sendText ? ' <div class="preview_html"> ' . $html . ' </div>' : '') . ' <div class="preview_text"> <pre style="white-space:pre-wrap">' . $text . '</pre> </div> <div class="tl_tbox"> <div class="w50"> <h3><label for="ctrl_mpc">' . $GLOBALS['TL_LANG']['tl_newsletter']['mailsPerCycle'][0] . '</label></h3> <input type="text" name="mpc" id="ctrl_mpc" value="10" class="tl_text" onfocus="Backend.getScrollOffset()">' . ($GLOBALS['TL_LANG']['tl_newsletter']['mailsPerCycle'][1] && \Config::get('showHelp') ? ' <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['mailsPerCycle'][1] . '</p>' : '') . ' </div> <div class="w50"> <h3><label for="ctrl_timeout">' . $GLOBALS['TL_LANG']['tl_newsletter']['timeout'][0] . '</label></h3> <input type="text" name="timeout" id="ctrl_timeout" value="1" class="tl_text" onfocus="Backend.getScrollOffset()">' . ($GLOBALS['TL_LANG']['tl_newsletter']['timeout'][1] && \Config::get('showHelp') ? ' <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['timeout'][1] . '</p>' : '') . ' </div> <div class="w50"> <h3><label for="ctrl_start">' . $GLOBALS['TL_LANG']['tl_newsletter']['start'][0] . '</label></h3> <input type="text" name="start" id="ctrl_start" value="0" class="tl_text" onfocus="Backend.getScrollOffset()">' . ($GLOBALS['TL_LANG']['tl_newsletter']['start'][1] && \Config::get('showHelp') ? ' <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['start'][1] . '</p>' : '') . ' </div> <div class="w50"> <h3><label for="ctrl_recipient">' . $GLOBALS['TL_LANG']['tl_newsletter']['sendPreviewTo'][0] . '</label></h3> <input type="text" name="recipient" id="ctrl_recipient" value="' . $this->User->email . '" class="tl_text" onfocus="Backend.getScrollOffset()">' . (isset($_SESSION['TL_PREVIEW_MAIL_ERROR']) ? ' <div class="tl_error">' . $GLOBALS['TL_LANG']['ERR']['email'] . '</div>' : ($GLOBALS['TL_LANG']['tl_newsletter']['sendPreviewTo'][1] && \Config::get('showHelp') ? ' <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_newsletter']['sendPreviewTo'][1] . '</p>' : '')) . ' </div> <div class="clear"></div> </div> </div>'; $return .= ' <div class="tl_formbody_submit"> <div class="tl_submit_container"> <button type="submit" name="preview" class="tl_submit" accesskey="p">' . $GLOBALS['TL_LANG']['tl_newsletter']['preview'] . '</button> <button type="submit" id="send" class="tl_submit" accesskey="s" onclick="return confirm(\'' . str_replace("'", "\\'", $GLOBALS['TL_LANG']['tl_newsletter']['sendConfirm']) . '\')">' . $GLOBALS['TL_LANG']['tl_newsletter']['send'][0] . '</button> </div> </div> </form>'; unset($_SESSION['TL_PREVIEW_MAIL_ERROR']); return $return; }
/** * Return the files model * * @return FilesModel The files model */ public function getModel() { if ($this->objModel === null && \Dbafs::shouldBeSynchronized($this->strFile)) { $this->objModel = \FilesModel::findByPath($this->strFile); } return $this->objModel; }
/** * Generate the module */ protected function compile() { $objFaq = \FaqModel::findPublishedByPids($this->faq_categories); if ($objFaq === null) { $this->Template->faq = array(); return; } /** @var PageModel $objPage */ global $objPage; $arrFaqs = array_fill_keys($this->faq_categories, array()); // Add FAQs while ($objFaq->next()) { /** @var FaqModel $objFaq */ $objTemp = (object) $objFaq->row(); // Clean the RTE output $objTemp->answer = \StringUtil::toHtml5($objFaq->answer); $objTemp->answer = \StringUtil::encodeEmail($objTemp->answer); $objTemp->addImage = false; // Add an image if ($objFaq->addImage && $objFaq->singleSRC != '') { $objModel = \FilesModel::findByUuid($objFaq->singleSRC); if ($objModel !== null && is_file(TL_ROOT . '/' . $objModel->path)) { // Do not override the field now that we have a model registry (see #6303) $arrFaq = $objFaq->row(); $arrFaq['singleSRC'] = $objModel->path; $strLightboxId = 'lightbox[' . substr(md5('mod_faqpage_' . $objFaq->id), 0, 6) . ']'; // see #5810 $this->addImageToTemplate($objTemp, $arrFaq, null, $strLightboxId); } } $objTemp->enclosure = array(); // Add enclosure if ($objFaq->addEnclosure) { $this->addEnclosuresToTemplate($objTemp, $objFaq->row()); } /** @var UserModel $objAuthor */ $objAuthor = $objFaq->getRelated('author'); $objTemp->info = sprintf($GLOBALS['TL_LANG']['MSC']['faqCreatedBy'], \Date::parse($objPage->dateFormat, $objFaq->tstamp), $objAuthor->name); /** @var FaqCategoryModel $objPid */ $objPid = $objFaq->getRelated('pid'); // Order by PID $arrFaqs[$objFaq->pid]['items'][] = $objTemp; $arrFaqs[$objFaq->pid]['headline'] = $objPid->headline; $arrFaqs[$objFaq->pid]['title'] = $objPid->title; } $arrFaqs = array_values(array_filter($arrFaqs)); $limit_i = count($arrFaqs) - 1; // Add classes first, last, even and odd for ($i = 0; $i <= $limit_i; $i++) { $class = ($i == 0 ? 'first ' : '') . ($i == $limit_i ? 'last ' : '') . ($i % 2 == 0 ? 'even' : 'odd'); $arrFaqs[$i]['class'] = trim($class); $limit_j = count($arrFaqs[$i]['items']) - 1; for ($j = 0; $j <= $limit_j; $j++) { $class = ($j == 0 ? 'first ' : '') . ($j == $limit_j ? 'last ' : '') . ($j % 2 == 0 ? 'even' : 'odd'); $arrFaqs[$i]['items'][$j]->class = trim($class); } } $this->Template->faq = $arrFaqs; $this->Template->request = \Environment::get('indexFreeRequest'); $this->Template->topLink = $GLOBALS['TL_LANG']['MSC']['backToTop']; }
/** * Set all user properties from a database record */ protected function setUserFromDb() { $this->intId = $this->id; // Unserialize values foreach ($this->arrData as $k => $v) { if (!is_numeric($v)) { $this->{$k} = deserialize($v); } } $GLOBALS['TL_USERNAME'] = $this->username; \System::getContainer()->get('request_stack')->getCurrentRequest()->setLocale($this->language); \System::getContainer()->get('translator')->setLocale($this->language); // Deprecated since Contao 4.0, to be removed in Contao 5.0 $GLOBALS['TL_LANGUAGE'] = str_replace('_', '-', $this->language); \Config::set('showHelp', $this->showHelp); \Config::set('useRTE', $this->useRTE); \Config::set('useCE', $this->useCE); \Config::set('thumbnails', $this->thumbnails); \Config::set('backendTheme', $this->backendTheme); // Inherit permissions $always = array('alexf'); $depends = array('modules', 'themes', 'pagemounts', 'alpty', 'filemounts', 'fop', 'forms', 'formp', 'imageSizes'); // HOOK: Take custom permissions if (!empty($GLOBALS['TL_PERMISSIONS']) && is_array($GLOBALS['TL_PERMISSIONS'])) { $depends = array_merge($depends, $GLOBALS['TL_PERMISSIONS']); } // Overwrite user permissions if only group permissions shall be inherited if ($this->inherit == 'group') { foreach ($depends as $field) { $this->{$field} = array(); } } // Merge permissions $inherit = in_array($this->inherit, array('group', 'extend')) ? array_merge($always, $depends) : $always; $time = \Date::floorToMinute(); foreach ((array) $this->groups as $id) { $objGroup = $this->Database->prepare("SELECT * FROM tl_user_group WHERE id=? AND disable!='1' AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "')")->limit(1)->execute($id); if ($objGroup->numRows > 0) { foreach ($inherit as $field) { $value = deserialize($objGroup->{$field}, true); // The new page/file picker can return integers instead of arrays, so use empty() instead of is_array() and deserialize(true) here if (!empty($value)) { $this->{$field} = array_merge(is_array($this->{$field}) ? $this->{$field} : ($this->{$field} != '' ? array($this->{$field}) : array()), $value); $this->{$field} = array_unique($this->{$field}); } } } } // Make sure pagemounts and filemounts are set! if (!is_array($this->pagemounts)) { $this->pagemounts = array(); } else { $this->pagemounts = array_filter($this->pagemounts); } if (!is_array($this->filemounts)) { $this->filemounts = array(); } else { $this->filemounts = array_filter($this->filemounts); } // Store the numeric file mounts $this->arrFilemountIds = $this->filemounts; // Convert the file mounts into paths if (!$this->isAdmin && !empty($this->filemounts)) { $objFiles = \FilesModel::findMultipleByUuids($this->filemounts); if ($objFiles !== null) { $this->filemounts = $objFiles->fetchEach('path'); } } }
/** * Render a calendar event. * * @param GetCalendarEventEvent $event The event. * * @param string $eventName The event name. * * @param EventDispatcherInterface $eventDispatcher The event dispatcher. * * @return void * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.Superglobals) * @SuppressWarnings(PHPMD.CamelCaseVariableName) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function handleEvent(GetCalendarEventEvent $event, $eventName, EventDispatcherInterface $eventDispatcher) { if ($event->getCalendarEventHtml()) { return; } $calendarCollection = CalendarModel::findAll(); if (!$calendarCollection) { return; } $calendarIds = $calendarCollection->fetchEach('id'); $eventModel = CalendarEventsModel::findPublishedByParentAndIdOrAlias($event->getCalendarEventId(), $calendarIds); if (!$eventModel) { return; } $calendarModel = $eventModel->getRelated('pid'); $objPage = PageModel::findWithDetails($calendarModel->jumpTo); if ($event->getDateTime()) { $selectedStartDateTime = clone $event->getDateTime(); $selectedStartDateTime->setTime(date('H', $eventModel->startTime), date('i', $eventModel->startTime), date('s', $eventModel->startTime)); $secondsBetweenStartAndEndTime = $eventModel->endTime - $eventModel->startTime; $intStartTime = $selectedStartDateTime->getTimestamp(); $intEndTime = $intStartTime + $secondsBetweenStartAndEndTime; } else { $intStartTime = $eventModel->startTime; $intEndTime = $eventModel->endTime; } $span = Calendar::calculateSpan($intStartTime, $intEndTime); // Do not show dates in the past if the event is recurring (see #923). if ($eventModel->recurring) { $arrRange = deserialize($eventModel->repeatEach); while ($intStartTime < time() && $intEndTime < $eventModel->repeatEnd) { $intStartTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intStartTime); $intEndTime = strtotime('+' . $arrRange['value'] . ' ' . $arrRange['unit'], $intEndTime); } } if ($objPage->outputFormat == 'xhtml') { $strTimeStart = ''; $strTimeEnd = ''; $strTimeClose = ''; } else { $strTimeStart = ''; $strTimeEnd = ''; $strTimeClose = ''; // @codingStandardsIgnoreStart /* TODO $this->date and $this->time is used in the <a> title attribute and cannot contain HTML! $strTimeStart = '<time datetime="' . date('Y-m-d\TH:i:sP', $intStartTime) . '">'; $strTimeEnd = '<time datetime="' . date('Y-m-d\TH:i:sP', $intEndTime) . '">'; $strTimeClose = '</time>'; */ // @codingStandardsIgnoreEnd } // Get date. if ($span > 0) { $date = $strTimeStart . Date::parse($eventModel->addTime ? $objPage->datimFormat : $objPage->dateFormat, $intStartTime) . $strTimeClose . ' - ' . $strTimeEnd . Date::parse($eventModel->addTime ? $objPage->datimFormat : $objPage->dateFormat, $intEndTime) . $strTimeClose; } elseif ($intStartTime == $intEndTime) { $date = $strTimeStart . Date::parse($objPage->dateFormat, $intStartTime) . ($eventModel->addTime ? ' (' . Date::parse($objPage->timeFormat, $intStartTime) . ')' : '') . $strTimeClose; } else { $date = $strTimeStart . Date::parse($objPage->dateFormat, $intStartTime) . ($eventModel->addTime ? ' (' . Date::parse($objPage->timeFormat, $intStartTime) . $strTimeClose . ' - ' . $strTimeEnd . Date::parse($objPage->timeFormat, $intEndTime) . ')' : '') . $strTimeClose; } $until = ''; $recurring = ''; // Recurring event. if ($eventModel->recurring) { $arrRange = deserialize($eventModel->repeatEach); $strKey = 'cal_' . $arrRange['unit']; $recurring = sprintf($GLOBALS['TL_LANG']['MSC'][$strKey], $arrRange['value']); if ($eventModel->recurrences > 0) { $until = sprintf($GLOBALS['TL_LANG']['MSC']['cal_until'], Date::parse($objPage->dateFormat, $eventModel->repeatEnd)); } } // Override the default image size. // This is always false. if ($this->imgSize != '') { $size = deserialize($this->imgSize); if ($size[0] > 0 || $size[1] > 0) { $eventModel->size = $this->imgSize; } } $objTemplate = new FrontendTemplate($event->getTemplate()); $objTemplate->setData($eventModel->row()); $objTemplate->date = $date; $objTemplate->start = $intStartTime; $objTemplate->end = $intEndTime; $objTemplate->class = $eventModel->cssClass != '' ? ' ' . $eventModel->cssClass : ''; $objTemplate->recurring = $recurring; $objTemplate->until = $until; $objTemplate->locationLabel = $GLOBALS['TL_LANG']['MSC']['location']; $objTemplate->details = ''; $objElement = ContentModel::findPublishedByPidAndTable($eventModel->id, 'tl_calendar_events'); if ($objElement !== null) { while ($objElement->next()) { $getContentElementEvent = new GetContentElementEvent($objElement->id); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_GET_CONTENT_ELEMENT, $getContentElementEvent); $objTemplate->details .= $getContentElementEvent->getContentElementHtml(); } $objTemplate->hasDetails = true; } $objTemplate->addImage = false; // Add an image. if ($eventModel->addImage && $eventModel->singleSRC != '') { $objModel = FilesModel::findByUuid($eventModel->singleSRC); if ($objModel === null) { if (!Validator::isUuid($eventModel->singleSRC)) { $objTemplate->text = '<p class="error">' . $GLOBALS['TL_LANG']['ERR']['version2format'] . '</p>'; } } elseif (is_file(TL_ROOT . '/' . $objModel->path)) { // Do not override the field now that we have a model registry (see #6303). $arrEvent = $eventModel->row(); $arrEvent['singleSRC'] = $objModel->path; $addImageToTemplateEvent = new AddImageToTemplateEvent($arrEvent, $objTemplate); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_IMAGE_TO_TEMPLATE, $addImageToTemplateEvent); } } $objTemplate->enclosure = array(); // Add enclosures. if ($eventModel->addEnclosure) { $addEnclosureToTemplateEvent = new AddEnclosureToTemplateEvent($eventModel->row(), $objTemplate); $eventDispatcher->dispatch(ContaoEvents::CONTROLLER_ADD_ENCLOSURE_TO_TEMPLATE, $addEnclosureToTemplateEvent); } $calendarEvent = $objTemplate->parse(); $event->setCalendarEventHtml($calendarEvent); }
/** * Translate the file IDs to file paths */ protected function convertValuesToPaths() { if (empty($this->varValue)) { return; } if (!is_array($this->varValue)) { $this->varValue = array($this->varValue); } elseif (empty($this->varValue[0])) { $this->varValue = array(); } if (empty($this->varValue)) { return; } // TinyMCE will pass the path instead of the ID if (strncmp($this->varValue[0], \Config::get('uploadPath') . '/', strlen(\Config::get('uploadPath')) + 1) === 0) { return; } // Ignore the numeric IDs when in switch mode (TinyMCE) if (\Input::get('switch')) { return; } $objFiles = \FilesModel::findMultipleByIds($this->varValue); if ($objFiles !== null) { $this->varValue = array_values($objFiles->fetchEach('path')); } }
/** * Add the file meta information to the request * * @param string $strUuid * @param string $strPtable * @param integer $intPid */ public static function addFileMetaInformationToRequest($strUuid, $strPtable, $intPid) { $objFile = \FilesModel::findByUuid($strUuid); if ($objFile === null) { return; } $arrMeta = \StringUtil::deserialize($objFile->meta); if (empty($arrMeta)) { return; } $objPage = null; if ($strPtable == 'tl_article') { $objPage = \PageModel::findOneBy(array('tl_page.id=(SELECT pid FROM tl_article WHERE id=?)'), $intPid); } else { // HOOK: support custom modules if (isset($GLOBALS['TL_HOOKS']['addFileMetaInformationToRequest']) && is_array($GLOBALS['TL_HOOKS']['addFileMetaInformationToRequest'])) { foreach ($GLOBALS['TL_HOOKS']['addFileMetaInformationToRequest'] as $callback) { if (($val = \System::importStatic($callback[0])->{$callback[1]}($strPtable, $intPid)) !== false) { $objPage = $val; } } if ($objPage instanceof Result && $objPage->numRows < 1) { return; } if (is_object($objPage) && !$objPage instanceof PageModel) { $objPage = \PageModel::findByPk($objPage->id); } } } if ($objPage === null) { return; } $objPage->loadDetails(); // Convert the language to a locale (see #5678) $strLanguage = str_replace('-', '_', $objPage->rootLanguage); if (isset($arrMeta[$strLanguage])) { if (\Input::post('title') == '' && !empty($arrMeta[$strLanguage]['title'])) { \Input::setPost('title', $arrMeta[$strLanguage]['title']); } if (\Input::post('alt') == '' && !empty($arrMeta[$strLanguage]['alt'])) { \Input::setPost('alt', $arrMeta[$strLanguage]['alt']); } if (\Input::post('caption') == '' && !empty($arrMeta[$strLanguage]['caption'])) { \Input::setPost('caption', $arrMeta[$strLanguage]['caption']); } } }
/** * Convert insert tags inside "src" attributes to file paths * * @param string $data The markup string * * @return string The markup with insert tags converted to file paths */ 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 = $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; }
/** * Create all header scripts * * @param \PageModel $objPage * @param \LayoutModel $objLayout */ protected function createHeaderScripts($objPage, $objLayout) { $strStyleSheets = ''; $strCcStyleSheets = ''; $arrStyleSheets = deserialize($objLayout->stylesheet); $arrFramework = deserialize($objLayout->framework); // Google web fonts if ($objLayout->webfonts != '') { $strStyleSheets .= \Template::generateStyleTag('//fonts.googleapis.com/css?family=' . str_replace('|', '%7C', $objLayout->webfonts), 'all') . "\n"; } // Add the Contao CSS framework style sheets if (is_array($arrFramework)) { foreach ($arrFramework as $strFile) { if ($strFile != 'tinymce.css') { $GLOBALS['TL_FRAMEWORK_CSS'][] = 'assets/contao/css/' . basename($strFile, '.css') . '.min.css'; } } } // Make sure TL_USER_CSS is set if (!is_array($GLOBALS['TL_USER_CSS'])) { $GLOBALS['TL_USER_CSS'] = array(); } // User style sheets if (is_array($arrStyleSheets) && strlen($arrStyleSheets[0])) { $objStylesheets = \StyleSheetModel::findByIds($arrStyleSheets); if ($objStylesheets !== null) { while ($objStylesheets->next()) { $media = implode(',', deserialize($objStylesheets->media)); // Overwrite the media type with a custom media query if ($objStylesheets->mediaQuery != '') { $media = $objStylesheets->mediaQuery; } // Style sheets with a CC or a combination of font-face and media-type != all cannot be aggregated (see #5216) if ($objStylesheets->cc || $objStylesheets->hasFontFace && $media != 'all') { $strStyleSheet = ''; // External style sheet if ($objStylesheets->type == 'external') { $objFile = \FilesModel::findByPk($objStylesheets->singleSRC); if ($objFile !== null) { $strStyleSheet = \Template::generateStyleTag(TL_ASSETS_URL . $objFile->path, $media); } } else { $strStyleSheet = \Template::generateStyleTag(TL_ASSETS_URL . 'assets/css/' . $objStylesheets->name . '.css', $media); } if ($objStylesheets->cc) { $strStyleSheet = '<!--[' . $objStylesheets->cc . ']>' . $strStyleSheet . '<![endif]-->'; } $strCcStyleSheets .= $strStyleSheet . "\n"; } else { // External style sheet if ($objStylesheets->type == 'external') { $objFile = \FilesModel::findByPk($objStylesheets->singleSRC); if ($objFile !== null) { $GLOBALS['TL_USER_CSS'][] = $objFile->path . '|' . $media . '|static|' . filemtime(TL_ROOT . '/' . $objFile->path); } } else { $GLOBALS['TL_USER_CSS'][] = 'assets/css/' . $objStylesheets->name . '.css|' . $media . '|static|' . max($objStylesheets->tstamp, $objStylesheets->tstamp2, $objStylesheets->tstamp3); } } } } } $arrExternal = deserialize($objLayout->external); // External style sheets if (!empty($arrExternal) && is_array($arrExternal)) { // Consider the sorting order (see #5038) if ($objLayout->orderExt != '') { $tmp = deserialize($objLayout->orderExt); if (!empty($tmp) && is_array($tmp)) { // Remove all values $arrOrder = array_map(function () { }, array_flip($tmp)); // Move the matching elements to their position in $arrOrder foreach ($arrExternal as $k => $v) { if (array_key_exists($v, $arrOrder)) { $arrOrder[$v] = $v; unset($arrExternal[$k]); } } // Append the left-over style sheets at the end if (!empty($arrExternal)) { $arrOrder = array_merge($arrOrder, array_values($arrExternal)); } // Remove empty (unreplaced) entries $arrExternal = array_values(array_filter($arrOrder)); unset($arrOrder); } } // Get the file entries from the database $objFiles = \FilesModel::findMultipleByUuids($arrExternal); if ($objFiles !== null) { $arrFiles = array(); while ($objFiles->next()) { if (file_exists(TL_ROOT . '/' . $objFiles->path)) { $arrFiles[] = $objFiles->path . '|static'; } } // Inject the external style sheets before or after the internal ones (see #6937) if ($objLayout->loadingOrder == 'external_first') { array_splice($GLOBALS['TL_USER_CSS'], 0, 0, $arrFiles); } else { array_splice($GLOBALS['TL_USER_CSS'], count($GLOBALS['TL_USER_CSS']), 0, $arrFiles); } } } // Add a placeholder for dynamic style sheets (see #4203) $strStyleSheets .= '[[TL_CSS]]'; // Always add conditional style sheets at the end $strStyleSheets .= $strCcStyleSheets; $newsfeeds = deserialize($objLayout->newsfeeds); $calendarfeeds = deserialize($objLayout->calendarfeeds); // Add newsfeeds if (!empty($newsfeeds) && is_array($newsfeeds)) { $objFeeds = \NewsFeedModel::findByIds($newsfeeds); if ($objFeeds !== null) { while ($objFeeds->next()) { $strStyleSheets .= \Template::generateFeedTag(($objFeeds->feedBase ?: \Environment::get('base')) . 'share/' . $objFeeds->alias . '.xml', $objFeeds->format, $objFeeds->title) . "\n"; } } } // Add calendarfeeds if (!empty($calendarfeeds) && is_array($calendarfeeds)) { $objFeeds = \CalendarFeedModel::findByIds($calendarfeeds); if ($objFeeds !== null) { while ($objFeeds->next()) { $strStyleSheets .= \Template::generateFeedTag(($objFeeds->feedBase ?: \Environment::get('base')) . 'share/' . $objFeeds->alias . '.xml', $objFeeds->format, $objFeeds->title) . "\n"; } } } // Add a placeholder for dynamic <head> tags (see #4203) $strHeadTags = '[[TL_HEAD]]'; // Add the user <head> tags if (($strHead = trim($objLayout->head)) != false) { $strHeadTags .= $strHead . "\n"; } $this->Template->stylesheets = $strStyleSheets; $this->Template->head = $strHeadTags; }