public function testAttachFiles()
 {
     $email = new Email();
     $email->attachFileFromString('foo bar', 'foo.txt', 'text/plain');
     $email->attachFile(__DIR__ . '/fixtures/attachment.txt', null, 'text/plain');
     $this->assertEquals(array('contents' => 'foo bar', 'filename' => 'foo.txt', 'mimetype' => 'text/plain'), $email->attachments[0], 'File is attached correctly from string');
     $this->assertEquals(array('contents' => 'Hello, I\'m a text document.', 'filename' => 'attachment.txt', 'mimetype' => 'text/plain'), $email->attachments[1], 'File is attached correctly from file');
 }
Beispiel #2
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();
 }
Beispiel #3
0
 public function postmessage($data, $form)
 {
     $signature = PostmarkSignature::get()->byID($data['FromID']);
     PostmarkMailer::RecordEmails(true);
     PostmarkMailer::ReplyToMessageID($data['InReplyToID']);
     $clients = PostmarkHelper::client_list()->filter('ID', $data['ToMemberID']);
     foreach ($clients as $client) {
         $email = new Email($signature->Email, $client->Email, $data['Subject'], PostmarkHelper::MergeEmailText($data['Body'], $client));
         for ($i = 1; $i <= 5; $i += 1) {
             $strKey = 'Attachment_' . $i;
             if (isset($_FILES[$strKey]) && $_FILES[$strKey]['tmp_name']) {
                 $contents = file_get_contents($_FILES[$strKey]['tmp_name']);
                 if (strlen($contents)) {
                     $email->attachFileFromString($contents, $_FILES[$strKey]['name']);
                 }
             }
         }
         $this->extend('updatePostmessage', $email, $data);
         $email->setTemplate('NewsletterTemplate');
         $email->send();
     }
     PostmarkMailer::RecordEmails(false);
     PostmarkMailer::ReplyToMessageID(0);
 }
