예제 #1
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     $this->Template->src = $this->singleSRC;
     $this->Template->href = $this->source == 'external' ? $this->url : $this->singleSRC;
     $this->Template->alt = $this->altContent;
     $this->Template->var = 'swf' . $this->id;
     $this->Template->transparent = $this->transparent ? true : false;
     $this->Template->interactive = $this->interactive ? true : false;
     $this->Template->flashId = $this->flashID ?: 'swf_' . $this->id;
     $this->Template->fsCommand = '  ' . preg_replace('/[\\n\\r]/', "\n  ", \String::decodeEntities($this->flashJS));
     $this->Template->flashvars = 'URL=' . \Environment::get('base');
     $this->Template->version = $this->version ?: '6.0.0';
     $size = deserialize($this->size);
     $this->Template->width = $size[0];
     $this->Template->height = $size[1];
     $intMaxWidth = TL_MODE == 'BE' ? 320 : \Config::get('maxImageWidth');
     // Adjust movie size
     if ($intMaxWidth > 0 && $size[0] > $intMaxWidth) {
         $this->Template->width = $intMaxWidth;
         $this->Template->height = floor($intMaxWidth * $size[1] / $size[0]);
     }
     if (strlen($this->flashvars)) {
         $this->Template->flashvars .= '&' . \String::decodeEntities($this->flashvars);
     }
 }
예제 #2
0
 /**
  * Recursively replace simple tokens and insert tags
  *
  * @param   string $strText
  * @param   array  $arrTokens Array of Tokens
  *
  * @return  string
  */
 public static function recursiveReplaceTokensAndTags($text, $tokens)
 {
     // Must decode, tokens could be encoded
     $text = \String::decodeEntities($text);
     // Replace all opening and closing tags with a hash so they don't get stripped
     // by parseSimpleTokens()
     $hash = md5($text);
     $openTagReplacement = 'LEADS-TAG-OPEN-' . $hash;
     $closeTagReplacement = 'LEADS-TAG-CLOSE-' . $hash;
     $original = array('<', '>');
     $replacement = array($openTagReplacement, $closeTagReplacement);
     $text = str_replace($original, $replacement, $text);
     // first parse the tokens as they might have if-else clauses
     $buffer = \String::parseSimpleTokens($text, $tokens);
     // Restore tags
     $buffer = str_replace($replacement, $original, $buffer);
     // Replace the Insert Tags
     $buffer = \Haste\Haste::getInstance()->call('replaceInsertTags', array($buffer, false));
     // Check if the Insert Tags have returned a Simple Token or an Insert Tag to parse
     if ((strpos($buffer, '##') !== false || strpos($buffer, '{{') !== false) && $buffer != $text) {
         $buffer = static::recursiveReplaceTokensAndTags($buffer, $tokens);
     }
     $buffer = \String::restoreBasicEntities($buffer);
     return $buffer;
 }
예제 #3
0
 /**
  * Recursively replace simple tokens and insert tags
  * @param   string $strText
  * @param   array  $arrTokens Array of Tokens
  * @param   int    $intTextFlags Filters the tokens and the text for a given set of options
  *
  * @return  string
  */
 public static function recursiveReplaceTokensAndTags($strText, $arrTokens, $intTextFlags = 0)
 {
     if ($intTextFlags > 0) {
         $arrTokens = static::convertToText($arrTokens, $intTextFlags);
     }
     // Must decode, tokens could be encoded
     $strText = \String::decodeEntities($strText);
     // Replace all opening and closing tags with a hash so they don't get stripped
     // by parseSimpleTokens() - this is useful e.g. for XML content
     $strHash = md5($strText);
     $strTagOpenReplacement = 'NC-TAG-OPEN-' . $strHash;
     $strTagCloseReplacement = 'NC-TAG-CLOSE-' . $strHash;
     $arrOriginal = array('<', '>');
     $arrReplacement = array($strTagOpenReplacement, $strTagCloseReplacement);
     $strText = str_replace($arrOriginal, $arrReplacement, $strText);
     // first parse the tokens as they might have if-else clauses
     $strBuffer = \String::parseSimpleTokens($strText, $arrTokens);
     $strBuffer = str_replace($arrReplacement, $arrOriginal, $strBuffer);
     // then replace the insert tags
     $strBuffer = \Haste\Haste::getInstance()->call('replaceInsertTags', array($strBuffer, false));
     // check if the inserttags have returned a simple token or an insert tag to parse
     if ((strpos($strBuffer, '##') !== false || strpos($strBuffer, '{{') !== false) && $strBuffer != $strText) {
         $strBuffer = static::recursiveReplaceTokensAndTags($strBuffer, $arrTokens, $intTextFlags);
     }
     $strBuffer = \String::restoreBasicEntities($strBuffer);
     if ($intTextFlags > 0) {
         $strBuffer = static::convertToText($strBuffer, $intTextFlags);
     }
     return $strBuffer;
 }
예제 #4
0
 /**
  * Recursively replace simple tokens and insert tags
  *
  * @param string $strText
  * @param array  $arrTokens    Array of Tokens
  * @param int    $intTextFlags Filters the tokens and the text for a given set of options
  *
  * @return string
  */
 public static function recursiveReplaceTokensAndTags($strText, $arrTokens, $intTextFlags = 0)
 {
     if ($intTextFlags > 0) {
         $arrTokens = static::convertToText($arrTokens, $intTextFlags);
     }
     // PHP 7 compatibility
     // See #309 (https://github.com/contao/core-bundle/issues/309)
     if (version_compare(VERSION . '.' . BUILD, '3.5.1', '>=')) {
         // Must decode, tokens could be encoded
         $strText = \StringUtil::decodeEntities($strText);
     } else {
         // Must decode, tokens could be encoded
         $strText = \String::decodeEntities($strText);
     }
     // Replace all opening and closing tags with a hash so they don't get stripped
     // by parseSimpleTokens() - this is useful e.g. for XML content
     $strHash = md5($strText);
     $strTagOpenReplacement = 'HASTE-TAG-OPEN-' . $strHash;
     $strTagCloseReplacement = 'HASTE-TAG-CLOSE-' . $strHash;
     $arrOriginal = array('<', '>');
     $arrReplacement = array($strTagOpenReplacement, $strTagCloseReplacement);
     $strBuffer = str_replace($arrOriginal, $arrReplacement, $strText);
     // PHP 7 compatibility
     // See #309 (https://github.com/contao/core-bundle/issues/309)
     if (version_compare(VERSION . '.' . BUILD, '3.5.1', '>=')) {
         // first parse the tokens as they might have if-else clauses
         $strBuffer = \StringUtil::parseSimpleTokens($strBuffer, $arrTokens);
     } else {
         // first parse the tokens as they might have if-else clauses
         $strBuffer = \String::parseSimpleTokens($strBuffer, $arrTokens);
     }
     $strBuffer = str_replace($arrReplacement, $arrOriginal, $strBuffer);
     // then replace the insert tags
     $strBuffer = \Controller::replaceInsertTags($strBuffer, false);
     // check if the inserttags have returned a simple token or an insert tag to parse
     if ((strpos($strBuffer, '##') !== false || strpos($strBuffer, '{{') !== false) && $strBuffer != $strText) {
         $strBuffer = static::recursiveReplaceTokensAndTags($strBuffer, $arrTokens, $intTextFlags);
     }
     // PHP 7 compatibility
     // See #309 (https://github.com/contao/core-bundle/issues/309)
     if (version_compare(VERSION . '.' . BUILD, '3.5.1', '>=')) {
         $strBuffer = \StringUtil::restoreBasicEntities($strBuffer);
     } else {
         $strBuffer = \String::restoreBasicEntities($strBuffer);
     }
     if ($intTextFlags > 0) {
         $strBuffer = static::convertToText($strBuffer, $intTextFlags);
     }
     return $strBuffer;
 }
 /**
  * This function is for the manipulation of the attribute value
  * Must return the value in the format what is needed for MetaModels
  *
  * @param $widget
  * @return mixed
  */
 public function parseWidget($widget)
 {
     if (is_a($widget, 'Contao\\FormTextArea') || is_a($widget, 'Contao\\FormTextField')) {
         if ($this->field->getEval('allowHtml')) {
             $value = strip_tags(\String::decodeEntities($widget->value), \Config::get('allowedTags'));
         } else {
             $value = strip_tags(\String::decodeEntities($widget->value));
         }
         if ($this->field->getEval('decodeEntities')) {
             return $value;
         } else {
             return specialchars($value);
         }
     }
     return $widget->value;
 }
예제 #6
0
 protected static function addToPDFSearchIndex($strFile, $arrParentSet)
 {
     $objFile = new \File($strFile);
     if (!Validator::isValidPDF($objFile)) {
         return false;
     }
     $objDatabase = \Database::getInstance();
     $objModel = $objFile->getModel();
     $arrMeta = \Frontend::getMetaData($objModel->meta, $arrParentSet['language']);
     // Use the file name as title if none is given
     if ($arrMeta['title'] == '') {
         $arrMeta['title'] = specialchars($objFile->basename);
     }
     $arrSet = array('pid' => $arrParentSet['pid'], 'tstamp' => time(), 'title' => $arrMeta['title'], 'url' => $objFile->value, 'filesize' => \System::getReadableSize($objFile->size, 2), 'checksum' => $objFile->hash, 'protected' => $arrParentSet['protected'], 'groups' => $arrParentSet['groups'], 'language' => $arrParentSet['language'], 'mime' => $objFile->mime);
     // Return if the file is indexed and up to date
     $objIndex = $objDatabase->prepare("SELECT * FROM tl_search WHERE url=? AND checksum=?")->execute($arrSet['url'], $arrSet['checksum']);
     // there are already indexed files containing this file (same checksum and filename)
     if ($objIndex->numRows) {
         // Return if the page with the file is indexed
         if (in_array($arrSet['pid'], $objIndex->fetchEach('pid'))) {
             return false;
         }
         $strContent = $objIndex->text;
     } else {
         try {
             // parse only for the first occurrence
             $parser = new \Smalot\PdfParser\Parser();
             $objPDF = $parser->parseFile($strFile);
             $strContent = $objPDF->getText();
         } catch (\Exception $e) {
             // Missing object refernce #...
             return false;
         }
     }
     // Put everything together
     $arrSet['text'] = $strContent;
     $arrSet['text'] = trim(preg_replace('/ +/', ' ', \String::decodeEntities($arrSet['text'])));
     // Update an existing old entry
     if ($objIndex->pid == $arrSet['pid']) {
         $objDatabase->prepare("UPDATE tl_search %s WHERE id=?")->set($arrSet)->execute($objIndex->id);
         $intInsertId = $objIndex->id;
     } else {
         $objInsertStmt = $objDatabase->prepare("INSERT INTO tl_search %s")->set($arrSet)->execute();
         $intInsertId = $objInsertStmt->insertId;
     }
     static::indexContent($arrSet, $intInsertId);
 }
 /**
  * Should only return the field value
  * @return string
  */
 public function generate()
 {
     $arrData = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$this->strName];
     $value = FormSubmission::prepareSpecialValueForPrint($this->varValue, $arrData, $this->strTable, $this, $this->activeRecord);
     switch ($this->type) {
         case 'multifileupload':
             if ($this->fieldType == 'checkbox') {
                 $value = '<ul class="download-list">' . implode('', array_map(function ($val) {
                     return '<li>{{download::' . str_replace(\Environment::get('url') . '/', '', $val) . '}}</li>';
                 }, explode(', ', $value))) . '</ul>';
                 break;
             }
             $value = '{{download::' . str_replace(\Environment::get('url') . '/', '', $value) . '}}';
             break;
     }
     $value = class_exists('Contao\\StringUtil') ? \StringUtil::decodeEntities(\Controller::replaceInsertTags($value)) : \String::decodeEntities(\Controller::replaceInsertTags($value));
     if (!$value) {
         $value = '-';
     }
     return $value;
 }
 public static function loadDynamicPaletteByParentTable($strAct, $strTable, &$dc)
 {
     switch ($strAct) {
         case 'create':
             $strParentTable = FieldPalette::getParentTableFromRequest();
             $strPalette = FieldPalette::getPaletteFromRequest();
             break;
         case 'cut':
         case 'edit':
         case 'show':
         case 'delete':
         case 'toggle':
             $id = strlen(\Input::get('id')) ? \Input::get('id') : CURRENT_ID;
             $objModel = \HeimrichHannot\FieldPalette\FieldPaletteModel::findByPk($id);
             if ($objModel === null) {
                 break;
             }
             $strParentTable = FieldPalette::getParentTable($objModel, $objModel->id);
             $strPalette = $objModel->pfield;
             // set back link from request
             if (\Input::get('popup') && \Input::get('popupReferer')) {
                 $arrSession = \Session::getInstance()->getData();
                 if (class_exists('\\Contao\\StringUtil')) {
                     $arrSession['popupReferer'][TL_REFERER_ID]['current'] = \StringUtil::decodeEntities(rawurldecode(\Input::get('popupReferer')));
                 } else {
                     $arrSession['popupReferer'][TL_REFERER_ID]['current'] = \String::decodeEntities(rawurldecode(\Input::get('popupReferer')));
                 }
                 \Session::getInstance()->setData($arrSession);
             }
             break;
     }
     if (!$strParentTable || !$strPalette) {
         return false;
     }
     if ($strTable !== $strParentTable) {
         \Controller::loadDataContainer($strParentTable);
     }
     static::registerFieldPalette($dc, $strParentTable, $strTable, $strPalette);
 }
예제 #9
0
 /**
  * Get a translation of a value using the translation tabel
  * @param   mixed
  * @param   boolean
  * @return  mixed
  */
 public static function get($varLabel, $strLanguage = null)
 {
     if (!\Database::getInstance()->tableExists(Label::getTable())) {
         return $varLabel;
     }
     if (null === $strLanguage) {
         $strLanguage = $GLOBALS['TL_LANGUAGE'];
     }
     // Recursively translate label array
     if (is_array($varLabel)) {
         foreach ($varLabel as $k => $v) {
             $varLabel[$k] = static::get($v, $strLanguage);
         }
         return $varLabel;
     }
     // Load labels
     static::initialize($strLanguage);
     if (isset(static::$arrLabels[$strLanguage][$varLabel])) {
         static::$arrLabels[$strLanguage][$varLabel] = \String::decodeEntities(static::$arrLabels[$strLanguage][$varLabel]);
         return static::$arrLabels[$strLanguage][$varLabel];
     }
     return $varLabel;
 }
예제 #10
0
파일: Comments.php 프로젝트: rikaix/core
 /**
  * Add comments to a template
  * @param \FrontendTemplate
  * @param \stdClass
  * @param string
  * @param integer
  * @param array
  */
 public function addCommentsToTemplate(\FrontendTemplate $objTemplate, \stdClass $objConfig, $strSource, $intParent, $arrNotifies)
 {
     global $objPage;
     $limit = 0;
     $offset = 0;
     $total = 0;
     $gtotal = 0;
     $arrComments = array();
     $objTemplate->comments = array();
     // see #4064
     // Pagination
     if ($objConfig->perPage > 0) {
         // Get the total number of comments
         $intTotal = \CommentsModel::countPublishedBySourceAndParent($strSource, $intParent);
         $total = $gtotal = $intTotal;
         // Get the current page
         $id = 'page_c' . $this->id;
         $page = \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 / $objConfig->perPage), 1)) {
             global $objPage;
             $objPage->noSearch = 1;
             $objPage->cache = 0;
             // Send a 404 header
             header('HTTP/1.1 404 Not Found');
             $objTemplate->allowComments = false;
             return;
         }
         // Set limit and offset
         $limit = $objConfig->perPage;
         $offset = ($page - 1) * $objConfig->perPage;
         // Initialize the pagination menu
         $objPagination = new \Pagination($total, $objConfig->perPage, 7, $id);
         $objTemplate->pagination = $objPagination->generate("\n  ");
     }
     $objTemplate->allowComments = true;
     // Get all published comments
     if ($limit) {
         $objComments = \CommentsModel::findPublishedBySourceAndParent($strSource, $intParent, $limit, $offset);
     } else {
         $objComments = \CommentsModel::findPublishedBySourceAndParent($strSource, $intParent);
     }
     if ($objComments !== null && ($total = $objComments->count()) > 0) {
         $count = 0;
         if ($objConfig->template == '') {
             $objConfig->template = 'com_default';
         }
         $objPartial = new \FrontendTemplate($objConfig->template);
         while ($objComments->next()) {
             $objPartial->setData($objComments->row());
             // Clean the RTE output
             if ($objPage->outputFormat == 'xhtml') {
                 $objComments->comment = \String::toXhtml($objComments->comment);
             } else {
                 $objComments->comment = \String::toHtml5($objComments->comment);
             }
             $objPartial->comment = trim(str_replace(array('{{', '}}'), array('&#123;&#123;', '&#125;&#125;'), $objComments->comment));
             $objPartial->datim = $this->parseDate($objPage->datimFormat, $objComments->date);
             $objPartial->date = $this->parseDate($objPage->dateFormat, $objComments->date);
             $objPartial->class = ($count < 1 ? ' first' : '') . ($count >= $total - 1 ? ' last' : '') . ($count % 2 == 0 ? ' even' : ' odd');
             $objPartial->by = $GLOBALS['TL_LANG']['MSC']['comment_by'];
             $objPartial->id = 'c' . $objComments->id;
             $objPartial->timestamp = $objComments->date;
             $objPartial->datetime = date('Y-m-d\\TH:i:sP', $objComments->date);
             $objPartial->addReply = false;
             // Reply
             if ($objComments->addReply && $objComments->reply != '') {
                 if (($objAuthor = $objComments->getRelated('author')) !== null) {
                     $objPartial->addReply = true;
                     $objPartial->rby = $GLOBALS['TL_LANG']['MSC']['reply_by'];
                     $objPartial->reply = $this->replaceInsertTags($objComments->reply);
                     $objPartial->author = $objAuthor;
                     // Clean the RTE output
                     if ($objPage->outputFormat == 'xhtml') {
                         $objPartial->reply = \String::toXhtml($objPartial->reply);
                     } else {
                         $objPartial->reply = \String::toHtml5($objPartial->reply);
                     }
                 }
             }
             $arrComments[] = $objPartial->parse();
             ++$count;
         }
     }
     $objTemplate->comments = $arrComments;
     $objTemplate->addComment = $GLOBALS['TL_LANG']['MSC']['addComment'];
     $objTemplate->name = $GLOBALS['TL_LANG']['MSC']['com_name'];
     $objTemplate->email = $GLOBALS['TL_LANG']['MSC']['com_email'];
     $objTemplate->website = $GLOBALS['TL_LANG']['MSC']['com_website'];
     $objTemplate->commentsTotal = $limit ? $gtotal : $total;
     // Get the front end user object
     $this->import('FrontendUser', 'User');
     // Access control
     if ($objConfig->requireLogin && !BE_USER_LOGGED_IN && !FE_USER_LOGGED_IN) {
         $objTemplate->requireLogin = true;
         return;
     }
     // Form fields
     $arrFields = array('name' => array('name' => 'name', 'label' => $GLOBALS['TL_LANG']['MSC']['com_name'], 'value' => trim($this->User->firstname . ' ' . $this->User->lastname), 'inputType' => 'text', 'eval' => array('mandatory' => true, 'maxlength' => 64)), 'email' => array('name' => 'email', 'label' => $GLOBALS['TL_LANG']['MSC']['com_email'], 'value' => $this->User->email, 'inputType' => 'text', 'eval' => array('rgxp' => 'email', 'mandatory' => true, 'maxlength' => 128, 'decodeEntities' => true)), 'website' => array('name' => 'website', 'label' => $GLOBALS['TL_LANG']['MSC']['com_website'], 'inputType' => 'text', 'eval' => array('rgxp' => 'url', 'maxlength' => 128, 'decodeEntities' => true)));
     // Captcha
     if (!$objConfig->disableCaptcha) {
         $arrFields['captcha'] = array('name' => 'captcha', 'inputType' => 'captcha', 'eval' => array('mandatory' => true));
     }
     // Comment field
     $arrFields['comment'] = array('name' => 'comment', 'label' => $GLOBALS['TL_LANG']['MSC']['com_comment'], 'inputType' => 'textarea', 'eval' => array('mandatory' => true, 'rows' => 4, 'cols' => 40, 'preserveTags' => true));
     $doNotSubmit = false;
     $arrWidgets = array();
     $strFormId = 'com_' . $strSource . '_' . $intParent;
     // Initialize widgets
     foreach ($arrFields as $arrField) {
         $strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
         // Continue if the class is not defined
         if (!$this->classFileExists($strClass)) {
             continue;
         }
         $arrField['eval']['required'] = $arrField['eval']['mandatory'];
         $objWidget = new $strClass($this->prepareForWidget($arrField, $arrField['name'], $arrField['value']));
         // Validate the widget
         if (\Input::post('FORM_SUBMIT') == $strFormId) {
             $objWidget->validate();
             if ($objWidget->hasErrors()) {
                 $doNotSubmit = true;
             }
         }
         $arrWidgets[$arrField['name']] = $objWidget;
     }
     $objTemplate->fields = $arrWidgets;
     $objTemplate->submit = $GLOBALS['TL_LANG']['MSC']['com_submit'];
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->messages = '';
     // Backwards compatibility
     $objTemplate->formId = $strFormId;
     $objTemplate->hasError = $doNotSubmit;
     // Do not index or cache the page with the confirmation message
     if ($_SESSION['TL_COMMENT_ADDED']) {
         global $objPage;
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['com_confirm'];
         $_SESSION['TL_COMMENT_ADDED'] = false;
     }
     // Add the comment
     if (!$doNotSubmit && \Input::post('FORM_SUBMIT') == $strFormId) {
         $strWebsite = $arrWidgets['website']->value;
         // Add http:// to the website
         if ($strWebsite != '' && !preg_match('@^(https?://|ftp://|mailto:|#)@i', $strWebsite)) {
             $strWebsite = 'http://' . $strWebsite;
         }
         // Do not parse any tags in the comment
         $strComment = htmlspecialchars(trim($arrWidgets['comment']->value));
         $strComment = str_replace(array('&amp;', '&lt;', '&gt;'), array('[&]', '[lt]', '[gt]'), $strComment);
         // Remove multiple line feeds
         $strComment = preg_replace('@\\n\\n+@', "\n\n", $strComment);
         // Parse BBCode
         if ($objConfig->bbcode) {
             $strComment = $this->parseBbCode($strComment);
         }
         // Prevent cross-site request forgeries
         $strComment = preg_replace('/(href|src|on[a-z]+)="[^"]*(contao\\/main\\.php|typolight\\/main\\.php|javascript|vbscri?pt|script|alert|document|cookie|window)[^"]*"+/i', '$1="#"', $strComment);
         $time = time();
         // Prepare the record
         $arrSet = array('source' => $strSource, 'parent' => $intParent, 'tstamp' => $time, 'name' => $arrWidgets['name']->value, 'email' => $arrWidgets['email']->value, 'website' => $strWebsite, 'comment' => $this->convertLineFeeds($strComment), 'ip' => $this->anonymizeIp(\Environment::get('ip')), 'date' => $time, 'published' => $objConfig->moderate ? '' : 1);
         $objComment = new \CommentsModel();
         $objComment->setRow($arrSet);
         $objComment->save();
         $insertId = $objComment->id;
         // HOOK: add custom logic
         if (isset($GLOBALS['TL_HOOKS']['addComment']) && is_array($GLOBALS['TL_HOOKS']['addComment'])) {
             foreach ($GLOBALS['TL_HOOKS']['addComment'] as $callback) {
                 $this->import($callback[0]);
                 $this->{$callback}[0]->{$callback}[1]($insertId, $arrSet, $this);
             }
         }
         // Notification
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['com_subject'], \Environment::get('host'));
         // Convert the comment to plain text
         $strComment = strip_tags($strComment);
         $strComment = \String::decodeEntities($strComment);
         $strComment = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strComment);
         // Add comment details
         $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['com_message'], $arrSet['name'] . ' (' . $arrSet['email'] . ')', $strComment, \Environment::get('base') . \Environment::get('request'), \Environment::get('base') . 'contao/main.php?do=comments&act=edit&id=' . $insertId);
         // Do not send notifications twice
         if (is_array($arrNotifies)) {
             $arrNotifies = array_unique($arrNotifies);
         }
         $objEmail->sendTo($arrNotifies);
         // Pending for approval
         if ($objConfig->moderate) {
             $_SESSION['TL_COMMENT_ADDED'] = true;
         }
         $this->reload();
     }
 }
