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