Ejemplo n.º 1
0
 /**
  * Recursively replace simple tokens and insert tags
  *
  * @param   string $strText
  * @param   array  $arrTokens Array of Tokens
  *
  * @return  string
  */
 public static function recursiveReplaceTokensAndTags($text, $tokens)
 {
     // Must decode, tokens could be encoded
     $text = \String::decodeEntities($text);
     // Replace all opening and closing tags with a hash so they don't get stripped
     // by parseSimpleTokens()
     $hash = md5($text);
     $openTagReplacement = 'LEADS-TAG-OPEN-' . $hash;
     $closeTagReplacement = 'LEADS-TAG-CLOSE-' . $hash;
     $original = array('<', '>');
     $replacement = array($openTagReplacement, $closeTagReplacement);
     $text = str_replace($original, $replacement, $text);
     // first parse the tokens as they might have if-else clauses
     $buffer = \String::parseSimpleTokens($text, $tokens);
     // Restore tags
     $buffer = str_replace($replacement, $original, $buffer);
     // Replace the Insert Tags
     $buffer = \Haste\Haste::getInstance()->call('replaceInsertTags', array($buffer, false));
     // Check if the Insert Tags have returned a Simple Token or an Insert Tag to parse
     if ((strpos($buffer, '##') !== false || strpos($buffer, '{{') !== false) && $buffer != $text) {
         $buffer = static::recursiveReplaceTokensAndTags($buffer, $tokens);
     }
     $buffer = \String::restoreBasicEntities($buffer);
     return $buffer;
 }
 /**
  * Generate the module
  */
 protected function compile()
 {
     global $objPage;
     $this->Template->content = '';
     $this->Template->referer = 'javascript:history.go(-1)';
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     if (TL_MODE == 'FE' && BE_USER_LOGGED_IN) {
         $objNewsletter = \NewsletterModel::findByIdOrAlias(\Input::get('items'));
     } else {
         $objNewsletter = \NewsletterModel::findSentByParentAndIdOrAlias(\Input::get('items'), $this->nl_channels);
     }
     if ($objNewsletter === null) {
         // Do not index or cache the page
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         // Send a 404 header
         header('HTTP/1.1 404 Not Found');
         $this->Template->content = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], \Input::get('items')) . '</p>';
         return;
     }
     // Overwrite the page title (see #2853 and #4955)
     if ($objNewsletter->subject != '') {
         $objPage->pageTitle = strip_tags(strip_insert_tags($objNewsletter->subject));
     }
     // Add enclosure
     if ($objNewsletter->addFile) {
         $this->addEnclosuresToTemplate($this->Template, $objNewsletter->row(), 'files');
     }
     if (!$objNewsletter->sendText) {
         $nl2br = $objPage->outputFormat == 'xhtml' ? 'nl2br_xhtml' : 'nl2br_html5';
         $strContent = '';
         $objContentElements = \ContentModel::findPublishedByPidAndTable($objNewsletter->id, 'tl_newsletter');
         if ($objContentElements !== null) {
             if (!defined('NEWSLETTER_CONTENT_PREVIEW')) {
                 define('NEWSLETTER_CONTENT_PREVIEW', true);
             }
             foreach ($objContentElements as $objContentElement) {
                 $strContent .= $this->getContentElement($objContentElement->id);
             }
         }
         // Parse simple tokens and insert tags
         $strContent = $this->replaceInsertTags($strContent);
         $strContent = \String::parseSimpleTokens($strContent, array());
         // Encode e-mail addresses
         $strContent = \String::encodeEmail($strContent);
         $this->Template->content = $strContent;
     } else {
         $strContent = str_ireplace(' align="center"', '', $objNewsletter->content);
     }
     // Convert relative URLs
     $strContent = $this->convertRelativeUrls($strContent);
     // Parse simple tokens and insert tags
     $strContent = $this->replaceInsertTags($strContent);
     $strContent = \String::parseSimpleTokens($strContent, array());
     // Encode e-mail addresses
     $strContent = \String::encodeEmail($strContent);
     $this->Template->content = $strContent;
     $this->Template->subject = $objNewsletter->subject;
 }
Ejemplo n.º 3
0
 /**
  * Return formatted address (hCard)
  * @param array
  * @return string
  */
 public function generate($arrFields = null)
 {
     // We need a country to format the address, use default country if none is available
     $strCountry = $this->country ?: Isotope::getConfig()->country;
     // Use generic format if no country specific format is available
     $strFormat = $GLOBALS['ISO_ADR'][$strCountry] ?: $GLOBALS['ISO_ADR']['generic'];
     $arrTokens = $this->getTokens($arrFields);
     $strAddress = \String::parseSimpleTokens($strFormat, $arrTokens);
     return $strAddress;
 }
Ejemplo n.º 4
0
 /**
  * Prepare file name
  * @param   string File name
  * @param   array Simple tokens (optional)
  * @param   string Path (optional)
  * @return  string Sanitized file name
  */
 protected function prepareFileName($strName, $arrTokens = array(), $strPath = '')
 {
     // Replace simple tokens
     $strName = \String::parseSimpleTokens($strName, $arrTokens);
     $strName = $this->sanitizeFileName($strName);
     if ($strPath) {
         // Make sure the path contains a trailing slash
         $strPath = preg_replace('/([^\\/]+)$/', '$1/', $strPath);
         $strName = $strPath . $strName;
     }
     return $strName;
 }
Ejemplo n.º 5
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;
 }
Ejemplo n.º 6
0
 public static function getPageIdFromUrlHook($arrFragments)
 {
     $objParticipation = ParticipationModel::findPublishedByAlias(\Environment::get('request'));
     if ($objParticipation !== null) {
         $blnAddParticipation = true;
         // only one participation per alias is supported yet
         if ($objParticipation instanceof \Model\Collection) {
             $objParticipation = $objParticipation->current();
         }
         $objArchive = $objParticipation->getRelated('pid');
         if ($objArchive === null) {
             $blnAddParticipation = false;
         }
         // check if current page is in defined root
         if ($objArchive->defineRoot && $objArchive->rootPage > 0) {
             $objCurrentRootPage = \Frontend::getRootPageFromUrl();
             $objRootPage = \PageModel::findByPk($objArchive->rootPage);
             if ($objRootPage !== null && $objCurrentRootPage !== null) {
                 if ($objRootPage->domain != $objCurrentRootPage->domain) {
                     $blnAddParticipation = false;
                     ParticipationController::removeActiveParticipation();
                 }
             }
         }
         if ($blnAddParticipation) {
             ParticipationController::setActiveParticipation($objParticipation);
             if ($objArchive->addInfoMessage && $objArchive->infoMessageWith !== '') {
                 ParticipationMessage::addInfo(\String::parseSimpleTokens($objArchive->infoMessageWith, array('participation' => ParticipationController::getParticipationLabel($objParticipation, '', true))), PARTICIPATION_MESSAGEKEY_ACTIVE);
             }
         }
         if (($objConfig = ParticipationController::findParticipationDataConfigClass($objParticipation)) !== null) {
             global $objPage;
             $objJumpTo = $objConfig->getJumpToPage();
             // redirect first, otherwise participation process will run twice
             if ($objJumpTo !== null && $objPage->id != $objJumpTo->id) {
                 \Controller::redirect(\Controller::generateFrontendUrl($objJumpTo->row()));
             }
         }
     }
     return $arrFragments;
 }
 /**
  * Gets an array of valid attachments of a token field
  *
  * @param string $strAttachmentTokens
  * @param array  $arrTokens
  *
  * @return array
  */
 public static function getTokenAttachments($strAttachmentTokens, array $arrTokens)
 {
     $arrAttachments = array();
     if ($strAttachmentTokens == '') {
         return $arrAttachments;
     }
     foreach (trimsplit(',', $strAttachmentTokens) as $strToken) {
         if (version_compare(VERSION . '.' . BUILD, '3.5.1', '<')) {
             $strParsedToken = \String::parseSimpleTokens($strToken, $arrTokens);
         } else {
             $strParsedToken = \StringUtil::parseSimpleTokens($strToken, $arrTokens);
         }
         foreach (trimsplit(',', $strParsedToken) as $strFile) {
             $strFileFull = TL_ROOT . '/' . str_replace($arrTokens['env_url'] . '/', '', $strFile);
             if (is_file($strFileFull)) {
                 $arrAttachments[$strFile] = $strFileFull;
             }
         }
     }
     return $arrAttachments;
 }
