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