silverstripe-framework/email/Email.php

781 lines
22 KiB
PHP
Raw Normal View History

<?php
/**
* @package sapphire
* @subpackage email
*/
if(isset($_SERVER['SERVER_NAME'])) {
/**
* X-Mailer header value on emails sent
*/
define('X_MAILER', 'SilverStripe Mailer - version 2006.06.21 (Sent from "'.$_SERVER['SERVER_NAME'].'")');
} else {
/**
* @ignore
*/
define('X_MAILER', 'SilverStripe Mailer - version 2006.06.21');
}
// Note: The constant 'BOUNCE_EMAIL' should be defined as a valid email address for where bounces should be returned to.
/**
* Class to support sending emails.
* @package sapphire
* @subpackage email
*/
class Email extends ViewableData {
/**
* @param string $from Email-Address
*/
protected $from;
/**
* @param string $to Email-Address. Use comma-separation to pass multiple email-addresses.
*/
protected $to;
/**
* @param string $subject Subject of the email
*/
protected $subject;
/**
* @param string $body HTML content of the email.
* Passed straight into {@link $ss_template} as $Body variable.
*/
protected $body;
/**
* @param string $plaintext_body Optional string for plaintext emails.
* If not set, defaults to converting the HTML-body with {@link Convert::xml2raw()}.
*/
protected $plaintext_body;
/**
* @param string $cc
*/
protected $cc;
/**
* @param string $bcc
*/
protected $bcc;
/**
* @param Mailer $mailer Instance of a {@link Mailer} class.
*/
protected static $mailer;
/**
* This can be used to provide a mailer class other than the default, e.g. for testing.
*
* @param Mailer $mailer
*/
static function set_mailer(Mailer $mailer) {
self::$mailer = $mailer;
}
/**
* Get the mailer.
*
* @return Mailer
*/
static function mailer() {
if(!self::$mailer) self::$mailer = new Mailer();
return self::$mailer;
}
/**
* @param array $customHeaders A map of header-name -> header-value
*/
protected $customHeaders = array();
/**
* @param array $attachements Internal, use {@link attachFileFromString()} or {@link attachFile()}
*/
protected $attachments = array();
/**
* @param boolean $
*/
protected $parseVariables_done = false;
/**
* @param string $ss_template The name of the used template (without *.ss extension)
*/
protected $ss_template = "GenericEmail";
/**
* @param array $template_data Additional data available in a template.
* Used in the same way than {@link ViewableData->customize()}.
*/
protected $template_data = null;
/**
* @param string $bounceHandlerURL
*/
protected $bounceHandlerURL = null;
/**
* @param sring $admin_email_address The default administrator email address.
* This will be set in the config on a site-by-site basis
*/
static $admin_email_address = '';
/**
* @param string $send_all_emails_to Email-Address
*/
protected static $send_all_emails_to = null;
/**
* @param string $bcc_all_emails_to Email-Address
*/
protected static $bcc_all_emails_to = null;
/**
* @param string $cc_all_emails_to Email-Address
*/
protected static $cc_all_emails_to = null;
/**
* Create a new email.
*/
public function __construct($from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null) {
$this->from = $from;
$this->to = $to;
$this->subject = $subject;
$this->body = $body;
$this->cc = $cc;
$this->bcc = $bcc;
$this->setBounceHandlerURL($bounceHandlerURL);
}
public function attachFileFromString($data, $filename, $mimetype = null) {
$this->attachments[] = array(
'contents' => $data,
'filename' => $filename,
'mimetype' => $mimetype,
);
}
public function setBounceHandlerURL( $bounceHandlerURL ) {
if($bounceHandlerURL) {
$this->bounceHandlerURL = $bounceHandlerURL;
} else {
$this->bounceHandlerURL = $_SERVER['HTTP_HOST'] . Director::baseURL() . 'Email_BounceHandler';
}
}
public function attachFile($filename, $attachedFilename = null, $mimetype = null) {
$absoluteFileName = Director::getAbsFile($filename);
if(file_exists($absoluteFileName)) {
$this->attachFileFromString(file_get_contents($absoluteFileName), $attachedFilename, $mimetype);
} else {
user_error("Could not attach '$absoluteFileName' to email. File does not exist.", E_USER_NOTICE);
}
}
/**
* @deprecated 2.3 Not used anywhere else
*/
public function setFormat($format) {
user_error('Email->setFormat() is deprecated', E_USER_NOTICE);
}
public function Subject() {
return $this->subject;
}
public function Body() {
return $this->body;
}
public function To() {
return $this->to;
}
public function From() {
return $this->from;
}
public function Cc() {
return $this->cc;
}
public function Bcc() {
return $this->bcc;
}
public function setSubject($val) {
$this->subject = $val;
}
public function setBody($val) {
$this->body = $val;
}
public function setTo($val) {
$this->to = $val;
}
public function setFrom($val) {
$this->from = $val;
}
public function setCc($val) {
$this->cc = $val;
}
public function setBcc($val) {
$this->bcc = $val;
}
/**
* Set the "Reply-To" header with an email address.
* @param string $email The email address of the "Reply-To" header
*/
public function replyTo($email) {
$this->addCustomHeader('Reply-To', $email);
}
/**
* Add a custom header to this value.
* Useful for implementing all those cool features that we didn't think of.
*/
public function addCustomHeader($headerName, $headerValue) {
if($headerName == 'Cc') $this->cc = $headerValue;
else if($headerName == 'Bcc') $this->bcc = $headerValue;
else {
if(isset($this->customHeaders[$headerName])) $this->customHeaders[$headerName] .= ", " . $headerValue;
else $this->customHeaders[$headerName] = $headerValue;
}
}
public function BaseURL() {
return Director::absoluteBaseURL();
}
/**
* Debugging help
*/
public function debug() {
$this->parseVariables();
return "<h2>Email template $this->class</h2>\n" .
"<p><b>From:</b> $this->from\n" .
"<b>To:</b> $this->to\n" .
"<b>Cc:</b> $this->cc\n" .
"<b>Bcc:</b> $this->bcc\n" .
"<b>Subject:</b> $this->subject</p>" .
$this->body;
}
/**
* Set template name (without *.ss extension).
*
* @param string $template
*/
public function setTemplate($template) {
$this->ss_template = $template;
}
/**
* @return string
*/
public function getTemplate() {
return $this->ss_template;
}
protected function templateData() {
if($this->template_data) {
return $this->template_data->customise(array(
"To" => $this->to,
"Cc" => $this->cc,
"Bcc" => $this->bcc,
"From" => $this->from,
"Subject" => $this->subject,
"Body" => $this->body,
"BaseURL" => $this->BaseURL(),
"IsEmail" => true,
));
} else {
return $this;
}
}
/**
* Used by {@link SSViewer} templates to detect if we're rendering an email template rather than a page template
*/
public function IsEmail() {
return true;
}
/**
* Populate this email template with values.
* This may be called many times.
*/
function populateTemplate($data) {
if($this->template_data) {
$this->template_data = $this->template_data->customise($data);
} else {
if(is_array($data)) $data = new ArrayData($data);
$this->template_data = $this->customise($data);
}
$this->parseVariables_done = false;
}
/**
* Load all the template variables into the internal variables, including
* the template into body. Called before send() or debugSend()
* $isPlain=true will cause the template to be ignored, otherwise the GenericEmail template will be used
* and it won't be plain email :)
*/
protected function parseVariables($isPlain = false) {
SSViewer::set_source_file_comments(false);
if(!$this->parseVariables_done) {
$this->parseVariables_done = true;
// Parse $ variables in the base parameters
$data = $this->templateData();
foreach(array('from','to','subject','body', 'plaintext_body', 'cc', 'bcc') as $param) {
$template = SSViewer::fromString($this->$param);
$this->$param = $template->process($data);
}
// Process a .SS template file
$fullBody = $this->body;
if($this->ss_template && !$isPlain) {
// Requery data so that updated versions of To, From, Subject, etc are included
$data = $this->templateData();
$template = new SSViewer($this->ss_template);
if($template->exists()) {
$fullBody = $template->process($data);
}
}
// Rewrite relative URLs
$this->body = HTTP::absoluteURLs($fullBody);
}
}
/**
* @desc Validates the email address. Returns true of false
*/
static function validEmailAddress($address) {
return ereg('^([a-zA-Z0-9_+\.\-]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$', $address);
}
/**
* Send the email in plaintext.
*
* @see send() for sending emails with HTML content.
* @uses Mailer->sendPlain()
*
* @param string $messageID Optional message ID so the message can be identified in bounces etc.
* @return bool Success of the sending operation from an MTA perspective.
* Doesn't actually give any indication if the mail has been delivered to the recipient properly)
*/
function sendPlain($messageID = null) {
Requirements::clear();
$this->parseVariables(true);
if(empty($this->from)) $this->from = Email::getAdminEmail();
$this->setBounceHandlerURL($this->bounceHandlerURL);
$headers = $this->customHeaders;
$headers['X-SilverStripeBounceURL'] = $this->bounceHandlerURL;
if($messageID) $headers['X-SilverStripeMessageID'] = project() . '.' . $messageID;
if(project()) $headers['X-SilverStripeSite'] = project();
$to = $this->to;
$subject = $this->subject;
if(self::$send_all_emails_to) {
$subject .= " [addressed to $to";
$to = self::$send_all_emails_to;
if($this->cc) $subject .= ", cc to $this->cc";
if($this->bcc) $subject .= ", bcc to $this->bcc";
$subject .= ']';
} else {
if($this->cc) $headers['Cc'] = $this->cc;
if($this->bcc) $headers['Bcc'] = $this->bcc;
}
if(self::$cc_all_emails_to) {
if(!empty($headers['Cc']) && trim($headers['Cc'])) {
$headers['Cc'] .= ', ' . self::$cc_all_emails_to;
} else {
$headers['Cc'] = self::$cc_all_emails_to;
}
}
if(self::$bcc_all_emails_to) {
if(!empty($headers['Bcc']) && trim($headers['Bcc'])) {
$headers['Bcc'] .= ', ' . self::$bcc_all_emails_to;
} else {
$headers['Bcc'] = self::$bcc_all_emails_to;
}
}
Requirements::restore();
return self::mailer()->sendPlain($to, $this->from, $subject, $this->body, $this->attachments, $headers);
}
/**
* Send the email.
*/
public function send($messageID = null) {
Requirements::clear();
$this->parseVariables();
if(empty($this->from)) $this->from = Email::getAdminEmail();
$this->setBounceHandlerURL( $this->bounceHandlerURL );
$headers = $this->customHeaders;
$headers['X-SilverStripeBounceURL'] = $this->bounceHandlerURL;
if($messageID) $headers['X-SilverStripeMessageID'] = project() . '.' . $messageID;
if(project()) $headers['X-SilverStripeSite'] = project();
$to = $this->to;
$subject = $this->subject;
if(self::$send_all_emails_to) {
$subject .= " [addressed to $to";
$to = self::$send_all_emails_to;
if($this->cc) $subject .= ", cc to $this->cc";
if($this->bcc) $subject .= ", bcc to $this->bcc";
$subject .= ']';
unset($headers['Cc']);
unset($headers['Bcc']);
} else {
if($this->cc) $headers['Cc'] = $this->cc;
if($this->bcc) $headers['Bcc'] = $this->bcc;
}
if(self::$cc_all_emails_to) {
if(!empty($headers['Cc']) && trim($headers['Cc'])) {
$headers['Cc'] .= ', ' . self::$cc_all_emails_to;
} else {
$headers['Cc'] = self::$cc_all_emails_to;
}
}
if(self::$bcc_all_emails_to) {
if(!empty($headers['Bcc']) && trim($headers['Bcc'])) {
$headers['Bcc'] .= ', ' . self::$bcc_all_emails_to;
} else {
$headers['Bcc'] = self::$bcc_all_emails_to;
}
}
Requirements::restore();
return self::mailer()->sendHTML($to, $this->from, $subject, $this->body, $this->attachments, $headers, $this->plaintext_body);
}
/**
* Used as a default sender address in the {@link Email} class
* unless overwritten. Also shown to users on live environments
* as a contact address on system error pages.
*
Merging in refactored Translatable architecture from trunk, including related/required changesets like enhancements to Object static handling (see details below) ------------------------------------------------------------------------ r68900 | sminnee | 2008-12-15 14:30:41 +1300 (Mon, 15 Dec 2008) | 1 line Static caching merges from dnc branch ------------------------------------------------------------------------ r68917 | sminnee | 2008-12-15 14:49:06 +1300 (Mon, 15 Dec 2008) | 1 line Merged Requirements fix from nestedurls branch ------------------------------------------------------------------------ r70033 | aoneil | 2009-01-13 14:03:41 +1300 (Tue, 13 Jan 2009) | 2 lines Add translation migration task ------------------------------------------------------------------------ r70072 | ischommer | 2009-01-13 17:34:27 +1300 (Tue, 13 Jan 2009) | 5 lines API CHANGE Removed obsolete internal Translatable methods: hasOwnTranslatableFields(), allFieldsInTable() ENHANCEMENT Removed $create flag in Translatable::getTranslation() and replaced with explit action createTranslation() ENHANCEMENT Sorting return array of Translatable::getTranslatedLangs() ENHANCEMENT Added a note about saving a page before creating a translation MINOR Added phpdoc to Translatable ------------------------------------------------------------------------ r70073 | ischommer | 2009-01-13 17:34:45 +1300 (Tue, 13 Jan 2009) | 1 line ENHANCEMENT Added basic unit tests to new Translatable API ------------------------------------------------------------------------ r70080 | aoneil | 2009-01-13 18:04:21 +1300 (Tue, 13 Jan 2009) | 3 lines BUGFIX: Fix translatable migration regenerating URLSegments when it shouldn't BUGFIX: Fix translatable migration not writing records to Live properly ------------------------------------------------------------------------ r70118 | ischommer | 2009-01-14 11:28:24 +1300 (Wed, 14 Jan 2009) | 3 lines API CHANGE Removed obsolete Translatable::table_exists() ENHANCEMENT Made Translatable constructor arguments optional, as by default all database fields are marked translatable MINOR More unit tests for Translatable ------------------------------------------------------------------------ r70138 | ischommer | 2009-01-14 17:00:30 +1300 (Wed, 14 Jan 2009) | 1 line BUGFIX Disabled assumption that SQLQuery->filtersOnID() should only kick in when exactly one WHERE clause is given - this is very fragile and hard to test. It would return TRUE on $where = "SiteTree.ID = 5", but not on $where = array("Lang = 'de'", "SiteTree.ID = 5") ------------------------------------------------------------------------ r70214 | ischommer | 2009-01-15 18:56:25 +1300 (Thu, 15 Jan 2009) | 3 lines BUGFIX Falling back to Translatable::current_lang() if no $context object is given, in augmentAllChildrenIncludingDeleted() and AllChildrenIncludingDeleted() MINOR phpdoc for Translatable MINOR Added more Translatable unit tests ------------------------------------------------------------------------ r70306 | ischommer | 2009-01-16 17:14:34 +1300 (Fri, 16 Jan 2009) | 9 lines ENHANCEMENT Recursively creating translations for parent pages to ensure that a translated page is still accessible by traversing the tree, e.g. in "cms translation mode" (in Translatable->onBeforeWrite()) ENHANCEMENT Simplified AllChildrenIncludingDeleted() to not require a special augmentAllChildrenIncludingDeleted() implementation: We don't combine untranslated/translated children any longer (which was used in CMS tree view), but rather just show translated records ENHANCEMENT Ensuring uniqueness of URL segments by appending "-<langcode>" to new translations (in Translatable->onBeforeWrite()) ENHANCEMENT Added Translatable->alternateGetByUrl() as a hook into SiteTree::get_by_url() ENHANCEMENT Adding link back to original page in CMS editform for translations BUGFIX Excluding HiddenField instances from Translatable->updateCMSFields() BUGFIX Don't require a record to be written (through exists()) when checking Translatable->isTranslation() or Translatable->hasTranslation() MINOR Don't use createMethod() shortcut for Translatable->AllChildrenIncludingDeleted() MINOR Added Translatable unit tests ------------------------------------------------------------------------ r70318 | ischommer | 2009-01-19 11:46:16 +1300 (Mon, 19 Jan 2009) | 1 line BUGFIX Reverted special cases for Translatable in Versioned->canBeVersioned() (originally committed in r42119) - was checking for existence of underscores in table names as an indication of the "_lang" suffix, which is no longer needed. It was also a flawed assumption which tripped over classes like TranslatableTest_TestPage ------------------------------------------------------------------------ r70319 | ischommer | 2009-01-19 11:47:02 +1300 (Mon, 19 Jan 2009) | 1 line ENHANCEMENT Disabled Translatab-e>augmentWrite() - was only needed for the blacklist fields implementation which is inactive for the moment ------------------------------------------------------------------------ r70326 | ischommer | 2009-01-19 14:25:23 +1300 (Mon, 19 Jan 2009) | 2 lines ENHANCEMENT Making ErrorPage static HTML files translatable (#2233) ENHANCEMENT Added ErrorPage::$static_filepath to flexibly set location of static error pages (defaults to /assets) ------------------------------------------------------------------------ r70327 | ischommer | 2009-01-19 15:18:41 +1300 (Mon, 19 Jan 2009) | 1 line FEATURE Enabled specifying a language through a hidden field in SearchForm which limits the search to pages in this language (incl. unit tests) ------------------------------------------------------------------------ r71258 | sharvey | 2009-02-03 15:49:34 +1300 (Tue, 03 Feb 2009) | 2 lines BUGFIX: Fix translatable being enabled when it shouldn't be ------------------------------------------------------------------------ r71340 | ischommer | 2009-02-04 14:36:12 +1300 (Wed, 04 Feb 2009) | 1 line BUGFIX Including Hierarchy->children in flushCache() and renamed to _cache_children. This caused problems in TranslatableTest when re-using the same SiteTree->Children() method with different languages on the same object (even with calling flushCache() inbetween the calls) ------------------------------------------------------------------------ r71567 | gmunn | 2009-02-10 13:49:16 +1300 (Tue, 10 Feb 2009) | 1 line 'URLSegment' on line 484 and 494 now escaped ------------------------------------------------------------------------ r72054 | ischommer | 2009-02-23 10:30:41 +1300 (Mon, 23 Feb 2009) | 3 lines BUGFIX Fixed finding a translated homepage without an explicit URLSegment (e.g. http://mysite.com/?lang=de) - see #3540 ENHANCEMENT Added Translatable::get_homepage_urlsegment_by_language() ENHANCEMENT Added RootURLController::get_default_homepage_urlsegment() ------------------------------------------------------------------------ r72367 | ischommer | 2009-03-03 11:13:30 +1300 (Tue, 03 Mar 2009) | 2 lines ENHANCEMENT Added i18n::get_lang_from_locale() and i18n::convert_rfc1766() ENHANCEMENT Using IETF/HTTP compatible "long" language code in SiteTree->MetaTags(). This means the default <meta type="content-language..."> value will be "en-US" instead of "en". The locale can be either set through the Translatable content language, or through i18n::set_locale() ------------------------------------------------------------------------ r73036 | sminnee | 2009-03-14 13:16:32 +1300 (Sat, 14 Mar 2009) | 1 line ENHANCEMENT #3032 ajshort: Use static methods for accessing static data ------------------------------------------------------------------------ r73059 | sminnee | 2009-03-15 14:09:59 +1300 (Sun, 15 Mar 2009) | 2 lines ENHANCEMENT: Added Object::clearCache() to clear a cache BUGFIX: Make object cache testing more robust ------------------------------------------------------------------------ r73338 | ischommer | 2009-03-19 05:13:40 +1300 (Thu, 19 Mar 2009) | 9 lines API CHANGE Added concept of "translation groups" to Translatable- every page can belong to a group of related translations, rather than having an explicit "original", meaning you can have pages in "non-default" languages which have no representation in other language trees. This group is recorded in a new table "<classname>_translationgroups". Translatable->createTranslation() and Translatable->onBeforeWrite() will automatically associate records in this groups. Added Translatable->addTranslationGroup(), Translatable->removeTranslationGroup(), Translatable->getTranslationGroup() API CHANGE Removed Translatable->isTranslation() - after the new "translation group" model, every page is potentially a translation API CHANGE Translatable->findOriginalIDs(), Translatable->setOriginalPage(), Translatable->getOriginalPage() ENHANCEMENT Translatable->getCMSFields() will now always show the "create translation" option, not only on default languages - meaning you can create translations based on other translations ENHANCEMENT Translatable language dropdown in CMS will always show all available languages, rather than filtering by already existing translations ENHANCEMENT Added check for an existing record in Translatable->createTranslation() BUGFIX Removed Translatable->getLang() which overloaded the $db property - it was causing side effects during creation of SiteTree default records. BUGFIX Added check in Translatable->augmentSQL() to avoid reapplying "Lang = ..." filter twice BUGFIX Removed bypass in Translatable->AllChildrenIncludingDeleted() ------------------------------------------------------------------------ r73339 | ischommer | 2009-03-19 05:15:46 +1300 (Thu, 19 Mar 2009) | 1 line BUGFIX Disabled "untranslated" CSS class for SiteTree elements - doesn't apply any longer with the new "translation groups" concept ------------------------------------------------------------------------ r73341 | ischommer | 2009-03-19 06:01:51 +1300 (Thu, 19 Mar 2009) | 1 line BUGFIX Disabled auto-excluding of default language from the "available languages" array in LanguageDropdownField - due to the new "translation groups" its possible to have a translation from another language into the default language ------------------------------------------------------------------------ r73342 | ischommer | 2009-03-19 06:13:23 +1300 (Thu, 19 Mar 2009) | 4 lines BUGFIX Setting ParentID of translated record if recursively creating parents in Translatable::onBeforeWrite() BUGFIX Fixing inline form action for "create translation" BUGFIX Removed link to "original page" for a translation - no longer valid MINOR documentation for Translatable ------------------------------------------------------------------------ r73464 | ischommer | 2009-03-20 20:51:00 +1300 (Fri, 20 Mar 2009) | 1 line MINOR documentation ------------------------------------------------------------------------ r73465 | ischommer | 2009-03-20 20:58:52 +1300 (Fri, 20 Mar 2009) | 1 line BUGFIX Fixed Hierarchy->Children() testing in TranslatableTest - with the new datamodel you can't call Children() in a different language regardless of Translatable::set_reading_lang(), the Children() call has to be made from a parent in the same language ------------------------------------------------------------------------ r73466 | ischommer | 2009-03-20 21:36:40 +1300 (Fri, 20 Mar 2009) | 2 lines ENHANCEMENT Added Translatable::get_locale_from_lang(), Translatable::get_common_locales(), $common_locales and $likely_subtags in preparation to switch Translatable from using short "lang" codes to proper long locales API CHANGE Deprecated Translatable::set_default_lang(), Translatable::default_lang() ------------------------------------------------------------------------ r73467 | ischommer | 2009-03-20 21:38:57 +1300 (Fri, 20 Mar 2009) | 1 line ENHANCEMENT Supporting "Locale-English" and "Locale-Native" as listing arguments in LanguageDropdownField ------------------------------------------------------------------------ r73468 | ischommer | 2009-03-20 21:47:06 +1300 (Fri, 20 Mar 2009) | 7 lines ENHANCEMENT Adjusted SearchForm, Debug, ErrorPage, SiteTree to using locales instead of lang codes API CHANGE Changed Translatable datamodel to use locales ("en_US") instead of lang values ("en). API CHANGE Changed Translatable::$default_lang to $default_locale, Translatable::$reading_lang to $reading_locale API CHANGE Using "locale" instead of "lang" in Translatable::choose_site_lang() to auto-detect language from cookies or GET parameters API CHANGE Deprecated Translatable::is_default_lang(), set_default_lang(), get_default_lang(), current_lang(), set_reading_lang(), get_reading_lang(), get_by_lang(), get_one_by_lang() API CHANGE Removed Translatable::get_original() - with the new "translation groups" concept there no longer is an original for a translation BUGFIX Updated MigrateTranslatableTask to new Locale based datamodel ------------------------------------------------------------------------ r73470 | ischommer | 2009-03-20 21:56:57 +1300 (Fri, 20 Mar 2009) | 1 line MINOR fixed typo ------------------------------------------------------------------------ r73472 | sminnee | 2009-03-21 17:30:04 +1300 (Sat, 21 Mar 2009) | 1 line BUGFIX: Fixed translatable test execution by making protected methods public ------------------------------------------------------------------------ r73473 | sminnee | 2009-03-21 18:10:05 +1300 (Sat, 21 Mar 2009) | 1 line ENHANCEMENT: Added Object::combined_static(), which gets all values of a static property from each class in the hierarchy ------------------------------------------------------------------------ r73883 | ischommer | 2009-04-01 08:32:19 +1300 (Wed, 01 Apr 2009) | 1 line BUGFIX Making $_SINGLETONS a global instead of a static in Core.php so it can be re-used in other places ------------------------------------------------------------------------ r73951 | ischommer | 2009-04-02 05:35:32 +1300 (Thu, 02 Apr 2009) | 3 lines API CHANGE Deprecated Translatable::enable() and i18n::enable()- use Object::add_extension('SiteTree','Translatable'), Deprecated Translatable::disable() and i18n::disable() - use Object::remove_extension('SiteTree','Translatable'), Deprecated Translatable::enabled() - use $myPage->hasExtension('Translatable') API CHANGE Removed Translatable::creating_from() - doesn't apply any longer ENHANCEMENT Translatable extension is no longer hooked up to SiteTree by default, which should improve performance and memory usage for sites not using Translatable. Please use Object::add_extension('SiteTree','Translatable') in your _config.php instead. Adjusted several classes (Image, ErrorPage, RootURLController) to the new behaviour. ------------------------------------------------------------------------ r73882 | ischommer | 2009-04-01 08:31:21 +1300 (Wed, 01 Apr 2009) | 1 line ENHANCEMENT Added DataObjectDecorator->setOwner() ------------------------------------------------------------------------ r73884 | ischommer | 2009-04-01 08:32:51 +1300 (Wed, 01 Apr 2009) | 1 line ENHANCEMENT Added Extension::get_classname_without_arguments() ------------------------------------------------------------------------ r73900 | ischommer | 2009-04-01 11:27:53 +1300 (Wed, 01 Apr 2009) | 7 lines API CHANGE Deprecated Object->extInstance(), use getExtensionInstance() instead ENHANCEMENT Added Object->getExtensionInstances() ENHANCEMENT Added Object::get_extensions() ENHANCEMENT Unsetting class caches when using Object::add_extension() to avoid problems with defineMethods etc. BUGFIX Fixed extension comparison with case sensitivity and stripping arguments in Object::has_extension() BUGFIX Unsetting all cached singletons in Object::remove_extension() to avoid outdated extension_instances MINOR Documentation in Object ------------------------------------------------------------------------ r74017 | ischommer | 2009-04-03 10:49:40 +1300 (Fri, 03 Apr 2009) | 1 line ENHANCEMENT Improved deprecated fallbacks in Translatable by auto-converting short language codes to long locales and vice versa through i18n::get_lang_from_locale()/i18n::get_locale_from_lang() ------------------------------------------------------------------------ r74030 | ischommer | 2009-04-03 11:41:26 +1300 (Fri, 03 Apr 2009) | 1 line MINOR Re-added Translatable::default_lang() for more graceful fallback to Translatable::default_locale() ------------------------------------------------------------------------ r74065 | ischommer | 2009-04-04 05:38:51 +1300 (Sat, 04 Apr 2009) | 1 line BUGFIX Re-added Translatable->isTranslation() for more friendly deprecation (originally removed in r73338) ------------------------------------------------------------------------ r74069 | ischommer | 2009-04-04 09:43:01 +1300 (Sat, 04 Apr 2009) | 1 line BUGFIX Fixed legacy handling of Translatable::enable(),Translatable::disable() and Translatable::is_enabled() - applying extension to SiteTree instead of Page to avoid datamodel clashes ------------------------------------------------------------------------ r74070 | ischommer | 2009-04-04 10:23:51 +1300 (Sat, 04 Apr 2009) | 1 line API CHANGE Deprecated Translatable::choose_site_lang(), use choose_site_locale() ------------------------------------------------------------------------ r74941 | ischommer | 2009-04-22 15:22:09 +1200 (Wed, 22 Apr 2009) | 2 lines ENHANCEMENT Adding SapphireTest::set_up_once() and SapphireTest::tear_down_once() for better test performance with state that just needs to be initialized once per test case (not per test method). Added new SapphireTestSuite to support this through PHPUnit. ENHANCEMENT Using set_up_once() in TranslatableTest and TranslatableSearchFormTest for better test run performance ------------------------------------------------------------------------ r74942 | ischommer | 2009-04-22 15:24:50 +1200 (Wed, 22 Apr 2009) | 1 line BUGFIX Fixed TranslatableSearchFormTest->setUp() method ------------------------------------------------------------------------ r73509 | ischommer | 2009-03-23 11:59:14 +1300 (Mon, 23 Mar 2009) | 1 line MINOR phpdoc documentation ------------------------------------------------------------------------ git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/2.3@74986 467b73ca-7a2a-4603-9d3b-597d59a354a9
2009-04-23 03:45:10 +02:00
* Used by {@link Email->send()}, {@link Email->sendPlain()}, {@link Debug->friendlyError()}.
*
* @param string $newEmail
*/
public static function setAdminEmail($newEmail) {
self::$admin_email_address = $newEmail;
}
public static function getAdminEmail() {
return self::$admin_email_address;
}
/**
* Send every email generated by the Email class to the given address.
* It will also add " [addressed to (email), cc to (email), bcc to (email)]" to the end of the subject line
* This can be used when testing, by putting a command like this in your _config.php file
*
* if(!Director::isLive()) Email::send_all_emails_to("someone@example.com")
*/
public static function send_all_emails_to($emailAddress) {
self::$send_all_emails_to = $emailAddress;
}
/**
* CC every email generated by the Email class to the given address.
* It won't affect the original delivery in the same way that send_all_emails_to does. It just adds a CC header
* with the given email address. Note that you can only call this once - subsequent calls will overwrite the configuration
* variable.
*
* This can be used when you have a system that relies heavily on email and you want someone to be checking all correspondence.
*
* if(Director::isLive()) Email::cc_all_emails_to("supportperson@example.com")
*/
public static function cc_all_emails_to($emailAddress) {
self::$cc_all_emails_to = $emailAddress;
}
/**
* BCC every email generated by the Email class to the given address.
* It won't affect the original delivery in the same way that send_all_emails_to does. It just adds a BCC header
* with the given email address. Note that you can only call this once - subsequent calls will overwrite the configuration
* variable.
*
* This can be used when you have a system that relies heavily on email and you want someone to be checking all correspondence.
*
* if(Director::isLive()) Email::cc_all_emails_to("supportperson@example.com")
*/
public static function bcc_all_emails_to($emailAddress) {
self::$bcc_all_emails_to = $emailAddress;
}
/**
* Checks for RFC822-valid email format.
*
* @param string $str
* @return boolean
*
* @see http://code.iamcal.com/php/rfc822/rfc822.phps
* @copyright Cal Henderson <cal@iamcal.com>
* This code is licensed under a Creative Commons Attribution-ShareAlike 2.5 License
* http://creativecommons.org/licenses/by-sa/2.5/
*/
function is_valid_address($email){
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c[\\x00-\\x7f]';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$addr_spec = "$local_part\\x40$domain";
return preg_match("!^$addr_spec$!", $email) ? 1 : 0;
}
/**
* Encode an email-address to protect it from spambots.
* At the moment only simple string substitutions,
* which are not 100% safe from email harvesting.
*
* @todo Integrate javascript-based solution
*
* @param string $email Email-address
* @param string $method Method for obfuscating/encoding the address
* - 'direction': Reverse the text and then use CSS to put the text direction back to normal
* - 'visible': Simple string substitution ('@' to '[at]', '.' to '[dot], '-' to [dash])
* - 'hex': Hexadecimal URL-Encoding - useful for mailto: links
* @return string
*/
public static function obfuscate($email, $method = 'visible') {
switch($method) {
case 'direction' :
Requirements::customCSS(
'span.codedirection { unicode-bidi: bidi-override; direction: rtl; }',
'codedirectionCSS'
);
return '<span class="codedirection">' . strrev($email) . '</span>';
case 'visible' :
$obfuscated = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
return strtr($email, $obfuscated);
case 'hex' :
$encoded = '';
for ($x=0; $x < strlen($email); $x++) $encoded .= '&#x' . bin2hex($email{$x}).';';
return $encoded;
default:
user_error('Email::obfuscate(): Unknown obfuscation method', E_USER_NOTICE);
return $email;
}
}
}
/**
* Implements an email template that can be populated.
*
* @deprecated - Please use Email instead!.
* @todo Remove this in 2.4
* @package sapphire
* @subpackage email
*/
class Email_Template extends Email {
public function __construct($from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null) {
parent::__construct($from, $to, $subject, $body, $bounceHandlerURL, $cc, $bcc);
user_error('Email_Template is deprecated. Please use Email instead.', E_USER_NOTICE);
}
}
/**
* Base class that email bounce handlers extend
* @package sapphire
* @subpackage email
*/
class Email_BounceHandler extends Controller {
function init() {
BasicAuth::disable();
parent::init();
}
function index() {
$subclasses = ClassInfo::subclassesFor( $this->class );
unset($subclasses[$this->class]);
if( $subclasses ) {
$subclass = array_pop( $subclasses );
$task = new $subclass();
$task->index();
return;
}
// Check if access key exists
if( !isset($_REQUEST['Key']) ) {
echo 'Error: Access validation failed. No "Key" specified.';
return;
}
// Check against access key defined in sapphire/_config.php
if( $_REQUEST['Key'] != EMAIL_BOUNCEHANDLER_KEY) {
echo 'Error: Access validation failed. Invalid "Key" specified.';
return;
}
if( !$_REQUEST['Email'] ) {
echo "No email address";
return;
}
$this->recordBounce( $_REQUEST['Email'], $_REQUEST['Date'], $_REQUEST['Time'], $_REQUEST['Message'] );
}
private function recordBounce( $email, $date = null, $time = null, $error = null ) {
if(ereg('<(.*)>', $email, $parts)) $email = $parts[1];
$SQL_email = Convert::raw2sql($email);
$SQL_bounceTime = Convert::raw2sql("$date $time");
$duplicateBounce = DataObject::get_one("Email_BounceRecord", "BounceEmail = '$SQL_email' AND (BounceTime+INTERVAL 1 MINUTE) > '$SQL_bounceTime'");
if(!$duplicateBounce) {
$record = new Email_BounceRecord();
$member = DataObject::get_one( 'Member', "`Email`='$SQL_email'" );
if( $member ) {
$record->MemberID = $member->ID;
// If the SilverStripeMessageID (taken from the X-SilverStripeMessageID header embedded in the email) is sent,
// then log this bounce in a Newsletter_SentRecipient record so it will show up on the 'Sent Status Report' tab of the Newsletter
if( isset($_REQUEST['SilverStripeMessageID'])) {
// Note: was sent out with: $project . '.' . $messageID;
$message_id_parts = explode('.', $_REQUEST['SilverStripeMessageID']);
// Note: was encoded with: base64_encode( $newsletter->ID . '_' . date( 'd-m-Y H:i:s' ) );
$newsletter_id_date_parts = explode ('_', base64_decode($message_id_parts[1]) );
// Escape just in case
$SQL_memberID = Convert::raw2sql($member->ID);
$SQL_newsletterID = Convert::raw2sql($newsletter_id_date_parts[0]);
// Log the bounce
$oldNewsletterSentRecipient = DataObject::get_one("Newsletter_SentRecipient", "MemberID = '$SQL_memberID' AND ParentID = '$SQL_newsletterID' AND Email = '$SQL_email'");
// Update the Newsletter_SentRecipient record if it exists
if($oldNewsletterSentRecipient) {
$oldNewsletterSentRecipient->Result = 'Bounced';
$oldNewsletterSentRecipient->write();
} else {
// For some reason it didn't exist, create a new record
$newNewsletterSentRecipient = new Newsletter_SentRecipient();
$newNewsletterSentRecipient->Email = $SQL_email;
$newNewsletterSentRecipient->MemberID = $member->ID;
$newNewsletterSentRecipient->Result = 'Bounced';
$newNewsletterSentRecipient->ParentID = $newsletter_id_date_parts[0];
$newNewsletterSentRecipient->write();
}
// Now we are going to Blacklist this member so that email will not be sent to them in the future.
// Note: Sending can be re-enabled by going to 'Mailing List' 'Bounced' tab and unchecking the box under 'Blacklisted'
$member->setBlacklistedEmail(TRUE);
echo '<p><b>Member: '.$member->FirstName.' '.$member->Surname.' <'.$member->Email.'> was added to the Email Blacklist!</b></p>';
}
}
if( !$date )
$date = date( 'd-m-Y' );
/*else
$date = date( 'd-m-Y', strtotime( $date ) );*/
if( !$time )
$time = date( 'H:i:s' );
/*else
$time = date( 'H:i:s', strtotime( $time ) );*/
$record->BounceEmail = $email;
$record->BounceTime = $date . ' ' . $time;
$record->BounceMessage = $error;
$record->write();
echo "Handled bounced email to address: $email";
} else {
echo 'Sorry, this bounce report has already been logged, not logging this duplicate bounce.';
}
}
}
/**
* Database record for recording a bounced email
* @package sapphire
* @subpackage email
*/
class Email_BounceRecord extends DataObject {
static $db = array(
'BounceEmail' => 'Varchar',
'BounceTime' => 'SSDatetime',
'BounceMessage' => 'Varchar'
);
static $has_one = array(
'Member' => 'Member'
);
static $has_many = array();
static $many_many = array();
static $defaults = array();
static $singular_name = 'Email Bounce Record';
/**
* a record of Email_BounceRecord can't be created manually. Instead, it should be
* created though system.
*/
public function canCreate($member = null) {
return false;
}
}
?>