/** * Send an email to the email address set in * this writer. */ public function _write($event) { // If no formatter set up, use the default if (!$this->_formatter) { $formatter = new SS_LogErrorEmailFormatter(); $this->setFormatter($formatter); } $formattedData = $this->_formatter->format($event); $subject = $formattedData['subject']; $data = $formattedData['data']; $from = Config::inst()->get('SS_LogEmailWriter', 'send_from'); // override the SMTP server with a custom one if required $originalSMTP = ini_get('SMTP'); if ($this->customSmtpServer) { ini_set('SMTP', $this->customSmtpServer); } // Use plain mail() implementation to avoid complexity of Mailer implementation. // Only use built-in mailer when we're in test mode (to allow introspection) $mailer = Email::mailer(); if ($mailer instanceof TestMailer) { $mailer->sendHTML($this->emailAddress, null, $subject, $data, null, "Content-type: text/html\nFrom: " . $from); } else { mail($this->emailAddress, $subject, $data, "Content-type: text/html\nFrom: " . $from); } // reset the SMTP server to the original if ($this->customSmtpServer) { ini_set('SMTP', $originalSMTP); } }
/** * Get the mailer. * * @return Mailer */ public static function mailer() { if (!self::$mailer) { self::$mailer = new Mailer(); } return self::$mailer; }
/** * @return MandrillMailer * @throws Exception */ public function getMailer() { $mailer = Email::mailer(); if (get_class($mailer) != 'MandrillMailer') { throw new Exception('This class require to use MandrillMailer'); } return $mailer; }
/** * @return SparkPostMailer * @throws Exception */ public function getMailer() { $mailer = Email::mailer(); if (!$mailer instanceof SparkPostMailer) { throw new Exception('This class require to use SparkPostMailer'); } return $mailer; }
public function testSetup() { Object::useCustomClass('Email', 'SMTPEmail'); Email::set_mailer(new SmtpMailer()); SMTPEmail::set_mailer(new SmtpMailer()); $mailer = Email::mailer(); $this->assertEquals('SmtpMailer', get_class($mailer)); $mailer = SMTPEmail::mailer(); $this->assertEquals('SmtpMailer', get_class($mailer)); }
function setUp() { // Mark test as being run $this->originalIsRunningTest = self::$is_running_test; self::$is_running_test = true; // Remove password validation $this->originalMemberPasswordValidator = Member::password_validator(); $this->originalRequirements = Requirements::backend(); Member::set_password_validator(null); Cookie::set_report_errors(false); $className = get_class($this); $fixtureFile = eval("return {$className}::\$fixture_file;"); // Set up fixture if($fixtureFile) { if(substr(DB::getConn()->currentDatabase(),0,5) != 'tmpdb') { //echo "Re-creating temp database... "; self::create_temp_db(); //echo "done.\n"; } // This code is a bit misplaced; we want some way of the whole session being reinitialised... Versioned::reading_stage(null); singleton('DataObject')->flushCache(); $dbadmin = new DatabaseAdmin(); $dbadmin->clearAllData(); // We have to disable validation while we import the fixtures, as the order in // which they are imported doesnt guarantee valid relations until after the // import is complete. $validationenabled = DataObject::get_validation_enabled(); DataObject::set_validation_enabled(false); $this->fixture = new YamlFixture($fixtureFile); $this->fixture->saveIntoDatabase(); DataObject::set_validation_enabled($validationenabled); } // Set up email $this->originalMailer = Email::mailer(); $this->mailer = new TestMailer(); Email::set_mailer($this->mailer); }
/** * Event handler called before writing to the database. */ public function onBeforeWrite() { if ($this->SetPassword) { $this->Password = $this->SetPassword; } // If a member with the same "unique identifier" already exists with a different ID, don't allow merging. // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form), // but rather a last line of defense against data inconsistencies. $identifierField = Member::config()->unique_identifier_field; if ($this->{$identifierField}) { // Note: Same logic as Member_Validator class $filter = array("\"{$identifierField}\"" => $this->{$identifierField}); if ($this->ID) { $filter[] = array('"Member"."ID" <> ?' => $this->ID); } $existingRecord = DataObject::get_one('Member', $filter); if ($existingRecord) { throw new ValidationException(ValidationResult::create(false, _t('Member.ValidationIdentifierFailed', 'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))', 'Values in brackets show "fieldname = value", usually denoting an existing email address', array('id' => $existingRecord->ID, 'name' => $identifierField, 'value' => $this->{$identifierField})))); } } // We don't send emails out on dev/tests sites to prevent accidentally spamming users. // However, if TestMailer is in use this isn't a risk. if ((Director::isLive() || Email::mailer() instanceof TestMailer) && $this->isChanged('Password') && $this->record['Password'] && $this->config()->notify_password_change) { $e = Member_ChangePasswordEmail::create(); $e->populateTemplate($this); $e->setTo($this->Email); $e->send(); } // The test on $this->ID is used for when records are initially created. // Note that this only works with cleartext passwords, as we can't rehash // existing passwords. if (!$this->ID && $this->Password || $this->isChanged('Password')) { // Password was changed: encrypt the password according the settings $encryption_details = Security::encrypt_password($this->Password, $this->Salt, $this->PasswordEncryption ? $this->PasswordEncryption : Security::config()->password_encryption_algorithm, $this); // Overwrite the Password property with the hashed value $this->Password = $encryption_details['password']; $this->Salt = $encryption_details['salt']; $this->PasswordEncryption = $encryption_details['algorithm']; // If we haven't manually set a password expiry if (!$this->isChanged('PasswordExpiry')) { // then set it for us if (self::config()->password_expiry_days) { $this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::config()->password_expiry_days); } else { $this->PasswordExpiry = null; } } } // save locale if (!$this->Locale) { $this->Locale = i18n::get_locale(); } parent::onBeforeWrite(); }
public function setUp() { // We cannot run the tests on this abstract class. if (get_class($this) == "SapphireTest") { $this->skipTest = true; } if ($this->skipTest) { $this->markTestSkipped(sprintf('Skipping %s ', get_class($this))); return; } // Mark test as being run $this->originalIsRunningTest = self::$is_running_test; self::$is_running_test = true; // i18n needs to be set to the defaults or tests fail i18n::set_locale(i18n::default_locale()); i18n::config()->date_format = null; i18n::config()->time_format = null; // Set default timezone consistently to avoid NZ-specific dependencies date_default_timezone_set('UTC'); // Remove password validation $this->originalMemberPasswordValidator = Member::password_validator(); $this->originalRequirements = Requirements::backend(); Member::set_password_validator(null); Config::inst()->update('Cookie', 'report_errors', false); if (class_exists('RootURLController')) { RootURLController::reset(); } if (class_exists('Translatable')) { Translatable::reset(); } Versioned::reset(); DataObject::reset(); if (class_exists('SiteTree')) { SiteTree::reset(); } Hierarchy::reset(); if (Controller::has_curr()) { Controller::curr()->setSession(Injector::inst()->create('Session', array())); } Security::$database_is_ready = null; // Add controller-name auto-routing Config::inst()->update('Director', 'rules', array('$Controller//$Action/$ID/$OtherID' => '*')); $fixtureFile = static::get_fixture_file(); $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_'; // Set up email $this->originalMailer = Email::mailer(); $this->mailer = new TestMailer(); Email::set_mailer($this->mailer); Config::inst()->remove('Email', 'send_all_emails_to'); // Todo: this could be a special test model $this->model = DataModel::inst(); // Set up fixture if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) { if (substr(DB::get_conn()->getSelectedDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) { //echo "Re-creating temp database... "; self::create_temp_db(); //echo "done.\n"; } singleton('DataObject')->flushCache(); self::empty_temp_db(); foreach ($this->requireDefaultRecordsFrom as $className) { $instance = singleton($className); if (method_exists($instance, 'requireDefaultRecords')) { $instance->requireDefaultRecords(); } if (method_exists($instance, 'augmentDefaultRecords')) { $instance->augmentDefaultRecords(); } } if ($fixtureFile) { $pathForClass = $this->getCurrentAbsolutePath(); $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile); $i = 0; foreach ($fixtureFiles as $fixtureFilePath) { // Support fixture paths relative to the test class, rather than relative to webroot // String checking is faster than file_exists() calls. $isRelativeToFile = strpos('/', $fixtureFilePath) === false || preg_match('/^\\.\\./', $fixtureFilePath); if ($isRelativeToFile) { $resolvedPath = realpath($pathForClass . '/' . $fixtureFilePath); if ($resolvedPath) { $fixtureFilePath = $resolvedPath; } } $fixture = Injector::inst()->create('YamlFixture', $fixtureFilePath); $fixture->writeInto($this->getFixtureFactory()); $this->fixtures[] = $fixture; // backwards compatibility: Load first fixture into $this->fixture if ($i == 0) { $this->fixture = $fixture; } $i++; } } $this->logInWithPermission("ADMIN"); } // Preserve memory settings $this->originalMemoryLimit = ini_get('memory_limit'); // turn off template debugging Config::inst()->update('SSViewer', 'source_file_comments', false); // Clear requirements Requirements::clear(); }
/** * Get the mailer. * * @return Mailer */ static function mailer() { if(!self::$mailer) self::$mailer = new Mailer(); return self::$mailer; }
public function batch(array $to, array &$failed = NULL) { $message = clone $this->_message; $mailer = Email::mailer(); $total = 0; foreach ($to as $email => $name) { if (ctype_digit((string) $email)) { $email = $name; $name = NULL; } $message->setTo($email, $name); $total += $mailer->send($message, $failed); } return $total; }
/** * Send the email. Failed recipients can be collected by passing an array. * * @param array failed recipient list, by reference * @return boolean */ public function send(array &$failed = NULL) { return Email::mailer()->send($this->_message, $failed); }
function setUp() { // We cannot run the tests on this abstract class. if (get_class($this) == "SapphireTest") { $this->skipTest = true; } if ($this->skipTest) { $this->markTestSkipped(sprintf('Skipping %s ', get_class($this))); return; } // Mark test as being run $this->originalIsRunningTest = self::$is_running_test; self::$is_running_test = true; // i18n needs to be set to the defaults or tests fail i18n::set_locale(i18n::default_locale()); i18n::set_date_format(null); i18n::set_time_format(null); // Remove password validation $this->originalMemberPasswordValidator = Member::password_validator(); $this->originalRequirements = Requirements::backend(); Member::set_password_validator(null); Cookie::set_report_errors(false); if (class_exists('RootURLController')) { RootURLController::reset(); } if (class_exists('Translatable')) { Translatable::reset(); } Versioned::reset(); DataObject::reset(); if (class_exists('SiteTree')) { SiteTree::reset(); } Hierarchy::reset(); if (Controller::has_curr()) { Controller::curr()->setSession(new Session(array())); } $this->originalTheme = SSViewer::current_theme(); if (class_exists('SiteTree')) { // Save nested_urls state, so we can restore it later $this->originalNestedURLsState = SiteTree::nested_urls(); } $className = get_class($this); $fixtureFile = eval("return {$className}::\$fixture_file;"); $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_'; // Todo: this could be a special test model $this->model = DataModel::inst(); // Set up fixture if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) { if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) { //echo "Re-creating temp database... "; self::create_temp_db(); //echo "done.\n"; } singleton('DataObject')->flushCache(); self::empty_temp_db(); foreach ($this->requireDefaultRecordsFrom as $className) { $instance = singleton($className); if (method_exists($instance, 'requireDefaultRecords')) { $instance->requireDefaultRecords(); } if (method_exists($instance, 'augmentDefaultRecords')) { $instance->augmentDefaultRecords(); } } if ($fixtureFile) { $pathForClass = $this->getCurrentAbsolutePath(); $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile); $i = 0; foreach ($fixtureFiles as $fixtureFilePath) { // Support fixture paths relative to the test class, rather than relative to webroot // String checking is faster than file_exists() calls. $isRelativeToFile = strpos('/', $fixtureFilePath) === false || preg_match('/^\\.\\./', $fixtureFilePath); if ($isRelativeToFile) { $resolvedPath = realpath($pathForClass . '/' . $fixtureFilePath); if ($resolvedPath) { $fixtureFilePath = $resolvedPath; } } $fixture = new YamlFixture($fixtureFilePath); $fixture->saveIntoDatabase($this->model); $this->fixtures[] = $fixture; // backwards compatibility: Load first fixture into $this->fixture if ($i == 0) { $this->fixture = $fixture; } $i++; } } $this->logInWithPermission("ADMIN"); } // Set up email $this->originalMailer = Email::mailer(); $this->mailer = new TestMailer(); Email::set_mailer($this->mailer); Email::send_all_emails_to(null); // Preserve memory settings $this->originalMemoryLimit = ini_get('memory_limit'); }
public function testSetup() { $inst = SparkPostMailer::setAsMailer(); $this->assertTrue($inst === Email::mailer()); }
/** * Check the permission to make sure the current user has a mandrill * * @return bool */ public function canView($member = null) { $mailer = Email::mailer(); if (get_class($mailer) != 'MandrillMailer') { return false; } return Permission::check("CMS_ACCESS_Mandrill", "any", $member); }
/** * Send the email to a batch of addresses. * * !! Failed recipients can be collected by using the second parameter. * * @param array failed recipient list, by reference * @return integer number of emails sent */ public function batch(array $to, array &$failed = NULL) { // Get a copy of the current message $message = clone $this->_message; // Load the mailer instance $mailer = Email::mailer(); // Count the total number of messages sent $total = 0; foreach ($to as $email => $name) { if (ctype_digit((string) $email)) { // Only an email address was provided $email = $name; $name = NULL; } // Set the To addre $message->setTo($email, $name); // Send this email $total += $mailer->send($message, $failed); } return $total; }
/** * Event handler called before writing to the database. */ function onBeforeWrite() { if($this->SetPassword) $this->Password = $this->SetPassword; $identifierField = self::$unique_identifier_field; if($this->$identifierField) { $idClause = ($this->ID) ? " AND `Member`.ID <> $this->ID" : ''; $SQL_identifierField = Convert::raw2sql($this->$identifierField); $existingRecord = DataObject::get_one('Member', "$identifierField = '{$SQL_identifierField}'{$idClause}"); if($existingRecord) { $newID = $existingRecord->ID; if($this->ID) { DB::query("UPDATE Group_Members SET MemberID = $newID WHERE MemberID = $this->ID"); } $this->ID = $newID; // Merge existing data into the local record foreach($existingRecord->getAllFields() as $k => $v) { if(!isset($this->changed[$k]) || !$this->changed[$k]) $this->record[$k] = $v; } } } // We don't send emails out on dev/tests sites to prevent accidentally spamming users. // However, if TestMailer is in use this isn't a risk. if( (Director::isLive() || Email::mailer() instanceof TestMailer) && isset($this->changed['Password']) && $this->changed['Password'] && $this->record['Password'] && Member::$notify_password_change ) { $this->sendInfo('changePassword'); } // The test on $this->ID is used for when records are initially created if(!$this->ID || (isset($this->changed['Password']) && $this->changed['Password'])) { // Password was changed: encrypt the password according the settings $encryption_details = Security::encrypt_password($this->Password); $this->Password = $encryption_details['password']; $this->Salt = $encryption_details['salt']; $this->PasswordEncryption = $encryption_details['algorithm']; $this->changed['Salt'] = true; $this->changed['PasswordEncryption'] = true; // If we haven't manually set a password expiry if(!isset($this->changed['PasswordExpiry']) || !$this->changed['PasswordExpiry']) { // then set it for us if(self::$password_expiry_days) { $this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::$password_expiry_days); } else { $this->PasswordExpiry = null; } } } // save locale if(!$this->Locale) { $this->Locale = i18n::get_locale(); } parent::onBeforeWrite(); }
/** * Gets the mailer (or makes a new one) * * @return object */ protected function getMailer() { if (!self::$mailer instanceof Swift_Mailer) { self::$mailer = new Swift_Mailer($this->transport); } return self::$mailer; }
function setUp() { // Mark test as being run $this->originalIsRunningTest = self::$is_running_test; self::$is_running_test = true; // i18n needs to be set to the defaults or tests fail i18n::set_locale(i18n::default_locale()); i18n::set_date_format(null); i18n::set_time_format(null); // Remove password validation $this->originalMemberPasswordValidator = Member::password_validator(); $this->originalRequirements = Requirements::backend(); Member::set_password_validator(null); Cookie::set_report_errors(false); RootURLController::reset(); Translatable::reset(); Versioned::reset(); DataObject::reset(); SiteTree::reset(); Hierarchy::reset(); if (Controller::has_curr()) { Controller::curr()->setSession(new Session(array())); } $this->originalTheme = SSViewer::current_theme(); // Save nested_urls state, so we can restore it later $this->originalNestedURLsState = SiteTree::nested_urls(); $className = get_class($this); $fixtureFile = eval("return {$className}::\$fixture_file;"); $prefix = defined('SS_DATABASE_PREFIX') ? SS_DATABASE_PREFIX : 'ss_'; // Set up fixture if ($fixtureFile || $this->usesDatabase || !self::using_temp_db()) { if (substr(DB::getConn()->currentDatabase(), 0, strlen($prefix) + 5) != strtolower(sprintf('%stmpdb', $prefix))) { //echo "Re-creating temp database... "; self::create_temp_db(); //echo "done.\n"; } singleton('DataObject')->flushCache(); self::empty_temp_db(); foreach ($this->requireDefaultRecordsFrom as $className) { $instance = singleton($className); if (method_exists($instance, 'requireDefaultRecords')) { $instance->requireDefaultRecords(); } if (method_exists($instance, 'augmentDefaultRecords')) { $instance->augmentDefaultRecords(); } } if ($fixtureFile) { $fixtureFiles = is_array($fixtureFile) ? $fixtureFile : array($fixtureFile); $i = 0; foreach ($fixtureFiles as $fixtureFilePath) { $fixture = new YamlFixture($fixtureFilePath); $fixture->saveIntoDatabase(); $this->fixtures[] = $fixture; // backwards compatibility: Load first fixture into $this->fixture if ($i == 0) { $this->fixture = $fixture; } $i++; } } $this->logInWithPermission("ADMIN"); } // Set up email $this->originalMailer = Email::mailer(); $this->mailer = new TestMailer(); Email::set_mailer($this->mailer); Email::send_all_emails_to(null); // Preserve memory settings $this->originalMemoryLimit = ini_get('memory_limit'); }
/** * Check the permission for current user * * @return bool */ public function canView($member = null) { $mailer = Email::mailer(); if (!$mailer instanceof SparkPostMailer) { return false; } return Permission::check("CMS_ACCESS_SparkPost", 'any', $member); }
/** * Event handler called before writing to the database. */ function onBeforeWrite() { if ($this->SetPassword) { $this->Password = $this->SetPassword; } // If a member with the same "unique identifier" already exists with a different ID, don't allow merging. // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form), // but rather a last line of defense against data inconsistencies. $identifierField = self::$unique_identifier_field; if ($this->{$identifierField}) { // Note: Same logic as Member_Validator class $idClause = $this->ID ? sprintf(" AND \"Member\".\"ID\" <> %d", (int) $this->ID) : ''; $existingRecord = DataObject::get_one('Member', sprintf("\"%s\" = '%s' %s", $identifierField, Convert::raw2sql($this->{$identifierField}), $idClause)); if ($existingRecord) { throw new ValidationException(new ValidationResult(false, sprintf(_t('Member.ValidationIdentifierFailed', 'Can\'t overwrite existing member #%d with identical identifier (%s = %s))', PR_MEDIUM, 'The values in brackets show a fieldname mapped to a value, usually denoting an existing email address'), $existingRecord->ID, $identifierField, $this->{$identifierField}))); } } // We don't send emails out on dev/tests sites to prevent accidentally spamming users. // However, if TestMailer is in use this isn't a risk. if ((Director::isLive() || Email::mailer() instanceof TestMailer) && $this->isChanged('Password') && $this->record['Password'] && Member::$notify_password_change) { $this->sendInfo('changePassword'); } // The test on $this->ID is used for when records are initially created. // Note that this only works with cleartext passwords, as we can't rehash // existing passwords. if (!$this->ID && $this->Password || $this->isChanged('Password')) { // Password was changed: encrypt the password according the settings $encryption_details = Security::encrypt_password($this->Password, $this->Salt, $this->PasswordEncryption, $this); // Overwrite the Password property with the hashed value $this->Password = $encryption_details['password']; $this->Salt = $encryption_details['salt']; $this->PasswordEncryption = $encryption_details['algorithm']; // If we haven't manually set a password expiry if (!$this->isChanged('PasswordExpiry')) { // then set it for us if (self::$password_expiry_days) { $this->PasswordExpiry = date('Y-m-d', time() + 86400 * self::$password_expiry_days); } else { $this->PasswordExpiry = null; } } } // save locale if (!$this->Locale) { $this->Locale = i18n::get_locale(); } parent::onBeforeWrite(); }
/** * Display information when default route is viewed * Default routes is /dev/healthcheck */ public function index() { $data = array('Title' => 'Health check', 'Content' => 'Health check content...', 'Environment' => Director::get_environment_type(), 'Mailer' => Email::mailer()->class, 'AdminEmail' => Config::inst()->get('Email', 'admin_email'), 'SendAllEmailsTo' => Config::inst()->get('Email', 'send_all_emails_to'), 'Nofollow' => $this->getRobotsMetaTag(), 'Logging' => $this->getLogWriters(), 'SiteMap' => $this->hasSiteMap(), 'LastCommit' => $this->getLastCommit()); $this->extend('updateIndexData', $data); return $this->customise($data)->renderWith(array("HealthCheck")); }