예제 #11
0
 public function export($strMode = 'csv')
 {
     if (strlen(\Input::get('expmode'))) {
         $strMode = \Input::get('expmode');
     }
     $return = '';
     $blnCustomXlsExport = false;
     $blnCustomExport = false;
     $arrHookData = array();
     $arrHookDataColumns = array();
     if ($strMode == 'xls') {
         // Check for HOOK efgExportXls
         if (array_key_exists('efgExportXls', $GLOBALS['TL_HOOKS']) && is_array($GLOBALS['TL_HOOKS']['efgExportXls'])) {
             $blnCustomXlsExport = true;
         }
     } elseif ($strMode != 'csv') {
         $blnCustomExport = true;
     }
     // filter or search for values
     $session = $this->Session->getData();
     $showFields = array_merge($this->arrBaseFields, $this->arrDetailFields);
     $ignoreFields = array('tstamp');
     if (!empty($this->arrExportIgnoreFields)) {
         $ignoreFields = array_unique(array_merge($ignoreFields, $this->arrExportIgnoreFields));
     }
     $table = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 6 ? $this->ptable : $this->strTable;
     $table_alias = $table == 'tl_formdata' ? ' f' : '';
     $orderBy = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['fields'];
     $firstOrderBy = preg_replace('/\\s+.*$/i', '', $orderBy[0]);
     if (is_array($this->orderBy) && strlen($this->orderBy[0])) {
         $orderBy = $this->orderBy;
         $firstOrderBy = $this->firstOrderBy;
     }
     if (\Input::get('table') && $GLOBALS['TL_DCA'][$this->strTable]['config']['ptable'] && \Database::getInstance()->fieldExists('pid', $this->strTable)) {
         $this->procedure[] = 'pid=?';
         $this->values[] = \Input::get('id');
     }
     $query = "SELECT * " . (!empty($this->arrSqlDetails) ? ', ' . implode(',', array_values($this->arrSqlDetails)) : '') . " FROM " . $this->strTable . $table_alias;
     $sqlWhere = '';
     // Set search value from session
     $strSessionKey = $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 4 ? $this->strTable . '_' . CURRENT_ID : strlen($this->strFormKey) ? $this->strFormKey : $this->strTable;
     if (strlen($session['search'][$strSessionKey]['value'])) {
         $sqlSearchField = $session['search'][$strSessionKey]['field'];
         if (in_array($sqlSearchField, $this->arrDetailFields)) {
             $sqlSearchField = '(SELECT value FROM tl_formdata_details WHERE ff_name=\'' . $session['search'][$strSessionKey]['field'] . '\' AND pid=f.id)';
         }
         $this->procedure[] = "CAST(" . $sqlSearchField . " AS CHAR) REGEXP ?";
         $this->values[] = $session['search'][$strSessionKey]['value'];
     }
     // Set filter from session
     $arrFilterFields = array();
     foreach ($GLOBALS['TL_DCA'][$this->strTable]['fields'] as $k => $v) {
         if ($v['filter']) {
             $arrFilterFields[] = $k;
         }
     }
     if (!empty($arrFilterFields)) {
         foreach ($arrFilterFields as $field) {
             if (isset($session['filter'][$strSessionKey][$field])) {
                 $sqlFilterField = $field;
                 if (in_array($field, $this->arrDetailFields)) {
                     $sqlFilterField = '(SELECT value FROM tl_formdata_details WHERE ff_name=\'' . $field . '\' AND pid=f.id)';
                 }
                 // Sort by day
                 if (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(5, 6))) {
                     if ($session['filter'][$strSessionKey][$field] == '') {
                         $this->procedure[] = $sqlFilterField . "=''";
                     } else {
                         $objDate = new \Date($session['filter'][$strSessionKey][$field]);
                         $this->procedure[] = $sqlFilterField . ' BETWEEN ? AND ?';
                         $this->values[] = $objDate->dayBegin;
                         $this->values[] = $objDate->dayEnd;
                     }
                 } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(7, 8))) {
                     if ($session['filter'][$strSessionKey][$field] == '') {
                         $this->procedure[] = $sqlFilterField . "=''";
                     } else {
                         $objDate = new \Date($session['filter'][$strSessionKey][$field]);
                         $this->procedure[] = $sqlFilterField . ' BETWEEN ? AND ?';
                         $this->values[] = $objDate->monthBegin;
                         $this->values[] = $objDate->monthEnd;
                     }
                 } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['flag'], array(9, 10))) {
                     if ($session['filter'][$strSessionKey][$field] == '') {
                         $this->procedure[] = $sqlFilterField . "=''";
                     } else {
                         $objDate = new \Date($session['filter'][$strSessionKey][$field]);
                         $this->procedure[] = $sqlFilterField . ' BETWEEN ? AND ?';
                         $this->values[] = $objDate->yearBegin;
                         $this->values[] = $objDate->yearEnd;
                     }
                 } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$field]['eval']['multiple']) {
                     $this->procedure[] = $sqlFilterField . ' LIKE ?';
                     $this->values[] = '%"' . $session['filter'][$strSessionKey][$field] . '"%';
                 } else {
                     $this->procedure[] = $sqlFilterField . '=?';
                     $this->values[] = $session['filter'][$strSessionKey][$field];
                 }
             }
         }
     }
     if (!empty($this->procedure)) {
         $arrProcedure = $this->procedure;
         foreach ($arrProcedure as $kProc => $vProc) {
             $strProcField = substr($vProc, 0, strpos($vProc, '='));
             if (in_array($strProcField, $this->arrDetailFields)) {
                 $arrProcedure[$kProc] = "(SELECT value FROM tl_formdata_details WHERE ff_name='" . $strProcField . "' AND pid=f.id)=?";
             }
         }
         $sqlWhere .= ($sqlWhere != '' ? " AND " : " WHERE ") . implode(' AND ', $arrProcedure);
     }
     if ($sqlWhere != '') {
         $query .= $sqlWhere;
     }
     if (is_array($orderBy) && strlen($orderBy[0])) {
         foreach ($orderBy as $o => $strVal) {
             $arrOrderField = explode(' ', $strVal);
             $strOrderField = $arrOrderField[0];
             unset($arrOrderField);
             if (!in_array($strOrderField, $this->arrBaseFields)) {
                 $orderBy[$o] = "(SELECT value FROM tl_formdata_details WHERE ff_name='" . $strOrderField . "' AND pid=f.id)";
             }
         }
         $query .= " ORDER BY " . implode(', ', $orderBy);
     }
     if ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 1 && $GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['flag'] % 2 == 0) {
         $query .= " DESC";
     }
     $objRowStmt = \Database::getInstance()->prepare($query);
     $objRow = $objRowStmt->execute($this->values);
     $intRowCounter = -1;
     $strExpEncl = '';
     $strExpSep = ';';
     $useFormValues = $this->Formdata->arrStoringForms[substr($this->strFormKey, 3)]['useFormValues'];
     $useFieldNames = $this->Formdata->arrStoringForms[substr($this->strFormKey, 3)]['useFieldNames'];
     if ($strMode == 'csv') {
         header('Content-Type: appplication/csv; charset=' . ($this->blnExportUTF8Decode ? $this->strExportConvertToCharset : 'utf-8'));
         header('Content-Transfer-Encoding: binary');
         header('Content-Disposition: attachment; filename="export_' . $this->strFormKey . '_' . date("Ymd_His") . '.csv"');
         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
         header('Pragma: public');
         header('Expires: 0');
     } elseif ($strMode == 'xls') {
         if (!$blnCustomXlsExport) {
             $xls = new \xlsexport();
             $strXlsSheet = "Export";
             $xls->addworksheet($strXlsSheet);
         }
     }
     // List records
     if ($objRow->numRows) {
         $result = $objRow->fetchAllAssoc();
         // Rename each pid to its label and resort the result (sort by parent table)
         if ($GLOBALS['TL_DCA'][$this->strTable]['list']['sorting']['mode'] == 3 && \Database::getInstance()->fieldExists('pid', $this->strTable)) {
             $firstOrderBy = 'pid';
             foreach ($result as $k => $v) {
                 $objField = \Database::getInstance()->prepare("SELECT " . $showFields[0] . " FROM " . $this->ptable . " WHERE id=?")->limit(1)->execute($v['pid']);
                 $result[$k]['pid'] = $objField->{$showFields}[0];
             }
             $aux = array();
             foreach ($result as $row) {
                 $aux[] = $row['pid'];
             }
             array_multisort($aux, SORT_ASC, $result);
         }
         // Process result and format values
         foreach ($result as $row) {
             $intRowCounter++;
             $args = array();
             $this->current[] = $row['id'];
             if ($intRowCounter == 0) {
                 if ($strMode == 'xls') {
                     if (!$blnCustomXlsExport) {
                         $xls->totalcol = count($showFields);
                     }
                 }
                 $strExpEncl = '"';
                 $strExpSep = '';
                 $intColCounter = -1;
                 foreach ($showFields as $k => $v) {
                     if (in_array($v, $ignoreFields)) {
                         continue;
                     }
                     $intColCounter++;
                     if ($useFieldNames) {
                         $strName = $v;
                     } elseif (strlen($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['label'][0])) {
                         $strName = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['label'][0];
                     } elseif (strlen($GLOBALS['TL_LANG']['tl_formdata'][$v][0])) {
                         $strName = $GLOBALS['TL_LANG']['tl_formdata'][$v][0];
                     } else {
                         $strName = strtoupper($v);
                     }
                     if (strlen($strName)) {
                         $strName = \String::decodeEntities($strName);
                     }
                     if ($this->blnExportUTF8Decode || $strMode == 'xls' && !$blnCustomXlsExport) {
                         $strName = $this->convertEncoding($strName, $GLOBALS['TL_CONFIG']['characterSet'], $this->strExportConvertToCharset);
                     }
                     if ($strMode == 'csv') {
                         $strName = str_replace('"', '""', $strName);
                         echo $strExpSep . $strExpEncl . $strName . $strExpEncl;
                         $strExpSep = ";";
                     } elseif ($strMode == 'xls') {
                         if (!$blnCustomXlsExport) {
                             $xls->setcell(array("sheetname" => $strXlsSheet, "row" => $intRowCounter, "col" => $intColCounter, "data" => $strName, "fontweight" => XLSFONT_BOLD, "vallign" => XLSXF_VALLIGN_TOP, "fontfamily" => XLSFONT_FAMILY_NORMAL));
                             $xls->setcolwidth($strXlsSheet, $intColCounter, 0x1aff);
                         } else {
                             $arrHookDataColumns[$v] = $strName;
                         }
                     } elseif ($blnCustomExport) {
                         $arrHookDataColumns[$v] = $strName;
                     }
                 }
                 $intRowCounter++;
                 if ($strMode == 'csv') {
                     echo "\n";
                 }
             }
             $strExpSep = '';
             $intColCounter = -1;
             // Prepare field value
             foreach ($showFields as $k => $v) {
                 if (in_array($v, $ignoreFields)) {
                     continue;
                 }
                 $intColCounter++;
                 $strVal = '';
                 $strVal = $row[$v];
                 if ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['inputType'] == 'date' && in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['flag'], array(5, 6, 7, 8, 9, 10))) {
                     $strVal = $row[$v] ? date($GLOBALS['TL_CONFIG']['dateFormat'], $row[$v]) : '';
                 } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['inputType'] == 'datim' && in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['flag'], array(5, 6, 7, 8, 9, 10))) {
                     $strVal = $row[$v] ? date($GLOBALS['TL_CONFIG']['datimFormat'], $row[$v]) : '';
                 } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['flag'], array(5, 6, 7, 8, 9, 10))) {
                     $strVal = $row[$v] ? date($GLOBALS['TL_CONFIG']['datimFormat'], $row[$v]) : '';
                 } elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['inputType'] == 'checkbox' && !$GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['multiple']) {
                     if (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options']) && count($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options']) > 0) {
                         if ($row[$v] != '') {
                             if (!$useFormValues) {
                                 $strVal = $row[$v];
                             } else {
                                 $arrCbOpt = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options'];
                                 $arrCbOpt = array_flip($arrCbOpt);
                                 $strVal = $arrCbOpt[$row[$v]];
                             }
                         } else {
                             $strVal = '';
                         }
                     } else {
                         $strVal = $row[$v] != '' ? $GLOBALS['TL_LANG']['MSC']['yes'] : $GLOBALS['TL_LANG']['MSC']['no'];
                     }
                 } elseif (in_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['inputType'], array('radio', 'efgLookupRadio', 'select', 'conditionalselect', 'efgLookupSelect', 'checkbox', 'efgLookupCheckbox'))) {
                     $strSep = isset($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['csv']) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['csv'] : '|';
                     // take the assigned value instead of the user readable output
                     if ($useFormValues == 1) {
                         if (strpos($row[$v], $strSep) === false && (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options']) && count($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options']) > 0)) {
                             // handle grouped options
                             $arrOptions = array();
                             foreach ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options'] as $o => $mxVal) {
                                 if (!is_array($mxVal)) {
                                     $arrOptions[$o] = $mxVal;
                                 } else {
                                     foreach ($mxVal as $ov => $mxOVal) {
                                         $arrOptions[$ov] = $mxOVal;
                                     }
                                 }
                             }
                             $options = array_flip($arrOptions);
                             $strVal = $options[$row[$v]];
                         } else {
                             if (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options']) && count($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options']) > 0) {
                                 // handle grouped options
                                 $arrOptions = array();
                                 foreach ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['options'] as $o => $mxVal) {
                                     if (!is_array($mxVal)) {
                                         $arrOptions[$o] = $mxVal;
                                     } else {
                                         foreach ($mxVal as $ov => $mxOVal) {
                                             $arrOptions[$ov] = $mxOVal;
                                         }
                                     }
                                 }
                                 $options = array_flip($arrOptions);
                                 $tmparr = explode($strSep, $row[$v]);
                                 $fieldvalues = array();
                                 foreach ($tmparr as $valuedesc) {
                                     array_push($fieldvalues, $options[$valuedesc]);
                                 }
                                 $strVal = implode(",\n", $fieldvalues);
                             } else {
                                 $strVal = strlen($row[$v]) ? str_replace($strSep, ",\n", $row[$v]) : '';
                             }
                         }
                     } else {
                         $strVal = strlen($row[$v]) ? str_replace($strSep, ",\n", $row[$v]) : '';
                     }
                 } else {
                     $row_v = deserialize($row[$v]);
                     if (!empty($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['csv'])) {
                         $row_v = explode($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['eval']['csv'], $row[$v]);
                     }
                     if (is_array($row_v)) {
                         $args_k = array();
                         foreach ($row_v as $option) {
                             $args_k[] = strlen($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['reference'][$option]) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['reference'][$option] : $option;
                         }
                         $args[$k] = implode(",\n", $args_k);
                     } elseif (is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['reference'][$row[$v]])) {
                         $args[$k] = is_array($GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['reference'][$row[$v]]) ? $GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['reference'][$row[$v]][0] : $GLOBALS['TL_DCA'][$this->strTable]['fields'][$v]['reference'][$row[$v]];
                     } else {
                         $args[$k] = $row[$v];
                     }
                     $strVal = is_null($args[$k]) ? $args[$k] : vsprintf('%s', $args[$k]);
                 }
                 if (in_array($v, $this->arrBaseFields) || in_array($v, $this->arrOwnerFields)) {
                     if ($v == 'fd_member') {
                         $strVal = $this->arrMembers[intval($row[$v])];
                     } elseif ($v == 'fd_user') {
                         $strVal = $this->arrUsers[intval($row[$v])];
                     } elseif ($v == 'fd_member_group') {
                         $strVal = $this->arrMemberGroups[intval($row[$v])];
                     } elseif ($v == 'fd_user_group') {
                         $strVal = $this->arrUserGroups[intval($row[$v])];
                     }
                 }
                 if (strlen($strVal)) {
                     $strVal = \String::decodeEntities($strVal);
                     $strVal = preg_replace(array('/<br.*\\/*>/si'), array("\n"), $strVal);
                     if ($this->blnExportUTF8Decode || $strMode == 'xls' && !$blnCustomXlsExport) {
                         $strVal = $this->convertEncoding($strVal, $GLOBALS['TL_CONFIG']['characterSet'], $this->strExportConvertToCharset);
                     }
                 }
                 if ($strMode == 'csv') {
                     $strVal = str_replace('"', '""', $strVal);
                     echo $strExpSep . $strExpEncl . $strVal . $strExpEncl;
                     $strExpSep = ";";
                 } elseif ($strMode == 'xls') {
                     if (!$blnCustomXlsExport) {
                         $xls->setcell(array("sheetname" => $strXlsSheet, "row" => $intRowCounter, "col" => $intColCounter, "data" => $strVal, "vallign" => XLSXF_VALLIGN_TOP, "fontfamily" => XLSFONT_FAMILY_NORMAL));
                     } else {
                         $arrHookData[$intRowCounter][$v] = $strVal;
                     }
                 } elseif ($blnCustomExport) {
                     $arrHookData[$intRowCounter][$v] = $strVal;
                 }
             }
             if ($strMode == 'csv') {
                 $strExpSep = '';
                 echo "\n";
             }
         }
     }
     if ($strMode == 'xls') {
         if (!$blnCustomXlsExport) {
             $xls->sendfile("export_" . $this->strFormKey . "_" . date("Ymd_His") . ".xls");
             exit;
         } else {
             foreach ($GLOBALS['TL_HOOKS']['efgExportXls'] as $key => $callback) {
                 $this->import($callback[0]);
                 $res = $this->{$callback}[0]->{$callback}[1]($arrHookDataColumns, $arrHookData);
             }
         }
     } elseif ($blnCustomExport) {
         foreach ($GLOBALS['TL_HOOKS']['efgExport'] as $key => $callback) {
             $this->import($callback[0]);
             $res = $this->{$callback}[0]->{$callback}[1]($arrHookDataColumns, $arrHookData, $strMode);
         }
     }
     exit;
 }
예제 #12
0
파일: Email.php 프로젝트: juergen83/contao
 /**
  * Set an object property
  *
  * @param string $strKey   The property name
  * @param mixed  $varValue The property value
  *
  * @throws \Exception If $strKey is unknown
  */
 public function __set($strKey, $varValue)
 {
     switch ($strKey) {
         case 'subject':
             $this->strSubject = preg_replace(array('/[\\t]+/', '/[\\n\\r]+/'), array(' ', ''), $varValue);
             break;
         case 'text':
             $this->strText = \String::decodeEntities($varValue);
             break;
         case 'html':
             $this->strHtml = $varValue;
             break;
         case 'from':
             $this->strSender = $varValue;
             break;
         case 'fromName':
             $this->strSenderName = $varValue;
             break;
         case 'priority':
             switch ($varValue) {
                 case 1:
                 case 'highest':
                     $this->intPriority = 1;
                     break;
                 case 2:
                 case 'high':
                     $this->intPriority = 2;
                     break;
                 case 3:
                 case 'normal':
                     $this->intPriority = 3;
                     break;
                 case 4:
                 case 'low':
                     $this->intPriority = 4;
                     break;
                 case 5:
                 case 'lowest':
                     $this->intPriority = 5;
                     break;
             }
             break;
         case 'charset':
             $this->strCharset = $varValue;
             break;
         case 'imageDir':
             $this->strImageDir = $varValue;
             break;
         case 'embedImages':
             $this->blnEmbedImages = $varValue;
             break;
         case 'logFile':
             $this->strLogFile = $varValue;
             break;
         default:
             throw new \Exception(sprintf('Invalid argument "%s"', $strKey));
             break;
     }
 }