Beispiel #4
0
 /**
  * Process submitted form data
  * Send mail, store data in backend
  * @param array $arrSubmitted Submitted data
  * @param array|bool $arrForm Form configuration
  * @param array|bool $arrFiles Files uploaded
  * @param array|bool $arrLabels Form field labels
  * @return void
  */
 public function processSubmittedData($arrSubmitted, $arrForm = false, $arrFiles = false, $arrLabels = false)
 {
     // Form config
     if (!$arrForm) {
         return;
     }
     $arrFormFields = array();
     $this->import('FrontendUser', 'Member');
     $this->import('Formdata');
     $this->strFdDcaKey = 'fd_' . (!empty($arrForm['alias']) ? $arrForm['alias'] : str_replace('-', '_', standardize($arrForm['title'])));
     $this->Formdata->FdDcaKey = $this->strFdDcaKey;
     // Get params of related listing formdata
     $intListingId = intval($_SESSION['EFP']['LISTING_MOD']['id']);
     if ($intListingId > 0) {
         $objListing = \Database::getInstance()->prepare("SELECT * FROM tl_module WHERE id=?")->execute($intListingId);
         if ($objListing->numRows) {
             $arrListing = $objListing->fetchAssoc();
             // Mail delivery defined in frontend listing module
             $arrForm['sendConfirmationMailOnFrontendEditing'] = $arrListing['efg_fe_no_confirmation_mail'] ? false : true;
             $arrForm['sendFormattedMailOnFrontendEditing'] = $arrListing['efg_fe_no_formatted_mail'] ? false : true;
         }
     }
     if (!empty($arrListing['efg_DetailsKey'])) {
         $this->strFormdataDetailsKey = $arrListing['efg_DetailsKey'];
     }
     $blnFEedit = false;
     $intOldId = 0;
     $strRedirectTo = '';
     $strUrl = preg_replace('/\\?.*$/', '', \Environment::get('request'));
     $strUrlParams = '';
     $blnQuery = false;
     foreach (preg_split('/&(amp;)?/', $_SERVER['QUERY_STRING']) as $fragment) {
         if (strlen($fragment)) {
             if (strncasecmp($fragment, $this->strFormdataDetailsKey, strlen($this->strFormdataDetailsKey)) !== 0 && strncasecmp($fragment, 'act', 3) !== 0) {
                 $strUrlParams .= (!$blnQuery ? '' : '&amp;') . $fragment;
                 $blnQuery = true;
             }
         }
     }
     if (in_array($arrListing['efg_fe_edit_access'], array('public', 'groupmembers', 'member'))) {
         if (\Input::get('act') == 'edit') {
             $blnFEedit = true;
             $objCheck = \Database::getInstance()->prepare("SELECT id FROM tl_formdata WHERE id=? OR alias=?")->execute(\Input::get($this->strFormdataDetailsKey), \Input::get($this->strFormdataDetailsKey));
             if ($objCheck->numRows == 1) {
                 $intOldId = intval($objCheck->id);
             } else {
                 $this->log('Could not identify record by ID "' . \Input::get($this->strFormdataDetailsKey) . '"', __METHOD__, TL_GENERAL);
             }
         }
     }
     // Types of form fields with storable data
     $arrFFstorable = $this->Formdata->arrFFstorable;
     if (($arrForm['storeFormdata'] || $arrForm['sendConfirmationMail'] || $arrForm['sendFormattedMail']) && !empty($arrSubmitted)) {
         $timeNow = time();
         $this->loadDataContainer($this->strFdDcaKey);
         $this->loadDataContainer('tl_formdata_details');
         $this->loadDataContainer('tl_files');
         $arrFormFields = $this->Formdata->getFormfieldsAsArray($arrForm['id']);
         $arrBaseFields = array();
         $arrDetailFields = array();
         if (!empty($GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['baseFields'])) {
             $arrBaseFields = $GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['baseFields'];
         }
         if (!empty($GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['detailFields'])) {
             $arrDetailFields = $GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['detailFields'];
         }
         $arrHookFields = array_merge($arrBaseFields, $arrDetailFields);
         $arrToSave = array();
         foreach ($arrSubmitted as $k => $varVal) {
             if (in_array($k, array('id'))) {
                 continue;
             } elseif (in_array($k, $arrHookFields) || in_array($k, array_keys($arrFormFields)) || in_array($k, array('FORM_SUBMIT', 'MAX_FILE_SIZE'))) {
                 $arrToSave[$k] = $varVal;
             }
         }
         // HOOK: process efg form data callback
         if (array_key_exists('processEfgFormData', $GLOBALS['TL_HOOKS']) && is_array($GLOBALS['TL_HOOKS']['processEfgFormData'])) {
             foreach ($GLOBALS['TL_HOOKS']['processEfgFormData'] as $key => $callback) {
                 $this->import($callback[0]);
                 $arrResult = $this->{$callback}[0]->{$callback}[1]($arrToSave, $arrFiles, $intOldId, $arrForm, $arrLabels);
                 if (!empty($arrResult)) {
                     $arrSubmitted = $arrResult;
                     $arrToSave = $arrSubmitted;
                 }
             }
         }
     }
     // Formdata storage
     if ($arrForm['storeFormdata'] && !empty($arrSubmitted)) {
         $blnStoreOptionsValue = $arrForm['efgStoreValues'] ? true : false;
         // Get old record on frontend editing
         if ($intOldId > 0) {
             $arrOldData = $this->Formdata->getFormdataAsArray($intOldId);
             $arrOldFormdata = $arrOldData['fd_base'];
             $arrOldFormdataDetails = $arrOldData['fd_details'];
         }
         // Prepare record tl_formdata
         $arrSet = array('form' => $arrForm['title'], 'tstamp' => $timeNow, 'date' => $timeNow, 'ip' => \System::anonymizeIp(\Environment::get('ip')), 'published' => $GLOBALS['TL_DCA']['tl_formdata']['fields']['published']['default'] ? '1' : '', 'fd_member' => intval($this->Member->id), 'fd_member_group' => intval($this->Member->groups[0]), 'fd_user' => intval($this->User->id), 'fd_user_group' => intval($this->User->groups[0]));
         // Keep some values from existing record on frontend editing
         if ($intOldId > 0) {
             $arrSet['form'] = $arrOldFormdata['form'];
             $arrSet['be_notes'] = $arrOldFormdata['be_notes'];
             $arrSet['fd_member'] = $arrOldFormdata['fd_member'];
             $arrSet['fd_member_group'] = $arrOldFormdata['fd_member_group'];
             if (intval($this->Member->id) > 0) {
                 $arrSet['fd_member'] = intval($this->Member->id);
                 if (count($this->Member->groups) == 1 && intval($this->Member->groups[0]) > 0) {
                     $arrSet['fd_member_group'] = intval($this->Member->groups[0]);
                 }
             } else {
                 $arrSet['fd_member'] = 0;
             }
             $arrSet['fd_user'] = $arrOldFormdata['fd_user'];
             $arrSet['fd_user_group'] = $arrOldFormdata['fd_user_group'];
             // Set published to value of old record, if no default value is defined
             if (!isset($GLOBALS['TL_DCA']['tl_formdata']['fields']['published']['default'])) {
                 $arrSet['published'] = $arrOldFormdata['published'];
             }
         }
         // Store formdata: Update or insert and delete
         if ($blnFEedit && strlen($arrListing['efg_fe_keep_id'])) {
             $intNewId = $intOldId;
             \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrSet)->execute($intOldId);
             \Database::getInstance()->prepare("DELETE FROM tl_formdata_details WHERE pid=?")->execute($intOldId);
         } else {
             $objNewFormdata = \Database::getInstance()->prepare("INSERT INTO tl_formdata %s")->set($arrSet)->execute();
             $intNewId = $objNewFormdata->insertId;
             // Update related comments
             if (in_array('comments', \ModuleLoader::getActive())) {
                 \Database::getInstance()->prepare("UPDATE tl_comments %s WHERE `source` = 'tl_formdata' AND parent=?")->set(array('parent' => $intNewId))->execute($intOldId);
             }
         }
         // Store details data
         foreach ($arrFormFields as $k => $arrField) {
             $strType = $arrField['formfieldType'];
             $strVal = '';
             if (in_array($strType, $arrFFstorable)) {
                 if ($blnStoreOptionsValue) {
                     $arrField['eval']['efgStoreValues'] = true;
                 } else {
                     $arrField['eval']['efgStoreValues'] = false;
                 }
                 // Set rgxp 'date' for field type 'calendar' if not set
                 if ($strType == 'calendar') {
                     if (!isset($arrField['rgxp'])) {
                         $arrField['rgxp'] = 'date';
                     }
                 } elseif ($strType == 'xdependentcalendarfields') {
                     $arrField['rgxp'] = 'date';
                     $arrField['dateFormat'] = $arrField['xdateformat'];
                 }
                 $strVal = $this->Formdata->preparePostValueForDatabase($arrSubmitted[$k], $arrField, $arrFiles[$k]);
                 // Special treatment for type upload
                 // Keep old file on frontend editing, if no new file has been uploaded
                 if ($strType == 'upload') {
                     if ($intOldId) {
                         if (!$arrFiles[$k]['name']) {
                             if (strlen($arrOldFormdataDetails[$k]['value'])) {
                                 $strVal = $arrOldFormdataDetails[$k]['value'];
                             }
                         }
                     }
                 }
                 if (isset($arrSubmitted[$k]) || $strType == 'upload' && strlen($strVal)) {
                     // Prepare data
                     $arrFieldSet = array('pid' => $intNewId, 'sorting' => $arrField['sorting'], 'tstamp' => $timeNow, 'ff_id' => $arrField['id'], 'ff_name' => $arrField['name'], 'value' => $strVal);
                     $objNewFormdataDetails = \Database::getInstance()->prepare("INSERT INTO tl_formdata_details %s")->set($arrFieldSet)->execute();
                 }
             }
         }
         // Delete old record after frontend editing
         if ($blnFEedit) {
             if (!isset($arrListing['efg_fe_keep_id']) || $arrListing['efg_fe_keep_id'] != "1") {
                 if ($intNewId > 0 && intval($intOldId) > 0 && intval($intNewId) != intval($intOldId)) {
                     \Database::getInstance()->prepare("DELETE FROM tl_formdata_details WHERE pid=?")->execute($intOldId);
                     \Database::getInstance()->prepare("DELETE FROM tl_formdata WHERE id=?")->execute($intOldId);
                 }
             }
             $strRedirectTo = preg_replace('/\\?.*$/', '', \Environment::get('request'));
         }
         // Auto-generate alias
         $strAlias = $this->Formdata->generateAlias($arrOldFormdata['alias'], $arrForm['title'], $intNewId);
         if (strlen($strAlias)) {
             $arrUpd = array('alias' => $strAlias);
             \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrUpd)->execute($intNewId);
         }
     }
     // Store data in the session to display on confirmation page
     unset($_SESSION['EFP']['FORMDATA']);
     $blnSkipEmptyFields = $arrForm['confirmationMailSkipEmpty'] ? true : false;
     foreach ($arrFormFields as $k => $arrField) {
         $strType = $arrField['formfieldType'];
         $strVal = '';
         if (in_array($strType, $arrFFstorable)) {
             $strVal = $this->Formdata->preparePostValueForMail($arrSubmitted[$k], $arrField, $arrFiles[$k], $blnSkipEmptyFields);
         }
         $_SESSION['EFP']['FORMDATA'][$k] = $strVal;
     }
     $_SESSION['EFP']['FORMDATA']['_formId_'] = $arrForm['id'];
     // Confirmation Mail
     if ($blnFEedit && !$arrForm['sendConfirmationMailOnFrontendEditing']) {
         $arrForm['sendConfirmationMail'] = false;
     }
     if ($arrForm['sendConfirmationMail']) {
         $objMailProperties = new \stdClass();
         $objMailProperties->subject = '';
         $objMailProperties->sender = '';
         $objMailProperties->senderName = '';
         $objMailProperties->replyTo = '';
         $objMailProperties->recipients = array();
         $objMailProperties->messageText = '';
         $objMailProperties->messageHtmlTmpl = '';
         $objMailProperties->messageHtml = '';
         $objMailProperties->attachments = array();
         $objMailProperties->skipEmptyFields = false;
         $objMailProperties->skipEmptyFields = $arrForm['confirmationMailSkipEmpty'] ? true : false;
         // Set the sender as given in form configuration
         list($senderName, $sender) = \String::splitFriendlyEmail($arrForm['confirmationMailSender']);
         $objMailProperties->sender = $sender;
         $objMailProperties->senderName = $senderName;
         // Set the 'reply to' address, if given in form configuration
         if (!empty($arrForm['confirmationMailReplyto'])) {
             list($replyToName, $replyTo) = \String::splitFriendlyEmail($arrForm['confirmationMailReplyto']);
             $objMailProperties->replyTo = strlen($replyToName) ? $replyToName . ' <' . $replyTo . '>' : $replyTo;
         }
         // Set recipient(s)
         $recipientFieldName = $arrForm['confirmationMailRecipientField'];
         $varRecipient = $arrSubmitted[$recipientFieldName];
         if (is_array($varRecipient)) {
             $arrRecipient = $varRecipient;
         } else {
             $arrRecipient = trimsplit(',', $varRecipient);
         }
         if (!empty($arrForm['confirmationMailRecipient'])) {
             $varRecipient = $arrForm['confirmationMailRecipient'];
             $arrRecipient = array_merge($arrRecipient, trimsplit(',', $varRecipient));
         }
         $arrRecipient = array_filter(array_unique($arrRecipient));
         if (!empty($arrRecipient)) {
             foreach ($arrRecipient as $kR => $recipient) {
                 list($recipientName, $recipient) = \String::splitFriendlyEmail($this->replaceInsertTags($recipient, false));
                 $arrRecipient[$kR] = strlen($recipientName) ? $recipientName . ' <' . $recipient . '>' : $recipient;
             }
         }
         $objMailProperties->recipients = $arrRecipient;
         // Check if we want custom attachments... (Thanks to Torben Schwellnus)
         if ($arrForm['addConfirmationMailAttachments']) {
             if ($arrForm['confirmationMailAttachments']) {
                 $arrCustomAttachments = deserialize($arrForm['confirmationMailAttachments'], true);
                 if (!empty($arrCustomAttachments)) {
                     foreach ($arrCustomAttachments as $varFile) {
                         $objFileModel = \FilesModel::findById($varFile);
                         if ($objFileModel !== null) {
                             $objFile = new \File($objFileModel->path);
                             if ($objFile->size) {
                                 $objMailProperties->attachments[TL_ROOT . '/' . $objFile->path] = array('file' => TL_ROOT . '/' . $objFile->path, 'name' => $objFile->basename, 'mime' => $objFile->mime);
                             }
                         }
                     }
                 }
             }
         }
         $objMailProperties->subject = \String::decodeEntities($arrForm['confirmationMailSubject']);
         $objMailProperties->messageText = \String::decodeEntities($arrForm['confirmationMailText']);
         $objMailProperties->messageHtmlTmpl = $arrForm['confirmationMailTemplate'];
         // Replace Insert tags and conditional tags
         $objMailProperties = $this->Formdata->prepareMailData($objMailProperties, $arrSubmitted, $arrFiles, $arrForm, $arrFormFields);
         // Send Mail
         $blnConfirmationSent = false;
         if (!empty($objMailProperties->recipients)) {
             $objMail = new \Email();
             $objMail->from = $objMailProperties->sender;
             if (!empty($objMailProperties->senderName)) {
                 $objMail->fromName = $objMailProperties->senderName;
             }
             if (!empty($objMailProperties->replyTo)) {
                 $objMail->replyTo($objMailProperties->replyTo);
             }
             $objMail->subject = $objMailProperties->subject;
             if (!empty($objMailProperties->attachments)) {
                 foreach ($objMailProperties->attachments as $strFile => $varParams) {
                     $strContent = file_get_contents($varParams['file'], false);
                     $objMail->attachFileFromString($strContent, $varParams['name'], $varParams['mime']);
                 }
             }
             if (!empty($objMailProperties->messageText)) {
                 $objMail->text = $objMailProperties->messageText;
             }
             if (!empty($objMailProperties->messageHtml)) {
                 $objMail->html = $objMailProperties->messageHtml;
             }
             foreach ($objMailProperties->recipients as $recipient) {
                 $objMail->sendTo($recipient);
                 $blnConfirmationSent = true;
             }
         }
         if ($blnConfirmationSent && isset($intNewId) && intval($intNewId) > 0) {
             $arrUpd = array('confirmationSent' => '1', 'confirmationDate' => $timeNow);
             $res = \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrUpd)->execute($intNewId);
         }
     }
     // Information (formatted) Mail
     if ($blnFEedit && !$arrForm['sendFormattedMailOnFrontendEditing']) {
         $arrForm['sendFormattedMail'] = false;
     }
     if ($arrForm['sendFormattedMail']) {
         $objMailProperties = new \stdClass();
         $objMailProperties->subject = '';
         $objMailProperties->sender = '';
         $objMailProperties->senderName = '';
         $objMailProperties->replyTo = '';
         $objMailProperties->recipients = array();
         $objMailProperties->messageText = '';
         $objMailProperties->messageHtmlTmpl = '';
         $objMailProperties->messageHtml = '';
         $objMailProperties->attachments = array();
         $objMailProperties->skipEmptyFields = false;
         $objMailProperties->skipEmptyFields = $arrForm['formattedMailSkipEmpty'] ? true : false;
         // Set the admin e-mail as "from" address
         $objMailProperties->sender = $GLOBALS['TL_ADMIN_EMAIL'];
         $objMailProperties->senderName = $GLOBALS['TL_ADMIN_NAME'];
         // Get 'reply to' address, if form contains field named 'email'
         if (isset($arrSubmitted['email']) && !empty($arrSubmitted['email']) && !is_bool(strpos($arrSubmitted['email'], '@'))) {
             $replyTo = $arrSubmitted['email'];
             // add name
             if (isset($arrSubmitted['name']) && !empty($arrSubmitted['name'])) {
                 $replyTo = '"' . $arrSubmitted['name'] . '" <' . $arrSubmitted['email'] . '>';
             }
             $objMailProperties->replyTo = $replyTo;
         }
         // Set recipient(s)
         $varRecipient = $arrForm['formattedMailRecipient'];
         if (is_array($varRecipient)) {
             $arrRecipient = $varRecipient;
         } else {
             $arrRecipient = trimsplit(',', $varRecipient);
         }
         $arrRecipient = array_filter(array_unique($arrRecipient));
         if (!empty($arrRecipient)) {
             foreach ($arrRecipient as $kR => $recipient) {
                 list($recipientName, $recipient) = \String::splitFriendlyEmail($this->replaceInsertTags($recipient, false));
                 $arrRecipient[$kR] = strlen($recipientName) ? $recipientName . ' <' . $recipient . '>' : $recipient;
             }
         }
         $objMailProperties->recipients = $arrRecipient;
         // Check if we want custom attachments... (Thanks to Torben Schwellnus)
         if ($arrForm['addFormattedMailAttachments']) {
             if ($arrForm['formattedMailAttachments']) {
                 $arrCustomAttachments = deserialize($arrForm['formattedMailAttachments'], true);
                 if (is_array($arrCustomAttachments)) {
                     foreach ($arrCustomAttachments as $varFile) {
                         $objFileModel = \FilesModel::findById($varFile);
                         if ($objFileModel !== null) {
                             $objFile = new \File($objFileModel->path);
                             if ($objFile->size) {
                                 $objMailProperties->attachments[TL_ROOT . '/' . $objFile->path] = array('file' => TL_ROOT . '/' . $objFile->path, 'name' => $objFile->basename, 'mime' => $objFile->mime);
                             }
                         }
                     }
                 }
             }
         }
         $objMailProperties->subject = \String::decodeEntities($arrForm['formattedMailSubject']);
         $objMailProperties->messageText = \String::decodeEntities($arrForm['formattedMailText']);
         $objMailProperties->messageHtmlTmpl = $arrForm['formattedMailTemplate'];
         // Replace Insert tags and conditional tags
         $objMailProperties = $this->Formdata->prepareMailData($objMailProperties, $arrSubmitted, $arrFiles, $arrForm, $arrFormFields);
         // Send Mail
         $blnInformationSent = false;
         if (!empty($objMailProperties->recipients)) {
             $objMail = new \Email();
             $objMail->from = $objMailProperties->sender;
             if (!empty($objMailProperties->senderName)) {
                 $objMail->fromName = $objMailProperties->senderName;
             }
             if (!empty($objMailProperties->replyTo)) {
                 $objMail->replyTo($objMailProperties->replyTo);
             }
             $objMail->subject = $objMailProperties->subject;
             if (!empty($objMailProperties->attachments)) {
                 foreach ($objMailProperties->attachments as $strFile => $varParams) {
                     $strContent = file_get_contents($varParams['file'], false);
                     $objMail->attachFileFromString($strContent, $varParams['name'], $varParams['mime']);
                 }
             }
             if (!empty($objMailProperties->messageText)) {
                 $objMail->text = $objMailProperties->messageText;
             }
             if (!empty($objMailProperties->messageHtml)) {
                 $objMail->html = $objMailProperties->messageHtml;
             }
             foreach ($objMailProperties->recipients as $recipient) {
                 $objMail->sendTo($recipient);
                 $blnInformationSent = true;
             }
         }
     }
     // Redirect after frontend editing
     if ($blnFEedit) {
         if (!empty($strRedirectTo)) {
             $strRed = preg_replace(array('/\\/' . $this->strFormdataDetailsKey . '\\/' . \Input::get($this->strFormdataDetailsKey) . '/i', '/' . $this->strFormdataDetailsKey . '=' . \Input::get($this->strFormdataDetailsKey) . '/i', '/act=edit/i'), array('', '', ''), $strUrl) . (!empty($strUrlParams) ? '?' . $strUrlParams : '');
             \Controller::redirect($strRed);
         }
     }
 }