Ejemplo n.º 8
0
 /**
  * Get the filename from a database config.
  *
  * @param   \Database\Result $config
  * @return  string
  */
 public static function getName($config)
 {
     if ($config->filename == '') {
         $filename = 'export_' . md5(uniqid());
         if ($config->type) {
             $filename .= '.' . $config->type;
         }
         return $filename;
     }
     $tokens = array('time' => \Date::parse($GLOBALS['TL_CONFIG']['timeFormat']), 'date' => \Date::parse($GLOBALS['TL_CONFIG']['dateFormat']), 'datim' => \Date::parse($GLOBALS['TL_CONFIG']['datimFormat']));
     // Add custom logic
     if (isset($GLOBALS['TL_HOOKS']['getLeadsFilenameTokens']) && is_array($GLOBALS['TL_HOOKS']['getLeadsFilenameTokens'])) {
         foreach ($GLOBALS['TL_HOOKS']['getLeadsFilenameTokens'] as $callback) {
             if (is_array($callback)) {
                 $tokens = \System::importStatic($callback[0])->{$callback[1]}($tokens, $config);
             } elseif (is_callable($callback)) {
                 $tokens = $callback($tokens, $config);
             }
         }
     }
     return \String::parseSimpleTokens($config->filename, $tokens);
 }
Ejemplo n.º 9
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     global $objPage;
     $this->Template->content = '';
     $this->Template->referer = 'javascript:history.go(-1)';
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     $objNewsletter = \NewsletterModel::findSentByParentAndIdOrAlias(\Input::get('items'), $this->nl_channels);
     if ($objNewsletter === null) {
         // Do not index or cache the page
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         // Send a 404 header
         header('HTTP/1.1 404 Not Found');
         $this->Template->content = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], \Input::get('items')) . '</p>';
         return;
     }
     $arrEnclosures = array();
     // Add enclosure
     if ($objNewsletter->addFile) {
         $arrEnclosure = deserialize($objNewsletter->files, true);
         $allowedDownload = trimsplit(',', strtolower($GLOBALS['TL_CONFIG']['allowedDownload']));
         if (is_array($arrEnclosure)) {
             // Send file to the browser
             if (\Input::get('file', true) != '' && in_array(\Input::get('file', true), $arrEnclosure)) {
                 $this->sendFileToBrowser(\Input::get('file', true));
             }
             // Add download links
             for ($i = 0; $i < count($arrEnclosure); $i++) {
                 if (is_file(TL_ROOT . '/' . $arrEnclosure[$i])) {
                     $objFile = new \File($arrEnclosure[$i]);
                     if (in_array($objFile->extension, $allowedDownload)) {
                         $src = 'system/themes/' . $this->getTheme() . '/images/' . $objFile->icon;
                         if (($imgSize = @getimagesize(TL_ROOT . '/' . $src)) !== false) {
                             $arrEnclosures[$i]['size'] = ' ' . $imgSize[3];
                         }
                         $arrEnclosures[$i]['icon'] = TL_FILES_URL . $src;
                         $arrEnclosures[$i]['link'] = basename($arrEnclosure[$i]);
                         $arrEnclosures[$i]['filesize'] = $this->getReadableSize($objFile->filesize);
                         $arrEnclosures[$i]['title'] = ucfirst(str_replace('_', ' ', $objFile->filename));
                         $arrEnclosures[$i]['href'] = \Environment::get('request') . ($GLOBALS['TL_CONFIG']['disableAlias'] || strpos(\Environment::get('request'), '?') !== false ? '&amp;' : '?') . 'file=' . $this->urlEncode($arrEnclosure[$i]);
                         $arrEnclosures[$i]['enclosure'] = $arrEnclosure[$i];
                     }
                 }
             }
         }
     }
     // Support plain text newsletters (thanks to Hagen Klemp)
     if ($objNewsletter->sendText) {
         $nl2br = $objPage->outputFormat == 'xhtml' ? 'nl2br_xhtml' : 'nl2br_html5';
         $strContent = $nl2br($objNewsletter->text);
     } else {
         $strContent = str_ireplace(' align="center"', '', $objNewsletter->content);
     }
     // Parse simple tokens and insert tags
     $strContent = $this->replaceInsertTags($strContent);
     $strContent = \String::parseSimpleTokens($strContent, array());
     // Encode e-mail addresses
     $strContent = \String::encodeEmail($strContent);
     $this->Template->content = $strContent;
     $this->Template->subject = $objNewsletter->subject;
     $this->Template->enclosure = $arrEnclosures;
 }