예제 #13
0
 /**
  * Compile format definitions and return them as string
  *
  * @param array   $row
  * @param boolean $blnWriteToFile
  * @param array   $vars
  * @param array   $parent
  * @param boolean $export
  *
  * @return string
  */
 public function compileDefinition($row, $blnWriteToFile = false, $vars = array(), $parent = array(), $export = false)
 {
     if ($blnWriteToFile) {
         $strGlue = '../../';
         $lb = '';
         $return = '';
     } elseif ($export) {
         $strGlue = '';
         $lb = "\n    ";
         $return = '';
     } else {
         $strGlue = '';
         $lb = "\n    ";
         $return = "\n" . '<pre' . ($row['invisible'] ? ' class="disabled"' : '') . '>';
     }
     $blnNeedsPie = false;
     // Comment
     if ((!$blnWriteToFile || $export) && $row['comment'] != '') {
         $search = array('@^\\s*/\\*+@', '@\\*+/\\s*$@');
         $comment = preg_replace($search, '', $row['comment']);
         if ($export) {
             $return .= "\n/* " . $comment . " */\n";
         } else {
             $comment = wordwrap(trim($comment), 72);
             $return .= "\n" . '<span class="comment">' . $comment . '</span>' . "\n";
         }
     }
     // Selector
     $arrSelector = trimsplit(',', \String::decodeEntities($row['selector']));
     $return .= implode($blnWriteToFile ? ',' : ",\n", $arrSelector) . ($blnWriteToFile ? '' : ' ') . '{';
     // Size
     if ($row['size']) {
         // Width
         $row['width'] = deserialize($row['width']);
         if (isset($row['width']['value']) && $row['width']['value'] != '') {
             $return .= $lb . 'width:' . $row['width']['value'] . ($row['width']['value'] == 'auto' ? '' : $row['width']['unit']) . ';';
         }
         // Height
         $row['height'] = deserialize($row['height']);
         if (isset($row['height']['value']) && $row['height']['value'] != '') {
             $return .= $lb . 'height:' . $row['height']['value'] . ($row['height']['value'] == 'auto' ? '' : $row['height']['unit']) . ';';
         }
         // Min-width
         $row['minwidth'] = deserialize($row['minwidth']);
         if (isset($row['minwidth']['value']) && $row['minwidth']['value'] != '') {
             $return .= $lb . 'min-width:' . $row['minwidth']['value'] . ($row['minwidth']['value'] == 'inherit' ? '' : $row['minwidth']['unit']) . ';';
         }
         // Min-height
         $row['minheight'] = deserialize($row['minheight']);
         if (isset($row['minheight']['value']) && $row['minheight']['value'] != '') {
             $return .= $lb . 'min-height:' . $row['minheight']['value'] . ($row['minheight']['value'] == 'inherit' ? '' : $row['minheight']['unit']) . ';';
         }
         // Max-width
         $row['maxwidth'] = deserialize($row['maxwidth']);
         if (isset($row['maxwidth']['value']) && $row['maxwidth']['value'] != '') {
             $return .= $lb . 'max-width:' . $row['maxwidth']['value'] . ($row['maxwidth']['value'] == 'inherit' || $row['maxwidth']['value'] == 'none' ? '' : $row['maxwidth']['unit']) . ';';
         }
         // Max-height
         $row['maxheight'] = deserialize($row['maxheight']);
         if (isset($row['maxheight']['value']) && $row['maxheight']['value'] != '') {
             $return .= $lb . 'max-height:' . $row['maxheight']['value'] . ($row['maxheight']['value'] == 'inherit' || $row['maxheight']['value'] == 'none' ? '' : $row['maxheight']['unit']) . ';';
         }
     }
     // Position
     if ($row['positioning']) {
         // Top/right/bottom/left
         $row['trbl'] = deserialize($row['trbl']);
         if (is_array($row['trbl'])) {
             foreach ($row['trbl'] as $k => $v) {
                 if ($v != '' && $k != 'unit') {
                     $return .= $lb . $k . ':' . $v . ($v == 'auto' || $v === '0' ? '' : $row['trbl']['unit']) . ';';
                 }
             }
         }
         // Position
         if ($row['position'] != '') {
             $return .= $lb . 'position:' . $row['position'] . ';';
         }
         // Overflow
         if ($row['overflow'] != '') {
             $return .= $lb . 'overflow:' . $row['overflow'] . ';';
         }
         // Float
         if ($row['floating'] != '') {
             $return .= $lb . 'float:' . $row['floating'] . ';';
         }
         // Clear
         if ($row['clear'] != '') {
             $return .= $lb . 'clear:' . $row['clear'] . ';';
         }
         // Display
         if ($row['display'] != '') {
             $return .= $lb . 'display:' . $row['display'] . ';';
         }
     }
     // Margin, padding and alignment
     if ($row['alignment']) {
         // Margin
         if ($row['margin'] != '' || $row['align'] != '') {
             $row['margin'] = deserialize($row['margin']);
             if (is_array($row['margin'])) {
                 $top = $row['margin']['top'];
                 $right = $row['margin']['right'];
                 $bottom = $row['margin']['bottom'];
                 $left = $row['margin']['left'];
                 // Overwrite the left and right margin if an alignment is set
                 if ($row['align'] != '') {
                     if ($row['align'] == 'left' || $row['align'] == 'center') {
                         $right = 'auto';
                     }
                     if ($row['align'] == 'right' || $row['align'] == 'center') {
                         $left = 'auto';
                     }
                 }
                 // Try to shorten the definition
                 if ($top != '' && $right != '' && $bottom != '' && $left != '') {
                     if ($top == $right && $top == $bottom && $top == $left) {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ';';
                     } elseif ($top == $bottom && $right == $left) {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ' ' . $right . ($right == 'auto' || $right === '0' ? '' : $row['margin']['unit']) . ';';
                     } elseif ($top != $bottom && $right == $left) {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ' ' . $right . ($right == 'auto' || $right === '0' ? '' : $row['margin']['unit']) . ' ' . $bottom . ($bottom == 'auto' || $bottom === '0' ? '' : $row['margin']['unit']) . ';';
                     } else {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ' ' . $right . ($right == 'auto' || $right === '0' ? '' : $row['margin']['unit']) . ' ' . $bottom . ($bottom == 'auto' || $bottom === '0' ? '' : $row['margin']['unit']) . ' ' . $left . ($left == 'auto' || $left === '0' ? '' : $row['margin']['unit']) . ';';
                     }
                 } else {
                     $arrDir = array('top' => $top, 'right' => $right, 'bottom' => $bottom, 'left' => $left);
                     foreach ($arrDir as $k => $v) {
                         if ($v != '') {
                             $return .= $lb . 'margin-' . $k . ':' . $v . ($v == 'auto' || $v === '0' ? '' : $row['margin']['unit']) . ';';
                         }
                     }
                 }
             }
         }
         // Padding
         if ($row['padding'] != '') {
             $row['padding'] = deserialize($row['padding']);
             if (is_array($row['padding'])) {
                 $top = $row['padding']['top'];
                 $right = $row['padding']['right'];
                 $bottom = $row['padding']['bottom'];
                 $left = $row['padding']['left'];
                 // Try to shorten the definition
                 if ($top != '' && $right != '' && $bottom != '' && $left != '') {
                     if ($top == $right && $top == $bottom && $top == $left) {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ';';
                     } elseif ($top == $bottom && $right == $left) {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['padding']['unit']) . ';';
                     } elseif ($top != $bottom && $right == $left) {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['padding']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['padding']['unit']) . ';';
                     } else {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['padding']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['padding']['unit']) . ' ' . $left . ($left === '0' ? '' : $row['padding']['unit']) . ';';
                     }
                 } else {
                     $arrDir = array('top' => $top, 'right' => $right, 'bottom' => $bottom, 'left' => $left);
                     foreach ($arrDir as $k => $v) {
                         if ($v != '') {
                             $return .= $lb . 'padding-' . $k . ':' . $v . ($v === '0' ? '' : $row['padding']['unit']) . ';';
                         }
                     }
                 }
             }
         }
         // Vertical alignment
         if ($row['verticalalign'] != '') {
             $return .= $lb . 'vertical-align:' . $row['verticalalign'] . ';';
         }
         // Text alignment
         if ($row['textalign'] != '') {
             $return .= $lb . 'text-align:' . $row['textalign'] . ';';
         }
         // White space
         if ($row['whitespace'] != '') {
             $return .= $lb . 'white-space:' . $row['whitespace'] . ';';
         }
     }
     // Background
     if ($row['background']) {
         $bgColor = deserialize($row['bgcolor'], true);
         // Try to shorten the definition
         if ($bgColor[0] != '' && $row['bgimage'] != '' && $row['bgposition'] != '' && $row['bgrepeat'] != '') {
             if (($strImage = $this->generateBase64Image($row['bgimage'], $parent)) !== false) {
                 $return .= $lb . 'background:' . $this->compileColor($bgColor, $blnWriteToFile, $vars) . ' url("' . $strImage . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ';';
             } else {
                 $glue = strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0 ? $strGlue : '';
                 $return .= $lb . 'background:' . $this->compileColor($bgColor, $blnWriteToFile, $vars) . ' url("' . $glue . $row['bgimage'] . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ';';
             }
         } else {
             // Background color
             if ($bgColor[0] != '') {
                 $return .= $lb . 'background-color:' . $this->compileColor($bgColor, $blnWriteToFile, $vars) . ';';
             }
             // Background image
             if ($row['bgimage'] == 'none') {
                 $return .= $lb . 'background-image:none;';
             } elseif ($row['bgimage'] != '') {
                 if (($strImage = $this->generateBase64Image($row['bgimage'], $parent)) !== false) {
                     $return .= $lb . 'background-image:url("' . $strImage . '");';
                 } else {
                     $glue = strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0 ? $strGlue : '';
                     $return .= $lb . 'background-image:url("' . $glue . $row['bgimage'] . '");';
                 }
             }
             // Background position
             if ($row['bgposition'] != '') {
                 $return .= $lb . 'background-position:' . $row['bgposition'] . ';';
             }
             // Background repeat
             if ($row['bgrepeat'] != '') {
                 $return .= $lb . 'background-repeat:' . $row['bgrepeat'] . ';';
             }
         }
         // Background gradient
         if ($row['gradientAngle'] != '' && $row['gradientColors'] != '') {
             $row['gradientColors'] = deserialize($row['gradientColors']);
             if (is_array($row['gradientColors']) && count(array_filter($row['gradientColors'])) > 0) {
                 $blnNeedsPie = true;
                 $bgImage = '';
                 // CSS3 PIE only supports -pie-background, so if there is a background image, include it here, too.
                 if ($row['bgimage'] != '' && $row['bgposition'] != '' && $row['bgrepeat'] != '') {
                     $glue = strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0 ? $strGlue : '';
                     $bgImage = 'url("' . $glue . $row['bgimage'] . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ',';
                 }
                 // Default starting point
                 if ($row['gradientAngle'] == '') {
                     $row['gradientAngle'] = 'to top';
                 }
                 $row['gradientColors'] = array_values(array_filter($row['gradientColors']));
                 // Add a hash tag to the color values
                 foreach ($row['gradientColors'] as $k => $v) {
                     $row['gradientColors'][$k] = '#' . $v;
                 }
                 $angle = '';
                 // Convert the angle for the legacy commands (see #4569)
                 if (strpos($row['gradientAngle'], 'deg') !== false) {
                     $angle = abs(intval($row['gradientAngle']) - 450) % 360 . 'deg';
                 } else {
                     switch ($row['gradientAngle']) {
                         case 'to top':
                             $angle = 'bottom';
                             break;
                         case 'to right':
                             $angle = 'left';
                             break;
                         case 'to bottom':
                             $angle = 'top';
                             break;
                         case 'to left':
                             $angle = 'right';
                             break;
                         case 'to top left':
                             $angle = 'bottom right';
                             break;
                         case 'to top right':
                             $angle = 'bottom left';
                             break;
                         case 'to bottom left':
                             $angle = 'top right';
                             break;
                         case 'to bottom right':
                             $angle = 'top left';
                             break;
                     }
                 }
                 $colors = implode(',', $row['gradientColors']);
                 $legacy = $angle . ',' . $colors;
                 $gradient = $row['gradientAngle'] . ',' . $colors;
                 $return .= $lb . 'background:' . $bgImage . '-moz-linear-gradient(' . $legacy . ');';
                 $return .= $lb . 'background:' . $bgImage . '-webkit-linear-gradient(' . $legacy . ');';
                 $return .= $lb . 'background:' . $bgImage . '-o-linear-gradient(' . $legacy . ');';
                 $return .= $lb . 'background:' . $bgImage . '-ms-linear-gradient(' . $legacy . ');';
                 $return .= $lb . 'background:' . $bgImage . 'linear-gradient(' . $gradient . ');';
                 $return .= $lb . '-pie-background:' . $bgImage . 'linear-gradient(' . $legacy . ');';
             }
         }
         // Box shadow
         if ($row['shadowsize'] != '') {
             $shColor = deserialize($row['shadowcolor'], true);
             $row['shadowsize'] = deserialize($row['shadowsize']);
             if (is_array($row['shadowsize']) && $row['shadowsize']['top'] != '' && $row['shadowsize']['right'] != '') {
                 $blnNeedsPie = true;
                 $offsetx = $row['shadowsize']['top'];
                 $offsety = $row['shadowsize']['right'];
                 $blursize = $row['shadowsize']['bottom'];
                 $radius = $row['shadowsize']['left'];
                 $shadow = $offsetx . ($offsetx === '0' ? '' : $row['shadowsize']['unit']);
                 $shadow .= ' ' . $offsety . ($offsety === '0' ? '' : $row['shadowsize']['unit']);
                 if ($blursize != '') {
                     $shadow .= ' ' . $blursize . ($blursize === '0' ? '' : $row['shadowsize']['unit']);
                 }
                 if ($radius != '') {
                     $shadow .= ' ' . $radius . ($radius === '0' ? '' : $row['shadowsize']['unit']);
                 }
                 if ($shColor[0] != '') {
                     $shadow .= ' ' . $this->compileColor($shColor, $blnWriteToFile, $vars);
                 }
                 $shadow .= ';';
                 // Prefix required in Safari <= 5 and Android
                 $return .= $lb . '-webkit-box-shadow:' . $shadow;
                 $return .= $lb . 'box-shadow:' . $shadow;
             }
         }
     }
     // Border
     if ($row['border']) {
         $bdColor = deserialize($row['bordercolor'], true);
         $row['borderwidth'] = deserialize($row['borderwidth']);
         // Border width
         if (is_array($row['borderwidth'])) {
             $top = $row['borderwidth']['top'];
             $right = $row['borderwidth']['right'];
             $bottom = $row['borderwidth']['bottom'];
             $left = $row['borderwidth']['left'];
             // Try to shorten the definition
             if ($top != '' && $right != '' && $bottom != '' && $left != '' && $top == $right && $top == $bottom && $top == $left) {
                 $return .= $lb . 'border:' . $top . $row['borderwidth']['unit'] . ($row['borderstyle'] != '' ? ' ' . $row['borderstyle'] : '') . ($bdColor[0] != '' ? ' ' . $this->compileColor($bdColor, $blnWriteToFile, $vars) : '') . ';';
             } elseif ($top != '' && $right != '' && $bottom != '' && $left != '' && $top == $bottom && $left == $right) {
                 $return .= $lb . 'border-width:' . $top . $row['borderwidth']['unit'] . ' ' . $right . $row['borderwidth']['unit'] . ';';
                 if ($row['borderstyle'] != '') {
                     $return .= $lb . 'border-style:' . $row['borderstyle'] . ';';
                 }
                 if ($bdColor[0] != '') {
                     $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';';
                 }
             } elseif ($top == '' && $right == '' && $bottom == '' && $left == '') {
                 if ($row['borderstyle'] != '') {
                     $return .= $lb . 'border-style:' . $row['borderstyle'] . ';';
                 }
                 if ($bdColor[0] != '') {
                     $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';';
                 }
             } else {
                 $arrDir = array('top' => $top, 'right' => $right, 'bottom' => $bottom, 'left' => $left);
                 foreach ($arrDir as $k => $v) {
                     if ($v != '') {
                         $return .= $lb . 'border-' . $k . ':' . $v . $row['borderwidth']['unit'] . ($row['borderstyle'] != '' ? ' ' . $row['borderstyle'] : '') . ($bdColor[0] != '' ? ' ' . $this->compileColor($bdColor, $blnWriteToFile, $vars) : '') . ';';
                     }
                 }
             }
         } else {
             if ($row['borderstyle'] != '') {
                 $return .= $lb . 'border-style:' . $row['borderstyle'] . ';';
             }
             if ($bdColor[0] != '') {
                 $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';';
             }
         }
         // Border radius
         if ($row['borderradius'] != '') {
             $row['borderradius'] = deserialize($row['borderradius']);
             if (is_array($row['borderradius']) && ($row['borderradius']['top'] != '' || $row['borderradius']['right'] != '' || $row['borderradius']['bottom'] != '' || $row['borderradius']['left'] != '')) {
                 $blnNeedsPie = true;
                 $top = $row['borderradius']['top'];
                 $right = $row['borderradius']['right'];
                 $bottom = $row['borderradius']['bottom'];
                 $left = $row['borderradius']['left'];
                 $borderradius = '';
                 // Try to shorten the definition
                 if ($top != '' && $right != '' && $bottom != '' && $left != '') {
                     if ($top == $right && $top == $bottom && $top == $left) {
                         $borderradius = $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ';';
                     } elseif ($top == $bottom && $right == $left) {
                         $borderradius = $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['borderradius']['unit']) . ';';
                     } elseif ($top != $bottom && $right == $left) {
                         $borderradius = $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['borderradius']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['borderradius']['unit']) . ';';
                     } else {
                         $borderradius .= $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['borderradius']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['borderradius']['unit']) . ' ' . $left . ($left === '0' ? '' : $row['borderradius']['unit']) . ';';
                     }
                     $return .= $lb . 'border-radius:' . $borderradius;
                 } else {
                     $arrDir = array('top-left' => $top, 'top-right' => $right, 'bottom-right' => $bottom, 'bottom-left' => $left);
                     foreach ($arrDir as $k => $v) {
                         if ($v != '') {
                             $return .= $lb . 'border-' . $k . '-radius:' . $v . ($v === '0' ? '' : $row['borderradius']['unit']) . ';';
                         }
                     }
                 }
             }
         }
         // Border collapse
         if ($row['bordercollapse'] != '') {
             $return .= $lb . 'border-collapse:' . $row['bordercollapse'] . ';';
         }
         // Border spacing
         $row['borderspacing'] = deserialize($row['borderspacing']);
         if (isset($row['borderspacing']['value']) && $row['borderspacing']['value'] != '') {
             $return .= $lb . 'border-spacing:' . $row['borderspacing']['value'] . $row['borderspacing']['unit'] . ';';
         }
     }
     // Font
     if ($row['font']) {
         $row['fontsize'] = deserialize($row['fontsize']);
         $row['lineheight'] = deserialize($row['lineheight']);
         $row['fontfamily'] = str_replace(', ', ',', $row['fontfamily']);
         // Try to shorten the definition
         if ($row['fontfamily'] != '' && $row['fontfamily'] != 'inherit' && isset($row['fontsize']['value']) && $row['fontsize']['value'] != '' && $row['fontsize']['value'] != 'inherit') {
             $return .= $lb . 'font:' . $row['fontsize']['value'] . $row['fontsize']['unit'] . (isset($row['lineheight']['value']) && $row['lineheight']['value'] != '' ? '/' . $row['lineheight']['value'] . $row['lineheight']['unit'] : '') . ' ' . $row['fontfamily'] . ';';
         } else {
             // Font family
             if ($row['fontfamily'] != '') {
                 $return .= $lb . 'font-family:' . $row['fontfamily'] . ';';
             }
             // Font size
             if (isset($row['fontsize']['value']) && $row['fontsize']['value'] != '') {
                 $return .= $lb . 'font-size:' . $row['fontsize']['value'] . $row['fontsize']['unit'] . ';';
             }
             // Line height
             if (isset($row['lineheight']['value']) && $row['lineheight']['value'] != '') {
                 $return .= $lb . 'line-height:' . $row['lineheight']['value'] . $row['lineheight']['unit'] . ';';
             }
         }
         // Font style
         $row['fontstyle'] = deserialize($row['fontstyle']);
         if (is_array($row['fontstyle'])) {
             if (in_array('bold', $row['fontstyle'])) {
                 $return .= $lb . 'font-weight:bold;';
             }
             if (in_array('italic', $row['fontstyle'])) {
                 $return .= $lb . 'font-style:italic;';
             }
             if (in_array('normal', $row['fontstyle'])) {
                 $return .= $lb . 'font-weight:normal;';
             }
             if (in_array('underline', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:underline;';
             }
             if (in_array('line-through', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:line-through;';
             }
             if (in_array('overline', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:overline;';
             }
             if (in_array('notUnderlined', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:none;';
             }
             if (in_array('small-caps', $row['fontstyle'])) {
                 $return .= $lb . 'font-variant:small-caps;';
             }
         }
         $fnColor = deserialize($row['fontcolor'], true);
         // Font color
         if ($fnColor[0] != '') {
             $return .= $lb . 'color:' . $this->compileColor($fnColor, $blnWriteToFile, $vars) . ';';
         }
         // Text transform
         if ($row['texttransform'] != '') {
             $return .= $lb . 'text-transform:' . $row['texttransform'] . ';';
         }
         // Text indent
         $row['textindent'] = deserialize($row['textindent']);
         if (isset($row['textindent']['value']) && $row['textindent']['value'] != '') {
             $return .= $lb . 'text-indent:' . $row['textindent']['value'] . $row['textindent']['unit'] . ';';
         }
         // Letter spacing
         $row['letterspacing'] = deserialize($row['letterspacing']);
         if (isset($row['letterspacing']['value']) && $row['letterspacing']['value'] != '') {
             $return .= $lb . 'letter-spacing:' . $row['letterspacing']['value'] . $row['letterspacing']['unit'] . ';';
         }
         // Word spacing
         $row['wordspacing'] = deserialize($row['wordspacing']);
         if (isset($row['wordspacing']['value']) && $row['wordspacing']['value'] != '') {
             $return .= $lb . 'word-spacing:' . $row['wordspacing']['value'] . $row['wordspacing']['unit'] . ';';
         }
     }
     // List
     if ($row['list']) {
         // List bullet
         if ($row['liststyletype'] != '') {
             $return .= $lb . 'list-style-type:' . $row['liststyletype'] . ';';
         }
         // List image
         if ($row['liststyleimage'] == 'none') {
             $return .= $lb . 'list-style-image:none;';
         } elseif ($row['liststyleimage'] != '') {
             if (($strImage = $this->generateBase64Image($row['liststyleimage'], $parent)) !== false) {
                 $return .= $lb . 'list-style-image:url("' . $strImage . '");';
             } else {
                 $glue = strncmp($row['liststyleimage'], 'data:', 5) !== 0 && strncmp($row['liststyleimage'], 'http://', 7) !== 0 && strncmp($row['liststyleimage'], 'https://', 8) !== 0 && strncmp($row['liststyleimage'], '/', 1) !== 0 ? $strGlue : '';
                 $return .= $lb . 'list-style-image:url("' . $glue . $row['liststyleimage'] . '");';
             }
         }
     }
     // Optimize floating-point numbers (see #6634)
     $return = preg_replace('/([^0-9\\.\\+\\-])0\\.([0-9]+)/', '$1.$2', $return);
     // CSS3PIE
     if ($blnNeedsPie && !$parent['disablePie']) {
         $return .= $lb . 'behavior:url(\'assets/css3pie/' . $GLOBALS['TL_ASSETS']['CSS3PIE'] . '/PIE.htc\');';
     }
     // Custom code
     if ($row['own'] != '') {
         $own = trim(\String::decodeEntities($row['own']));
         $own = preg_replace('/url\\("(?!data:|\\/)/', 'url("' . $strGlue, $own);
         $own = preg_split('/[\\n\\r]+/', $own);
         $own = implode($blnWriteToFile ? '' : $lb, $own);
         $return .= $lb . (!$blnWriteToFile ? specialchars($own) : $own);
     }
     // Allow custom definitions
     if (isset($GLOBALS['TL_HOOKS']['compileDefinition']) && is_array($GLOBALS['TL_HOOKS']['compileDefinition'])) {
         foreach ($GLOBALS['TL_HOOKS']['compileDefinition'] as $callback) {
             $this->import($callback[0]);
             $strTemp = $this->{$callback}[0]->{$callback}[1]($row, $blnWriteToFile, $vars, $parent);
             if ($strTemp != '') {
                 $return .= $lb . $strTemp;
             }
         }
     }
     // Close the format definition
     if ($blnWriteToFile) {
         // Remove the last semi-colon (;) before the closing bracket
         if (substr($return, -1) == ';') {
             $return = substr($return, 0, -1);
         }
         $return .= '}';
     } elseif ($export) {
         $return .= "\n}\n";
     } else {
         $return .= "\n}</pre>\n";
     }
     // Replace global variables
     if (strpos($return, '$') !== false && !empty($vars)) {
         $return = str_replace(array_keys($vars), array_values($vars), $return);
     }
     // Replace insert tags (see #5512)
     return $this->replaceInsertTags($return, false);
 }
예제 #14
0
파일: Search.php 프로젝트: juergen83/contao
 /**
  * Search the index and return the result object
  *
  * @param string  $strKeywords The keyword string
  * @param boolean $blnOrSearch If true, the result can contain any keyword
  * @param array   $arrPid      An optional array of page IDs to limit the result to
  * @param integer $intRows     An optional maximum number of result rows
  * @param integer $intOffset   An optional result offset
  * @param boolean $blnFuzzy    If true, the search will be fuzzy
  *
  * @return \Database\Result The database result object
  *
  * @throws \Exception If the cleaned keyword string is empty
  */
 public static function searchFor($strKeywords, $blnOrSearch = false, $arrPid = array(), $intRows = 0, $intOffset = 0, $blnFuzzy = false)
 {
     // Clean the keywords
     $strKeywords = utf8_strtolower($strKeywords);
     $strKeywords = \String::decodeEntities($strKeywords);
     if (function_exists('mb_eregi_replace')) {
         $strKeywords = mb_eregi_replace('[^[:alnum:] \\*\\+\'"\\.:,_-]|\\. |\\.$|: |:$|, |,$', ' ', $strKeywords);
     } else {
         $strKeywords = preg_replace(array('/\\. /', '/\\.$/', '/: /', '/:$/', '/, /', '/,$/', '/[^\\pN\\pL \\*\\+\'"\\.:,_-]/u'), ' ', $strKeywords);
     }
     // Check keyword string
     if (!strlen($strKeywords)) {
         throw new \Exception('Empty keyword string');
     }
     // Split keywords
     $arrChunks = array();
     preg_match_all('/"[^"]+"|[\\+\\-]?[^ ]+\\*?/', $strKeywords, $arrChunks);
     $arrPhrases = array();
     $arrKeywords = array();
     $arrWildcards = array();
     $arrIncluded = array();
     $arrExcluded = array();
     foreach ($arrChunks[0] as $strKeyword) {
         if (substr($strKeyword, -1) == '*' && strlen($strKeyword) > 1) {
             $arrWildcards[] = str_replace('*', '%', $strKeyword);
             continue;
         }
         switch (substr($strKeyword, 0, 1)) {
             // Phrases
             case '"':
                 if (($strKeyword = trim(substr($strKeyword, 1, -1))) != false) {
                     $arrPhrases[] = '[[:<:]]' . str_replace(array(' ', '*'), array('[^[:alnum:]]+', ''), $strKeyword) . '[[:>:]]';
                 }
                 break;
                 // Included keywords
             // Included keywords
             case '+':
                 if (($strKeyword = trim(substr($strKeyword, 1))) != false) {
                     $arrIncluded[] = $strKeyword;
                 }
                 break;
                 // Excluded keywords
             // Excluded keywords
             case '-':
                 if (($strKeyword = trim(substr($strKeyword, 1))) != false) {
                     $arrExcluded[] = $strKeyword;
                 }
                 break;
                 // Wildcards
             // Wildcards
             case '*':
                 if (strlen($strKeyword) > 1) {
                     $arrWildcards[] = str_replace('*', '%', $strKeyword);
                 }
                 break;
                 // Normal keywords
             // Normal keywords
             default:
                 $arrKeywords[] = $strKeyword;
                 break;
         }
     }
     // Fuzzy search
     if ($blnFuzzy) {
         foreach ($arrKeywords as $strKeyword) {
             $arrWildcards[] = '%' . $strKeyword . '%';
         }
         $arrKeywords = array();
     }
     // Count keywords
     $intPhrases = count($arrPhrases);
     $intWildcards = count($arrWildcards);
     $intIncluded = count($arrIncluded);
     $intExcluded = count($arrExcluded);
     $intKeywords = 0;
     $arrValues = array();
     // Remember found words so we can highlight them later
     $strQuery = "SELECT tl_search_index.pid AS sid, GROUP_CONCAT(word) AS matches";
     // Get the number of wildcard matches
     if (!$blnOrSearch && $intWildcards) {
         $strQuery .= ", (SELECT COUNT(*) FROM tl_search_index WHERE (" . implode(' OR ', array_fill(0, $intWildcards, 'word LIKE ?')) . ") AND pid=sid) AS wildcards";
         $arrValues = array_merge($arrValues, $arrWildcards);
     }
     // Count the number of matches
     $strQuery .= ", COUNT(*) AS count";
     // Get the relevance
     $strQuery .= ", SUM(relevance) AS relevance";
     // Get meta information from tl_search
     $strQuery .= ", tl_search.*";
     // see #4506
     // Prepare keywords array
     $arrAllKeywords = array();
     // Get keywords
     if (!empty($arrKeywords)) {
         $arrAllKeywords[] = implode(' OR ', array_fill(0, count($arrKeywords), 'word=?'));
         $arrValues = array_merge($arrValues, $arrKeywords);
         $intKeywords += count($arrKeywords);
     }
     // Get included keywords
     if ($intIncluded) {
         $arrAllKeywords[] = implode(' OR ', array_fill(0, $intIncluded, 'word=?'));
         $arrValues = array_merge($arrValues, $arrIncluded);
         $intKeywords += $intIncluded;
     }
     // Get keywords from phrases
     if ($intPhrases) {
         foreach ($arrPhrases as $strPhrase) {
             $arrWords = explode('[^[:alnum:]]+', utf8_substr($strPhrase, 7, -7));
             $arrAllKeywords[] = implode(' OR ', array_fill(0, count($arrWords), 'word=?'));
             $arrValues = array_merge($arrValues, $arrWords);
             $intKeywords += count($arrWords);
         }
     }
     // Get wildcards
     if ($intWildcards) {
         $arrAllKeywords[] = implode(' OR ', array_fill(0, $intWildcards, 'word LIKE ?'));
         $arrValues = array_merge($arrValues, $arrWildcards);
     }
     $strQuery .= " FROM tl_search_index LEFT JOIN tl_search ON(tl_search_index.pid=tl_search.id) WHERE (" . implode(' OR ', $arrAllKeywords) . ")";
     // Get phrases
     if ($intPhrases) {
         $strQuery .= " AND (" . implode($blnOrSearch ? ' OR ' : ' AND ', array_fill(0, $intPhrases, 'tl_search_index.pid IN(SELECT id FROM tl_search WHERE text REGEXP ?)')) . ")";
         $arrValues = array_merge($arrValues, $arrPhrases);
     }
     // Include keywords
     if ($intIncluded) {
         $strQuery .= " AND tl_search_index.pid IN(SELECT pid FROM tl_search_index WHERE " . implode(' OR ', array_fill(0, $intIncluded, 'word=?')) . ")";
         $arrValues = array_merge($arrValues, $arrIncluded);
     }
     // Exclude keywords
     if ($intExcluded) {
         $strQuery .= " AND tl_search_index.pid NOT IN(SELECT pid FROM tl_search_index WHERE " . implode(' OR ', array_fill(0, $intExcluded, 'word=?')) . ")";
         $arrValues = array_merge($arrValues, $arrExcluded);
     }
     // Limit results to a particular set of pages
     if (!empty($arrPid) && is_array($arrPid)) {
         $strQuery .= " AND tl_search_index.pid IN(SELECT id FROM tl_search WHERE pid IN(" . implode(',', array_map('intval', $arrPid)) . "))";
     }
     $strQuery .= " GROUP BY tl_search_index.pid";
     // Make sure to find all words
     if (!$blnOrSearch) {
         // Number of keywords without wildcards
         $strQuery .= " HAVING count >= " . $intKeywords;
         // Dynamically add the number of wildcard matches
         if ($intWildcards) {
             $strQuery .= " + IF(wildcards>" . $intWildcards . ", wildcards, " . $intWildcards . ")";
         }
     }
     // Sort by relevance
     $strQuery .= " ORDER BY relevance DESC";
     // Return result
     $objResultStmt = \Database::getInstance()->prepare($strQuery);
     if ($intRows > 0) {
         $objResultStmt->limit($intRows, $intOffset);
     }
     return $objResultStmt->execute($arrValues);
 }
예제 #15
0
 /**
  * Process submitted form data
  * Send mail, store data in backend
  * @param array $arrSubmitted Submitted data
  * @param array|bool $arrForm Form configuration
  * @param array|bool $arrFiles Files uploaded
  * @param array|bool $arrLabels Form field labels
  * @return void
  */
 public function processSubmittedData($arrSubmitted, $arrForm = false, $arrFiles = false, $arrLabels = false)
 {
     // Form config
     if (!$arrForm) {
         return;
     }
     $arrFormFields = array();
     $this->import('FrontendUser', 'Member');
     $this->import('Formdata');
     $this->strFdDcaKey = 'fd_' . (!empty($arrForm['alias']) ? $arrForm['alias'] : str_replace('-', '_', standardize($arrForm['title'])));
     $this->Formdata->FdDcaKey = $this->strFdDcaKey;
     // Get params of related listing formdata
     $intListingId = intval($_SESSION['EFP']['LISTING_MOD']['id']);
     if ($intListingId > 0) {
         $objListing = \Database::getInstance()->prepare("SELECT * FROM tl_module WHERE id=?")->execute($intListingId);
         if ($objListing->numRows) {
             $arrListing = $objListing->fetchAssoc();
             // Mail delivery defined in frontend listing module
             $arrForm['sendConfirmationMailOnFrontendEditing'] = $arrListing['efg_fe_no_confirmation_mail'] ? false : true;
             $arrForm['sendFormattedMailOnFrontendEditing'] = $arrListing['efg_fe_no_formatted_mail'] ? false : true;
         }
     }
     if (!empty($arrListing['efg_DetailsKey'])) {
         $this->strFormdataDetailsKey = $arrListing['efg_DetailsKey'];
     }
     $blnFEedit = false;
     $intOldId = 0;
     $strRedirectTo = '';
     $strUrl = preg_replace('/\\?.*$/', '', \Environment::get('request'));
     $strUrlParams = '';
     $blnQuery = false;
     foreach (preg_split('/&(amp;)?/', $_SERVER['QUERY_STRING']) as $fragment) {
         if (strlen($fragment)) {
             if (strncasecmp($fragment, $this->strFormdataDetailsKey, strlen($this->strFormdataDetailsKey)) !== 0 && strncasecmp($fragment, 'act', 3) !== 0) {
                 $strUrlParams .= (!$blnQuery ? '' : '&amp;') . $fragment;
                 $blnQuery = true;
             }
         }
     }
     if (in_array($arrListing['efg_fe_edit_access'], array('public', 'groupmembers', 'member'))) {
         if (\Input::get('act') == 'edit') {
             $blnFEedit = true;
             $objCheck = \Database::getInstance()->prepare("SELECT id FROM tl_formdata WHERE id=? OR alias=?")->execute(\Input::get($this->strFormdataDetailsKey), \Input::get($this->strFormdataDetailsKey));
             if ($objCheck->numRows == 1) {
                 $intOldId = intval($objCheck->id);
             } else {
                 $this->log('Could not identify record by ID "' . \Input::get($this->strFormdataDetailsKey) . '"', __METHOD__, TL_GENERAL);
             }
         }
     }
     // Types of form fields with storable data
     $arrFFstorable = $this->Formdata->arrFFstorable;
     if (($arrForm['storeFormdata'] || $arrForm['sendConfirmationMail'] || $arrForm['sendFormattedMail']) && !empty($arrSubmitted)) {
         $timeNow = time();
         $this->loadDataContainer($this->strFdDcaKey);
         $this->loadDataContainer('tl_formdata_details');
         $this->loadDataContainer('tl_files');
         $arrFormFields = $this->Formdata->getFormfieldsAsArray($arrForm['id']);
         $arrBaseFields = array();
         $arrDetailFields = array();
         if (!empty($GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['baseFields'])) {
             $arrBaseFields = $GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['baseFields'];
         }
         if (!empty($GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['detailFields'])) {
             $arrDetailFields = $GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['detailFields'];
         }
         $arrHookFields = array_merge($arrBaseFields, $arrDetailFields);
         $arrToSave = array();
         foreach ($arrSubmitted as $k => $varVal) {
             if (in_array($k, array('id'))) {
                 continue;
             } elseif (in_array($k, $arrHookFields) || in_array($k, array_keys($arrFormFields)) || in_array($k, array('FORM_SUBMIT', 'MAX_FILE_SIZE'))) {
                 $arrToSave[$k] = $varVal;
             }
         }
         // HOOK: process efg form data callback
         if (array_key_exists('processEfgFormData', $GLOBALS['TL_HOOKS']) && is_array($GLOBALS['TL_HOOKS']['processEfgFormData'])) {
             foreach ($GLOBALS['TL_HOOKS']['processEfgFormData'] as $key => $callback) {
                 $this->import($callback[0]);
                 $arrResult = $this->{$callback}[0]->{$callback}[1]($arrToSave, $arrFiles, $intOldId, $arrForm, $arrLabels);
                 if (!empty($arrResult)) {
                     $arrSubmitted = $arrResult;
                     $arrToSave = $arrSubmitted;
                 }
             }
         }
     }
     // Formdata storage
     if ($arrForm['storeFormdata'] && !empty($arrSubmitted)) {
         $blnStoreOptionsValue = $arrForm['efgStoreValues'] ? true : false;
         // Get old record on frontend editing
         if ($intOldId > 0) {
             $arrOldData = $this->Formdata->getFormdataAsArray($intOldId);
             $arrOldFormdata = $arrOldData['fd_base'];
             $arrOldFormdataDetails = $arrOldData['fd_details'];
         }
         // Prepare record tl_formdata
         $arrSet = array('form' => $arrForm['title'], 'tstamp' => $timeNow, 'date' => $timeNow, 'ip' => \System::anonymizeIp(\Environment::get('ip')), 'published' => $GLOBALS['TL_DCA']['tl_formdata']['fields']['published']['default'] ? '1' : '', 'fd_member' => intval($this->Member->id), 'fd_member_group' => intval($this->Member->groups[0]), 'fd_user' => intval($this->User->id), 'fd_user_group' => intval($this->User->groups[0]));
         // Keep some values from existing record on frontend editing
         if ($intOldId > 0) {
             $arrSet['form'] = $arrOldFormdata['form'];
             $arrSet['be_notes'] = $arrOldFormdata['be_notes'];
             $arrSet['fd_member'] = $arrOldFormdata['fd_member'];
             $arrSet['fd_member_group'] = $arrOldFormdata['fd_member_group'];
             if (intval($this->Member->id) > 0) {
                 $arrSet['fd_member'] = intval($this->Member->id);
                 if (count($this->Member->groups) == 1 && intval($this->Member->groups[0]) > 0) {
                     $arrSet['fd_member_group'] = intval($this->Member->groups[0]);
                 }
             } else {
                 $arrSet['fd_member'] = 0;
             }
             $arrSet['fd_user'] = $arrOldFormdata['fd_user'];
             $arrSet['fd_user_group'] = $arrOldFormdata['fd_user_group'];
             // Set published to value of old record, if no default value is defined
             if (!isset($GLOBALS['TL_DCA']['tl_formdata']['fields']['published']['default'])) {
                 $arrSet['published'] = $arrOldFormdata['published'];
             }
         }
         // Store formdata: Update or insert and delete
         if ($blnFEedit && strlen($arrListing['efg_fe_keep_id'])) {
             $intNewId = $intOldId;
             \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrSet)->execute($intOldId);
             \Database::getInstance()->prepare("DELETE FROM tl_formdata_details WHERE pid=?")->execute($intOldId);
         } else {
             $objNewFormdata = \Database::getInstance()->prepare("INSERT INTO tl_formdata %s")->set($arrSet)->execute();
             $intNewId = $objNewFormdata->insertId;
             // Update related comments
             if (in_array('comments', \ModuleLoader::getActive())) {
                 \Database::getInstance()->prepare("UPDATE tl_comments %s WHERE `source` = 'tl_formdata' AND parent=?")->set(array('parent' => $intNewId))->execute($intOldId);
             }
         }
         // Store details data
         foreach ($arrFormFields as $k => $arrField) {
             $strType = $arrField['formfieldType'];
             $strVal = '';
             if (in_array($strType, $arrFFstorable)) {
                 if ($blnStoreOptionsValue) {
                     $arrField['eval']['efgStoreValues'] = true;
                 } else {
                     $arrField['eval']['efgStoreValues'] = false;
                 }
                 // Set rgxp 'date' for field type 'calendar' if not set
                 if ($strType == 'calendar') {
                     if (!isset($arrField['rgxp'])) {
                         $arrField['rgxp'] = 'date';
                     }
                 } elseif ($strType == 'xdependentcalendarfields') {
                     $arrField['rgxp'] = 'date';
                     $arrField['dateFormat'] = $arrField['xdateformat'];
                 }
                 $strVal = $this->Formdata->preparePostValueForDatabase($arrSubmitted[$k], $arrField, $arrFiles[$k]);
                 // Special treatment for type upload
                 // Keep old file on frontend editing, if no new file has been uploaded
                 if ($strType == 'upload') {
                     if ($intOldId) {
                         if (!$arrFiles[$k]['name']) {
                             if (strlen($arrOldFormdataDetails[$k]['value'])) {
                                 $strVal = $arrOldFormdataDetails[$k]['value'];
                             }
                         }
                     }
                 }
                 if (isset($arrSubmitted[$k]) || $strType == 'upload' && strlen($strVal)) {
                     // Prepare data
                     $arrFieldSet = array('pid' => $intNewId, 'sorting' => $arrField['sorting'], 'tstamp' => $timeNow, 'ff_id' => $arrField['id'], 'ff_name' => $arrField['name'], 'value' => $strVal);
                     $objNewFormdataDetails = \Database::getInstance()->prepare("INSERT INTO tl_formdata_details %s")->set($arrFieldSet)->execute();
                 }
             }
         }
         // Delete old record after frontend editing
         if ($blnFEedit) {
             if (!isset($arrListing['efg_fe_keep_id']) || $arrListing['efg_fe_keep_id'] != "1") {
                 if ($intNewId > 0 && intval($intOldId) > 0 && intval($intNewId) != intval($intOldId)) {
                     \Database::getInstance()->prepare("DELETE FROM tl_formdata_details WHERE pid=?")->execute($intOldId);
                     \Database::getInstance()->prepare("DELETE FROM tl_formdata WHERE id=?")->execute($intOldId);
                 }
             }
             $strRedirectTo = preg_replace('/\\?.*$/', '', \Environment::get('request'));
         }
         // Auto-generate alias
         $strAlias = $this->Formdata->generateAlias($arrOldFormdata['alias'], $arrForm['title'], $intNewId);
         if (strlen($strAlias)) {
             $arrUpd = array('alias' => $strAlias);
             \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrUpd)->execute($intNewId);
         }
     }
     // Store data in the session to display on confirmation page
     unset($_SESSION['EFP']['FORMDATA']);
     $blnSkipEmptyFields = $arrForm['confirmationMailSkipEmpty'] ? true : false;
     foreach ($arrFormFields as $k => $arrField) {
         $strType = $arrField['formfieldType'];
         $strVal = '';
         if (in_array($strType, $arrFFstorable)) {
             $strVal = $this->Formdata->preparePostValueForMail($arrSubmitted[$k], $arrField, $arrFiles[$k], $blnSkipEmptyFields);
         }
         $_SESSION['EFP']['FORMDATA'][$k] = $strVal;
     }
     $_SESSION['EFP']['FORMDATA']['_formId_'] = $arrForm['id'];
     // Confirmation Mail
     if ($blnFEedit && !$arrForm['sendConfirmationMailOnFrontendEditing']) {
         $arrForm['sendConfirmationMail'] = false;
     }
     if ($arrForm['sendConfirmationMail']) {
         $objMailProperties = new \stdClass();
         $objMailProperties->subject = '';
         $objMailProperties->sender = '';
         $objMailProperties->senderName = '';
         $objMailProperties->replyTo = '';
         $objMailProperties->recipients = array();
         $objMailProperties->messageText = '';
         $objMailProperties->messageHtmlTmpl = '';
         $objMailProperties->messageHtml = '';
         $objMailProperties->attachments = array();
         $objMailProperties->skipEmptyFields = false;
         $objMailProperties->skipEmptyFields = $arrForm['confirmationMailSkipEmpty'] ? true : false;
         // Set the sender as given in form configuration
         list($senderName, $sender) = \String::splitFriendlyEmail($arrForm['confirmationMailSender']);
         $objMailProperties->sender = $sender;
         $objMailProperties->senderName = $senderName;
         // Set the 'reply to' address, if given in form configuration
         if (!empty($arrForm['confirmationMailReplyto'])) {
             list($replyToName, $replyTo) = \String::splitFriendlyEmail($arrForm['confirmationMailReplyto']);
             $objMailProperties->replyTo = strlen($replyToName) ? $replyToName . ' <' . $replyTo . '>' : $replyTo;
         }
         // Set recipient(s)
         $recipientFieldName = $arrForm['confirmationMailRecipientField'];
         $varRecipient = $arrSubmitted[$recipientFieldName];
         if (is_array($varRecipient)) {
             $arrRecipient = $varRecipient;
         } else {
             $arrRecipient = trimsplit(',', $varRecipient);
         }
         if (!empty($arrForm['confirmationMailRecipient'])) {
             $varRecipient = $arrForm['confirmationMailRecipient'];
             $arrRecipient = array_merge($arrRecipient, trimsplit(',', $varRecipient));
         }
         $arrRecipient = array_filter(array_unique($arrRecipient));
         if (!empty($arrRecipient)) {
             foreach ($arrRecipient as $kR => $recipient) {
                 list($recipientName, $recipient) = \String::splitFriendlyEmail($this->replaceInsertTags($recipient, false));
                 $arrRecipient[$kR] = strlen($recipientName) ? $recipientName . ' <' . $recipient . '>' : $recipient;
             }
         }
         $objMailProperties->recipients = $arrRecipient;
         // Check if we want custom attachments... (Thanks to Torben Schwellnus)
         if ($arrForm['addConfirmationMailAttachments']) {
             if ($arrForm['confirmationMailAttachments']) {
                 $arrCustomAttachments = deserialize($arrForm['confirmationMailAttachments'], true);
                 if (!empty($arrCustomAttachments)) {
                     foreach ($arrCustomAttachments as $varFile) {
                         $objFileModel = \FilesModel::findById($varFile);
                         if ($objFileModel !== null) {
                             $objFile = new \File($objFileModel->path);
                             if ($objFile->size) {
                                 $objMailProperties->attachments[TL_ROOT . '/' . $objFile->path] = array('file' => TL_ROOT . '/' . $objFile->path, 'name' => $objFile->basename, 'mime' => $objFile->mime);
                             }
                         }
                     }
                 }
             }
         }
         $objMailProperties->subject = \String::decodeEntities($arrForm['confirmationMailSubject']);
         $objMailProperties->messageText = \String::decodeEntities($arrForm['confirmationMailText']);
         $objMailProperties->messageHtmlTmpl = $arrForm['confirmationMailTemplate'];
         // Replace Insert tags and conditional tags
         $objMailProperties = $this->Formdata->prepareMailData($objMailProperties, $arrSubmitted, $arrFiles, $arrForm, $arrFormFields);
         // Send Mail
         $blnConfirmationSent = false;
         if (!empty($objMailProperties->recipients)) {
             $objMail = new \Email();
             $objMail->from = $objMailProperties->sender;
             if (!empty($objMailProperties->senderName)) {
                 $objMail->fromName = $objMailProperties->senderName;
             }
             if (!empty($objMailProperties->replyTo)) {
                 $objMail->replyTo($objMailProperties->replyTo);
             }
             $objMail->subject = $objMailProperties->subject;
             if (!empty($objMailProperties->attachments)) {
                 foreach ($objMailProperties->attachments as $strFile => $varParams) {
                     $strContent = file_get_contents($varParams['file'], false);
                     $objMail->attachFileFromString($strContent, $varParams['name'], $varParams['mime']);
                 }
             }
             if (!empty($objMailProperties->messageText)) {
                 $objMail->text = $objMailProperties->messageText;
             }
             if (!empty($objMailProperties->messageHtml)) {
                 $objMail->html = $objMailProperties->messageHtml;
             }
             foreach ($objMailProperties->recipients as $recipient) {
                 $objMail->sendTo($recipient);
                 $blnConfirmationSent = true;
             }
         }
         if ($blnConfirmationSent && isset($intNewId) && intval($intNewId) > 0) {
             $arrUpd = array('confirmationSent' => '1', 'confirmationDate' => $timeNow);
             $res = \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrUpd)->execute($intNewId);
         }
     }
     // Information (formatted) Mail
     if ($blnFEedit && !$arrForm['sendFormattedMailOnFrontendEditing']) {
         $arrForm['sendFormattedMail'] = false;
     }
     if ($arrForm['sendFormattedMail']) {
         $objMailProperties = new \stdClass();
         $objMailProperties->subject = '';
         $objMailProperties->sender = '';
         $objMailProperties->senderName = '';
         $objMailProperties->replyTo = '';
         $objMailProperties->recipients = array();
         $objMailProperties->messageText = '';
         $objMailProperties->messageHtmlTmpl = '';
         $objMailProperties->messageHtml = '';
         $objMailProperties->attachments = array();
         $objMailProperties->skipEmptyFields = false;
         $objMailProperties->skipEmptyFields = $arrForm['formattedMailSkipEmpty'] ? true : false;
         // Set the admin e-mail as "from" address
         $objMailProperties->sender = $GLOBALS['TL_ADMIN_EMAIL'];
         $objMailProperties->senderName = $GLOBALS['TL_ADMIN_NAME'];
         // Get 'reply to' address, if form contains field named 'email'
         if (isset($arrSubmitted['email']) && !empty($arrSubmitted['email']) && !is_bool(strpos($arrSubmitted['email'], '@'))) {
             $replyTo = $arrSubmitted['email'];
             // add name
             if (isset($arrSubmitted['name']) && !empty($arrSubmitted['name'])) {
                 $replyTo = '"' . $arrSubmitted['name'] . '" <' . $arrSubmitted['email'] . '>';
             }
             $objMailProperties->replyTo = $replyTo;
         }
         // Set recipient(s)
         $varRecipient = $arrForm['formattedMailRecipient'];
         if (is_array($varRecipient)) {
             $arrRecipient = $varRecipient;
         } else {
             $arrRecipient = trimsplit(',', $varRecipient);
         }
         $arrRecipient = array_filter(array_unique($arrRecipient));
         if (!empty($arrRecipient)) {
             foreach ($arrRecipient as $kR => $recipient) {
                 list($recipientName, $recipient) = \String::splitFriendlyEmail($this->replaceInsertTags($recipient, false));
                 $arrRecipient[$kR] = strlen($recipientName) ? $recipientName . ' <' . $recipient . '>' : $recipient;
             }
         }
         $objMailProperties->recipients = $arrRecipient;
         // Check if we want custom attachments... (Thanks to Torben Schwellnus)
         if ($arrForm['addFormattedMailAttachments']) {
             if ($arrForm['formattedMailAttachments']) {
                 $arrCustomAttachments = deserialize($arrForm['formattedMailAttachments'], true);
                 if (is_array($arrCustomAttachments)) {
                     foreach ($arrCustomAttachments as $varFile) {
                         $objFileModel = \FilesModel::findById($varFile);
                         if ($objFileModel !== null) {
                             $objFile = new \File($objFileModel->path);
                             if ($objFile->size) {
                                 $objMailProperties->attachments[TL_ROOT . '/' . $objFile->path] = array('file' => TL_ROOT . '/' . $objFile->path, 'name' => $objFile->basename, 'mime' => $objFile->mime);
                             }
                         }
                     }
                 }
             }
         }
         $objMailProperties->subject = \String::decodeEntities($arrForm['formattedMailSubject']);
         $objMailProperties->messageText = \String::decodeEntities($arrForm['formattedMailText']);
         $objMailProperties->messageHtmlTmpl = $arrForm['formattedMailTemplate'];
         // Replace Insert tags and conditional tags
         $objMailProperties = $this->Formdata->prepareMailData($objMailProperties, $arrSubmitted, $arrFiles, $arrForm, $arrFormFields);
         // Send Mail
         $blnInformationSent = false;
         if (!empty($objMailProperties->recipients)) {
             $objMail = new \Email();
             $objMail->from = $objMailProperties->sender;
             if (!empty($objMailProperties->senderName)) {
                 $objMail->fromName = $objMailProperties->senderName;
             }
             if (!empty($objMailProperties->replyTo)) {
                 $objMail->replyTo($objMailProperties->replyTo);
             }
             $objMail->subject = $objMailProperties->subject;
             if (!empty($objMailProperties->attachments)) {
                 foreach ($objMailProperties->attachments as $strFile => $varParams) {
                     $strContent = file_get_contents($varParams['file'], false);
                     $objMail->attachFileFromString($strContent, $varParams['name'], $varParams['mime']);
                 }
             }
             if (!empty($objMailProperties->messageText)) {
                 $objMail->text = $objMailProperties->messageText;
             }
             if (!empty($objMailProperties->messageHtml)) {
                 $objMail->html = $objMailProperties->messageHtml;
             }
             foreach ($objMailProperties->recipients as $recipient) {
                 $objMail->sendTo($recipient);
                 $blnInformationSent = true;
             }
         }
     }
     // Redirect after frontend editing
     if ($blnFEedit) {
         if (!empty($strRedirectTo)) {
             $strRed = preg_replace(array('/\\/' . $this->strFormdataDetailsKey . '\\/' . \Input::get($this->strFormdataDetailsKey) . '/i', '/' . $this->strFormdataDetailsKey . '=' . \Input::get($this->strFormdataDetailsKey) . '/i', '/act=edit/i'), array('', '', ''), $strUrl) . (!empty($strUrlParams) ? '?' . $strUrlParams : '');
             \Controller::redirect($strRed);
         }
     }
 }
