Ejemplo n.º 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  ", \StringUtil::decodeEntities($this->flashJS));
     $this->Template->flashvars = 'URL=' . \Environment::get('base');
     $this->Template->version = $this->version ?: '6.0.0';
     $size = \StringUtil::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 .= '&' . \StringUtil::decodeEntities($this->flashvars);
     }
 }
Ejemplo n.º 2
0
 /**
  * Get a translation of a value using the translation label
  *
  * @param mixed  $varLabel
  * @param string $strLanguage
  *
  * @return mixed
  */
 public static function get($varLabel, $strLanguage = null)
 {
     if (!\Database::getInstance()->tableExists(Label::getTable())) {
         return $varLabel;
     }
     if (null === $strLanguage) {
         $strLanguage = $GLOBALS['TL_LANGUAGE'];
     }
     // Convert Language Tag to Locale ID
     $strLanguage = str_replace('-', '_', $strLanguage);
     // 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] = \StringUtil::decodeEntities(static::$arrLabels[$strLanguage][$varLabel]);
         return static::$arrLabels[$strLanguage][$varLabel];
     }
     return $varLabel;
 }
Ejemplo n.º 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);
     }
     // 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;
 }
 protected function getFieldMappingDbValue($arrSourceConfig, $arrTargetConfig, $strForeignKey = '')
 {
     $t = $this->dbSourceTable;
     $strValue = $arrSourceConfig['name'];
     switch ($arrSourceConfig['type']) {
         case 'timestamp':
             if ($arrTargetConfig['type'] == 'int') {
                 $strValue = "UNIX_TIMESTAMP({$t}.{$strValue})";
             }
             break;
         default:
             $strValue = $this->dbSourceTable . '.' . $strValue;
     }
     if ($strForeignKey != '' && preg_match('#(?<PK>.*)=(?<TABLE>.*)[.](?<COLUMN>.*)#', \StringUtil::decodeEntities($strForeignKey), $arrForeignKey)) {
         if (isset($arrForeignKey['PK']) && $arrForeignKey['TABLE'] && $arrForeignKey['COLUMN']) {
             $strValue = sprintf("(SELECT %s FROM %s WHERE %s=%s)", $arrForeignKey['COLUMN'], $arrForeignKey['TABLE'], $arrForeignKey['PK'], $strValue);
         }
     }
     return $strValue;
 }
 /**
  * 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);
 }
Ejemplo n.º 7
0
 /**
  * Process form data, store it in the session and redirect to the jumpTo page
  *
  * @param array $arrSubmitted
  * @param array $arrLabels
  * @param array $arrFields
  */
 protected function processFormData($arrSubmitted, $arrLabels, $arrFields)
 {
     // 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, $arrFields, $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 = \StringUtil::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') {
             /** @var \FrontendTemplate|object $objTemplate */
             $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(\StringUtil::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 = \StringUtil::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;
                 // Convert date formats into timestamps (see #6827)
                 if ($arrSet[$k] != '' && in_array($arrFields[$k]->rgxp, array('date', 'time', 'datim'))) {
                     $objDate = new \Date($arrSet[$k], \Date::getFormatFromRgxp($arrFields[$k]->rgxp));
                     $arrSet[$k] = $objDate->tstamp;
                 }
             }
         }
         // 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();
 }
Ejemplo n.º 8
0
 /**
  * Add a form to create new comments
  *
  * @param \FrontendTemplate|object $objTemplate
  * @param \stdClass                $objConfig
  * @param string                   $strSource
  * @param integer                  $intParent
  * @param mixed                    $varNotifies
  */
 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;
         $objTemplate->login = $GLOBALS['TL_LANG']['MSC']['com_login'];
         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) {
         /** @var \Widget $strClass */
         $strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
         // Continue if the class is not defined
         if (!class_exists($strClass)) {
             continue;
         }
         $arrField['eval']['required'] = $arrField['eval']['mandatory'];
         /** @var \Widget $objWidget */
         $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']) {
         /** @var \PageModel $objPage */
         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 = \StringUtil::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();
     }
 }