Ejemplo n.º 10
0
 /**
  * Validate the input and set the value
  */
 public function validate()
 {
     $this->maxlength = $GLOBALS['TL_CONFIG']['avatar_maxsize'];
     $this->extensions = $GLOBALS['TL_CONFIG']['avatar_filetype'];
     $this->uploadFolder = $GLOBALS['TL_CONFIG']['avatar_dir'];
     $this->storeFile = $this->uploadFolder != '' ? true : false;
     $arrImage = deserialize($GLOBALS['TL_CONFIG']['avatar_maxdims']);
     $this->import('FrontendUser', 'User');
     // No file specified
     if (!isset($_FILES[$this->strName]) || empty($_FILES[$this->strName]['name'])) {
         if ($this->mandatory) {
             if ($this->strLabel == '') {
                 $this->addError($GLOBALS['TL_LANG']['ERR']['mdtryNoLabel']);
             } else {
                 $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['mandatory'], $this->strLabel));
             }
         }
         return;
     }
     $file = $_FILES[$this->strName];
     $maxlength_kb = $this->getReadableSize($this->maxlength);
     // Romanize the filename
     $file['name'] = utf8_romanize($file['name']);
     // File was not uploaded
     if (!is_uploaded_file($file['tmp_name'])) {
         if (in_array($file['error'], array(1, 2))) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb));
             $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR);
         }
         if ($file['error'] == 3) {
             $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filepartial'], $file['name']));
             $this->log('File "' . $file['name'] . '" was only partially uploaded', 'FormFileUpload validate()', TL_ERROR);
         }
         unset($_FILES[$this->strName]);
         return;
     }
     // File is too big
     if ($this->maxlength > 0 && $file['size'] > $this->maxlength) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filesize'], $maxlength_kb));
         $this->log('File "' . $file['name'] . '" exceeds the maximum file size of ' . $maxlength_kb, 'FormFileUpload validate()', TL_ERROR);
         unset($_FILES[$this->strName]);
         return;
     }
     $strExtension = pathinfo($file['name'], PATHINFO_EXTENSION);
     $uploadTypes = trimsplit(',', $this->extensions);
     // File type is not allowed
     if (!in_array(strtolower($strExtension), $uploadTypes)) {
         $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $strExtension));
         $this->log('File type "' . $strExtension . '" is not allowed to be uploaded (' . $file['name'] . ')', 'FormFileUpload validate()', TL_ERROR);
         unset($_FILES[$this->strName]);
         return;
     }
     $blnResize = false;
     if (($arrImageSize = @getimagesize($file['tmp_name'])) != false) {
         // Image exceeds maximum image width
         if ($arrImageSize[0] > $arrImage[0]) {
             if ($GLOBALS['TL_CONFIG']['avatar_resize']) {
                 $blnResize = true;
             } else {
                 $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], $file['name'], $arrImage[0]));
                 $this->log('File "' . $file['name'] . '" exceeds the maximum image width of ' . $GLOBALS['TL_CONFIG']['imageWidth'] . ' pixels', 'FormFileUpload validate()', TL_ERROR);
                 unset($_FILES[$this->strName]);
                 return;
             }
         }
         // Image exceeds maximum image height
         if ($arrImageSize[1] > $arrImage[1]) {
             if ($GLOBALS['TL_CONFIG']['avatar_resize']) {
                 $blnResize = true;
             } else {
                 $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], $file['name'], $arrImage[1]));
                 $this->log('File "' . $file['name'] . '" exceeds the maximum image height of ' . $GLOBALS['TL_CONFIG']['imageHeight'] . ' pixels', 'FormFileUpload validate()', TL_ERROR);
                 unset($_FILES[$this->strName]);
                 return;
             }
         }
     }
     // Store file in the session and optionally on the server
     if (!$this->hasErrors()) {
         $_SESSION['FILES'][$this->strName] = $_FILES[$this->strName];
         $this->log('File "' . $file['name'] . '" uploaded successfully', 'FormFileUpload validate()', TL_FILES);
         if ($this->storeFile) {
             $intUploadFolder = $this->uploadFolder;
             if ($this->User->assignDir && $this->User->homeDir) {
                 $intUploadFolder = $this->User->homeDir;
             }
             $objUploadFolder = \FilesModel::findByUuid($intUploadFolder);
             // The upload folder could not be found
             if ($objUploadFolder === null) {
                 throw new \Exception("Invalid upload folder ID {$intUploadFolder}");
             }
             $strUploadFolder = $objUploadFolder->path;
             // Store the file if the upload folder exists
             if ($strUploadFolder != '' && is_dir(TL_ROOT . '/' . $strUploadFolder)) {
                 $this->import('Files');
                 if ($GLOBALS['TL_CONFIG']['avatar_rename']) {
                     $pathinfo = pathinfo($file['name']);
                     $user = \MemberModel::findByPk($this->User->id);
                     $targetName = standardize(\String::parseSimpleTokens($GLOBALS['TL_CONFIG']['avatar_name'], $user->row())) . '.' . $pathinfo['extension'];
                 } else {
                     $targetName = $file['name'];
                 }
                 // Do not overwrite existing files
                 if ($this->doNotOverwrite && file_exists(TL_ROOT . '/' . $strUploadFolder . '/' . $targetName)) {
                     $offset = 1;
                     $pathinfo = pathinfo($targetName);
                     $name = $pathinfo['filename'];
                     $arrAll = scan(TL_ROOT . '/' . $strUploadFolder);
                     $arrFiles = preg_grep('/^' . preg_quote($name, '/') . '.*\\.' . preg_quote($pathinfo['extension'], '/') . '/', $arrAll);
                     foreach ($arrFiles as $strFile) {
                         if (preg_match('/__[0-9]+\\.' . preg_quote($pathinfo['extension'], '/') . '$/', $strFile)) {
                             $strFile = str_replace('.' . $pathinfo['extension'], '', $strFile);
                             $intValue = intval(substr($strFile, strrpos($strFile, '_') + 1));
                             $offset = max($offset, $intValue);
                         }
                     }
                     $targetName = str_replace($name, $name . '__' . ++$offset, $targetName);
                 }
                 $this->Files->move_uploaded_file($file['tmp_name'], $strUploadFolder . '/' . $targetName);
                 $this->Files->chmod($strUploadFolder . '/' . $targetName, $GLOBALS['TL_CONFIG']['defaultFileChmod']);
                 if ($blnResize) {
                     \Image::resize($strUploadFolder . '/' . $targetName, $arrImageSize[0], $arrImageSize[1], $arrImageSize[2]);
                 }
                 $_SESSION['FILES'][$this->strName] = array('name' => $targetName, 'type' => $file['type'], 'tmp_name' => TL_ROOT . '/' . $strUploadFolder . '/' . $file['name'], 'error' => $file['error'], 'size' => $file['size'], 'uploaded' => true);
                 $strFile = $strUploadFolder . '/' . $targetName;
                 $objModel = \Dbafs::addResource($strFile, true);
                 // new Avatar for Member
                 $objMember = \MemberModel::findByPk($this->User->id);
                 $objMember->avatar = $objModel->uuid;
                 $objMember->save();
                 $this->varValue = $objModel->uuid;
                 $this->log('File "' . $targetName . '" has been moved to "' . $strUploadFolder . '"', __METHOD__, TL_FILES);
             }
         }
     }
     unset($_FILES[$this->strName]);
 }
Ejemplo n.º 11
0
 /**
  * Parse simple tokens that can be used to personalize newsletters
  * 
  * @param string $strBuffer The text with the tokens to be replaced
  * @param array  $arrData   The replacement data as array
  * 
  * @return string The text with the replaced tokens
  * 
  * @deprecated Use String::parseSimpleTokens() instead
  */
 protected function parseSimpleTokens($strBuffer, $arrData)
 {
     return \String::parseSimpleTokens($strBuffer, $arrData);
 }
Ejemplo n.º 12
0
 public function run()
 {
     $arrJobs = array();
     $objTemplate = new \BackendTemplate('be_rename_avatars');
     $objTemplate->isActive = $this->isActive();
     // Confirmation message
     if ($_SESSION['RENAME_AVATARS_CONFIRM'] != '') {
         $objTemplate->message = sprintf('<p class="tl_confirm">%s</p>' . "\n", $_SESSION['RENAME_AVATARS_CONFIRM']);
         $_SESSION['RENAME_AVATARS_CONFIRM'] = '';
     }
     // Add potential error messages
     if (!empty($_SESSION['TL_ERROR']) && is_array($_SESSION['TL_ERROR'])) {
         foreach ($_SESSION['TL_ERROR'] as $message) {
             $objTemplate->message .= sprintf('<p class="tl_error">%s</p>' . "\n", $message);
         }
         $_SESSION['TL_ERROR'] = array();
     }
     // Run the jobs
     if (\Input::post('FORM_SUBMIT') == 'tl_rename_avatars') {
         /**
          * @var \Files $files
          */
         $files = \Files::getInstance();
         /**
          * @var string $uploadDir
          */
         $uploadDir = \FilesModel::findByPk($GLOBALS['TL_CONFIG']['avatar_dir']);
         if ($uploadDir) {
             $uploadDir = $uploadDir->path;
         } else {
             $_SESSION['TL_ERROR'][] = 'Upload dir is invalid!';
             $this->reload();
         }
         /**
          * @var \MemberModel $member
          */
         $member = \MemberModel::findBy(array('avatar!=?'), '');
         $count = 0;
         while ($member->next()) {
             $avatarRecord = \FilesModel::findByUuid($member->avatar);
             if ($avatarRecord) {
                 $avatar = $avatarRecord->path;
             } else {
                 $_SESSION['TL_ERROR'][] = sprintf('Avatar for user ID %d is invalid', $member->id);
                 continue;
             }
             $pathinfo = pathinfo($avatar);
             $newName = standardize(\String::parseSimpleTokens($GLOBALS['TL_CONFIG']['avatar_name'], $member->row()));
             if ($pathinfo['filename'] != $newName) {
                 $newPath = $uploadDir . '/' . $newName . '.' . $pathinfo['extension'];
                 $n = 1;
                 while (file_exists(TL_ROOT . '/' . $newPath)) {
                     $newPath = $uploadDir . '/' . $newName . '__' . $n++ . '.' . $pathinfo['extension'];
                 }
                 $files->rename($avatar, $newPath);
                 $avatarRecord->path = $newPath;
                 $avatarRecord->name = $newName;
                 $avatarRecord->save();
                 $count++;
             }
         }
         $_SESSION['RENAME_AVATARS_CONFIRM'] = sprintf($GLOBALS['TL_LANG']['tl_maintenance']['avatarsRenamed'], $count);
         $this->reload();
     }
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->headline = $GLOBALS['TL_LANG']['tl_maintenance']['renameAvatars'];
     $objTemplate->submit = specialchars($GLOBALS['TL_LANG']['tl_maintenance']['doRenameAvatars']);
     $objTemplate->help = $GLOBALS['TL_LANG']['tl_maintenance']['renameAvatarsHelp'];
     return $objTemplate->parse();
 }