예제 #16
0
파일: Form.php 프로젝트: iCodr8/core
 /**
  * Process form data, store it in the session and redirect to the jumpTo page
  * @param array
  * @param array
  */
 protected function processFormData($arrSubmitted, $arrLabels)
 {
     // HOOK: prepare form data callback
     if (isset($GLOBALS['TL_HOOKS']['prepareFormData']) && is_array($GLOBALS['TL_HOOKS']['prepareFormData'])) {
         foreach ($GLOBALS['TL_HOOKS']['prepareFormData'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($arrSubmitted, $arrLabels, $this);
         }
     }
     // Send form data via e-mail
     if ($this->sendViaEmail) {
         $keys = array();
         $values = array();
         $fields = array();
         $message = '';
         foreach ($arrSubmitted as $k => $v) {
             if ($k == 'cc') {
                 continue;
             }
             $v = deserialize($v);
             // Skip empty fields
             if ($this->skipEmpty && !is_array($v) && !strlen($v)) {
                 continue;
             }
             // Add field to message
             $message .= (isset($arrLabels[$k]) ? $arrLabels[$k] : ucfirst($k)) . ': ' . (is_array($v) ? implode(', ', $v) : $v) . "\n";
             // Prepare XML file
             if ($this->format == 'xml') {
                 $fields[] = array('name' => $k, 'values' => is_array($v) ? $v : array($v));
             }
             // Prepare CSV file
             if ($this->format == 'csv') {
                 $keys[] = $k;
                 $values[] = is_array($v) ? implode(',', $v) : $v;
             }
         }
         $recipients = \String::splitCsv($this->recipient);
         // Format recipients
         foreach ($recipients as $k => $v) {
             $recipients[$k] = str_replace(array('[', ']', '"'), array('<', '>', ''), $v);
         }
         $email = new \Email();
         // Get subject and message
         if ($this->format == 'email') {
             $message = $arrSubmitted['message'];
             $email->subject = $arrSubmitted['subject'];
         }
         // Set the admin e-mail as "from" address
         $email->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $email->fromName = $GLOBALS['TL_ADMIN_NAME'];
         // Get the "reply to" address
         if (strlen(\Input::post('email', true))) {
             $replyTo = \Input::post('email', true);
             // Add name
             if (strlen(\Input::post('name'))) {
                 $replyTo = '"' . \Input::post('name') . '" <' . $replyTo . '>';
             }
             $email->replyTo($replyTo);
         }
         // Fallback to default subject
         if (!strlen($email->subject)) {
             $email->subject = $this->replaceInsertTags($this->subject, false);
         }
         // Send copy to sender
         if (strlen($arrSubmitted['cc'])) {
             $email->sendCc(\Input::post('email', true));
             unset($_SESSION['FORM_DATA']['cc']);
         }
         // Attach XML file
         if ($this->format == 'xml') {
             $objTemplate = new \FrontendTemplate('form_xml');
             $objTemplate->fields = $fields;
             $objTemplate->charset = \Config::get('characterSet');
             $email->attachFileFromString($objTemplate->parse(), 'form.xml', 'application/xml');
         }
         // Attach CSV file
         if ($this->format == 'csv') {
             $email->attachFileFromString(\String::decodeEntities('"' . implode('";"', $keys) . '"' . "\n" . '"' . implode('";"', $values) . '"'), 'form.csv', 'text/comma-separated-values');
         }
         $uploaded = '';
         // Attach uploaded files
         if (!empty($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $file) {
                 // Add a link to the uploaded file
                 if ($file['uploaded']) {
                     $uploaded .= "\n" . \Environment::get('base') . str_replace(TL_ROOT . '/', '', dirname($file['tmp_name'])) . '/' . rawurlencode($file['name']);
                     continue;
                 }
                 $email->attachFileFromString(file_get_contents($file['tmp_name']), $file['name'], $file['type']);
             }
         }
         $uploaded = strlen(trim($uploaded)) ? "\n\n---\n" . $uploaded : '';
         $email->text = \String::decodeEntities(trim($message)) . $uploaded . "\n\n";
         // Send the e-mail
         try {
             $email->sendTo($recipients);
         } catch (\Swift_SwiftException $e) {
             $this->log('Form "' . $this->title . '" could not be sent: ' . $e->getMessage(), __METHOD__, TL_ERROR);
         }
     }
     // Store the values in the database
     if ($this->storeValues && $this->targetTable != '') {
         $arrSet = array();
         // Add the timestamp
         if ($this->Database->fieldExists('tstamp', $this->targetTable)) {
             $arrSet['tstamp'] = time();
         }
         // Fields
         foreach ($arrSubmitted as $k => $v) {
             if ($k != 'cc' && $k != 'id') {
                 $arrSet[$k] = $v;
             }
         }
         // Files
         if (!empty($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $k => $v) {
                 if ($v['uploaded']) {
                     $arrSet[$k] = str_replace(TL_ROOT . '/', '', $v['tmp_name']);
                 }
             }
         }
         // HOOK: store form data callback
         if (isset($GLOBALS['TL_HOOKS']['storeFormData']) && is_array($GLOBALS['TL_HOOKS']['storeFormData'])) {
             foreach ($GLOBALS['TL_HOOKS']['storeFormData'] as $callback) {
                 $this->import($callback[0]);
                 $arrSet = $this->{$callback}[0]->{$callback}[1]($arrSet, $this);
             }
         }
         // Set the correct empty value (see #6284, #6373)
         foreach ($arrSet as $k => $v) {
             if ($v === '') {
                 $arrSet[$k] = \Widget::getEmptyValueByFieldType($GLOBALS['TL_DCA'][$this->targetTable]['fields'][$k]['sql']);
             }
         }
         // Do not use Models here (backwards compatibility)
         $this->Database->prepare("INSERT INTO " . $this->targetTable . " %s")->set($arrSet)->execute();
     }
     // Store all values in the session
     foreach (array_keys($_POST) as $key) {
         $_SESSION['FORM_DATA'][$key] = $this->allowTags ? \Input::postHtml($key, true) : \Input::post($key, true);
     }
     $arrFiles = $_SESSION['FILES'];
     // HOOK: process form data callback
     if (isset($GLOBALS['TL_HOOKS']['processFormData']) && is_array($GLOBALS['TL_HOOKS']['processFormData'])) {
         foreach ($GLOBALS['TL_HOOKS']['processFormData'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($arrSubmitted, $this->arrData, $arrFiles, $arrLabels, $this);
         }
     }
     $_SESSION['FILES'] = array();
     // DO NOT CHANGE
     // Add a log entry
     if (FE_USER_LOGGED_IN) {
         $this->import('FrontendUser', 'User');
         $this->log('Form "' . $this->title . '" has been submitted by "' . $this->User->username . '".', __METHOD__, TL_FORMS);
     } else {
         $this->log('Form "' . $this->title . '" has been submitted by ' . \System::anonymizeIp(\Environment::get('ip')) . '.', __METHOD__, TL_FORMS);
     }
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
예제 #17
0
 /**
  * replace Inserttag
  *
  * @param
  *        	string
  *        	
  * @return string
  */
 public function replaceTags($strTag)
 {
     list($strTag, $strParams) = trimsplit('?', $strTag);
     $arrTag = trimsplit('::', $strTag);
     if ($arrTag[0] != 'avatar') {
         return false;
     }
     // get default settings
     $arrDims = deserialize($GLOBALS['TL_CONFIG']['avatar_maxdims']);
     $strAlt = $GLOBALS['TL_CONFIG']['avatar_default_alt'];
     $strTitle = $GLOBALS['TL_CONFIG']['avatar_default_title'];
     $strClass = $GLOBALS['TL_CONFIG']['avatar_default_class'];
     // parse query parameters
     $strParams = \String::decodeEntities($strParams);
     $strParams = str_replace('[&]', '&', $strParams);
     $arrParams = explode('&', $strParams);
     foreach ($arrParams as $strParam) {
         list($key, $value) = explode('=', $strParam);
         switch ($key) {
             case 'width':
                 $arrDims[0] = $value;
                 break;
             case 'height':
                 $arrDims[1] = $value;
                 break;
             case 'alt':
                 $strAlt = specialchars($value);
                 break;
             case 'title':
                 $strTitle = specialchars($value);
                 break;
             case 'class':
                 $strClass = $value;
                 break;
             case 'mode':
                 $arrDims[2] = $value;
                 break;
         }
     }
     // if no id given, use the current logged in member
     if (!$arrTag[1]) {
         // if no member is logged in, return anonymous avatar
         if (!FE_USER_LOGGED_IN) {
             return $this->generateAnonymousAvatar($arrDims);
         }
         $arrTag[1] = \FrontendUser::getInstance()->id;
     }
     // search the member record
     $objMember = \MemberModel::findByPk($arrTag[1]);
     // return anonymous avatar, if member not found
     if (!$objMember) {
         return $this->generateAnonymousAvatar($arrDims);
     }
     // get the avatar
     $strAvatar = $objMember->avatar;
     // parse the alt and title text
     $strAlt = \String::parseSimpleTokens($strAlt, $objMember->row());
     $strTitle = \String::parseSimpleTokens($strTitle, $objMember->row());
     // avatar available and file exists
     if ($strAvatar && ($objFile = \FilesModel::findByUuid($strAvatar)) && file_exists(TL_ROOT . '/' . $objFile->path)) {
         $strAvatar = $objFile->path;
     } else {
         if ($GLOBALS['TL_CONFIG']['avatar_fallback_image'] && ($objFile = \FilesModel::findByUuid($GLOBALS['TL_CONFIG']['avatar_fallback_image'])) && file_exists(TL_ROOT . '/' . $objFile->path)) {
             $strAvatar = $objFile->path;
         } else {
             if ($strAvatar == '' && \FrontendUser::getInstance()->gender != '') {
                 $strAvatar = "system/modules/avatar/assets/" . \FrontendUser::getInstance()->gender . ".png";
             } else {
                 $strAvatar = 'system/modules/avatar/assets/male.png';
             }
         }
     }
     // resize if size is requested
     $this->resize($strAvatar, $arrDims);
     // generate the img tag
     return sprintf('<img src="%s" width="%s" height="%s" alt="%s" title="%s" class="%s">', TL_FILES_URL . $strAvatar, $arrDims[0], $arrDims[1], $strAlt, $strTitle, $strClass);
 }
예제 #18
0
 /**
  * Shorten a string to a certain number of characters
  *
  * Shortens a string to a given number of characters preserving words
  * (therefore it might be a bit shorter or longer than the number of
  * characters specified). Stips all tags.
  *
  * @param string
  * @param integer
  * @param string
  *
  * @return string
  */
 public function substrCenter($strString, $intNumberOfChars, $strEllipsis = ' […] ')
 {
     $strString = preg_replace('/[\\t\\n\\r]+/', ' ', $strString);
     $strString = strip_tags($strString);
     if (utf8_strlen($strString) <= $intNumberOfChars) {
         return $strString;
     }
     $intCharCount = 0;
     $arrWords = array();
     $arrChunks = preg_split('/\\s+/', $strString);
     $blnAddEllipsis = false;
     //first part
     foreach ($arrChunks as $chunkKey => $strChunk) {
         if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
             $intCharCount += utf8_strlen(\StringUtil::decodeEntities($strChunk));
         } else {
             $intCharCount += utf8_strlen(\String::decodeEntities($strChunk));
         }
         if ($intCharCount++ <= $intNumberOfChars / 2) {
             // if we add the whole word remove it from list
             unset($arrChunks[$chunkKey]);
             $arrWords[] = $strChunk;
             continue;
         }
         // If the first word is longer than $intNumberOfChars already, shorten it
         // with utf8_substr() so the method does not return an empty string.
         if (empty($arrWords)) {
             $arrWords[] = utf8_substr($strChunk, 0, $intNumberOfChars / 2);
         }
         if ($strEllipsis !== false) {
             $blnAddEllipsis = true;
         }
         break;
     }
     // Backwards compatibility
     if ($strEllipsis === true) {
         $strEllipsis = ' […] ';
     }
     $intCharCount = 0;
     $arrWordsPt2 = array();
     // Second path
     foreach (array_reverse($arrChunks) as $strChunk) {
         if (version_compare(VERSION . '.' . BUILD, '3.5.5', '>=')) {
             $intCharCount += utf8_strlen(\StringUtil::decodeEntities($strChunk));
         } else {
             $intCharCount += utf8_strlen(\String::decodeEntities($strChunk));
         }
         if ($intCharCount++ <= $intNumberOfChars / 2) {
             $arrWordsPt2[] = $strChunk;
             continue;
         }
         // If the first word is longer than $intNumberOfChars already, shorten it
         // with utf8_substr() so the method does not return an empty string.
         if (empty($arrWordsPt2)) {
             $arrWordsPt2[] = utf8_substr($strChunk, utf8_strlen($strChunk) - $intNumberOfChars / 2, utf8_strlen($strChunk));
         }
         break;
     }
     return implode(' ', $arrWords) . ($blnAddEllipsis ? $strEllipsis : '') . implode(' ', array_reverse($arrWordsPt2));
 }
 /**
  * @param $objComment
  */
 public function notifyUser($objComment)
 {
     global $objPage;
     $objRatedMember = \MemberModel::findByPk($objComment->parent);
     if ($objRatedMember === null) {
         return;
     }
     if ($objRatedMember->email == '') {
         return;
     }
     $objAuthor = \MemberModel::findByPk($objComment->owner);
     if ($objAuthor === null) {
         return;
     }
     // Generate the data array for simple token use
     $arrData = array();
     foreach ($objAuthor->row() as $k => $v) {
         $arrData['author_' . $k] = $v;
     }
     foreach ($objRatedMember->row() as $k => $v) {
         $arrData['recipient_' . $k] = $v;
     }
     foreach ($objComment->row() as $k => $v) {
         $arrData['comments_' . $k] = $v;
     }
     $objTemplate = new \FrontendTemplate('member_rating_email_notification');
     $objTemplate->comment = nl2br($objComment->comment);
     $objTemplate->score = $objComment->score;
     $objTemplate->link = \Environment::get('url') . '/' . \Controller::generateFrontendUrl($objPage->row(), '', $objPage->language) . '?publish=true&activation_token=' . $objComment->activation_token;
     $objTemplate->link_del = \Environment::get('url') . '/' . \Controller::generateFrontendUrl($objPage->row(), '', $objPage->language) . '?del=true&activation_token=' . $objComment->activation_token;
     $strContent = $objTemplate->parse();
     // Mail
     $objEmail = new \Email();
     $strSubject = sprintf($GLOBALS['TL_LANG']['MOD']['member_rating']['emailNotify']['subject'], $_SERVER['SERVER_NAME']);
     $objEmail->subject = \String::parseSimpleTokens($strSubject, $arrData);
     $strContent = $this->replaceInsertTags($strContent);
     $strContent = \String::parseSimpleTokens($strContent, $arrData);
     $objEmail->html = $strContent;
     // Text version
     $strContent = \String::decodeEntities($strContent);
     $strContent = strip_tags($strContent);
     $strContent = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strContent);
     $objEmail->text = $strContent;
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->sendTo($objRatedMember->email);
 }
예제 #20
0
 /**
  * Format a value
  * @param mixed
  * @return mixed
  */
 public function formatValue($k, $value)
 {
     global $objPage;
     $value = deserialize($value);
     $rgxp = '';
     if ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp']) {
         $rgxp = $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['rgxp'];
     } else {
         $rgxp = $this->arrFF[$k]['rgxp'];
     }
     // Array
     if (is_array($value)) {
         $value = implode(', ', $value);
     } elseif ($value && $rgxp == 'date') {
         $value = \Date::parse(!empty($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['dateFormat']) ? $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['eval']['dateFormat'] : $objPage->dateFormat, $value);
     } elseif ($value && $rgxp == 'time') {
         $value = \Date::parse($objPage->timeFormat, $value);
     } elseif ($value && $rgxp == 'datim') {
         $value = \Date::parse($objPage->datimFormat, $value);
     } elseif ($value && ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['inputType'] == 'checkbox' || $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['inputType'] == 'efgLookupCheckbox' || $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['inputType'] == 'select' || $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['inputType'] == 'conditionalselect' || $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['inputType'] == 'efgLookupSelect' || $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['inputType'] == 'radio' || $GLOBALS['TL_DCA'][$this->list_table]['fields'][$k]['inputType'] == 'fileTree')) {
         $value = str_replace('|', ', ', $value);
     }
     // owner fields fd_member, fd_user
     if (in_array($k, $this->arrBaseFields) && in_array($k, $this->arrOwnerFields)) {
         if ($k == 'fd_member') {
             $value = $this->arrMembers[$value];
         } elseif ($k == 'fd_user') {
             $value = $this->arrUsers[$value];
         } elseif ($k == 'fd_member_group') {
             $value = $this->arrMemberGroups[$value];
         } elseif ($k == 'fd_user_group') {
             $value = $this->arrUserGroups[$value];
         }
     }
     // URLs
     if ($value && $rgxp == 'url' && preg_match('@^(https?://|ftp://)@i', $value)) {
         $value = '<a href="' . $value . '"' . ($objPage->outputFormat == 'xhtml' ? ' onclick="return !window.open(this.href)"' : ' target="_blank"') . '>' . $value . '</a>';
         return $value;
     }
     // E-mail addresses
     if ($value && ($rgxp == 'email' || strpos($this->arrFF[$k]['name'], 'mail') !== false || strpos($k, 'mail') !== false)) {
         $value = \String::encodeEmail($value);
         $value = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $value . '">' . $value . '</a>';
         return $value;
     }
     if (strlen($value)) {
         $value = \String::decodeEntities($value);
         $value = ampersand($value);
         if (!is_bool(strpos($value, "\n"))) {
             $value = $this->Formdata->formatMultilineValue($value);
         }
     }
     return $value;
 }
