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