Ejemplo n.º 13
0
 /**
  * Create a new user and redirect
  *
  * @param array $arrData
  */
 protected function createNewUser($arrData)
 {
     $arrData['tstamp'] = time();
     $arrData['login'] = $this->reg_allowLogin;
     $arrData['activation'] = md5(uniqid(mt_rand(), true));
     $arrData['dateAdded'] = $arrData['tstamp'];
     // Set default groups
     if (!array_key_exists('groups', $arrData)) {
         $arrData['groups'] = $this->reg_groups;
     }
     // Disable account
     $arrData['disable'] = 1;
     // Send activation e-mail
     if ($this->reg_activate) {
         // Prepare the simple token data
         $arrTokenData = $arrData;
         $arrTokenData['domain'] = \Idna::decode(\Environment::get('host'));
         $arrTokenData['link'] = \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $arrData['activation'];
         $arrTokenData['channels'] = '';
         if (in_array('newsletter', \ModuleLoader::getActive())) {
             // Make sure newsletter is an array
             if (!is_array($arrData['newsletter'])) {
                 if ($arrData['newsletter'] != '') {
                     $arrData['newsletter'] = array($arrData['newsletter']);
                 } else {
                     $arrData['newsletter'] = array();
                 }
             }
             // Replace the wildcard
             if (!empty($arrData['newsletter'])) {
                 $objChannels = \NewsletterChannelModel::findByIds($arrData['newsletter']);
                 if ($objChannels !== null) {
                     $arrTokenData['channels'] = implode("\n", $objChannels->fetchEach('title'));
                 }
             }
         }
         // Backwards compatibility
         $arrTokenData['channel'] = $arrTokenData['channels'];
         $objEmail = new \Email();
         $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
         $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['emailSubject'], \Idna::decode(\Environment::get('host')));
         $objEmail->text = \String::parseSimpleTokens($this->reg_text, $arrTokenData);
         $objEmail->sendTo($arrData['email']);
     }
     // Make sure newsletter is an array
     if (isset($arrData['newsletter']) && !is_array($arrData['newsletter'])) {
         $arrData['newsletter'] = array($arrData['newsletter']);
     }
     // Create the user
     $objNewUser = new \MemberModel();
     $objNewUser->setRow($arrData);
     $objNewUser->save();
     // Assign home directory
     if ($this->reg_assignDir) {
         $objHomeDir = \FilesModel::findByUuid($this->reg_homeDir);
         if ($objHomeDir !== null) {
             $this->import('Files');
             $strUserDir = standardize($arrData['username']) ?: 'user_' . $objNewUser->id;
             // Add the user ID if the directory exists
             while (is_dir(TL_ROOT . '/' . $objHomeDir->path . '/' . $strUserDir)) {
                 $strUserDir .= '_' . $objNewUser->id;
             }
             // Create the user folder
             new \Folder($objHomeDir->path . '/' . $strUserDir);
             $objUserDir = \FilesModel::findByPath($objHomeDir->path . '/' . $strUserDir);
             // Save the folder ID
             $objNewUser->assignDir = 1;
             $objNewUser->homeDir = $objUserDir->uuid;
             $objNewUser->save();
         }
     }
     // HOOK: send insert ID and user data
     if (isset($GLOBALS['TL_HOOKS']['createNewUser']) && is_array($GLOBALS['TL_HOOKS']['createNewUser'])) {
         foreach ($GLOBALS['TL_HOOKS']['createNewUser'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($objNewUser->id, $arrData, $this);
         }
     }
     // Create the initial version (see #7816)
     $objVersions = new \Versions('tl_member', $objNewUser->id);
     $objVersions->setUsername($objNewUser->username);
     $objVersions->setUserId(0);
     $objVersions->setEditUrl('contao/main.php?do=member&act=edit&id=%s&rt=1');
     $objVersions->initialize();
     // Inform admin if no activation link is sent
     if (!$this->reg_activate) {
         $this->sendAdminNotification($objNewUser->id, $arrData);
     }
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Ejemplo n.º 14
0
 /**
  * @param $objComment
  */
 public function notifyUser($objComment)
 {
     global $objPage;
     $objRatedMember = \MemberModel::findByPk($objComment->parent);
     if ($objRatedMember === null) {
         return;
     }
     if ($objRatedMember->email == '') {
         return;
     }
     $objAuthor = \MemberModel::findByPk($objComment->owner);
     if ($objAuthor === null) {
         return;
     }
     // Generate the data array for simple token use
     $arrData = array();
     foreach ($objAuthor->row() as $k => $v) {
         $arrData['author_' . $k] = $v;
     }
     foreach ($objRatedMember->row() as $k => $v) {
         $arrData['recipient_' . $k] = $v;
     }
     foreach ($objComment->row() as $k => $v) {
         $arrData['comments_' . $k] = $v;
     }
     $objTemplate = new \FrontendTemplate('member_rating_email_notification');
     $objTemplate->comment = nl2br($objComment->comment);
     $objTemplate->score = $objComment->score;
     $objTemplate->link = \Environment::get('url') . '/' . \Controller::generateFrontendUrl($objPage->row(), '', $objPage->language) . '?publish=true&activation_token=' . $objComment->activation_token;
     $objTemplate->link_del = \Environment::get('url') . '/' . \Controller::generateFrontendUrl($objPage->row(), '', $objPage->language) . '?del=true&activation_token=' . $objComment->activation_token;
     $strContent = $objTemplate->parse();
     // Mail
     $objEmail = new \Email();
     $strSubject = sprintf($GLOBALS['TL_LANG']['MOD']['member_rating']['emailNotify']['subject'], $_SERVER['SERVER_NAME']);
     $objEmail->subject = \String::parseSimpleTokens($strSubject, $arrData);
     $strContent = $this->replaceInsertTags($strContent);
     $strContent = \String::parseSimpleTokens($strContent, $arrData);
     $objEmail->html = $strContent;
     // Text version
     $strContent = \String::decodeEntities($strContent);
     $strContent = strip_tags($strContent);
     $strContent = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strContent);
     $objEmail->text = $strContent;
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->sendTo($objRatedMember->email);
 }