예제 #21
0
파일: Controller.php 프로젝트: rikaix/core
 /**
  * Replace insert tags with their values
  * 
  * @param string  $strBuffer The text with the tags to be replaced
  * @param boolean $blnCache  If true, some tags will be preserved
  * 
  * @return string The text with the replaced tags
  */
 protected function replaceInsertTags($strBuffer, $blnCache = false)
 {
     global $objPage;
     // Preserve insert tags
     if ($GLOBALS['TL_CONFIG']['disableInsertTags']) {
         return $this->restoreBasicEntities($strBuffer);
     }
     $tags = preg_split('/\\{\\{([^\\}]+)\\}\\}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
     $strBuffer = '';
     $arrCache = array();
     for ($_rit = 0; $_rit < count($tags); $_rit = $_rit + 2) {
         $strBuffer .= $tags[$_rit];
         $strTag = $tags[$_rit + 1];
         // Skip empty tags
         if ($strTag == '') {
             continue;
         }
         // Load value from cache array
         if (isset($arrCache[$strTag])) {
             $strBuffer .= $arrCache[$strTag];
             continue;
         }
         $elements = explode('::', $strTag);
         // Skip certain elements if the output will be cached
         if ($blnCache) {
             if ($elements[0] == 'date' || $elements[0] == 'ua' || $elements[0] == 'file' || $elements[1] == 'back' || $elements[1] == 'referer' || $elements[0] == 'request_token' || strncmp($elements[0], 'cache_', 6) === 0) {
                 $strBuffer .= '{{' . $strTag . '}}';
                 continue;
             }
         }
         $arrCache[$strTag] = '';
         // Replace the tag
         switch (strtolower($elements[0])) {
             // Date
             case 'date':
                 $arrCache[$strTag] = $this->parseDate($elements[1] ?: $GLOBALS['TL_CONFIG']['dateFormat']);
                 break;
                 // Accessibility tags
             // Accessibility tags
             case 'lang':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '</span>';
                 } elseif ($objPage->outputFormat == 'xhtml') {
                     $arrCache[$strTag] = '<span lang="' . $elements[1] . '" xml:lang="' . $elements[1] . '">';
                 } else {
                     $arrCache[$strTag] = $arrCache[$strTag] = '<span lang="' . $elements[1] . '">';
                 }
                 break;
                 // E-mail addresses
             // E-mail addresses
             case 'email':
             case 'email_open':
             case 'email_url':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $strEmail = \String::encodeEmail($elements[1]);
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'email':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" class="email">' . preg_replace('/\\?.*$/', '', $strEmail) . '</a>';
                         break;
                     case 'email_open':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" class="email">';
                         break;
                     case 'email_url':
                         $arrCache[$strTag] = $strEmail;
                         break;
                 }
                 break;
                 // Label tags
             // Label tags
             case 'label':
                 $keys = explode(':', $elements[1]);
                 if (count($keys) < 2) {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $this->loadLanguageFile($keys[0]);
                 if (count($keys) == 2) {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]];
                 } else {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]][$keys[2]];
                 }
                 break;
                 // Front end user
             // Front end user
             case 'user':
                 if (FE_USER_LOGGED_IN) {
                     $this->import('FrontendUser', 'User');
                     $value = $this->User->{$elements}[1];
                     if ($value == '') {
                         $arrCache[$strTag] = $value;
                         break;
                     }
                     $this->loadDataContainer('tl_member');
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['inputType'] == 'password') {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $value = deserialize($value);
                     $rgxp = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['rgxp'];
                     $opts = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['options'];
                     $rfrc = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['reference'];
                     if ($rgxp == 'date') {
                         $arrCache[$strTag] = $this->parseDate($GLOBALS['TL_CONFIG']['dateFormat'], $value);
                     } elseif ($rgxp == 'time') {
                         $arrCache[$strTag] = $this->parseDate($GLOBALS['TL_CONFIG']['timeFormat'], $value);
                     } elseif ($rgxp == 'datim') {
                         $arrCache[$strTag] = $this->parseDate($GLOBALS['TL_CONFIG']['datimFormat'], $value);
                     } elseif (is_array($value)) {
                         $arrCache[$strTag] = implode(', ', $value);
                     } elseif (is_array($opts) && array_is_assoc($opts)) {
                         $arrCache[$strTag] = isset($opts[$value]) ? $opts[$value] : $value;
                     } elseif (is_array($rfrc)) {
                         $arrCache[$strTag] = isset($rfrc[$value]) ? is_array($rfrc[$value]) ? $rfrc[$value][0] : $rfrc[$value] : $value;
                     } else {
                         $arrCache[$strTag] = $value;
                     }
                     // Convert special characters (see #1890)
                     $arrCache[$strTag] = specialchars($arrCache[$strTag]);
                 }
                 break;
                 // Link
             // Link
             case 'link':
             case 'link_open':
             case 'link_url':
             case 'link_title':
                 // Back link
                 if ($elements[1] == 'back') {
                     $strUrl = 'javascript:history.go(-1)';
                     $strTitle = $GLOBALS['TL_LANG']['MSC']['goBack'];
                     // No language files if the page is cached
                     if (!strlen($strTitle)) {
                         $strTitle = 'Go back';
                     }
                     $strName = $strTitle;
                 } elseif (strncmp($elements[1], 'http://', 7) === 0 || strncmp($elements[1], 'https://', 8) === 0) {
                     $strUrl = $elements[1];
                     $strTitle = $elements[1];
                     $strName = str_replace(array('http://', 'https://'), '', $elements[1]);
                 } else {
                     // User login page
                     if ($elements[1] == 'login') {
                         if (!FE_USER_LOGGED_IN) {
                             break;
                         }
                         $this->import('FrontendUser', 'User');
                         $elements[1] = $this->User->loginPage;
                     }
                     $objNextPage = \PageModel::findByIdOrAlias($elements[1]);
                     if ($objNextPage === null) {
                         break;
                     }
                     // Page type specific settings (thanks to Andreas Schempp)
                     switch ($objNextPage->type) {
                         case 'redirect':
                             $strUrl = $objNextPage->url;
                             if (strncasecmp($strUrl, 'mailto:', 7) === 0) {
                                 $strUrl = \String::encodeEmail($strUrl);
                             }
                             break;
                         case 'forward':
                             if (($objTarget = $objNextPage->getRelated('jumpTo')) !== null) {
                                 $strUrl = $this->generateFrontendUrl($objTarget->row());
                                 break;
                             } elseif (($objTarget = \PageModel::findFirstPublishedRegularByPid($objNextPage->id)) !== null) {
                                 if ($GLOBALS['TL_CONFIG']['addLanguageToUrl']) {
                                     $objTarget = $this->getPageDetails($objTarget);
                                     // see #3983
                                     $strUrl = $this->generateFrontendUrl($objTarget->row(), null, $objTarget->language);
                                 } else {
                                     $strUrl = $this->generateFrontendUrl($objTarget->row());
                                 }
                                 break;
                             }
                             // DO NOT ADD A break; STATEMENT
                         // DO NOT ADD A break; STATEMENT
                         default:
                             if ($GLOBALS['TL_CONFIG']['addLanguageToUrl']) {
                                 $objNextPage = $this->getPageDetails($objNextPage);
                                 // see #3983
                                 $strUrl = $this->generateFrontendUrl($objNextPage->row(), null, $objNextPage->language);
                             } else {
                                 $strUrl = $this->generateFrontendUrl($objNextPage->row());
                             }
                             break;
                     }
                     $strName = $objNextPage->title;
                     $strTarget = $objNextPage->target ? $objPage->outputFormat == 'xhtml' ? LINK_NEW_WINDOW : ' target="_blank"' : '';
                     $strTitle = $objNextPage->pageTitle ?: $objNextPage->title;
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'link':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>%s</a>', $strUrl, specialchars($strTitle), $strTarget, specialchars($strName));
                         break;
                     case 'link_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>', $strUrl, specialchars($strTitle), $strTarget);
                         break;
                     case 'link_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'link_title':
                         $arrCache[$strTag] = specialchars($strTitle);
                         break;
                     case 'link_target':
                         $arrCache[$strTag] = $strTarget;
                         break;
                 }
                 break;
                 // Closing link tag
             // Closing link tag
             case 'link_close':
                 $arrCache[$strTag] = '</a>';
                 break;
                 // Insert article
             // Insert article
             case 'insert_article':
                 if (($strOutput = $this->getArticle($elements[1], false, true)) !== false) {
                     $arrCache[$strTag] = $this->replaceInsertTags(ltrim($strOutput));
                 } else {
                     $arrCache[$strTag] = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], $elements[1]) . '</p>';
                 }
                 break;
                 // Insert content element
             // Insert content element
             case 'insert_content':
                 $arrCache[$strTag] = $this->replaceInsertTags($this->getContentElement($elements[1]));
                 break;
                 // Insert module
             // Insert module
             case 'insert_module':
                 $arrCache[$strTag] = $this->replaceInsertTags($this->getFrontendModule($elements[1]));
                 break;
                 // Insert form
             // Insert form
             case 'insert_form':
                 $arrCache[$strTag] = $this->replaceInsertTags($this->getForm($elements[1]));
                 break;
                 // Article
             // Article
             case 'article':
             case 'article_open':
             case 'article_url':
             case 'article_title':
                 $objArticle = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objArticle === null) {
                     break;
                 } else {
                     $strUrl = $this->generateFrontendUrl($objArticle->row(), '/articles/' . (!$GLOBALS['TL_CONFIG']['disableAlias'] && strlen($objArticle->alias) ? $objArticle->alias : $objArticle->id));
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'article':
                         $strLink = specialchars($objArticle->title);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'article_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objArticle->title));
                         break;
                     case 'article_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'article_title':
                         $arrCache[$strTag] = specialchars($objArticle->title);
                         break;
                 }
                 break;
                 // FAQ
             // FAQ
             case 'faq':
             case 'faq_open':
             case 'faq_url':
             case 'faq_title':
                 $objFaq = \FaqModel::findByIdOrAlias($elements[1]);
                 if ($objFaq === null) {
                     break;
                 } else {
                     $strUrl = $this->generateFrontendUrl($objFaq->row(), ($GLOBALS['TL_CONFIG']['useAutoItem'] ? '/' : '/items/') . (!$GLOBALS['TL_CONFIG']['disableAlias'] && $objFaq->alias != '' ? $objFaq->alias : $objFaq->id));
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'faq':
                         $strLink = specialchars($objFaq->question);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'faq_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objFaq->question));
                         break;
                     case 'faq_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'faq_title':
                         $arrCache[$strTag] = specialchars($objFaq->question);
                         break;
                 }
                 break;
                 // News
             // News
             case 'news':
             case 'news_open':
             case 'news_url':
             case 'news_title':
                 $objNews = \NewsModel::findByIdOrAlias($elements[1]);
                 if ($objNews === null) {
                     break;
                 } elseif ($objNews->source == 'internal') {
                     $strUrl = $this->generateFrontendUrl($objNews->getRelated('jumpTo')->row());
                 } elseif ($objNews->source == 'article') {
                     $objArticle = \ArticleModel::findByPk($objNews->articleId, array('eager' => true));
                     $strUrl = $this->generateFrontendUrl($objArticle->pid, '/articles/' . (!$GLOBALS['TL_CONFIG']['disableAlias'] && $objArticle->alias != '' ? $objArticle->alias : $objArticle->id));
                 } elseif ($objNews->source == 'external') {
                     $strUrl = $objNews->url;
                 } else {
                     $strUrl = $this->generateFrontendUrl($objNews->pid, ($GLOBALS['TL_CONFIG']['useAutoItem'] ? '/' : '/items/') . (!$GLOBALS['TL_CONFIG']['disableAlias'] && $objNews->alias != '' ? $objNews->alias : $objNews->id));
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'news':
                         $strLink = specialchars($objNews->headline);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'news_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objNews->headline));
                         break;
                     case 'news_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'news_title':
                         $arrCache[$strTag] = specialchars($objNews->headline);
                         break;
                 }
                 break;
                 // Events
             // Events
             case 'event':
             case 'event_open':
             case 'event_url':
             case 'event_title':
                 $objEvent = \CalendarEventsModel::findByIdOrAlias($elements[1]);
                 if ($objEvent === null) {
                     break;
                 } elseif ($objEvent->source == 'internal') {
                     $strUrl = $this->generateFrontendUrl($objEvent->getRelated('jumpTo')->row());
                 } elseif ($objEvent->source == 'article') {
                     $objArticle = \ArticleModel::findByPk($objEvent->articleId, array('eager' => true));
                     $strUrl = $this->generateFrontendUrl($objArticle->pid, '/articles/' . (!$GLOBALS['TL_CONFIG']['disableAlias'] && $objArticle->alias != '' ? $objArticle->alias : $objArticle->id));
                 } elseif ($objEvent->source == 'external') {
                     $strUrl = $objEvent->url;
                 } else {
                     $strUrl = $this->generateFrontendUrl($objEvent->pid, ($GLOBALS['TL_CONFIG']['useAutoItem'] ? '/' : '/events/') . (!$GLOBALS['TL_CONFIG']['disableAlias'] && $objEvent->alias != '' ? $objEvent->alias : $objEvent->id));
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'event':
                         $strLink = specialchars($objEvent->title);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'event_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objEvent->title));
                         break;
                     case 'event_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'event_title':
                         $arrCache[$strTag] = specialchars($objEvent->title);
                         break;
                 }
                 break;
                 // Article teaser
             // Article teaser
             case 'article_teaser':
                 $objTeaser = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     if ($objPage->outputFormat == 'xhtml') {
                         $arrCache[$strTag] = \String::toXhtml($this->replaceInsertTags($objTeaser->teaser));
                     } else {
                         $arrCache[$strTag] = \String::toHtml5($this->replaceInsertTags($objTeaser->teaser));
                     }
                 }
                 break;
                 // News teaser
             // News teaser
             case 'news_teaser':
                 $objTeaser = \NewsModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     if ($objPage->outputFormat == 'xhtml') {
                         $arrCache[$strTag] = \String::toXhtml($objTeaser->teaser);
                     } else {
                         $arrCache[$strTag] = \String::toHtml5($objTeaser->teaser);
                     }
                 }
                 break;
                 // Event teaser
             // Event teaser
             case 'event_teaser':
                 $objTeaser = \CalendarEventsModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     if ($objPage->outputFormat == 'xhtml') {
                         $arrCache[$strTag] = \String::toXhtml($objTeaser->teaser);
                     } else {
                         $arrCache[$strTag] = \String::toHtml5($objTeaser->teaser);
                     }
                 }
                 break;
                 // News feed URL
             // News feed URL
             case 'news_feed':
                 // FIXME: feeds are now in tl_calendar_feed
                 $objFeed = \NewsArchiveModel::findByPk($elements[1]);
                 if ($objFeed !== null) {
                     $arrCache[$strTag] = $objFeed->feedBase . $objFeed->alias . '.xml';
                 }
                 break;
                 // Calendar feed URL
             // Calendar feed URL
             case 'calendar_feed':
                 // FIXME: feeds are now in tl_calendar_feed
                 $objFeed = \CalendarModel::findByPk($elements[1]);
                 if ($objFeed !== null) {
                     $arrCache[$strTag] = $objFeed->feedBase . $objFeed->alias . '.xml';
                 }
                 break;
                 // Last update
             // Last update
             case 'last_update':
                 $objUpdate = \Database::getInstance()->execute("SELECT MAX(tstamp) AS tc, (SELECT MAX(tstamp) FROM tl_news) AS tn, (SELECT MAX(tstamp) FROM tl_calendar_events) AS te FROM tl_content");
                 if ($objUpdate->numRows) {
                     $arrCache[$strTag] = $this->parseDate($elements[1] ?: $GLOBALS['TL_CONFIG']['datimFormat'], max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
                 }
                 break;
                 // Version
             // Version
             case 'version':
                 $arrCache[$strTag] = VERSION . '.' . BUILD;
                 break;
                 // Request token
             // Request token
             case 'request_token':
                 $arrCache[$strTag] = REQUEST_TOKEN;
                 break;
                 // Conditional tags
             // Conditional tags
             case 'iflng':
                 if ($elements[1] != '' && $elements[1] != $objPage->language) {
                     for ($_rit; $_rit < count($tags); $_rit += 2) {
                         if ($tags[$_rit + 1] == 'iflng') {
                             break;
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
             case 'ifnlng':
                 if ($elements[1] != '') {
                     $langs = trimsplit(',', $elements[1]);
                     if (in_array($objPage->language, $langs)) {
                         for ($_rit; $_rit < count($tags); $_rit += 2) {
                             if ($tags[$_rit + 1] == 'ifnlng') {
                                 break;
                             }
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Environment
             // Environment
             case 'env':
                 switch ($elements[1]) {
                     case 'host':
                         $arrCache[$strTag] = \Environment::get('host');
                         break;
                     case 'http_host':
                         $arrCache[$strTag] = \Environment::get('httpHost');
                         break;
                     case 'url':
                         $arrCache[$strTag] = \Environment::get('url');
                         break;
                     case 'path':
                         $arrCache[$strTag] = \Environment::get('base');
                         break;
                     case 'request':
                         $arrCache[$strTag] = $this->getIndexFreeRequest(true);
                         break;
                     case 'ip':
                         $arrCache[$strTag] = \Environment::get('ip');
                         break;
                     case 'referer':
                         $arrCache[$strTag] = $this->getReferer(true);
                         break;
                     case 'files_url':
                         $arrCache[$strTag] = TL_FILES_URL;
                         break;
                     case 'script_url':
                         $arrCache[$strTag] = TL_SCRIPT_URL;
                         break;
                     case 'plugins_url':
                         $arrCache[$strTag] = TL_PLUGINS_URL;
                         break;
                 }
                 break;
                 // Page
             // Page
             case 'page':
                 if ($elements[1] == 'pageTitle' && $objPage->pageTitle == '') {
                     $elements[1] = 'title';
                 } elseif ($elements[1] == 'parentPageTitle' && $objPage->parentPageTitle == '') {
                     $elements[1] = 'parentTitle';
                 } elseif ($elements[1] == 'mainPageTitle' && $objPage->mainPageTitle == '') {
                     $elements[1] = 'mainTitle';
                 }
                 $arrCache[$strTag] = specialchars($objPage->{$elements[1]});
                 break;
                 // User agent
             // User agent
             case 'ua':
                 $ua = \Environment::get('agent');
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = $ua->{$elements[1]};
                 } else {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Acronyms
             // Acronyms
             case 'acronym':
                 if ($objPage->outputFormat == 'xhtml') {
                     if ($elements[1] != '') {
                         $arrCache[$strTag] = '<acronym title="' . $elements[1] . '">';
                     } else {
                         $arrCache[$strTag] = '</acronym>';
                     }
                     break;
                 }
                 // NO break;
                 // Abbreviations
             // NO break;
             // Abbreviations
             case 'abbr':
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = '<abbr title="' . $elements[1] . '">';
                 } else {
                     $arrCache[$strTag] = '</abbr>';
                 }
                 break;
                 // Images
             // Images
             case 'image':
                 $width = null;
                 $height = null;
                 $alt = '';
                 $class = '';
                 $rel = '';
                 $strFile = $elements[1];
                 $mode = '';
                 // Take arguments
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]), 2);
                     $strSource = \String::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         list($key, $value) = explode('=', $strParam);
                         switch ($key) {
                             case 'width':
                                 $width = $value;
                                 break;
                             case 'height':
                                 $height = $value;
                                 break;
                             case 'alt':
                                 $alt = specialchars($value);
                                 break;
                             case 'class':
                                 $class = $value;
                                 break;
                             case 'rel':
                                 $rel = $value;
                                 break;
                             case 'mode':
                                 $mode = $value;
                                 break;
                         }
                     }
                     $strFile = $arrChunks[0];
                 }
                 // Sanitize path
                 $strFile = str_replace('../', '', $strFile);
                 // Check maximum image width
                 if ($GLOBALS['TL_CONFIG']['maxImageWidth'] > 0 && $width > $GLOBALS['TL_CONFIG']['maxImageWidth']) {
                     $width = $GLOBALS['TL_CONFIG']['maxImageWidth'];
                     $height = null;
                 }
                 // Generate the thumbnail image
                 try {
                     $src = \Image::get($strFile, $width, $height, $mode);
                     $dimensions = '';
                     // Add the image dimensions
                     if (($imgSize = @getimagesize(TL_ROOT . '/' . rawurldecode($src))) !== false) {
                         $dimensions = $imgSize[3];
                     }
                     // Generate the HTML markup
                     if ($rel != '') {
                         if (strncmp($rel, 'lightbox', 8) !== 0 || $objPage->outputFormat == 'xhtml') {
                             $attribute = ' rel="' . $rel . '"';
                         } else {
                             $attribute = ' data-lightbox="' . substr($rel, 8) . '"';
                         }
                         $arrCache[$strTag] = '<a href="' . TL_FILES_URL . $strFile . '"' . ($alt != '' ? ' title="' . $alt . '"' : '') . $attribute . '><img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . $alt . '"' . ($class != '' ? ' class="' . $class . '"' : '') . ($objPage->outputFormat == 'xhtml' ? ' />' : '>') . '</a>';
                     } else {
                         $arrCache[$strTag] = '<img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . $alt . '"' . ($class != '' ? ' class="' . $class . '"' : '') . ($objPage->outputFormat == 'xhtml' ? ' />' : '>');
                     }
                 } catch (Exception $e) {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Files from the templates directory
             // Files from the templates directory
             case 'file':
                 $arrGet = $_GET;
                 \Input::resetCache();
                 $strFile = $elements[1];
                 // Take arguments and add them to the $_GET array
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]));
                     $strSource = \String::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         $arrParam = explode('=', $strParam);
                         $_GET[$arrParam[0]] = $arrParam[1];
                     }
                     $strFile = $arrChunks[0];
                 }
                 // Sanitize path
                 $strFile = str_replace('../', '', $strFile);
                 // Include .php, .tpl, .xhtml and .html5 files
                 if (preg_match('/\\.(php|tpl|xhtml|html5)$/', $strFile) && file_exists(TL_ROOT . '/templates/' . $strFile)) {
                     ob_start();
                     include TL_ROOT . '/templates/' . $strFile;
                     $arrCache[$strTag] = ob_get_contents();
                     ob_end_clean();
                 }
                 $_GET = $arrGet;
                 \Input::resetCache();
                 break;
                 // HOOK: pass unknown tags to callback functions
             // HOOK: pass unknown tags to callback functions
             default:
                 if (isset($GLOBALS['TL_HOOKS']['replaceInsertTags']) && is_array($GLOBALS['TL_HOOKS']['replaceInsertTags'])) {
                     foreach ($GLOBALS['TL_HOOKS']['replaceInsertTags'] as $callback) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback}[0]->{$callback}[1]($strTag);
                         // Replace the tag and stop the loop
                         if ($varValue !== false) {
                             $arrCache[$strTag] = $varValue;
                             break;
                         }
                     }
                 }
                 break;
         }
         $strBuffer .= $arrCache[$strTag];
     }
     return $this->restoreBasicEntities($strBuffer);
 }
