Merge branch '4.7.28-rc' into master
[civicrm-core.git] / api / v3 / Mailing.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * APIv3 functions for registering/processing mailing events.
31 *
32 * @package CiviCRM_APIv3
33 */
34
35 /**
36 * Handle a create event.
37 *
38 * @param array $params
39 *
40 * @return array
41 * API Success Array
42 * @throws \API_Exception
43 * @throws \Civi\API\Exception\UnauthorizedException
44 */
45 function civicrm_api3_mailing_create($params) {
46 if (isset($params['template_options']) && is_array($params['template_options'])) {
47 $params['template_options'] = ($params['template_options'] === array()) ? '{}' : json_encode($params['template_options']);
48 }
49 if (CRM_Mailing_Info::workflowEnabled()) {
50 // Note: 'schedule mailings' and 'approve mailings' can update certain fields, but can't create.
51
52 if (empty($params['id'])) {
53 if (!CRM_Core_Permission::check('access CiviMail') && !CRM_Core_Permission::check('create mailings')) {
54 throw new \Civi\API\Exception\UnauthorizedException("Cannot create new mailing. Required permission: 'access CiviMail' or 'create mailings'");
55 }
56 }
57
58 $safeParams = array();
59 $fieldPerms = CRM_Mailing_BAO_Mailing::getWorkflowFieldPerms();
60 foreach (array_keys($params) as $field) {
61 if (CRM_Core_Permission::check($fieldPerms[$field])) {
62 $safeParams[$field] = $params[$field];
63 }
64 }
65 }
66 else {
67 $safeParams = $params;
68 }
69 $timestampCheck = TRUE;
70 if (!empty($params['id']) && !empty($params['modified_date'])) {
71 $timestampCheck = _civicrm_api3_compare_timestamps($safeParams['modified_date'], $safeParams['id'], 'Mailing');
72 unset($safeParams['modified_date']);
73 }
74 if (!$timestampCheck) {
75 throw new API_Exception("Mailing has not been saved, Content maybe out of date, please refresh the page and try again");
76 }
77 $safeParams['_evil_bao_validator_'] = 'CRM_Mailing_BAO_Mailing::checkSendable';
78 $result = _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $safeParams);
79 return _civicrm_api3_mailing_get_formatResult($result);
80 }
81
82 /**
83 * Get tokens for one or more entity type
84 *
85 * Output will be formatted either as a flat list,
86 * or pass sequential=1 to retrieve as a hierarchy formatted for select2.
87 *
88 * @param array $params
89 * Should contain an array of entities to retrieve tokens for.
90 *
91 * @return array
92 * @throws \API_Exception
93 */
94 function civicrm_api3_mailing_gettokens($params) {
95 $tokens = array();
96 foreach ((array) $params['entity'] as $ent) {
97 $func = lcfirst($ent) . 'Tokens';
98 if (!method_exists('CRM_Core_SelectValues', $func)) {
99 throw new API_Exception('Unknown token entity: ' . $ent);
100 }
101 $tokens = array_merge(CRM_Core_SelectValues::$func(), $tokens);
102 }
103 if (!empty($params['sequential'])) {
104 $tokens = CRM_Utils_Token::formatTokensForDisplay($tokens);
105 }
106 return civicrm_api3_create_success($tokens, $params, 'Mailing', 'gettokens');
107 }
108
109 /**
110 * Adjust Metadata for Create action.
111 *
112 * The metadata is used for setting defaults, documentation & validation.
113 *
114 * @param array $params
115 * Array of parameters determined by getfields.
116 */
117 function _civicrm_api3_mailing_gettokens_spec(&$params) {
118 $params['entity'] = array(
119 'api.default' => array('contact'),
120 'api.required' => 1,
121 'api.multiple' => 1,
122 'title' => 'Entity',
123 'options' => array(),
124 );
125 // Fetch a list of token functions and format to look like entity names
126 foreach (get_class_methods('CRM_Core_SelectValues') as $func) {
127 if (strpos($func, 'Tokens')) {
128 $ent = ucfirst(str_replace('Tokens', '', $func));
129 $params['entity']['options'][$ent] = $ent;
130 }
131 }
132 }
133
134 /**
135 * Adjust Metadata for Create action.
136 *
137 * The metadata is used for setting defaults, documentation & validation.
138 *
139 * @param array $params
140 * Array of parameters determined by getfields.
141 */
142 function _civicrm_api3_mailing_create_spec(&$params) {
143 $params['created_id']['api.default'] = 'user_contact_id';
144
145 $params['override_verp']['api.default'] = !CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'track_civimail_replies');
146 $params['visibility']['api.default'] = 'Public Pages';
147 $params['dedupe_email']['api.default'] = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'dedupe_email_default');
148
149 $params['forward_replies']['api.default'] = FALSE;
150 $params['auto_responder']['api.default'] = FALSE;
151 $params['open_tracking']['api.default'] = TRUE;
152 $params['url_tracking']['api.default'] = TRUE;
153
154 $params['header_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Header', '');
155 $params['footer_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Footer', '');
156 $params['optout_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('OptOut', '');
157 $params['reply_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Reply', '');
158 $params['resubscribe_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Resubscribe', '');
159 $params['unsubscribe_id']['api.default'] = CRM_Mailing_PseudoConstant::defaultComponent('Unsubscribe', '');
160 $params['mailing_type']['api.default'] = 'standalone';
161 $defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
162 foreach ($defaultAddress as $value) {
163 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
164 $params['from_email']['api.default'] = $match[2];
165 $params['from_name']['api.default'] = $match[1];
166 }
167 }
168 }
169
170 /**
171 * Adjust metadata for clone spec action.
172 *
173 * @param array $spec
174 */
175 function _civicrm_api3_mailing_clone_spec(&$spec) {
176 $mailingFields = CRM_Mailing_DAO_Mailing::fields();
177 $spec['id'] = $mailingFields['id'];
178 $spec['id']['api.required'] = 1;
179 }
180
181 /**
182 * Clone mailing.
183 *
184 * @param array $params
185 *
186 * @return array
187 * @throws \CiviCRM_API3_Exception
188 */
189 function civicrm_api3_mailing_clone($params) {
190 $BLACKLIST = array(
191 'id',
192 'is_completed',
193 'created_id',
194 'created_date',
195 'scheduled_id',
196 'scheduled_date',
197 'approver_id',
198 'approval_date',
199 'approval_status_id',
200 'approval_note',
201 'is_archived',
202 'hash',
203 'mailing_type',
204 );
205
206 $get = civicrm_api3('Mailing', 'getsingle', array('id' => $params['id']));
207
208 $newParams = array();
209 $newParams['debug'] = CRM_Utils_Array::value('debug', $params);
210 $newParams['groups']['include'] = array();
211 $newParams['groups']['exclude'] = array();
212 $newParams['mailings']['include'] = array();
213 $newParams['mailings']['exclude'] = array();
214 foreach ($get as $field => $value) {
215 if (!in_array($field, $BLACKLIST)) {
216 $newParams[$field] = $value;
217 }
218 }
219
220 $dao = new CRM_Mailing_DAO_MailingGroup();
221 $dao->mailing_id = $params['id'];
222 $dao->find();
223 while ($dao->fetch()) {
224 // CRM-11431; account for multi-lingual
225 $entity = (substr($dao->entity_table, 0, 15) == 'civicrm_mailing') ? 'mailings' : 'groups';
226 $newParams[$entity][strtolower($dao->group_type)][] = $dao->entity_id;
227 }
228
229 return civicrm_api3('Mailing', 'create', $newParams);
230 }
231
232 /**
233 * Handle a delete event.
234 *
235 * @param array $params
236 *
237 * @return array
238 * API Success Array
239 */
240 function civicrm_api3_mailing_delete($params) {
241 return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
242 }
243
244 /**
245 * Handle a get event.
246 *
247 * @param array $params
248 *
249 * @return array
250 */
251 function civicrm_api3_mailing_get($params) {
252 $result = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
253 return _civicrm_api3_mailing_get_formatResult($result);
254 }
255
256 /**
257 * Format definition.
258 *
259 * @param array $result
260 *
261 * @return array
262 * @throws \CRM_Core_Exception
263 */
264 function _civicrm_api3_mailing_get_formatResult($result) {
265 if (isset($result['values']) && is_array($result['values'])) {
266 foreach ($result['values'] as $key => $caseType) {
267 if (isset($result['values'][$key]['template_options']) && is_string($result['values'][$key]['template_options'])) {
268 $result['values'][$key]['template_options'] = json_decode($result['values'][$key]['template_options'], TRUE);
269 }
270 }
271 }
272 return $result;
273 }
274
275 /**
276 * Adjust metadata for mailing submit api function.
277 *
278 * @param array $spec
279 */
280 function _civicrm_api3_mailing_submit_spec(&$spec) {
281 $mailingFields = CRM_Mailing_DAO_Mailing::fields();
282 $spec['id'] = $mailingFields['id'];
283 $spec['scheduled_date'] = $mailingFields['scheduled_date'];
284 $spec['approval_date'] = $mailingFields['approval_date'];
285 $spec['approval_status_id'] = $mailingFields['approval_status_id'];
286 $spec['approval_note'] = $mailingFields['approval_note'];
287 // _skip_evil_bao_auto_recipients_: bool
288 }
289
290 /**
291 * Mailing submit.
292 *
293 * @param array $params
294 *
295 * @return array
296 * @throws API_Exception
297 */
298 function civicrm_api3_mailing_submit($params) {
299 civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_Mailing', array('id'));
300
301 if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
302 throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
303 }
304 if (!is_numeric(CRM_Core_Session::getLoggedInContactID())) {
305 throw new API_Exception("Failed to determine current user");
306 }
307
308 $updateParams = array();
309 $updateParams['id'] = $params['id'];
310
311 // Note: we'll pass along scheduling/approval fields, but they may get ignored
312 // if we don't have permission.
313 if (isset($params['scheduled_date'])) {
314 $updateParams['scheduled_date'] = $params['scheduled_date'];
315 $updateParams['scheduled_id'] = CRM_Core_Session::getLoggedInContactID();
316 }
317 if (isset($params['approval_date'])) {
318 $updateParams['approval_date'] = $params['approval_date'];
319 $updateParams['approver_id'] = CRM_Core_Session::getLoggedInContactID();
320 $updateParams['approval_status_id'] = CRM_Utils_Array::value('approval_status_id', $updateParams, CRM_Core_OptionGroup::getDefaultValue('mail_approval_status'));
321 }
322 if (isset($params['approval_note'])) {
323 $updateParams['approval_note'] = $params['approval_note'];
324 }
325 if (isset($params['_skip_evil_bao_auto_recipients_'])) {
326 $updateParams['_skip_evil_bao_auto_recipients_'] = $params['_skip_evil_bao_auto_recipients_'];
327 }
328
329 $updateParams['options']['reload'] = 1;
330 return civicrm_api3('Mailing', 'create', $updateParams);
331 }
332
333 /**
334 * Process a bounce event by passing through to the BAOs.
335 *
336 * @param array $params
337 *
338 * @throws API_Exception
339 * @return array
340 */
341 function civicrm_api3_mailing_event_bounce($params) {
342 $body = $params['body'];
343 unset($params['body']);
344
345 $params += CRM_Mailing_BAO_BouncePattern::match($body);
346
347 if (CRM_Mailing_Event_BAO_Bounce::create($params)) {
348 return civicrm_api3_create_success($params);
349 }
350 else {
351 throw new API_Exception(ts('Queue event could not be found'), 'no_queue_event');
352 }
353 }
354
355 /**
356 * Adjust Metadata for bounce_spec action.
357 *
358 * The metadata is used for setting defaults, documentation & validation.
359 *
360 * @param array $params
361 * Array of parameters determined by getfields.
362 */
363 function _civicrm_api3_mailing_event_bounce_spec(&$params) {
364 $params['job_id']['api.required'] = 1;
365 $params['job_id']['title'] = 'Job ID';
366 $params['event_queue_id']['api.required'] = 1;
367 $params['event_queue_id']['title'] = 'Event Queue ID';
368 $params['hash']['api.required'] = 1;
369 $params['hash']['title'] = 'Hash';
370 $params['body']['api.required'] = 1;
371 $params['body']['title'] = 'Body';
372 }
373
374 /**
375 * Handle a confirm event.
376 *
377 * @deprecated
378 *
379 * @param array $params
380 *
381 * @return array
382 */
383 function civicrm_api3_mailing_event_confirm($params) {
384 return civicrm_api('MailingEventConfirm', 'create', $params);
385 }
386
387 /**
388 * Declare deprecated functions.
389 *
390 * @deprecated api notice
391 * @return array
392 * Array of deprecated actions
393 */
394 function _civicrm_api3_mailing_deprecation() {
395 return array('event_confirm' => 'Mailing api "event_confirm" action is deprecated. Use the mailing_event_confirm api instead.');
396 }
397
398 /**
399 * Handle a reply event.
400 *
401 * @param array $params
402 *
403 * @return array
404 */
405 function civicrm_api3_mailing_event_reply($params) {
406 $job = $params['job_id'];
407 $queue = $params['event_queue_id'];
408 $hash = $params['hash'];
409 $replyto = $params['replyTo'];
410 $bodyTxt = CRM_Utils_Array::value('bodyTxt', $params);
411 $bodyHTML = CRM_Utils_Array::value('bodyHTML', $params);
412 $fullEmail = CRM_Utils_Array::value('fullEmail', $params);
413
414 $mailing = CRM_Mailing_Event_BAO_Reply::reply($job, $queue, $hash, $replyto);
415
416 if (empty($mailing)) {
417 return civicrm_api3_create_error('Queue event could not be found');
418 }
419
420 CRM_Mailing_Event_BAO_Reply::send($queue, $mailing, $bodyTxt, $replyto, $bodyHTML, $fullEmail);
421
422 return civicrm_api3_create_success($params);
423 }
424
425 /**
426 * Adjust Metadata for event_reply action.
427 *
428 * The metadata is used for setting defaults, documentation & validation.
429 *
430 * @param array $params
431 * Array of parameters determined by getfields.
432 */
433 function _civicrm_api3_mailing_event_reply_spec(&$params) {
434 $params['job_id']['api.required'] = 1;
435 $params['job_id']['title'] = 'Job ID';
436 $params['event_queue_id']['api.required'] = 1;
437 $params['event_queue_id']['title'] = 'Event Queue ID';
438 $params['hash']['api.required'] = 1;
439 $params['hash']['title'] = 'Hash';
440 $params['replyTo']['api.required'] = 0;
441 $params['replyTo']['title'] = 'Reply To';//doesn't really explain adequately
442 }
443
444 /**
445 * Handle a forward event.
446 *
447 * @param array $params
448 *
449 * @return array
450 */
451 function civicrm_api3_mailing_event_forward($params) {
452 $job = $params['job_id'];
453 $queue = $params['event_queue_id'];
454 $hash = $params['hash'];
455 $email = $params['email'];
456 $fromEmail = CRM_Utils_Array::value('fromEmail', $params);
457 $params = CRM_Utils_Array::value('params', $params);
458
459 $forward = CRM_Mailing_Event_BAO_Forward::forward($job, $queue, $hash, $email, $fromEmail, $params);
460
461 if ($forward) {
462 return civicrm_api3_create_success($params);
463 }
464
465 return civicrm_api3_create_error('Queue event could not be found');
466 }
467
468 /**
469 * Adjust Metadata for event_forward action.
470 *
471 * The metadata is used for setting defaults, documentation & validation.
472 *
473 * @param array $params
474 * Array of parameters determined by getfields.
475 */
476 function _civicrm_api3_mailing_event_forward_spec(&$params) {
477 $params['job_id']['api.required'] = 1;
478 $params['job_id']['title'] = 'Job ID';
479 $params['event_queue_id']['api.required'] = 1;
480 $params['event_queue_id']['title'] = 'Event Queue ID';
481 $params['hash']['api.required'] = 1;
482 $params['hash']['title'] = 'Hash';
483 $params['email']['api.required'] = 1;
484 $params['email']['title'] = 'Forwarded to Email';
485 }
486
487 /**
488 * Handle a click event.
489 *
490 * @param array $params
491 *
492 * @return array
493 */
494 function civicrm_api3_mailing_event_click($params) {
495 civicrm_api3_verify_mandatory($params,
496 'CRM_Mailing_Event_DAO_TrackableURLOpen',
497 array('event_queue_id', 'url_id'),
498 FALSE
499 );
500
501 $url_id = $params['url_id'];
502 $queue = $params['event_queue_id'];
503
504 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($queue, $url_id);
505
506 $values = array();
507 $values['url'] = $url;
508 $values['is_error'] = 0;
509
510 return civicrm_api3_create_success($values);
511 }
512
513 /**
514 * Handle an open event.
515 *
516 * @param array $params
517 *
518 * @return array
519 */
520 function civicrm_api3_mailing_event_open($params) {
521
522 civicrm_api3_verify_mandatory($params,
523 'CRM_Mailing_Event_DAO_Opened',
524 array('event_queue_id'),
525 FALSE
526 );
527
528 $queue = $params['event_queue_id'];
529 $success = CRM_Mailing_Event_BAO_Opened::open($queue);
530
531 if (!$success) {
532 return civicrm_api3_create_error('mailing open event failed');
533 }
534
535 return civicrm_api3_create_success($params);
536 }
537
538 /**
539 * Preview mailing.
540 *
541 * @param array $params
542 * Array per getfields metadata.
543 *
544 * @return array
545 * @throws \API_Exception
546 */
547 function civicrm_api3_mailing_preview($params) {
548 civicrm_api3_verify_mandatory($params,
549 'CRM_Mailing_DAO_Mailing',
550 array('id'),
551 FALSE
552 );
553
554 $fromEmail = NULL;
555 if (!empty($params['from_email'])) {
556 $fromEmail = $params['from_email'];
557 }
558
559 $session = CRM_Core_Session::singleton();
560 $mailing = new CRM_Mailing_BAO_Mailing();
561 $mailing->id = $params['id'];
562 $mailing->find(TRUE);
563
564 CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
565
566 // get and format attachments
567 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
568
569 $returnProperties = $mailing->getReturnProperties();
570 $contactID = CRM_Utils_Array::value('contact_id', $params);
571 if (!$contactID) {
572 $contactID = $session->get('userID');
573 }
574 $mailingParams = array('contact_id' => $contactID);
575
576 $details = CRM_Utils_Token::getTokenDetails($mailingParams, $returnProperties, TRUE, TRUE, NULL, $mailing->getFlattenedTokens());
577
578 $mime = $mailing->compose(NULL, NULL, NULL, $session->get('userID'), $fromEmail, $fromEmail,
579 TRUE, $details[0][$contactID], $attachments
580 );
581
582 return civicrm_api3_create_success(array(
583 'id' => $params['id'],
584 'contact_id' => $contactID,
585 'subject' => $mime->_headers['Subject'],
586 'body_html' => $mime->getHTMLBody(),
587 'body_text' => $mime->getTXTBody(),
588 ));
589 }
590
591 /**
592 * Adjust metadata for send test function.
593 *
594 * @param array $spec
595 */
596 function _civicrm_api3_mailing_send_test_spec(&$spec) {
597 $spec['test_group']['title'] = 'Test Group ID';
598 $spec['test_email']['title'] = 'Test Email Address';
599 }
600
601 /**
602 * Send test mailing.
603 *
604 * @param array $params
605 *
606 * @return array
607 * @throws \API_Exception
608 * @throws \CiviCRM_API3_Exception
609 */
610 function civicrm_api3_mailing_send_test($params) {
611 if (!array_key_exists('test_group', $params) && !array_key_exists('test_email', $params)) {
612 throw new API_Exception("Mandatory key(s) missing from params array: test_group and/or test_email field are required");
613 }
614 civicrm_api3_verify_mandatory($params,
615 'CRM_Mailing_DAO_MailingJob',
616 array('mailing_id'),
617 FALSE
618 );
619
620 $testEmailParams = _civicrm_api3_generic_replace_base_params($params);
621 $testEmailParams['is_test'] = 1;
622 $testEmailParams['status'] = 'Scheduled';
623 $testEmailParams['scheduled_date'] = CRM_Utils_Date::processDate(date('Y-m-d'), date('H:i:s'));
624 $job = civicrm_api3('MailingJob', 'create', $testEmailParams);
625 $testEmailParams['job_id'] = $job['id'];
626 $testEmailParams['emails'] = array_key_exists('test_email', $testEmailParams) ? explode(',', $testEmailParams['test_email']) : NULL;
627 if (!empty($params['test_email'])) {
628 $query = CRM_Utils_SQL_Select::from('civicrm_email e')
629 ->select(array('e.id', 'e.contact_id', 'e.email'))
630 ->join('c', 'INNER JOIN civicrm_contact c ON e.contact_id = c.id')
631 ->where('e.email IN (@emails)', array('@emails' => $testEmailParams['emails']))
632 ->where('e.on_hold = 0')
633 ->where('c.is_opt_out = 0')
634 ->where('c.do_not_email = 0')
635 ->where('c.is_deceased = 0')
636 ->where('c.is_deleted = 0')
637 ->groupBy('e.id')
638 ->orderBy(array('e.is_bulkmail DESC', 'e.is_primary DESC'))
639 ->toSQL();
640 $dao = CRM_Core_DAO::executeQuery($query);
641 $emailDetail = array();
642 // fetch contact_id and email id for all existing emails
643 while ($dao->fetch()) {
644 $emailDetail[$dao->email] = array(
645 'contact_id' => $dao->contact_id,
646 'email_id' => $dao->id,
647 );
648 }
649 $dao->free();
650 foreach ($testEmailParams['emails'] as $key => $email) {
651 $email = trim($email);
652 $contactId = $emailId = NULL;
653 if (array_key_exists($email, $emailDetail)) {
654 $emailId = $emailDetail[$email]['email_id'];
655 $contactId = $emailDetail[$email]['contact_id'];
656 }
657 if (!$contactId) {
658 //create new contact.
659 $contact = civicrm_api3('Contact', 'create',
660 array(
661 'contact_type' => 'Individual',
662 'email' => $email,
663 'api.Email.get' => array('return' => 'id'),
664 )
665 );
666 $contactId = $contact['id'];
667 $emailId = $contact['values'][$contactId]['api.Email.get']['id'];
668 }
669 civicrm_api3('MailingEventQueue', 'create',
670 array(
671 'job_id' => $job['id'],
672 'email_id' => $emailId,
673 'contact_id' => $contactId,
674 )
675 );
676 }
677 }
678
679 $isComplete = FALSE;
680 $config = CRM_Core_Config::singleton();
681 $mailerJobSize = Civi::settings()->get('mailerJobSize');
682 while (!$isComplete) {
683 // Q: In CRM_Mailing_BAO_Mailing::processQueue(), the three runJobs*()
684 // functions are all called. Why does Mailing.send_test only call one?
685 // CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, NULL);
686 $isComplete = CRM_Mailing_BAO_MailingJob::runJobs($testEmailParams);
687 // CRM_Mailing_BAO_MailingJob::runJobs_post(NULL);
688 }
689
690 //return delivered mail info
691 $mailDelivered = CRM_Mailing_Event_BAO_Delivered::getRows($params['mailing_id'], $job['id'], TRUE, NULL, NULL, NULL, TRUE);
692
693 return civicrm_api3_create_success($mailDelivered);
694 }
695
696 /**
697 * Adjust Metadata for send_mail action.
698 *
699 * The metadata is used for setting defaults, documentation & validation.
700 *
701 * @param array $params
702 * Array of parameters determined by getfields.
703 */
704 function _civicrm_api3_mailing_stats_spec(&$params) {
705 $params['date']['api.default'] = 'now';
706 $params['date']['title'] = 'Date';
707 $params['is_distinct']['api.default'] = FALSE;
708 $params['is_distinct']['title'] = 'Is Distinct';
709 }
710
711 /**
712 * Function which needs to be explained.
713 *
714 * @param array $params
715 *
716 * @return array
717 * @throws \API_Exception
718 */
719 function civicrm_api3_mailing_stats($params) {
720 civicrm_api3_verify_mandatory($params,
721 'CRM_Mailing_DAO_MailingJob',
722 array('mailing_id'),
723 FALSE
724 );
725
726 if ($params['date'] == 'now') {
727 $params['date'] = date('YmdHis');
728 }
729 else {
730 $params['date'] = CRM_Utils_Date::processDate($params['date'] . ' ' . $params['date_time']);
731 }
732
733 $stats[$params['mailing_id']] = array();
734 if (empty($params['job_id'])) {
735 $params['job_id'] = NULL;
736 }
737 foreach (array('Delivered', 'Bounces', 'Unsubscribers', 'Unique Clicks', 'Opened') as $detail) {
738 switch ($detail) {
739 case 'Delivered':
740 $stats[$params['mailing_id']] += array(
741 $detail => CRM_Mailing_Event_BAO_Delivered::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], $params['date']),
742 );
743 break;
744
745 case 'Bounces':
746 $stats[$params['mailing_id']] += array(
747 $detail => CRM_Mailing_Event_BAO_Bounce::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], $params['date']),
748 );
749 break;
750
751 case 'Unsubscribers':
752 $stats[$params['mailing_id']] += array(
753 $detail => CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], NULL, $params['date']),
754 );
755 break;
756
757 case 'Unique Clicks':
758 $stats[$params['mailing_id']] += array(
759 $detail => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], NULL, $params['date']),
760 );
761 break;
762
763 case 'Opened':
764 $stats[$params['mailing_id']] += array(
765 $detail => CRM_Mailing_Event_BAO_Opened::getTotalCount($params['mailing_id'], $params['job_id'], (bool) $params['is_distinct'], $params['date']),
766 );
767 break;
768 }
769 }
770 return civicrm_api3_create_success($stats);
771 }
772
773 /**
774 * Fix the reset dates on the email record based on when a mail was last delivered.
775 *
776 * We only consider mailings that were completed and finished in the last 3 to 7 days
777 * Both the min and max days can be set via the params
778 *
779 * @param array $params
780 *
781 * @return array
782 */
783 function civicrm_api3_mailing_update_email_resetdate($params) {
784 CRM_Mailing_Event_BAO_Delivered::updateEmailResetDate(
785 CRM_Utils_Array::value('minDays', $params, 3),
786 CRM_Utils_Array::value('maxDays', $params, 3)
787 );
788 return civicrm_api3_create_success();
789 }