コード例 #1
0
 /**
  * Delete templates by module name
  *
  * @param string $name
  * @return boolean
  */
 function deleteByModule($name)
 {
     $delete = EmailTemplates::delete(array('module = ?', $name));
     if ($delete && !is_error($delete)) {
         db_execute('DELETE FROM ' . TABLE_PREFIX . 'email_template_translations WHERE module = ?', $name);
     }
     // if
     return $delete;
 }
コード例 #2
0
ファイル: EmailTemplateApi.php プロジェクト: romeo14/pow
 public static function getAllTemplates()
 {
     $models = EmailTemplates::model()->findAll();
     if ($models) {
         return $models;
     } else {
         return false;
     }
 }
コード例 #3
0
ファイル: EmailHelper.php プロジェクト: jasonhai/onehome
 public static function bindEmailContent($emailTemplateId, $param, $to, $cc = null, $from = null)
 {
     $modelEmailTemplate = EmailTemplates::model()->findByPk($emailTemplateId);
     if (!empty($modelEmailTemplate)) {
         $message = $modelEmailTemplate->email_body;
         $subject = $modelEmailTemplate->email_subject;
         if (!empty($param)) {
             foreach ($param as $key => $value) {
                 $message = str_replace($key, $value, $message);
                 $subject = str_replace($key, $value, $subject);
             }
         }
         // Send a email to patient
         $data = array('subject' => $subject, 'message' => $message, 'to' => $to, 'cc' => $cc, 'from' => empty($from) ? Yii::app()->params['autoEmail'] : $from);
         self::sendMail($data);
     }
 }
コード例 #4
0
 protected function doJob($arg)
 {
     $tomorrow = strtotime("+ 12 day", strtotime(date('Y-m-d H:i:s')));
     $mAppointment = Appointment::model()->findAll(array('condition' => 't.date_appointment < "' . date('Y-m-d H:i:s', $tomorrow) . '" AND t.date_appointment > "' . date('Y-m-d H:i:s') . '"', 'order' => 't.date_appointment ASC'));
     if (count($mAppointment) > 0) {
         foreach ($mAppointment as $eApp) {
             foreach ($eApp->bookings as $booking) {
                 if ($booking->email_reminded == 0) {
                     //send email notification to doctor
                     $modelEmailTemplate = EmailTemplates::model()->findByPk(8);
                     $dataEmail = array($booking->appointment->users->first_name . ' ' . $booking->appointment->users->last_name, $booking->user->first_name . ' ' . $booking->user->last_name, $booking->user->email, $booking->user->phone, date('l, d M Y, g:i A', strtotime($booking->appointment->date_appointment)), $booking->id, $booking->user->first_name . ' ' . $booking->user->last_name);
                     $pattern = array('{DOCTOR_NAME}', '{PATIENT_NAME}', '{PATIENT_EMAIL}', '{PATIENT_PHONE}', '{DATE_APPOINTMENT}', '{BOOKING_ID}', '{BOOKING_NAME}');
                     $message = str_replace($pattern, $dataEmail, $modelEmailTemplate->email_body);
                     $subject = $modelEmailTemplate->email_subject;
                     $data = array('subject' => $subject, 'params' => array('message' => $message), 'view' => 'message', 'to' => $booking->appointment->users->email, 'from' => Yii::app()->params['autoEmail']);
                     CmsEmail::mail($data);
                     //send email notification to patient
                     $modelEmailTemplate = EmailTemplates::model()->findByPk(7);
                     $dataEmail = array($booking->appointment->users->first_name . ' ' . $booking->appointment->users->last_name, $booking->user->first_name . ' ' . $booking->user->last_name, $booking->appointment->users->doctors->main_specialty, date('l, d M Y, g:i A', strtotime($booking->appointment->date_appointment)), $booking->id, $booking->appointment->address->address);
                     $pattern = array('{DOCTOR_NAME}', '{PATIENT_NAME}', '{DOCTOR_SPECIALTY}', '{DATE_APPOINTMENT}', '{BOOKING_ID}', '{DOCTOR_ADDRESS}');
                     $message = str_replace($pattern, $dataEmail, $modelEmailTemplate->email_body);
                     $subject = $modelEmailTemplate->email_subject;
                     $data = array('subject' => $subject, 'params' => array('message' => $message), 'view' => 'message', 'to' => $booking->user->email, 'from' => Yii::app()->params['autoEmail']);
                     CmsEmail::mail($data);
                     $booking->email_reminded = 1;
                     $booking->update(array('email_reminded'));
                     $this->index++;
                     //count email is sent for current cron job
                     if ($this->index >= $this->max) {
                         break;
                     }
                 }
             }
         }
     } else {
         return;
     }
 }