Ejemplo n.º 15
0
 /**
  * Add a new recipient
  */
 protected function addRecipient()
 {
     $arrChannels = \Input::post('channels');
     if (!is_array($arrChannels)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         $this->reload();
     }
     $arrChannels = array_intersect($arrChannels, $this->nl_channels);
     // see #3240
     // Check the selection
     if (!is_array($arrChannels) || empty($arrChannels)) {
         $_SESSION['SUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         $this->reload();
     }
     $varInput = \Idna::encodeEmail(\Input::post('email', true));
     // Validate the e-mail address
     if (!\Validator::isEmail($varInput)) {
         $_SESSION['SUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['email'];
         $this->reload();
     }
     $arrSubscriptions = array();
     // Get the existing active subscriptions
     if (($objSubscription = \NewsletterRecipientsModel::findBy(array("email=? AND active=1"), $varInput)) !== null) {
         $arrSubscriptions = $objSubscription->fetchEach('pid');
     }
     $arrNew = array_diff($arrChannels, $arrSubscriptions);
     // Return if there are no new subscriptions
     if (!is_array($arrNew) || empty($arrNew)) {
         $_SESSION['SUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['subscribed'];
         $this->reload();
     }
     // Remove old subscriptions that have not been activated yet
     if (($objOld = \NewsletterRecipientsModel::findBy(array("email=? AND active=''"), $varInput)) !== null) {
         while ($objOld->next()) {
             $objOld->delete();
         }
     }
     $time = time();
     $strToken = md5(uniqid(mt_rand(), true));
     // Add the new subscriptions
     foreach ($arrNew as $id) {
         $objRecipient = new \NewsletterRecipientsModel();
         $objRecipient->pid = $id;
         $objRecipient->tstamp = $time;
         $objRecipient->email = $varInput;
         $objRecipient->active = '';
         $objRecipient->addedOn = $time;
         $objRecipient->ip = $this->anonymizeIp(\Environment::get('ip'));
         $objRecipient->token = $strToken;
         $objRecipient->confirmed = '';
         $objRecipient->save();
     }
     // Get the channels
     $objChannel = \NewsletterChannelModel::findByIds($arrChannels);
     // Prepare the simple token data
     $arrData = array();
     $arrData['token'] = $strToken;
     $arrData['domain'] = \Idna::decode(\Environment::get('host'));
     $arrData['link'] = \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $strToken;
     $arrData['channel'] = $arrData['channels'] = implode("\n", $objChannel->fetchEach('title'));
     // Activation e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['nl_subject'], \Idna::decode(\Environment::get('host')));
     $objEmail->text = \String::parseSimpleTokens($this->nl_subscribe, $arrData);
     $objEmail->sendTo($varInput);
     // Redirect to the jumpTo page
     if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->redirect($this->generateFrontendUrl($objTarget->row()));
     }
     $_SESSION['SUBSCRIBE_CONFIRM'] = $GLOBALS['TL_LANG']['MSC']['nl_confirm'];
     $this->reload();
 }
Ejemplo n.º 16
0
 /**
  * Create a new user and redirect
  *
  * @param \MemberModel $objMember
  */
 protected function sendPasswordLink($objMember)
 {
     $confirmationId = md5(uniqid(mt_rand(), true));
     // Store the confirmation ID
     $objMember = \MemberModel::findByPk($objMember->id);
     $objMember->activation = $confirmationId;
     $objMember->save();
     // Prepare the simple token data
     $arrData = $objMember->row();
     $arrData['domain'] = \Idna::decode(\Environment::get('host'));
     $arrData['link'] = \Idna::decode(\Environment::get('base')) . \Environment::get('request') . (\Config::get('disableAlias') || strpos(\Environment::get('request'), '?') !== false ? '&' : '?') . 'token=' . $confirmationId;
     // Send e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['passwordSubject'], \Idna::decode(\Environment::get('host')));
     $objEmail->text = \String::parseSimpleTokens($this->reg_password, $arrData);
     $objEmail->sendTo($objMember->email);
     $this->log('A new password has been requested for user ID ' . $objMember->id . ' (' . $objMember->email . ')', __METHOD__, TL_ACCESS);
     // Check whether there is a jumpTo page
     if (($objJumpTo = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->jumpToOrReload($objJumpTo->row());
     }
     $this->reload();
 }
Ejemplo n.º 17
0
 /**
  * Compile the newsletter and send it
  * @param \Email
  * @param \Database_Result
  * @param array
  * @param string
  * @param string
  * @param string
  * @return string
  */
 protected function sendNewsletter(\Email $objEmail, \Database_Result $objNewsletter, $arrRecipient, $text, $html, $css = null)
 {
     // Prepare the text content
     $objEmail->text = \String::parseSimpleTokens($text, $arrRecipient);
     // Add the HTML content
     if (!$objNewsletter->sendText) {
         // Default template
         if ($objNewsletter->template == '') {
             $objNewsletter->template = 'mail_default';
         }
         // Load the mail template
         $objTemplate = new \BackendTemplate($objNewsletter->template);
         $objTemplate->setData($objNewsletter->row());
         $objTemplate->title = $objNewsletter->subject;
         $objTemplate->body = \String::parseSimpleTokens($html, $arrRecipient);
         $objTemplate->charset = $GLOBALS['TL_CONFIG']['characterSet'];
         $objTemplate->css = $css;
         // Backwards compatibility
         // Parse template
         $objEmail->html = $objTemplate->parse();
         $objEmail->imageDir = TL_ROOT . '/';
     }
     // Deactivate invalid addresses
     try {
         $objEmail->sendTo($arrRecipient['email']);
     } catch (Swift_RfcComplianceException $e) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // Rejected recipients
     if ($objEmail->hasFailures()) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
 }
 /**
  * Compile the newsletter and send it
  * @param \Email
  * @param \Database\Result
  * @param array
  * @param string
  * @param string
  * @param string
  * @return string
  */
 protected function sendNewsletter(\Email $objEmail, \Database\Result $objNewsletter, $arrRecipient, $text, $body, $css = null)
 {
     // Prepare the text content
     $text = \String::parseSimpleTokens($text, $arrRecipient);
     // add piwik campaign links
     $text = $this->addPiwikCampaignText($text, $objNewsletter->hoja_piwik_campaign);
     $objEmail->text = $text;
     // Add the HTML content
     if (!$objNewsletter->sendText) {
         // Default template
         if ($objNewsletter->template == '') {
             $objNewsletter->template = 'mail_default';
         }
         // Load the mail template
         $objTemplate = new \BackendTemplate($objNewsletter->template);
         $objTemplate->setData($objNewsletter->row());
         $objTemplate->title = $objNewsletter->subject;
         $objTemplate->body = $body;
         $objTemplate->charset = \Config::get('characterSet');
         $objTemplate->css = $css;
         // Backwards compatibility
         $this->addCssToTemplate($objTemplate);
         $objTemplate->recipient = $arrRecipient['email'];
         // Parse template
         $html = $objTemplate->parse();
         $html = $this->convertRelativeUrls($html);
         $html = $this->replaceInsertTags($html);
         // $html = $this->prepareLinkTracking($html, $objNewsletter->id, $arrRecipient['email'], $arrRecipient['extra'] ?: '');
         $html = $this->parseSimpleTokens($html, $arrRecipient);
         // add piwik campaign links
         $html = $this->addPiwikCampaignHtml($html, $objNewsletter->hoja_piwik_campaign);
         // Append to mail object
         $objEmail->html = $html;
         $objEmail->imageDir = TL_ROOT . '/';
     }
     // Deactivate invalid addresses
     try {
         $objEmail->sendTo($arrRecipient['email']);
     } catch (\Swift_RfcComplianceException $e) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // Rejected recipients
     if ($objEmail->hasFailures()) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['sendNewsletter']) && is_array($GLOBALS['TL_HOOKS']['sendNewsletter'])) {
         foreach ($GLOBALS['TL_HOOKS']['sendNewsletter'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($objEmail, $objNewsletter, $arrRecipient, $text, $html);
         }
     }
 }
Ejemplo n.º 19
0
 /**
  * @param $strText
  * @return string
  * @deprecated
  */
 protected function replaceParameters($strText)
 {
     if (is_array($this->arrParameters)) {
         foreach ($this->arrParameters as $key => $varValue) {
             $strText = str_replace('{{' . $key . '}}', $varValue, $strText);
         }
     }
     $strText = \String::parseSimpleTokens($strText, $this->arrParameters);
     $strText = \String::restoreBasicEntities($strText);
     return (string) $strText;
 }
Ejemplo n.º 20
0
 /**
  * replace Inserttag
  *
  * @param
  *        	string
  *        	
  * @return string
  */
 public function replaceTags($strTag)
 {
     list($strTag, $strParams) = trimsplit('?', $strTag);
     $arrTag = trimsplit('::', $strTag);
     if ($arrTag[0] != 'avatar') {
         return false;
     }
     // get default settings
     $arrDims = deserialize($GLOBALS['TL_CONFIG']['avatar_maxdims']);
     $strAlt = $GLOBALS['TL_CONFIG']['avatar_default_alt'];
     $strTitle = $GLOBALS['TL_CONFIG']['avatar_default_title'];
     $strClass = $GLOBALS['TL_CONFIG']['avatar_default_class'];
     // parse query parameters
     $strParams = \String::decodeEntities($strParams);
     $strParams = str_replace('[&]', '&', $strParams);
     $arrParams = explode('&', $strParams);
     foreach ($arrParams as $strParam) {
         list($key, $value) = explode('=', $strParam);
         switch ($key) {
             case 'width':
                 $arrDims[0] = $value;
                 break;
             case 'height':
                 $arrDims[1] = $value;
                 break;
             case 'alt':
                 $strAlt = specialchars($value);
                 break;
             case 'title':
                 $strTitle = specialchars($value);
                 break;
             case 'class':
                 $strClass = $value;
                 break;
             case 'mode':
                 $arrDims[2] = $value;
                 break;
         }
     }
     // if no id given, use the current logged in member
     if (!$arrTag[1]) {
         // if no member is logged in, return anonymous avatar
         if (!FE_USER_LOGGED_IN) {
             return $this->generateAnonymousAvatar($arrDims);
         }
         $arrTag[1] = \FrontendUser::getInstance()->id;
     }
     // search the member record
     $objMember = \MemberModel::findByPk($arrTag[1]);
     // return anonymous avatar, if member not found
     if (!$objMember) {
         return $this->generateAnonymousAvatar($arrDims);
     }
     // get the avatar
     $strAvatar = $objMember->avatar;
     // parse the alt and title text
     $strAlt = \String::parseSimpleTokens($strAlt, $objMember->row());
     $strTitle = \String::parseSimpleTokens($strTitle, $objMember->row());
     // avatar available and file exists
     if ($strAvatar && ($objFile = \FilesModel::findByUuid($strAvatar)) && file_exists(TL_ROOT . '/' . $objFile->path)) {
         $strAvatar = $objFile->path;
     } else {
         if ($GLOBALS['TL_CONFIG']['avatar_fallback_image'] && ($objFile = \FilesModel::findByUuid($GLOBALS['TL_CONFIG']['avatar_fallback_image'])) && file_exists(TL_ROOT . '/' . $objFile->path)) {
             $strAvatar = $objFile->path;
         } else {
             if ($strAvatar == '' && \FrontendUser::getInstance()->gender != '') {
                 $strAvatar = "system/modules/avatar/assets/" . \FrontendUser::getInstance()->gender . ".png";
             } else {
                 $strAvatar = 'system/modules/avatar/assets/male.png';
             }
         }
     }
     // resize if size is requested
     $this->resize($strAvatar, $arrDims);
     // generate the img tag
     return sprintf('<img src="%s" width="%s" height="%s" alt="%s" title="%s" class="%s">', TL_FILES_URL . $strAvatar, $arrDims[0], $arrDims[1], $strAlt, $strTitle, $strClass);
 }
 /**
  * Send the e-mail reminders
  */
 public function sendEmailReminders()
 {
     $now = mktime(date('H'), 0, 0, 1, 1, 1970);
     $objCalendars = $this->Database->execute("SELECT * FROM tl_calendar WHERE subscription_reminders=1 AND ((subscription_time >= {$now}) AND (subscription_time <= {$now} + 3600))");
     // Return if there are no calendars with subscriptions
     if (!$objCalendars->numRows) {
         return;
     }
     $intReminders = 0;
     $objToday = new \Date();
     // Send the e-mails
     while ($objCalendars->next()) {
         $arrDays = array_map('intval', trimsplit(',', $objCalendars->subscription_days));
         if (empty($arrDays)) {
             continue;
         }
         $arrWhere = array();
         // Bulid a WHERE statement
         foreach ($arrDays as $intDay) {
             $objDateEvent = new \Date(strtotime('+' . $intDay . ' days'));
             $arrWhere[] = "((e.startTime BETWEEN " . $objDateEvent->dayBegin . " AND " . $objDateEvent->dayEnd . ") AND ((es.lastEmail = 0) OR (es.lastEmail NOT BETWEEN " . $objToday->dayBegin . " AND " . $objToday->dayEnd . ")))";
         }
         $objSubscriptions = $this->Database->prepare("SELECT e.*, es.member FROM tl_calendar_events_subscriptions es JOIN tl_calendar_events e ON e.id=es.pid WHERE e.pid=?" . (!empty($arrWhere) ? " AND (" . implode(" OR ", $arrWhere) . ")" : ""))->execute($objCalendars->id);
         // Continue if there are no subscriptions to send
         if (!$objSubscriptions->numRows) {
             continue;
         }
         $arrWildcards = $this->generateWildcards($objCalendars->row(), 'calendar');
         while ($objSubscriptions->next()) {
             // Get the member if it is not in cache
             if (!isset(self::$arrMembers[$objSubscriptions->member])) {
                 $objMember = $this->Database->prepare("SELECT * FROM tl_member WHERE id=? AND email!=''")->limit(1)->execute($objSubscriptions->member);
                 // Continue if member was not found
                 if (!$objMember->numRows) {
                     continue;
                 }
                 self::$arrMembers[$objSubscriptions->member] = $objMember->row();
             }
             $arrWildcards = array_merge($arrWildcards, $this->generateWildcards($objSubscriptions->row(), 'event'), $this->generateWildcards(self::$arrMembers[$objSubscriptions->member], 'member'));
             // Generate an e-mail
             $objEmail = new \Email();
             $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
             $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
             $objEmail->subject = \String::parseSimpleTokens($objCalendars->subscription_subject, $arrWildcards);
             $objEmail->text = \String::parseSimpleTokens($objCalendars->subscription_message, $arrWildcards);
             // Send an e-mail
             if ($objEmail->sendTo(self::$arrMembers[$objSubscriptions->member]['email'])) {
                 $intReminders++;
                 $this->Database->prepare("UPDATE tl_calendar_events_subscriptions SET lastEmail=? WHERE pid=? AND member=?")->execute(time(), $objSubscriptions->id, $objSubscriptions->member);
             }
         }
     }
     self::log('A total number of ' . $intReminders . ' event reminders have been sent', 'EventsSubscriptions sendEmailReminders()', TL_INFO);
 }
Ejemplo n.º 22
0
 /**
  * Generate and return document template
  * @return  string
  */
 protected function generateTemplate(IsotopeProductCollection $objCollection, array $arrTokens)
 {
     $objTemplate = new \Isotope\Template($this->documentTpl);
     $objTemplate->setData($this->arrData);
     $objTemplate->title = \String::parseSimpleTokens($this->documentTitle, $arrTokens);
     $objTemplate->collection = $objCollection;
     // Render the collection
     $objCollectionTemplate = new \Isotope\Template($this->collectionTpl);
     $objCollection->addToTemplate($objCollectionTemplate, array('gallery' => $this->gallery, 'sorting' => $objCollection->getItemsSortingCallable($this->orderCollectionBy)));
     $objTemplate->products = $objCollectionTemplate->parse();
     // Generate template and fix PDF issues, see Contao's ModuleArticle
     $strBuffer = Haste::getInstance()->call('replaceInsertTags', array($objTemplate->parse(), false));
     $strBuffer = html_entity_decode($strBuffer, ENT_QUOTES, $GLOBALS['TL_CONFIG']['characterSet']);
     $strBuffer = \Controller::convertRelativeUrls($strBuffer, '', true);
     // Remove form elements and JavaScript links
     $arrSearch = array('@<form.*</form>@Us', '@<a [^>]*href="[^"]*javascript:[^>]+>.*</a>@Us');
     $strBuffer = preg_replace($arrSearch, '', $strBuffer);
     // URL decode image paths (see contao/core#6411)
     // Make image paths absolute
     $strBuffer = preg_replace_callback('@(src=")([^"]+)(")@', function ($args) {
         if (preg_match('@^(http://|https://)@', $args[2])) {
             return $args[2];
         }
         return $args[1] . TL_ROOT . '/' . rawurldecode($args[2]) . $args[3];
     }, $strBuffer);
     // Handle line breaks in preformatted text
     $strBuffer = preg_replace_callback('@(<pre.*</pre>)@Us', 'nl2br_callback', $strBuffer);
     // Default PDF export using TCPDF
     $arrSearch = array('@<span style="text-decoration: ?underline;?">(.*)</span>@Us', '@(<img[^>]+>)@', '@(<div[^>]+block[^>]+>)@', '@[\\n\\r\\t]+@', '@<br( /)?><div class="mod_article@', '@href="([^"]+)(pdf=[0-9]*(&|&amp;)?)([^"]*)"@');
     $arrReplace = array('<u>$1</u>', '<br>$1', '<br>$1', ' ', '<div class="mod_article', 'href="$1$4"');
     $strBuffer = preg_replace($arrSearch, $arrReplace, $strBuffer);
     return $strBuffer;
 }
Ejemplo n.º 23
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     global $objPage;
     $this->Template->content = '';
     $this->Template->referer = 'javascript:history.go(-1)';
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     $objNewsletter = \NewsletterModel::findSentByParentAndIdOrAlias(\Input::get('items'), $this->nl_channels);
     if ($objNewsletter === null) {
         // Do not index or cache the page
         $objPage->noSearch = 1;
         $objPage->cache = 0;
         // Send a 404 header
         header('HTTP/1.1 404 Not Found');
         $this->Template->content = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], \Input::get('items')) . '</p>';
         return;
     }
     // Overwrite the page title (see #2853 and #4955)
     if ($objNewsletter->subject != '') {
         $objPage->pageTitle = strip_tags(strip_insert_tags($objNewsletter->subject));
     }
     // Add enclosure
     if ($objNewsletter->addFile) {
         $this->addEnclosuresToTemplate($this->Template, $objNewsletter->row(), 'files');
     }
     // Support plain text newsletters (thanks to Hagen Klemp)
     if ($objNewsletter->sendText) {
         $nl2br = $objPage->outputFormat == 'xhtml' ? 'nl2br_xhtml' : 'nl2br_html5';
         $strContent = $nl2br($objNewsletter->text);
     } else {
         $strContent = str_ireplace(' align="center"', '', $objNewsletter->content);
     }
     // Parse simple tokens and insert tags
     $strContent = $this->replaceInsertTags($strContent);
     $strContent = \String::parseSimpleTokens($strContent, array());
     // Encode e-mail addresses
     $strContent = \String::encodeEmail($strContent);
     $this->Template->content = $strContent;
     $this->Template->subject = $objNewsletter->subject;
 }
 protected function replaceInserts($objEvent, $text = '', $intQuantity = false)
 {
     global $objPage;
     $this->import('String');
     $strUrl = $this->generateFrontendUrl(array('id' => $objPage->id, 'alias' => $objPage->alias), '/events/%s');
     $objEvent->url = $this->generateEventUrl($objEvent, $strUrl);
     $arrUser = $this->User->getData();
     $arrEvent = $objEvent->row();
     $arrData = array();
     foreach ($arrUser as $k => $v) {
         $key = 'user_' . $k;
         $arrData[$key] = $v;
     }
     foreach ($arrEvent as $k => $v) {
         $key = 'event_' . $k;
         $arrData[$key] = $this->String->decodeEntities($v);
     }
     if ($intQuantity) {
         $arrData['ser_quantity'] = $intQuantity;
     }
     $text = \String::parseSimpleTokens($text, $arrData);
     $text = $this->replaceInsertTags($text);
     return $text;
 }
