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