コード例 #5
0
 /**
  * Returns the data model based on the primary key given in the GET variable.
  * If the data model is not found, an HTTP exception will be raised.
  * @param integer the ID of the model to be loaded
  */
 public function loadModel($id)
 {
     $model = EmailTemplates::model()->findByPk($id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
コード例 #6
0
 /**
  * Send email to list of recipients
  * 
  * $to is a list of users who need to receive email notifications. If this 
  * function gets list of email addresses default language will be used. If 
  * we get User instances we'll use language set as prefered on their profile 
  * page
  * 
  * $to can also be a single user or email address
  * 
  * $tpl is a script in format module/name. If / is not present activeCollab 
  * will assume that template is in system module
  * 
  * Context is object that this email is primary related to
  * 
  * $attachments is array of attachments that are structured like this
  *    path -> path to file
  *    name -> name which will be displayed in email (if ommited original filename will be used)
  *    mime_type -> file mime type (if ommited system will determine mime type automatically)
  * here is sample of one $attachments array
  *    $attachments = array(
  *      array('path' => '/work/picture3.png', 'name' => 'simple_file_name.png', 'mime_type' => 'image/png')
  *    );
  * 
  * @param array $to
  * @param string $tpl
  * @param array $replacements
  * @param mixed $context
  * @param array $attachments
  * @return boolean
  */
 function send($to, $tpl, $replacements = null, $context = null, $attachments = null)
 {
     static $mark_as_bulk = null, $empty_return_path = null;
     if (isset($this) && instance_of($this, 'ApplicationMailer')) {
         if (!$this->connected) {
             $this->connect();
         }
         // if
         if (!is_foreachable($to)) {
             if (instance_of($to, 'User') || is_valid_email($to)) {
                 $to = array($to);
             } else {
                 return true;
                 // no recipients
             }
             // if
         }
         // if
         if (strpos($tpl, '/') === false) {
             $template_module = SYSTEM_MODULE;
         } else {
             list($template_module, $template_name) = explode('/', $tpl);
         }
         // if
         $template = EmailTemplates::findById(array('module' => $template_module, 'name' => $template_name));
         if (!instance_of($template, 'EmailTemplate')) {
             return false;
         }
         // if
         $owner_company = get_owner_company();
         if (is_array($replacements)) {
             $replacements['owner_company_name'] = $owner_company->getName();
         } else {
             $replacements = array('owner_company_name' => $owner_company->getName());
         }
         // if
         // Array of messages and recipients organized by language
         $to_send = array();
         // Set default locale (built in one)
         $default_locale = BUILT_IN_LOCALE;
         // Do we have a default language set
         $default_language_id = ConfigOptions::getValue('language');
         if ($default_language_id) {
             $default_language = Languages::findById($default_language_id);
             if (instance_of($default_language, 'Language') && !$default_language->isBuiltIn()) {
                 $default_locale = $default_language->getLocale();
             }
             // if
         }
         // if
         // Cache of loaded languages
         $languages = array();
         // Get from email and from name
         $from_email = ConfigOptions::getValue('notifications_from_email');
         $from_name = ConfigOptions::getValue('notifications_from_name');
         if (!is_valid_email($from_email)) {
             $from_email = ADMIN_EMAIL;
         }
         // if
         if (empty($from_name)) {
             $from_name = $owner_company->getName();
         }
         // if
         // Now prepare messages
         foreach ($to as $recipient) {
             $locale = $default_locale;
             if (instance_of($recipient, 'User')) {
                 $locale = $recipient->getLocale($default_locale);
                 $recipient_name = $recipient->getDisplayName();
                 $recipient_email = $recipient->getEmail();
                 // If same reset name... "name@site.com <*****@*****.**>" can cause
                 // problems with some servers
                 if ($recipient_name == $recipient_email) {
                     $recipient_name = null;
                 }
                 // if
             } else {
                 $recipient_name = null;
                 $recipient_email = $recipient;
             }
             // if
             $language = isset($languages[$locale]) ? $languages[$locale] : Languages::findByLocale($locale);
             // We have message prepared, just need to add a recipient
             //BOF:mod
             //if(isset($to_send[$locale])) {
             if (isset($to_send[$locale]) && $tpl != 'resources/new_comment') {
                 //EOF:moid
                 $to_send[$locale]['recipients']->add($recipient_email, $recipient_name);
                 // Need to prepare message and add first recipient
             } else {
                 //BOF:mod 20110711 ticketid231
                 if ($tpl == 'resources/new_comment') {
                     $mark_actionrequest_complete = '';
                     $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                     mysql_select_db(DB_NAME);
                     $query = "select a.is_action_request, b.project_id from healingcrystals_assignments_action_request a inner join healingcrystals_project_objects b on a.comment_id=b.id where a.comment_id='" . $replacements['comment_id'] . "' and a.user_id='" . $recipient->getId() . "'";
                     $result = mysql_query($query);
                     if (mysql_num_rows($result)) {
                         $info = mysql_fetch_assoc($result);
                         if ($info['is_action_request'] == '1') {
                             $mark_actionrequest_complete = '<div style="margin:5px 0 5px 0;"><a href="' . assemble_url('project_comment_action_request_completed', array('project_id' => $info['project_id'], 'comment_id' => $replacements['comment_id'])) . '">Click here to Mark this Action Request Complete</a></div>';
                         }
                     }
                     mysql_close($link);
                     $replacements['mark_actionrequest_complete'] = $mark_actionrequest_complete;
                 }
                 //EOF:mod 20110711 ticketid231
                 $subject = $template->getSubject($locale);
                 $body = $template->getBody($locale);
                 foreach ($replacements as $k => $v) {
                     if (is_array($v)) {
                         $v = isset($v[$locale]) ? $v[$locale] : array_shift($v);
                     }
                     // if
                     $subject = str_replace(":{$k}", $v, $subject);
                     if (str_ends_with($k, '_body')) {
                         $body = str_replace(":{$k}", $v, $body);
                     } else {
                         //$body = str_replace(":$k", clean($v), $body);
                         $body = str_replace(":{$k}", $v, $body);
                     }
                     // if
                 }
                 // foreach
                 //BOF:mod
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 if ($tpl=='resources/new_comment'){
                 	$add_to_subject = '';
                 	            $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
                 				mysql_select_db(DB_NAME);
                 				$query = "select a.is_action_request, a.is_fyi, a.priority_actionrequest, b.project_id from healingcrystals_assignments_action_request a inner join healingcrystals_project_objects b on a.comment_id=b.id where a.comment_id='" . $replacements['comment_id'] . "' and a.user_id='" . $recipient->getId() . "'";
                 				$result = mysql_query($query, $link);
                 				if (mysql_num_rows($result)){
                 					$info = mysql_fetch_assoc($result);
                 					$flag_action_request = $info['is_action_request'];
                 					$flag_fyi = $info['is_fyi'];
                 					$priority = $info['priority_actionrequest'];
                 					if ($flag_action_request=='1'){
                 						switch($priority){
                 							case PRIORITY_LOWEST:
                 								$priority_desc = 'Lowest Priority ';
                 								break;
                 							case PRIORITY_LOW:
                 								$priority_desc = 'Low Priority ';
                 								break;
                 							case PRIORITY_NORMAL:
                 								$priority_desc = 'Normal Priority ';
                 								break;
                 							case PRIORITY_HIGH:
                 								$priority_desc = 'High Priority ';
                 								break;
                 							case PRIORITY_HIGHEST:
                 								$priority_desc = 'Highest Priority ';
                 								break;
                 							default:
                 								$priority_desc = '';
                 						}
                 						$add_to_subject .= $priority_desc . 'Action Request';
                 						
                 					}
                 					if ($flag_fyi=='1'){
                 						if (!empty($add_to_subject)){
                 							$add_to_subject .= '/';
                 						}
                 						$add_to_subject .= 'FYI';
                 						$body = '<a href="' . assemble_url('project_comment_fyi_read', array('project_id' => $info['project_id'], 'comment_id' => $replacements['comment_id'])) . '">Mark this FYI Notification as Read</a>' . "<br>\n" . $body;
                 					}
                 					if (!empty($add_to_subject)){
                 						$add_to_subject .= ' - ';
                 					}
                 				}
                 				mysql_close($link);
                 	            $subject =  $add_to_subject . $subject;
                 }
                 //EOF:mod
                 //BOF:mod 20111101
                 */
                 //EOF:mod 20111101
                 //BOF:mod 20111110 #493
                 if ($tpl == 'resources/new_comment') {
                     $subject .= ' [CID' . $replacements['comment_id'] . ']';
                 }
                 //EOF:mod 20111110 #493
                 event_trigger('on_prepare_email', array($tpl, $recipient_email, $context, &$body, &$subject, &$attachments, &$language, $replacements['subscribers_name']));
                 // if files need to be attached, message will be multipart
                 if (is_foreachable($attachments)) {
                     $message = new Swift_Message($subject);
                     $message->attach(new Swift_Message_Part($body, 'text/html', EMAIL_ENCODING, EMAIL_CHARSET));
                     foreach ($attachments as $attachment) {
                         $file_path = array_var($attachment, 'path', null);
                         if (file_exists($file_path)) {
                             $message->attach(new Swift_Message_Attachment(new Swift_File($file_path), array_var($attachment, 'name', basename($file_path)), array_var($attachment, 'mime_type', mime_content_type($file_path))));
                         }
                     }
                     // if
                 } else {
                     $message = new Swift_Message($subject, $body, 'text/html', EMAIL_ENCODING, EMAIL_CHARSET);
                 }
                 // if
                 // Load values...
                 if ($mark_as_bulk === null || $empty_return_path === null) {
                     $mark_as_bulk = (bool) ConfigOptions::getValue('mailing_mark_as_bulk');
                     $empty_return_path = (bool) ConfigOptions::getValue('mailing_empty_return_path');
                 }
                 // if
                 // Custom headers (to prevent auto responders)
                 if ($mark_as_bulk) {
                     $message->headers->set('Auto-Submitted', 'auto-generated');
                     $message->headers->set('Precedence', 'bulk');
                 }
                 // if
                 if ($empty_return_path) {
                     $message->headers->set('Return-Path', '<>');
                 } else {
                     $message->headers->set('Return-Path', "<{$from_email}>");
                 }
                 // if
                 if (!isset($to_send[$locale])) {
                     $to_send[$locale] = array('recipients' => new Swift_RecipientList(), 'message' => $message);
                 }
                 //BOF:mod
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 if ($tpl=='resources/new_comment'){
                     $to_send[$locale]['modified_subject'][$recipient_email] =  $subject;
                 }
                 //BOF:mod 20111101
                 */
                 //EOF:mod 20111101
                 //EOF:mod
                 $to_send[$locale]['recipients']->add($recipient_email, $recipient_name);
             }
             // if
         }
         // foreach
         if (is_foreachable($to_send)) {
             foreach ($to_send as $locale => $message_data) {
                 //BOF:mod 20111101
                 /*
                 //EOF:mod 20111101
                 $this->swift->batchSend($message_data['message'], $message_data['recipients'], new Swift_Address($from_email, $from_name), $message_data['modified_subject']);
                 //BOF:mod 20111101
                 */
                 $this->swift->batchSend($message_data['message'], $message_data['recipients'], new Swift_Address($from_email, $from_name));
                 //EOF:mod 20111101
             }
             // foreach
         }
         // if
         return true;
     } else {
         $instance =& ApplicationMailer::instance();
         return $instance->send($to, $tpl, $replacements, $context, $attachments);
     }
     // if
 }
コード例 #7
0
ファイル: CmsEmail.php プロジェクト: jasonhai/onehome
 /**
 * 
 * @param int $iEmailTemplateID
 * @param array $aSubject
 * @param array $aBody
 * @param array $sTo
 * @example  
 *          $aSubject = array('{KEY_1}' =>'value1',
                    '{KEY_2}'=>'value2',
                    '{KEY_3}'=>'value3'
                );
 
            $aBody = array('{KEY_1}' =>'value1',
                    '{KEY_2}'=>'value2',
                    '{KEY_3}'=>'value3'
                );
 * @author bb  <*****@*****.**>
 */
 public static function sendmail($iEmailTemplateID, $aSubject = null, $aBody, $sTo, $sFrom = null, $sSubject = null)
 {
     $modelEmailTemplate = is_int($iEmailTemplateID) ? EmailTemplates::model()->findByPk($iEmailTemplateID) : EmailTemplates::model()->findByAttributes(array('slug' => $iEmailTemplateID));
     if (empty($sSubject)) {
         $sSubject = $modelEmailTemplate->email_subject;
         if (is_array($aSubject) && count($aSubject) > 0) {
             foreach ($aSubject as $key => $value) {
                 $sSubject = str_replace($key, $value, $sSubject);
             }
         }
     }
     $sBody = $modelEmailTemplate->email_body;
     if (is_array($aBody) && count($aBody) > 0) {
         foreach ($aBody as $key => $value) {
             $sBody = str_replace($key, $value, $sBody);
         }
     }
     $data = array('subject' => $sSubject, 'params' => array('message' => $sBody), 'view' => 'message', 'to' => $sTo, 'from' => empty($sFrom) ? Yii::app()->params['autoEmail'] : $sFrom);
     return CmsEmail::mail($data);
 }
 /**
  * List all avilable email tempaltes and let users manage them
  *
  * @param void
  * @return null
  */
 function index()
 {
     $this->smarty->assign('grouped_templates', EmailTemplates::findGrouped());
 }
コード例 #9
0
ファイル: CandidatesUI.php プロジェクト: Hassanj343/candidats
    public function onEmailCandidates()
    {
        if ($this->_accessLevel == ACCESS_LEVEL_DEMO)
        {
            CommonErrors::fatal(COMMONERROR_PERMISSION, $this, 'Sorry, but demo accounts are not allowed to send e-mails.');
        }
        Logger::getLogger("AuieoATS")->info("inside onEmailCandidates");
        if (isset($_POST['postback']))
        {
            $templateid = $_POST['titleSelect'];
            
            $emailTo = $_POST['emailTo'];
            $emailSubject = $_POST['emailSubject'];
            
            $idlist=$_POST["idlist"];
            $obj=json_decode(urldecode($idlist),true);
            foreach($obj as $candid=>$details)
            {
                $emailBody = $_POST['emailBody'];
                $emailData=array();
                $emailData["id"]=$candid;
                $emailData["email"]=array();
                foreach($details["email"] as $emailind=>$data)
                {
                    //$objTemplate=new EmailTemplates($this->_siteID); 
                    //$rowTemplate=$objTemplate->get($templateid);
                    $emailBody=$this->renderTemplateVars($emailBody, $candid);

                    $tmpDestination = $data["email"];
                    $emailData["email"][]=array("email"=>$tmpDestination,"name"=>$tmpDestination);
                    $mailer = new Mailer($this->_siteID);
                    // FIXME: Use sendToOne()?
                    $mailerStatus = $mailer->send(
                        array($_SESSION['CATS']->getEmail(), $_SESSION['CATS']->getEmail()),
                        $emailData,
                        $emailSubject,
                        $emailBody,
                        true,
                        true
                    );
                }
            }

            $this->_template->assign('active', $this);
            $this->_template->assign('success_to', $emailTo);
            if($mailer->getError())
            {
                $this->_template->assign('error', $mailer->getError());
                $this->_template->display('./modules/candidates/emailFail.php');
            }
            else
            {
                $this->_template->assign('success', true);
                $this->_template->display('./modules/candidates/emailSuccess.php');
            }
            return;
        }
        else
        {
            if(isset($_REQUEST["idlist"]))
            {
                $db = DatabaseConnection::getInstance();
                $idlist=trim($_REQUEST["idlist"]);
                $rs = $db->getAllAssoc(sprintf(
                    'SELECT candidate_id, email1, email2, last_name, first_name '
                    . 'FROM candidate '
                    . 'WHERE candidate_id IN (%s)',
                    $idlist
                ));
				
                $emailTemplates = new EmailTemplates($this->_siteID);
                $emailTemplatesRS = $emailTemplates->getAll();
                $this->_template->assign('emailTemplatesRS', $emailTemplatesRS);
                $this->_template->assign('active', $this);
                $this->_template->assign('success', true);
                $this->_template->assign('recipients', $rs);
                $this->_template->display('./modules/candidates/emailCandidates.php');
                return;
            }
            else
            {
                $dataGrid = DataGrid::getFromRequest();

                $candidateIDs = $dataGrid->getExportIDs();

                /* Validate each ID */
                foreach ($candidateIDs as $index => $candidateID)
                {
                    if (!$this->isRequiredIDValid($index, $candidateIDs))
                    {
                        CommonErrors::fatalModal(COMMONERROR_BADINDEX, $this, 'Invalid candidate ID.');
                        return;
                    }
                }

                $db_str = implode(", ", $candidateIDs);

                $db = DatabaseConnection::getInstance();

                $rs = $db->getAllAssoc(sprintf(
                    'SELECT candidate_id, email1, email2, last_name, first_name '
                    . 'FROM candidate '
                    . 'WHERE candidate_id IN (%s)',
                    $db_str
                ));

                if(!$mailerStatus)
                {
                    CommonErrors::fatal(COMMONERROR_EMAILFAILED, NULL, $mailer->getError());
                }
                $this->_template->assign('active', $this);
                $this->_template->assign('success', true);
                $this->_template->assign('success_to', $emailTo);
                $this->_template->display('./modules/candidates/emailSuccess.php');

                //$arrTpl["privledgedUser"]=$privledgedUser;
                /*$emailTemplates = new EmailTemplates($this->_siteID);
                $emailTemplatesRS = $emailTemplates->getAll();
                $arrTpl["emailTemplatesRS"]=$emailTemplatesRS;
                $arrTpl["active"]=$this;
                $arrTpl["success"]=false;
                $arrTpl["recipients"]=$rs;
                return $arrTpl;*/
            }
        }
    }
コード例 #10
0
ファイル: CompaniesUI.php プロジェクト: rankinp/OpenCATS
 private function onEdit()
 {
     if ($this->_accessLevel < ACCESS_LEVEL_EDIT) {
         $this->listByView('Invalid user level for action.');
         return;
     }
     $companies = new Companies($this->_siteID);
     /* Bail out if we don't have a valid company ID. */
     if (!$this->isRequiredIDValid('companyID', $_POST)) {
         $this->listByView('Invalid company ID.');
         return;
     }
     /* Bail out if we don't have a valid owner user ID. */
     if (!$this->isOptionalIDValid('owner', $_POST)) {
         $this->listByView('Invalid owner user ID.');
         return;
     }
     /* Bail out if we don't have a valid billing contact ID. */
     if (!$this->isOptionalIDValid('billingContact', $_POST)) {
         $this->listByView('Invalid billing contact ID.');
         return;
     }
     $formattedPhone1 = StringUtility::extractPhoneNumber($this->getTrimmedInput('phone1', $_POST));
     if (!empty($formattedPhone1)) {
         $phone1 = $formattedPhone1;
     } else {
         $phone1 = $this->getTrimmedInput('phone1', $_POST);
     }
     $formattedPhone2 = StringUtility::extractPhoneNumber($this->getTrimmedInput('phone2', $_POST));
     if (!empty($formattedPhone2)) {
         $phone2 = $formattedPhone2;
     } else {
         $phone2 = $this->getTrimmedInput('phone2', $_POST);
     }
     $formattedFaxNumber = StringUtility::extractPhoneNumber($this->getTrimmedInput('faxNumber', $_POST));
     if (!empty($formattedFaxNumber)) {
         $faxNumber = $formattedFaxNumber;
     } else {
         $faxNumber = $this->getTrimmedInput('faxNumber', $_POST);
     }
     $url = $this->getTrimmedInput('url', $_POST);
     if (!empty($url)) {
         $formattedURL = StringUtility::extractURL($url);
         if (!empty($formattedURL)) {
             $url = $formattedURL;
         }
     }
     /* Hot company? */
     $isHot = $this->isChecked('isHot', $_POST);
     $companyID = $_POST['companyID'];
     $owner = $_POST['owner'];
     $billingContact = $_POST['billingContact'];
     /* Change ownership email? */
     if ($this->isChecked('ownershipChange', $_POST) && $owner > 0) {
         $companyDetails = $companies->get($companyID);
         $users = new Users($this->_siteID);
         $ownerDetails = $users->get($_POST['owner']);
         if (!empty($ownerDetails)) {
             $emailAddress = $ownerDetails['email'];
             /* Get the change status email template. */
             $emailTemplates = new EmailTemplates($this->_siteID);
             $statusChangeTemplateRS = $emailTemplates->getByTag('EMAIL_TEMPLATE_OWNERSHIPASSIGNCLIENT');
             if (empty($statusChangeTemplateRS) || empty($statusChangeTemplateRS['textReplaced'])) {
                 $statusChangeTemplate = '';
             } else {
                 $statusChangeTemplate = $statusChangeTemplateRS['textReplaced'];
             }
             /* Replace e-mail template variables. */
             $stringsToFind = array('%CLNTOWNER%', '%CLNTNAME%', '%CLNTCATSURL%');
             $replacementStrings = array($ownerDetails['fullName'], $companyDetails['name'], '<a href="http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) . '?m=companies&amp;a=show&amp;companyID=' . $companyID . '">' . 'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) . '?m=companies&amp;a=show&amp;companyID=' . $companyID . '</a>');
             $statusChangeTemplate = str_replace($stringsToFind, $replacementStrings, $statusChangeTemplate);
             $email = $statusChangeTemplate;
         } else {
             $email = '';
             $emailAddress = '';
         }
     } else {
         $email = '';
         $emailAddress = '';
     }
     $name = $this->getTrimmedInput('name', $_POST);
     $address = $this->getTrimmedInput('address', $_POST);
     $city = $this->getTrimmedInput('city', $_POST);
     $state = $this->getTrimmedInput('state', $_POST);
     $zip = $this->getTrimmedInput('zip', $_POST);
     $keyTechnologies = $this->getTrimmedInput('keyTechnologies', $_POST);
     $notes = $this->getTrimmedInput('notes', $_POST);
     /* Departments list editor. */
     $departmentsCSV = $this->getTrimmedInput('departmentsCSV', $_POST);
     /* Bail out if any of the required fields are empty. */
     if (empty($name)) {
         $this->listByView('Required fields are missing.');
         return;
     }
     if (!eval(Hooks::get('CLIENTS_ON_EDIT_PRE'))) {
         return;
     }
     $departments = $companies->getDepartments($companyID);
     $departmentsDifferences = ListEditor::getDifferencesFromList($departments, 'name', 'departmentID', $departmentsCSV);
     $companies->updateDepartments($companyID, $departmentsDifferences);
     if (!$companies->update($companyID, $name, $address, $city, $state, $zip, $phone1, $phone2, $faxNumber, $url, $keyTechnologies, $isHot, $notes, $owner, $billingContact, $email, $emailAddress)) {
         CommonErrors::fatal(COMMONERROR_RECORDERROR, $this, 'Failed to update company.');
     }
     if (!eval(Hooks::get('CLIENTS_ON_EDIT_POST'))) {
         return;
     }
     /* Update extra fields. */
     $companies->extraFields->setValuesOnEdit($companyID);
     /* Update contacts? */
     if (isset($_POST['updateContacts'])) {
         if ($_POST['updateContacts'] == 'yes') {
             $contacts = new Contacts($this->_siteID);
             $contacts->updateByCompany($companyID, $address, $city, $state, $zip);
         }
     }
     CATSUtility::transferRelativeURI('m=companies&a=show&companyID=' . $companyID);
 }
コード例 #11
0
ファイル: ContactsUI.php プロジェクト: rankinp/OpenCATS
 private function onEdit()
 {
     if ($this->_accessLevel < ACCESS_LEVEL_EDIT) {
         CommonErrors::fatal(COMMONERROR_PERMISSION, $this, 'Invalid user level for action.');
     }
     /* Bail out if we don't have a valid contact ID. */
     if (!$this->isRequiredIDValid('contactID', $_POST)) {
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'Invalid contact ID.');
     }
     /* Bail out if we don't have a valid company ID. */
     if (!$this->isRequiredIDValid('companyID', $_POST)) {
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'Invalid company ID.');
     }
     /* Bail out if we don't have a valid owner user ID. */
     if (!$this->isOptionalIDValid('owner', $_POST)) {
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'Invalid owner user ID.');
     }
     $contactID = $_POST['contactID'];
     $companyID = $_POST['companyID'];
     $owner = $_POST['owner'];
     $formattedPhoneWork = StringUtility::extractPhoneNumber($this->getTrimmedInput('phoneWork', $_POST));
     if (!empty($formattedPhoneWork)) {
         $phoneWork = $formattedPhoneWork;
     } else {
         $phoneWork = $this->getTrimmedInput('phoneWork', $_POST);
     }
     $formattedPhoneCell = StringUtility::extractPhoneNumber($this->getTrimmedInput('phoneCell', $_POST));
     if (!empty($formattedPhoneCell)) {
         $phoneCell = $formattedPhoneCell;
     } else {
         $phoneCell = $this->getTrimmedInput('phoneCell', $_POST);
     }
     $formattedPhoneOther = StringUtility::extractPhoneNumber($this->getTrimmedInput('phoneOther', $_POST));
     if (!empty($formattedPhoneOther)) {
         $phoneOther = $formattedPhoneOther;
     } else {
         $phoneOther = $this->getTrimmedInput('phoneOther', $_POST);
     }
     $contacts = new Contacts($this->_siteID);
     if ($this->isChecked('ownershipChange', $_POST) && $owner > 0) {
         $contactDetails = $contacts->get($contactID);
         $users = new Users($this->_siteID);
         $ownerDetails = $users->get($owner);
         if (!empty($ownerDetails)) {
             $emailAddress = $ownerDetails['email'];
             /* Get the change status email template. */
             $emailTemplates = new EmailTemplates($this->_siteID);
             $statusChangeTemplateRS = $emailTemplates->getByTag('EMAIL_TEMPLATE_OWNERSHIPASSIGNCONTACT');
             if (empty($statusChangeTemplateRS) || empty($statusChangeTemplateRS['textReplaced'])) {
                 $statusChangeTemplate = '';
             } else {
                 $statusChangeTemplate = $statusChangeTemplateRS['textReplaced'];
             }
             /* Replace e-mail template variables. */
             $stringsToFind = array('%CONTOWNER%', '%CONTFIRSTNAME%', '%CONTFULLNAME%', '%CONTCLIENTNAME%', '%CONTCATSURL%');
             $replacementStrings = array($ownerDetails['fullName'], $contactDetails['firstName'], $contactDetails['firstName'] . ' ' . $contactDetails['lastName'], $contactDetails['companyName'], '<a href="http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) . '?m=contacts&amp;a=show&amp;contactID=' . $contactID . '">' . 'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) . '?m=contacts&amp;a=show&amp;contactID=' . $contactID . '</a>');
             $statusChangeTemplate = str_replace($stringsToFind, $replacementStrings, $statusChangeTemplate);
             $email = $statusChangeTemplate;
         } else {
             $email = '';
             $emailAddress = '';
         }
     } else {
         $email = '';
         $emailAddress = '';
     }
     $firstName = $this->getTrimmedInput('firstName', $_POST);
     $lastName = $this->getTrimmedInput('lastName', $_POST);
     $title = $this->getTrimmedInput('title', $_POST);
     $department = $this->getTrimmedInput('department', $_POST);
     $reportsTo = $this->getTrimmedInput('reportsTo', $_POST);
     $email1 = $this->getTrimmedInput('email1', $_POST);
     $email2 = $this->getTrimmedInput('email2', $_POST);
     $address = $this->getTrimmedInput('address', $_POST);
     $city = $this->getTrimmedInput('city', $_POST);
     $state = $this->getTrimmedInput('state', $_POST);
     $zip = $this->getTrimmedInput('zip', $_POST);
     $notes = $this->getTrimmedInput('notes', $_POST);
     $isHot = $this->isChecked('isHot', $_POST);
     $leftCompany = $this->isChecked('leftCompany', $_POST);
     /* Departments list editor. */
     $departmentsCSV = $this->getTrimmedInput('departmentsCSV', $_POST);
     /* Bail out if any of the required fields are empty. */
     if (empty($firstName) || empty($lastName) || empty($title)) {
         CommonErrors::fatal(COMMONERROR_MISSINGFIELDS, $this, 'Required fields are missing.');
     }
     if (!eval(Hooks::get('CONTACTS_ON_EDIT_PRE'))) {
         return;
     }
     /* Update departments. */
     $companies = new Companies($this->_siteID);
     $departments = $companies->getDepartments($companyID);
     $departmentsDifferences = ListEditor::getDifferencesFromList($departments, 'name', 'departmentID', $departmentsCSV);
     $companies->updateDepartments($companyID, $departmentsDifferences);
     if (!$contacts->update($contactID, $companyID, $firstName, $lastName, $title, $department, $reportsTo, $email1, $email2, $phoneWork, $phoneCell, $phoneOther, $address, $city, $state, $zip, $isHot, $leftCompany, $notes, $owner, $email, $emailAddress)) {
         CommonErrors::fatal(COMMONERROR_RECORDERROR, $this, 'Failed to update contact.');
     }
     /* Update extra fields. */
     $contacts->extraFields->setValuesOnEdit($contactID);
     if (!eval(Hooks::get('CONTACTS_ON_EDIT_POST'))) {
         return;
     }
     CATSUtility::transferRelativeURI('m=contacts&a=show&contactID=' . $contactID);
 }
コード例 #12
0
 private function addActivityChangeStatus()
 {
     /* Bail out if we don't have a valid candidate ID. */
     if (!$this->isRequiredIDValid('candidateID', $_GET)) {
         CommonErrors::fatalModal(COMMONERROR_BADINDEX, $this, 'Invalid candidate ID.');
     }
     /* Bail out if we don't have a valid job order ID. */
     if (!$this->isOptionalIDValid('jobOrderID', $_GET)) {
         CommonErrors::fatalModal(COMMONERROR_BADINDEX, $this, 'Invalid job order ID.');
     }
     $selectedJobOrderID = $_GET['jobOrderID'];
     $candidateID = $_GET['candidateID'];
     $candidates = new Candidates($this->_siteID);
     $candidateData = $candidates->get($candidateID);
     /* Bail out if we got an empty result set. */
     if (empty($candidateData)) {
         CommonErrors::fatalModal(COMMONERROR_BADINDEX, $this);
         return;
         /*$this->fatalModal(
               'The specified candidate ID could not be found.'
           );*/
     }
     $pipelines = new Pipelines($this->_siteID);
     $pipelineRS = $pipelines->getCandidatePipeline($candidateID);
     $statusRS = $pipelines->getStatusesForPicking();
     if ($selectedJobOrderID != -1) {
         $selectedStatusID = ResultSetUtility::getColumnValueByIDValue($pipelineRS, 'jobOrderID', $selectedJobOrderID, 'statusID');
     } else {
         $selectedStatusID = -1;
     }
     /* Get the change status email template. */
     $emailTemplates = new EmailTemplates($this->_siteID);
     $statusChangeTemplateRS = $emailTemplates->getByTag('EMAIL_TEMPLATE_STATUSCHANGE');
     if (empty($statusChangeTemplateRS) || empty($statusChangeTemplateRS['textReplaced'])) {
         $statusChangeTemplate = '';
         $emailDisabled = '1';
     } else {
         $statusChangeTemplate = $statusChangeTemplateRS['textReplaced'];
         $emailDisabled = $statusChangeTemplateRS['disabled'];
     }
     /* Replace e-mail template variables. '%CANDSTATUS%', '%JBODTITLE%',
      * '%JBODCLIENT%' are replaced by JavaScript.
      */
     $stringsToFind = array('%CANDOWNER%', '%CANDFIRSTNAME%', '%CANDFULLNAME%');
     $replacementStrings = array($candidateData['ownerFullName'], $candidateData['firstName'], $candidateData['firstName'] . ' ' . $candidateData['lastName'], $candidateData['firstName'], $candidateData['firstName']);
     $statusChangeTemplate = str_replace($stringsToFind, $replacementStrings, $statusChangeTemplate);
     /* Are we in "Only Schedule Event" mode? */
     $onlyScheduleEvent = $this->isChecked('onlyScheduleEvent', $_GET);
     $calendar = new Calendar($this->_siteID);
     $calendarEventTypes = $calendar->getAllEventTypes();
     if (!eval(Hooks::get('CANDIDATE_ADD_ACTIVITY_CHANGE_STATUS'))) {
         return;
     }
     if (SystemUtility::isSchedulerEnabled() && !$_SESSION['CATS']->isDemo()) {
         $allowEventReminders = true;
     } else {
         $allowEventReminders = false;
     }
     $this->_template->assign('candidateID', $candidateID);
     $this->_template->assign('pipelineRS', $pipelineRS);
     $this->_template->assign('statusRS', $statusRS);
     $this->_template->assign('selectedJobOrderID', $selectedJobOrderID);
     $this->_template->assign('selectedStatusID', $selectedStatusID);
     $this->_template->assign('allowEventReminders', $allowEventReminders);
     $this->_template->assign('userEmail', $_SESSION['CATS']->getEmail());
     $this->_template->assign('calendarEventTypes', $calendarEventTypes);
     $this->_template->assign('statusChangeTemplate', $statusChangeTemplate);
     $this->_template->assign('onlyScheduleEvent', $onlyScheduleEvent);
     $this->_template->assign('emailDisabled', $emailDisabled);
     $this->_template->assign('isFinishedMode', false);
     $this->_template->assign('isJobOrdersMode', false);
     $this->_template->display('./modules/candidates/AddActivityChangeStatusModal.tpl');
 }
コード例 #13
0
ファイル: mass_mail.php プロジェクト: mozdial/Directory
<?php

/**
* @project ApPHP Business Directory
* @copyright (c) 2011 ApPHP
* @author ApPHP <*****@*****.**>
* @license http://www.gnu.org/licenses/
*/
// *** Make sure the file isn't accessed directly
defined('APPHP_EXEC') or die('Restricted Access');
//--------------------------------------------------------------------------
if ($objLogin->IsLoggedInAsAdmin()) {
    draw_title_bar(prepare_breadcrumbs(array(_MASS_MAIL_AND_TEMPLATES => '', _MASS_MAIL => '')));
    $objMassMail = new EmailTemplates();
    $task = isset($_POST['task']) ? prepare_input($_POST['task']) : '';
    if ($task == 'send') {
        $objMassMail->SendMassMail();
    }
    $objMassMail->DrawMassMailForm();
} else {
    draw_title_bar(_ADMIN);
    draw_important_message(_NOT_AUTHORIZED);
}
コード例 #14
0
 /**
  * Uninstall this module
  *
  * @param void
  * @return boolean
  */
 function uninstall()
 {
     db_begin_work();
     $name = $this->name;
     ProjectObjects::deleteByModule($name);
     ConfigOptions::deleteByModule($name);
     EmailTemplates::deleteByModule($name);
     cache_clear();
     $delete = $this->delete();
     if ($delete && !is_error($delete)) {
         db_commit();
         return true;
     } else {
         db_rollback();
         return $delete;
     }
     // if
 }
コード例 #15
0
ファイル: index.php プロジェクト: arp19690/newtravel
 public function register()
 {
     if (!isset($this->session->userdata['user_id'])) {
         $data = array();
         $model = new Common_model();
         if ($this->input->post()) {
             $redirect_url = base_url();
             if ($this->input->get('next')) {
                 $redirect_url = $this->input->get('next');
             }
             $arr = $this->input->post();
             //                prd($arr);
             $user_email = trim(strtolower($arr["user_email"]));
             $is_email_exists = $model->is_exists('user_id', TABLE_USERS, array('user_email' => $user_email));
             if (empty($is_email_exists)) {
                 // valid email
                 $verification_code = substr(getEncryptedString($arr['user_email'] . $arr['user_gender'] . time()), 0, 30);
                 $user_username = getUniqueUsernameFromEmail($user_email);
                 $location_details = get_location_details_from_google(trim($arr['user_location']));
                 $location_lat_long = getLatLonByAddress(trim($arr['user_location']));
                 $data_array = array('user_fullname' => $arr['user_fullname'], 'user_gender' => strtolower($arr['user_gender']), 'user_username' => $user_username, 'user_email' => $user_email, 'user_password' => md5($arr['user_password']), 'user_ipaddress' => USER_IP, 'user_useragent' => USER_AGENT, 'user_created_on' => date('Y-m-d H:i:s'), 'user_status' => '0', 'user_verification_code' => $verification_code, 'user_city' => $location_details['city'], 'user_state' => $location_details['state'], 'user_country' => $location_details['country'], 'user_location' => trim($arr['user_location']), 'user_latitude' => $location_lat_long['latitude'], 'user_longitude' => $location_lat_long['longitude']);
                 $user_id = $model->insertData(TABLE_USERS, $data_array);
                 // updating redis keys now
                 $this->redis_functions->set_user_profile_data($user_username);
                 if (USER_IP != '127.0.0.1') {
                     $verification_url = base_url('activate?code=' . $verification_code);
                     $this->load->library('EmailTemplates');
                     $EmailTemplates = new EmailTemplates();
                     $messageText = $EmailTemplates->registerEmail(ucwords($arr['user_fullname']), $verification_url);
                     $email_model = new Email_model();
                     $email_model->sendMail($arr['user_email'], 'Verification Email - ' . $this->redis_functions->get_site_setting('SITE_NAME'), $messageText);
                 }
                 $this->session->set_flashdata('success', '<strong>Success!</strong> We have sent you an email. Please verify your email address');
                 redirect($redirect_url);
             } else {
                 // invalid email
                 $this->session->set_flashdata('error', '<strong>Oops!</strong> Email already exists');
                 $this->session->set_flashdata('post', $arr);
                 redirect(base_url('register?next=' . $this->input->get('next')));
             }
         } else {
             $page_title = 'Register';
             $input_arr = array(base_url() => 'Home', '#' => $page_title);
             $breadcrumbs = get_breadcrumbs($input_arr);
             $data["breadcrumbs"] = $breadcrumbs;
             $data["page_title"] = $page_title;
             $data['meta_title'] = $data["page_title"] . ' - ' . $this->redis_functions->get_site_setting('SITE_NAME');
             $this->template->write_view("content", "pages/index/register", $data);
             $this->template->render();
         }
     } else {
         redirect('my-account');
     }
 }
コード例 #16
0
ファイル: ContactsUI.php プロジェクト: Hassanj343/candidats
    public function emailContacts()
    {
        Logger::getLogger("AuieoATS")->info("emailContacts:start");
        if ($this->_accessLevel == ACCESS_LEVEL_DEMO)
        {
            CommonErrors::fatal(COMMONERROR_PERMISSION, $this, 'Sorry, but demo accounts are not allowed to send e-mails.');
        }
        
        if(isset($_REQUEST["idlist"]))
        {
            $db = DatabaseConnection::getInstance();
            $idlist=trim($_REQUEST["idlist"]);
            $rs = $db->getAllAssoc(sprintf(
                'SELECT contact_id, email1, email2 '
                    . 'FROM contact '
                    . 'WHERE contact_id IN (%s)',
                $idlist
            ));
            $emailTemplates = new EmailTemplates($this->_siteID);
            $emailTemplatesRS = $emailTemplates->getAll();
            $this->_template->assign('emailTemplatesRS', $emailTemplatesRS);
            $this->_template->assign('active', $this);
            $this->_template->assign('success', false);
            $this->_template->assign('recipients', $rs);
            $this->_template->display('./modules/contacts/emailContacts.php');
        }
        else
        {
            $dataGrid = DataGrid::getFromRequest();

            $contactIDs = $dataGrid->getExportIDs();

            /* Validate each ID */
            foreach ($contactIDs as $index => $contactID)
            {
                if (!$this->isRequiredIDValid($index, $contactIDs))
                {
                    Logger::getLogger("AuieoATS")->error("Invalid contact ID.");
                    CommonErrors::fatalModal(COMMONERROR_BADINDEX, $this, 'Invalid contact ID.');
                    return;
                }
            }

            $db_str = implode(", ", $contactIDs);

            $db = DatabaseConnection::getInstance();

            $rs = $db->getAllAssoc(sprintf(
                'SELECT contact_id, email1, email2 '
                    . 'FROM contact '
                    . 'WHERE contact_id IN (%s)',
                $db_str
            ));

            //$this->_template->assign('privledgedUser', $privledgedUser);
            $emailTemplates = new EmailTemplates($this->_siteID);
            $emailTemplatesRS = $emailTemplates->getAll();
            $this->_template->assign('emailTemplatesRS', $emailTemplatesRS);
            $this->_template->assign('active', $this);
            $this->_template->assign('success', false);
            $this->_template->assign('recipients', $rs);
            $this->_template->display('./modules/contacts/emailContacts.php');
        }
        Logger::getLogger("AuieoATS")->info("emailContacts:end");
    }
コード例 #17
0
 function register_assignees_flag($assignees_flag = array(), $is_new_object = false)
 {
     $link = mysql_connect(DB_HOST, DB_USER, DB_PASS);
     mysql_select_db(DB_NAME);
     if (!$is_new_object) {
         $query = "delete from healingcrystals_assignments_flag_fyi_actionrequest where object_id='" . $this->getId() . "'";
         mysql_query($query, $link);
     }
     $users = array();
     foreach ($assignees_flag['flag_fyi'] as $user_id) {
         if (!array_key_exists((string) $user_id, $users)) {
             $users[(string) $user_id] = array('flag_fyi' => '0', 'flag_actionrequest' => '0', 'priority_actionrequest' => '0', 'flag_email' => '0');
         }
         $users[(string) $user_id]['flag_fyi'] = '1';
     }
     foreach ($assignees_flag['flag_actionrequest'] as $user_id) {
         if (!array_key_exists((string) $user_id, $users)) {
             $users[(string) $user_id] = array('flag_fyi' => '0', 'flag_actionrequest' => '0', 'priority_actionrequest' => '0', 'flag_email' => '0');
         }
         $users[(string) $user_id]['flag_actionrequest'] = '1';
     }
     foreach ($assignees_flag['priority_actionrequest'] as $entry) {
         $vals = explode('_', $entry);
         list($temp_user_id, $priority) = $vals;
         if (array_key_exists((string) $temp_user_id, $users) && $users[(string) $temp_user_id]['flag_actionrequest'] == '1') {
             $users[(string) $temp_user_id]['priority_actionrequest'] = $priority;
         }
     }
     foreach ($assignees_flag['flag_email'] as $user_id) {
         if (!array_key_exists((string) $user_id, $users)) {
             $users[(string) $user_id] = array('flag_fyi' => '0', 'flag_actionrequest' => '0', 'priority_actionrequest' => '0', 'flag_email' => '0');
         }
         $users[(string) $user_id]['flag_email'] = '1';
     }
     foreach ($users as $user_id => $flags) {
         $query = "insert into healingcrystals_assignments_flag_fyi_actionrequest (user_id, object_id, flag_fyi, flag_actionrequest, priority_actionrequest, email_flag) values ('" . $user_id . "', '" . $this->getId() . "', '" . $flags['flag_fyi'] . "', '" . $flags['flag_actionrequest'] . "', '" . $flags['priority_actionrequest'] . "', '" . $flags['flag_email'] . "')";
         //mysql_query("insert into testing (date_added, content)  values (now(), '" . mysql_real_escape_string($query) . "')");
         mysql_query($query, $link);
     }
     //BOF:mod 20111011 #449
     if ($is_new_object) {
         $query = "select user_id from healingcrystals_assignments_flag_fyi_actionrequest where object_id='" . $this->getId() . "' and email_flag='1'";
         $result = mysql_query($query);
         $email_to = array();
         if (mysql_num_rows($result)) {
             while ($entry = mysql_fetch_assoc($result)) {
                 $email_to[] = new User($entry['user_id']);
             }
         }
         if (count($email_to)) {
             $owner_company = get_owner_company();
             $project = $this->getProject();
             // Prepare object type translations
             if (is_foreachable($languages)) {
                 $object_type = array();
                 foreach ($languages as $language) {
                     $object_type[$language->getLocale()] = $this->getVerboseType(false, $language);
                 }
                 // foreach
             } else {
                 $object_type = $this->getVerboseType();
             }
             // if
             $created_by_id = $this->getCreatedById();
             $created_by = new User($created_by_id);
             $variables = array('details_body' => EmailTemplates::renderProjectObjectDetails($this, $languages), 'project_name' => $project->getName(), 'project_url' => $project->getOverviewUrl(), 'object_type' => $object_type, 'object_name' => $this->getName(), 'object_body' => $this->getFormattedBody(), 'object_url' => $this->getViewUrl(), 'owner_company_name' => $owner_company->getName(), 'created_by_name' => $created_by->getDisplayName(), 'created_by_url' => $created_by->getViewUrl());
             if ($context === null) {
                 $context = $this->getNotificationContext();
             }
             // if
             ApplicationMailer::send($email_to, 'resources/task_assigned', $variables, $context);
         }
     }
     //EOF:mod 20111011 #449
     mysql_close($link);
 }
コード例 #18
0
ファイル: SettingsUI.php プロジェクト: rankinp/OpenCATS
 private function onEmailSettings()
 {
     if ($this->_realAccessLevel < ACCESS_LEVEL_SA) {
         CommonErrors::fatal(COMMONERROR_PERMISSION, $this);
         return;
         //$this->fatal(ERROR_NO_PERMISSION);
     }
     $mailerSettings = new MailerSettings($this->_siteID);
     $mailerSettingsRS = $mailerSettings->getAll();
     foreach ($mailerSettingsRS as $setting => $value) {
         if (isset($_POST[$setting])) {
             $mailerSettings->set($setting, $_POST[$setting]);
         }
     }
     $candidateJoborderStatusSendsMessage = unserialize($mailerSettingsRS['candidateJoborderStatusSendsMessage']);
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_CONTACTED] = UserInterface::isChecked('statusChangeContacted', $_POST) ? 1 : 0;
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_CANDIDATE_REPLIED] = UserInterface::isChecked('statusChangeReplied', $_POST) ? 1 : 0;
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_QUALIFYING] = UserInterface::isChecked('statusChangeQualifying', $_POST) ? 1 : 0;
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_SUBMITTED] = UserInterface::isChecked('statusChangeSubmitted', $_POST) ? 1 : 0;
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_INTERVIEWING] = UserInterface::isChecked('statusChangeInterviewing', $_POST) ? 1 : 0;
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_OFFERED] = UserInterface::isChecked('statusChangeOffered', $_POST) ? 1 : 0;
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_CLIENTDECLINED] = UserInterface::isChecked('statusChangeDeclined', $_POST) ? 1 : 0;
     $candidateJoborderStatusSendsMessage[PIPELINE_STATUS_PLACED] = UserInterface::isChecked('statusChangePlaced', $_POST) ? 1 : 0;
     $mailerSettings->set('candidateJoborderStatusSendsMessage', serialize($candidateJoborderStatusSendsMessage));
     $emailTemplates = new EmailTemplates($this->_siteID);
     $emailTemplatesRS = $emailTemplates->getAll();
     foreach ($emailTemplatesRS as $index => $data) {
         $emailTemplates->updateIsActive($data['emailTemplateID'], UserInterface::isChecked('useThisTemplate' . $data['emailTemplateID'], $_POST) ? 0 : 1);
     }
     $this->_template->assign('active', $this);
     CATSUtility::transferRelativeURI('m=settings&a=administration');
 }