예제 #22
0
 /**
  * Replace insert tags with their values
  *
  * @param string  $strBuffer The text with the tags to be replaced
  * @param boolean $blnCache  If false, non-cacheable tags will be replaced
  *
  * @return string The text with the replaced tags
  */
 public function replace($strBuffer, $blnCache = true)
 {
     /** @var \PageModel $objPage */
     global $objPage;
     // Preserve insert tags
     if (\Config::get('disableInsertTags')) {
         return \String::restoreBasicEntities($strBuffer);
     }
     $tags = preg_split('/\\{\\{(([^\\{\\}]*|(?R))*)\\}\\}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
     $strBuffer = '';
     // Create one cache per cache setting (see #7700)
     static $arrItCache;
     $arrCache =& $arrItCache[$blnCache];
     for ($_rit = 0, $_cnt = count($tags); $_rit < $_cnt; $_rit += 3) {
         $strBuffer .= $tags[$_rit];
         $strTag = $tags[$_rit + 1];
         // Skip empty tags
         if ($strTag == '') {
             continue;
         }
         // Run the replacement again if there are more tags (see #4402)
         if (strpos($strTag, '{{') !== false) {
             $strTag = $this->replace($strTag, $blnCache);
         }
         $flags = explode('|', $strTag);
         $tag = array_shift($flags);
         $elements = explode('::', $tag);
         // Load the value from cache
         if (isset($arrCache[$strTag]) && !in_array('refresh', $flags)) {
             $strBuffer .= $arrCache[$strTag];
             continue;
         }
         // Skip certain elements if the output will be cached
         if ($blnCache) {
             if ($elements[0] == 'date' || $elements[0] == 'ua' || $elements[0] == 'post' || $elements[0] == 'file' || $elements[1] == 'back' || $elements[1] == 'referer' || $elements[0] == 'request_token' || $elements[0] == 'toggle_view' || strncmp($elements[0], 'cache_', 6) === 0 || in_array('uncached', $flags)) {
                 $strBuffer .= '{{' . $strTag . '}}';
                 continue;
             }
         }
         $arrCache[$strTag] = '';
         // Replace the tag
         switch (strtolower($elements[0])) {
             // Date
             case 'date':
                 $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('dateFormat'));
                 break;
                 // Accessibility tags
             // Accessibility tags
             case 'lang':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '</span>';
                 } elseif ($objPage->outputFormat == 'xhtml') {
                     $arrCache[$strTag] = '<span lang="' . $elements[1] . '" xml:lang="' . $elements[1] . '">';
                 } else {
                     $arrCache[$strTag] = $arrCache[$strTag] = '<span lang="' . $elements[1] . '">';
                 }
                 break;
                 // Line break
             // Line break
             case 'br':
                 $arrCache[$strTag] = '<br' . ($objPage->outputFormat == 'xhtml' ? ' />' : '>');
                 break;
                 // E-mail addresses
             // E-mail addresses
             case 'email':
             case 'email_open':
             case 'email_url':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $strEmail = \String::encodeEmail($elements[1]);
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'email':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" class="email">' . preg_replace('/\\?.*$/', '', $strEmail) . '</a>';
                         break;
                     case 'email_open':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" title="' . $strEmail . '" class="email">';
                         break;
                     case 'email_url':
                         $arrCache[$strTag] = $strEmail;
                         break;
                 }
                 break;
                 // Label tags
             // Label tags
             case 'label':
                 $keys = explode(':', $elements[1]);
                 if (count($keys) < 2) {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $file = $keys[0];
                 // Map the key (see #7217)
                 switch ($file) {
                     case 'CNT':
                         $file = 'countries';
                         break;
                     case 'LNG':
                         $file = 'languages';
                         break;
                     case 'MOD':
                     case 'FMD':
                         $file = 'modules';
                         break;
                     case 'FFL':
                         $file = 'tl_form_field';
                         break;
                     case 'CACHE':
                         $file = 'tl_page';
                         break;
                     case 'XPL':
                         $file = 'explain';
                         break;
                     case 'XPT':
                         $file = 'exception';
                         break;
                     case 'MSC':
                     case 'ERR':
                     case 'CTE':
                     case 'PTY':
                     case 'FOP':
                     case 'CHMOD':
                     case 'DAYS':
                     case 'MONTHS':
                     case 'UNITS':
                     case 'CONFIRM':
                     case 'DP':
                     case 'COLS':
                         $file = 'default';
                         break;
                 }
                 \System::loadLanguageFile($file);
                 if (count($keys) == 2) {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]];
                 } else {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]][$keys[2]];
                 }
                 break;
                 // Front end user
             // Front end user
             case 'user':
                 if (FE_USER_LOGGED_IN) {
                     $this->import('FrontendUser', 'User');
                     $value = $this->User->{$elements}[1];
                     if ($value == '') {
                         $arrCache[$strTag] = $value;
                         break;
                     }
                     $this->loadDataContainer('tl_member');
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['inputType'] == 'password') {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $value = deserialize($value);
                     // Decrypt the value
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['encrypt']) {
                         $value = \Encryption::decrypt($value);
                     }
                     $rgxp = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['rgxp'];
                     $opts = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['options'];
                     $rfrc = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['reference'];
                     if ($rgxp == 'date') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('dateFormat'), $value);
                     } elseif ($rgxp == 'time') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('timeFormat'), $value);
                     } elseif ($rgxp == 'datim') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('datimFormat'), $value);
                     } elseif (is_array($value)) {
                         $arrCache[$strTag] = implode(', ', $value);
                     } elseif (is_array($opts) && array_is_assoc($opts)) {
                         $arrCache[$strTag] = isset($opts[$value]) ? $opts[$value] : $value;
                     } elseif (is_array($rfrc)) {
                         $arrCache[$strTag] = isset($rfrc[$value]) ? is_array($rfrc[$value]) ? $rfrc[$value][0] : $rfrc[$value] : $value;
                     } else {
                         $arrCache[$strTag] = $value;
                     }
                     // Convert special characters (see #1890)
                     $arrCache[$strTag] = specialchars($arrCache[$strTag]);
                 }
                 break;
                 // Link
             // Link
             case 'link':
             case 'link_open':
             case 'link_url':
             case 'link_title':
             case 'link_target':
             case 'link_name':
                 $strTarget = null;
                 // Back link
                 if ($elements[1] == 'back') {
                     $strUrl = 'javascript:history.go(-1)';
                     $strTitle = $GLOBALS['TL_LANG']['MSC']['goBack'];
                     // No language files if the page is cached
                     if (!strlen($strTitle)) {
                         $strTitle = 'Go back';
                     }
                     $strName = $strTitle;
                 } elseif (strncmp($elements[1], 'http://', 7) === 0 || strncmp($elements[1], 'https://', 8) === 0) {
                     $strUrl = $elements[1];
                     $strTitle = $elements[1];
                     $strName = str_replace(array('http://', 'https://'), '', $elements[1]);
                 } else {
                     // User login page
                     if ($elements[1] == 'login') {
                         if (!FE_USER_LOGGED_IN) {
                             break;
                         }
                         $this->import('FrontendUser', 'User');
                         $elements[1] = $this->User->loginPage;
                     }
                     $objNextPage = \PageModel::findByIdOrAlias($elements[1]);
                     if ($objNextPage === null) {
                         break;
                     }
                     // Page type specific settings (thanks to Andreas Schempp)
                     switch ($objNextPage->type) {
                         case 'redirect':
                             $strUrl = $this->replaceInsertTags($objNextPage->url);
                             // see #6765
                             if (strncasecmp($strUrl, 'mailto:', 7) === 0) {
                                 $strUrl = \String::encodeEmail($strUrl);
                             }
                             break;
                         case 'forward':
                             if ($objNextPage->jumpTo) {
                                 /** @var \PageModel $objNext */
                                 $objNext = $objNextPage->getRelated('jumpTo');
                             } else {
                                 $objNext = \PageModel::findFirstPublishedRegularByPid($objNextPage->id);
                             }
                             if ($objNext !== null) {
                                 $strForceLang = null;
                                 $objNext->loadDetails();
                                 // Check the target page language (see #4706)
                                 if (\Config::get('addLanguageToUrl')) {
                                     $strForceLang = $objNext->language;
                                 }
                                 $strUrl = $this->generateFrontendUrl($objNext->row(), null, $strForceLang, true);
                                 break;
                             }
                             // DO NOT ADD A break; STATEMENT
                         // DO NOT ADD A break; STATEMENT
                         default:
                             $strForceLang = null;
                             $objNextPage->loadDetails();
                             // Check the target page language (see #4706, #5465)
                             if (\Config::get('addLanguageToUrl')) {
                                 $strForceLang = $objNextPage->language;
                             }
                             $strUrl = $this->generateFrontendUrl($objNextPage->row(), null, $strForceLang, true);
                             break;
                     }
                     $strName = $objNextPage->title;
                     $strTarget = $objNextPage->target ? $objPage->outputFormat == 'xhtml' ? LINK_NEW_WINDOW : ' target="_blank"' : '';
                     $strTitle = $objNextPage->pageTitle ?: $objNextPage->title;
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'link':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>%s</a>', $strUrl, specialchars($strTitle), $strTarget, specialchars($strName));
                         break;
                     case 'link_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>', $strUrl, specialchars($strTitle), $strTarget);
                         break;
                     case 'link_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'link_title':
                         $arrCache[$strTag] = specialchars($strTitle);
                         break;
                     case 'link_target':
                         $arrCache[$strTag] = $strTarget;
                         break;
                     case 'link_name':
                         $arrCache[$strTag] = specialchars($strName);
                         break;
                 }
                 break;
                 // Closing link tag
             // Closing link tag
             case 'link_close':
                 $arrCache[$strTag] = '</a>';
                 break;
                 // Insert article
             // Insert article
             case 'insert_article':
                 if (($strOutput = $this->getArticle($elements[1], false, true)) !== false) {
                     $arrCache[$strTag] = $this->replaceInsertTags(ltrim($strOutput), $blnCache);
                 } else {
                     $arrCache[$strTag] = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], $elements[1]) . '</p>';
                 }
                 break;
                 // Insert content element
             // Insert content element
             case 'insert_content':
                 $arrCache[$strTag] = $this->replaceInsertTags($this->getContentElement($elements[1]), $blnCache);
                 break;
                 // Insert module
             // Insert module
             case 'insert_module':
                 $arrCache[$strTag] = $this->replaceInsertTags($this->getFrontendModule($elements[1]), $blnCache);
                 break;
                 // Insert form
             // Insert form
             case 'insert_form':
                 $arrCache[$strTag] = $this->replaceInsertTags($this->getForm($elements[1]), $blnCache);
                 break;
                 // Article
             // Article
             case 'article':
             case 'article_open':
             case 'article_url':
             case 'article_title':
                 if (($objArticle = \ArticleModel::findByIdOrAlias($elements[1])) === null || ($objPid = $objArticle->getRelated('pid')) === null) {
                     break;
                 }
                 $strUrl = $this->generateFrontendUrl($objPid->row(), '/articles/' . (!\Config::get('disableAlias') && strlen($objArticle->alias) ? $objArticle->alias : $objArticle->id));
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'article':
                         $strLink = specialchars($objArticle->title);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'article_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objArticle->title));
                         break;
                     case 'article_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'article_title':
                         $arrCache[$strTag] = specialchars($objArticle->title);
                         break;
                 }
                 break;
                 // FAQ
             // FAQ
             case 'faq':
             case 'faq_open':
             case 'faq_url':
             case 'faq_title':
                 if (($objFaq = \FaqModel::findByIdOrAlias($elements[1])) === null || ($objPid = $objFaq->getRelated('pid')) === null || ($objJumpTo = $objPid->getRelated('jumpTo')) === null) {
                     break;
                 }
                 $strUrl = $this->generateFrontendUrl($objJumpTo->row(), (\Config::get('useAutoItem') && !\Config::get('disableAlias') ? '/' : '/items/') . (!\Config::get('disableAlias') && $objFaq->alias != '' ? $objFaq->alias : $objFaq->id));
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'faq':
                         $strLink = specialchars($objFaq->question);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'faq_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objFaq->question));
                         break;
                     case 'faq_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'faq_title':
                         $arrCache[$strTag] = specialchars($objFaq->question);
                         break;
                 }
                 break;
                 // News
             // News
             case 'news':
             case 'news_open':
             case 'news_url':
             case 'news_title':
                 if (($objNews = \NewsModel::findByIdOrAlias($elements[1])) === null) {
                     break;
                 }
                 $strUrl = '';
                 if ($objNews->source == 'external') {
                     $strUrl = $objNews->url;
                 } elseif ($objNews->source == 'internal') {
                     if (($objJumpTo = $objNews->getRelated('jumpTo')) !== null) {
                         $strUrl = $this->generateFrontendUrl($objJumpTo->row());
                     }
                 } elseif ($objNews->source == 'article') {
                     if (($objArticle = \ArticleModel::findByPk($objNews->articleId, array('eager' => true))) !== null && ($objPid = $objArticle->getRelated('pid')) !== null) {
                         $strUrl = $this->generateFrontendUrl($objPid->row(), '/articles/' . (!\Config::get('disableAlias') && $objArticle->alias != '' ? $objArticle->alias : $objArticle->id));
                     }
                 } else {
                     if (($objArchive = $objNews->getRelated('pid')) !== null && ($objJumpTo = $objArchive->getRelated('jumpTo')) !== null) {
                         $strUrl = $this->generateFrontendUrl($objJumpTo->row(), (\Config::get('useAutoItem') && !\Config::get('disableAlias') ? '/' : '/items/') . (!\Config::get('disableAlias') && $objNews->alias != '' ? $objNews->alias : $objNews->id));
                     }
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'news':
                         $strLink = specialchars($objNews->headline);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'news_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objNews->headline));
                         break;
                     case 'news_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'news_title':
                         $arrCache[$strTag] = specialchars($objNews->headline);
                         break;
                 }
                 break;
                 // Events
             // Events
             case 'event':
             case 'event_open':
             case 'event_url':
             case 'event_title':
                 if (($objEvent = \CalendarEventsModel::findByIdOrAlias($elements[1])) === null) {
                     break;
                 }
                 $strUrl = '';
                 if ($objEvent->source == 'external') {
                     $strUrl = $objEvent->url;
                 } elseif ($objEvent->source == 'internal') {
                     if (($objJumpTo = $objEvent->getRelated('jumpTo')) !== null) {
                         $strUrl = $this->generateFrontendUrl($objJumpTo->row());
                     }
                 } elseif ($objEvent->source == 'article') {
                     if (($objArticle = \ArticleModel::findByPk($objEvent->articleId, array('eager' => true))) !== null && ($objPid = $objArticle->getRelated('pid')) !== null) {
                         $strUrl = $this->generateFrontendUrl($objPid->row(), '/articles/' . (!\Config::get('disableAlias') && $objArticle->alias != '' ? $objArticle->alias : $objArticle->id));
                     }
                 } else {
                     if (($objCalendar = $objEvent->getRelated('pid')) !== null && ($objJumpTo = $objCalendar->getRelated('jumpTo')) !== null) {
                         $strUrl = $this->generateFrontendUrl($objJumpTo->row(), (\Config::get('useAutoItem') && !\Config::get('disableAlias') ? '/' : '/events/') . (!\Config::get('disableAlias') && $objEvent->alias != '' ? $objEvent->alias : $objEvent->id));
                     }
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'event':
                         $strLink = specialchars($objEvent->title);
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, $strLink, $strLink);
                         break;
                     case 'event_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, specialchars($objEvent->title));
                         break;
                     case 'event_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'event_title':
                         $arrCache[$strTag] = specialchars($objEvent->title);
                         break;
                 }
                 break;
                 // Article teaser
             // Article teaser
             case 'article_teaser':
                 $objTeaser = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     if ($objPage->outputFormat == 'xhtml') {
                         $arrCache[$strTag] = \String::toXhtml($this->replaceInsertTags($objTeaser->teaser, $blnCache));
                     } else {
                         $arrCache[$strTag] = \String::toHtml5($this->replaceInsertTags($objTeaser->teaser, $blnCache));
                     }
                 }
                 break;
                 // News teaser
             // News teaser
             case 'news_teaser':
                 $objTeaser = \NewsModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     if ($objPage->outputFormat == 'xhtml') {
                         $arrCache[$strTag] = \String::toXhtml($this->replaceInsertTags($objTeaser->teaser, $blnCache));
                     } else {
                         $arrCache[$strTag] = \String::toHtml5($this->replaceInsertTags($objTeaser->teaser, $blnCache));
                     }
                 }
                 break;
                 // Event teaser
             // Event teaser
             case 'event_teaser':
                 $objTeaser = \CalendarEventsModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     if ($objPage->outputFormat == 'xhtml') {
                         $arrCache[$strTag] = \String::toXhtml($this->replaceInsertTags($objTeaser->teaser, $blnCache));
                     } else {
                         $arrCache[$strTag] = \String::toHtml5($this->replaceInsertTags($objTeaser->teaser, $blnCache));
                     }
                 }
                 break;
                 // News feed URL
             // News feed URL
             case 'news_feed':
                 $objFeed = \NewsFeedModel::findByPk($elements[1]);
                 if ($objFeed !== null) {
                     $arrCache[$strTag] = $objFeed->feedBase . 'share/' . $objFeed->alias . '.xml';
                 }
                 break;
                 // Calendar feed URL
             // Calendar feed URL
             case 'calendar_feed':
                 $objFeed = \CalendarFeedModel::findByPk($elements[1]);
                 if ($objFeed !== null) {
                     $arrCache[$strTag] = $objFeed->feedBase . 'share/' . $objFeed->alias . '.xml';
                 }
                 break;
                 // Last update
             // Last update
             case 'last_update':
                 $strQuery = "SELECT MAX(tstamp) AS tc";
                 if (in_array('news', \ModuleLoader::getActive())) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_news) AS tn";
                 }
                 if (in_array('calendar', \ModuleLoader::getActive())) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_calendar_events) AS te";
                 }
                 $strQuery .= " FROM tl_content";
                 $objUpdate = \Database::getInstance()->query($strQuery);
                 if ($objUpdate->numRows) {
                     $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('datimFormat'), max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
                 }
                 break;
                 // Version
             // Version
             case 'version':
                 $arrCache[$strTag] = VERSION . '.' . BUILD;
                 break;
                 // Request token
             // Request token
             case 'request_token':
                 $arrCache[$strTag] = REQUEST_TOKEN;
                 break;
                 // POST data
             // POST data
             case 'post':
                 $arrCache[$strTag] = \Input::post($elements[1]);
                 break;
                 // Mobile/desktop toggle (see #6469)
             // Mobile/desktop toggle (see #6469)
             case 'toggle_view':
                 $strUrl = ampersand(\Environment::get('request'));
                 $strGlue = strpos($strUrl, '?') === false ? '?' : '&amp;';
                 if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=desktop" class="toggle_desktop" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['toggleDesktop'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleDesktop'][0] . '</a>';
                 } else {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=mobile" class="toggle_mobile" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['toggleMobile'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleMobile'][0] . '</a>';
                 }
                 break;
                 // Conditional tags (if)
             // Conditional tags (if)
             case 'iflng':
                 if ($elements[1] != '' && $elements[1] != $objPage->language) {
                     for (; $_rit < $_cnt; $_rit += 3) {
                         if ($tags[$_rit + 1] == 'iflng' || $tags[$_rit + 1] == 'iflng::' . $objPage->language) {
                             break;
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Conditional tags (if not)
             // Conditional tags (if not)
             case 'ifnlng':
                 if ($elements[1] != '') {
                     $langs = trimsplit(',', $elements[1]);
                     if (in_array($objPage->language, $langs)) {
                         for (; $_rit < $_cnt; $_rit += 3) {
                             if ($tags[$_rit + 1] == 'ifnlng') {
                                 break;
                             }
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Environment
             // Environment
             case 'env':
                 switch ($elements[1]) {
                     case 'host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('host'));
                         break;
                     case 'http_host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('httpHost'));
                         break;
                     case 'url':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('url'));
                         break;
                     case 'path':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('base'));
                         break;
                     case 'request':
                         $arrCache[$strTag] = \Environment::get('indexFreeRequest');
                         break;
                     case 'ip':
                         $arrCache[$strTag] = \Environment::get('ip');
                         break;
                     case 'referer':
                         $arrCache[$strTag] = $this->getReferer(true);
                         break;
                     case 'files_url':
                         $arrCache[$strTag] = TL_FILES_URL;
                         break;
                     case 'assets_url':
                     case 'plugins_url':
                     case 'script_url':
                         $arrCache[$strTag] = TL_ASSETS_URL;
                         break;
                 }
                 break;
                 // Page
             // Page
             case 'page':
                 if ($elements[1] == 'pageTitle' && $objPage->pageTitle == '') {
                     $elements[1] = 'title';
                 } elseif ($elements[1] == 'parentPageTitle' && $objPage->parentPageTitle == '') {
                     $elements[1] = 'parentTitle';
                 } elseif ($elements[1] == 'mainPageTitle' && $objPage->mainPageTitle == '') {
                     $elements[1] = 'mainTitle';
                 }
                 // Do not use specialchars() here (see #4687)
                 $arrCache[$strTag] = $objPage->{$elements[1]};
                 break;
                 // User agent
             // User agent
             case 'ua':
                 $ua = \Environment::get('agent');
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = $ua->{$elements[1]};
                 } else {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Acronyms
             // Acronyms
             case 'acronym':
                 if ($objPage->outputFormat == 'xhtml') {
                     if ($elements[1] != '') {
                         $arrCache[$strTag] = '<acronym title="' . $elements[1] . '">';
                     } else {
                         $arrCache[$strTag] = '</acronym>';
                     }
                     break;
                 }
                 // NO break;
                 // Abbreviations
             // NO break;
             // Abbreviations
             case 'abbr':
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = '<abbr title="' . $elements[1] . '">';
                 } else {
                     $arrCache[$strTag] = '</abbr>';
                 }
                 break;
                 // Images
             // Images
             case 'image':
             case 'picture':
                 $width = null;
                 $height = null;
                 $alt = '';
                 $class = '';
                 $rel = '';
                 $strFile = $elements[1];
                 $mode = '';
                 $size = null;
                 $strTemplate = 'picture_default';
                 // Take arguments
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]), 2);
                     $strSource = \String::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         list($key, $value) = explode('=', $strParam);
                         switch ($key) {
                             case 'width':
                                 $width = $value;
                                 break;
                             case 'height':
                                 $height = $value;
                                 break;
                             case 'alt':
                                 $alt = specialchars($value);
                                 break;
                             case 'class':
                                 $class = $value;
                                 break;
                             case 'rel':
                                 $rel = $value;
                                 break;
                             case 'mode':
                                 $mode = $value;
                                 break;
                             case 'size':
                                 $size = (int) $value;
                                 break;
                             case 'template':
                                 $strTemplate = preg_replace('/[^a-z0-9_]/i', '', $value);
                                 break;
                         }
                     }
                     $strFile = $arrChunks[0];
                 }
                 if (\Validator::isUuid($strFile)) {
                     // Handle UUIDs
                     $objFile = \FilesModel::findByUuid($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } elseif (is_numeric($strFile)) {
                     // Handle numeric IDs (see #4805)
                     $objFile = \FilesModel::findByPk($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } else {
                     // Check the path
                     if (\Validator::isInsecurePath($strFile)) {
                         throw new \RuntimeException('Invalid path ' . $strFile);
                     }
                 }
                 // Check the maximum image width
                 if (\Config::get('maxImageWidth') > 0 && $width > \Config::get('maxImageWidth')) {
                     $width = \Config::get('maxImageWidth');
                     $height = null;
                 }
                 // Generate the thumbnail image
                 try {
                     // Image
                     if (strtolower($elements[0]) == 'image') {
                         $dimensions = '';
                         $imageObj = \Image::create($strFile, array($width, $height, $mode));
                         $src = $imageObj->executeResize()->getResizedPath();
                         $objFile = new \File(rawurldecode($src), true);
                         // Add the image dimensions
                         if (($imgSize = $objFile->imageSize) !== false) {
                             $dimensions = ' width="' . $imgSize[0] . '" height="' . $imgSize[1] . '"';
                         }
                         $arrCache[$strTag] = '<img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . $alt . '"' . ($class != '' ? ' class="' . $class . '"' : '') . ($objPage->outputFormat == 'xhtml' ? ' />' : '>');
                     } else {
                         $picture = \Picture::create($strFile, array(0, 0, $size))->getTemplateData();
                         $picture['alt'] = $alt;
                         $picture['class'] = $class;
                         $pictureTemplate = new \FrontendTemplate($strTemplate);
                         $pictureTemplate->setData($picture);
                         $arrCache[$strTag] = $pictureTemplate->parse();
                     }
                     // Add a lightbox link
                     if ($rel != '') {
                         if (strncmp($rel, 'lightbox', 8) !== 0 || $objPage->outputFormat == 'xhtml') {
                             $attribute = ' rel="' . $rel . '"';
                         } else {
                             $attribute = ' data-lightbox="' . substr($rel, 8) . '"';
                         }
                         $arrCache[$strTag] = '<a href="' . TL_FILES_URL . $strFile . '"' . ($alt != '' ? ' title="' . $alt . '"' : '') . $attribute . '>' . $arrCache[$strTag] . '</a>';
                     }
                 } catch (\Exception $e) {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Files (UUID or template path)
             // Files (UUID or template path)
             case 'file':
                 if (\Validator::isUuid($elements[1])) {
                     $objFile = \FilesModel::findByUuid($elements[1]);
                     if ($objFile !== null) {
                         $arrCache[$strTag] = $objFile->path;
                         break;
                     }
                 }
                 $arrGet = $_GET;
                 \Input::resetCache();
                 $strFile = $elements[1];
                 // Take arguments and add them to the $_GET array
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]));
                     $strSource = \String::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         $arrParam = explode('=', $strParam);
                         $_GET[$arrParam[0]] = $arrParam[1];
                     }
                     $strFile = $arrChunks[0];
                 }
                 // Check the path
                 if (\Validator::isInsecurePath($strFile)) {
                     throw new \RuntimeException('Invalid path ' . $strFile);
                 }
                 // Include .php, .tpl, .xhtml and .html5 files
                 if (preg_match('/\\.(php|tpl|xhtml|html5)$/', $strFile) && file_exists(TL_ROOT . '/templates/' . $strFile)) {
                     ob_start();
                     include TL_ROOT . '/templates/' . $strFile;
                     $arrCache[$strTag] = ob_get_contents();
                     ob_end_clean();
                 }
                 $_GET = $arrGet;
                 \Input::resetCache();
                 break;
                 // HOOK: pass unknown tags to callback functions
             // HOOK: pass unknown tags to callback functions
             default:
                 if (isset($GLOBALS['TL_HOOKS']['replaceInsertTags']) && is_array($GLOBALS['TL_HOOKS']['replaceInsertTags'])) {
                     foreach ($GLOBALS['TL_HOOKS']['replaceInsertTags'] as $callback) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback}[0]->{$callback}[1]($tag, $blnCache, $arrCache[$strTag], $flags, $tags, $arrCache, $_rit, $_cnt);
                         // see #6672
                         // Replace the tag and stop the loop
                         if ($varValue !== false) {
                             $arrCache[$strTag] = $varValue;
                             break;
                         }
                     }
                 }
                 if (\Config::get('debugMode')) {
                     $GLOBALS['TL_DEBUG']['unknown_insert_tags'][] = $strTag;
                 }
                 break;
         }
         // Handle the flags
         if (!empty($flags)) {
             foreach ($flags as $flag) {
                 switch ($flag) {
                     case 'addslashes':
                     case 'stripslashes':
                     case 'standardize':
                     case 'ampersand':
                     case 'specialchars':
                     case 'nl2br':
                     case 'nl2br_pre':
                     case 'strtolower':
                     case 'utf8_strtolower':
                     case 'strtoupper':
                     case 'utf8_strtoupper':
                     case 'ucfirst':
                     case 'lcfirst':
                     case 'ucwords':
                     case 'trim':
                     case 'rtrim':
                     case 'ltrim':
                     case 'utf8_romanize':
                     case 'strrev':
                     case 'urlencode':
                     case 'rawurlencode':
                         $arrCache[$strTag] = $flag($arrCache[$strTag]);
                         break;
                     case 'encodeEmail':
                     case 'decodeEntities':
                         $arrCache[$strTag] = \String::$flag($arrCache[$strTag]);
                         break;
                     case 'number_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 0);
                         break;
                     case 'currency_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 2);
                         break;
                     case 'readable_size':
                         $arrCache[$strTag] = \System::getReadableSize($arrCache[$strTag]);
                         break;
                         // HOOK: pass unknown flags to callback functions
                     // HOOK: pass unknown flags to callback functions
                     default:
                         if (isset($GLOBALS['TL_HOOKS']['insertTagFlags']) && is_array($GLOBALS['TL_HOOKS']['insertTagFlags'])) {
                             foreach ($GLOBALS['TL_HOOKS']['insertTagFlags'] as $callback) {
                                 $this->import($callback[0]);
                                 $varValue = $this->{$callback}[0]->{$callback}[1]($flag, $tag, $arrCache[$strTag], $flags, $blnCache, $tags, $arrCache, $_rit, $_cnt);
                                 // see #5806
                                 // Replace the tag and stop the loop
                                 if ($varValue !== false) {
                                     $arrCache[$strTag] = $varValue;
                                     break;
                                 }
                             }
                         }
                         if (\Config::get('debugMode')) {
                             $GLOBALS['TL_DEBUG']['unknown_insert_tag_flags'][] = $flag;
                         }
                         break;
                 }
             }
         }
         $strBuffer .= $arrCache[$strTag];
     }
     return \String::restoreBasicEntities($strBuffer);
 }
