/**
     * Save the member and redirect
     */
    function register($data, $form, $request)
    {
        //Check if this member already exists
        // Create new OR update logged in {@link Member} record
        $member = CleanUpRole::createOrMerge($data);
        $tempMember = TempMember::Emailexists($data);
        if (!$member || $tempMember) {
            $form->sessionMessage(_t('RegisterForm.MEMBEREXISTS', 'Sorry, a member already exists with that email address.
					If this is your email address, please <a href="my-events/">log in here</a>'), 'bad');
            Director::redirectBack();
            return false;
        }
        //CHANGE
        //Create temp member
        $tempMember = new TempMember();
        $form->saveInto($tempMember);
        if ($tempMember->write()) {
            // Send a confirmation Email
            $from = Email::getAdminEmail();
            $to = $tempMember->Email;
            $name = $tempMember->FirstName;
            $subject = 'Thank you for joining Love Your Coast';
            $email = new joinEmail_SignUpMessage();
            $email->setFrom($from);
            $email->setTo($to);
            $email->setSubject($subject);
            $email->populateTemplate(array('Contact' => $name, 'VerificationCode' => $tempMember->VerificationCode));
            $email->send();
            Director::redirect('success');
        } else {
            $form->sessionMessage(_t("Register.REGISTRATION ERROR", "Your registration wasn't successful please try again"), 'bad');
            Director::redirectBack();
        }
        //END-OF-CHANGE
    }
 /**
  * make sure to return TRUE as response if the message is sent
  * successfully
  * Sends a message from the current user to someone else in the networkd
  * @param Int | String | Member $to -
  * @param String $message - Message you are sending
  * @param String $link - Link to send with message - NOT USED IN EMAIL
  * @param Array - other variables that we include
  * @return Boolean - return TRUE as success
  */
 public static function send_message($to, $message, $link = "", $otherVariables = array())
 {
     //FROM
     if (!empty($otherVariables["From"])) {
         $from = $otherVariables["From"];
     } else {
         $from = Email::getAdminEmail();
     }
     //TO
     if ($to instanceof Member) {
         $to = $to->Email;
     }
     //SUBJECT
     if (!empty($otherVariables["Subject"])) {
         $subject = $otherVariables["Subject"];
     } else {
         $subject = substr($message, 0, 30);
     }
     //BODY
     $body = $message;
     //CC
     if (!empty($otherVariables["CC"])) {
         $cc = $otherVariables["CC"];
     } else {
         $cc = "";
     }
     //BCC
     $bcc = Email::getAdminEmail();
     //SEND EMAIL
     $email = new Email($from, $to, $subject, $body, $bounceHandlerURL = null, $cc, $bcc);
     return $email->send();
 }
 /**
  * Form action handler for ContactInquiryForm.
  *
  * @param array $data The form request data submitted
  * @param Form $form The {@link Form} this was submitted on
  */
 function dosave(array $data, Form $form, SS_HTTPRequest $request)
 {
     $SQLData = Convert::raw2sql($data);
     $attrs = $form->getAttributes();
     if ($SQLData['Comment'] != '' || $SQLData['Url'] != '') {
         // most probably spam - terminate silently
         Director::redirect(Director::baseURL() . $this->URLSegment . "/success");
         return;
     }
     $item = new ContactInquiry();
     $form->saveInto($item);
     // $form->sessionMessage(_t("ContactPage.FORMMESSAGEGOOD", "Your inquiry has been submitted. Thanks!"), 'good');
     $item->write();
     $mailFrom = $this->currController->MailFrom ? $this->currController->MailFrom : $SQLData['Email'];
     $mailTo = $this->currController->MailTo ? $this->currController->MailTo : Email::getAdminEmail();
     $mailSubject = $this->currController->MailSubject ? $this->currController->MailSubject . ' - ' . $SQLData['Ref'] : _t('ContactPage.SUBJECT', '[web] New contact inquiry - ') . ' ' . $data['Ref'];
     $email = new Email($mailFrom, $mailTo, $mailSubject);
     $email->replyTo($SQLData['Email']);
     $email->setTemplate("ContactInquiry");
     $email->populateTemplate($SQLData);
     $email->send();
     // $this->controller->redirectBack();
     if ($email->send()) {
         $this->controller->redirect($this->controller->Link() . "success");
     } else {
         $this->controller->redirect($this->controller->Link() . "error");
     }
     return false;
 }
Esempio n. 4
0
 /**
  * Create the new notification email.
  * 
  * @param Member $customer
  * @param Order $order
  * @param String $from
  * @param String $to
  * @param String $subject
  * @param String $body
  * @param String $bounceHandlerURL
  * @param String $cc
  * @param String $bcc
  */
 public function __construct(Member $customer, Order $order, $from = null, $to = null, $subject = null, $body = null, $bounceHandlerURL = null, $cc = null, $bcc = null)
 {
     $siteConfig = ShopConfig::get()->first();
     if ($siteConfig->NotificationTo) {
         $this->to = $siteConfig->NotificationTo;
     }
     if ($siteConfig->NotificationSubject) {
         $this->subject = $siteConfig->NotificationSubject . ' - Order #' . $order->ID;
     }
     if ($siteConfig->NotificationBody) {
         $this->body = $siteConfig->NotificationBody;
     }
     if ($customer->Email) {
         $this->from = $customer->Email;
     } elseif (Email::getAdminEmail()) {
         $this->from = Email::getAdminEmail();
     } else {
         $this->from = 'no-reply@' . $_SERVER['HTTP_HOST'];
     }
     $this->signature = '';
     $adminLink = Director::absoluteURL('/admin/shop/');
     //Get css for Email by reading css file and put css inline for emogrification
     $this->setTemplate('Order_NotificationEmail');
     if (file_exists(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css'))) {
         $css = file_get_contents(Director::getAbsFile($this->ThemeDir() . '/css/ShopEmail.css'));
     } else {
         $css = file_get_contents(Director::getAbsFile('swipestripe/css/ShopEmail.css'));
     }
     $this->populateTemplate(array('Message' => $this->Body(), 'Order' => $order, 'Customer' => $customer, 'InlineCSS' => "<style>{$css}</style>", 'Signature' => $this->signature, 'AdminLink' => $adminLink));
     parent::__construct($from, null, $subject, $body, $bounceHandlerURL, $cc, $bcc);
 }
Esempio n. 5
0
 /**
  * @param MemberProfilePage $page
  * @param Member $member
  */
 public function __construct($page, $member)
 {
     $from = $page->EmailFrom ? $page->EmailFrom : Email::getAdminEmail();
     $to = $member->Email;
     $subject = self::get_parsed_string($page->ApprovalEmailSubject, $member, $page);
     $body = self::get_parsed_string($page->ApprovalEmailTemplate, $member, $page);
     parent::__construct($from, $to, $subject, $body);
 }
 /**
  * Update the CMS fields on the extended object
  *
  * @param FieldList $fields
  */
 public function updateCMSFields(FieldList $fields)
 {
     $member = Member::currentUser();
     // lock down testing for the administrator only
     if ($member->Email == Email::getAdminEmail()) {
         $fields->addFieldToTab('Root.ABTesting', new CheckboxField('ABGlobalTest', 'This site currently undergoing AB testing.'));
         $fields->addFieldToTab('Root.ABTesting', new TextareaField('ABTestGlobalScript', 'Inline Script for AB Testing (from Google content experiments)'));
     }
 }
 /**
  * Update the CMS fields on the extended object
  *
  * @param FieldList $fields
  */
 public function updateCMSFields(FieldList $fields)
 {
     $member = Member::currentUser();
     // lock down testing for heyday developers only
     if ($member->Email == Email::getAdminEmail()) {
         $fields->addFieldToTab('Root.ABTesting', new CheckboxField('ABTestPage', 'This is a page currently undergoing AB testing.'));
         $fields->addFieldToTab('Root.ABTesting', new TextareaField('ABTestInlineScript', 'Inline Script for AB Testing (from Google content experiments)'));
     }
 }
 function onAfterWrite()
 {
     parent::onAfterWrite();
     if (!$this->Sent) {
         $email = new Email($from = Email::getAdminEmail(), $to = $this->To, $subject = $this->Subject, $body = $this->Body, $bounceHandlerURL = null, $cc = null, $bcc = Email::getAdminEmail());
         $email->send();
         $this->Sent = 1;
         $this->write();
     }
 }
 public function createEmail($subject = "Website Enquiry", $template = "GenericEmail")
 {
     $content = $this->renderWith("EnquiryEmail_content");
     $to = Email::getAdminEmail();
     $email = new Email($this->Email, $to, $subject);
     $email->setTemplate($template);
     $email->populateTemplate($this);
     $email->populateTemplate(array('Body' => $content));
     $this->extend('updateReceiptEmail', $email);
     return $email;
 }
 public function doContact(array $data)
 {
     $email = new Email();
     $email->setTo(Email::getAdminEmail());
     $email->setFrom($data['Email']);
     $email->setSubject(_t('ContactForm.SUBJECT', 'ContactForm.SUBJECT') . $data['Name']);
     $email->setBody($data['Message']);
     //$email->set
     $email->send();
     $this->sessionMessage(_t('ContactForm.SUCCESS', 'ContactForm.SUCCESS'), 'good');
     $this->controller->redirectBack();
 }
 function go()
 {
     $from = Email::getAdminEmail();
     $to = $this->Recipient;
     $subject = 'Clean Up Week Reminder';
     $memberid = $this->MemberID;
     $member = DataObject::get_one('Member', "Member.ID = '{$memberid}'");
     $cleanups = $member->myCleanUpGroups($memberid);
     $email = new EventReminderEmail();
     $email->setFrom($from);
     $email->setTo($to);
     $email->setSubject($subject);
     $email->populateTemplate(array('Member' => $member, 'CleanUps' => $cleanups));
     $email->send();
 }
 protected function emailNotice($emailClass)
 {
     $from = Email::getAdminEmail();
     $to = $this->Recipient;
     $subject = $this->Subject ? $this->Subject : "Thanks for joining in on a Love Your Coast Event";
     $name = $this->FirstName;
     $cleanupid = $this->CleanUpGroupID;
     $cleanup = DataObject::get_one('CleanUpGroup', "CleanUpGroup.ID = '{$cleanupid}'");
     $email = new $emailClass();
     $email->setFrom($from);
     $email->setTo($to);
     $email->setSubject($subject);
     $email->populateTemplate(array('Contact' => $name, 'CleanUp' => $cleanup));
     $email->send();
 }
 /**
  * Returns the email address that should be notified of comments to the given page
  * 
  * @param DataObject $parent Parent object
  * @return string Email address, if available
  */
 public static function get_recipient($parent)
 {
     $recipient = Config::inst()->get('CommentsNotifications', 'recipient');
     switch ($recipient) {
         case 'Disabled':
             return null;
         case 'SiteConfig':
             return SiteConfig::current_site_config()->CommentNotificationEmail;
         case 'Page':
             return $parent->CommentNotificationEmail;
         case 'Admin':
             return Email::getAdminEmail();
         default:
             return $recipient;
     }
 }
 /**
  * Register action
  * @param type $data
  * @param type $form
  * @return \SS_HTTPResponse
  */
 public function doRegister($data, $form)
 {
     $r = new EventRegistration();
     $form->saveInto($r);
     $EventDetails = Event::get()->byID($r->EventID);
     if ($EventDetails->TicketsRequired) {
         $r->AmountPaid = $r->AmountPaid / 100;
     }
     $r->write();
     $from = Email::getAdminEmail();
     $to = $r->Email;
     $bcc = $EventDetails->RSVPEmail;
     $subject = "Event Registration - " . $EventDetails->Title . " - " . date("d/m/Y H:ia");
     $body = "";
     $email = new Email($from, $to, $subject, $body, null, null, $bcc);
     $email->setTemplate('EventRegistration');
     $email->send();
     exit;
 }
Esempio n. 15
0
 /**
  *
  * @param Null|String $messageID - ID for the message, you can leave this blank
  * @param Order $order - the order to which the email relates
  * @param Boolean $resend - should the email be resent even if it has been sent already?
  * @return Boolean - TRUE for success and FALSE for failure.
  */
 public function send($messageID = null, $order, $resend = false)
 {
     if (!$this->subject) {
         $this->subject = self::get_subject();
     }
     $this->subject = str_replace("[OrderNumber]", $order->ID, $this->subject);
     if (!$this->hasBeenSent($order) || $resend) {
         if (EcommerceConfig::get("Order_Email", "copy_to_admin_for_all_emails") && $this->to != Email::getAdminEmail()) {
             $this->setBcc(Email::getAdminEmail());
         }
         if (EcommerceConfig::get("Order_Email", "send_all_emails_plain")) {
             $result = parent::sendPlain($messageID);
         } else {
             $result = parent::send($messageID);
         }
         $this->createRecord($result, $order);
         return $result;
     }
 }
 /**
  * Send temporary password to user via email.
  */
 public function sendTempPasswordEmail($template = null, $subject = null, $extradata = null)
 {
     //set expiry
     $template = $template ? $template : 'TempPasswordEmail';
     $subject = $subject ? $subject : "Temporary Password";
     $data = array('CleartextTempPassword' => $this->owner->setupTempPassword());
     if ($extradata) {
         $data = array_merge($data, $extradata);
     }
     $body = $this->owner->customise($data)->renderWith($template);
     if (Email::validEmailAddress($this->owner->Email)) {
         $email = new Email(Email::getAdminEmail(), $this->owner->Email, $subject, $body);
         if ($email->send()) {
             return true;
         }
         return false;
     }
     return false;
 }
 /**
  * We hook into onAfterWrite() because we want to check this every time the comment is written - primarily because
  * of the test that we perform to ensure that the comment isn't currently moderated. Most sites will moderate
  * comments initially, and there's no point sending an email to a user if the comment is still awaiting moderation
  * (and therefore the user can't see it yet).
  *
  * @todo This will lead to multiple emails being sent if a comment is edited after being posted
  */
 public function onAfterWrite()
 {
     parent::onAfterWrite();
     $parentClass = $this->owner->BaseClass;
     $parentID = $this->owner->ParentID;
     // We only want to notify people if certain conditions are met:
     // - The comment has passed moderation (aka. if required, it has been approved by an admin)
     // - We are either seeing the Comment for the first time, or it has just passed moderation by an admin
     if ($this->shouldSendUserNotificationEmails()) {
         if (ClassInfo::exists($parentClass)) {
             $commentParent = $parentClass::get()->byID($parentID);
             // Get all comments attached to this page, which we have to do manually as the has_one relationship is
             // 'faked' by the Comment class (because it can be attached to multiple parent classes).
             if ($commentParent) {
                 $comments = Comment::get()->filter(array('BaseClass' => $parentClass, 'ParentID' => $parentID, 'NotifyOfUpdates' => true));
                 // If we have comments, iterate over them to build a unique list of all email addresses to notify
                 if ($comments) {
                     $emailList = array();
                     foreach ($comments as $c) {
                         $author = $c->Author();
                         if ($author) {
                             if (!in_array($author->Email, $emailList)) {
                                 $emailList[] = $author->Email;
                             }
                         }
                     }
                     // Send an email to everyone in the list
                     if (sizeof($emailList) > 0) {
                         foreach ($emailList as $emailAddress) {
                             $email = new Email();
                             $email->setSubject('New Comment on "' . $commentParent->dbObject('Title')->XML() . '"');
                             $email->setFrom(Email::getAdminEmail());
                             $email->setTo($emailAddress);
                             $email->populateTemplate($this->owner);
                             $email->send();
                         }
                     }
                 }
             }
         }
     }
 }
Esempio n. 18
0
	protected function notifySubscribers($members) {
		if($members) foreach($members as $member) {
			$body = "
				<p>Hi {$member->FirstName}!</p>
				<p>
				 A new job posting is available at the following URL:
				 {$this->Link()}
				</p>
			";
			
			$email = new Email(
				Email::getAdminEmail(),
				$member->Email,
				'Job Posting Notification',
				$body
			);
			$email->send();	
		}
		
	}
 public function submitenquiry($data, $form)
 {
     $siteconfig = SiteConfig::current_site_config();
     $to = Email::getAdminEmail();
     $subject = $this->emailsubject ? $this->emailsubject : _t("EnquiryForm.SUBJECT", "Website Contact");
     $form->makeReadOnly();
     $data = array('Values' => $form->Fields());
     if ($this->extraemaildata) {
         $data = array_merge($data, $this->extraemaildata);
     }
     $email = new Email($to, $to, $subject, $this->customise($data)->renderWith($this->emailtemplate));
     if (isset($data['Email']) && Email::is_valid_address($data['Email'])) {
         $email->replyTo($data['Email']);
     }
     $success = $email->send();
     $defaultmessage = "<p class=\"message good\">" . _t("Enquiry.SUCCESS", "Thanks for your contact. We'll be in touch shortly.") . "</p>";
     $content = $siteconfig && $siteconfig->EnquiryContent ? $siteconfig->EnquiryContent : $defaultmessage;
     if (Director::is_ajax()) {
         return "success";
     }
     return new Page_Controller(new Page(array('Title' => _t('Enquiry.Singular', 'Enquiry'), 'Content' => $content, 'EnquiryForm' => '')));
 }
 function index($request)
 {
     if (!Permission::check("ADMIN")) {
         return Security::permissionFailure($this);
     }
     $email = $request->requestVar($name = "email");
     if ($email && Email::validEmailAddress($email)) {
         $number = rand(0, 10000);
         $from = Email::getAdminEmail();
         $to = $email;
         $subject = "test mail ID" . $number;
         $body = "test mail ID" . $number;
         $htmlBody = "<h1>test mail ID" . $number . '</h1>';
         $basicMailOk = @mail($email, $subject, $body);
         if ($basicMailOk) {
             DB::alteration_message("basic mail (using the PHP mail function)  has been sent with ID: " . $number, "created");
         } else {
             DB::alteration_message("basic mail (using the PHP mail function) has * NOT * been sent with ID:" . $number, "deleted");
         }
         $e = new Email($from, $to, $subject, $body);
         if ($e->send()) {
             DB::alteration_message("standard Silverstripe email has been sent with ID: " . $number, "created");
         } else {
             DB::alteration_message("standard Silverstripe email ***NOT*** has been sent with ID: " . $number, "deleted");
         }
         //OR
         $e = new Email($from, $to, $subject, $body);
         if ($e->sendPlain()) {
             DB::alteration_message("plain text Silverstripe  email has been sent with ID: " . $number, "created");
         } else {
             DB::alteration_message("plain text Silverstripe email has ***NOT*** been sent with ID: " . $number, "deleted");
         }
     } else {
         user_error("make sure to add a valid email - current one is '" . $email . "' (you can add the email like this: " . $request->getURL() . "?email=myemail@test.com", E_USER_WARNING);
     }
 }
 /**
  * Runs an explicit check on all currently running jobs to make sure their "processed" count is incrementing
  * between each run. If it's not, then we need to flag it as paused due to an error.
  *
  * This typically happens when a PHP fatal error is thrown, which can't be picked up by the error
  * handler or exception checker; in this case, we detect these stalled jobs later and fix (try) to
  * fix them
  */
 public function checkJobHealth()
 {
     // first off, we want to find jobs that haven't changed since they were last checked (assuming they've actually
     // processed a few steps...)
     $filter = singleton('QJUtils')->quote(array('JobStatus =' => QueuedJob::STATUS_RUN, 'StepsProcessed >' => 0));
     $filter = $filter . ' AND "StepsProcessed"="LastProcessedCount"';
     $stalledJobs = DataObject::get('QueuedJobDescriptor', $filter);
     if ($stalledJobs) {
         foreach ($stalledJobs as $stalledJob) {
             if ($stalledJob->ResumeCount <= self::$stall_threshold) {
                 $stalledJob->ResumeCount++;
                 $stalledJob->pause();
                 $stalledJob->resume();
                 $msg = sprintf(_t('QueuedJobs.STALLED_JOB_MSG', 'A job named %s appears to have stalled. It will be stopped and restarted, please login to make sure it has continued'), $stalledJob->JobTitle);
             } else {
                 $stalledJob->pause();
                 $msg = sprintf(_t('QueuedJobs.STALLED_JOB_MSG', 'A job named %s appears to have stalled. It has been paused, please login to check it'), $stalledJob->JobTitle);
             }
             $mail = new Email(Email::getAdminEmail(), Email::getAdminEmail(), _t('QueuedJobs.STALLED_JOB', 'Stalled job'), $msg);
             $mail->send();
         }
     }
     // now, find those that need to be marked before the next check
     $filter = singleton('QJUtils')->quote(array('JobStatus =' => QueuedJob::STATUS_RUN));
     $runningJobs = DataObject::get('QueuedJobDescriptor', $filter);
     if ($runningJobs) {
         // foreach job, mark it as having been incremented
         foreach ($runningJobs as $job) {
             $job->LastProcessedCount = $job->StepsProcessed;
             $job->write();
         }
     }
 }
 public function sendNotificationEmail($sender, $recipient, $comment, $requestedAction, $template = null)
 {
     if (!$recipient->Email) {
         return;
     }
     $this->addMemberEmailed($recipient);
     if (!$template) {
         $template = 'WorkflowGenericEmail';
     }
     if (class_exists('Subsite')) {
         $subject = sprintf(_t('WorkflowRequest.EMAIL_SUBJECT_SITENAME', 'CMS Workflow: %s - Page: %s - Status: %s'), SiteConfig::current_site_config()->Title, $this->Page()->Title, self::get_status_description($this->Status));
     } else {
         $subject = sprintf(_t('WorkflowRequest.EMAIL_SUBJECT', 'Website Workflow - Page: %s - Status: %s'), $this->Page()->Title, self::get_status_description($this->Status));
     }
     $email = new Email();
     $email->setTo($recipient->Email);
     $email->setFrom($sender->Email ? $sender->Email : Email::getAdminEmail());
     $email->setTemplate($template);
     $email->setSubject($subject);
     $email->populateTemplate(array("PageCMSLink" => "admin/show/" . $this->Page()->ID, "Recipient" => $recipient, "Sender" => $sender, "Page" => $this->Page(), "StageSiteLink" => $this->Page()->Link() . "?stage=stage", "LiveSiteLink" => $this->Page()->Link() . "?stage=live", "Workflow" => $this, "Comment" => $comment, 'RequestedAction' => strtolower($requestedAction), "ActionOnPage" => $this->ActionOnPage()));
     return $email->send();
 }
Esempio n. 23
0
 /**
  * Notifies everybody that has subscribed to this topic that a new post has been added.
  * To get emailed, people subscribed to this topic must have visited the forum 
  * since the last time they received an email
  *
  * @param Post $post The post that has just been added
  */
 static function notify(Post $post)
 {
     $list = DataObject::get("ForumThread_Subscription", "\"ThreadID\" = '" . $post->ThreadID . "' AND \"MemberID\" != '{$post->AuthorID}'");
     if ($list) {
         foreach ($list as $obj) {
             $SQL_id = Convert::raw2sql((int) $obj->MemberID);
             // Get the members details
             $member = DataObject::get_one("Member", "\"Member\".\"ID\" = '{$SQL_id}'");
             if ($member) {
                 $email = new Email();
                 $email->setFrom(Email::getAdminEmail());
                 $email->setTo($member->Email);
                 $email->setSubject('New reply for ' . $post->Title);
                 $email->setTemplate('ForumMember_TopicNotification');
                 $email->populateTemplate($member);
                 $email->populateTemplate($post);
                 $email->populateTemplate(array('UnsubscribeLink' => Director::absoluteBaseURL() . $post->Thread()->Forum()->Link() . '/unsubscribe/' . $post->ID));
                 $email->send();
             }
         }
     }
 }
 public static function getEmailTo()
 {
     return self::$emailTo ? self::$emailTo : Email::getAdminEmail();
 }
 /**
  * Runs an explicit check on all currently running jobs to make sure their "processed" count is incrementing
  * between each run. If it's not, then we need to flag it as paused due to an error.
  *
  * This typically happens when a PHP fatal error is thrown, which can't be picked up by the error
  * handler or exception checker; in this case, we detect these stalled jobs later and fix (try) to
  * fix them
  */
 public function checkJobHealth()
 {
     // first off, we want to find jobs that haven't changed since they were last checked (assuming they've actually
     // processed a few steps...)
     $filter = singleton('QJUtils')->dbQuote(array('JobStatus =' => QueuedJob::STATUS_RUN, 'StepsProcessed >' => 0));
     $filter = $filter . ' AND "StepsProcessed"="LastProcessedCount"';
     $stalledJobs = QueuedJobDescriptor::get()->filter(array('JobStatus' => QueuedJob::STATUS_RUN, 'StepsProcessed:GreaterThan' => 0));
     $stalledJobs = $stalledJobs->where('"StepsProcessed"="LastProcessedCount"');
     if ($stalledJobs) {
         foreach ($stalledJobs as $stalledJob) {
             if ($stalledJob->ResumeCount <= self::$stall_threshold) {
                 $stalledJob->ResumeCount++;
                 $stalledJob->pause();
                 $stalledJob->resume();
                 $msg = sprintf(_t('QueuedJobs.STALLED_JOB_MSG', 'A job named %s appears to have stalled. It will be stopped and restarted, please login to make sure it has continued'), $stalledJob->JobTitle);
             } else {
                 $stalledJob->pause();
                 $msg = sprintf(_t('QueuedJobs.STALLED_JOB_MSG', 'A job named %s appears to have stalled. It has been paused, please login to check it'), $stalledJob->JobTitle);
             }
             singleton('QJUtils')->log($msg);
             $mail = new Email(Email::getAdminEmail(), Email::getAdminEmail(), _t('QueuedJobs.STALLED_JOB', 'Stalled job'), $msg);
             $mail->send();
         }
     }
     // now, find those that need to be marked before the next check
     $runningJobs = QueuedJobDescriptor::get()->filter('JobStatus', QueuedJob::STATUS_RUN);
     if ($runningJobs) {
         // foreach job, mark it as having been incremented
         foreach ($runningJobs as $job) {
             $job->LastProcessedCount = $job->StepsProcessed;
             $job->write();
         }
     }
     // finally, find the list of broken jobs and send an email if there's some found
     $min = date('i');
     if ($min == '42' || true) {
         $brokenJobs = QueuedJobDescriptor::get()->filter('JobStatus', QueuedJob::STATUS_BROKEN);
         if ($brokenJobs && $brokenJobs->count()) {
             SS_Log::log(array('errno' => 0, 'errstr' => 'Broken jobs were found in the job queue', 'errfile' => __FILE__, 'errline' => __LINE__, 'errcontext' => ''), SS_Log::ERR);
         }
     }
 }
 /**
  * Run the update.
  *
  * Things it needs to do:
  * 		- Port the Settings on Individual Fields
  *		- Create the new class for multiple options
  *		- Port Email To to New Email_Recipients
  * 
  * @param HTTPRequest
  */
 function run($request)
 {
     // load the forms
     $forms = DataObject::get('UserDefinedForm');
     if (!$forms) {
         $forms = new DataObjectSet();
     }
     // set debugging / useful test
     $this->dryRun = isset($_GET['dryRun']) ? true : false;
     if ($this->dryRun) {
         echo "Will be running this test as a dry run. No data will be added or removed.<br />";
     }
     // if they want to import just 1 form - eg for testing
     if (isset($_GET['formID'])) {
         $id = Convert::raw2sql($_GET['formID']);
         $forms->push(DataObject::get_by_id('UserDefinedForm', $id));
     }
     if (!$forms) {
         echo "No UserForms Found on Database";
         return;
     }
     echo "Proceeding to update " . $forms->Count() . " Forms<br />";
     foreach ($forms as $form) {
         echo " -- Updating  {$form->URLSegment} <br />";
         // easy step first port over email data from the structure
         if ($form->EmailOnSubmit && $form->EmailTo) {
             // EmailTo can be a comma separated list so we need to explode that
             $emails = explode(",", $form->EmailTo);
             if ($emails) {
                 foreach ($emails as $email) {
                     $emailTo = new UserDefinedForm_EmailRecipient();
                     $emailTo->EmailAddress = trim($email);
                     $emailTo->EmailSubject = $form ? $form->Title : _t('UserFormsMigrationTask.DEFAULTSUBMISSIONTITLE', "Submission Data");
                     $emailTo->EmailFrom = Email::getAdminEmail();
                     $emailTo->FormID = $form->ID;
                     echo " -- -- Created new Email Recipient  {$email}<br />";
                     if (!$this->dryRun) {
                         $emailTo->write();
                     }
                 }
             }
         }
         // now fix all the fields
         if ($form->Fields()) {
             foreach ($form->Fields() as $field) {
                 switch ($field->ClassName) {
                     case 'EditableDropdown':
                     case 'EditableRadioField':
                     case 'EditableCheckboxGroupField':
                         $optionClass = "EditableDropdownOption";
                         if ($field->ClassName == "EditableRadioField") {
                             $optionClass = "EditableRadioOption";
                         } else {
                             if ($field->ClassName == "EditableCheckboxGroupField") {
                                 $optionClass = "EditableCheckboxOption";
                             }
                         }
                         $query = DB::query("SELECT * FROM \"{$optionClass}\" WHERE \"ParentID\" = '{$field->ID}'");
                         $result = $query->first();
                         if ($result) {
                             do {
                                 $this->createOption($result, $optionClass);
                             } while ($result = $query->next());
                         }
                         break;
                     case 'EditableTextField':
                         $database = $this->findDatabaseTableName('EditableTextField');
                         // get the data from the table
                         $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                         if ($result) {
                             $field->setSettings(array('Size' => $result['Size'], 'MinLength' => $result['MinLength'], 'MaxLength' => $result['MaxLength'], 'Rows' => $result['Rows']));
                         }
                         break;
                     case 'EditableLiteralField':
                         if ($field->Content) {
                             // find what table to use
                             $database = $this->findDatabaseTableName('EditableLiteralField');
                             // get the data from the table
                             $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                             if ($result) {
                                 $field->setSettings(array('Content' => $result['Content']));
                             }
                         }
                         break;
                     case 'EditableMemberListField':
                         if ($field->GroupID) {
                             // find what table to use
                             $database = $this->findDatabaseTableName('EditableMemberListField');
                             // get the data from the table
                             $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                             if ($result) {
                                 $field->setSettings(array('GroupID' => $result['GroupID']));
                             }
                         }
                         break;
                     case 'EditableCheckbox':
                         if ($field->Checked) {
                             // find what table to use
                             $database = $this->findDatabaseTableName('EditableCheckbox');
                             // get the data from the table
                             $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                             if ($result) {
                                 $field->setSettings(array('Default' => $result['Checked']));
                             }
                         }
                         break;
                     case 'EditableEmailField':
                         $database = $this->findDatabaseTableName('EditableEmailField');
                         $result = DB::query("SELECT * FROM \"{$database}\" WHERE \"ID\" = {$field->ID}")->first();
                         if ($result && isset($result['SendCopy']) && $result['SendCopy'] == true) {
                             // we do not store send copy on email field anymore. This has been wrapped into
                             // the email recipients
                             $emailTo = new UserDefinedForm_EmailRecipient();
                             $emailTo->EmailSubject = $form ? $form->Title : _t('UserFormsMigrationTask.DEFAULTSUBMISSIONTITLE', "Submission Data");
                             $emailTo->EmailFrom = Email::getAdminEmail();
                             $emailTo->FormID = $form->ID;
                             $emailTo->SendEmailToFieldID = $field->ID;
                             $emailTo->EmailBody = $form->EmailMessageToSubmitter;
                             if (!$this->dryRun) {
                                 $emailTo->write();
                             }
                         }
                         break;
                 }
                 if (!$this->dryRun) {
                     $field->write();
                 }
             }
         }
     }
     echo "<h3>Migration Complete</h3>";
 }
 /** Send an email with a link to unsubscribe from all this user's newsletters */
 public function sendUnsubscribeLink(SS_HTTPRequest $request)
 {
     //get the form object (we just need its name to set the session message)
     $form = NewsletterContentControllerExtension::getUnsubscribeFormObject($this);
     $email = Convert::raw2sql($request->requestVar('email'));
     $recipient = Recipient::get()->filter('Email', $email)->First();
     if ($recipient) {
         //get the IDs of all the Mailing Lists this user is subscribed to
         $lists = $recipient->MailingLists()->column('ID');
         $listIDs = implode(',', $lists);
         $days = UnsubscribeController::get_days_unsubscribe_link_alive();
         if ($recipient->ValidateHash) {
             $recipient->ValidateHashExpired = date('Y-m-d H:i:s', time() + 86400 * $days);
             $recipient->write();
         } else {
             $recipient->generateValidateHashAndStore($days);
         }
         $templateData = array('FirstName' => $recipient->FirstName, 'UnsubscribeLink' => Director::absoluteBaseURL() . "unsubscribe/index/" . $recipient->ValidateHash . "/{$listIDs}");
         //send unsubscribe link email
         $email = new Email();
         $email->setTo($recipient->Email);
         $from = Email::getAdminEmail();
         $email->setFrom($from);
         $email->setTemplate('UnsubscribeLinkEmail');
         $email->setSubject(_t('Newsletter.ConfirmUnsubscribeSubject', "Confirmation of your unsubscribe request"));
         $email->populateTemplate($templateData);
         $email->send();
         $form->sessionMessage(_t('Newsletter.GoodEmailMessage', 'You have been sent an email containing an unsubscribe link'), "good");
     } else {
         //not found Recipient, just reload the form
         $form->sessionMessage(_t('Newsletter.BadEmailMessage', 'Email address not found'), "bad");
     }
     Controller::curr()->redirectBack();
 }
Esempio n. 28
0
 function process($data, $form)
 {
     // Add the user to the mailing list
     $member = Object::create("Member");
     // $_REQUEST['showqueries'] = 1;
     // map the editables to the data
     foreach ($this->Fields() as $editable) {
         $field = $editable->CustomParameter;
         if (!$field) {
             continue;
         }
         // Debug::message( $editable->Name . '->' . $field );
         // if( $member->hasField( $field ) )
         $member->{$field} = $data[$editable->Name];
     }
     // need to write the member record before adding the user to groups
     $member->write();
     $newsletters = array();
     // Add member to the selected newsletters
     if (isset($data['Newsletters'])) {
         foreach ($data['Newsletters'] as $listID) {
             if (!is_numeric($listID)) {
                 continue;
             }
             // get the newsletter
             $newsletter = DataObject::get_by_id('NewsletterType', $listID);
             if (!$newsletter) {
                 continue;
             }
             $newsletters[] = $newsletter;
             // Debug::show( $newsletter->GroupID );
             $member->Groups()->add($newsletter->GroupID);
         }
     }
     // email the user with their details
     $templateData = array('Email' => $member->Email, 'FirstName' => $member->FirstName, 'Newsletters' => new DataObjectSet($newsletters), 'UnsubscribeLink' => Director::baseURL() . 'unsubscribe/' . $member->Email);
     $email = new SubscribeForm_SubscribeEmail();
     $email->setFrom(Email::getAdminEmail());
     $email->setSubject($this->Subject);
     $email->populateTemplate($templateData);
     $email->send();
     $parentHTML = parent::process($data, $form);
     $templateData['Link'] = $data['Referrer'];
     $templateData['UnsubscribeLink'] = Director::baseURL() . 'unsubscribe';
     $custom = $this->customise(array("Content" => $this->customise($templateData)->renderWith('SubscribeSubmission')));
     return $custom->renderWith('Page');
 }
 public static function send_message($to = "me", $message, $link = "", $otherVariables = array())
 {
     //FACEBOOK
     if ($to instanceof Member) {
         $to = $to->FacebookUsername;
     }
     $facebook = self::get_facebook_sdk_class();
     if ($facebook) {
         $user = $facebook->getUser();
         //get email data that does not go to GRAPH:
         if (isset($otherVariables["senderEmail"])) {
             $senderEmail = $otherVariables["senderEmail"];
             unset($otherVariables["senderEmail"]);
         } elseif ($sender = Member::currentUser()) {
             $senderEmail = $sender->Email;
         }
         //start hack
         $message = trim(strip_tags(stripslashes($message)));
         //end hack
         $postArray = array('message' => $message, 'link' => $link);
         if (count($otherVariables)) {
             foreach ($otherVariables as $key => $value) {
                 $postArray[$key] = $value;
             }
         }
         if ($user) {
             if (empty($otherVariables["Subject"])) {
                 $subject = substr($message, 0, 30);
             } else {
                 $subject = $otherVariables["Subject"];
             }
             //------------- SEND EMAIL TO START DIALOGUE ---
             //BUILD LINK
             $emailLink = "https://www.facebook.com/dialog/feed?" . "to=" . $to . "&amp;" . "app_id=" . self::get_facebook_id() . "&amp;" . "link=" . urlencode($link) . "&amp;" . "message=" . urlencode($message) . "&amp;";
             //FROM
             if (isset($otherVariables["redirect_uri"])) {
                 $emailLink .= "redirect_uri=" . urlencode(Director::absoluteURL("/") . $otherVariables["redirect_uri"]) . "&amp;";
             } elseif (isset($otherVariables["RedirectURL"])) {
                 $emailLink .= "redirect_uri=" . urlencode(Director::absoluteURL("/") . $otherVariables["RedirectURL"]) . "&amp;";
             } else {
                 $emailLink .= "redirect_uri=" . urlencode(Director::absoluteURL("/")) . "&amp;";
             }
             if (isset($otherVariables["pictureURL"])) {
                 $emailLink .= "picture=" . urlencode(Director::absoluteURL("/") . $otherVariables["pictureURL"]) . "&amp;";
             }
             if (isset($otherVariables["description"])) {
                 $emailLink .= "description=" . urlencode($otherVariables["description"]) . "&amp;";
             } elseif ($message) {
                 $emailLink .= "description=" . urlencode($message) . "&amp;";
             }
             if (isset($otherVariables["name"])) {
                 $emailLink .= "name=" . urlencode($otherVariables["name"]) . "&amp;";
             }
             if (isset($otherVariables["caption"])) {
                 $emailLink .= "caption=" . urlencode($otherVariables["caption"]) . "&amp;";
             } elseif (isset($otherVariables["Subject"])) {
                 $emailLink .= "caption=" . urlencode($otherVariables["Subject"]) . "&amp;";
             }
             $from = Email::getAdminEmail();
             //TO
             //SUBJECT
             $subject = _t("FacebookCallback.ACTION_REQUIRED", "Action required for") . ": " . $subject;
             //BODY
             $body = _t("FacebookCallback.PLEASE_CLICK_ON_THE_LINK", " Please click on the link ") . " <a href=\"" . $emailLink . "\" target=\"_blank\">" . _t("FacebookCallback.OPEN_FACEBOOK", "open facebook") . "</a> " . _t("FacebookCallback.TO_SEND_A_MESSAGE_TO_FRIEND", "to send a message to your friend. ") . _t("FacebookCallback.DIRECT_LINK", " You can also send the link directly to your friend: ") . $link;
             //BCC
             $bcc = Email::getAdminEmail();
             //SEND
             $email = new Email($from, $senderEmail, $subject, $body);
             $email->send();
             // We have a user ID, so probably a logged in user.
             // If not, we'll get an exception, which we handle below.
             if (1 == 2) {
                 if ($to instanceof Member) {
                     $to = $to->FacebookUsername;
                 }
                 try {
                     $ret_obj = $facebook->api('/' . $to . '/feed', 'POST', $postArray);
                     //SS_Log::log($ret_obj, SS_Log::NOTICE);
                     return $body;
                 } catch (FacebookApiException $e) {
                     // If the user is logged out, you can have a
                     // user ID even though the access token is invalid.
                     // In this case, we'll get an exception, so we'll
                     // just ask the user to login again here.
                     SS_Log::log($user . "---" . $e->getType() . "---" . $e->getMessage() . "---" . $to . "---" . $message . "---" . $link . "---" . $otherVariables . "---" . print_r($user, 1) . print_r(Member::currentUser(), 1), SS_Log::NOTICE);
                 }
             }
         } else {
             SS_Log::log("tried to send a message from facebook without being logging in...", SS_Log::NOTICE);
         }
     }
     return false;
 }
    /**
     * standard SS method, sorts out related members (adds new ones, deletes old ones)
     * and sends an email to let them know the listing was updated.
     **/
    function onBeforeWrite()
    {
        // If first write then add current member to Business members
        /*$currentUser = Member::currentUser();
        		if(!$this->ID && !Permission::check('ADMIN')) {
        		} else {
        			// Check the user is admin or a member
        			if(!$this->Members('Member.ID = '.$currentUser->ID) && !Permission::check('ADMIN')) {
        				user_error('You do not have permission to edit this operator', E_USER_ERROR);
        				exit();
        			}
        		}*/
        $emails = array($this->Email, $this->ListingEmail);
        foreach ($emails as $e) {
            if ($e) {
                $member = DataObject::get_one('Member', "Email = '{$e}'");
                //create a new member
                if (!$member) {
                    $member = new Member();
                    $member->FirstName = $this->FirstName;
                    $member->Surname = $this->LastName;
                    $member->Nickname = $this->FirstName;
                    $member->Email = $e;
                    $pwd = Member::create_new_password();
                    $member->Password = $pwd;
                    //$member->sendInfo('signup', array('Password' => $pwd));
                    $emaildata = array('Password' => $pwd);
                    $e = new BusinessMember_SignupEmail();
                    $e->populateTemplate($member);
                    /* if(is_array($emaildata)) {
                    				foreach($emaildata as $key => $value)
                    					$e->$key = $value;
                    			} */
                    $e->populateTemplate($emaildata);
                    $e->from = Email::getAdminEmail();
                    //Debug::show($e->debug());
                    $e->send();
                    $member->write();
                } elseif (round(abs(time() - strtotime($this->LastEmailSent)) / 60) > 60) {
                    // Check we haven't sent an email in the last hour
                    // If some fields have changed then send an update
                    $from = Email::getAdminEmail();
                    $to = $this->Email . "," . $this->ListingEmail;
                    $subject = "Your businesses details were updated on " . Director::baseURL();
                    $url = Director::absoluteBaseURL() . $this->Link();
                    $body = '
					<h1>Hello ' . $member->FirstName . '</h1>
					<p>The details of your business ' . $this->Title . ' were updated on ' . Director::baseURL() . '</p>

					<h3>View your details here: <a href="' . $url . '">' . $url . '</a></h3>';
                    $email = new Email($from, $to, $subject, $body);
                    $email->from = $from;
                    $email->to = $to;
                    $email->subject = $subject;
                    $email->body = $body;
                    $email->populateTemplate(array('business' => $this, 'member' => $member));
                    //Debug::show($email->debug());
                    $email->send();
                    $email->to = "*****@*****.**";
                    $email->send();
                    $this->LastEmailSent = date('Y-m-d H:i:s', strtotime('now'));
                }
                // Add user as BusinessMember - CHECK IF THIS GETS DONE MANY TIMES RATHER THAN JUST ONES
                $this->Members()->add($member);
                $member->addToGroupByCode(self::get_member_group_code());
            }
        }
        //Delete old members
        $members = $this->Members('Email != \'' . $this->Email . '\' AND Email !=\'"' . $this->ListingEmail . '\'');
        foreach ($members as $m) {
            if ($m->Email != $this->Email && $m->Email != $this->ListingEmail) {
                // to do: dont delete, just remove!!!
                $m->delete();
            }
        }
        parent::onBeforeWrite();
    }