コード例 #19
0
 private function addActivityChangeStatus()
 {
     /* Bail out if we don't have a valid candidate ID. */
     if (!$this->isRequiredIDValid('candidateID', $_GET)) {
         CommonErrors::fatalModal(COMMONERROR_BADINDEX, $this, 'Invalid candidate ID.');
     }
     /* Bail out if we don't have a valid job order ID. */
     if (!$this->isRequiredIDValid('jobOrderID', $_GET)) {
         CommonErrors::fatalModal(COMMONERROR_BADINDEX, $this, 'Invalid job order ID.');
     }
     $candidateID = $_GET['candidateID'];
     $jobOrderID = $_GET['jobOrderID'];
     $candidates = new Candidates($this->_siteID);
     $candidateData = $candidates->get($candidateID);
     /* Bail out if we got an empty result set. */
     if (empty($candidateData)) {
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'The specified candidate ID could not be found.');
     }
     $pipelines = new Pipelines($this->_siteID);
     $pipelineData = $pipelines->get($candidateID, $jobOrderID);
     /* Bail out if we got an empty result set. */
     if (empty($pipelineData)) {
         CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'The specified pipeline entry could not be found.');
     }
     $statusRS = $pipelines->getStatusesForPicking();
     $selectedStatusID = $pipelineData['statusID'];
     /* Override default send email behavior with site specific send email behavior. */
     $mailerSettings = new MailerSettings($this->_siteID);
     $mailerSettingsRS = $mailerSettings->getAll();
     $candidateJoborderStatusSendsMessage = unserialize($mailerSettingsRS['candidateJoborderStatusSendsMessage']);
     foreach ($statusRS as $index => $status) {
         $statusRS[$index]['triggersEmail'] = $candidateJoborderStatusSendsMessage[$status['statusID']];
     }
     /* Get the change status email template. */
     $emailTemplates = new EmailTemplates($this->_siteID);
     $statusChangeTemplateRS = $emailTemplates->getByTag('EMAIL_TEMPLATE_STATUSCHANGE');
     if (empty($statusChangeTemplateRS) || empty($statusChangeTemplateRS['textReplaced'])) {
         $statusChangeTemplate = '';
         $emailDisabled = $statusChangeTemplateRS['disabled'];
     } else {
         $statusChangeTemplate = $statusChangeTemplateRS['textReplaced'];
         $emailDisabled = $statusChangeTemplateRS['disabled'];
     }
     /* Replace e-mail template variables. '%CANDSTATUS%', '%JBODTITLE%',
      * '%JBODCLIENT%' are replaced by JavaScript.
      */
     $stringsToFind = array('%CANDOWNER%', '%CANDFIRSTNAME%', '%CANDFULLNAME%');
     $replacementStrings = array($candidateData['ownerFullName'], $candidateData['firstName'], $candidateData['firstName'] . ' ' . $candidateData['lastName']);
     $statusChangeTemplate = str_replace($stringsToFind, $replacementStrings, $statusChangeTemplate);
     $calendar = new Calendar($this->_siteID);
     $calendarEventTypes = $calendar->getAllEventTypes();
     if (SystemUtility::isSchedulerEnabled() && !$_SESSION['CATS']->isDemo()) {
         $allowEventReminders = true;
     } else {
         $allowEventReminders = false;
     }
     $this->_template->assign('candidateID', $candidateID);
     $this->_template->assign('pipelineData', $pipelineData);
     $this->_template->assign('statusRS', $statusRS);
     $this->_template->assign('selectedJobOrderID', $jobOrderID);
     $this->_template->assign('selectedStatusID', $selectedStatusID);
     $this->_template->assign('calendarEventTypes', $calendarEventTypes);
     $this->_template->assign('allowEventReminders', $allowEventReminders);
     $this->_template->assign('userEmail', $_SESSION['CATS']->getEmail());
     $this->_template->assign('onlyScheduleEvent', false);
     $this->_template->assign('statusChangeTemplate', $statusChangeTemplate);
     $this->_template->assign('emailDisabled', $emailDisabled);
     $this->_template->assign('isFinishedMode', false);
     $this->_template->assign('isJobOrdersMode', true);
     if (!eval(Hooks::get('JO_ADD_ACTIVITY_CHANGE_STATUS'))) {
         return;
     }
     $this->_template->display('./modules/candidates/AddActivityChangeStatusModal.tpl');
 }
