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