Ejemplo n.º 25
0
 protected function createConfirmationAvisotaEmail($intMessageId, $strSalutationGroupId, $arrSubmissionData)
 {
     $objMessage = AvisotaHelper::getAvisotaMessage($intMessageId);
     $objMessage->setSubject(\String::parseSimpleTokens($this->replaceInsertTags(FormHelper::replaceFormDataTags($objMessage->getSubject(), $arrSubmissionData), false), $arrSubmissionData));
     foreach ($objMessage->getContents() as $objContent) {
         $strText = $objContent->getText();
         if (!$strText) {
             continue;
         }
         $objContent->setText(\String::parseSimpleTokens($this->replaceInsertTags(FormHelper::replaceFormDataTags($strText, $arrSubmissionData), false), $arrSubmissionData));
     }
     AvisotaHelper::sendAvisotaEMailByMessage($objMessage, $arrSubmissionData[$this->confirmationMailRecipientField]['value'], array_map(function ($arrValue) {
         if (isset($arrValue['value'])) {
             return $arrValue['value'];
         } else {
             return $arrValue;
         }
     }, $arrSubmissionData), $strSalutationGroupId, AvisotaHelper::RECIPIENT_MODE_USE_SUBMISSION_DATA);
 }
Ejemplo n.º 26
0
 /**
  * Compile the newsletter and send it
  *
  * @param \Email                  $objEmail
  * @param \Database\Result|object $objNewsletter
  * @param array                   $arrRecipient
  * @param string                  $text
  * @param string                  $html
  * @param string                  $css
  *
  * @return string
  */
 protected function sendNewsletter(\Email $objEmail, \Database\Result $objNewsletter, $arrRecipient, $text, $html, $css = null)
 {
     // Prepare the text content
     $objEmail->text = \String::parseSimpleTokens($text, $arrRecipient);
     if (!$objNewsletter->sendText) {
         // Default template
         if ($objNewsletter->template == '') {
             $objNewsletter->template = 'mail_default';
         }
         /** @var \BackendTemplate|object $objTemplate */
         $objTemplate = new \BackendTemplate($objNewsletter->template);
         $objTemplate->setData($objNewsletter->row());
         $objTemplate->title = $objNewsletter->subject;
         $objTemplate->body = \String::parseSimpleTokens($html, $arrRecipient);
         $objTemplate->charset = \Config::get('characterSet');
         $objTemplate->css = $css;
         // Backwards compatibility
         $objTemplate->recipient = $arrRecipient['email'];
         // Parse template
         $objEmail->html = $objTemplate->parse();
         $objEmail->imageDir = TL_ROOT . '/';
     }
     // Deactivate invalid addresses
     try {
         $objEmail->sendTo($arrRecipient['email']);
     } catch (\Swift_RfcComplianceException $e) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // Rejected recipients
     if ($objEmail->hasFailures()) {
         $_SESSION['REJECTED_RECIPIENTS'][] = $arrRecipient['email'];
     }
     // HOOK: add custom logic
     if (isset($GLOBALS['TL_HOOKS']['sendNewsletter']) && is_array($GLOBALS['TL_HOOKS']['sendNewsletter'])) {
         foreach ($GLOBALS['TL_HOOKS']['sendNewsletter'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($objEmail, $objNewsletter, $arrRecipient, $text, $html);
         }
     }
 }
Ejemplo n.º 27
0
 /**
  * Generate the module
  */
 protected function compile()
 {
     /** @var \PageModel $objPage */
     global $objPage;
     $this->Template->content = '';
     $this->Template->referer = 'javascript:history.go(-1)';
     $this->Template->back = $GLOBALS['TL_LANG']['MSC']['goBack'];
     $objNewsletter = \NewsletterModel::findSentByParentAndIdOrAlias(\Input::get('items'), $this->nl_channels);
     if (null === $objNewsletter) {
         /** @var \PageError404 $objHandler */
         $objHandler = new $GLOBALS['TL_PTY']['error_404']();
         $objHandler->generate($objPage->id);
     }
     // Overwrite the page title (see #2853 and #4955)
     if ($objNewsletter->subject != '') {
         $objPage->pageTitle = strip_tags(strip_insert_tags($objNewsletter->subject));
     }
     // Add enclosure
     if ($objNewsletter->addFile) {
         $this->addEnclosuresToTemplate($this->Template, $objNewsletter->row(), 'files');
     }
     // Support plain text newsletters (thanks to Hagen Klemp)
     if ($objNewsletter->sendText) {
         $nl2br = $objPage->outputFormat == 'xhtml' ? 'nl2br_xhtml' : 'nl2br_html5';
         $strContent = $nl2br($objNewsletter->text);
     } else {
         $strContent = str_ireplace(' align="center"', '', $objNewsletter->content);
     }
     // Parse simple tokens and insert tags
     $strContent = $this->replaceInsertTags($strContent);
     $strContent = \String::parseSimpleTokens($strContent, array());
     // Encode e-mail addresses
     $strContent = \String::encodeEmail($strContent);
     $this->Template->content = $strContent;
     $this->Template->subject = $objNewsletter->subject;
 }
Ejemplo n.º 28
0
 /**
  * Remove the recipient
  */
 protected function removeRecipient()
 {
     $arrChannels = \Input::post('channels');
     if (!is_array($arrChannels)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         $this->reload();
     }
     $arrChannels = array_intersect($arrChannels, $this->nl_channels);
     // see #3240
     // Check the selection
     if (!is_array($arrChannels) || empty($arrChannels)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['noChannels'];
         $this->reload();
     }
     $varInput = \Idna::encodeEmail(\Input::post('email', true));
     // Validate e-mail address
     if (!\Validator::isEmail($varInput)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['email'];
         $this->reload();
     }
     $arrSubscriptions = array();
     // Get the existing active subscriptions
     if (($objSubscription = \NewsletterRecipientsModel::findBy(array("email=? AND active=1"), $varInput)) !== null) {
         $arrSubscriptions = $objSubscription->fetchEach('pid');
     }
     $arrRemove = array_intersect($arrChannels, $arrSubscriptions);
     // Return if there are no subscriptions to remove
     if (!is_array($arrRemove) || empty($arrRemove)) {
         $_SESSION['UNSUBSCRIBE_ERROR'] = $GLOBALS['TL_LANG']['ERR']['unsubscribed'];
         $this->reload();
     }
     // Remove the subscriptions
     if (($objRemove = \NewsletterRecipientsModel::findByEmailAndPids($varInput, $arrRemove)) !== null) {
         while ($objRemove->next()) {
             $objRemove->delete();
         }
     }
     // Get the channels
     $objChannels = \NewsletterChannelModel::findByIds($arrRemove);
     $arrChannels = $objChannels->fetchEach('title');
     // Log activity
     $this->log($varInput . ' unsubscribed from ' . implode(', ', $arrChannels), __METHOD__, TL_NEWSLETTER);
     // HOOK: post unsubscribe callback
     if (isset($GLOBALS['TL_HOOKS']['removeRecipient']) && is_array($GLOBALS['TL_HOOKS']['removeRecipient'])) {
         foreach ($GLOBALS['TL_HOOKS']['removeRecipient'] as $callback) {
             $this->import($callback[0]);
             $this->{$callback}[0]->{$callback}[1]($varInput, $arrRemove);
         }
     }
     // Prepare the simple token data
     $arrData = array();
     $arrData['domain'] = \Idna::decode(\Environment::get('host'));
     $arrData['channel'] = $arrData['channels'] = implode("\n", $arrChannels);
     // Confirmation e-mail
     $objEmail = new \Email();
     $objEmail->from = $GLOBALS['TL_ADMIN_EMAIL'];
     $objEmail->fromName = $GLOBALS['TL_ADMIN_NAME'];
     $objEmail->subject = sprintf($GLOBALS['TL_LANG']['MSC']['nl_subject'], \Idna::decode(\Environment::get('host')));
     $objEmail->text = \String::parseSimpleTokens($this->nl_unsubscribe, $arrData);
     $objEmail->sendTo($varInput);
     // Redirect to the jumpTo page
     if ($this->jumpTo && ($objTarget = $this->objModel->getRelated('jumpTo')) !== null) {
         $this->redirect($this->generateFrontendUrl($objTarget->row()));
     }
     $_SESSION['UNSUBSCRIBE_CONFIRM'] = $GLOBALS['TL_LANG']['MSC']['nl_removed'];
     $this->reload();
 }
Ejemplo n.º 29
0
 /**
  * Gets an array of valid attachments of a token field
  * @param   string
  * @param   array Tokens
  * @return  array
  */
 public static function getTokenAttachments($strAttachmentTokens, array $arrTokens)
 {
     $arrAttachments = array();
     if ($strAttachmentTokens == '') {
         return $arrAttachments;
     }
     foreach (trimsplit(',', $strAttachmentTokens) as $strToken) {
         $strFile = TL_ROOT . '/' . \String::parseSimpleTokens($strToken, $arrTokens);
         if (is_file($strFile)) {
             $arrAttachments[$strToken] = $strFile;
         }
     }
     return $arrAttachments;
 }