コード例 #20
0
/**
 * Send email
 * 		@param $recipient
 * 		@param $sender
 * 		@param $email_template
 * 		@param $replace_holders
 * 		@param $cc_email
 * 		@param $cc_subject
 * 		@param $debug
 */
function send_email($recipient, $sender, $email_template, $replace_holders = array(), $lang = '', $cc_email = '', $cc_subject = '', $debug = false)
{
    global $objSettings;
    if ($lang == '') {
        $lang = Application::Get('lang');
        $lang_dir = Application::Get('lang_dir');
    } else {
        $lang_dir = Languages::Get($lang, 'lang_dir');
    }
    $objEmailTemplates = new EmailTemplates();
    $email_info = $objEmailTemplates->GetTemplate($email_template, $lang);
    $arr_constants = array();
    $arr_constants_all = array('{FIRST NAME}', '{LAST NAME}', '{USER NAME}', '{USER PASSWORD}', '{USER EMAIL}', '{REGISTRATION CODE}', '{BASE URL}', '{WEB SITE}', '{YEAR}', '{EVENT}');
    $arr_values = array();
    foreach ($replace_holders as $key => $val) {
        $arr_constants[] = $key;
        $arr_values[] = $val;
    }
    // add the rest of holders
    foreach ($arr_constants_all as $key) {
        if (!in_array($key, $arr_constants)) {
            $arr_constants[] = $key;
            $arr_values[] = '';
        }
    }
    $subject = str_ireplace($arr_constants, $arr_values, $email_info['template_subject']);
    if ($cc_email == '' && $cc_subject != '') {
        $subject = $cc_subject;
    }
    $body = '<div style=direction:' . $lang_dir . '>';
    $body .= str_ireplace($arr_constants, $arr_values, $email_info['template_content']);
    $body .= '</div>';
    if ($objSettings->GetParameter('mailer') == 'smtp') {
        $mail = PHPMailer::Instance();
        $mail->IsSMTP();
        // telling the class to use SMTP
        $mail->SMTPDebug = 0;
        // enables SMTP debug information (for testing)
        // 1 = errors and messages
        // 2 = messages only
        $mail->SMTPAuth = true;
        // enable SMTP authentication
        $mail->SMTPSecure = 'ssl';
        // sets the prefix to the server
        $mail->Host = $objSettings->GetParameter('smtp_host');
        $mail->Port = $objSettings->GetParameter('smtp_port');
        $mail->Username = $objSettings->GetParameter('smtp_username');
        $mail->Password = $objSettings->GetParameter('smtp_password');
        $mail->ClearAddresses();
        // clear previously added 'To' addresses
        $mail->ClearReplyTos();
        // clear previously added 'ReplyTo' addresses
        $mail->SetFrom($sender);
        // $mail->SetFrom($mail_from, 'First Last');
        $mail->AddReplyTo($sender);
        // $mail->AddReplyTo($mail_to, 'First Last');
        $recipients = explode(',', $recipient);
        foreach ($recipients as $key) {
            $mail->AddAddress($key);
            // $mail->AddAddress($mail_to, 'John Doe');
        }
        $mail->Subject = $subject;
        $mail->AltBody = strip_tags($body);
        $mail->MsgHTML(nl2br($body));
        $result = $mail->Send();
        if ($cc_email != '') {
            $mail->ClearAddresses();
            // clear previously added 'To' addresses
            $mail->ClearReplyTos();
            // clear previously added 'ReplyTo' addresses
            $mail->AddAddress($cc_email);
            // $mail->AddAddress($mail_to, 'John Doe');
            $mail->Subject = $cc_subject != '' ? $cc_subject : $subject;
            $result = $mail->Send();
        }
    } else {
        $text_version = strip_tags($body);
        $html_version = nl2br($body);
        $objEmail = new Email($recipient, $sender, $subject);
        $objEmail->textOnly = false;
        $objEmail->content = $html_version;
        $result = $objEmail->Send();
        if ($cc_email != '') {
            if ($cc_subject != '') {
                $subject = $cc_subject;
            }
            $objEmail = new Email($cc_email, $sender, $subject);
            $objEmail->textOnly = false;
            $objEmail->content = $html_version;
            $result = $objEmail->Send();
        }
    }
    if ($debug) {
        echo 'To: ' . $recipient . ' <br>From: ' . $sender . ' <br>Subject: ' . $subject . ' <br>' . $body;
        if ($cc_email != '') {
            echo '<br>--------<br>To: ' . $cc_email . ' <br>From: ' . $sender . ' <br>';
        }
        exit;
    }
    return $result;
}
コード例 #21
0
ファイル: CareersUI.php プロジェクト: Hassanj343/candidats
    public function onApplyToJobOrder($siteID, $candidateID = false)
    {
        $jobOrders = new JobOrders($siteID);
        $careerPortalSettings = new CareerPortalSettings($siteID);

        if (!$this->isRequiredIDValid('ID', $_POST))
        {
            CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'Invalid job order ID.');
            return;
        }

        $jobOrderID = $_POST['ID'];

        $jobOrderData = $jobOrders->get($jobOrderID);
        if (!isset($jobOrderData['public']) || $jobOrderData['public'] == 0)
        {
            CommonErrors::fatal(COMMONERROR_BADINDEX, $this, 'The specified job order could not be found.');
            return;
        }

        $lastName       = $this->getTrimmedInput('lastName', $_POST);
        $middleName     = $this->getTrimmedInput('middleName', $_POST);
        $firstName      = $this->getTrimmedInput('firstName', $_POST);
        $email          = $this->getTrimmedInput('email', $_POST);
        $email2         = $this->getTrimmedInput('email2', $_POST);
        $address        = $this->getTrimmedInput('address', $_POST);
        $city           = $this->getTrimmedInput('city', $_POST);
        $state          = $this->getTrimmedInput('state', $_POST);
        $zip            = $this->getTrimmedInput('zip', $_POST);
        $source         = $this->getTrimmedInput('source', $_POST);
        $phone          = $this->getTrimmedInput('phone', $_POST);
        $phoneHome      = $this->getTrimmedInput('phoneHome', $_POST);
        $phoneCell      = $this->getTrimmedInput('phoneCell', $_POST);
        $bestTimeToCall = $this->getTrimmedInput('bestTimeToCall', $_POST);
        $keySkills      = $this->getTrimmedInput('keySkills', $_POST);
        $extraNotes     = $this->getTrimmedInput('extraNotes', $_POST);
        $employer       = $this->getTrimmedInput('employer', $_POST);

        $gender         = $this->getTrimmedInput('eeogender', $_POST);
        $race           = $this->getTrimmedInput('eeorace', $_POST);
        $veteran        = $this->getTrimmedInput('eeoveteran', $_POST);
        $disability     = $this->getTrimmedInput('eeodisability', $_POST);

        if (empty($firstName))
        {
            CommonErrors::fatal(COMMONERROR_MISSINGFIELDS, $this, 'First Name is a required field - please have your administrator edit your templates to include the first name field.');
        }

        if (empty($lastName))
        {
            CommonErrors::fatal(COMMONERROR_MISSINGFIELDS, $this, 'Last Name is a required field - please have your administrator edit your templates to include the last name field.');
        }

        if (empty($email))
        {
            CommonErrors::fatal(COMMONERROR_MISSINGFIELDS, $this, 'E-Mail address is a required field - please have your administrator edit your templates to include the email field.');
        }

        if (empty($source))
        {
            $source = 'Online Careers Website';
        }

        $users = new Users(CATS_ADMIN_SITE);
        $automatedUser = $users->getAutomatedUser();

        /* Find if another user with same e-mail exists. If so, update the user
         * to contain the new information.
         */
        $candidates = new Candidates($siteID);

        /**
         * Save basic information in a cookie in case the site is using registration to
         * process repeated postings, etc.
         */
        $fields = array('firstName', 'lastName', 'email', 'address', 'city', 'state', 'zip', 'phone',
            'phoneHome', 'phoneCell'
        );
        $storedVal = '';
        foreach ($fields as $field)
        {
            eval('$tmp = sprintf(\'"%s"="%s"\', $field, urlencode($' . $field . '));');
            $storedVal .= $tmp;
        }
        // Store their information for an hour only (about 1 session), if they return they can log in again and
        // specify "remember me" which stores it for 2 weeks.
        @setcookie($this->getCareerPortalCookieName($siteID), $storedVal, time()+60*60);

        if ($candidateID !== false)
        {
            $candidate = $candidates->get($candidateID);

            // Candidate exists and registered. Update their profile with new values (if provided)
            $candidates->update(
                $candidateID, $candidate['isActive'] ? true : false, $firstName, $middleName,
                $lastName, $email, $email2, $phoneHome, $phoneCell, $phone, $address, $city,
                $state, $zip, $source, $keySkills, '', $employer, '', '', '', $candidate['notes'],
                '', $bestTimeToCall, $automatedUser['userID'], $automatedUser['userID'], $gender,
                $race, $veteran, $disability
            );

            /* Update extra feilds */
            $candidates->extraFields->setValuesOnEdit($candidateID);
        }
        else
        {
            // Lookup the candidate by e-mail, use that candidate instead if found (but don't update profile)
            $candidateID = $candidates->getIDByEmail($email);
        }

        if ($candidateID === false || $candidateID < 0)
        {
            /* New candidate. */
            $candidateID = $candidates->add(
                $firstName,
                $middleName,
                $lastName,
                $email,
                $email2,
                $phoneHome,
                $phoneCell,
                $phone,
                $address,
                $city,
                $state,
                $zip,
                $source,
                $keySkills,
                '',
                $employer,
                '',
                '',
                '',
                'Candidate submitted these notes with first application: '
                . "\n\n" . $extraNotes,
                '',
                $bestTimeToCall,
                $automatedUser['userID'],
                $automatedUser['userID'],
                $gender,
                $race,
                $veteran,
                $disability
            );

            /* Update extra fields. */
            $candidates->extraFields->setValuesOnEdit($candidateID);
        }

        // If the candidate was added and a questionnaire exists for the job order
        if ($candidateID > 0 && ($questionnaireID = $jobOrderData['questionnaireID']))
        {
            $questionnaireLib = new Questionnaire($siteID);
            // Perform any actions specified by the questionnaire
            $questionnaireLib->doActions($questionnaireID, $candidateID, $_POST);
        }

        $fileUploaded = false;

        /* Upload resume (no questionnaire) */
        if (isset($_FILES['file']) && !empty($_FILES['file']['name']))
        {
            $attachmentCreator = new AttachmentCreator($siteID);
            $attachmentCreator->createFromUpload(
                DATA_ITEM_CANDIDATE, $candidateID, 'file', false, true
            );

            if ($attachmentCreator->isError())
            {
                CommonErrors::fatal(COMMONERROR_FILEERROR, $this, $attachmentCreator->getError());
                return;
            }

            $duplicatesOccurred = $attachmentCreator->duplicatesOccurred();

            $isTextExtractionError = $attachmentCreator->isTextExtractionError();
            $textExtractionErrorMessage = $attachmentCreator->getTextExtractionError();

            // FIXME: Show parse errors!

            $fileUploaded = true;
            $resumePath = $attachmentCreator->getNewFilePath();
        }
        /* Upload resume (with questionnaire) */
        else if (isset($_POST['file']) && !empty($_POST['file']))
        {
            $resumePath = '';

            $newFilePath = FileUtility::getUploadFilePath($siteID, 'careerportaladd', $_POST['file']);

            if ($newFilePath !== false)
            {
                $attachmentCreator = new AttachmentCreator($siteID);
                $attachmentCreator->createFromFile(
                    DATA_ITEM_CANDIDATE, $candidateID, $newFilePath, false, '', true, true
                );

                if ($attachmentCreator->isError())
                {
                    CommonErrors::fatal(COMMONERROR_FILEERROR, $this, $attachmentCreator->getError());
                    return;
                }

                $duplicatesOccurred = $attachmentCreator->duplicatesOccurred();

                $isTextExtractionError = $attachmentCreator->isTextExtractionError();
                $textExtractionErrorMessage = $attachmentCreator->getTextExtractionError();

                // FIXME: Show parse errors!

                $fileUploaded = true;
                $resumePath = $attachmentCreator->getNewFilePath();
            }
        }

        $pipelines = new Pipelines($siteID);
        $activityEntries = new ActivityEntries($siteID);

        /* Is the candidate already in the pipeline for this job order? */
        $rs = $pipelines->get($candidateID, $jobOrderID);
        if (count($rs) == 0)
        {
            /* Attempt to add the candidate to the pipeline. */
            if (!$pipelines->add($candidateID, $jobOrderID))
            {
                CommonErrors::fatal(COMMONERROR_RECORDERROR, $this, 'Failed to add candidate to pipeline.');
            }

            // FIXME: For some reason, pipeline entries like to disappear between
            //        the above add() and this get(). WTF?
            $rs = $pipelines->get($candidateID, $jobOrderID);
            if (isset($rs['candidateJobOrderID']))
                $pipelines->updateRatingValue($rs['candidateJobOrderID'], -1);

            $newApplication = true;
        }
        else
        {
            $newApplication = false;
        }

        /* Build activity note. */
        if (!$newApplication)
        {
            $activityNote = 'User re-applied through candidate portal';
        }
        else
        {
            $activityNote = 'User applied through candidate portal';
        }

        if ($fileUploaded)
        {
            if (!$duplicatesOccurred)
            {
                $activityNote .= ' <span style="font-weight: bold;">and'
                    . ' attached a new resume (<a href="' . $resumePath
                    . '">Download</a>)</span>';
            }
            else
            {
                $activityNote .= ' and attached an existing resume (<a href="'
                    . $resumePath . '">Download</a>)';
            }
        }

		if (!empty($extraNotes))
		{
        	$activityNote .= '; added these notes: ' . $extraNotes;
		}

        /* Add the activity note. */
        $activityID = $activityEntries->add(
            $candidateID,
            DATA_ITEM_CANDIDATE,
            ACTIVITY_OTHER,
            $activityNote,
            $automatedUser['userID'],
            $jobOrderID
        );

        /* Send an E-Mail describing what happened. */
        $emailTemplates = new EmailTemplates($siteID);
        $candidatesEmailTemplateRS = $emailTemplates->getByTag(
            'EMAIL_TEMPLATE_CANDIDATEAPPLY'
        );

        if (!isset($candidatesEmailTemplateRS['textReplaced']) ||
            empty($candidatesEmailTemplateRS['textReplaced']) ||
            $candidatesEmailTemplateRS['disabled'] == 1)
        {
            $candidatesEmailTemplate = '';
        }
        else
        {
            $candidatesEmailTemplate = $candidatesEmailTemplateRS['textReplaced'];
        }

        /* Replace e-mail template variables. */
        /* E-Mail #1 - to candidate */
        $stringsToFind = array(
            '%CANDFIRSTNAME%',
            '%CANDFULLNAME%',
            '%JBODOWNER%',
            '%JBODTITLE%',
            '%JBODCLIENT%'
        );
        $replacementStrings = array(
            $firstName,
            $firstName . ' ' . $lastName,
            $jobOrderData['ownerFullName'],
            $jobOrderData['title'],
            $jobOrderData['companyName']

            //'<a href="http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) . '?m=candidates&amp;a=show&amp;candidateID=' . $candidateID . '">'.
              //  'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?')) . '?m=candidates&amp;a=show&amp;candidateID=' . $candidateID . '</a>'
        );
        $candidatesEmailTemplate = str_replace(
            $stringsToFind,
            $replacementStrings,
            $candidatesEmailTemplate
        );

        $emailContents = $candidatesEmailTemplate;

        if (!empty($emailContents))
        {
            if(!$candidates->isLoaded())
            {
                $candidates->load($candidateID);
            }
            $candidates->sendEMail(
                $automatedUser['userID'],
                $email,
                CAREERS_CANDIDATEAPPLY_SUBJECT,
                $emailContents
            );
        }

        /* E-Mail #2 - to owner */

        $candidatesEmailTemplateRS = $emailTemplates->getByTag(
            'EMAIL_TEMPLATE_CANDIDATEPORTALNEW'
        );

        if (!isset($candidatesEmailTemplateRS['textReplaced']) ||
            empty($candidatesEmailTemplateRS['textReplaced']) ||
            $candidatesEmailTemplateRS['disabled'] == 1)
        {
            $candidatesEmailTemplate = '';
        }
        else
        {
            $candidatesEmailTemplate = $candidatesEmailTemplateRS['textReplaced'];
        }

        // FIXME: This will break if 'http' is elsewhere in the URL.
        $uri = str_replace('employment', '', $_SERVER['REQUEST_URI']);
        $uri = str_replace('http://', 'http', $uri);
        $uri = str_replace('//', '/', $uri);
        $uri = str_replace('http', 'http://', $uri);
        $uri = str_replace('/careers', '', $uri);

        /* Replace e-mail template variables. */
        $stringsToFind = array(
            '%CANDFIRSTNAME%',
            '%CANDFULLNAME%',
            '%JBODOWNER%',
            '%CANDOWNER%',     // Because the candidate was just added, we assume
            '%JBODTITLE%',     // the candidate owner = job order owner.
            '%JBODCLIENT%',
            '%CANDCATSURL%',
            '%JBODID%',
            '%JBODCATSURL%'
        );
        $replacementStrings = array(
            $firstName,
            $firstName . ' ' . $lastName,
            $jobOrderData['ownerFullName'],
            $jobOrderData['ownerFullName'],
            $jobOrderData['title'],
            $jobOrderData['companyName'],
            '<a href="http://' . $_SERVER['HTTP_HOST'] . substr($uri, 0, strpos($uri, '?')) . '?m=candidates&amp;a=show&amp;candidateID=' . $candidateID . '">'.
                'http://' . $_SERVER['HTTP_HOST'] . substr($uri, 0, strpos($uri, '?')) . '?m=candidates&amp;a=show&amp;candidateID=' . $candidateID . '</a>',
            $jobOrderData['jobOrderID'],
            '<a href="http://' . $_SERVER['HTTP_HOST'] . substr($uri, 0, strpos($uri, '?')) . '?m=joborders&amp;a=show&amp;jobOrderID=' . $jobOrderData['jobOrderID'] . '">'.
                'http://' . $_SERVER['HTTP_HOST'] . substr($uri, 0, strpos($uri, '?')) . '?m=joborders&amp;a=show&amp;jobOrderID=' . $jobOrderData['jobOrderID'] . '</a>',
        );
        $candidatesEmailTemplate = str_replace(
            $stringsToFind,
            $replacementStrings,
            $candidatesEmailTemplate
        );

        $emailContents = $candidatesEmailTemplate;

        if (!empty($emailContents))
        {
            if(!$jobOrders->isLoaded())
            {
                $jobOrders->load($jobOrderID);
            }
            $jobOrders->sendEmail(
                $automatedUser['userID'],
                $jobOrderData['owner_email'],
                CAREERS_OWNERAPPLY_SUBJECT,
                $emailContents
            );


            if ($jobOrderData['owner_email'] != $jobOrderData['recruiter_email'])
            {
                $jobOrders->sendEmail(
                    $automatedUser['userID'],
                    $jobOrderData['recruiter_email'],
                    CAREERS_OWNERAPPLY_SUBJECT,
                    $emailContents
                );
            }
        }
    }