public function testSendHTML() { // Set custom $project - used in email headers global $project; $oldProject = $project; $project = 'emailtest'; Email::set_mailer(new EmailTest_Mailer()); $email = new Email('*****@*****.**', '*****@*****.**', 'Test send plain', 'Testing Email->sendPlain()', null, '*****@*****.**', '*****@*****.**'); $email->attachFile(__DIR__ . '/fixtures/attachment.txt', null, 'text/plain'); $email->addCustomHeader('foo', 'bar'); $sent = $email->send(123); // Restore old project name after sending $project = $oldProject; $this->assertEquals('*****@*****.**', $sent['to']); $this->assertEquals('*****@*****.**', $sent['from']); $this->assertEquals('Test send plain', $sent['subject']); $this->assertContains('Testing Email->sendPlain()', $sent['content']); $this->assertNull($sent['plaincontent']); $this->assertEquals(array(0 => array('contents' => 'Hello, I\'m a text document.', 'filename' => 'attachment.txt', 'mimetype' => 'text/plain')), $sent['files']); $this->assertEquals(array('foo' => 'bar', 'X-SilverStripeMessageID' => 'emailtest.123', 'X-SilverStripeSite' => 'emailtest', 'Cc' => '*****@*****.**', 'Bcc' => '*****@*****.**'), $sent['customheaders']); }
public function process() { $service = singleton('QueuedJobService'); $report = $this->getReport(); if (!$report) { $this->currentStep++; $this->isComplete = true; return; } $clone = clone $report; $clone->GeneratedReportTitle = $report->ScheduledTitle; $result = $clone->prepareAndGenerate(); if ($report->ScheduleEvery) { if ($report->ScheduleEvery == 'Custom') { $interval = $report->ScheduleEveryCustom; } else { $interval = $report->ScheduleEvery; } $next = $service->queueJob(new ScheduledReportJob($report, $this->timesGenerated + 1), date('Y-m-d H:i:s', strtotime("+1 {$interval}"))); $report->QueuedJobID = $next; } else { $report->Scheduled = false; $report->QueuedJobID = 0; } $report->write(); if ($report->EmailScheduledTo) { $email = new Email(); $email->setTo($report->EmailScheduledTo); $email->setSubject($result->Title); $email->setBody(_t('ScheduledReportJob.SEE_ATTACHED_REPORT', 'Please see the attached report file')); $email->attachFile($result->PDFFile()->getFullPath(), $result->PDFFile()->Filename, 'application/pdf'); $email->send(); } $this->currentStep++; $this->isComplete = true; }
/** * Generate the e-mail object and return it * @param object * @param array * @return object */ protected function generateEmailObject(Database_Result $objNewsletter, $arrAttachments) { $objEmail = new Email(); $objEmail->from = $objNewsletter->sender; $objEmail->subject = $objNewsletter->subject; // Add sender name if (strlen($objNewsletter->senderName)) { $objEmail->fromName = $objNewsletter->senderName; } $objEmail->embedImages = !$objNewsletter->externalImages; $objEmail->logFile = 'newsletter_' . $objNewsletter->id . '.log'; // Attachments if (is_array($arrAttachments) && count($arrAttachments) > 0) { foreach ($arrAttachments as $strAttachment) { $objEmail->attachFile(TL_ROOT . '/' . $strAttachment); } } return $objEmail; }
/** * onsubmit_callback * send email */ public function onSubmitCbSendEmail() { // the save-button is a fileupload-button if (!\Input::post('saveNclose')) { return; } $email = new Email(); $fromMail = $this->User->email; $subject = \Input::post('subject'); $email->replyTo($fromMail); $email->from = $fromMail; $email->subject = $subject; $email->html = base64_decode($_POST['content']); //save attachment $arrFiles = array(); $db = $this->Database->prepare('SELECT attachment FROM tl_be_email WHERE id=?')->execute(\Input::get('id')); // Attachment if ($db->attachment != '') { $arrFiles = unserialize($db->attachment); foreach ($arrFiles as $filekey => $filename) { if (file_exists(TL_ROOT . '/' . BE_EMAIL_UPLOAD_DIR . '/' . $filekey)) { $this->Files->copy(BE_EMAIL_UPLOAD_DIR . '/' . $filekey, 'system/tmp/' . $filename); $email->attachFile(TL_ROOT . '/system/tmp/' . $filename); } } } // Cc $cc_recipients = array_unique($this->validateEmailAddresses(\Input::post('recipientsCc'), 'recipientsCc')); if (count($cc_recipients)) { $email->sendCc($cc_recipients); } // Bcc $bcc_recipients = array_unique($this->validateEmailAddresses(\Input::post('recipientsBcc'), 'recipientsBcc')); if (count($bcc_recipients)) { $email->sendBcc($bcc_recipients); } // To $recipients = array_unique($this->validateEmailAddresses(\Input::post('recipientsTo'), 'recipientsTo')); if (count($recipients)) { $email->sendTo($recipients); } // Delete attachment from server foreach ($arrFiles as $filekey => $filename) { // delete file in the tmp-folder if (is_file(TL_ROOT . '/system/tmp/' . $filename)) { $this->Files->delete('/system/tmp/' . $filename); } } }
/** * Send confirmation mail * @param integer * @param integer * @return string */ public function mail($intID = false, $ajaxId = false) { $blnSend = false; if (strlen($this->Input->get('token')) && $this->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 * " . (count($this->arrSqlDetails) > 0 ? ', ' . implode(',', array_values($this->arrSqlDetails)) : '') . " FROM " . $this->strTable . $table_alias; $sqlWhere = " WHERE id=?"; if ($sqlWhere != '') { $sqlQuery .= $sqlWhere; } $objRow = $this->Database->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 ID "' . $this->intId . '" of table "' . $this->strTable . '"!', 'DC_Table edit()', TL_ERROR); $this->redirect('typolight/main.php?act=error'); } $arrSubmitted = $objRow->fetchAssoc(); $arrFiles = array(); // Form $intFormId = 0; if (count($GLOBALS['TL_DCA'][$this->strTable]['tl_formdata']['detailFields'])) { // try to get Form ID foreach ($GLOBALS['TL_DCA'][$this->strTable]['tl_formdata']['detailFields'] as $strField) { if ($intFormId > 0) { break; } if (strlen($GLOBALS['TL_DCA'][$this->strTable]['fields'][$strField]['f_id'])) { $intFormId = intval($GLOBALS['TL_DCA'][$this->strTable]['fields'][$strField]['f_id']); $objForm = $this->Database->prepare("SELECT * FROM tl_form WHERE id=?")->limit(1)->execute($intFormId); } } } if ($intFormId == 0) { $objForm = $this->Database->prepare("SELECT * FROM tl_form WHERE title=?")->limit(1)->execute($arrSubmitted['form']); } if ($objForm->numRows < 1) { $this->log('Could not load form by ID ' . $intFormId . ' or title "' . $arrSubmitted['form'] . '" of table "tl_form"!', 'DC_Formdata mail()', TL_ERROR); $this->redirect('typolight/main.php?act=error'); } $arrForm = $objForm->fetchAssoc(); if (strlen($arrForm['id'])) { $arrFormFields = $this->FormData->getFormfieldsAsArray($arrForm['id']); } // Types of form fields with storable data $arrFFstorable = $this->FormData->arrFFstorable; 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->import('String'); $messageText = ''; $messageHtml = ''; $messageHtmlTmpl = ''; $strRecipient = ''; $arrRecipient = array(); $sender = ''; $senderName = ''; $attachments = array(); $blnSkipEmpty = $arrForm['confirmationMailSkipEmpty'] ? true : false; $blnStoreOptionsValues = $arrForm['efgStoreValues'] ? true : false; $dirImages = ''; $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']; if (strlen($recipientFieldName) && $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->prepareDbValForWidget($varRecipient, $arrFormFields[$recipientFieldName], false); if (count($arrRecipient)) { $varRecipient = implode(', ', $arrRecipient); } unset($arrRecipient); } } $varRecipient = str_replace('|', ',', $varRecipient); } if (strlen($varRecipient) || strlen($arrForm['confirmationMailRecipient'])) { $arrRecipient = array_unique(array_merge(trimsplit(',', $varRecipient), trimsplit(',', $arrForm['confirmationMailRecipient']))); } if ($this->Input->get('recipient')) { $arrRecipient = array_unique(trimsplit(',', $this->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 = $this->Database->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); $strRecipient = implode(', ', $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' $subject = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $subject); if (strlen($messageText)) { $messageText = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $messageText); } if (strlen($messageHtml)) { $messageHtml = preg_replace(array('/\\{\\{/', '/\\}\\}/'), array('__BRCL__', '__BRCR__'), $messageHtml); } // replace 'condition tags' $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('/{{[^{}]+}}/i', $messageText . $messageHtml . $subject . $sender, $tags); preg_match_all('/__BRCL__.*?__BRCR__/si', $messageText . $messageHtml . $subject . $sender, $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('/^{{/i', '/}}$/i'), array('',''), $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]; $strType = $arrField['type']; if (!isset($arrFormFields[$strKey]) && in_array($strKey, $this->arrBaseFields)) { $arrField = $GLOBALS['TL_DCA'][$this->strTable]['fields'][$strKey]; $strType = $arrField['inputType']; } $strLabel = ''; $strVal = ''; if ($arrTagParams && strlen($arrTagParams['label'])) { $strLabel = $arrTagParams['label']; } if (in_array($strType, $arrFFstorable)) { if ($strType == 'efgImageSelect') { $varText = ''; $varHtml = ''; if (strlen($arrSubmitted[$strKey]) || is_array($arrSubmitted[$strKey])) { $varVal = $this->FormData->prepareDbValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]); foreach ($varVal as $k => $strVal) { if (strlen($strVal)) { $varText[] = $this->Environment->base . $strVal; $varHtml[] = '<img src="' . $strVal . '">'; } } if (is_array($varText)) { $varText = implode(', ', $varText); $varHtml = implode(', ', $varHtml); } } if (!strlen($varText) && $blnSkipEmpty) { $strLabel = ''; } $subject = str_replace($tag, $strLabel . $varText, $subject); $messageText = str_replace($tag, $strLabel . $varText, $messageText); $messageHtml = str_replace($tag, $strLabel . $varHtml, $messageHtml); unset($varText); unset($varHtml); } elseif ($strType == 'upload') { if (strlen($arrSubmitted[$strKey])) { if (!array_key_exists($strKey, $arrFiles)) { $objFile = new File($arrSubmitted[$strKey]); if ($objFile->size) { $arrFiles[$strKey] = array('tmp_name' => $objFile->value, 'file' => $objFile->value, 'name' => $objFile->basename, 'mime' => $objFile->mime); } } } if ($arrTagParams && (array_key_exists('attachment', $arrTagParams) && $arrTagParams['attachment'] == true || array_key_exists('attachement', $arrTagParams) && $arrTagParams['attachement'] == true)) { if (array_key_exists($strKey, $arrFiles) && strlen($arrFiles[$strKey]['name'])) { if (!count($attachments) || !in_array($arrFiles[$strKey]['file'], $attachments)) { $attachments[] = $arrFiles[$strKey]['file']; } } $strVal = ''; } else { $strVal = $this->FormData->prepareDbValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]); $strVal = $this->formatValue($strKey, $strVal); } if (!strlen($strVal) && $blnSkipEmpty) { $strLabel = ''; } $subject = str_replace($tag, $strLabel . $strVal, $subject); $messageText = str_replace($tag, $strLabel . $strVal, $messageText); $messageHtml = str_replace($tag, $strLabel . $strVal, $messageHtml); } else { $strVal = $this->FormData->prepareDbValForMail($arrSubmitted[$strKey], $arrField, $arrFiles[$strKey]); $strVal = $this->formatValue($strKey, $strVal); if (!strlen($strVal) && $blnSkipEmpty) { $strLabel = ''; } $messageText = str_replace($tag, $strLabel . $strVal, $messageText); if (!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); } break; } } // Replace standard insert tags and eval condition tags 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); } } 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); } } 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 sender if (strlen($sender)) { $sender = $this->replaceInsertTags($sender); } $confEmail = new Email(); $confEmail->from = $sender; if (strlen($senderName)) { $confEmail->fromName = $senderName; } $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); // did the saved value result in an array? if (is_array($arrCustomAttachments)) { foreach ($arrCustomAttachments as $strFile) { // does the file really exist? if (is_file(TL_ROOT . '/' . $strFile)) { // can we read the file? if (is_readable(TL_ROOT . '/' . $strFile)) { $objFile = new File($strFile); if ($objFile->size) { $attachments[] = $objFile->value; } } } } } } } if (is_array($attachments) && count($attachments) > 0) { foreach ($attachments as $attachment) { $confEmail->attachFile(TL_ROOT . '/' . $attachment); } } if ($dirImages != '') { $confEmail->imageDir = $dirImages; } if ($messageText != '') { $messageText = html_entity_decode($messageText, ENT_QUOTES, $GLOBALS['TL_CONFIG']['characterSet']); $messageText = strip_tags($messageText); $confEmail->text = $messageText; } if ($messageHtml != '') { $confEmail->html = $messageHtml; } // Send Mail if (strlen($this->Input->get('token')) && $this->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 (count($arrRecipient) > 0) { $arrSentTo = array(); foreach ($arrRecipient 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]; } } $confEmail->sendTo($recipient); $blnConfirmationSent = true; $_SESSION['TL_INFO'][] = sprintf($GLOBALS['TL_LANG']['tl_formdata']['mail_sent'], str_replace(array('<', '>'), array('[', ']'), $recipient)); } } $url = $this->Environment->base . preg_replace('/&(amp;)?(token|recipient)=[^&]*/', '', $this->Environment->request); if ($blnConfirmationSent && isset($this->intId) && intval($this->intId) > 0) { $arrUpd = array('confirmationSent' => '1', 'confirmationDate' => time()); $res = $this->Database->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']['backBT']) . '">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a> </div> <h2 class="sub_headline">' . $GLOBALS['TL_LANG']['tl_formdata']['mail'][0] . '</h2>' . $this->getMessages() . $strHint . ' <form action="' . ampersand($this->Environment->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="' . $this->Input->get('do') . '"> <input type="hidden" name="table" value="' . $this->Input->get('table') . '"> <input type="hidden" name="act" value="' . $this->Input->get('act') . '"> <input type="hidden" name="id" value="' . $this->Input->get('id') . '"> <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">' . $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="' . $strRecipient . '" ' . ($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">' . $subject . '</td> </tr>'; if (is_array($attachments) && count($attachments) > 0) { $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($messageText) . ' </div>'; if (strlen($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('', ''), $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; }
/** * Attaches the given files to the given email. * * @param Email $email Email * @param array $attachments Attachments * * @return void * * @author Sebastian Diel <*****@*****.**> * @since 26.08.2011 */ protected static function attachFiles(Email $email, $attachments) { if (!is_null($attachments)) { if (is_array($attachments)) { foreach ($attachments as $attachment) { if (is_array($attachment)) { $filename = $attachment['filename']; $attachedFilename = array_key_exists('attachedFilename', $attachment) ? $attachment['attachedFilename'] : basename($filename); $mimetype = array_key_exists('mimetype', $attachment) ? $attachment['mimetype'] : null; } else { $filename = $attachment; $attachedFilename = basename($attachment); $mimetype = null; } $email->attachFile($filename, $attachedFilename, $mimetype); } } else { $email->attachFile($attachments, basename($attachments)); } } }
public function process() { self::$config = $this->config(); if (!self::$config->wkHtmlToPdfPath) { throw new Exception("You must provide a path for WkHtmlToPdf in your sites configuration."); } if (!self::$config->emailAddress) { throw new Exception("You must provide an email address to send from in your sites configuration."); } increase_memory_limit_to('1024M'); set_time_limit(0); $sites = LinkCheckSite::get(); $outputDir = BASE_PATH . DIRECTORY_SEPARATOR . "silverstripe-linkcheck/runs/"; $filesCreated = array(); // build the crawler chdir(__DIR__ . "/../thirdparty"); exec("javac " . self::$crawler . " " . self::$linkStats . " && " . "javac " . self::$linkProject); if ($sites) { foreach ($sites as $site) { echo "Checking " . $site->SiteURL . "\r\n"; $url = $site->SiteURL; // if the output directory doesn't exist for the run, create it if (!file_exists($outputDir . str_replace("http://", "", $url))) { mkdir($outputDir . str_replace("http://", "", $url)); } $filename = date("Y-m-d") . '-' . rand(0, 1000) . ".html"; $filepath = $outputDir . str_replace("http://", "", $url) . '/'; // execute the crawler exec("java Project {$url} " . $filepath . $filename . " 10 1000"); $filesCreated[$site->ID]['FilePath'] = $filepath; $filesCreated[$site->ID]['FileName'] = $filename; $filesCreated[$site->ID]['SiteName'] = $site->SiteName; $filesCreated[$site->ID]['ID'] = $site->ID; $filesCreated[$site->ID]['URL'] = $url; $emailRecipients = $site->EmailRecipients(); if ($emailRecipients) { foreach ($emailRecipients as $recipient) { $filesCreated[$site->ID]['Email'][] = $recipient->Email; } } } foreach ($filesCreated as $file) { Folder::find_or_make("LinkCheck" . DIRECTORY_SEPARATOR . $file['SiteName'] . DIRECTORY_SEPARATOR); $pdfPath = "assets" . DIRECTORY_SEPARATOR . "LinkCheck" . DIRECTORY_SEPARATOR . $file['SiteName'] . DIRECTORY_SEPARATOR; $pdfFullPath = BASE_PATH . DIRECTORY_SEPARATOR . $pdfPath; $pdfName = str_replace("html", "pdf", $file['FileName']); $generator = new WkHtml\Generator(new \Knp\Snappy\Pdf(self::$config->wkHtmlToPdfPath), new WkHtml\Input\String(file_get_contents($file['FilePath'] . $file['FileName'])), new WkHtml\Output\File($pdfFullPath . $pdfName, 'application/pdf')); $generator->process(); $site = LinkCheckSite::get()->byID($file['ID']); $pdfUpload = new File(); $pdfUpload->Title = $file['SiteName'] . '-' . $pdfName; $pdfUpload->Filename = $pdfPath . $pdfName; $pdfUpload->write(); $linkCheckRun = new LinkCheckRun(); $linkCheckRun->LinkCheckFileID = $pdfUpload->ID; $linkCheckRun->LinkCheckSiteID = $site->ID; $linkCheckRun->write(); $site->LinkCheckRuns()->add($linkCheckRun); foreach ($file['Email'] as $emailAddress) { $email = new Email(); $email->to = $emailAddress; $email->from = $this->config()->emailAddress; $email->subject = $file['SiteName'] . " link check run"; $email->body = "Site Link Check Run for {$file['URL']} on " . date("Y/m/d"); $email->attachFile($pdfPath . $pdfName, "linkcheck.pdf"); $email->send(); } unlink($file['FilePath'] . $file['FileName']); } } }