Ejemplo n.º 9
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
  */
 protected function doReplace($strBuffer, $blnCache)
 {
     /** @var PageModel $objPage */
     global $objPage;
     // Preserve insert tags
     if (\Config::get('disableInsertTags')) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $tags = preg_split('/{{([^{}]+)}}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
     if (count($tags) < 2) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $strBuffer = '';
     // Create one cache per cache setting (see #7700)
     static $arrItCache;
     $arrCache =& $arrItCache[$blnCache];
     for ($_rit = 0, $_cnt = count($tags); $_rit < $_cnt; $_rit += 2) {
         $strBuffer .= $tags[$_rit];
         $strTag = $tags[$_rit + 1];
         // Skip empty tags
         if ($strTag == '') {
             continue;
         }
         $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>';
                 } else {
                     $arrCache[$strTag] = $arrCache[$strTag] = '<span lang="' . $elements[1] . '">';
                 }
                 break;
                 // Line break
             // Line break
             case 'br':
                 $arrCache[$strTag] = '<br>';
                 break;
                 // E-mail addresses
             // E-mail addresses
             case 'email':
             case 'email_open':
             case 'email_url':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $strEmail = \StringUtil::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 = \StringUtil::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] = \StringUtil::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 = $objNextPage->url;
                             if (strncasecmp($strUrl, 'mailto:', 7) === 0) {
                                 $strUrl = \StringUtil::encodeEmail($strUrl);
                             }
                             break;
                         case 'forward':
                             if ($objNextPage->jumpTo) {
                                 /** @var PageModel $objNext */
                                 $objNext = $objNextPage->getRelated('jumpTo');
                             } else {
                                 $objNext = \PageModel::findFirstPublishedRegularByPid($objNextPage->id);
                             }
                             if ($objNext instanceof PageModel) {
                                 $strUrl = $objNext->getFrontendUrl();
                                 break;
                             }
                             // DO NOT ADD A break; STATEMENT
                         // DO NOT ADD A break; STATEMENT
                         default:
                             $strUrl = $objNextPage->getFrontendUrl();
                             break;
                     }
                     $strName = $objNextPage->title;
                     $strTarget = $objNextPage->target ? ' 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, \StringUtil::specialchars($strTitle), $strTarget, $strName);
                         break;
                     case 'link_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget);
                         break;
                     case 'link_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'link_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($strTitle);
                         break;
                     case 'link_target':
                         $arrCache[$strTag] = $strTarget;
                         break;
                     case 'link_name':
                         $arrCache[$strTag] = $strName;
                         break;
                 }
                 break;
                 // Closing link tag
             // Closing link tag
             case 'link_close':
             case 'email_close':
                 $arrCache[$strTag] = '</a>';
                 break;
                 // Insert article
             // Insert article
             case 'insert_article':
                 if (($strOutput = $this->getArticle($elements[1], false, true)) !== false) {
                     $arrCache[$strTag] = 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->getContentElement($elements[1]);
                 break;
                 // Insert module
             // Insert module
             case 'insert_module':
                 $arrCache[$strTag] = $this->getFrontendModule($elements[1]);
                 break;
                 // Insert form
             // Insert form
             case 'insert_form':
                 $arrCache[$strTag] = $this->getForm($elements[1]);
                 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')) instanceof PageModel) {
                     break;
                 }
                 /** @var PageModel $objPid */
                 $strUrl = $objPid->getFrontendUrl('/articles/' . ($objArticle->alias ?: $objArticle->id));
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'article':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, \StringUtil::specialchars($objArticle->title), $objArticle->title);
                         break;
                     case 'article_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, \StringUtil::specialchars($objArticle->title));
                         break;
                     case 'article_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'article_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($objArticle->title);
                         break;
                 }
                 break;
                 // Article teaser
             // Article teaser
             case 'article_teaser':
                 $objTeaser = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     $arrCache[$strTag] = \StringUtil::toHtml5($objTeaser->teaser);
                 }
                 break;
                 // Last update
             // Last update
             case 'last_update':
                 $strQuery = "SELECT MAX(tstamp) AS tc";
                 $bundles = \System::getContainer()->getParameter('kernel.bundles');
                 if (isset($bundles['ContaoNewsBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_news) AS tn";
                 }
                 if (isset($bundles['ContaoCalendarBundle'])) {
                     $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="' . \StringUtil::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="' . \StringUtil::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 += 2) {
                         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 = \StringUtil::trimsplit(',', $elements[1]);
                     if (in_array($objPage->language, $langs)) {
                         for (; $_rit < $_cnt; $_rit += 2) {
                             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;
                     case 'base_url':
                         $arrCache[$strTag] = \System::getContainer()->get('request_stack')->getCurrentRequest()->getBaseUrl();
                         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 \StringUtil::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;
                 // Abbreviations
             // Abbreviations
             case 'abbr':
             case 'acronym':
                 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 = \StringUtil::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 = \StringUtil::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));
                         // 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 . '"' : '') . '>';
                     } 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) {
                             $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 = \StringUtil::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_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] = \StringUtil::$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;
                     case 'flatten':
                         if (!is_array($arrCache[$strTag])) {
                             break;
                         }
                         $it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arrCache[$strTag]));
                         $result = array();
                         foreach ($it as $leafValue) {
                             $keys = array();
                             foreach (range(0, $it->getDepth()) as $depth) {
                                 $keys[] = $it->getSubIterator($depth)->key();
                             }
                             $result[] = implode('.', $keys) . ': ' . $leafValue;
                         }
                         $arrCache[$strTag] = implode(', ', $result);
                         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 \StringUtil::restoreBasicEntities($strBuffer);
 }
