/** * @return array */ public function mailing_select() { $data = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $query = "SELECT name FROM civicrm_mailing WHERE sms_provider_id IS NULL"; $mailing->query($query); while ($mailing->fetch()) { $data[mysql_real_escape_string($mailing->name)] = $mailing->name; } return $data; }
function mailing_select() { require_once 'CRM/Mailing/BAO/Mailing.php'; $data = array(); $mailing = new CRM_Mailing_BAO_Mailing(); $query = "SELECT name FROM civicrm_mailing "; $mailing->query($query); while ($mailing->fetch()) { $data[$mailing->name] = $mailing->name; } return $data; }
function run() { $this->_mailing_id = CRM_Utils_Request::retrieve('mid', 'Positive', $this); // check that the user has permission to access mailing id CRM_Mailing_BAO_Mailing::checkPermission($this->_mailing_id); $report = CRM_Mailing_BAO_Mailing::report($this->_mailing_id); //get contents of mailing CRM_Mailing_BAO_Mailing::getMailingContent($report, $this); //assign backurl $context = CRM_Utils_Request::retrieve('context', 'String', $this); $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this); if ($context == 'activitySelector') { $backUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=activity"); $backUrlTitle = ts('Back to Activities'); } elseif ($context == 'activity') { $atype = CRM_Utils_Request::retrieve('atype', 'Positive', $this); $aid = CRM_Utils_Request::retrieve('aid', 'Positive', $this); $backUrl = CRM_Utils_System::url('civicrm/activity/view', "atype={$atype}&action=view&reset=1&id={$aid}&cid={$cid}&context=activity"); $backUrlTitle = ts('Back to Activity'); } elseif ($context == 'mailing') { $backUrl = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=mailing"); $backUrlTitle = ts('Back to Mailing'); } else { $backUrl = CRM_Utils_System::url('civicrm/mailing', 'reset=1'); $backUrlTitle = ts('Back to CiviMail'); } $this->assign('backUrl', $backUrl); $this->assign('backUrlTitle', $backUrlTitle); $this->assign('report', $report); CRM_Utils_System::setTitle(ts('CiviMail Report: %1', array(1 => $report['mailing']['name']))); return CRM_Core_Page::run(); }
/** * Send a email to ?? with the mailing report of one mailing * * @param type $mailing_id */ function civicrm_api3_job_rapportagenamailings_mail($mailing_id) { global $base_root; // create a new Cor Page $page = new CRM_Core_Page(); $page->_mailing_id = $mailing_id; // create a new template $template = CRM_Core_Smarty::singleton(); // from CRM/Mailing/Page/Report.php // check that the user has permission to access mailing id CRM_Mailing_BAO_Mailing::checkPermission($mailing_id); $report = CRM_Mailing_BAO_Mailing::report($mailing_id); //get contents of mailing CRM_Mailing_BAO_Mailing::getMailingContent($report, $page); $subject = ts('Mailing Gereed: %1', array(1 => $report['mailing']['name'])); $template->assign('report', $report); // inlcude $base_root $template->assign('base_root', $base_root); $template->assign('subject', $subject); // from CRM/Core/page.php // only print $template->assign('tplFile', 'CRM/Rapportagenamailings/Page/RapportMailing.tpl'); $content = $template->fetch('CRM/common/print.tpl'); CRM_Utils_System::appendTPLFile('CRM/Rapportagenamailings/Page/RapportMailing.tpl', $content, $page->overrideExtraTemplateFileName()); //its time to call the hook. CRM_Utils_Hook::alterContent($content, 'page', 'CRM/Rapportagenamailings/Page/RapportMailing.tpl', $page); //echo $content; // send mail $params = array('from' => '*****@*****.**', 'toName' => 'Front Office VnV', 'toEmail' => '*****@*****.**', 'subject' => $subject, 'text' => $subject, 'html' => $content, 'replyTo' => '*****@*****.**'); CRM_Utils_Mail::send($params); }
/** * Function to retrieve contact mailings */ public static function getContactMailings() { $contactID = CRM_Utils_Type::escape($_GET['contact_id'], 'Integer'); $sortMapper = array(0 => 'subject', 1 => 'creator_name', 2 => '', 3 => 'start_date', 4 => '', 5 => 'links'); $sEcho = CRM_Utils_Type::escape($_REQUEST['sEcho'], 'Integer'); $offset = isset($_REQUEST['iDisplayStart']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayStart'], 'Integer') : 0; $rowCount = isset($_REQUEST['iDisplayLength']) ? CRM_Utils_Type::escape($_REQUEST['iDisplayLength'], 'Integer') : 25; $sort = isset($_REQUEST['iSortCol_0']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_REQUEST['iSortCol_0'], 'Integer'), $sortMapper) : NULL; $sortOrder = isset($_REQUEST['sSortDir_0']) ? CRM_Utils_Type::escape($_REQUEST['sSortDir_0'], 'String') : 'asc'; $params = $_POST; if ($sort && $sortOrder) { $params['sortBy'] = $sort . ' ' . $sortOrder; } $params['page'] = $offset / $rowCount + 1; $params['rp'] = $rowCount; $params['contact_id'] = $contactID; $params['context'] = $context; // get the contact mailings $mailings = CRM_Mailing_BAO_Mailing::getContactMailingSelector($params); $iFilteredTotal = $iTotal = $params['total']; $selectorElements = array('subject', 'mailing_creator', 'recipients', 'start_date', 'openstats', 'links'); header('Content-Type: application/json'); echo CRM_Utils_JSON::encodeDataTableSelector($mailings, $sEcho, $iTotal, $iFilteredTotal, $selectorElements); CRM_Utils_System::civiExit(); }
/** * Store Mails into Spool table. * * @param string|array $recipient * Either a comma-seperated list of recipients * (RFC822 compliant), or an array of recipients, * each RFC822 valid. This may contain recipients not * specified in the headers, for Bcc:, resending * messages, etc. * @param array $headers * The array of headers to send with the mail. * * @param string $body * The full text of the message body, including any mime parts, etc. * * @param int $job_id * * @return bool|CRM_Core_Error * true if successful */ public function send($recipient, $headers, $body, $job_id = NULL) { $headerStr = array(); foreach ($headers as $name => $value) { $headerStr[] = "{$name}: {$value}"; } $headerStr = implode("\n", $headerStr); if (is_null($job_id)) { // This is not a bulk mailing. Create a dummy job for it. $session = CRM_Core_Session::singleton(); $params = array(); $params['created_id'] = $session->get('userID'); $params['created_date'] = date('YmdHis'); $params['scheduled_id'] = $params['created_id']; $params['scheduled_date'] = $params['created_date']; $params['is_completed'] = 1; $params['is_archived'] = 1; $params['body_html'] = htmlspecialchars($headerStr) . "\n\n" . $body; $params['subject'] = $headers['Subject']; $params['name'] = $headers['Subject']; $ids = array(); $mailing = CRM_Mailing_BAO_Mailing::create($params, $ids); if (empty($mailing) || is_a($mailing, 'CRM_Core_Error')) { return PEAR::raiseError('Unable to create spooled mailing.'); } $job = new CRM_Mailing_BAO_MailingJob(); $job->is_test = 0; // if set to 1 it doesn't show in the UI $job->status = 'Complete'; $job->scheduled_date = CRM_Utils_Date::processDate(date('Y-m-d'), date('H:i:s')); $job->start_date = $job->scheduled_date; $job->end_date = $job->scheduled_date; $job->mailing_id = $mailing->id; $job->save(); $job_id = $job->id; // need this for parent_id below $job = new CRM_Mailing_BAO_MailingJob(); $job->is_test = 0; $job->status = 'Complete'; $job->scheduled_date = CRM_Utils_Date::processDate(date('Y-m-d'), date('H:i:s')); $job->start_date = $job->scheduled_date; $job->end_date = $job->scheduled_date; $job->mailing_id = $mailing->id; $job->parent_id = $job_id; $job->job_type = 'child'; $job->save(); $job_id = $job->id; // this is the one we want for the spool if (is_array($recipient)) { $recipient = implode(';', $recipient); } } $session = CRM_Core_Session::singleton(); $params = array('job_id' => $job_id, 'recipient_email' => $recipient, 'headers' => $headerStr, 'body' => $body, 'added_at' => date("YmdHis"), 'removed_at' => NULL); $spoolMail = new CRM_Mailing_DAO_Spool(); $spoolMail->copyValues($params); $spoolMail->save(); return TRUE; }
/** * Retrieve contact mailings. */ public static function getContactMailings() { $params = CRM_Core_Page_AJAX::defaultSortAndPagerParams(); $params += CRM_Core_Page_AJAX::validateParams(array('contact_id' => 'Integer')); // get the contact mailings $mailings = CRM_Mailing_BAO_Mailing::getContactMailingSelector($params); CRM_Utils_JSON::output($mailings); }
/** * Build the form * * @access public * @return void */ static function buildQuickForm(&$form) { $form->assign('totalSelectedContacts', count($form->_contactIds)); require_once "CRM/Mailing/BAO/Mailing.php"; CRM_Mailing_BAO_Mailing::commonLetterCompose($form); $form->addDefaultButtons(ts('Make PDF Letters')); $form->addFormRule(array('CRM_Contact_Form_Task_PDFLetterCommon', 'formRule'), $form); }
function run() { $this->_mailing_id = CRM_Utils_Request::retrieve('mid', $this); require_once 'CRM/Mailing/BAO/Mailing.php'; $report =& CRM_Mailing_BAO_Mailing::report($this->_mailing_id); $this->assign('report', $report); CRM_Utils_System::setTitle(ts('CiviMail Report: %1', array(1 => $report['mailing']['name']))); parent::run(); }
/** * run this page (figure out the action needed and perform it). * * @return void */ function run() { require_once 'CRM/Mailing/BAO/Mailing.php'; $session = CRM_Core_Session::singleton(); $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, false, 'text'); $type = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, false, 'text'); $options = array(); $session->getVars($options, "CRM_Mailing_Controller_Send_{$qfKey}"); //get the options if control come from search context, CRM-3711 if (empty($options)) { $session->getVars($options, "CRM_Contact_Controller_Search_{$qfKey}"); } // FIXME: the below and CRM_Mailing_Form_Test::testMail() // should be refactored $fromEmail = null; $mailing = new CRM_Mailing_BAO_Mailing(); if (!empty($options)) { $mailing->id = $options['mailing_id']; $fromEmail = CRM_Utils_Array::value('from_email', $options); } $mailing->find(true); CRM_Mailing_BAO_Mailing::tokenReplace($mailing); if (defined('CIVICRM_MAIL_SMARTY')) { require_once 'CRM/Core/Smarty/resources/String.php'; civicrm_smarty_register_string_resource(); } // get and format attachments require_once 'CRM/Core/BAO/File.php'; $attachments =& CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id); //get details of contact with token value including Custom Field Token Values.CRM-3734 $returnProperties = $mailing->getReturnProperties(); $params = array('contact_id' => $session->get('userID')); $details = $mailing->getDetails($params, $returnProperties); $mime =& $mailing->compose(null, null, null, $session->get('userID'), $fromEmail, $fromEmail, true, $details[0][$session->get('userID')], $attachments); if ($type == 'html') { header('Content-Type: text/html; charset=utf-8'); print $mime->getHTMLBody(); } else { header('Content-Type: text/plain; charset=utf-8'); print $mime->getTXTBody(); } CRM_Utils_System::civiExit(); }
/** * * @return void */ public function postProcess() { if ($this->_action & CRM_Core_Action::DELETE) { CRM_Mailing_BAO_Mailing::del($this->_mailingId); } elseif ($this->_action & CRM_Core_Action::DISABLE) { CRM_Mailing_BAO_MailingJob::cancel($this->_mailingId); } elseif ($this->_action & CRM_Core_Action::RENEW) { //set is_archived to 1 CRM_Core_DAO::setFieldValue('CRM_Mailing_DAO_Mailing', $this->_mailingId, 'is_archived', TRUE); } }
/** * Class constructor. */ public function __construct() { $this->_columns = array(); $this->_columns['civicrm_contact'] = array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('id' => array('title' => ts('Contact ID'), 'required' => TRUE), 'sort_name' => array('title' => ts('Contact Name'), 'required' => TRUE)), 'filters' => array('sort_name' => array('title' => ts('Contact Name')), 'source' => array('title' => ts('Contact Source'), 'type' => CRM_Utils_Type::T_STRING), 'id' => array('title' => ts('Contact ID'), 'no_display' => TRUE)), 'order_bys' => array('sort_name' => array('title' => ts('Contact Name'), 'default' => TRUE, 'default_order' => 'ASC')), 'grouping' => 'contact-fields'); $this->_columns['civicrm_mailing'] = array('dao' => 'CRM_Mailing_DAO_Mailing', 'fields' => array('mailing_name' => array('name' => 'name', 'title' => ts('Mailing'), 'default' => TRUE), 'mailing_name_alias' => array('name' => 'name', 'required' => TRUE, 'no_display' => TRUE)), 'filters' => array('mailing_id' => array('name' => 'id', 'title' => ts('Mailing'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'type' => CRM_Utils_Type::T_INT, 'options' => CRM_Mailing_BAO_Mailing::getMailingsList(), 'operator' => 'like')), 'order_bys' => array('mailing_name' => array('name' => 'name', 'title' => ts('Mailing'))), 'grouping' => 'mailing-fields'); $this->_columns['civicrm_email'] = array('dao' => 'CRM_Core_DAO_Email', 'fields' => array('email' => array('title' => ts('Email'), 'no_repeat' => TRUE)), 'order_bys' => array('email' => array('title' => ts('Email'), 'default_order' => 'ASC')), 'grouping' => 'contact-fields'); $this->_columns['civicrm_phone'] = array('dao' => 'CRM_Core_DAO_Phone', 'fields' => array('phone' => NULL), 'grouping' => 'contact-fields'); $this->_groupFilter = TRUE; $this->_tagFilter = TRUE; parent::__construct(); }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { //get the activity values $activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this); $context = CRM_Utils_Request::retrieve('context', 'String', $this); $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this); //check for required permissions, CRM-6264 if ($activityId && !CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::VIEW)) { CRM_Core_Error::fatal(ts('You do not have permission to access this page.')); } $session = CRM_Core_Session::singleton(); if (!in_array($context, array('home', 'dashlet', 'dashletFullscreen'))) { $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=activity"); } else { $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1'); } $session->pushUserContext($url); $defaults = array(); $params = array('id' => $activityId); CRM_Activity_BAO_Activity::retrieve($params, $defaults); //set activity type name and description to template list($activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($defaults['activity_type_id']); $this->assign('activityTypeName', $activityTypeName); $this->assign('activityTypeDescription', $activityTypeDescription); if (CRM_Utils_Array::value('mailingId', $defaults)) { $this->_mailing_id = CRM_Utils_Array::value('source_record_id', $defaults); $mailingReport = CRM_Mailing_BAO_Mailing::report($this->_mailing_id, TRUE); CRM_Mailing_BAO_Mailing::getMailingContent($mailingReport, $this); $this->assign('mailingReport', $mailingReport); $full_open_report = CRM_Mailing_Event_BAO_Opened::getRows($this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, $cid); $this->assign('openreport', $full_open_report); $click_thru_report = CRM_Mailing_Event_BAO_TrackableURLOpen::getRows($this->_mailing_id, NULL, FALSE, NULL, NULL, NULL, NULL, $cid); $this->assign('clickreport', $click_thru_report); } foreach ($defaults as $key => $value) { if (substr($key, -3) != '_id') { $values[$key] = $value; } } //get the campaign if ($campaignId = CRM_Utils_Array::value('campaign_id', $defaults)) { $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); $values['campaign'] = $campaigns[$campaignId]; } if ($engagementLevel = CRM_Utils_Array::value('engagement_level', $defaults)) { $engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel(); $values['engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel); } $values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId); $this->assign('values', $values); }
/** * A PHP cron script to run the outstanding and scheduled CiviMail jobs * initiated by Owen Barton from a mailing sent by Lobo to crm-mail * * The structure of the file is set to mimiic soap.php which is a stand-alone * script and hence does not have any UF issues. You should be able to run * this script using a web url or from the command line */ function run() { session_start(); if (!function_exists('drush_get_context')) { require_once '../civicrm.config.php'; } require_once 'CRM/Core/Config.php'; $config = CRM_Core_Config::singleton(); // this does not return on failure CRM_Utils_System::authenticateScript(TRUE); // we now use DB locks on a per job basis require_once 'CRM/Mailing/BAO/Mailing.php'; CRM_Mailing_BAO_Mailing::processQueue(); }
/** * Run this page (figure out the action needed and perform it). * * @return void */ public function run() { $session = CRM_Core_Session::singleton(); $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, FALSE, 'text'); $type = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, FALSE, 'text'); $options = array(); $session->getVars($options, "CRM_Mailing_Controller_Send_{$qfKey}"); //get the options if control come from search context, CRM-3711 if (empty($options)) { $session->getVars($options, "CRM_Contact_Controller_Search_{$qfKey}"); } // FIXME: the below and CRM_Mailing_Form_Test::testMail() // should be refactored $fromEmail = NULL; $mailing = new CRM_Mailing_BAO_Mailing(); if (!empty($options)) { $mailing->id = $options['mailing_id']; $fromEmail = CRM_Utils_Array::value('from_email', $options); } $mailing->find(TRUE); CRM_Mailing_BAO_Mailing::tokenReplace($mailing); // get and format attachments $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id); //get details of contact with token value including Custom Field Token Values.CRM-3734 $returnProperties = $mailing->getReturnProperties(); $params = array('contact_id' => $session->get('userID')); $details = CRM_Utils_Token::getTokenDetails($params, $returnProperties, TRUE, TRUE, NULL, $mailing->getFlattenedTokens(), get_class($this)); $mime =& $mailing->compose(NULL, NULL, NULL, $session->get('userID'), $fromEmail, $fromEmail, TRUE, $details[0][$session->get('userID')], $attachments); if ($type == 'html') { CRM_Utils_System::setHttpHeader('Content-Type', 'text/html; charset=utf-8'); print $mime->getHTMLBody(); } else { CRM_Utils_System::setHttpHeader('Content-Type', 'text/plain; charset=utf-8'); print $mime->getTXTBody(); } CRM_Utils_System::civiExit(); }
/** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { //get the activity values $activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this); $context = CRM_Utils_Request::retrieve('context', 'String', $this); $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this); //check for required permissions, CRM-6264 if ($activityId && !CRM_Activity_BAO_Activity::checkPermission($activityId, CRM_Core_Action::VIEW)) { CRM_Core_Error::fatal(ts('You do not have permission to access this page.')); } $session = CRM_Core_Session::singleton(); if ($context != 'home') { $url = CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$cid}&selectedChild=activity"); } else { $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1'); } $session->pushUserContext($url); $params = array('id' => $activityId); CRM_Activity_BAO_Activity::retrieve($params, $defaults); //set activity type name and description to template require_once 'CRM/Core/BAO/OptionValue.php'; list($activityTypeName, $activityTypeDescription) = CRM_Core_BAO_OptionValue::getActivityTypeDetails($defaults['activity_type_id']); $this->assign('activityTypeName', $activityTypeName); $this->assign('activityTypeDescription', $activityTypeDescription); if (CRM_Utils_Array::value('mailingId', $defaults)) { $this->_mailing_id = CRM_Utils_Array::value('source_record_id', $defaults); require_once 'CRM/Mailing/BAO/Mailing.php'; $mailingReport =& CRM_Mailing_BAO_Mailing::report($this->_mailing_id, true); CRM_Mailing_BAO_Mailing::getMailingContent($mailingReport, $this); $this->assign('mailingReport', $mailingReport); } foreach ($defaults as $key => $value) { if (substr($key, -3) != '_id') { $values[$key] = $value; } } require_once 'CRM/Core/BAO/File.php'; $values['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_activity', $activityId); $this->assign('values', $values); }
/** * Implementation of hook_civicrm_install */ function mte_civicrm_install() { $mailingParams = array('subject' => '***All Transactional Emails***', 'name' => ts('Transaction Emails'), 'url_tracking' => TRUE, 'forward_replies' => FALSE, 'auto_responder' => FALSE, 'open_tracking' => TRUE, 'is_completed' => FALSE); //create entry in civicrm_mailing $mailing = CRM_Mailing_BAO_Mailing::add($mailingParams, CRM_Core_DAO::$_nullArray); //add entry in civicrm_mailing_job //MTE-17 $config = CRM_Core_Config::singleton(); if (property_exists($config, 'civiVersion')) { $civiVersion = $config->civiVersion; } else { $civiVersion = CRM_Core_BAO_Domain::version(); } $jobCLassName = 'CRM_Mailing_DAO_MailingJob'; if (version_compare('4.4alpha1', $civiVersion) > 0) { $jobCLassName = 'CRM_Mailing_DAO_Job'; } $changeENUM = FALSE; if (version_compare('4.5alpha1', $civiVersion) > 0) { $changeENUM = TRUE; } CRM_Core_Smarty::singleton()->assign('changeENUM', $changeENUM); _mte_civix_civicrm_install(); $saveJob = new $jobCLassName(); $saveJob->start_date = $saveJob->end_date = date('YmdHis'); $saveJob->status = 'Complete'; $saveJob->job_type = "Special: All transactional emails being sent through Mandrill"; $saveJob->mailing_id = $mailing->id; $saveJob->save(); // create mailing bounce type $mailingBounceType = array('1' => array('name' => 'Mandrill Hard', 'description' => 'Mandrill hard bounce', 'hold_threshold' => 1), '2' => array('name' => 'Mandrill Soft', 'description' => 'Mandrill soft bounce', 'hold_threshold' => 3), '3' => array('name' => 'Mandrill Spam', 'description' => 'User marked a transactional email sent via Mandrill as spam', 'hold_threshold' => 1), '4' => array('name' => 'Mandrill Reject', 'description' => 'Mandrill rejected delivery to this email address', 'hold_threshold' => 1)); foreach ($mailingBounceType as $value) { $bounceType = new CRM_Mailing_DAO_BounceType(); $bounceType->copyValues($value); if (!$bounceType->find(true)) { $bounceType->save(); } } return TRUE; }
/** * Retrieve contact mailings. */ public static function getContactMailings() { $contactID = CRM_Utils_Type::escape($_GET['contact_id'], 'Integer'); $sortMapper = array(); foreach ($_GET['columns'] as $key => $value) { $sortMapper[$key] = $value['data']; } $offset = isset($_GET['start']) ? CRM_Utils_Type::escape($_GET['start'], 'Integer') : 0; $rowCount = isset($_GET['length']) ? CRM_Utils_Type::escape($_GET['length'], 'Integer') : 25; $sort = isset($_GET['order'][0]['column']) ? CRM_Utils_Array::value(CRM_Utils_Type::escape($_GET['order'][0]['column'], 'Integer'), $sortMapper) : NULL; $sortOrder = isset($_GET['order'][0]['dir']) ? CRM_Utils_Type::escape($_GET['order'][0]['dir'], 'String') : 'asc'; $params = $_GET; if ($sort && $sortOrder) { $params['sortBy'] = $sort . ' ' . $sortOrder; } $params['page'] = $offset / $rowCount + 1; $params['rp'] = $rowCount; $params['contact_id'] = $contactID; $params['context'] = $context; // get the contact mailings $mailings = CRM_Mailing_BAO_Mailing::getContactMailingSelector($params); CRM_Utils_JSON::output($mailings); }
/** * Build the form object. * * * @param CRM_Core_Form $form * * @return void */ public static function buildQuickForm(&$form) { $toArray = array(); $providers = CRM_SMS_BAO_Provider::getProviders(NULL, NULL, TRUE, 'is_default desc'); $providerSelect = array(); foreach ($providers as $provider) { $providerSelect[$provider['id']] = $provider['title']; } $suppressedSms = 0; //here we are getting logged in user id as array but we need target contact id. CRM-5988 $cid = $form->get('cid'); if ($cid) { $form->_contactIds = array($cid); } $to = $form->add('text', 'to', ts('To'), array('class' => 'huge'), TRUE); $form->add('text', 'activity_subject', ts('Name The SMS'), array('class' => 'huge'), TRUE); $toSetDefault = TRUE; if (property_exists($form, '_context') && $form->_context == 'standalone') { $toSetDefault = FALSE; } // when form is submitted recompute contactIds $allToSMS = array(); if ($to->getValue()) { $allToPhone = explode(',', $to->getValue()); $form->_contactIds = array(); foreach ($allToPhone as $value) { list($contactId, $phone) = explode('::', $value); if ($contactId) { $form->_contactIds[] = $contactId; $form->_toContactPhone[] = $phone; } } $toSetDefault = TRUE; } //get the group of contacts as per selected by user in case of Find Activities if (!empty($form->_activityHolderIds)) { $extendTargetContacts = 0; $invalidActivity = 0; $validActivities = 0; foreach ($form->_activityHolderIds as $key => $id) { //valid activity check if (CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $id, 'subject', 'id') != self::RECIEVED_SMS_ACTIVITY_SUBJECT) { $invalidActivity++; continue; } $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); //target contacts limit check $ids = array_keys(CRM_Activity_BAO_ActivityContact::getNames($id, $targetID)); if (count($ids) > 1) { $extendTargetContacts++; continue; } $validActivities++; $form->_contactIds = empty($form->_contactIds) ? $ids : array_unique(array_merge($form->_contactIds, $ids)); } if (!$validActivities) { $errorMess = ""; if ($extendTargetContacts) { $errorMess = ts('One selected activity consists of more than one target contact.', array('count' => $extendTargetContacts, 'plural' => '%count selected activities consist of more than one target contact.')); } if ($invalidActivity) { $errorMess = $errorMess ? ' ' : ''; $errorMess .= ts('The selected activity is invalid.', array('count' => $invalidActivity, 'plural' => '%count selected activities are invalid.')); } CRM_Core_Error::statusBounce(ts("%1: SMS Reply will not be sent.", array(1 => $errorMess))); } } if (is_array($form->_contactIds) && !empty($form->_contactIds) && $toSetDefault) { $returnProperties = array('sort_name' => 1, 'phone' => 1, 'do_not_sms' => 1, 'is_deceased' => 1, 'display_name' => 1); list($form->_contactDetails) = CRM_Utils_Token::getTokenDetails($form->_contactIds, $returnProperties, FALSE, FALSE); // make a copy of all contact details $form->_allContactDetails = $form->_contactDetails; foreach ($form->_contactIds as $key => $contactId) { $value = $form->_contactDetails[$contactId]; //to check if the phone type is "Mobile" $phoneTypes = CRM_Core_OptionGroup::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name'); if (CRM_Utils_System::getClassName($form) == 'CRM_Activity_Form_Task_SMS') { //to check for "if the contact id belongs to a specified activity type" $actDetails = CRM_Activity_BAO_Activity::getContactActivity($contactId); if (self::RECIEVED_SMS_ACTIVITY_SUBJECT != CRM_Utils_Array::retrieveValueRecursive($actDetails, 'subject')) { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } if (isset($value['phone_type_id']) && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) || $value['do_not_sms'] || empty($value['phone']) || !empty($value['is_deceased'])) { //if phone is not primary check if non-primary phone is "Mobile" if (!empty($value['phone']) && $value['phone_type_id'] != CRM_Utils_Array::value('Mobile', $phoneTypes) && empty($value['is_deceased'])) { $filter = array('do_not_sms' => 0); $contactPhones = CRM_Core_BAO_Phone::allPhones($contactId, FALSE, 'Mobile', $filter); if (count($contactPhones) > 0) { $mobilePhone = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'phone'); $form->_contactDetails[$contactId]['phone_id'] = CRM_Utils_Array::retrieveValueRecursive($contactPhones, 'id'); $form->_contactDetails[$contactId]['phone'] = $mobilePhone; $form->_contactDetails[$contactId]['phone_type_id'] = CRM_Utils_Array::value('Mobile', $phoneTypes); } else { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } else { $suppressedSms++; unset($form->_contactDetails[$contactId]); continue; } } if (isset($mobilePhone)) { $phone = $mobilePhone; } elseif (empty($form->_toContactPhone)) { $phone = $value['phone']; } else { $phone = CRM_Utils_Array::value($key, $form->_toContactPhone); } if ($phone) { $toArray[] = array('text' => '"' . $value['sort_name'] . '" (' . $phone . ')', 'id' => "{$contactId}::{$phone}"); } } if (empty($toArray)) { CRM_Core_Error::statusBounce(ts('Selected contact(s) do not have a valid Phone, or communication preferences specify DO NOT SMS, or they are deceased')); } } //activity related variables if (isset($invalidActivity)) { $form->assign('invalidActivity', $invalidActivity); } if (isset($extendTargetContacts)) { $form->assign('extendTargetContacts', $extendTargetContacts); } $form->assign('toContact', json_encode($toArray)); $form->assign('suppressedSms', $suppressedSms); $form->assign('totalSelectedContacts', count($form->_contactIds)); $form->add('select', 'sms_provider_id', ts('From'), $providerSelect, TRUE); CRM_Mailing_BAO_Mailing::commonCompose($form); if ($form->_single) { // also fix the user context stack if ($form->_context) { $url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1'); } else { $url = CRM_Utils_System::url('civicrm/contact/view', "&show=1&action=browse&cid={$form->_contactIds[0]}&selectedChild=activity"); } $session = CRM_Core_Session::singleton(); $session->replaceUserContext($url); $form->addDefaultButtons(ts('Send SMS'), 'upload', 'cancel'); } else { $form->addDefaultButtons(ts('Send SMS'), 'upload'); } $form->addFormRule(array('CRM_Contact_Form_Task_SMSCommon', 'formRule'), $form); }
/** * Confirm a pending subscription * * @param int $contact_id The id of the contact * @param int $subscribe_id The id of the subscription event * @param string $hash The hash * * @return boolean True on success * @access public * @static */ public static function confirm($contact_id, $subscribe_id, $hash) { $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash); if (!$se) { return FALSE; } // before we proceed lets just check if this contact is already 'Added' // if so, we should ignore this request and hence avoid sending multiple // emails - CRM-11157 $details = CRM_Contact_BAO_GroupContact::getMembershipDetail($contact_id, $se->group_id); if ($details && $details->status == 'Added') { // This contact is already subscribed // lets return the group title return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $se->group_id, 'title'); } $transaction = new CRM_Core_Transaction(); $ce = new CRM_Mailing_Event_BAO_Confirm(); $ce->event_subscribe_id = $se->id; $ce->time_stamp = date('YmdHis'); $ce->save(); CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id); $transaction->commit(); $config = CRM_Core_Config::singleton(); $domain = CRM_Core_BAO_Domain::getDomain(); list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail(); list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id); $group = new CRM_Contact_DAO_Group(); $group->id = $se->group_id; $group->find(TRUE); $component = new CRM_Mailing_BAO_Component(); $component->is_default = 1; $component->is_active = 1; $component->component_type = 'Welcome'; $component->find(TRUE); $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain(); $html = $component->body_html; if ($component->body_text) { $text = $component->body_text; } else { $text = CRM_Utils_String::htmlToText($component->body_html); } $bao = new CRM_Mailing_BAO_Mailing(); $bao->body_text = $text; $bao->body_html = $html; $tokens = $bao->getTokens(); $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']); $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, TRUE); $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']); $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE); $mailParams = array('groupName' => 'Mailing Event ' . $component->component_type, 'subject' => $component->subject, 'from' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'toEmail' => $email, 'toName' => $display_name, 'replyTo' => "do-not-reply@{$emailDomain}", 'returnPath' => "do-not-reply@{$emailDomain}", 'html' => $html, 'text' => $text); // send - ignore errors because the desired status change has already been successful $unused_result = CRM_Utils_Mail::send($mailParams); return $group->title; }
/** * Get the mailing object for this queue event instance * * @param * @return object Mailing BAO * @access public */ function &getMailing() { $mailing =& new CRM_Mailing_BAO_Mailing(); $jobs = CRM_Mailing_BAO_Job::getTableName(); $mailings = CRM_Mailing_BAO_Mailing::getTableName(); $queue = CRM_Mailing_Event_BAO_Queue::getTableName(); $mailing->query("\n SELECT {$mailings}.*\n FROM {$mailings}\n INNER JOIN {$jobs}\n ON {$jobs}.mailing_id = {$mailings}.id\n INNER JOIN {$queue}\n ON {$queue}.job_id = {$jobs}.id\n WHERE {$queue}.id = {$this->id}"); $mailing->fetch(); return $mailing; }
/** * @param $token * @param $mailing * @param bool $escapeSmarty * * @return string */ public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) { $value = ''; switch ($token) { // CRM-7663 case 'id': $value = $mailing ? $mailing->id : 'undefined'; break; case 'name': $value = $mailing ? $mailing->name : 'Mailing Name'; break; case 'group': $groups = $mailing ? $mailing->getGroupNames() : array('Mailing Groups'); $value = implode(', ', $groups); break; case 'subject': $value = $mailing->subject; break; case 'viewUrl': $mailingKey = $mailing->id; if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) { $mailingKey = $hash; } $value = CRM_Utils_System::url('civicrm/mailing/view', "reset=1&id={$mailingKey}", TRUE, NULL, FALSE, TRUE); break; case 'editUrl': case 'scheduleUrl': // Note: editUrl and scheduleUrl used to be different, but now there's // one screen which can adapt based on permissions (in workflow mode). $value = CRM_Utils_System::url('civicrm/mailing/send', "reset=1&mid={$mailing->id}&continue=true", TRUE, NULL, FALSE, TRUE); break; case 'html': $page = new CRM_Mailing_Page_View(); $value = $page->run($mailing->id, NULL, FALSE, TRUE); break; case 'approvalStatus': $value = CRM_Core_PseudoConstant::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id); break; case 'approvalNote': $value = $mailing->approval_note; break; case 'approveUrl': $value = CRM_Utils_System::url('civicrm/mailing/approve', "reset=1&mid={$mailing->id}", TRUE, NULL, FALSE, TRUE); break; case 'creator': $value = CRM_Contact_BAO_Contact::displayName($mailing->created_id); break; case 'creatorEmail': $value = CRM_Contact_BAO_Contact::getPrimaryEmail($mailing->created_id); break; default: $value = "{mailing.{$token}}"; break; } if ($escapeSmarty) { $value = self::tokenEscapeSmarty($value); } return $value; }
/** * Get all the completed mailing. * * * @param null $mode * * @return array * array reference of all mailing templates if any */ public static function &completed($mode = NULL) { if (!self::$completed) { $mailingACL = CRM_Mailing_BAO_Mailing::mailingACL(); $mailingACL .= $mode == 'sms' ? " AND sms_provider_id IS NOT NULL " : ""; CRM_Core_PseudoConstant::populate(self::$completed, 'CRM_Mailing_DAO_Mailing', FALSE, 'name', 'is_completed', $mailingACL); } return self::$completed; }
public function postProcess() { $values = $this->controller->exportValues($this->_name); //build hidden smart group. when user want to send mailing //through search contact-> more action -> send Mailing. CRM-3711 $groups = array(); if ($this->_searchBasedMailing && $this->_contactIds) { //get the hidden smart group id. $ssId = $this->get('ssID'); $session = CRM_Core_Session::singleton(); $hiddenSmartParams = array('group_type' => array('2' => 1), 'form_values' => $this->get('formValues'), 'saved_search_id' => $ssId, 'search_custom_id' => $this->get('customSearchID'), 'search_context' => $this->get('context')); require_once 'CRM/Contact/BAO/Group.php'; list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams); //set the saved search id. if (!$ssId) { if ($savedSearchId) { $this->set('ssID', $savedSearchId); } else { CRM_Core_Error::fatal(); } } //get the base group for this mailing, CRM-3711 $groups['base'] = array($values['baseGroup']); $values['includeGroups'][] = $smartGroupId; } foreach (array('name', 'group_id', 'search_id', 'search_args') as $n) { if (CRM_Utils_Array::value($n, $values)) { $params[$n] = $values[$n]; } } $qf_Group_submit = $this->controller->exportValue($this->_name, '_qf_Group_submit'); $this->set('name', $params['name']); $inGroups = $values['includeGroups']; $outGroups = $values['excludeGroups']; $inMailings = $values['includeMailings']; $outMailings = $values['excludeMailings']; if (is_array($inGroups)) { foreach ($inGroups as $key => $id) { if ($id) { $groups['include'][] = $id; } } } if (is_array($outGroups)) { foreach ($outGroups as $key => $id) { if ($id) { $groups['exclude'][] = $id; } } } $mailings = array(); if (is_array($inMailings)) { foreach ($inMailings as $key => $id) { if ($id) { $mailings['include'][] = $id; } } } if (is_array($outMailings)) { foreach ($outMailings as $key => $id) { if ($id) { $mailings['exclude'][] = $id; } } } $session = CRM_Core_Session::singleton(); $params['groups'] = $groups; $params['mailings'] = $mailings; if ($this->get('mailing_id')) { $ids = array(); // don't create a new mailing if already exists $ids['mailing_id'] = $this->get('mailing_id'); $groupTableName = CRM_Contact_BAO_Group::getTableName(); $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName(); // delete previous includes/excludes, if mailing already existed require_once 'CRM/Contact/DAO/Group.php'; foreach (array('groups', 'mailings') as $entity) { $mg = new CRM_Mailing_DAO_Group(); $mg->mailing_id = $ids['mailing_id']; $mg->entity_table = $entity == 'groups' ? $groupTableName : $mailingTableName; $mg->find(); while ($mg->fetch()) { $mg->delete(); } } } else { // new mailing, so lets set the created_id $session = CRM_Core_Session::singleton(); $params['created_id'] = $session->get('userID'); $params['created_date'] = date('YmdHis'); } require_once 'CRM/Mailing/BAO/Mailing.php'; $mailing = CRM_Mailing_BAO_Mailing::create($params, $ids); $this->set('mailing_id', $mailing->id); $count = CRM_Mailing_BAO_Mailing::getRecipientsCount(true, false, $mailing->id); $this->set('count', $count); $this->assign('count', $count); $this->set('groups', $groups); $this->set('mailings', $mailings); if ($qf_Group_submit) { //when user perform mailing from search context //redirect it to search result CRM-3711. $ssID = $this->get('ssID'); $context = $this->get('context'); if ($ssID && $this->_searchBasedMailing) { if ($this->_action == CRM_Core_Action::BASIC) { $fragment = 'search'; } else { if ($this->_action == CRM_Core_Action::PROFILE) { $fragment = 'search/builder'; } else { if ($this->_action == CRM_Core_Action::ADVANCED) { $fragment = 'search/advanced'; } else { $fragment = 'search/custom'; } } } $context = $this->get('context'); if (!CRM_Contact_Form_Search::isSearchContext($context)) { $context = 'search'; } $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}"; $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this); if (CRM_Utils_Rule::qfKey($qfKey)) { $urlParams .= "&qfKey={$qfKey}"; } $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1'); $status = ts("Your mailing has been saved. You can continue later by clicking the 'Continue' action to resume working on it.<br /> From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL)); CRM_Core_Session::setStatus($status); //replace user context to search. $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams); CRM_Utils_System::redirect($url); } else { $status = ts("Your mailing has been saved. Click the 'Continue' action to resume working on it."); CRM_Core_Session::setStatus($status); $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1'); CRM_Utils_System::redirect($url); } } }
/** * Function to build the form * * @return void * @access public */ public function buildQuickForm() { $field = 'civicrm_event'; if ($this->_isTemplate) { $field = 'event_template'; } $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', $field, 'id', 'entity_value'); if (!$this->_mappingID) { CRM_Core_Error::fatal('Could not find mapping for event scheduled reminders.'); } parent::buildQuickForm(); $this->add('text', 'title', ts('Reminder Name'), array('size' => 45, 'maxlength' => 128), TRUE); $selectionOptions = CRM_Core_BAO_ActionSchedule::getSelection($this->_mappingID); extract($selectionOptions); $this->assign('recipientMapping', json_encode($recipientMapping)); // Fixme: hack to adjust the output of CRM_Core_BAO_ActionSchedule::getSelection so it looks nice with the jQuery.select2 plugin // TODO: fix this upstream $options = $sel3[$this->_mappingID][0]; $attributes = array('multiple' => 'multiple', 'class' => 'crm-select2 huge', 'placeholder' => $options[0]); unset($options[0]); $entity = $this->add('select', 'entity', ts('Recipient(s)'), $options, TRUE, $attributes); //get the frequency units. $this->_freqUnits = array('hour' => 'hour') + CRM_Core_OptionGroup::values('recur_frequency_units'); $numericOptions = CRM_Core_SelectValues::getNumericOptions(0, 30); //reminder_interval $this->add('select', 'start_action_offset', ts('When'), $numericOptions); foreach ($this->_freqUnits as $val => $label) { $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label)); } $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing')); //reminder_frequency $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE); $condition = array('before' => ts('before'), 'after' => ts('after')); //reminder_action $this->add('select', 'start_action_condition', ts('Action Condition'), $condition); $this->add('select', 'start_action_date', ts('Date Field'), $sel4, TRUE); $this->addElement('checkbox', 'record_activity', ts('Record activity for automated email')); $this->addElement('checkbox', 'is_repeat', ts('Repeat'), NULL, array('onclick' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);")); $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay); $this->add('select', 'repetition_frequency_interval', ts('every'), $numericOptions); $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay); $this->add('select', 'end_frequency_interval', ts('until'), $numericOptions); $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE); $this->add('select', 'end_date', ts('Date Field'), $sel4, TRUE); $recipient = 'event_contacts'; $limitOptions = array(1 => ts('Limit to'), 0 => ts('Addition to')); $this->add('select', 'limit_to', ts('Limit Options'), $limitOptions); $this->add('select', 'recipient', ts('Recipients'), $sel5[$recipient], FALSE, array('onchange' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);")); $recipientListing = $this->add('select', 'recipient_listing', ts('Recipient Listing'), $sel3[$this->_mappingID][0], FALSE, array('class' => 'crm-select2 huge')); $recipientListing->setMultiple(TRUE); //auto-complete url $dataUrl = CRM_Utils_System::url('civicrm/ajax/rest', "className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&context=activity&reset=1", FALSE, NULL, FALSE); $this->assign('dataUrl', $dataUrl); //token input url $tokenUrl = CRM_Utils_System::url('civicrm/ajax/checkemail', 'noemail=1', FALSE, NULL, FALSE); $this->assign('tokenUrl', $tokenUrl); $this->add('text', 'recipient_manual_id', ts('Manual Recipients')); $this->add('select', 'group_id', ts('Group'), CRM_Core_PseudoConstant::staticGroup(), FALSE, array('class' => 'crm-select2 huge')); CRM_Mailing_BAO_Mailing::commonCompose($this); $this->add('text', 'subject', ts('Subject'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject')); $this->add('checkbox', 'is_active', ts('Send email')); $this->addFormRule(array('CRM_Event_Form_ManageEvent_ScheduleReminders', 'formRule')); }
public function postProcess() { $values = $this->controller->exportValues($this->_name); $groups = array(); foreach (array('name', 'group_id', 'is_sms') as $n) { if (!empty($values[$n])) { $params[$n] = $values[$n]; } } $qf_Group_submit = $this->controller->exportValue($this->_name, '_qf_Group_submit'); $this->set('name', $params['name']); $inGroups = $values['includeGroups']; $outGroups = $values['excludeGroups']; $inMailings = $values['includeMailings']; $outMailings = $values['excludeMailings']; if (is_array($inGroups)) { foreach ($inGroups as $key => $id) { if ($id) { $groups['include'][] = $id; } } } if (is_array($outGroups)) { foreach ($outGroups as $key => $id) { if ($id) { $groups['exclude'][] = $id; } } } $mailings = array(); if (is_array($inMailings)) { foreach ($inMailings as $key => $id) { if ($id) { $mailings['include'][] = $id; } } } if (is_array($outMailings)) { foreach ($outMailings as $key => $id) { if ($id) { $mailings['exclude'][] = $id; } } } $session = CRM_Core_Session::singleton(); $params['groups'] = $groups; $params['mailings'] = $mailings; $ids = array(); if ($this->get('mailing_id')) { // don't create a new mass sms if already exists $ids['mailing_id'] = $this->get('mailing_id'); $groupTableName = CRM_Contact_BAO_Group::getTableName(); $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName(); // delete previous includes/excludes, if mailing already existed foreach (array('groups', 'mailings') as $entity) { $mg = new CRM_Mailing_DAO_MailingGroup(); $mg->mailing_id = $ids['mailing_id']; $mg->entity_table = $entity == 'groups' ? $groupTableName : $mailingTableName; $mg->find(); while ($mg->fetch()) { $mg->delete(); } } } else { // new mailing, so lets set the created_id $session = CRM_Core_Session::singleton(); $params['created_id'] = $session->get('userID'); $params['created_date'] = date('YmdHis'); } $mailing = CRM_Mailing_BAO_Mailing::create($params, $ids); $this->set('mailing_id', $mailing->id); // also compute the recipients and store them in the mailing recipients table CRM_Mailing_BAO_Mailing::getRecipients($mailing->id, $mailing->id, TRUE, FALSE, 'sms'); $count = CRM_Mailing_BAO_Recipients::mailingSize($mailing->id); $this->set('count', $count); $this->assign('count', $count); $this->set('groups', $groups); $this->set('mailings', $mailings); if ($qf_Group_submit) { $status = ts("Your Mass SMS has been saved."); CRM_Core_Session::setStatus($status, ts('Saved'), 'success'); $url = CRM_Utils_System::url('civicrm/mailing', 'reset=1&sms=1'); return $this->controller->setDestination($url); } }
/** * Returns all the rows in the given offset and rowCount. * * @param string $action * The action being performed. * @param int $offset * The row number to start from. * @param int $rowCount * The number of rows to return. * @param string $sort * The sql string that describes the sort order. * @param string $output * What should the result set include (web/email/csv). * * @return array * rows in the given offset and rowCount */ public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) { $result = $this->_query->searchQuery($offset, $rowCount, $sort, FALSE, FALSE, FALSE, FALSE, FALSE, $this->_activityClause); $rows = array(); $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs(); $accessCiviMail = CRM_Core_Permission::check('access CiviMail'); //get all campaigns. $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE); $engagementLevels = CRM_Campaign_PseudoConstant::engagementLevel(); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); //get all activity types $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name', TRUE); while ($result->fetch()) { $row = array(); // ignore rows where we dont have an activity id if (empty($result->activity_id)) { continue; } // the columns we are interested in foreach (self::$_properties as $property) { if (isset($result->{$property})) { $row[$property] = $result->{$property}; } } $contactId = CRM_Utils_Array::value('contact_id', $row); if (!$contactId) { $contactId = CRM_Utils_Array::value('source_contact_id', $row); } $row['target_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $targetID); $row['assignee_contact_name'] = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $assigneeID); list($row['source_contact_name'], $row['source_contact_id']) = CRM_Activity_BAO_ActivityContact::getNames($row['activity_id'], $sourceID, TRUE); $row['source_contact_name'] = implode(',', array_values($row['source_contact_name'])); $row['source_contact_id'] = implode(',', $row['source_contact_id']); if ($this->_context == 'search') { $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->activity_id; } $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id); $accessMailingReport = FALSE; $activityTypeId = $row['activity_type_id']; if ($row['activity_is_test']) { $row['activity_type'] = $row['activity_type'] . " (test)"; } $bulkActivityTypeID = CRM_Utils_Array::key('Bulk Email', $activityTypes); $row['mailingId'] = ''; if ($accessCiviMail && ($mailingIDs === TRUE || in_array($result->source_record_id, $mailingIDs)) && $bulkActivityTypeID == $activityTypeId) { $row['mailingId'] = CRM_Utils_System::url('civicrm/mailing/report', "mid={$result->source_record_id}&reset=1&cid={$contactId}&context=activitySelector"); $row['recipients'] = ts('(recipients)'); $row['target_contact_name'] = ''; $row['assignee_contact_name'] = ''; $accessMailingReport = TRUE; } $activityActions = new CRM_Activity_Selector_Activity($result->contact_id, NULL); $actionLinks = $activityActions->actionLinks($activityTypeId, CRM_Utils_Array::value('source_record_id', $row), $accessMailingReport, CRM_Utils_Array::value('activity_id', $row), $this->_key, $this->_compContext); $row['action'] = CRM_Core_Action::formLink($actionLinks, NULL, array('id' => $result->activity_id, 'cid' => $contactId, 'cxt' => $this->_context), ts('more'), FALSE, 'activity.selector.row', 'Activity', $result->activity_id); //carry campaign to selector. $row['campaign'] = CRM_Utils_Array::value($result->activity_campaign_id, $allCampaigns); $row['campaign_id'] = $result->activity_campaign_id; if ($engagementLevel = CRM_Utils_Array::value('activity_engagement_level', $row)) { $row['activity_engagement_level'] = CRM_Utils_Array::value($engagementLevel, $engagementLevels, $engagementLevel); } //Check if recurring activity $repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($row['activity_id'], 'civicrm_activity'); $row['repeat'] = ''; if ($repeat) { $row['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1])); } $rows[] = $row; } return $rows; }
/** * Get the list Activities. * * @param array $input * Array of parameters. * Keys include * - contact_id int contact_id whose activities we want to retrieve * - offset int which row to start from ? * - rowCount int how many rows to fetch * - sort object|array object or array describing sort order for sql query. * - admin boolean if contact is admin * - caseId int case ID * - context string page on which selector is build * - activity_type_id int|string the activitiy types we want to restrict by * * @return array * Relevant data object values of open activities */ public static function &getActivities($input) { // Step 1: Get the basic activity data. $bulkActivityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Bulk Email', 'name'); $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts); $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts); $config = CRM_Core_Config::singleton(); $randomNum = md5(uniqid()); $activityTempTable = "civicrm_temp_activity_details_{$randomNum}"; $tableFields = array('activity_id' => 'int unsigned', 'activity_date_time' => 'datetime', 'source_record_id' => 'int unsigned', 'status_id' => 'int unsigned', 'subject' => 'varchar(255)', 'source_contact_name' => 'varchar(255)', 'activity_type_id' => 'int unsigned', 'activity_type' => 'varchar(128)', 'case_id' => 'int unsigned', 'case_subject' => 'varchar(255)', 'campaign_id' => 'int unsigned'); $sql = "CREATE TEMPORARY TABLE {$activityTempTable} ( "; $insertValueSQL = array(); // The activityTempTable contains the sorted rows // so in order to maintain the sort order as-is we add an auto_increment // field; we can sort by this later to ensure the sort order stays correct. $sql .= " fixed_sort_order INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,"; foreach ($tableFields as $name => $desc) { $sql .= "{$name} {$desc},\n"; $insertValueSQL[] = $name; } // add unique key on activity_id just to be sure // this cannot be primary key because we need that for the auto_increment // fixed_sort_order field $sql .= "\n UNIQUE KEY ( activity_id )\n ) ENGINE=HEAP DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci\n "; CRM_Core_DAO::executeQuery($sql); $insertSQL = "INSERT INTO {$activityTempTable} (" . implode(',', $insertValueSQL) . " ) "; $order = $limit = $groupBy = ''; $groupBy = " GROUP BY tbl.activity_id "; if (!empty($input['sort'])) { if (is_a($input['sort'], 'CRM_Utils_Sort')) { $orderBy = $input['sort']->orderBy(); if (!empty($orderBy)) { $order = " ORDER BY {$orderBy}"; } } elseif (trim($input['sort'])) { $sort = CRM_Utils_Type::escape($input['sort'], 'String'); $order = " ORDER BY {$sort} "; } } if (empty($order)) { // context = 'activity' in Activities tab. $order = CRM_Utils_Array::value('context', $input) == 'activity' ? " ORDER BY tbl.activity_date_time desc " : " ORDER BY tbl.status_id asc, tbl.activity_date_time asc "; } if (!empty($input['rowCount']) && $input['rowCount'] > 0) { $limit = " LIMIT {$input['offset']}, {$input['rowCount']} "; } $input['count'] = FALSE; list($sqlClause, $params) = self::getActivitySQLClause($input); $query = "{$insertSQL}\n SELECT DISTINCT tbl.* from ( {$sqlClause} )\nas tbl "; // Filter case activities - CRM-5761. $components = self::activityComponents(); if (!in_array('CiviCase', $components)) { $query .= "\nLEFT JOIN civicrm_case_activity ON ( civicrm_case_activity.activity_id = tbl.activity_id )\n WHERE civicrm_case_activity.id IS NULL"; } $query = $query . $groupBy . $order . $limit; $dao = CRM_Core_DAO::executeQuery($query, $params); // step 2: Get target and assignee contacts for above activities // create temp table for target contacts $activityContactTempTable = "civicrm_temp_activity_contact_{$randomNum}"; $query = "CREATE TEMPORARY TABLE {$activityContactTempTable} (\n activity_id int unsigned, contact_id int unsigned, record_type_id varchar(16),\n contact_name varchar(255), is_deleted int unsigned, counter int unsigned, INDEX index_activity_id( activity_id ) )\n ENGINE=MYISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"; CRM_Core_DAO::executeQuery($query); // note that we ignore bulk email for targets, since we don't show it in selector $query = "\nINSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted )\nSELECT ac.activity_id,\n ac.contact_id,\n ac.record_type_id,\n c.sort_name,\n c.is_deleted\nFROM {$activityTempTable}\nINNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )\nINNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )\nINNER JOIN civicrm_contact c ON c.id = ac.contact_id\nWHERE ac.record_type_id != %1\n"; $params = array(1 => array($targetID, 'Integer')); CRM_Core_DAO::executeQuery($query, $params); // for each activity insert one target contact // if we load all target contacts the performance will suffer a lot for mass-activities. $query = "\nINSERT INTO {$activityContactTempTable} ( activity_id, contact_id, record_type_id, contact_name, is_deleted, counter )\nSELECT ac.activity_id,\n ac.contact_id,\n ac.record_type_id,\n c.sort_name,\n c.is_deleted,\n count(ac.contact_id)\nFROM {$activityTempTable}\nINNER JOIN civicrm_activity a ON ( a.id = {$activityTempTable}.activity_id )\nINNER JOIN civicrm_activity_contact ac ON ( ac.activity_id = {$activityTempTable}.activity_id )\nINNER JOIN civicrm_contact c ON c.id = ac.contact_id\nWHERE ac.record_type_id = %1\nGROUP BY ac.activity_id\n"; CRM_Core_DAO::executeQuery($query, $params); // step 3: Combine all temp tables to get final query for activity selector // sort by the original sort order, stored in fixed_sort_order $query = "\nSELECT {$activityTempTable}.*,\n {$activityContactTempTable}.contact_id,\n {$activityContactTempTable}.record_type_id,\n {$activityContactTempTable}.contact_name,\n {$activityContactTempTable}.is_deleted,\n {$activityContactTempTable}.counter,\n re.parent_id as is_recurring_activity\nFROM {$activityTempTable}\nINNER JOIN {$activityContactTempTable} on {$activityTempTable}.activity_id = {$activityContactTempTable}.activity_id\nLEFT JOIN civicrm_recurring_entity re on {$activityContactTempTable}.activity_id = re.entity_id\nORDER BY fixed_sort_order\n "; $dao = CRM_Core_DAO::executeQuery($query); // CRM-3553, need to check user has access to target groups. $mailingIDs = CRM_Mailing_BAO_Mailing::mailingACLIDs(); $accessCiviMail = CRM_Core_Permission::check('access CiviMail') || CRM_Mailing_Info::workflowEnabled() && CRM_Core_Permission::check('create mailings'); // Get all campaigns. $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE); $values = array(); while ($dao->fetch()) { $activityID = $dao->activity_id; $values[$activityID]['activity_id'] = $dao->activity_id; $values[$activityID]['source_record_id'] = $dao->source_record_id; $values[$activityID]['activity_type_id'] = $dao->activity_type_id; $values[$activityID]['activity_type'] = $dao->activity_type; $values[$activityID]['activity_date_time'] = $dao->activity_date_time; $values[$activityID]['status_id'] = $dao->status_id; $values[$activityID]['subject'] = $dao->subject; $values[$activityID]['campaign_id'] = $dao->campaign_id; $values[$activityID]['is_recurring_activity'] = $dao->is_recurring_activity; if ($dao->campaign_id) { $values[$activityID]['campaign'] = $allCampaigns[$dao->campaign_id]; } if (empty($values[$activityID]['assignee_contact_name'])) { $values[$activityID]['assignee_contact_name'] = array(); } if (empty($values[$activityID]['target_contact_name'])) { $values[$activityID]['target_contact_name'] = array(); $values[$activityID]['target_contact_counter'] = $dao->counter; } // if deleted, wrap in <del> if ($dao->is_deleted) { $dao->contact_name = "<del>{$dao->contact_name}</del>"; } if ($dao->record_type_id == $sourceID && $dao->contact_id) { $values[$activityID]['source_contact_id'] = $dao->contact_id; $values[$activityID]['source_contact_name'] = $dao->contact_name; } if (!$bulkActivityTypeID || $bulkActivityTypeID != $dao->activity_type_id) { // build array of target / assignee names if ($dao->record_type_id == $targetID && $dao->contact_id) { $values[$activityID]['target_contact_name'][$dao->contact_id] = $dao->contact_name; } if ($dao->record_type_id == $assigneeID && $dao->contact_id) { $values[$activityID]['assignee_contact_name'][$dao->contact_id] = $dao->contact_name; } // case related fields $values[$activityID]['case_id'] = $dao->case_id; $values[$activityID]['case_subject'] = $dao->case_subject; } else { $values[$activityID]['recipients'] = ts('(%1 recipients)', array(1 => $dao->counter)); $values[$activityID]['mailingId'] = FALSE; if ($accessCiviMail && ($mailingIDs === TRUE || in_array($dao->source_record_id, $mailingIDs))) { $values[$activityID]['mailingId'] = TRUE; } } } return $values; }
/** * Process the posted form values. Create and schedule a Mass SMS. */ public function postProcess() { $params = array(); $params['mailing_id'] = $ids['mailing_id'] = $this->_mailingID; if (empty($params['mailing_id'])) { CRM_Core_Error::fatal(ts('Could not find a mailing id')); } foreach (array('now', 'start_date', 'start_date_time') as $parameter) { $params[$parameter] = $this->controller->exportValue($this->_name, $parameter); } if ($params['now']) { $params['scheduled_date'] = date('YmdHis'); } else { $params['scheduled_date'] = CRM_Utils_Date::processDate($params['start_date'] . ' ' . $params['start_date_time']); } $session = CRM_Core_Session::singleton(); // set the scheduled_id $params['scheduled_id'] = $session->get('userID'); $params['scheduled_date'] = date('YmdHis'); // set approval details if workflow is not enabled if (!CRM_Mailing_Info::workflowEnabled()) { $params['approver_id'] = $session->get('userID'); $params['approval_date'] = date('YmdHis'); $params['approval_status_id'] = 1; } if ($params['now']) { $params['scheduled_date'] = date('YmdHis'); } else { $params['scheduled_date'] = CRM_Utils_Date::processDate($params['start_date'] . ' ' . $params['start_date_time']); } // Build the mailing object. CRM_Mailing_BAO_Mailing::create($params, $ids); $session = CRM_Core_Session::singleton(); $session->pushUserContext(CRM_Utils_System::url('civicrm/mailing/browse/scheduled', 'reset=1&scheduled=true&sms=1')); }
/** * Function to build the form * * @return None * @access public */ public function buildQuickForm() { parent::buildQuickForm(); $this->_mappingID = $mappingID = NULL; if ($this->_action & CRM_Core_Action::DELETE) { $reminderName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'title'); $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this); if ($this->_context == 'event') { $this->_eventId = CRM_Utils_Request::retrieve('eventId', 'Integer', $this); } $this->assign('reminderName', $reminderName); return; } elseif ($this->_action & CRM_Core_Action::UPDATE) { $this->_mappingID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionSchedule', $this->_id, 'mapping_id'); $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this); if ($this->_context == 'event') { $this->_eventId = CRM_Utils_Request::retrieve('eventId', 'Integer', $this); } } if (!empty($_POST) && CRM_Utils_Array::value('entity', $_POST)) { $mappingID = $_POST['entity'][0]; } elseif ($this->_mappingID) { $mappingID = $this->_mappingID; } $this->add('text', 'title', ts('Title'), array('size' => 45, 'maxlength' => 128), TRUE); $selectionOptions = CRM_Core_BAO_ActionSchedule::getSelection($mappingID); extract($selectionOptions); if (empty($sel1)) { CRM_Core_Error::fatal('Could not find mapping for scheduled reminders.'); } $this->assign('entityMapping', json_encode($entityMapping)); $this->assign('recipientMapping', json_encode($recipientMapping)); $sel =& $this->add('hierselect', 'entity', ts('Entity'), array('name' => 'entity[0]', 'style' => 'vertical-align: top;'), TRUE); $sel->setOptions(array($sel1, $sel2, $sel3)); if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) { // make second selector a multi-select - $sel->_elements[1]->setMultiple(TRUE); $sel->_elements[1]->setSize(5); } if (is_a($sel->_elements[2], 'HTML_QuickForm_select')) { // make third selector a multi-select - $sel->_elements[2]->setMultiple(TRUE); $sel->_elements[2]->setSize(5); } //get the frequency units. $this->_freqUnits = array('hour' => 'hour') + CRM_Core_OptionGroup::values('recur_frequency_units'); //pass the mapping ID in UPDATE mode $mappings = CRM_Core_BAO_ActionSchedule::getMapping($mappingID); $numericOptions = CRM_Core_SelectValues::getNumericOptions(0, 30); //reminder_interval $this->add('select', 'start_action_offset', ts('When'), $numericOptions); foreach ($this->_freqUnits as $val => $label) { $freqUnitsDisplay[$val] = ts('%1(s)', array(1 => $label)); } $this->addDate('absolute_date', ts('Start Date'), FALSE, array('formatType' => 'mailing')); //reminder_frequency $this->add('select', 'start_action_unit', ts('Frequency'), $freqUnitsDisplay, TRUE); $condition = array('before' => ts('before'), 'after' => ts('after')); //reminder_action $this->add('select', 'start_action_condition', ts('Action Condition'), $condition); $this->add('select', 'start_action_date', ts('Date Field'), $sel4, TRUE); $this->addElement('checkbox', 'is_repeat', ts('Repeat'), NULL, array('onclick' => "return showHideByValue('is_repeat',true,'repeatFields','table-row','radio',false);")); $this->add('select', 'repetition_frequency_unit', ts('every'), $freqUnitsDisplay); $this->add('select', 'repetition_frequency_interval', ts('every'), $numericOptions); $this->add('select', 'end_frequency_unit', ts('until'), $freqUnitsDisplay); $this->add('select', 'end_frequency_interval', ts('until'), $numericOptions); $this->add('select', 'end_action', ts('Repetition Condition'), $condition, TRUE); $this->add('select', 'end_date', ts('Date Field'), $sel4, TRUE); $recipient = 'activity_contacts'; $recipientListingOptions = array(); if ($mappingID) { $recipient = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_ActionMapping', $mappingID, 'entity_recipient'); } $this->add('select', 'recipient', ts('Recipient(s)'), $sel5[$recipient], FALSE, array('onClick' => "showHideByValue('recipient','manual','recipientManual','table-row','select',false); showHideByValue('recipient','group','recipientGroup','table-row','select',false);")); if (CRM_Utils_Array::value('is_recipient_listing', $_POST)) { $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($_POST['entity'][0], $_POST['recipient']); } elseif (CRM_Utils_Array::value('recipient_listing', $this->_values)) { $recipientListingOptions = CRM_Core_BAO_ActionSchedule::getRecipientListing($this->_values['mapping_id'], $this->_values['recipient']); } $recipientListing = $this->add('select', 'recipient_listing', ts('Recipient Listing'), $recipientListingOptions); $recipientListing->setMultiple(TRUE); $this->add('hidden', 'is_recipient_listing', empty($recipientListingOptions) ? FALSE : TRUE, array('id' => 'is_recipient_listing')); //autocomplete url $dataUrl = CRM_Utils_System::url('civicrm/ajax/rest', 'className=CRM_Contact_Page_AJAX&fnName=getContactList&json=1&context=activity&reset=1', FALSE, NULL, FALSE); $this->assign('dataUrl', $dataUrl); //tokeninput url $tokenUrl = CRM_Utils_System::url('civicrm/ajax/checkemail', 'noemail=1', FALSE, NULL, FALSE); $this->assign('tokenUrl', $tokenUrl); $this->add('text', 'recipient_manual_id', ts('Manual Recipients')); $this->addElement('select', 'group_id', ts('Group'), CRM_Core_PseudoConstant::staticGroup()); CRM_Mailing_BAO_Mailing::commonCompose($this); $this->add('text', 'subject', ts('Subject'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_ActionSchedule', 'subject')); $this->add('checkbox', 'is_active', ts('Send email')); $this->addFormRule(array('CRM_Admin_Form_ScheduleReminders', 'formRule')); }