예제 #23
0
파일: StyleSheets.php 프로젝트: rikaix/core
 /**
  * Compile format definitions and return them as string
  * @param array
  * @param boolean
  * @param array
  * @return string
  */
 public function compileDefinition($row, $blnWriteToFile = false, $vars = array())
 {
     $blnDebug = $GLOBALS['TL_CONFIG']['debugMode'];
     if ($blnWriteToFile) {
         $strGlue = '../../';
         $lb = $blnDebug ? "\n    " : '';
         $return = '';
     } else {
         $strGlue = '';
         $lb = "\n    ";
         $return = "\n" . '<pre' . ($row['invisible'] ? ' class="disabled"' : '') . '>';
     }
     $blnNeedsPie = false;
     // Comment
     if (!$blnWriteToFile && $row['comment'] != '') {
         $search = array('@^\\s*/\\*+@', '@\\*+/\\s*$@');
         $comment = preg_replace($search, '', $row['comment']);
         $comment = wordwrap(trim($comment), 72);
         $return .= "\n/* " . $comment . " */\n";
     }
     // Selector
     $arrSelector = trimsplit(',', \String::decodeEntities($row['selector']));
     $return .= implode($blnWriteToFile ? ',' : ', ', $arrSelector) . ($blnWriteToFile && !$blnDebug ? '' : ' ') . '{';
     // Size
     if ($row['size']) {
         // Width
         $row['width'] = deserialize($row['width']);
         if (isset($row['width']['value']) && $row['width']['value'] != '') {
             $return .= $lb . 'width:' . $row['width']['value'] . ($row['width']['value'] == 'auto' ? '' : $row['width']['unit']) . ';';
         }
         // Height
         $row['height'] = deserialize($row['height']);
         if (isset($row['height']['value']) && $row['height']['value'] != '') {
             $return .= $lb . 'height:' . $row['height']['value'] . ($row['height']['value'] == 'auto' ? '' : $row['height']['unit']) . ';';
         }
         // Min-width
         $row['minwidth'] = deserialize($row['minwidth']);
         if (isset($row['minwidth']['value']) && $row['minwidth']['value'] != '') {
             $return .= $lb . 'min-width:' . $row['minwidth']['value'] . $row['minwidth']['unit'] . ';';
         }
         // Min-height
         $row['minheight'] = deserialize($row['minheight']);
         if (isset($row['minheight']['value']) && $row['minheight']['value'] != '') {
             $return .= $lb . 'min-height:' . $row['minheight']['value'] . $row['minheight']['unit'] . ';';
         }
         // Max-width
         $row['maxwidth'] = deserialize($row['maxwidth']);
         if (isset($row['maxwidth']['value']) && $row['maxwidth']['value'] != '') {
             $return .= $lb . 'max-width:' . $row['maxwidth']['value'] . $row['maxwidth']['unit'] . ';';
         }
         // Max-height
         $row['maxheight'] = deserialize($row['maxheight']);
         if (isset($row['maxheight']['value']) && $row['maxheight']['value'] != '') {
             $return .= $lb . 'max-height:' . $row['maxheight']['value'] . $row['maxheight']['unit'] . ';';
         }
     }
     // Position
     if ($row['positioning']) {
         // Top/right/bottom/left
         $row['trbl'] = deserialize($row['trbl']);
         if (is_array($row['trbl'])) {
             foreach ($row['trbl'] as $k => $v) {
                 if ($v != '' && $k != 'unit') {
                     $return .= $lb . $k . ':' . $v . ($v == 'auto' || $v === '0' ? '' : $row['trbl']['unit']) . ';';
                 }
             }
         }
         // Position
         if ($row['position'] != '') {
             $return .= $lb . 'position:' . $row['position'] . ';';
         }
         // Overflow
         if ($row['overflow'] != '') {
             $return .= $lb . 'overflow:' . $row['overflow'] . ';';
         }
         // Float
         if ($row['floating'] != '') {
             $return .= $lb . 'float:' . $row['floating'] . ';';
         }
         // Clear
         if ($row['clear'] != '') {
             $return .= $lb . 'clear:' . $row['clear'] . ';';
         }
         // Display
         if ($row['display'] != '') {
             $return .= $lb . 'display:' . $row['display'] . ';';
         }
     }
     // Margin, padding and alignment
     if ($row['alignment']) {
         // Margin
         if ($row['margin'] != '' || $row['align'] != '') {
             $row['margin'] = deserialize($row['margin']);
             if (is_array($row['margin'])) {
                 $top = $row['margin']['top'];
                 $right = $row['margin']['right'];
                 $bottom = $row['margin']['bottom'];
                 $left = $row['margin']['left'];
                 // Overwrite the left and right margin if an alignment is set
                 if ($row['align'] != '') {
                     if ($row['align'] == 'left' || $row['align'] == 'center') {
                         $right = 'auto';
                     }
                     if ($row['align'] == 'right' || $row['align'] == 'center') {
                         $left = 'auto';
                     }
                 }
                 // Try to shorten the definition
                 if ($top != '' && $right != '' && $bottom != '' && $left != '') {
                     if ($top == $right && $top == $bottom && $top == $left) {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ';';
                     } elseif ($top == $bottom && $right == $left) {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ' ' . $right . ($right == 'auto' || $right === '0' ? '' : $row['margin']['unit']) . ';';
                     } elseif ($top != $bottom && $right == $left) {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ' ' . $right . ($right == 'auto' || $right === '0' ? '' : $row['margin']['unit']) . ' ' . $bottom . ($bottom == 'auto' || $bottom === '0' ? '' : $row['margin']['unit']) . ';';
                     } else {
                         $return .= $lb . 'margin:' . $top . ($top == 'auto' || $top === '0' ? '' : $row['margin']['unit']) . ' ' . $right . ($right == 'auto' || $right === '0' ? '' : $row['margin']['unit']) . ' ' . $bottom . ($bottom == 'auto' || $bottom === '0' ? '' : $row['margin']['unit']) . ' ' . $left . ($left == 'auto' || $left === '0' ? '' : $row['margin']['unit']) . ';';
                     }
                 } else {
                     $arrDir = array('top' => $top, 'right' => $right, 'bottom' => $bottom, 'left' => $left);
                     foreach ($arrDir as $k => $v) {
                         if ($v != '') {
                             $return .= $lb . 'margin-' . $k . ':' . $v . ($v == 'auto' || $v === '0' ? '' : $row['margin']['unit']) . ';';
                         }
                     }
                 }
             }
         }
         // Padding
         if ($row['padding'] != '') {
             $row['padding'] = deserialize($row['padding']);
             if (is_array($row['padding'])) {
                 $top = $row['padding']['top'];
                 $right = $row['padding']['right'];
                 $bottom = $row['padding']['bottom'];
                 $left = $row['padding']['left'];
                 // Try to shorten the definition
                 if ($top != '' && $right != '' && $bottom != '' && $left != '') {
                     if ($top == $right && $top == $bottom && $top == $left) {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ';';
                     } elseif ($top == $bottom && $right == $left) {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['padding']['unit']) . ';';
                     } elseif ($top != $bottom && $right == $left) {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['padding']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['padding']['unit']) . ';';
                     } else {
                         $return .= $lb . 'padding:' . $top . ($top === '0' ? '' : $row['padding']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['padding']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['padding']['unit']) . ' ' . $left . ($left === '0' ? '' : $row['padding']['unit']) . ';';
                     }
                 } else {
                     $arrDir = array('top' => $top, 'right' => $right, 'bottom' => $bottom, 'left' => $left);
                     foreach ($arrDir as $k => $v) {
                         if ($v != '') {
                             $return .= $lb . 'padding-' . $k . ':' . $v . ($v === '0' ? '' : $row['padding']['unit']) . ';';
                         }
                     }
                 }
             }
         }
         // Text alignment
         if ($row['textalign'] != '') {
             $return .= $lb . 'text-align:' . $row['textalign'] . ';';
         }
         // Vertical alignment
         if ($row['verticalalign'] != '') {
             $return .= $lb . 'vertical-align:' . $row['verticalalign'] . ';';
         }
     }
     // Background
     if ($row['background']) {
         $bgColor = deserialize($row['bgcolor'], true);
         // Try to shorten the definition
         if ($row['bgimage'] != '' && $row['bgposition'] != '' && $row['bgrepeat'] != '') {
             $glue = strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0 ? $strGlue : '';
             $return .= $lb . 'background:' . ($bgColor[0] != '' ? $this->compileColor($bgColor, $blnWriteToFile, $vars) . ' ' : '') . 'url("' . $glue . $row['bgimage'] . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ';';
         } else {
             // Background color
             if ($bgColor[0] != '') {
                 $return .= $lb . 'background-color:' . $this->compileColor($bgColor, $blnWriteToFile, $vars) . ';';
             }
             // Background image
             if ($row['bgimage'] == 'none') {
                 $return .= $lb . 'background-image:none;';
             } elseif ($row['bgimage'] != '') {
                 $glue = strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0 ? $strGlue : '';
                 $return .= $lb . 'background-image:url("' . $glue . $row['bgimage'] . '");';
             }
             // Background position
             if ($row['bgposition'] != '') {
                 $return .= $lb . 'background-position:' . $row['bgposition'] . ';';
             }
             // Background repeat
             if ($row['bgrepeat'] != '') {
                 $return .= $lb . 'background-repeat:' . $row['bgrepeat'] . ';';
             }
         }
         // Background gradient
         if ($row['gradientAngle'] != '' && $row['gradientColors'] != '') {
             $row['gradientColors'] = deserialize($row['gradientColors']);
             if (is_array($row['gradientColors']) && count(array_filter($row['gradientColors'])) > 0) {
                 $blnNeedsPie = true;
                 $bgImage = '';
                 // CSS3 PIE only supports -pie-background, so if there is a background image, include it here, too.
                 if ($row['bgimage'] != '' && $row['bgposition'] != '' && $row['bgrepeat'] != '') {
                     $glue = strncmp($row['bgimage'], 'data:', 5) !== 0 && strncmp($row['bgimage'], 'http://', 7) !== 0 && strncmp($row['bgimage'], 'https://', 8) !== 0 && strncmp($row['bgimage'], '/', 1) !== 0 ? $strGlue : '';
                     $bgImage = 'url("' . $glue . $row['bgimage'] . '") ' . $row['bgposition'] . ' ' . $row['bgrepeat'] . ',';
                 }
                 // Default starting point
                 if ($row['gradientAngle'] == '') {
                     $row['gradientAngle'] = 'top';
                 }
                 $webkitAngle = $row['gradientAngle'];
                 // Convert the starting point to degrees
                 $arrMapper = array('left' => '0deg', 'top' => '270deg', 'right' => '180deg', 'bottom' => '90deg', 'top left' => '315deg', 'left top' => '315deg', 'bottom left' => '45deg', 'left bottom' => '45deg', 'top right' => '225deg', 'right top' => '225deg', 'bottom right' => '135deg', 'right bottom' => '135deg');
                 if (isset($arrMapper[$webkitAngle])) {
                     $webkitAngle = $arrMapper[$webkitAngle];
                 }
                 $angle = floatval($webkitAngle);
                 $multi = 50 / 45;
                 // 45 degree == 50 %
                 // Make angle a positive value
                 while ($angle < 0) {
                     $angle += 360;
                 }
                 // Convert the angle to points in percentage from the top left corner
                 if ($angle >= 0 && $angle < 45) {
                     $offset = round($angle * $multi, 2);
                     $webkitAngle = '0% ' . (50 + $offset) . '%,100% ' . (50 - $offset) . '%';
                 } elseif ($angle >= 45 && $angle < 135) {
                     $offset = round(($angle - 45) * $multi, 2);
                     $webkitAngle = $offset . '% 100%,' . (100 - $offset) . '% 0%';
                 } elseif ($angle >= 135 && $angle < 225) {
                     $offset = round(($angle - 135) * $multi, 2);
                     $webkitAngle = '100% ' . (100 - $offset) . '%,0% ' . $offset . '%';
                 } elseif ($angle >= 225 && $angle < 315) {
                     $offset = round(($angle - 225) * $multi, 2);
                     $webkitAngle = 100 - $offset . '% 0%,' . $offset . '% 100%';
                 } elseif ($angle >= 315 && $angle <= 360) {
                     $offset = round(($angle - 315) * $multi, 2);
                     $webkitAngle = '0% ' . $offset . '%,100% ' . (100 - $offset) . '%';
                 }
                 $row['gradientColors'] = array_values(array_filter($row['gradientColors']));
                 // Add a hash tag to the color values
                 foreach ($row['gradientColors'] as $k => $v) {
                     $row['gradientColors'][$k] = '#' . $v;
                 }
                 $webkitColors = $row['gradientColors'];
                 // Convert #ffc 10% to color-stop(0.1,#ffc)
                 foreach ($webkitColors as $k => $v) {
                     // Split #ffc 10%
                     list($col, $pct) = explode(' ', $v, 2);
                     // Convert 10% to 0.1
                     if ($pct != '') {
                         $pct = intval($pct) / 100;
                     } else {
                         // Default values: 0, 0.33, 0.66, 1
                         switch ($k) {
                             case 0:
                                 $pct = 0;
                                 break;
                             case 1:
                                 if (count($webkitColors) == 2) {
                                     $pct = 1;
                                 } elseif (count($webkitColors) == 3) {
                                     $pct = 0.5;
                                 } elseif (count($webkitColors) == 4) {
                                     $pct = 0.33;
                                 }
                                 break;
                             case 2:
                                 if (count($webkitColors) == 3) {
                                     $pct = 1;
                                 } elseif (count($webkitColors) == 4) {
                                     $pct = 0.66;
                                 }
                                 break;
                             case 3:
                                 $pct = 1;
                                 break;
                         }
                     }
                     // The syntax is: color-stop(0.1,#ffc)
                     $webkitColors[$k] = 'color-stop(' . $pct . ',' . $col . ')';
                 }
                 $gradient = $row['gradientAngle'] . ',' . implode(',', $row['gradientColors']);
                 $webkitGradient = $webkitAngle . ',' . implode(',', $webkitColors);
                 $return .= $lb . 'background:' . $bgImage . '-moz-linear-gradient(' . $gradient . ');';
                 $return .= $lb . 'background:' . $bgImage . '-webkit-gradient(linear,' . $webkitGradient . ');';
                 $return .= $lb . 'background:' . $bgImage . '-o-linear-gradient(' . $gradient . ');';
                 $return .= $lb . 'background:' . $bgImage . 'linear-gradient(' . $gradient . ');';
                 $return .= $lb . '-pie-background:' . $bgImage . 'linear-gradient(' . $gradient . ');';
             }
         }
         // Box shadow
         if ($row['shadowsize'] != '') {
             $shColor = deserialize($row['shadowcolor'], true);
             $row['shadowsize'] = deserialize($row['shadowsize']);
             if (is_array($row['shadowsize']) && $row['shadowsize']['top'] != '' && $row['shadowsize']['right'] != '') {
                 $blnNeedsPie = true;
                 $offsetx = $row['shadowsize']['top'];
                 $offsety = $row['shadowsize']['right'];
                 $blursize = $row['shadowsize']['bottom'];
                 $radius = $row['shadowsize']['left'];
                 $shadow = $offsetx . ($offsetx === '0' ? '' : $row['shadowsize']['unit']);
                 $shadow .= ' ' . $offsety . ($offsety === '0' ? '' : $row['shadowsize']['unit']);
                 if ($blursize != '') {
                     $shadow .= ' ' . $blursize . ($blursize === '0' ? '' : $row['shadowsize']['unit']);
                 }
                 if ($radius != '') {
                     $shadow .= ' ' . $radius . ($radius === '0' ? '' : $row['shadowsize']['unit']);
                 }
                 if ($shColor[0] != '') {
                     $shadow .= ' ' . $this->compileColor($shColor, $blnWriteToFile, $vars);
                 }
                 $shadow .= ';';
                 $return .= $lb . '-moz-box-shadow:' . $shadow;
                 $return .= $lb . '-webkit-box-shadow:' . $shadow;
                 $return .= $lb . 'box-shadow:' . $shadow;
             }
         }
     }
     // Border
     if ($row['border']) {
         $bdColor = deserialize($row['bordercolor'], true);
         $row['borderwidth'] = deserialize($row['borderwidth']);
         // Border width
         if (is_array($row['borderwidth'])) {
             $top = $row['borderwidth']['top'];
             $right = $row['borderwidth']['right'];
             $bottom = $row['borderwidth']['bottom'];
             $left = $row['borderwidth']['left'];
             // Try to shorten the definition
             if ($top != '' && $right != '' && $bottom != '' && $left != '' && $top == $right && $top == $bottom && $top == $left) {
                 $return .= $lb . 'border:' . $top . $row['borderwidth']['unit'] . ($row['borderstyle'] != '' ? ' ' . $row['borderstyle'] : '') . ($bdColor[0] != '' ? ' ' . $this->compileColor($bdColor, $blnWriteToFile, $vars) : '') . ';';
             } elseif ($top != '' && $right != '' && $bottom != '' && $left != '' && $top == $bottom && $left == $right) {
                 $return .= $lb . 'border-width:' . $top . $row['borderwidth']['unit'] . ' ' . $right . $row['borderwidth']['unit'] . ';';
                 if ($row['borderstyle'] != '') {
                     $return .= $lb . 'border-style:' . $row['borderstyle'] . ';';
                 }
                 if ($bdColor[0] != '') {
                     $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';';
                 }
             } elseif ($top == '' && $right == '' && $bottom == '' && $left == '') {
                 if ($row['borderstyle'] != '') {
                     $return .= $lb . 'border-style:' . $row['borderstyle'] . ';';
                 }
                 if ($bdColor[0] != '') {
                     $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';';
                 }
             } else {
                 $arrDir = array('top' => $top, 'right' => $right, 'bottom' => $bottom, 'left' => $left);
                 foreach ($arrDir as $k => $v) {
                     if ($v != '') {
                         $return .= $lb . 'border-' . $k . ':' . $v . $row['borderwidth']['unit'] . ($row['borderstyle'] != '' ? ' ' . $row['borderstyle'] : '') . ($bdColor[0] != '' ? ' ' . $this->compileColor($bdColor, $blnWriteToFile, $vars) : '') . ';';
                     }
                 }
             }
         } else {
             if ($row['borderstyle'] != '') {
                 $return .= $lb . 'border-style:' . $row['borderstyle'] . ';';
             }
             if ($bdColor[0] != '') {
                 $return .= $lb . 'border-color:' . $this->compileColor($bdColor, $blnWriteToFile, $vars) . ';';
             }
         }
         // Border radius
         if ($row['borderradius'] != '') {
             $row['borderradius'] = deserialize($row['borderradius']);
             if (is_array($row['borderradius']) && ($row['borderradius']['top'] != '' || $row['borderradius']['right'] != '' || $row['borderradius']['bottom'] != '' || $row['borderradius']['left'] != '')) {
                 $blnNeedsPie = true;
                 $top = $row['borderradius']['top'];
                 $right = $row['borderradius']['right'];
                 $bottom = $row['borderradius']['bottom'];
                 $left = $row['borderradius']['left'];
                 $borderradius = '';
                 // Try to shorten the definition
                 if ($top != '' && $right != '' && $bottom != '' && $left != '') {
                     if ($top == $right && $top == $bottom && $top == $left) {
                         $borderradius = $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ';';
                     } elseif ($top == $bottom && $right == $left) {
                         $borderradius = $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['borderradius']['unit']) . ';';
                     } elseif ($top != $bottom && $right == $left) {
                         $borderradius = $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['borderradius']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['borderradius']['unit']) . ';';
                     } else {
                         $borderradius .= $top . ($top === '0' ? '' : $row['borderradius']['unit']) . ' ' . $right . ($right === '0' ? '' : $row['borderradius']['unit']) . ' ' . $bottom . ($bottom === '0' ? '' : $row['borderradius']['unit']) . ' ' . $left . ($left === '0' ? '' : $row['borderradius']['unit']) . ';';
                     }
                     $return .= $lb . '-moz-border-radius:' . $borderradius;
                     $return .= $lb . '-webkit-border-radius:' . $borderradius;
                     $return .= $lb . 'border-radius:' . $borderradius;
                 } else {
                     $arrDir = array('top-left' => $top, 'top-right' => $right, 'bottom-right' => $bottom, 'bottom-left' => $left);
                     foreach ($arrDir as $k => $v) {
                         if ($v != '') {
                             $return .= $lb . '-moz-border-radius-' . str_replace('-', '', $k) . ':' . $v . ($v === '0' ? '' : $row['borderradius']['unit']) . ';';
                             $return .= $lb . '-webkit-border-' . $k . '-radius:' . $v . ($v === '0' ? '' : $row['borderradius']['unit']) . ';';
                             $return .= $lb . 'border-' . $k . '-radius:' . $v . ($v === '0' ? '' : $row['borderradius']['unit']) . ';';
                         }
                     }
                 }
             }
         }
         // Border collapse
         if ($row['bordercollapse'] != '') {
             $return .= $lb . 'border-collapse:' . $row['bordercollapse'] . ';';
         }
         // Border spacing
         $row['borderspacing'] = deserialize($row['borderspacing']);
         if (isset($row['borderspacing']['value']) && $row['borderspacing']['value'] != '') {
             $return .= $lb . 'border-spacing:' . $row['borderspacing']['value'] . $row['borderspacing']['unit'] . ';';
         }
     }
     // Font
     if ($row['font']) {
         $row['fontsize'] = deserialize($row['fontsize']);
         $row['lineheight'] = deserialize($row['lineheight']);
         $row['fontfamily'] = str_replace(', ', ',', $row['fontfamily']);
         // Try to shorten the definition
         if ($row['fontfamily'] != '' && $row['fontfamily'] != 'inherit' && isset($row['fontsize']['value']) && $row['fontsize']['value'] != '' && $row['fontsize']['value'] != 'inherit') {
             $return .= $lb . 'font:' . $row['fontsize']['value'] . $row['fontsize']['unit'] . (isset($row['lineheight']['value']) && $row['lineheight']['value'] != '' ? '/' . $row['lineheight']['value'] . $row['lineheight']['unit'] : '') . ' ' . $row['fontfamily'] . ';';
         } else {
             // Font family
             if ($row['fontfamily'] != '') {
                 $return .= $lb . 'font-family:' . $row['fontfamily'] . ';';
             }
             // Font size
             if (isset($row['fontsize']['value']) && $row['fontsize']['value'] != '') {
                 $return .= $lb . 'font-size:' . $row['fontsize']['value'] . $row['fontsize']['unit'] . ';';
             }
             // Line height
             if (isset($row['lineheight']['value']) && $row['lineheight']['value'] != '') {
                 $return .= $lb . 'line-height:' . $row['lineheight']['value'] . $row['lineheight']['unit'] . ';';
             }
         }
         // Font style
         $row['fontstyle'] = deserialize($row['fontstyle']);
         if (is_array($row['fontstyle'])) {
             if (in_array('bold', $row['fontstyle'])) {
                 $return .= $lb . 'font-weight:bold;';
             }
             if (in_array('italic', $row['fontstyle'])) {
                 $return .= $lb . 'font-style:italic;';
             }
             if (in_array('normal', $row['fontstyle'])) {
                 $return .= $lb . 'font-weight:normal;';
             }
             if (in_array('underline', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:underline;';
             }
             if (in_array('line-through', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:line-through;';
             }
             if (in_array('overline', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:overline;';
             }
             if (in_array('notUnderlined', $row['fontstyle'])) {
                 $return .= $lb . 'text-decoration:none;';
             }
             if (in_array('small-caps', $row['fontstyle'])) {
                 $return .= $lb . 'font-variant:small-caps;';
             }
         }
         $fnColor = deserialize($row['fontcolor'], true);
         // Font color
         if ($fnColor[0] != '') {
             $return .= $lb . 'color:' . $this->compileColor($fnColor, $blnWriteToFile, $vars) . ';';
         }
         // White space
         if ($row['whitespace'] != '') {
             $return .= $lb . 'white-space:nowrap;';
         }
         // Text transform
         if ($row['texttransform'] != '') {
             $return .= $lb . 'text-transform:' . $row['texttransform'] . ';';
         }
         // Text indent
         $row['textindent'] = deserialize($row['textindent']);
         if (isset($row['textindent']['value']) && $row['textindent']['value'] != '') {
             $return .= $lb . 'text-indent:' . $row['textindent']['value'] . $row['textindent']['unit'] . ';';
         }
         // Letter spacing
         $row['letterspacing'] = deserialize($row['letterspacing']);
         if (isset($row['letterspacing']['value']) && $row['letterspacing']['value'] != '') {
             $return .= $lb . 'letter-spacing:' . $row['letterspacing']['value'] . $row['letterspacing']['unit'] . ';';
         }
         // Word spacing
         $row['wordspacing'] = deserialize($row['wordspacing']);
         if (isset($row['wordspacing']['value']) && $row['wordspacing']['value'] != '') {
             $return .= $lb . 'word-spacing:' . $row['wordspacing']['value'] . $row['wordspacing']['unit'] . ';';
         }
     }
     // List
     if ($row['list']) {
         // List bullet
         if ($row['liststyletype'] != '') {
             $return .= $lb . 'list-style-type:' . $row['liststyletype'] . ';';
         }
         // List image
         if ($row['liststyleimage'] == 'none') {
             $return .= $lb . 'list-style-image:none;';
         } elseif ($row['liststyleimage'] != '') {
             $glue = strncmp($row['liststyleimage'], 'data:', 5) !== 0 && strncmp($row['liststyleimage'], 'http://', 7) !== 0 && strncmp($row['liststyleimage'], 'https://', 8) !== 0 && strncmp($row['liststyleimage'], '/', 1) !== 0 ? $strGlue : '';
             $return .= $lb . 'list-style-image:url("' . $glue . $row['liststyleimage'] . '");';
         }
     }
     // CSS3PIE
     if ($blnNeedsPie) {
         $return .= $lb . 'behavior:url(\'plugins/' . CSS3PIE . '/css3pie/PIE.htc\');';
     }
     // Custom code
     if ($row['own'] != '') {
         $own = trim(\String::decodeEntities($row['own']));
         $own = preg_replace('/url\\("(?!data:|\\/)/', 'url("' . $strGlue, $own);
         $own = preg_split('/[\\n\\r]+/i', $own);
         $return .= $lb . implode($blnWriteToFile ? '' : $lb, $own);
     }
     // Allow custom definitions
     if (isset($GLOBALS['TL_HOOKS']['compileDefinition']) && is_array($GLOBALS['TL_HOOKS']['compileDefinition'])) {
         foreach ($GLOBALS['TL_HOOKS']['compileDefinition'] as $callback) {
             $this->import($callback[0]);
             $strTemp = $this->{$callback}[0]->{$callback}[1]($row, $blnWriteToFile, $vars);
             if ($strTemp != '') {
                 $return .= $lb . $strTemp;
             }
         }
     }
     // Close the format definition
     if ($blnWriteToFile) {
         // Remove the last semi-colon (;) before the closing bracket
         if (substr($return, -1) == ';') {
             $return = substr($return, 0, -1);
         }
         $nl = $blnDebug ? "\n" : '';
         $return .= $nl . '}' . $nl;
     } else {
         $return .= "\n}</pre>\n";
     }
     // Replace global variables
     if (strpos($return, '$') !== false && !empty($vars)) {
         $return = str_replace(array_keys($vars), array_values($vars), $return);
     }
     return $return;
 }
예제 #24
0
 protected function commentsController()
 {
     $returnarray['error'] = $this->errorcode(0);
     $returnarray['changes'] = 1;
     $getTs = \Input::get($this->request['ts']);
     $getId = \Input::get($this->request['id']);
     $returnarray['ts'] = isset($getTs) ? $getTs : 0;
     if (isset($getId)) {
         if (\Input::get($this->request['action']) == 'add') {
             $comment = $_REQUEST[$this->request['comment']];
             $name = $_REQUEST[$this->request['name']];
             $email = $_REQUEST[$this->request['email']];
             $key = $_REQUEST[$this->request['key']];
             if (!$comment || $comment == "" || !$name || !$email) {
                 $returnarray['error'] = $this->errorcode(30);
             } elseif (!\Validator::isEmail($email)) {
                 $returnarray['error'] = $this->errorcode(31);
             } else {
                 $ts = time();
                 $arrInsert = array('tstamp' => $ts, 'source' => 'tl_news', 'parent' => $getId, 'date' => $ts, 'name' => $name, 'email' => $email, 'comment' => trim($comment), 'published' => $this->settings['news_moderate'] == 1 ? 0 : 1, 'ip' => \Environment::get('remote_addr'));
                 $objComment = new \CommentsModel();
                 $objComment->setRow($arrInsert)->save();
                 if ($objComment->id) {
                     $strComment = $_REQUEST[$this->request['comment']];
                     $strComment = strip_tags($strComment);
                     $strComment = \String::decodeEntities($strComment);
                     $strComment = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strComment);
                     $objTemplate = new \FrontendTemplate('kommentar_email');
                     $objTemplate->name = $arrInsert['name'] . ' (' . $arrInsert['email'] . ')';
                     $objTemplate->comment = $strComment;
                     $objTemplate->edit = \Idna::decode(\Environment::get('base')) . 'contao/main.php?do=comments&act=edit&id=' . $objComment->id;
                     $objEmail = new \Email();
                     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
                     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
                     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['com_subject'], \Idna::decode(\Environment::get('host')));
                     $objEmail->text = $objTemplate->parse();
                     if ($GLOBALS['TL_ADMIN_EMAIL'] != '') {
                         $objEmail->sendTo($GLOBALS['TL_ADMIN_EMAIL']);
                     }
                     $returnarray['error'] = $this->errorcode(0);
                     $returnarray['ts'] = $ts;
                     $returnarray['comment_id'] = $objComment->id;
                     $returnarray['changes'] = 1;
                     $returnarray['status'] = $this->settings['news_moderate'] == 1 ? 'Kommentar wird geprüft.' : "Kommentar veröffentlicht.";
                 } else {
                     $returnarray['error'] = $this->errorcode(31);
                 }
             }
         } else {
             $post = $this->getComment($getId);
             if ($post['commentStatus'] == 'open') {
                 $returnarray['comment_status'] = $post['commentStatus'];
                 $returnarray['comments_count'] = $post['commentsCount'];
                 $returnarray['REQUEST_TOKEN'] = REQUEST_TOKEN;
                 if ($post['commentsCount'] > 0) {
                     $pos = 0;
                     foreach ($post['items'] as $comment) {
                         $tempArray = array();
                         $tempArray['pos'] = ++$pos;
                         $tempArray['id'] = $comment->id;
                         $tempArray['text'] = strip_tags($comment->comment);
                         $tempArray['timestamp'] = (int) $comment->date;
                         if ($tempArray['timestamp'] > $returnarray['ts']) {
                             $returnarray['ts'] = $tempArray['timestamp'];
                             $returnarray['changes'] = 1;
                         }
                         $tempArray['datum'] = date('d.m.Y, H:i', $tempArray['timestamp']);
                         $tempArray['author']['name'] = $comment->name;
                         $tempArray['author']['id'] = "0";
                         $tempArray['author']['email'] = $comment->email;
                         $tempArray['author']['img'] = "";
                         if ($comment->addReply) {
                             $objUser = \UserModel::findByPk($comment->author);
                             $tempArray['subitems'] = array(array('pos' => 1, 'id' => 1, 'parent_id' => $comment->id, 'text' => strip_tags($comment->reply), 'timestamp' => (int) $comment->tstamp, 'datum' => date('d.m.Y, H:i', $comment->tstamp), 'author' => array('name' => $objUser->name, 'id' => $objUser->id, 'email' => $objUser->email, 'img' => "")));
                         }
                         $returnarray['items'][] = $tempArray;
                     }
                     if ($returnarray['changes'] != 1) {
                         unset($returnarray['items']);
                     }
                 }
             } else {
                 $returnarray['error'] = $this->errorcode(29);
             }
         }
     } else {
         $returnarray['error'] = $this->errorcode(15);
     }
     return array('comments' => $returnarray);
 }
