4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.6 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
31 * APIv3 functions for registering/processing mailing events.
33 * @package CiviCRM_APIv3
34 * @subpackage API_Mailing
35 * @copyright CiviCRM LLC (c) 2004-2014
41 * Files required for this package
45 * Handle a create event.
47 * @param array $params
50 * @return array API Success Array
52 function civicrm_api3_mailing_create($params, $ids = array()) {
53 if (CRM_Mailing_Info
::workflowEnabled()) {
54 if (!CRM_Core_Permission
::check('create mailings')) {
55 throw new \Civi\API\Exception\
UnauthorizedException("This system uses advanced CiviMail workflows which require additional permissions");
57 if (!CRM_Core_Permission
::check('schedule mailings')) {
58 unset($params['scheduled_date']);
59 unset($params['scheduled_id']);
61 if (!CRM_Core_Permission
::check('approve mailings')) {
62 unset($params['approval_date']);
63 unset($params['approver_id']);
64 unset($params['approval_status_id']);
65 unset($params['approval_note']);
68 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__
), $params);
71 function civicrm_api3_mailing_get_token($params) {
72 if (!array_key_exists("usage", $params)) {
73 throw new API_Exception('Mandatory keys missing from params array: entity');
76 $tokens = CRM_Core_SelectValues
::contactTokens();
77 switch ($params['usage']) {
79 $tokens = array_merge(CRM_Core_SelectValues
::mailingTokens(), $tokens);
81 case 'ScheduleEventReminder' :
82 $tokens = array_merge(CRM_Core_SelectValues
::activityTokens(), $tokens);
83 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
84 $tokens = array_merge(CRM_Core_SelectValues
::membershipTokens(), $tokens);
86 case 'ManageEventScheduleReminder' :
87 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
91 return CRM_Utils_Token
::formatTokensForDisplay($tokens);
95 * Adjust Metadata for Create action
97 * The metadata is used for setting defaults, documentation & validation
98 * @param array $params
99 * Array or parameters determined by getfields.
101 function _civicrm_api3_mailing_create_spec(&$params) {
102 $params['name']['api.required'] = 1;
103 $params['subject']['api.required'] = 1;
104 $params['created_id']['api.required'] = 1;
105 $params['created_id']['api.default'] = 'user_contact_id';
106 $params['api.mailing_job.create']['api.default'] = 1;
107 $params['api.mailing_job.create']['title'] = 'Schedule Mailing?';
111 * Handle a delete event.
113 * @param array $params
116 * @return array API Success Array
118 function civicrm_api3_mailing_delete($params, $ids = array()) {
119 return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__
), $params);
123 * Handle a get event.
125 * @param array $params
128 function civicrm_api3_mailing_get($params) {
129 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__
), $params);
132 function _civicrm_api3_mailing_submit_spec(&$spec) {
133 $mailingFields = CRM_Mailing_DAO_Mailing
::fields();
134 $spec['id'] = $mailingFields['id'];
135 $spec['scheduled_date'] = $mailingFields['scheduled_date'];
136 $spec['approval_date'] = $mailingFields['approval_date'];
137 $spec['approval_status_id'] = $mailingFields['approval_status_id'];
138 $spec['approval_note'] = $mailingFields['approval_note'];
139 // _skip_evil_bao_auto_recipients_: bool
143 * @param array $params
145 * @throws API_Exception
147 function civicrm_api3_mailing_submit($params) {
148 civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_Mailing', array('id'));
150 if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
151 throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
153 if (!is_numeric(CRM_Core_Session
::getLoggedInContactID())) {
154 throw new API_Exception("Failed to determine current user");
157 $updateParams = array();
158 $updateParams['id'] = $params['id'];
160 // the BAO will autocreate the job
161 $updateParams['api.mailing_job.create'] = 0; // note: exact match to API default
163 // note: we'll pass along scheduling/approval fields, but they may get ignored
164 // if we don't have permission
165 if (isset($params['scheduled_date'])) {
166 $updateParams['scheduled_date'] = $params['scheduled_date'];
167 $updateParams['scheduled_id'] = CRM_Core_Session
::getLoggedInContactID();
169 if (isset($params['approval_date'])) {
170 $updateParams['approval_date'] = $params['approval_date'];
171 $updateParams['approver_id'] = CRM_Core_Session
::getLoggedInContactID();
172 $updateParams['approval_status_id'] = CRM_Utils_Array
::value('approval_status_id', $updateParams, CRM_Core_OptionGroup
::getDefaultValue('mail_approval_status'));
174 if (isset($params['approval_note'])) {
175 $updateParams['approval_note'] = $params['approval_note'];
177 if (isset($params['_skip_evil_bao_auto_recipients_'])) {
178 $updateParams['_skip_evil_bao_auto_recipients_'] = $params['_skip_evil_bao_auto_recipients_'];
181 $updateParams['options']['reload'] = 1;
182 return civicrm_api3('Mailing', 'create', $updateParams);
186 * Process a bounce event by passing through to the BAOs.
188 * @param array $params
190 * @throws API_Exception
193 function civicrm_api3_mailing_event_bounce($params) {
194 $body = $params['body'];
195 unset($params['body']);
197 $params +
= CRM_Mailing_BAO_BouncePattern
::match($body);
199 if (CRM_Mailing_Event_BAO_Bounce
::create($params)) {
200 return civicrm_api3_create_success($params);
203 throw new API_Exception(ts('Queue event could not be found'),'no_queue_event
209 * Adjust Metadata for bounce_spec action
211 * The metadata is used for setting defaults, documentation & validation
212 * @param array $params
213 * Array or parameters determined by getfields.
215 function _civicrm_api3_mailing_event_bounce_spec(&$params) {
216 $params['job_id']['api.required'] = 1;
217 $params['job_id']['title'] = 'Job ID';
218 $params['event_queue_id']['api.required'] = 1;
219 $params['event_queue_id']['title'] = 'Event Queue ID';
220 $params['hash']['api.required'] = 1;
221 $params['hash']['title'] = 'Hash';
222 $params['body']['api.required'] = 1;
223 $params['body']['title'] = 'Body';
227 * Handle a confirm event
230 * @param array $params
234 function civicrm_api3_mailing_event_confirm($params) {
235 return civicrm_api('mailing_event_confirm', 'create', $params);
239 * @deprecated api notice
240 * @return array of deprecated actions
242 function _civicrm_api3_mailing_deprecation() {
243 return array('event_confirm' => 'Mailing api "event_confirm" action is deprecated. Use the mailing_event_confirm api instead.');
247 * Handle a reply event
249 * @param array $params
253 function civicrm_api3_mailing_event_reply($params) {
254 $job = $params['job_id'];
255 $queue = $params['event_queue_id'];
256 $hash = $params['hash'];
257 $replyto = $params['replyTo'];
258 $bodyTxt = CRM_Utils_Array
::value('bodyTxt', $params);
259 $bodyHTML = CRM_Utils_Array
::value('bodyHTML', $params);
260 $fullEmail = CRM_Utils_Array
::value('fullEmail', $params);
262 $mailing = CRM_Mailing_Event_BAO_Reply
::reply($job, $queue, $hash, $replyto);
264 if (empty($mailing)) {
265 return civicrm_api3_create_error('Queue event could not be found');
268 CRM_Mailing_Event_BAO_Reply
::send($queue, $mailing, $bodyTxt, $replyto, $bodyHTML, $fullEmail);
270 return civicrm_api3_create_success($params);
274 * Adjust Metadata for event_reply action
276 * The metadata is used for setting defaults, documentation & validation
277 * @param array $params
278 * Array or parameters determined by getfields.
280 function _civicrm_api3_mailing_event_reply_spec(&$params) {
281 $params['job_id']['api.required'] = 1;
282 $params['job_id']['title'] = 'Job ID';
283 $params['event_queue_id']['api.required'] = 1;
284 $params['event_queue_id']['title'] = 'Event Queue ID';
285 $params['hash']['api.required'] = 1;
286 $params['hash']['title'] = 'Hash';
287 $params['replyTo']['api.required'] = 0;
288 $params['replyTo']['title'] = 'Reply To';//doesn't really explain adequately
292 * Handle a forward event
294 * @param array $params
298 function civicrm_api3_mailing_event_forward($params) {
299 $job = $params['job_id'];
300 $queue = $params['event_queue_id'];
301 $hash = $params['hash'];
302 $email = $params['email'];
303 $fromEmail = CRM_Utils_Array
::value('fromEmail', $params);
304 $params = CRM_Utils_Array
::value('params', $params);
306 $forward = CRM_Mailing_Event_BAO_Forward
::forward($job, $queue, $hash, $email, $fromEmail, $params);
309 return civicrm_api3_create_success($params);
312 return civicrm_api3_create_error('Queue event could not be found');
316 * Adjust Metadata for event_forward action
318 * The metadata is used for setting defaults, documentation & validation
319 * @param array $params
320 * Array or parameters determined by getfields.
322 function _civicrm_api3_mailing_event_forward_spec(&$params) {
323 $params['job_id']['api.required'] = 1;
324 $params['job_id']['title'] = 'Job ID';
325 $params['event_queue_id']['api.required'] = 1;
326 $params['event_queue_id']['title'] = 'Event Queue ID';
327 $params['hash']['api.required'] = 1;
328 $params['hash']['title'] = 'Hash';
329 $params['email']['api.required'] = 1;
330 $params['email']['title'] = 'Forwarded to Email';
334 * Handle a click event
336 * @param array $params
340 function civicrm_api3_mailing_event_click($params) {
341 civicrm_api3_verify_mandatory($params,
342 'CRM_Mailing_Event_DAO_TrackableURLOpen',
343 array('event_queue_id', 'url_id'),
347 $url_id = $params['url_id'];
348 $queue = $params['event_queue_id'];
350 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($queue, $url_id);
353 $values['url'] = $url;
354 $values['is_error'] = 0;
356 return civicrm_api3_create_success($values);
360 * Handle an open event
362 * @param array $params
366 function civicrm_api3_mailing_event_open($params) {
368 civicrm_api3_verify_mandatory($params,
369 'CRM_Mailing_Event_DAO_Opened',
370 array('event_queue_id'),
374 $queue = $params['event_queue_id'];
375 $success = CRM_Mailing_Event_BAO_Opened
::open($queue);
378 return civicrm_api3_create_error('mailing open event failed');
381 return civicrm_api3_create_success($params);
384 function civicrm_api3_mailing_preview($params) {
385 civicrm_api3_verify_mandatory($params,
386 'CRM_Mailing_DAO_Mailing',
392 if (!empty($params['from_email'])) {
393 $fromEmail = $params['from_email'];
396 $session = CRM_Core_Session
::singleton();
397 $mailing = new CRM_Mailing_BAO_Mailing();
398 $mailing->id
= $params['id'];
399 $mailing->find(TRUE);
401 CRM_Mailing_BAO_Mailing
::tokenReplace($mailing);
403 // get and format attachments
404 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_mailing', $mailing->id
);
406 $returnProperties = $mailing->getReturnProperties();
407 $contactID = CRM_Utils_Array
::value('contact_id', $params);
409 $contactID = $session->get('userID');
411 $mailingParams = array('contact_id' => $contactID);
413 $details = CRM_Utils_Token
::getTokenDetails($mailingParams, $returnProperties, TRUE, TRUE, NULL, $mailing->getFlattenedTokens());
415 $mime = &$mailing->compose(NULL, NULL, NULL, $session->get('userID'), $fromEmail, $fromEmail,
416 TRUE, $details[0][$contactID], $attachments
419 return civicrm_api3_create_success(array(
420 'id' => $params['id'],
421 'contact_id' => $contactID,
422 'subject' => $mime->_headers
['Subject'],
423 'body_html' => $mime->getHTMLBody(),
424 'body_text' => $mime->getTXTBody(),
428 function _civicrm_api3_mailing_send_test_spec(&$spec) {
429 $spec['test_group']['title'] = 'Test Group ID';
430 $spec['test_email']['title'] = 'Test Email Address';
433 function civicrm_api3_mailing_send_test($params) {
434 if (!array_key_exists('test_group', $params) && !array_key_exists('test_email', $params)) {
435 throw new API_Exception("Mandatory key(s) missing from params array: test_group and/or test_email field are required");
437 civicrm_api3_verify_mandatory($params,
438 'CRM_Mailing_DAO_MailingJob',
443 $testEmailParams = _civicrm_api3_generic_replace_base_params($params);
444 $testEmailParams['is_test'] = 1;
445 $job = civicrm_api3('MailingJob', 'create', $testEmailParams);
446 $testEmailParams['job_id'] = $job['id'];
447 $testEmailParams['emails'] = explode(',', $testEmailParams['test_email']);
448 if (!empty($params['test_email'])) {
449 $query = CRM_Utils_SQL_Select
::from('civicrm_email e')
450 ->select(array('e.id', 'e.contact_id', 'e.email'))
451 ->join('c', 'INNER JOIN civicrm_contact c ON e.contact_id = c.id')
452 ->where('e.email IN (@emails)', array('@emails' => $testEmailParams['emails']))
453 ->where('e.on_hold = 0')
454 ->where('c.is_opt_out = 0')
455 ->where('c.do_not_email = 0')
456 ->where('c.is_deceased = 0')
458 ->orderBy(array('e.is_bulkmail DESC', 'e.is_primary DESC'))
460 $dao = CRM_Core_DAO
::executeQuery($query);
461 $emailDetail = array();
462 // fetch contact_id and email id for all existing emails
463 while ($dao->fetch()) {
464 $emailDetail[$dao->email
] = array(
465 'contact_id' => $dao->contact_id
,
466 'email_id' => $dao->id
,
470 foreach ($testEmailParams['emails'] as $key => $email) {
471 $email = trim($email);
472 $contactId = $emailId = NULL;
473 if (array_key_exists($email, $emailDetail)) {
474 $emailId = $emailDetail[$email]['email_id'];
475 $contactId = $emailDetail[$email]['contact_id'];
478 //create new contact.
479 $contact = civicrm_api3('Contact', 'create',
480 array('contact_type' => 'Individual',
482 'api.Email.get' => array('return' => 'id')
485 $contactId = $contact['id'];
486 $emailId = $contact['values'][$contactId]['api.Email.get']['id'];
488 civicrm_api3('MailingEventQueue', 'create',
489 array('job_id' => $job['id'],
490 'email_id' => $emailId,
491 'contact_id' => $contactId
498 $config = CRM_Core_Config
::singleton();
499 $mailerJobSize = (property_exists($config, 'mailerJobSize')) ?
$config->mailerJobSize
: NULL;
500 while (!$isComplete) {
501 // Q: In CRM_Mailing_BAO_Mailing::processQueue(), the three runJobs*()
502 // functions are all called. Why does Mailing.send_test only call one?
503 // CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, NULL);
504 $isComplete = CRM_Mailing_BAO_MailingJob
::runJobs($testEmailParams);
505 // CRM_Mailing_BAO_MailingJob::runJobs_post(NULL);
508 //return delivered mail info
509 $mailDelivered = CRM_Mailing_Event_BAO_Delivered
::getRows($params['mailing_id'], $job['id'], TRUE, NULL, NULL, NULL, TRUE);
511 return civicrm_api3_create_success($mailDelivered);
515 * Adjust Metadata for send_mail action
517 * The metadata is used for setting defaults, documentation & validation
518 * @param array $params
519 * Array or parameters determined by getfields.
521 function _civicrm_api3_mailing_stats_spec(&$params) {
522 $params['date']['api.default'] = 'now';
523 $params['date']['title'] = 'Date';
526 function civicrm_api3_mailing_stats($params) {
527 civicrm_api3_verify_mandatory($params,
528 'CRM_Mailing_DAO_MailingJob',
533 if ($params['date'] == 'now') {
534 $params['date'] = date('YmdHis');
537 $params['date'] = CRM_Utils_Date
::processDate($params['date'] . ' ' . $params['date_time']);
540 $stats[$params['mailing_id']] = array();
541 if (empty($params['job_id'])) {
542 $params['job_id'] = NULL;
544 foreach (array('Delivered', 'Bounces', 'Unsubscribers', 'Unique Clicks', 'Opened') as $detail) {
547 $stats[$params['mailing_id']] +
= array(
548 $detail => CRM_Mailing_Event_BAO_Delivered
::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date'])
552 $stats[$params['mailing_id']] +
= array(
553 $detail => CRM_Mailing_Event_BAO_Bounce
::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date'])
556 case 'Unsubscribers':
557 $stats[$params['mailing_id']] +
= array(
558 $detail => CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date'])
561 case 'Unique Clicks':
562 $stats[$params['mailing_id']] +
= array(
563 $detail => CRM_Mailing_Event_BAO_TrackableURLOpen
::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date'])
567 $stats[$params['mailing_id']] +
= array(
568 $detail => CRM_Mailing_Event_BAO_Opened
::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date'])
573 return civicrm_api3_create_success($stats);
577 * Fix the reset dates on the email record based on when a mail was last delivered
578 * We only consider mailings that were completed and finished in the last 3 to 7 days
579 * Both the min and max days can be set via the params
581 function civicrm_api3_mailing_update_email_resetdate($params) {
582 CRM_Mailing_Event_BAO_Delivered
::updateEmailResetDate(
583 CRM_Utils_Array
::value('minDays', $params, 3),
584 CRM_Utils_Array
::value('maxDays', $params, 3)
586 return civicrm_api3_create_success();