Ejemplo n.º 10
0
 /**
  * Add a form to create new testimonials
  * @param \FrontendTemplate
  * @param \stdClass
  * @param string
  * @param integer
  * @param array
  */
 protected function renderTestimonialForm(\FrontendTemplate $objTemplate, \stdClass $objConfig, $intParent)
 {
     $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']['tm_name'], 'value' => trim($this->User->firstname . ' ' . $this->User->lastname), 'inputType' => 'text', 'eval' => array('mandatory' => true, 'maxlength' => 64, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_name'])), 'email' => array('name' => 'email', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_email'], 'value' => $this->User->email, 'inputType' => 'text', 'eval' => array('rgxp' => 'email', 'mandatory' => true, 'maxlength' => 128, 'decodeEntities' => true, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_email'])), 'url' => array('name' => 'url', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_url'], 'inputType' => 'text', 'eval' => array('rgxp' => 'url', 'maxlength' => 128, 'decodeEntities' => true, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_url'])), 'company' => array('name' => 'company', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_company'], 'inputType' => 'text', 'eval' => array('maxlength' => 128, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_company'])), 'title' => array('name' => 'title', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_title'], 'inputType' => 'text', 'eval' => array('maxlength' => 128, 'placeholder' => $GLOBALS['TL_LANG']['MSC']['tm_title'])));
     if ($objConfig->enableVoteField1 && $objConfig->addVote) {
         $arrFields['votefield1'] = array('name' => 'votefield1', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield1'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField2 && $objConfig->addVote) {
         $arrFields['votefield2'] = array('name' => 'votefield2', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield2'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField3 && $objConfig->addVote) {
         $arrFields['votefield3'] = array('name' => 'votefield3', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield3'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField4 && $objConfig->addVote) {
         $arrFields['votefield4'] = array('name' => 'votefield4', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield4'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField5 && $objConfig->addVote) {
         $arrFields['votefield5'] = array('name' => 'votefield5', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield5'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     if ($objConfig->enableVoteField6 && $objConfig->addVote) {
         $arrFields['votefield6'] = array('name' => 'votefield6', 'label' => &$GLOBALS['TL_LANG']['MSC']['votefield6'], 'default' => '0.0', 'inputType' => 'text', 'eval' => array('style' => 'display: none;'));
     }
     // Captcha
     if (!$objConfig->disableCaptcha) {
         $arrFields['captcha'] = array('name' => 'captcha', 'inputType' => 'captcha', 'eval' => array('mandatory' => true));
     }
     // Testimonial field
     $arrFields['testimonial'] = array('name' => 'testimonial', 'label' => $GLOBALS['TL_LANG']['MSC']['tm_testimonial'], 'inputType' => 'textarea', 'eval' => array('mandatory' => true, 'rows' => 15, 'cols' => 40, 'preserveTags' => true));
     $doNotSubmit = false;
     $arrWidgets = array();
     $strFormId = 'jedo_testimonials_' . $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($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_TESTIMONIAL_ADDED']) {
         global $objPage;
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         $objTemplate->confirm = $GLOBALS['TL_LANG']['MSC']['com_confirm'];
         $_SESSION['TL_TESTIMONIAL_ADDED'] = false;
     }
     // Store the testimonial
     if (!$doNotSubmit && \Input::post('FORM_SUBMIT') == $strFormId) {
         $strWebsite = $arrWidgets['url']->value;
         if ($strWebsite == $GLOBALS['TL_LANG']['MSC']['tm_url']) {
             $strWebsite = '';
         }
         // Add http:// to the website
         if ($strWebsite != '' && !preg_match('@^(https?://|ftp://|mailto:|#)@i', $strWebsite)) {
             $strWebsite = 'http://' . $strWebsite;
         }
         // Do not parse any tags in the testimonial
         $strTestimonial = htmlspecialchars(trim($arrWidgets['testimonial']->value));
         $strTestimonial = str_replace(array('&amp;', '&lt;', '&gt;'), array('[&]', '[lt]', '[gt]'), $strTestimonial);
         // Remove multiple line feeds
         $strTestimonial = preg_replace('@\\n\\n+@', "\n\n", $strTestimonial);
         // Parse BBCode
         if ($objConfig->bbcode) {
             $strTestimonial = $this->parseBbCode($strTestimonial);
         }
         // Prevent cross-site request forgeries
         $strTestimonial = preg_replace('/(href|src|on[a-z]+)="[^"]*(contao\\/main\\.php|typolight\\/main\\.php|javascript|vbscri?pt|script|alert|document|cookie|window)[^"]*"+/i', '$1="#"', $strTestimonial);
         $time = time();
         if ($objConfig->addVote) {
             // make the totalvote object
             $fields = 0;
             $value = 0.0;
             if ($objConfig->enableVoteField1) {
                 $arrWidgets['votefield1']->value = $this->getRatingValue($arrWidgets['votefield1']->value);
                 $value = $value + $arrWidgets['votefield1']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField2) {
                 $arrWidgets['votefield2']->value = $this->getRatingValue($arrWidgets['votefield2']->value);
                 $value = $value + $arrWidgets['votefield2']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField3) {
                 $arrWidgets['votefield3']->value = $this->getRatingValue($arrWidgets['votefield3']->value);
                 $value = $value + $arrWidgets['votefield3']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField4) {
                 $arrWidgets['votefield4']->value = $this->getRatingValue($arrWidgets['votefield4']->value);
                 $value = $value + $arrWidgets['votefield4']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField5) {
                 $arrWidgets['votefield5']->value = $this->getRatingValue($arrWidgets['votefield5']->value);
                 $value = $value + $arrWidgets['votefield5']->value;
                 $fields++;
             }
             if ($objConfig->enableVoteField6) {
                 $arrWidgets['votefield6']->value = $this->getRatingValue($arrWidgets['votefield6']->value);
                 $value = $value + $arrWidgets['votefield6']->value;
                 $fields++;
             }
             $totalvote = $value / $fields;
             $strTVotes = number_format($totalvote, 2);
         }
         if ($arrWidgets['company']->value == $value_company) {
             $arrWidgets['company']->value = '';
         }
         if ($arrWidgets['title']->value == $value_title) {
             $arrWidgets['title']->value = '';
         }
         // Prepare the record
         $arrSet = array('tstamp' => $time, 'name' => $arrWidgets['name']->value, 'email' => $arrWidgets['email']->value, 'company' => $arrWidgets['company']->value, 'title' => $arrWidgets['title']->value, 'url' => $strWebsite, 'testimonial' => $this->convertLineFeeds($strTestimonial), 'ip' => $this->anonymizeIp($this->Environment->ip), 'date' => $time, 'votestotal' => $strTVotes, 'votefield1' => !$objConfig->enableVoteField1 ? '' : $arrWidgets['votefield1']->value, 'votefield2' => !$objConfig->enableVoteField2 ? '' : $arrWidgets['votefield2']->value, 'votefield3' => !$objConfig->enableVoteField3 ? '' : $arrWidgets['votefield3']->value, 'votefield4' => !$objConfig->enableVoteField4 ? '' : $arrWidgets['votefield4']->value, 'votefield5' => !$objConfig->enableVoteField5 ? '' : $arrWidgets['votefield5']->value, 'votefield6' => !$objConfig->enableVoteField6 ? '' : $arrWidgets['votefield6']->value, 'published' => $objConfig->moderate ? '' : 1);
         // Store the testimonial
         $objTestimonials = new \TestimonialsModel();
         $objTestimonials->setRow($arrSet)->save();
         // 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']['tm_subject'], \Idna::decode(\Environment::get('host')));
         // Convert the testimonial to plain text
         $strTestimonial = strip_tags($strTestimonial);
         $strTestimonial = \StringUtil::decodeEntities($strTestimonial);
         $strTestimonial = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strTestimonial);
         // Add the testimonial details
         $objEmail->text = sprintf($GLOBALS['TL_LANG']['MSC']['tm_message'], $arrSet['name'] . ' (' . $arrSet['email'] . ')', $strTestimonial, \Idna::decode(\Environment::get('base')) . \Environment::get('request'), \Idna::decode(\Environment::get('base')) . 'contao/main.php?do=testimonials&act=edit&id=' . $objTestimonials->id);
         $objEmail->sendTo($GLOBALS['TL_ADMIN_EMAIL']);
         // Pending for approval
         if ($objConfig->moderate) {
             // FIXME: notify the subscribers when the testimonial is published
             $_SESSION['TL_TESTIMONIAL_ADDED'] = true;
         }
         $this->reload();
     }
 }
Ejemplo n.º 11
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"' : '') . '>';
     }
     // 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(',', \StringUtil::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) {
                 $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'] != '') {
                 $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'] != '')) {
                 $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);
     // Custom code
     if ($row['own'] != '') {
         $own = trim(\StringUtil::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);
 }
 protected static function addCopyrightToTemplate(&$objTemplate, $objFilesModel, $objModule)
 {
     $arrCopyright = deserialize($objFilesModel->copyright, true);
     $arrList = array();
     foreach ($arrCopyright as $strCopyright) {
         $strCopyright = \StringUtil::decodeEntities(\String::restoreBasicEntities($strCopyright));
         if ($objModule->creditsPrefix != '') {
             $strPrefix = \StringUtil::decodeEntities(\String::restoreBasicEntities($objModule->creditsPrefix));
             if (!($strPrefix === "" || strrpos($strCopyright, $strPrefix, -strlen($strCopyright)) !== false)) {
                 $strCopyright = $strPrefix . trim(ltrim($strCopyright, $strPrefix));
             }
         }
         $arrList[] = $strCopyright;
     }
     $objTemplate->copyright = implode(', ', $arrList);
 }
Ejemplo n.º 13
0
 /**
  * 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 = \StringUtil::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;
     }
 }
Ejemplo n.º 14
0
 /**
  * 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 = \StringUtil::decodeEntities($strKeywords);
     if (function_exists('mb_eregi_replace')) {
         $strKeywords = mb_eregi_replace('[^[:alnum:] \\*\\+\'"\\.:,_-]|\\. |\\.$|: |:$|, |,$', ' ', $strKeywords);
     } else {
         $strKeywords = preg_replace(array('/\\. /', '/\\.$/', '/: /', '/:$/', '/, /', '/,$/', '/[^\\w\' *+".:,-]/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);
 }
Ejemplo n.º 15
0
 /**
  * @param $varValue
  * @return mixed|string
  */
 private function decodeValue($varValue)
 {
     if (class_exists('StringUtil')) {
         $varValue = \StringUtil::decodeEntities($varValue);
     } else {
         // backwards compatible
         $varValue = \Input::decodeEntities($varValue);
     }
     return $varValue;
 }
Ejemplo n.º 16
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));
 }