예제 #25
0
파일: Comments.php 프로젝트: iCodr8/core
 /**
  * Add a form to create new comments
  * @param \FrontendTemplate
  * @param \stdClass
  * @param string
  * @param integer
  * @param mixed
  */
 protected function renderCommentForm(\FrontendTemplate $objTemplate, \stdClass $objConfig, $strSource, $intParent, $varNotifies)
 {
     $this->import('FrontendUser', 'User');
     // Access control
     if ($objConfig->requireLogin && !BE_USER_LOGGED_IN && !FE_USER_LOGGED_IN) {
         $objTemplate->requireLogin = true;
         return;
     }
     // Confirm or remove a subscription
     if (\Input::get('token')) {
         static::changeSubscriptionStatus($objTemplate);
         return;
     }
     // Form fields
     $arrFields = array('name' => array('name' => 'name', 'label' => $GLOBALS['TL_LANG']['MSC']['com_name'], 'value' => trim($this->User->firstname . ' ' . $this->User->lastname), 'inputType' => 'text', 'eval' => array('mandatory' => true, 'maxlength' => 64)), 'email' => array('name' => 'email', 'label' => $GLOBALS['TL_LANG']['MSC']['com_email'], 'value' => $this->User->email, 'inputType' => 'text', 'eval' => array('rgxp' => 'email', 'mandatory' => true, 'maxlength' => 128, 'decodeEntities' => true)), 'website' => array('name' => 'website', 'label' => $GLOBALS['TL_LANG']['MSC']['com_website'], 'inputType' => 'text', 'eval' => array('rgxp' => 'url', 'maxlength' => 128, 'decodeEntities' => true)));
     // Captcha
     if (!$objConfig->disableCaptcha) {
         $arrFields['captcha'] = array('name' => 'captcha', 'inputType' => 'captcha', 'eval' => array('mandatory' => true));
     }
     // Comment field
     $arrFields['comment'] = array('name' => 'comment', 'label' => $GLOBALS['TL_LANG']['MSC']['com_comment'], 'inputType' => 'textarea', 'eval' => array('mandatory' => true, 'rows' => 4, 'cols' => 40, 'preserveTags' => true));
     // Notify me of new comments
     $arrFields['notify'] = array('name' => 'notify', 'label' => '', 'inputType' => 'checkbox', 'options' => array(1 => $GLOBALS['TL_LANG']['MSC']['com_notify']));
     $doNotSubmit = false;
     $arrWidgets = array();
     $strFormId = 'com_' . $strSource . '_' . $intParent;
     // Initialize the widgets
     foreach ($arrFields as $arrField) {
         $strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
         // Continue if the class is not defined
         if (!class_exists($strClass)) {
             continue;
         }
         $arrField['eval']['required'] = $arrField['eval']['mandatory'];
         $objWidget = new $strClass($strClass::getAttributesFromDca($arrField, $arrField['name'], $arrField['value']));
         // Validate the widget
         if (\Input::post('FORM_SUBMIT') == $strFormId) {
             $objWidget->validate();
             if ($objWidget->hasErrors()) {
                 $doNotSubmit = true;
             }
         }
         $arrWidgets[$arrField['name']] = $objWidget;
     }
     $objTemplate->fields = $arrWidgets;
     $objTemplate->submit = $GLOBALS['TL_LANG']['MSC']['com_submit'];
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->messages = '';
     // Backwards compatibility
     $objTemplate->formId = $strFormId;
     $objTemplate->hasError = $doNotSubmit;
     // Do not index or cache the page with the confirmation message
     if ($_SESSION['TL_COMMENT_ADDED']) {
         global $objPage;
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['com_confirm'];
         $_SESSION['TL_COMMENT_ADDED'] = false;
     }
     // Store the comment
     if (!$doNotSubmit && \Input::post('FORM_SUBMIT') == $strFormId) {
         $strWebsite = $arrWidgets['website']->value;
         // Add http:// to the website
         if ($strWebsite != '' && !preg_match('@^(https?://|ftp://|mailto:|#)@i', $strWebsite)) {
             $strWebsite = 'http://' . $strWebsite;
         }
         // Do not parse any tags in the comment
         $strComment = specialchars(trim($arrWidgets['comment']->value));
         $strComment = str_replace(array('&amp;', '&lt;', '&gt;'), array('[&]', '[lt]', '[gt]'), $strComment);
         // Remove multiple line feeds
         $strComment = preg_replace('@\\n\\n+@', "\n\n", $strComment);
         // Parse BBCode
         if ($objConfig->bbcode) {
             $strComment = $this->parseBbCode($strComment);
         }
         // Prevent cross-site request forgeries
         $strComment = preg_replace('/(href|src|on[a-z]+)="[^"]*(contao\\/main\\.php|typolight\\/main\\.php|javascript|vbscri?pt|script|alert|document|cookie|window)[^"]*"+/i', '$1="#"', $strComment);
         $time = time();
         // Prepare the record
         $arrSet = array('tstamp' => $time, 'source' => $strSource, 'parent' => $intParent, 'name' => $arrWidgets['name']->value, 'email' => $arrWidgets['email']->value, 'website' => $strWebsite, 'comment' => $this->convertLineFeeds($strComment), 'ip' => $this->anonymizeIp(\Environment::get('ip')), 'date' => $time, 'published' => $objConfig->moderate ? '' : 1);
         // Store the comment
         $objComment = new \CommentsModel();
         $objComment->setRow($arrSet)->save();
         // Store the subscription
         if ($arrWidgets['notify']->value) {
             static::addCommentsSubscription($objComment);
         }
         // HOOK: add custom logic
         if (isset($GLOBALS['TL_HOOKS']['addComment']) && is_array($GLOBALS['TL_HOOKS']['addComment'])) {
             foreach ($GLOBALS['TL_HOOKS']['addComment'] as $callback) {
                 $this->import($callback[0]);
                 $this->{$callback}[0]->{$callback}[1]($objComment->id, $arrSet, $this);
             }
         }
         // Prepare the notification mail
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['com_subject'], \Idna::decode(\Environment::get('host')));
         // Convert the comment to plain text
         $strComment = strip_tags($strComment);
         $strComment = \String::decodeEntities($strComment);
         $strComment = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strComment);
         // Add the comment details
         $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['com_message'], $arrSet['name'] . ' (' . $arrSet['email'] . ')', $strComment, \Idna::decode(\Environment::get('base')) . \Environment::get('request'), \Idna::decode(\Environment::get('base')) . 'contao/main.php?do=comments&act=edit&id=' . $objComment->id);
         // Do not send notifications twice
         if (is_array($varNotifies)) {
             $objEmail->sendTo(array_unique($varNotifies));
         } elseif ($varNotifies != '') {
             $objEmail->sendTo($varNotifies);
             // see #5443
         }
         // Pending for approval
         if ($objConfig->moderate) {
             $_SESSION['TL_COMMENT_ADDED'] = true;
         } else {
             static::notifyCommentsSubscribers($objComment);
         }
         $this->reload();
     }
 }
예제 #26
0
 /**
  * Processes an HTML attribute value and strips dangerous protocols from URLs.
  *
  * @param string $string
  *   The string with the attribute value.
  *
  * @return string
  *   Cleaned up and HTML-escaped version of $string.
  */
 public static function filterBadProtocol($string)
 {
     // Get the plain text representation of the attribute value (i.e. its
     // meaning).
     $string = String::decodeEntities($string);
     return String::checkPlain(static::stripDangerousProtocols($string));
 }
예제 #27
0
파일: Formdata.php 프로젝트: Jobu/core
 /**
  * Parse Insert tag params
  * @param string $strTag Insert tag
  * @return array|null
  */
 public function parseInsertTagParams($strTag = '')
 {
     if ($strTag == '') {
         return null;
     }
     if (strpos($strTag, '?') == false) {
         return null;
     }
     $strTag = str_replace(array('{{', '}}', '__BRCL__', '__BRCR__'), array('', ''), $strTag);
     $arrTag = explode('?', $strTag);
     $strKey = $arrTag[0];
     if (isset($arrTag[1]) && strlen($arrTag[1])) {
         $arrTag[1] = str_replace('[&]', '__AMP__', $arrTag[1]);
         $strParams = \String::decodeEntities($arrTag[1]);
         $arrParams = preg_split('/&/sim', $strParams);
         $arrReturn = array();
         foreach ($arrParams as $strParam) {
             list($key, $value) = explode('=', $strParam);
             $arrReturn[$key] = str_replace('__AMP__', '&', $value);
         }
     }
     return $arrReturn;
 }
예제 #28
0
 private function notifiy($insertId)
 {
     $result = $this->Database->prepare('SELECT
         tl_shoutbox_entries.*,
         tl_shoutbox.email AS email,
         tl_member.username AS username,
         tl_member.email AS useremail
         FROM tl_shoutbox_entries, tl_shoutbox, tl_member
         WHERE tl_shoutbox_entries.id = ?
         AND tl_shoutbox_entries.member = tl_member.id
         AND tl_shoutbox_entries.pid = tl_shoutbox.id')->execute($insertId);
     if ($result->numRows != 1) {
         return false;
     }
     $data = (object) $result->row();
     if (!\Validator::isEmail($data->email)) {
         return false;
     }
     // Convert the comment to plain text
     $strComment = \String::decodeEntities(strip_tags($data->entry));
     $strComment = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strComment);
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = "New shoutbox entry from " . $data->username . ' (' . $data->useremail . ')';
     // Add comment details
     $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['com_message'], $data->username . ' (' . $data->useremail . ')', $strComment, \Environment::get('base') . \Environment::get('request'), \Environment::get('base') . 'contao/main.php?do=shoutbox&table=tl_shoutbox_entries&id=' . $data->pid);
     $objEmail->sendTo($data->email);
     return true;
 }
 protected function getConfigBubblesJs()
 {
     $arrData = array();
     $objElements = DatamapsElementsModel::findPublishedByPidsAndTypes(array($this->objConfig->id), array(DATAMAP_ELEMENT_BUBBLE));
     if ($objElements === null) {
         return '';
     }
     while ($objElements->next()) {
         $arrData[] = $this->generateElementData($objElements, $this->objConfig);
     }
     return \String::decodeEntities(json_encode($arrData));
 }
예제 #30
0
파일: Xss.php 프로젝트: royalwang/Pyramid
 /**
  * 清理属性
  */
 public function attributes($attributes, $elem = '')
 {
     $return = array();
     $mode = 0;
     $attrname = '';
     $skip = false;
     while (strlen($attributes) != 0) {
         $working = 0;
         switch ($mode) {
             //属性名
             case 0:
                 if (preg_match('/^([-a-zA-Z]+)/', $attributes, $match)) {
                     $working = 1;
                     $mode = 1;
                     $attrname = strtolower($match[1]);
                     $skip = substr($attrname, 0, 2) == 'on';
                     $attributes = preg_replace('/^[-a-zA-Z]+/', '', $attributes);
                 }
                 break;
                 //单个的属性值
             //单个的属性值
             case 1:
                 if (preg_match('/^\\s*=\\s*/', $attributes)) {
                     $working = 1;
                     $mode = 2;
                     $attributes = preg_replace('/^\\s*=\\s*/', '', $attributes);
                     break;
                 }
                 if (preg_match('/^\\s+/', $attributes)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array();
                     }
                     $attributes = preg_replace('/^\\s+/', '', $attributes);
                 }
                 break;
                 //属性值
             //属性值
             case 2:
                 if (preg_match('/^"([^"]*)"(\\s+|$)/', $attributes, $match)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array('value' => $match[1], 'delimiter' => '"');
                     }
                     $attributes = preg_replace('/^"[^"]*"(\\s+|$)/', '', $attributes);
                     break;
                 }
                 if (preg_match("/^'([^']*)'(\\s+|\$)/", $attributes, $match)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array('value' => $match[1], 'delimiter' => "'");
                     }
                     $attributes = preg_replace("/^'[^']*'(\\s+|\$)/", '', $attributes);
                     break;
                 }
                 if (preg_match("%^([^\\s\"']+)(\\s+|\$)%", $attributes, $match)) {
                     $working = 1;
                     $mode = 0;
                     if (!$skip) {
                         $return[$attrname] = array('value' => $match[1], 'delimiter' => '"');
                     }
                     $attributes = preg_replace("%^[^\\s\"']+(\\s+|\$)%", '', $attributes);
                 }
                 break;
         }
         //没有匹配到的,直接过滤
         if ($working == 0) {
             $attributes = preg_replace('/
               ^
               (
               "[^"]*("|$)     # - a string that starts with a double quote, up until the next double quote or the end of the string
               |               # or
               \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
               |               # or
               \\S              # - a non-whitespace character
               )*              # any number of the above three
               \\s*             # any number of whitespaces
               /x', '', $attributes);
             $mode = 0;
         }
     }
     if ($mode == 1 && !$skip) {
         $return[$attrname] = array();
     }
     //执行属性的清理
     $tag = isset($this->allowedTags[$elem]) ? $this->allowedTags[$elem] : array();
     foreach ($return as $name => $info) {
         if (!isset($info['value'])) {
             continue;
         }
         //去掉不允许的
         if (isset($tag['disallowed']) && in_array($name, $tag['disallowed'])) {
             unset($return[$name]);
             continue;
         }
         //只留允许的
         if (isset($tag['allowed']) && !in_array($name, $tag['allowed'])) {
             unset($return[$name]);
             continue;
         }
         //对style深度清理
         if ($name == 'style') {
             $sanitized_properties = array();
             $properties = array_filter(array_map('trim', explode(';', String::decodeEntities($info['value']))));
             foreach ($properties as $property) {
                 if (!preg_match('#^([a-zA-Z][-a-zA-Z]*)\\s*:\\s*(.*)$#', $property, $property_matches)) {
                     continue;
                 }
                 $property_name = strtolower($property_matches[1]);
                 $property_value =& $property_matches[2];
                 if (!isset($this->allowedStyleProperties[$property_name])) {
                     continue;
                 }
                 if (strpos($property_value, 'url(') !== false) {
                     if (!preg_match('`url\\(\\s*(([\'"]?)(?:[^)]|(?<=\\\\)\\))+[\'"]?)\\s*\\)`', $property_value, $url) || empty($url[1])) {
                         continue;
                     }
                     if (!empty($url[2])) {
                         if (substr($url[1], -1) != $url[2]) {
                             continue;
                         }
                         $url[1] = substr($url[1], 1, -1);
                     }
                     $url = preg_replace('`\\\\([(),\'"\\s])`', '\\1', $url[1]);
                     if (String::filterBadProtocol($url) != $url) {
                         continue;
                     }
                     if (!preg_match('`^/[^/]+`', $url)) {
                         $match = false;
                         foreach ($this->allowedStyleDomain as $reg) {
                             if (preg_match($reg, $url)) {
                                 $match = true;
                                 break;
                             }
                         }
                         if (!$match) {
                             continue;
                         }
                     }
                 }
                 $sanitized_properties[] = $property_name . ':' . String::checkPlain($property_value);
             }
             if (empty($sanitized_properties)) {
                 unset($return[$name]);
                 continue;
             }
             $info['value'] = implode('; ', $sanitized_properties);
         } else {
             $info['value'] = String::filterBadProtocol($info['value']);
         }
         $return[$name] = $name . '=' . $info['delimiter'] . $info['value'] . $info['delimiter'];
     }
     return $return;
 }