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