Beispiel #5
0
 /**
  * Optional confirmation mail, optional store data in backend
  * @param array	Submitted data
  * @param array	Form configuration
  * @param array Files uploaded
  * @param array	Form field labels
  */
 public function processSubmittedData($arrSubmitted, $arrForm = false, $arrFiles = false, $arrLabels = false)
 {
     // Form config
     if (!$arrForm) {
         return;
     }
     $arrFormFields = array();
     // NOTE: maybe use form alias instead in upcoming release
     $this->strFdDcaKey = 'fd_' . (strlen($arrForm['formID']) ? $arrForm['formID'] : str_replace('-', '_', standardize($arrForm['title'])));
     $this->import('FormData');
     $this->FormData->FdDcaKey = $this->strFdDcaKey;
     $this->import('FrontendUser', 'Member');
     $this->import('String');
     $dirImages = '';
     // get params of related listing formdata
     $intListingId = intval($_SESSION['EFP']['LISTING_MOD']['id']);
     if ($intListingId) {
         $objListing = $this->Database->prepare("SELECT * FROM tl_module WHERE id=?")->execute($intListingId);
         if ($objListing->numRows) {
             $arrListing = $objListing->fetchAssoc();
             // mail delivery defined in frontend listing module
             $arrForm['sendConfirmationMailOnFrontendEditing'] = $arrListing['efg_fe_no_confirmation_mail'] ? false : true;
             $arrForm['sendFormattedMailOnFrontendEditing'] = $arrListing['efg_fe_no_formatted_mail'] ? false : true;
         }
     }
     if (strlen($arrListing['efg_DetailsKey'])) {
         $this->strFormdataDetailsKey = $arrListing['efg_DetailsKey'];
     }
     $blnFEedit = false;
     $intOldId = 0;
     $strRedirectTo = '';
     $strUrl = preg_replace('/\\?.*$/', '', $this->Environment->request);
     $strUrlParams = '';
     $blnQuery = false;
     foreach (preg_split('/&(amp;)?/', $_SERVER['QUERY_STRING']) as $fragment) {
         if (strlen($fragment)) {
             if (strncasecmp($fragment, $this->strFormdataDetailsKey, strlen($this->strFormdataDetailsKey)) !== 0 && strncasecmp($fragment, 'act', 3) !== 0) {
                 $strUrlParams .= (!$blnQuery ? '' : '&amp;') . $fragment;
                 $blnQuery = true;
             }
         }
     }
     if (in_array($arrListing['efg_fe_edit_access'], array('public', 'groupmembers', 'member'))) {
         if ($this->Input->get('act') == 'edit') {
             $blnFEedit = true;
             $objCheck = $this->Database->prepare("SELECT id FROM tl_formdata WHERE id=? OR alias=?")->execute($this->Input->get($this->strFormdataDetailsKey), $this->Input->get($this->strFormdataDetailsKey));
             if ($objCheck->numRows == 1) {
                 $intOldId = intval($objCheck->id);
             } else {
                 $this->log('Could not identify record by ID "' . $this->Input->get($this->strFormdataDetailsKey) . '"', 'Efp processSubmittedData()', TL_GENERAL);
             }
         }
     }
     // Types of form fields with storable data
     $arrFFstorable = $this->FormData->arrFFstorable;
     if (($arrForm['storeFormdata'] || $arrForm['sendConfirmationMail'] || $arrForm['sendFormattedMail']) && count($arrSubmitted) > 0) {
         $timeNow = time();
         $this->loadDataContainer($this->strFdDcaKey);
         $this->loadDataContainer('tl_formdata_details');
         $arrFormFields = $this->FormData->getFormfieldsAsArray($arrForm['id']);
         $arrBaseFields = array();
         $arrDetailFields = array();
         if (count($GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['baseFields'])) {
             $arrBaseFields = $GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['baseFields'];
         }
         if (count($GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['detailFields'])) {
             $arrDetailFields = $GLOBALS['TL_DCA']['tl_formdata']['tl_formdata']['detailFields'];
         }
         $arrHookFields = array_merge($arrBaseFields, $arrDetailFields);
         $arrToSave = array();
         foreach ($arrSubmitted as $k => $varVal) {
             if (in_array($k, array('id'))) {
                 continue;
             } elseif (in_array($k, $arrHookFields) || in_array($k, array_keys($arrFormFields)) || in_array($k, array('FORM_SUBMIT', 'MAX_FILE_SIZE'))) {
                 $arrToSave[$k] = $varVal;
             }
         }
         // HOOK: process efg form data callback
         if (array_key_exists('processEfgFormData', $GLOBALS['TL_HOOKS']) && is_array($GLOBALS['TL_HOOKS']['processEfgFormData'])) {
             foreach ($GLOBALS['TL_HOOKS']['processEfgFormData'] as $key => $callback) {
                 $this->import($callback[0]);
                 $arrResult = $this->{$callback}[0]->{$callback}[1]($arrToSave, $arrFiles, $intOldId, $arrForm, $arrLabels);
                 if (is_array($arrResult) && count($arrResult) > 0) {
                     $arrSubmitted = $arrResult;
                     $arrToSave = $arrSubmitted;
                 }
             }
         }
     }
     // Formdata storage
     if ($arrForm['storeFormdata'] && count($arrSubmitted) > 0) {
         $blnStoreOptionsValue = $arrForm['efgStoreValues'] == "1" ? true : false;
         // if frontend editing, get old record
         if ($intOldId > 0) {
             $arrOldData = $this->FormData->getFormdataAsArray($intOldId);
             $arrOldFormdata = $arrOldData['fd_base'];
             $arrOldFormdataDetails = $arrOldData['fd_details'];
         }
         // Prepare record tl_formdata
         if ($arrFormFields['name']) {
             $strUserName = $arrSubmitted['name'];
         }
         if ($arrFormFields['email']) {
             $strUserEmail = $arrSubmitted['email'];
         }
         if ($arrFormFields['confirmationMailRecipientField']) {
             $strUserEmail = $arrSubmitted[$arrForm['confirmationMailRecipientField']];
         }
         if ($arrFormFields['message']) {
             $strUserMessage = $arrSubmitted['message'];
         }
         $arrSet = array('form' => $arrForm['title'], 'tstamp' => $timeNow, 'date' => $timeNow, 'ip' => $this->Environment->ip, 'published' => $GLOBALS['TL_DCA']['tl_formdata']['fields']['published']['default'] == '1' ? '1' : '', 'fd_member' => intval($this->Member->id), 'fd_member_group' => intval($this->Member->groups[0]), 'fd_user' => intval($this->User->id), 'fd_user_group' => intval($this->User->groups[0]));
         // if frontend editing keep some values from existing record
         if ($intOldId > 0) {
             $arrSet['form'] = $arrOldFormdata['form'];
             $arrSet['be_notes'] = $arrOldFormdata['be_notes'];
             $arrSet['fd_member'] = $arrOldFormdata['fd_member'];
             $arrSet['fd_member_group'] = $arrOldFormdata['fd_member_group'];
             if (intval($this->Member->id) > 0) {
                 $arrSet['fd_member'] = intval($this->Member->id);
                 if (count($this->Member->groups) == 1 && intval($this->Member->groups[0]) > 0) {
                     $arrSet['fd_member_group'] = intval($this->Member->groups[0]);
                 }
             } else {
                 $arrSet['fd_member'] = 0;
             }
             $arrSet['fd_user'] = $arrOldFormdata['fd_user'];
             $arrSet['fd_user_group'] = $arrOldFormdata['fd_user_group'];
             // set published to value of old record, if NO default value is defined
             if (!isset($GLOBALS['TL_DCA']['tl_formdata']['fields']['published']['default'])) {
                 $arrSet['published'] = $arrOldFormdata['published'];
             }
         }
         // store formdata
         // update or insert and delete
         if ($blnFEedit && strlen($arrListing['efg_fe_keep_id'])) {
             $intNewId = $intOldId;
             $this->Database->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrSet)->execute($intOldId);
             $this->Database->prepare("DELETE FROM tl_formdata_details WHERE pid=?")->execute($intOldId);
         } else {
             $objNewFormdata = $this->Database->prepare("INSERT INTO tl_formdata %s")->set($arrSet)->execute();
             $intNewId = $objNewFormdata->insertId;
             // update related comments
             if (in_array('comments', $this->Config->getActiveModules())) {
                 $this->Database->prepare("UPDATE tl_comments %s WHERE `source` = 'tl_formdata' AND parent=?")->set(array('parent' => $intNewId))->execute($intOldId);
             }
         }
         // store details data
         foreach ($arrFormFields as $k => $arrField) {
             $strType = $arrField['type'];
             $strVal = '';
             if (in_array($strType, $arrFFstorable)) {
                 if ($blnStoreOptionsValue && in_array($strType, array('checkbox', 'radio', 'select'))) {
                     $arrField['eval']['efgStoreValues'] = true;
                 }
                 // set rgxp 'date' for field type 'calendar' if not set
                 if ($arrField['type'] == 'calendar') {
                     if (!isset($arrField['rgxp'])) {
                         $arrField['rgxp'] = 'date';
                     }
                 } elseif ($arrField['type'] == 'xdependentcalendarfields') {
                     $arrField['rgxp'] = 'date';
                     $arrField['dateFormat'] = $arrField['xdateformat'];
                 }
                 $strVal = $this->FormData->preparePostValForDb($arrSubmitted[$k], $arrField, $arrFiles[$k]);
                 // special treatment for type upload
                 // if frontend editing and no new upload, keep old file
                 if ($strType == 'upload') {
                     if ($intOldId) {
                         if (!$arrFiles[$k]['name']) {
                             if (strlen($arrOldFormdataDetails[$k]['value'])) {
                                 $strVal = $arrOldFormdataDetails[$k]['value'];
                             }
                         }
                     }
                 }
                 if ($arrSubmitted[$k] || $strType == 'upload' && strlen($strVal)) {
                     // prepare data
                     $arrFieldSet = array('pid' => $intNewId, 'sorting' => $arrField['sorting'], 'tstamp' => $timeNow, 'ff_id' => $arrField['id'], 'ff_type' => $strType, 'ff_label' => $arrField['label'], 'ff_name' => $arrField['name'], 'value' => $strVal);
                     $objNewFormdataDetails = $this->Database->prepare("INSERT INTO tl_formdata_details %s")->set($arrFieldSet)->execute();
                     if (strlen($_SESSION['EFP_ERROR'])) {
                         unset($_SESSION['EFP_ERROR']);
                     }
                 }
             }
         }
         // end foreach $arrFormFields
         // after frontend editing delete old record
         if ($blnFEedit) {
             if (!isset($arrListing['efg_fe_keep_id']) || $arrListing['efg_fe_keep_id'] != "1") {
                 if ($intNewId > 0 && intval($intOldId) > 0 && intval($intNewId) != intval($intOldId)) {
                     $this->Database->prepare("DELETE FROM tl_formdata_details WHERE pid=?")->execute($intOldId);
                     $this->Database->prepare("DELETE FROM tl_formdata WHERE id=?")->execute($intOldId);
                 }
             }
             $strRedirectTo = preg_replace('/\\?.*$/', '', $this->Environment->request);
         }
         // auto generate alias
         $strAlias = $this->FormData->generateAlias($arrOldFormdata['alias'], $arrForm['title'], $intNewId);
         if (strlen($strAlias)) {
             $arrUpd = array('alias' => $strAlias);
             $this->Database->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrUpd)->execute($intNewId);
         }
     }
     // end form data storage
     // store data in session to display on confirmation page
     unset($_SESSION['EFP']['FORMDATA']);
     $blnSkipEmpty = $arrForm['confirmationMailSkipEmpty'] ? true : false;
     foreach ($arrFormFields as $k => $arrField) {
         $strType = $arrField['type'];
         $strVal = '';
         if (in_array($strType, $arrFFstorable)) {
             $strVal = $this->FormData->preparePostValForMail($arrSubmitted[$k], $arrField, $arrFiles[$k], $blnSkipEmpty);
         }
         $_SESSION['EFP']['FORMDATA'][$k] = $strVal;
     }
     $_SESSION['EFP']['FORMDATA']['_formId_'] = $arrForm['id'];
     // end store data in session
     // Confirmation Mail
     if ($blnFEedit && !$arrForm['sendConfirmationMailOnFrontendEditing']) {
         $arrForm['sendConfirmationMail'] = false;
     }
     if ($arrForm['sendConfirmationMail']) {
         $this->import('String');
         $messageText = '';
         $messageHtml = '';
         $messageHtmlTmpl = '';
         $recipient = '';
         $arrRecipient = array();
         $sender = '';
         $senderName = '';
         $replyTo = '';
         $attachments = array();
         $blnSkipEmpty = $arrForm['confirmationMailSkipEmpty'] ? true : false;
         $sender = $arrForm['confirmationMailSender'];
         if (strlen($sender)) {
             $sender = str_replace(array('[', ']'), array('<', '>'), $sender);
             if (strpos($sender, '<') > 0) {
                 preg_match('/(.*)?<(\\S*)>/si', $sender, $parts);
                 $sender = $parts[2];
                 $senderName = trim($parts[1]);
             }
         }
         $recipientFieldName = $arrForm['confirmationMailRecipientField'];
         $varRecipient = $arrSubmitted[$recipientFieldName];
         if (is_array($varRecipient)) {
             $arrRecipient = $varRecipient;
         } else {
             $arrRecipient = trimsplit(',', $varRecipient);
         }
         if (strlen($arrForm['confirmationMailRecipient'])) {
             $varRecipient = $arrForm['confirmationMailRecipient'];
             $arrRecipient = array_merge($arrRecipient, trimsplit(',', $varRecipient));
         }
         $arrRecipient = array_unique($arrRecipient);
         $subject = $this->String->decodeEntities($arrForm['confirmationMailSubject']);
         $messageText = $this->String->decodeEntities($arrForm['confirmationMailText']);
         $messageHtmlTmpl = $arrForm['confirmationMailTemplate'];
         if ($messageHtmlTmpl != '') {
             $fileTemplate = new File($messageHtmlTmpl);
             if ($fileTemplate->mime == 'text/html') {
                 $messageHtml = $fileTemplate->getContent();
             }
         }
         // prepare insert tags to handle separate from 'condition tags'
         if (strlen($messageText)) {
             $messageText = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $messageText);
         }
         if (strlen($messageHtml)) {
             $messageHtml = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $messageHtml);
         }
         if (strlen($subject)) {
             $subject = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $subject);
         }
         if (strlen($sender)) {
             $sender = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $sender);
         }
         if (strlen($senderName)) {
             $senderName = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $senderName);
         }
         foreach ($arrRecipient as $keyRcpt => $recipient) {
             $arrRecipient[$keyRcpt] = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $recipient);
         }
         $blnEvalSubject = $this->FormData->replaceConditionTags($subject);
         $blnEvalMessageText = $this->FormData->replaceConditionTags($messageText);
         $blnEvalMessageHtml = $this->FormData->replaceConditionTags($messageHtml);
         // Replace tags in messageText, messageHtml ...
         $tags = array();
         preg_match_all('/__BRCL__.*?__BRCR__/si', $messageText . $messageHtml . $subject . $sender . $senderName . implode(' ', $arrRecipient), $tags);
         // Replace tags of type {{form::<form field name>}}
         // .. {{form::uploadfieldname?attachment=true}}
         // .. {{form::fieldname?label=Label for this field: }}
         foreach ($tags[0] as $tag) {
             $elements = explode('::', preg_replace(array('/^__BRCL__/i', '/__BRCR__$/i'), array('', ''), $tag));
             switch (strtolower($elements[0])) {
                 // Form
                 case 'form':
                     $strKey = $elements[1];
                     $arrKey = explode('?', $strKey);
                     $strKey = $arrKey[0];
                     $arrTagParams = null;
                     if (isset($arrKey[1]) && strlen($arrKey[1])) {
                         $arrTagParams = $this->FormData->parseInsertTagParams($tag);
                     }
                     $arrField = $arrFormFields[$strKey];
                     $arrField['efgMailSkipEmpty'] = $blnSkipEmpty;
                     $strType = $arrField['type'];
                     $strLabel = '';
                     $strVal = '';
                     if ($arrTagParams && strlen($arrTagParams['label'])) {
                         $strLabel = $arrTagParams['label'];
                     }
                     if (in_array($strType, $arrFFstorable)) {
                         if ($strType == 'efgImageSelect') {
                             $strVal = '';
                             $varVal = $this->FormData->preparePostValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]);
                             $varTxt = array();
                             $varHtml = array();
                             if (is_string($varVal)) {
                                 $varVal = array($varVal);
                             }
                             if (count($varVal)) {
                                 foreach ($varVal as $strVal) {
                                     if (strlen($strVal)) {
                                         $varTxt[] = $this->Environment->base . $strVal;
                                         $varHtml[] = '<img src="' . $strVal . '" />';
                                     }
                                 }
                             }
                             if (!count($varTxt) && $blnSkipEmpty) {
                                 $strLabel = '';
                             }
                             $messageText = str_replace($tag, $strLabel . implode(', ', $varTxt), $messageText);
                             $messageHtml = str_replace($tag, $strLabel . implode(' ', $varHtml), $messageHtml);
                         } elseif ($strType == 'upload') {
                             if ($arrTagParams && (array_key_exists('attachment', $arrTagParams) && $arrTagParams['attachment'] == true || array_key_exists('attachement', $arrTagParams) && $arrTagParams['attachement'] == true)) {
                                 if (strlen($arrFiles[$strKey]['tmp_name']) && is_file($arrFiles[$strKey]['tmp_name'])) {
                                     if (!isset($attachments[$arrFiles[$strKey]['tmp_name']])) {
                                         $attachments[$arrFiles[$strKey]['tmp_name']] = array('name' => $arrFiles[$strKey]['name'], 'file' => $arrFiles[$strKey]['tmp_name'], 'mime' => $arrFiles[$strKey]['type']);
                                     }
                                 }
                                 $strVal = '';
                             } else {
                                 $strVal = $this->FormData->preparePostValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]);
                             }
                             if (!is_array($strVal) && !strlen($strVal) && $blnSkipEmpty) {
                                 $strLabel = '';
                             }
                             $messageText = str_replace($tag, $strLabel . $strVal, $messageText);
                             $messageHtml = str_replace($tag, $strLabel . $strVal, $messageHtml);
                         } else {
                             $strVal = $this->FormData->preparePostValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]);
                             if (!is_array($strVal) && !strlen($strVal) && $blnSkipEmpty) {
                                 $strLabel = '';
                             }
                             $messageText = str_replace($tag, $strLabel . $strVal, $messageText);
                             if (is_string($strVal) && strlen($strVal) && !is_bool(strpos($strVal, "\n"))) {
                                 $strVal = preg_replace('/(<\\/|<)(h\\d|p|div|ul|ol|li)([^>]*)(>)(\\n)/si', "\\1\\2\\3\\4", $strVal);
                                 $strVal = nl2br($strVal);
                                 $strVal = preg_replace('/(<\\/)(h\\d|p|div|ul|ol|li)([^>]*)(>)/si', "\\1\\2\\3\\4\n", $strVal);
                             }
                             $messageHtml = str_replace($tag, $strLabel . $strVal, $messageHtml);
                         }
                     }
                     // replace insert tags in subject
                     if (strlen($subject)) {
                         $subject = str_replace($tag, $strVal, $subject);
                     }
                     // replace insert tags in sender
                     if (strlen($sender)) {
                         $sender = str_replace($tag, $strVal, $sender);
                     }
                     // replace insert tags in sender name
                     if (strlen($senderName)) {
                         $senderName = str_replace($tag, $strVal, $senderName);
                     }
                     // replace insert tags in recipients
                     foreach ($arrRecipient as $keyRcpt => $recipient) {
                         $arrRecipient[$keyRcpt] = str_replace($tag, $strVal, $recipient);
                     }
                     break;
             }
         }
         // foreach tags
         // Replace standard insert tags
         if (strlen($messageText)) {
             $messageText = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $messageText);
             $messageText = $this->replaceInsertTags($messageText);
             if ($blnEvalMessageText) {
                 $messageText = $this->FormData->evalConditionTags($messageText, $arrSubmitted, $arrFiles, $arrForm);
             }
             $messageText = strip_tags($messageText);
         }
         if (strlen($messageHtml)) {
             $messageHtml = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $messageHtml);
             $messageHtml = $this->replaceInsertTags($messageHtml);
             if ($blnEvalMessageHtml) {
                 $messageHtml = $this->FormData->evalConditionTags($messageHtml, $arrSubmitted, $arrFiles, $arrForm);
             }
         }
         // replace insert tags in subject
         if (strlen($subject)) {
             $subject = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $subject);
             $subject = $this->replaceInsertTags($subject);
             if ($blnEvalSubject) {
                 $subject = $this->FormData->evalConditionTags($subject, $arrSubmitted, $arrFiles, $arrForm);
             }
         }
         // replace insert tags in sender
         if (strlen($sender)) {
             $sender = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $sender);
             $sender = trim($this->replaceInsertTags($sender));
         }
         // replace insert tags in sender name
         if (strlen($senderName)) {
             $senderName = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $senderName);
             $senderName = trim($this->replaceInsertTags($senderName));
         }
         // replace insert tags in replyto
         if (strlen($arrForm['confirmationMailReplyto'])) {
             $replyTo = $this->replaceInsertTags($arrForm['confirmationMailReplyto']);
         }
         // replace insert tags in recipients
         foreach ($arrRecipient as $keyRcpt => $recipient) {
             $arrRecipient[$keyRcpt] = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $recipient);
             $arrRecipient[$keyRcpt] = trim($this->replaceInsertTags($arrRecipient[$keyRcpt]));
         }
         $confEmail = new Email();
         $confEmail->from = $sender;
         if (strlen($senderName)) {
             $confEmail->fromName = $senderName;
         }
         if (strlen($replyTo)) {
             $confEmail->replyTo($replyTo);
         }
         $confEmail->subject = $subject;
         // Thanks to Torben Schwellnus
         // check if we want custom attachments...
         if ($arrForm['addConfirmationMailAttachments']) {
             // check if we have custom attachments...
             if ($arrForm['confirmationMailAttachments']) {
                 $arrCustomAttachments = deserialize($arrForm['confirmationMailAttachments'], true);
                 if (is_array($arrCustomAttachments)) {
                     foreach ($arrCustomAttachments as $strFile) {
                         if (is_file($strFile)) {
                             if (is_readable($strFile)) {
                                 $objFile = new File($strFile);
                                 if ($objFile->size) {
                                     $attachments[$objFile->value] = array('file' => TL_ROOT . '/' . $objFile->value, 'name' => $objFile->basename, 'mime' => $objFile->mime);
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (is_array($attachments) && count($attachments) > 0) {
             foreach ($attachments as $strFile => $varParams) {
                 $strContent = file_get_contents($strFile, false);
                 $confEmail->attachFileFromString($strContent, $varParams['name'], $varParams['mime']);
             }
         }
         if ($dirImages != '') {
             $confEmail->imageDir = $dirImages;
         }
         if ($messageText != '') {
             $confEmail->text = $messageText;
         }
         if ($messageHtml != '') {
             $confEmail->html = $messageHtml;
         }
         // Send e-mail
         $blnConfirmationSent = false;
         if (count($arrRecipient) > 0) {
             foreach ($arrRecipient as $recipient) {
                 if (strlen($recipient)) {
                     $recipient = $this->replaceInsertTags($recipient);
                     $recipient = str_replace(array('[', ']'), array('<', '>'), $recipient);
                     $recipientName = '';
                     if (strpos($recipient, '<') > 0) {
                         preg_match('/(.*)?<(\\S*)>/si', $recipient, $parts);
                         $recipientName = trim($parts[1]);
                         $recipient = strlen($recipientName) ? $recipientName . ' <' . $parts[2] . '>' : $parts[2];
                     }
                 }
                 $confEmail->sendTo($recipient);
                 $blnConfirmationSent = true;
             }
         }
         if ($blnConfirmationSent && isset($intNewId) && intval($intNewId) > 0) {
             $arrUpd = array('confirmationSent' => '1', 'confirmationDate' => $timeNow);
             $res = $this->Database->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrUpd)->execute($intNewId);
         }
     }
     // End confirmation mail
     // Information (formatted) Mail
     if ($blnFEedit && !$arrForm['sendFormattedMailOnFrontendEditing']) {
         $arrForm['sendFormattedMail'] = false;
     }
     if ($arrForm['sendFormattedMail']) {
         $this->import('String');
         $messageText = '';
         $messageHtml = '';
         $messageHtmlTmpl = '';
         $recipient = '';
         $arrRecipient = array();
         $sender = '';
         $senderName = '';
         $attachments = array();
         $blnSkipEmpty = $arrForm['formattedMailSkipEmpty'] ? true : false;
         // Set the admin e-mail as "from" address
         $sender = $GLOBALS['TL_ADMIN_EMAIL'];
         if (strlen($sender)) {
             $sender = str_replace(array('[', ']'), array('<', '>'), $sender);
             if (strpos($sender, '<') > 0) {
                 preg_match('/(.*)?<(\\S*)>/si', $sender, $parts);
                 $sender = $parts[2];
                 $senderName = trim($parts[1]);
             }
         }
         $varRecipient = $arrForm['formattedMailRecipient'];
         if (is_array($varRecipient)) {
             $arrRecipient = $varRecipient;
         } else {
             $arrRecipient = trimsplit(',', $varRecipient);
         }
         $arrRecipient = array_unique($arrRecipient);
         $subject = $this->String->decodeEntities($arrForm['formattedMailSubject']);
         $messageText = $this->String->decodeEntities($arrForm['formattedMailText']);
         $messageHtmlTmpl = $arrForm['formattedMailTemplate'];
         if ($messageHtmlTmpl != '') {
             $fileTemplate = new File($messageHtmlTmpl);
             if ($fileTemplate->mime == 'text/html') {
                 $messageHtml = $fileTemplate->getContent();
             }
         }
         // prepare insert tags to handle separate from 'condition tags'
         if (strlen($messageText)) {
             $messageText = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $messageText);
         }
         if (strlen($messageHtml)) {
             $messageHtml = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $messageHtml);
         }
         if (strlen($subject)) {
             $subject = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $subject);
         }
         if (strlen($sender)) {
             $sender = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $sender);
         }
         if (strlen($senderName)) {
             $senderName = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $senderName);
         }
         foreach ($arrRecipient as $keyRcpt => $recipient) {
             $arrRecipient[$keyRcpt] = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $recipient);
         }
         $blnEvalSubject = $this->FormData->replaceConditionTags($subject);
         $blnEvalMessageText = $this->FormData->replaceConditionTags($messageText);
         $blnEvalMessageHtml = $this->FormData->replaceConditionTags($messageHtml);
         // Replace tags in messageText, messageHtml ...
         $tags = array();
         preg_match_all('/__BRCL__.*?__BRCR__/si', $messageText . $messageHtml . $subject . $sender . $senderName . implode(' ', $arrRecipient), $tags);
         // Replace tags of type {{form::<form field name>}}
         // .. {{form::uploadfieldname?attachment=true}}
         // .. {{form::fieldname?label=Label for this field: }}
         foreach ($tags[0] as $tag) {
             $elements = explode('::', trim(str_replace(array('__BRCL__', '__BRCR__'), array('', ''), $tag)));
             switch (strtolower($elements[0])) {
                 // Form
                 case 'form':
                     $strKey = $elements[1];
                     $arrKey = explode('?', $strKey);
                     $strKey = $arrKey[0];
                     $arrTagParams = null;
                     if (isset($arrKey[1]) && strlen($arrKey[1])) {
                         $arrTagParams = $this->FormData->parseInsertTagParams($tag);
                     }
                     $arrField = $arrFormFields[$strKey];
                     $arrField['efgMailSkipEmpty'] = $blnSkipEmpty;
                     $strType = $arrField['type'];
                     $strLabel = '';
                     $strVal = '';
                     if ($arrTagParams && strlen($arrTagParams['label'])) {
                         $strLabel = $arrTagParams['label'];
                     }
                     if (in_array($strType, $arrFFstorable)) {
                         if ($strType == 'efgImageSelect') {
                             $strVal = '';
                             $varVal = $this->FormData->preparePostValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]);
                             $varTxt = array();
                             $varHtml = array();
                             if (is_string($varVal)) {
                                 $varVal = array($varVal);
                             }
                             if (count($varVal)) {
                                 foreach ($varVal as $strVal) {
                                     if (strlen($strVal)) {
                                         $varTxt[] = $this->Environment->base . $strVal;
                                         $varHtml[] = '<img src="' . $strVal . '" />';
                                     }
                                 }
                             }
                             if (!count($varTxt) && $blnSkipEmpty) {
                                 $strLabel = '';
                             }
                             $messageText = str_replace($tag, $strLabel . implode(', ', $varTxt), $messageText);
                             $messageHtml = str_replace($tag, $strLabel . implode(' ', $varHtml), $messageHtml);
                         } elseif ($strType == 'upload') {
                             if ($arrTagParams && (array_key_exists('attachment', $arrTagParams) && $arrTagParams['attachment'] == true || array_key_exists('attachement', $arrTagParams) && $arrTagParams['attachement'] == true)) {
                                 if (strlen($arrFiles[$strKey]['tmp_name']) && is_file($arrFiles[$strKey]['tmp_name'])) {
                                     if (!isset($attachments[$arrFiles[$strKey]['tmp_name']])) {
                                         $attachments[$arrFiles[$strKey]['tmp_name']] = array('name' => $arrFiles[$strKey]['name'], 'file' => $arrFiles[$strKey]['tmp_name'], 'mime' => $arrFiles[$strKey]['type']);
                                     }
                                 }
                                 $strVal = '';
                             } else {
                                 $strVal = $this->FormData->preparePostValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]);
                             }
                             if (!is_array($strVal) && !strlen($strVal) && $blnSkipEmpty) {
                                 $strLabel = '';
                             }
                             $messageText = str_replace($tag, $strLabel . $strVal, $messageText);
                             $messageHtml = str_replace($tag, $strLabel . $strVal, $messageHtml);
                         } else {
                             $strVal = $this->FormData->preparePostValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]);
                             if (!is_array($strVal) && !strlen($strVal) && $blnSkipEmpty) {
                                 $strLabel = '';
                             }
                             $messageText = str_replace($tag, $strLabel . $strVal, $messageText);
                             if (is_string($strVal) && strlen($strVal) && !is_bool(strpos($strVal, "\n"))) {
                                 $strVal = preg_replace('/(<\\/|<)(h\\d|p|div|ul|ol|li)([^>]*)(>)(\\n)/si', "\\1\\2\\3\\4", $strVal);
                                 $strVal = nl2br($strVal);
                                 $strVal = preg_replace('/(<\\/)(h\\d|p|div|ul|ol|li)([^>]*)(>)/si', "\\1\\2\\3\\4\n", $strVal);
                             }
                             $messageHtml = str_replace($tag, $strLabel . $strVal, $messageHtml);
                         }
                     }
                     // replace insert tags in subject
                     if (strlen($subject)) {
                         $subject = str_replace($tag, $strVal, $subject);
                     }
                     // replace insert tags in sender
                     if (strlen($sender)) {
                         $sender = str_replace($tag, $strVal, $sender);
                     }
                     // replace insert tags in sender name
                     if (strlen($senderName)) {
                         $senderName = str_replace($tag, $strVal, $senderName);
                     }
                     // replace insert tags in recipients
                     foreach ($arrRecipient as $keyRcpt => $recipient) {
                         $arrRecipient[$keyRcpt] = str_replace($tag, $strVal, $recipient);
                     }
                     break;
             }
         }
         // Replace standard insert tags
         if (strlen($messageText)) {
             $messageText = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $messageText);
             $messageText = $this->replaceInsertTags($messageText);
             if ($blnEvalMessageText) {
                 $messageText = $this->FormData->evalConditionTags($messageText, $arrSubmitted, $arrFiles, $arrForm);
             }
             $messageText = strip_tags($messageText);
         }
         if (strlen($messageHtml)) {
             $messageHtml = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $messageHtml);
             $messageHtml = $this->replaceInsertTags($messageHtml);
             if ($blnEvalMessageHtml) {
                 $messageHtml = $this->FormData->evalConditionTags($messageHtml, $arrSubmitted, $arrFiles, $arrForm);
             }
         }
         // replace insert tags in subject
         if (strlen($subject)) {
             $subject = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $subject);
             $subject = $this->replaceInsertTags($subject);
             if ($blnEvalSubject) {
                 $subject = $this->FormData->evalConditionTags($subject, $arrSubmitted, $arrFiles, $arrForm);
             }
         }
         // replace insert tags in sender
         if (strlen($sender)) {
             $sender = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $sender);
             $sender = trim($this->replaceInsertTags($sender));
         }
         // replace insert tags in sender name
         if (strlen($senderName)) {
             $senderName = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $senderName);
             $senderName = trim($this->replaceInsertTags($senderName));
         }
         // replace insert tags in recipients
         foreach ($arrRecipient as $keyRcpt => $recipient) {
             $arrRecipient[$keyRcpt] = preg_replace(array('/__BRCL__/', '/__BRCR__/'), array('{{', '}}'), $recipient);
             $arrRecipient[$keyRcpt] = trim($this->replaceInsertTags($arrRecipient[$keyRcpt]));
         }
         $infoEmail = new Email();
         $infoEmail->from = $sender;
         if (strlen($senderName)) {
             $infoEmail->fromName = $senderName;
         }
         $infoEmail->subject = $subject;
         // Get "reply to" address, if form contains field named 'email'
         if (isset($arrSubmitted['email']) && strlen($arrSubmitted['email']) && !is_bool(strpos($arrSubmitted['email'], '@'))) {
             $replyTo = $arrSubmitted['email'];
             // add name
             if (isset($arrSubmitted['name']) && strlen($arrSubmitted['name'])) {
                 $replyTo = '"' . $arrSubmitted['name'] . '" <' . $arrSubmitted['email'] . '>';
             }
             $infoEmail->replyTo($replyTo);
         }
         // check if we want custom attachments...
         if ($arrForm['addFormattedMailAttachments']) {
             // check if we have custom attachments...
             if ($arrForm['formattedMailAttachments']) {
                 $arrCustomAttachments = deserialize($arrForm['formattedMailAttachments'], true);
                 if (is_array($arrCustomAttachments)) {
                     foreach ($arrCustomAttachments as $strFile) {
                         if (is_file($strFile)) {
                             if (is_readable($strFile)) {
                                 $objFile = new File($strFile);
                                 if ($objFile->size) {
                                     $attachments[$objFile->value] = array('file' => TL_ROOT . '/' . $objFile->value, 'name' => $objFile->basename, 'mime' => $objFile->mime);
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (is_array($attachments) && count($attachments) > 0) {
             foreach ($attachments as $strFile => $varParams) {
                 $strContent = file_get_contents($strFile, false);
                 $infoEmail->attachFileFromString($strContent, $varParams['name'], $varParams['mime']);
             }
         }
         if ($dirImages != '') {
             $infoEmail->imageDir = $dirImages;
         }
         if ($messageText != '') {
             $infoEmail->text = $messageText;
         }
         if ($messageHtml != '') {
             $infoEmail->html = $messageHtml;
         }
         // Send e-mail
         if (count($arrRecipient) > 0) {
             foreach ($arrRecipient as $recipient) {
                 if (strlen($recipient)) {
                     $recipient = $this->replaceInsertTags($recipient);
                     $recipient = str_replace(array('[', ']'), array('<', '>'), $recipient);
                     $recipientName = '';
                     if (strpos($recipient, '<') > 0) {
                         preg_match('/(.*)?<(\\S*)>/si', $recipient, $parts);
                         $recipientName = trim($parts[1]);
                         $recipient = strlen($recipientName) ? $recipientName . ' <' . $parts[2] . '>' : $parts[2];
                     }
                 }
                 $infoEmail->sendTo($recipient);
             }
         }
     }
     // End information mail
     // redirect after frontend editing
     if ($blnFEedit) {
         if (strlen($strRedirectTo)) {
             $strRed = preg_replace(array('/\\/' . $this->strFormdataDetailsKey . '\\/' . $this->Input->get($this->strFormdataDetailsKey) . '/i', '/' . $this->strFormdataDetailsKey . '=' . $this->Input->get($this->strFormdataDetailsKey) . '/i', '/act=edit/i'), array('', '', ''), $strUrl) . (strlen($strUrlParams) ? '?' . $strUrlParams : '');
             $this->redirect($strRed);
         }
     }
 }
 protected function sendEmail($what, Member $member, array $data = [])
 {
     $profiledConfig = ProfiledConfig::current_profiled_config();
     $templateData = array_merge(['Member' => $member], $data);
     $memberEmailTemplate = self::MemberEmailPrefix . strtolower($what);
     if (SSViewer::hasTemplate($memberEmailTemplate)) {
         // send email to member from ProfiledConfig.SendEmailFrom to Member.Email
         $emailMember = new Email($profiledConfig->getProfiledSender('Member'), $member->Email, $profiledConfig->getProfiledEmailSubject('Member', $what));
         $emailMember->setTemplate($memberEmailTemplate);
         $emailMember->populateTemplate($templateData);
         $emailMember->send();
     }
     $adminEmailTemplate = self::AdminEmailPrefix . strtolower($what);
     if (SSViewer::hasTemplate([$adminEmailTemplate])) {
         // send admin email from either Member.Email or ProfiledConfig.SendEmailFrom to Profiled.AdminEmail
         $emailAdmin = new Email($profiledConfig->getProfiledSender('Admin', $member->Email), $profiledConfig->getAdminEmail(), $profiledConfig->getProfiledEmailSubject('Admin', $what));
         $emailAdmin->setTemplate($adminEmailTemplate);
         $emailAdmin->populateTemplate($templateData);
         // save body to attach to admin email
         if (isset($emailMember)) {
             $emailAdmin->attachFileFromString($emailMember->Body(), $member->Email . "_registration.txt");
         }
         $emailAdmin->send();
     }
 }
Beispiel #7
0
 /**
  * Process form data, store it in the session and redirect to the jumpTo page
  * @param array
  * @param array
  */
 protected function processFormData($arrSubmitted, $arrLabels)
 {
     // Send form data via e-mail
     if ($this->sendViaEmail) {
         $this->import('String');
         $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 = $this->String->splitCsv($this->recipient);
         // Format recipients
         foreach ($recipients as $k => $v) {
             $recipients[$k] = str_replace(array('[', ']', '"'), array('<', '>', ''), $v);
         }
         $email = new Email();
         // Get subject and message
         if ($this->format == 'email') {
             $message = $arrSubmitted['message'];
             $email->subject = $arrSubmitted['subject'];
         }
         // Set the admin e-mail as "from" address
         $email->from = $GLOBALS['TL_ADMIN_EMAIL'];
         $email->fromName = $GLOBALS['TL_ADMIN_NAME'];
         // Get the "reply to" address
         if (strlen($this->Input->post('email', true))) {
             $replyTo = $this->Input->post('email', true);
             // Add name
             if (strlen($this->Input->post('name'))) {
                 $replyTo = '"' . $this->Input->post('name') . '" <' . $replyTo . '>';
             }
             $email->replyTo($replyTo);
         }
         // Fallback to default subject
         if (!strlen($email->subject)) {
             $email->subject = $this->replaceInsertTags($this->subject);
         }
         // Send copy to sender
         if (strlen($arrSubmitted['cc'])) {
             $email->sendCc($this->Input->post('email', true));
             unset($_SESSION['FORM_DATA']['cc']);
         }
         // Attach XML file
         if ($this->format == 'xml') {
             $objTemplate = new FrontendTemplate('form_xml');
             $objTemplate->fields = $fields;
             $objTemplate->charset = $GLOBALS['TL_CONFIG']['characterSet'];
             $email->attachFileFromString($objTemplate->parse(), 'form.xml', 'application/xml');
         }
         // Attach CSV file
         if ($this->format == 'csv') {
             $email->attachFileFromString($this->String->decodeEntities('"' . implode('";"', $keys) . '"' . "\n" . '"' . implode('";"', $values) . '"'), 'form.csv', 'text/comma-separated-values');
         }
         $uploaded = '';
         // Attach uploaded files
         if (count($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $file) {
                 // Add a link to the uploaded file
                 if ($file['uploaded']) {
                     $uploaded .= "\n" . $this->Environment->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 : '';
         // Send e-mail
         $email->text = $this->String->decodeEntities(trim($message)) . $uploaded . "\n\n";
         $email->sendTo($recipients);
     }
     // Store values in the database
     if ($this->storeValues && strlen($this->targetTable)) {
         $arrSet = array();
         // Add timestamp
         if ($this->Database->fieldExists('tstamp', $this->targetTable)) {
             $arrSet['tstamp'] = time();
         }
         // Fields
         foreach ($arrSubmitted as $k => $v) {
             if ($k != 'cc' && $k != 'id') {
                 $arrSet[$k] = $v;
             }
         }
         // Files
         if (count($_SESSION['FILES'])) {
             foreach ($_SESSION['FILES'] as $k => $v) {
                 if ($v['uploaded']) {
                     $arrSet[$k] = str_replace(TL_ROOT . '/', '', $v['tmp_name']);
                 }
             }
         }
         $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 ? $this->Input->postHtml($key, true) : $this->Input->post($key, true);
     }
     $arrFiles = $_SESSION['FILES'];
     $arrData = $_SESSION['FORM_DATA'];
     // 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]($arrData, $this->arrData, $arrFiles, $arrLabels);
         }
     }
     // Reset form data in case it has been modified in a callback function
     $_SESSION['FORM_DATA'] = $arrData;
     $_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 . '".', 'Form processFormData()', TL_FORMS);
     } else {
         $this->log('Form "' . $this->title . '" has been submitted by ' . $this->Environment->ip . '.', 'Form processFormData()', TL_FORMS);
     }
     $this->jumpToOrReload($this->jumpTo);
 }
    /**
     * Send confirmation mail
     * @param integer $intID ID of record
     * @return string
     */
    public function mail($intID = false)
    {
        $blnSend = false;
        if (strlen(\Input::get('token')) && \Input::get('token') == $this->Session->get('fd_mail_send')) {
            $blnSend = true;
        }
        $strFormFilter = $this->strTable == 'tl_formdata' && strlen($this->strFormKey) ? $this->sqlFormFilter : '';
        $table_alias = $this->strTable == 'tl_formdata' ? ' f' : '';
        if ($intID) {
            $this->intId = $intID;
        }
        $return = '';
        $this->values[] = $this->intId;
        $this->procedure[] = 'id=?';
        $this->blnCreateNewVersion = false;
        // Get current record
        $sqlQuery = "SELECT * " . (!empty($this->arrSqlDetails) ? ', ' . implode(',', array_values($this->arrSqlDetails)) : '') . " FROM " . $this->strTable . $table_alias;
        $sqlWhere = " WHERE id=?";
        if ($sqlWhere != '') {
            $sqlQuery .= $sqlWhere;
        }
        $objRow = \Database::getInstance()->prepare($sqlQuery)->limit(1)->execute($this->intId);
        // Redirect if there is no record with the given ID
        if ($objRow->numRows < 1) {
            $this->log('Could not load record "' . $this->strTable . '.id=' . $this->intId . '"', __METHOD__, TL_ERROR);
            \Controller::redirect('contao/main.php?act=error');
        }
        $arrSubmitted = $objRow->fetchAssoc();
        $arrFiles = array();
        // Form
        $objForm = null;
        $intFormId = 0;
        if (!empty($GLOBALS['TL_DCA'][$this->strTable]['tl_formdata']['detailFields'])) {
            // Try to get the form
            foreach ($GLOBALS['TL_DCA'][$this->strTable]['tl_formdata']['detailFields'] as $strField) {
                if ($objForm !== null) {
                    break;
                }
                if (!empty($GLOBALS['TL_DCA'][$this->strTable]['fields'][$strField]['f_id'])) {
                    $intFormId = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$strField]['f_id'];
                    $objForm = \FormModel::findByPk($intFormId);
                }
            }
        }
        if ($objForm == null) {
            $objForm = \FormModel::findOneBy('title', $arrSubmitted['form']);
        }
        if ($objForm == null) {
            $this->log('Could not load record "tl_form.id=' . $intFormId . '" / "tl_form.title=' . $arrSubmitted['form'] . '"', __METHOD__, TL_ERROR);
            \Controller::redirect('contao/main.php?act=error');
        }
        $arrForm = $objForm->row();
        $arrFormFields = $this->Formdata->getFormfieldsAsArray($arrForm['id']);
        if (empty($arrForm['confirmationMailSubject']) || empty($arrForm['confirmationMailText']) && empty($arrForm['confirmationMailTemplate'])) {
            return '<p class="tl_error">Can not send this form data record.<br>Missing "Subject", "Text of confirmation mail" or "HTML-template for confirmation mail"<br>Please check configuration of form in form generator.</p>';
        }
        $this->loadDataContainer('tl_files');
        $objMailProperties = new \stdClass();
        $objMailProperties->subject = '';
        $objMailProperties->sender = '';
        $objMailProperties->senderName = '';
        $objMailProperties->replyTo = '';
        $objMailProperties->recipients = array();
        $objMailProperties->messageText = '';
        $objMailProperties->messageHtmlTmpl = '';
        $objMailProperties->messageHtml = '';
        $objMailProperties->attachments = array();
        $objMailProperties->skipEmptyFields = false;
        $objMailProperties->skipEmptyFields = $arrForm['confirmationMailSkipEmpty'] ? true : false;
        $blnStoreOptionsValues = $arrForm['efgStoreValues'] ? true : false;
        // Set the sender as given in form configuration
        list($senderName, $sender) = \String::splitFriendlyEmail($arrForm['confirmationMailSender']);
        $objMailProperties->sender = $sender;
        $objMailProperties->senderName = $senderName;
        // Set the 'reply to' address, if given in form configuration
        if (!empty($arrForm['confirmationMailReplyto'])) {
            list($replyToName, $replyTo) = \String::splitFriendlyEmail($arrForm['confirmationMailReplyto']);
            $objMailProperties->replyTo = strlen($replyToName) ? $replyToName . ' <' . $replyTo . '>' : $replyTo;
        }
        // Set recipient(s)
        $recipientFieldName = $arrForm['confirmationMailRecipientField'];
        if (!empty($recipientFieldName) && !empty($arrSubmitted[$recipientFieldName])) {
            $varRecipient = $arrSubmitted[$recipientFieldName];
            // handle efg option 'save options of values' for field types radio, select, checkbox
            if (in_array($arrFormFields[$recipientFieldName]['type'], array('radio', 'select', 'checkbox'))) {
                if (!$blnStoreOptionsValues) {
                    $arrRecipient = $this->Formdata->prepareDatabaseValueForWidget($varRecipient, $arrFormFields[$recipientFieldName], false);
                    if (!empty($arrRecipient)) {
                        $varRecipient = implode(', ', $arrRecipient);
                    }
                    unset($arrRecipient);
                }
            }
            $strSep = isset($arrFormFields[$recipientFieldName]['eval']['csv']) ? $arrFormFields[$recipientFieldName]['eval']['csv'] : '|';
            $varRecipient = str_replace($strSep, ',', $varRecipient);
        }
        if (strlen($varRecipient) || strlen($arrForm['confirmationMailRecipient'])) {
            $arrRecipient = array_merge(trimsplit(',', $varRecipient), trimsplit(',', $arrForm['confirmationMailRecipient']));
        }
        if (\Input::get('recipient')) {
            $arrRecipient = trimsplit(',', \Input::get('recipient'));
        }
        if (is_array($arrRecipient)) {
            $strRecipient = implode(', ', $arrRecipient);
            // handle insert tag {{user::email}} in recipient fields
            if (!is_bool(strpos($strRecipient, "{{user::email}}")) && $arrSubmitted['fd_member'] > 0) {
                $objUser = \Database::getInstance()->prepare("SELECT `email` FROM `tl_member` WHERE id=?")->limit(1)->execute($arrSubmitted['fd_member']);
                $arrRecipient = array_map("str_replace", array_fill(0, count($arrRecipient), "{{user::email}}"), array_fill(0, count($arrRecipient), $objUser->email), $arrRecipient);
            }
            $arrRecipient = array_filter(array_unique($arrRecipient));
        }
        $objMailProperties->recipients = $arrRecipient;
        // Check if we want custom attachments... (Thanks to Torben Schwellnus)
        if ($arrForm['addConfirmationMailAttachments']) {
            if ($arrForm['confirmationMailAttachments']) {
                $arrCustomAttachments = deserialize($arrForm['confirmationMailAttachments'], true);
                if (!empty($arrCustomAttachments)) {
                    foreach ($arrCustomAttachments as $varFile) {
                        $objFileModel = \FilesModel::findById($varFile);
                        if ($objFileModel !== null) {
                            $objFile = new \File($objFileModel->path, true);
                            if ($objFile->size) {
                                $objMailProperties->attachments[TL_ROOT . '/' . $objFile->path] = array('file' => TL_ROOT . '/' . $objFile->path, 'name' => $objFile->basename, 'mime' => $objFile->mime);
                            }
                        }
                    }
                }
            }
        }
        $objMailProperties->subject = \String::decodeEntities($arrForm['confirmationMailSubject']);
        $objMailProperties->messageText = \String::decodeEntities($arrForm['confirmationMailText']);
        $objMailProperties->messageHtmlTmpl = $arrForm['confirmationMailTemplate'];
        // Replace Insert tags and conditional tags
        $objMailProperties = $this->Formdata->prepareMailData($objMailProperties, $arrSubmitted, $arrFiles, $arrForm, $arrFormFields);
        $objEmail = new \Email();
        $objEmail->from = $objMailProperties->sender;
        if (!empty($objMailProperties->senderName)) {
            $objEmail->fromName = $objMailProperties->senderName;
        }
        $objEmail->subject = $objMailProperties->subject;
        if (!empty($objMailProperties->attachments)) {
            foreach ($objMailProperties->attachments as $strFile => $varParams) {
                $strContent = file_get_contents($varParams['file'], false);
                $objEmail->attachFileFromString($strContent, $varParams['name'], $varParams['mime']);
            }
        }
        if (!empty($objMailProperties->messageText)) {
            $objEmail->text = $objMailProperties->messageText;
        }
        if (!empty($objMailProperties->messageHtml)) {
            $objEmail->html = $objMailProperties->messageHtml;
        }
        // Send Mail
        if (strlen(\Input::get('token')) && \Input::get('token') == $this->Session->get('fd_mail_send')) {
            $this->Session->set('fd_mail_send', null);
            $blnSend = true;
            $blnConfirmationSent = false;
            if ($blnSend) {
                // Send e-mail
                if (!empty($objMailProperties->recipients)) {
                    foreach ($objMailProperties->recipients as $recipient) {
                        if (strlen($recipient)) {
                            $recipient = str_replace(array('[', ']'), array('<', '>'), $recipient);
                            $recipientName = '';
                            if (strpos($recipient, '<') > 0) {
                                preg_match('/(.*)?<(\\S*)>/si', $recipient, $parts);
                                $recipientName = trim($parts[1]);
                                $recipient = strlen($recipientName) ? $recipientName . ' <' . $parts[2] . '>' : $parts[2];
                            }
                        }
                        $objEmail->sendTo($recipient);
                        $blnConfirmationSent = true;
                        \Message::addInfo(sprintf($GLOBALS['TL_LANG']['tl_formdata']['mail_sent'], str_replace(array('<', '>'), array('[', ']'), $recipient)));
                    }
                }
                if ($blnConfirmationSent && isset($this->intId) && intval($this->intId) > 0) {
                    $arrUpd = array('confirmationSent' => '1', 'confirmationDate' => time());
                    $res = \Database::getInstance()->prepare("UPDATE tl_formdata %s WHERE id=?")->set($arrUpd)->execute($this->intId);
                }
            }
        }
        $strToken = md5(uniqid('', true));
        $this->Session->set('fd_mail_send', $strToken);
        $strHint = '';
        if (strlen($objRow->confirmationSent)) {
            if (!$blnSend) {
                if (strlen($objRow->confirmationDate)) {
                    $dateConfirmation = new \Date($objRow->confirmationDate);
                    $strHint .= '<div class="tl_message"><p class="tl_info">' . sprintf($GLOBALS['TL_LANG']['tl_formdata']['confirmation_sent'], $dateConfirmation->date, $dateConfirmation->time) . '</p></div>';
                } else {
                    $strHint .= '<div class="tl_message"><p class="tl_info">' . sprintf($GLOBALS['TL_LANG']['tl_formdata']['confirmation_sent'], '-n/a-', '-n/a-') . '</p></div>';
                }
            }
        }
        // Preview Mail
        $return = '
<div id="tl_buttons">
<a href="' . $this->getReferer(ENCODE_AMPERSANDS) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBTTitle']) . '">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>
</div>

<h2 class="sub_headline">' . $GLOBALS['TL_LANG']['tl_formdata']['mail'][0] . '</h2>' . \Message::generate() . $strHint . '

<form action="' . ampersand(\Environment::get('script'), ENCODE_AMPERSANDS) . '" id="tl_formdata_send" class="tl_form" method="get">
<div class="tl_formbody_edit fd_mail_send">
<input type="hidden" name="do" value="' . \Input::get('do') . '">
<input type="hidden" name="table" value="' . \Input::get('table') . '">
<input type="hidden" name="act" value="' . \Input::get('act') . '">
<input type="hidden" name="id" value="' . \Input::get('id') . '">
<input type="hidden" name="rt" value="' . REQUEST_TOKEN . '">
<input type="hidden" name="token" value="' . $strToken . '">

<table cellpadding="0" cellspacing="0" class="prev_header" summary="">
  <tr class="row_0">
    <td class="col_0">' . $GLOBALS['TL_LANG']['tl_formdata']['mail_sender'][0] . '</td>
    <td class="col_1">' . $objMailProperties->sender . '</td>
  </tr>

  <tr class="row_1">
    <td class="col_0"><label for="ctrl_formdata_recipient">' . $GLOBALS['TL_LANG']['tl_formdata']['mail_recipient'][0] . '</label></td>
    <td class="col_1"><input name="recipient" type="ctrl_recipient" class="tl_text" value="' . implode(',', $objMailProperties->recipients) . '" ' . ($blnSend ? 'disabled="disabled"' : '') . '></td>
  </tr>

  <tr class="row_2">
    <td class="col_0">' . $GLOBALS['TL_LANG']['tl_formdata']['mail_subject'][0] . '</td>
    <td class="col_1">' . $objMailProperties->subject . '</td>
  </tr>';
        if (!empty($objMailProperties->attachments)) {
            $attachments = array();
            foreach ($objMailProperties->attachments as $strFile => $arr) {
                $attachments[] = str_replace(TL_ROOT . '/', '', $strFile);
            }
            $return .= '
  <tr class="row_3">
    <td class="col_0" style="vertical-align:top">' . $GLOBALS['TL_LANG']['tl_formdata']['attachments'] . '</td>
    <td class="col_1">' . implode(',<br> ', $attachments) . '</td>
  </tr>';
        }
        $return .= '
</table>

<h3>' . $GLOBALS['TL_LANG']['tl_formdata']['mail_body_plaintext'][0] . '</h3>
<div class="preview_plaintext">
' . nl2br($objMailProperties->messageText) . '
</div>';
        if (!empty($objMailProperties->messageHtml)) {
            $return .= '
<h3>' . $GLOBALS['TL_LANG']['tl_formdata']['mail_body_html'][0] . '</h3>
<div class="preview_html">
' . preg_replace(array('/.*?<body.*?>/si', '/<\\/body>.*$/si'), array('', ''), $objMailProperties->messageHtml) . '
</div>';
        }
        $return .= '
</div>';
        if (!$blnSend) {
            $return .= '
<div class="tl_formbody_submit">

<div class="tl_submit_container">
<input type="submit" id="send" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['tl_formdata']['mail'][0]) . '">
</div>

</div>';
        }
        $return .= '
</form>';
        return $return;
    }