Merge pull request #4871 from eileenmcnaughton/CRM-15795
[civicrm-core.git] / api / v3 / Mailing.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.6 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27 */
28
29 /**
30 *
31 * APIv3 functions for registering/processing mailing events.
32 *
33 * @package CiviCRM_APIv3
34 * @subpackage API_Mailing
35 * @copyright CiviCRM LLC (c) 2004-2014
36 * $Id$
37 *
38 */
39
40 /**
41 * Files required for this package
42 */
43
44 /**
45 * Handle a create event.
46 *
47 * @param array $params
48 * @param array $ids
49 *
50 * @return array API Success Array
51 */
52 function civicrm_api3_mailing_create($params, $ids = array()) {
53 if (CRM_Mailing_Info::workflowEnabled()) {
54 if (!CRM_Core_Permission::check('create mailings')) {
55 throw new \Civi\API\Exception\UnauthorizedException("This system uses advanced CiviMail workflows which require additional permissions");
56 }
57 if (!CRM_Core_Permission::check('schedule mailings')) {
58 unset($params['scheduled_date']);
59 unset($params['scheduled_id']);
60 }
61 if (!CRM_Core_Permission::check('approve mailings')) {
62 unset($params['approval_date']);
63 unset($params['approver_id']);
64 unset($params['approval_status_id']);
65 unset($params['approval_note']);
66 }
67 }
68 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params);
69 }
70
71 function civicrm_api3_mailing_get_token($params) {
72 if (!array_key_exists("usage", $params)) {
73 throw new API_Exception('Mandatory keys missing from params array: entity');
74 }
75
76 $tokens = CRM_Core_SelectValues::contactTokens();
77 switch ($params['usage']) {
78 case 'Mailing' :
79 $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
80 break;
81 case 'ScheduleEventReminder' :
82 $tokens = array_merge(CRM_Core_SelectValues::activityTokens(), $tokens);
83 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
84 $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens);
85 break;
86 case 'ManageEventScheduleReminder' :
87 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
88 break;
89 }
90
91 return CRM_Utils_Token::formatTokensForDisplay($tokens);
92 }
93
94 /**
95 * Adjust Metadata for Create action
96 *
97 * The metadata is used for setting defaults, documentation & validation
98 * @param array $params
99 * Array or parameters determined by getfields.
100 */
101 function _civicrm_api3_mailing_create_spec(&$params) {
102 $params['name']['api.required'] = 1;
103 $params['subject']['api.required'] = 1;
104 $params['created_id']['api.required'] = 1;
105 $params['created_id']['api.default'] = 'user_contact_id';
106 $params['api.mailing_job.create']['api.default'] = 1;
107 $params['api.mailing_job.create']['title'] = 'Schedule Mailing?';
108 }
109
110 /**
111 * Handle a delete event.
112 *
113 * @param array $params
114 * @param array $ids
115 *
116 * @return array API Success Array
117 */
118 function civicrm_api3_mailing_delete($params, $ids = array()) {
119 return _civicrm_api3_basic_delete(_civicrm_api3_get_BAO(__FUNCTION__), $params);
120 }
121
122 /**
123 * Handle a get event.
124 *
125 * @param array $params
126 * @return array
127 */
128 function civicrm_api3_mailing_get($params) {
129 return _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
130 }
131
132 function _civicrm_api3_mailing_submit_spec(&$spec) {
133 $mailingFields = CRM_Mailing_DAO_Mailing::fields();
134 $spec['id'] = $mailingFields['id'];
135 $spec['scheduled_date'] = $mailingFields['scheduled_date'];
136 $spec['approval_date'] = $mailingFields['approval_date'];
137 $spec['approval_status_id'] = $mailingFields['approval_status_id'];
138 $spec['approval_note'] = $mailingFields['approval_note'];
139 // _skip_evil_bao_auto_recipients_: bool
140 }
141
142 /**
143 * @param array $params
144 * @return array
145 * @throws API_Exception
146 */
147 function civicrm_api3_mailing_submit($params) {
148 civicrm_api3_verify_mandatory($params, 'CRM_Mailing_DAO_Mailing', array('id'));
149
150 if (!isset($params['scheduled_date']) && !isset($updateParams['approval_date'])) {
151 throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
152 }
153 if (!is_numeric(CRM_Core_Session::getLoggedInContactID())) {
154 throw new API_Exception("Failed to determine current user");
155 }
156
157 $updateParams = array();
158 $updateParams['id'] = $params['id'];
159
160 // the BAO will autocreate the job
161 $updateParams['api.mailing_job.create'] = 0; // note: exact match to API default
162
163 // note: we'll pass along scheduling/approval fields, but they may get ignored
164 // if we don't have permission
165 if (isset($params['scheduled_date'])) {
166 $updateParams['scheduled_date'] = $params['scheduled_date'];
167 $updateParams['scheduled_id'] = CRM_Core_Session::getLoggedInContactID();
168 }
169 if (isset($params['approval_date'])) {
170 $updateParams['approval_date'] = $params['approval_date'];
171 $updateParams['approver_id'] = CRM_Core_Session::getLoggedInContactID();
172 $updateParams['approval_status_id'] = CRM_Utils_Array::value('approval_status_id', $updateParams, CRM_Core_OptionGroup::getDefaultValue('mail_approval_status'));
173 }
174 if (isset($params['approval_note'])) {
175 $updateParams['approval_note'] = $params['approval_note'];
176 }
177 if (isset($params['_skip_evil_bao_auto_recipients_'])) {
178 $updateParams['_skip_evil_bao_auto_recipients_'] = $params['_skip_evil_bao_auto_recipients_'];
179 }
180
181 $updateParams['options']['reload'] = 1;
182 return civicrm_api3('Mailing', 'create', $updateParams);
183 }
184
185 /**
186 * Process a bounce event by passing through to the BAOs.
187 *
188 * @param array $params
189 *
190 * @throws API_Exception
191 * @return array
192 */
193 function civicrm_api3_mailing_event_bounce($params) {
194 $body = $params['body'];
195 unset($params['body']);
196
197 $params += CRM_Mailing_BAO_BouncePattern::match($body);
198
199 if (CRM_Mailing_Event_BAO_Bounce::create($params)) {
200 return civicrm_api3_create_success($params);
201 }
202 else {
203 throw new API_Exception(ts('Queue event could not be found'),'no_queue_event
204 ');
205 }
206 }
207
208 /**
209 * Adjust Metadata for bounce_spec action
210 *
211 * The metadata is used for setting defaults, documentation & validation
212 * @param array $params
213 * Array or parameters determined by getfields.
214 */
215 function _civicrm_api3_mailing_event_bounce_spec(&$params) {
216 $params['job_id']['api.required'] = 1;
217 $params['job_id']['title'] = 'Job ID';
218 $params['event_queue_id']['api.required'] = 1;
219 $params['event_queue_id']['title'] = 'Event Queue ID';
220 $params['hash']['api.required'] = 1;
221 $params['hash']['title'] = 'Hash';
222 $params['body']['api.required'] = 1;
223 $params['body']['title'] = 'Body';
224 }
225
226 /**
227 * Handle a confirm event
228 * @deprecated
229 *
230 * @param array $params
231 *
232 * @return array
233 */
234 function civicrm_api3_mailing_event_confirm($params) {
235 return civicrm_api('mailing_event_confirm', 'create', $params);
236 }
237
238 /**
239 * @deprecated api notice
240 * @return array of deprecated actions
241 */
242 function _civicrm_api3_mailing_deprecation() {
243 return array('event_confirm' => 'Mailing api "event_confirm" action is deprecated. Use the mailing_event_confirm api instead.');
244 }
245
246 /**
247 * Handle a reply event
248 *
249 * @param array $params
250 *
251 * @return array
252 */
253 function civicrm_api3_mailing_event_reply($params) {
254 $job = $params['job_id'];
255 $queue = $params['event_queue_id'];
256 $hash = $params['hash'];
257 $replyto = $params['replyTo'];
258 $bodyTxt = CRM_Utils_Array::value('bodyTxt', $params);
259 $bodyHTML = CRM_Utils_Array::value('bodyHTML', $params);
260 $fullEmail = CRM_Utils_Array::value('fullEmail', $params);
261
262 $mailing = CRM_Mailing_Event_BAO_Reply::reply($job, $queue, $hash, $replyto);
263
264 if (empty($mailing)) {
265 return civicrm_api3_create_error('Queue event could not be found');
266 }
267
268 CRM_Mailing_Event_BAO_Reply::send($queue, $mailing, $bodyTxt, $replyto, $bodyHTML, $fullEmail);
269
270 return civicrm_api3_create_success($params);
271 }
272
273 /**
274 * Adjust Metadata for event_reply action
275 *
276 * The metadata is used for setting defaults, documentation & validation
277 * @param array $params
278 * Array or parameters determined by getfields.
279 */
280 function _civicrm_api3_mailing_event_reply_spec(&$params) {
281 $params['job_id']['api.required'] = 1;
282 $params['job_id']['title'] = 'Job ID';
283 $params['event_queue_id']['api.required'] = 1;
284 $params['event_queue_id']['title'] = 'Event Queue ID';
285 $params['hash']['api.required'] = 1;
286 $params['hash']['title'] = 'Hash';
287 $params['replyTo']['api.required'] = 0;
288 $params['replyTo']['title'] = 'Reply To';//doesn't really explain adequately
289 }
290
291 /**
292 * Handle a forward event
293 *
294 * @param array $params
295 *
296 * @return array
297 */
298 function civicrm_api3_mailing_event_forward($params) {
299 $job = $params['job_id'];
300 $queue = $params['event_queue_id'];
301 $hash = $params['hash'];
302 $email = $params['email'];
303 $fromEmail = CRM_Utils_Array::value('fromEmail', $params);
304 $params = CRM_Utils_Array::value('params', $params);
305
306 $forward = CRM_Mailing_Event_BAO_Forward::forward($job, $queue, $hash, $email, $fromEmail, $params);
307
308 if ($forward) {
309 return civicrm_api3_create_success($params);
310 }
311
312 return civicrm_api3_create_error('Queue event could not be found');
313 }
314
315 /**
316 * Adjust Metadata for event_forward action
317 *
318 * The metadata is used for setting defaults, documentation & validation
319 * @param array $params
320 * Array or parameters determined by getfields.
321 */
322 function _civicrm_api3_mailing_event_forward_spec(&$params) {
323 $params['job_id']['api.required'] = 1;
324 $params['job_id']['title'] = 'Job ID';
325 $params['event_queue_id']['api.required'] = 1;
326 $params['event_queue_id']['title'] = 'Event Queue ID';
327 $params['hash']['api.required'] = 1;
328 $params['hash']['title'] = 'Hash';
329 $params['email']['api.required'] = 1;
330 $params['email']['title'] = 'Forwarded to Email';
331 }
332
333 /**
334 * Handle a click event
335 *
336 * @param array $params
337 *
338 * @return array
339 */
340 function civicrm_api3_mailing_event_click($params) {
341 civicrm_api3_verify_mandatory($params,
342 'CRM_Mailing_Event_DAO_TrackableURLOpen',
343 array('event_queue_id', 'url_id'),
344 FALSE
345 );
346
347 $url_id = $params['url_id'];
348 $queue = $params['event_queue_id'];
349
350 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($queue, $url_id);
351
352 $values = array();
353 $values['url'] = $url;
354 $values['is_error'] = 0;
355
356 return civicrm_api3_create_success($values);
357 }
358
359 /**
360 * Handle an open event
361 *
362 * @param array $params
363 *
364 * @return array
365 */
366 function civicrm_api3_mailing_event_open($params) {
367
368 civicrm_api3_verify_mandatory($params,
369 'CRM_Mailing_Event_DAO_Opened',
370 array('event_queue_id'),
371 FALSE
372 );
373
374 $queue = $params['event_queue_id'];
375 $success = CRM_Mailing_Event_BAO_Opened::open($queue);
376
377 if (!$success) {
378 return civicrm_api3_create_error('mailing open event failed');
379 }
380
381 return civicrm_api3_create_success($params);
382 }
383
384 function civicrm_api3_mailing_preview($params) {
385 civicrm_api3_verify_mandatory($params,
386 'CRM_Mailing_DAO_Mailing',
387 array('id'),
388 FALSE
389 );
390
391 $fromEmail = NULL;
392 if (!empty($params['from_email'])) {
393 $fromEmail = $params['from_email'];
394 }
395
396 $session = CRM_Core_Session::singleton();
397 $mailing = new CRM_Mailing_BAO_Mailing();
398 $mailing->id = $params['id'];
399 $mailing->find(TRUE);
400
401 CRM_Mailing_BAO_Mailing::tokenReplace($mailing);
402
403 // get and format attachments
404 $attachments = CRM_Core_BAO_File::getEntityFile('civicrm_mailing', $mailing->id);
405
406 $returnProperties = $mailing->getReturnProperties();
407 $contactID = CRM_Utils_Array::value('contact_id', $params);
408 if (!$contactID) {
409 $contactID = $session->get('userID');
410 }
411 $mailingParams = array('contact_id' => $contactID);
412
413 $details = CRM_Utils_Token::getTokenDetails($mailingParams, $returnProperties, TRUE, TRUE, NULL, $mailing->getFlattenedTokens());
414
415 $mime = &$mailing->compose(NULL, NULL, NULL, $session->get('userID'), $fromEmail, $fromEmail,
416 TRUE, $details[0][$contactID], $attachments
417 );
418
419 return civicrm_api3_create_success(array(
420 'id' => $params['id'],
421 'contact_id' => $contactID,
422 'subject' => $mime->_headers['Subject'],
423 'body_html' => $mime->getHTMLBody(),
424 'body_text' => $mime->getTXTBody(),
425 ));
426 }
427
428 function _civicrm_api3_mailing_send_test_spec(&$spec) {
429 $spec['test_group']['title'] = 'Test Group ID';
430 $spec['test_email']['title'] = 'Test Email Address';
431 }
432
433 function civicrm_api3_mailing_send_test($params) {
434 if (!array_key_exists('test_group', $params) && !array_key_exists('test_email', $params)) {
435 throw new API_Exception("Mandatory key(s) missing from params array: test_group and/or test_email field are required");
436 }
437 civicrm_api3_verify_mandatory($params,
438 'CRM_Mailing_DAO_MailingJob',
439 array('mailing_id'),
440 FALSE
441 );
442
443 $testEmailParams = _civicrm_api3_generic_replace_base_params($params);
444 $testEmailParams['is_test'] = 1;
445 $job = civicrm_api3('MailingJob', 'create', $testEmailParams);
446 $testEmailParams['job_id'] = $job['id'];
447 $testEmailParams['emails'] = explode(',', $testEmailParams['test_email']);
448 if (!empty($params['test_email'])) {
449 $query = CRM_Utils_SQL_Select::from('civicrm_email e')
450 ->select(array('e.id', 'e.contact_id', 'e.email'))
451 ->join('c', 'INNER JOIN civicrm_contact c ON e.contact_id = c.id')
452 ->where('e.email IN (@emails)', array('@emails' => $testEmailParams['emails']))
453 ->where('e.on_hold = 0')
454 ->where('c.is_opt_out = 0')
455 ->where('c.do_not_email = 0')
456 ->where('c.is_deceased = 0')
457 ->groupBy('e.id')
458 ->orderBy(array('e.is_bulkmail DESC', 'e.is_primary DESC'))
459 ->toSQL();
460 $dao = CRM_Core_DAO::executeQuery($query);
461 $emailDetail = array();
462 // fetch contact_id and email id for all existing emails
463 while ($dao->fetch()) {
464 $emailDetail[$dao->email] = array(
465 'contact_id' => $dao->contact_id,
466 'email_id' => $dao->id,
467 );
468 }
469 $dao->free();
470 foreach ($testEmailParams['emails'] as $key => $email) {
471 $email = trim($email);
472 $contactId = $emailId = NULL;
473 if (array_key_exists($email, $emailDetail)) {
474 $emailId = $emailDetail[$email]['email_id'];
475 $contactId = $emailDetail[$email]['contact_id'];
476 }
477 if (!$contactId) {
478 //create new contact.
479 $contact = civicrm_api3('Contact', 'create',
480 array('contact_type' => 'Individual',
481 'email' => $email,
482 'api.Email.get' => array('return' => 'id')
483 )
484 );
485 $contactId = $contact['id'];
486 $emailId = $contact['values'][$contactId]['api.Email.get']['id'];
487 }
488 civicrm_api3('MailingEventQueue', 'create',
489 array('job_id' => $job['id'],
490 'email_id' => $emailId,
491 'contact_id' => $contactId
492 )
493 );
494 }
495 }
496
497 $isComplete = FALSE;
498 $config = CRM_Core_Config::singleton();
499 $mailerJobSize = (property_exists($config, 'mailerJobSize')) ? $config->mailerJobSize : NULL;
500 while (!$isComplete) {
501 // Q: In CRM_Mailing_BAO_Mailing::processQueue(), the three runJobs*()
502 // functions are all called. Why does Mailing.send_test only call one?
503 // CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, NULL);
504 $isComplete = CRM_Mailing_BAO_MailingJob::runJobs($testEmailParams);
505 // CRM_Mailing_BAO_MailingJob::runJobs_post(NULL);
506 }
507
508 //return delivered mail info
509 $mailDelivered = CRM_Mailing_Event_BAO_Delivered::getRows($params['mailing_id'], $job['id'], TRUE, NULL, NULL, NULL, TRUE);
510
511 return civicrm_api3_create_success($mailDelivered);
512 }
513
514 /**
515 * Adjust Metadata for send_mail action
516 *
517 * The metadata is used for setting defaults, documentation & validation
518 * @param array $params
519 * Array or parameters determined by getfields.
520 */
521 function _civicrm_api3_mailing_stats_spec(&$params) {
522 $params['date']['api.default'] = 'now';
523 $params['date']['title'] = 'Date';
524 }
525
526 function civicrm_api3_mailing_stats($params) {
527 civicrm_api3_verify_mandatory($params,
528 'CRM_Mailing_DAO_MailingJob',
529 array('mailing_id'),
530 FALSE
531 );
532
533 if ($params['date'] == 'now') {
534 $params['date'] = date('YmdHis');
535 }
536 else {
537 $params['date'] = CRM_Utils_Date::processDate($params['date'] . ' ' . $params['date_time']);
538 }
539
540 $stats[$params['mailing_id']] = array();
541 if (empty($params['job_id'])) {
542 $params['job_id'] = NULL;
543 }
544 foreach (array('Delivered', 'Bounces', 'Unsubscribers', 'Unique Clicks', 'Opened') as $detail) {
545 switch ($detail) {
546 case 'Delivered':
547 $stats[$params['mailing_id']] += array(
548 $detail => CRM_Mailing_Event_BAO_Delivered::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date'])
549 );
550 break;
551 case 'Bounces':
552 $stats[$params['mailing_id']] += array(
553 $detail => CRM_Mailing_Event_BAO_Bounce::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date'])
554 );
555 break;
556 case 'Unsubscribers':
557 $stats[$params['mailing_id']] += array(
558 $detail => CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date'])
559 );
560 break;
561 case 'Unique Clicks':
562 $stats[$params['mailing_id']] += array(
563 $detail => CRM_Mailing_Event_BAO_TrackableURLOpen::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, NULL, $params['date'])
564 );
565 break;
566 case 'Opened':
567 $stats[$params['mailing_id']] += array(
568 $detail => CRM_Mailing_Event_BAO_Opened::getTotalCount($params['mailing_id'], $params['job_id'], FALSE, $params['date'])
569 );
570 break;
571 }
572 }
573 return civicrm_api3_create_success($stats);
574 }
575
576 /**
577 * Fix the reset dates on the email record based on when a mail was last delivered
578 * We only consider mailings that were completed and finished in the last 3 to 7 days
579 * Both the min and max days can be set via the params
580 */
581 function civicrm_api3_mailing_update_email_resetdate($params) {
582 CRM_Mailing_Event_BAO_Delivered::updateEmailResetDate(
583 CRM_Utils_Array::value('minDays', $params, 3),
584 CRM_Utils_Array::value('maxDays', $params, 3)
585 );
586 return civicrm_api3_create_success();
587 }