3 * File for the TestMailing class
9 * This file is part of CiviCRM
11 * CiviCRM is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Affero General Public License
13 * as published by the Free Software Foundation; either version 3 of
14 * the License, or (at your option) any later version.
16 * CiviCRM is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Affero General Public License for more details.
21 * You should have received a copy of the GNU Affero General Public
22 * License along with this program. If not, see
23 * <http://www.gnu.org/licenses/>.
28 * Test APIv3 civicrm_mailing_* functions
33 class api_v3_MailingTest
extends CiviUnitTestCase
{
36 protected $_apiversion = 3;
37 protected $_params = array();
38 protected $_entity = 'Mailing';
39 protected $_contactID;
42 * APIv3 result from creating an example footer
47 public function setUp() {
49 $this->useTransaction();
50 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0; // DGW
51 $this->_contactID
= $this->individualCreate();
52 $this->_groupID
= $this->groupCreate();
53 $this->_email
= 'test@test.test';
54 $this->_params
= array(
55 'subject' => 'Hello {contact.display_name}',
56 'body_text' => "This is {contact.display_name}.\nhttps://civicrm.org\n{domain.address}{action.optOutUrl}",
57 'body_html' => "<p>This is {contact.display_name}.</p><p><a href='https://civicrm.org/'>CiviCRM.org</a></p><p>{domain.address}{action.optOutUrl}</p>",
58 'name' => 'mailing name',
59 'created_id' => $this->_contactID
,
64 $this->footer
= civicrm_api3('MailingComponent', 'create', array(
65 'name' => 'test domain footer',
66 'component_type' => 'footer',
67 'body_html' => '<p>From {domain.address}. To opt out, go to {action.optOutUrl}.</p>',
68 'body_text' => 'From {domain.address}. To opt out, go to {action.optOutUrl}.',
72 public function tearDown() {
73 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0; // DGW
78 * Test civicrm_mailing_create.
80 public function testMailerCreateSuccess() {
81 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
82 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
83 $this->assertEquals(1, $jobs['count']);
84 unset($this->_params
['created_id']); // return isn't working on this in getAndCheck so lets not check it for now
85 $this->getAndCheck($this->_params
, $result['id'], 'mailing');
89 * Tes that the parameter _skip_evil_bao_auto_schedule_ is respected & prevents jobs being created.
91 public function testSkipAutoSchedule() {
92 $this->callAPISuccess('Mailing', 'create', array_merge($this->_params
, [
93 '_skip_evil_bao_auto_schedule_' => TRUE,
94 'scheduled_date' => 'now'
96 $this->callAPISuccessGetCount('Mailing', [], 1);
97 $this->callAPISuccessGetCount('MailingJob', [], 0);
101 * Create a completed mailing (e.g when importing from a provider).
103 public function testMailerCreateCompleted() {
104 $this->_params
['body_html'] = 'I am completed so it does not matter if there is an opt out link since I have already been sent by another system';
105 $this->_params
['is_completed'] = 1;
106 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
107 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
108 $this->assertEquals(1, $jobs['count']);
109 $this->assertEquals('Complete', $jobs['values'][$jobs['id']]['status']);
110 unset($this->_params
['created_id']); // return isn't working on this in getAndCheck so lets not check it for now
111 $this->getAndCheck($this->_params
, $result['id'], 'mailing');
115 * Per CRM-20316 the mailing should still create without created_id (not mandatory).
117 public function testMailerCreateSuccessNoCreatedID() {
118 unset($this->_params
['created_id']);
119 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
120 $this->getAndCheck($this->_params
, $result['id'], 'mailing');
126 public function testTemplateTypeOptions() {
127 $types = $this->callAPISuccess('Mailing', 'getoptions', array('field' => 'template_type'));
128 $this->assertTrue(isset($types['values']['traditional']));
132 * The `template_options` field should be treated a JSON object.
134 * This test will create, read, and update the field.
136 public function testMailerCreateTemplateOptions() {
137 // 1. Create mailing with template_options.
138 $params = $this->_params
;
139 $params['template_options'] = json_encode(array('foo' => 'bar_1'));
140 $createResult = $this->callAPISuccess('mailing', 'create', $params);
141 $id = $createResult['id'];
142 $this->assertDBQuery('{"foo":"bar_1"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
143 1 => array($id, 'Int'),
145 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
147 // 2. Get mailing with template_options.
148 $getResult = $this->callAPISuccess('mailing', 'get', array(
151 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
152 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', array(
154 'return' => 'template_options',
156 $this->assertEquals('bar_1', $getValueResult['foo']);
158 // 3. Update mailing with template_options.
159 $updateResult = $this->callAPISuccess('mailing', 'create', array(
161 'template_options' => array('foo' => 'bar_2'),
163 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
164 1 => array($id, 'Int'),
166 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
170 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
171 * Make sure these work
173 public function testMagicGroups_create_update() {
175 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
176 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
177 $contactIDs['a'] = $this->individualCreate(array(
178 'email' => 'include.me@example.org',
179 'first_name' => 'Includer',
180 'last_name' => 'Person',
182 $contactIDs['b'] = $this->individualCreate(array(
183 'email' => 'exclude.me@example.org',
184 'last_name' => 'Excluder',
186 $this->callAPISuccess('GroupContact', 'create', array(
187 'group_id' => $groupIDs['a'],
188 'contact_id' => $contactIDs['a'],
190 $this->callAPISuccess('GroupContact', 'create', array(
191 'group_id' => $groupIDs['b'],
192 'contact_id' => $contactIDs['b'],
197 $createParams = $this->_params
;
198 $createParams['groups']['include'] = array($groupIDs['a']);
199 $createParams['groups']['exclude'] = array();
200 $createParams['mailings']['include'] = array();
201 $createParams['mailings']['exclude'] = array();
202 $createParams['api.mailing_job.create'] = 1;
203 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
204 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
205 $getGroup1_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup1['values']));
206 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
207 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
208 $getRecipient1_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient1['values']));
209 $this->assertEquals(array($contactIDs['a']), $getRecipient1_ids);
211 // ** Pass 2: Update without any changes to groups[include]
212 $nullOpParams = $createParams;
213 $nullOpParams['id'] = $createResult['id'];
214 $updateParams['api.mailing_job.create'] = 1;
215 unset($nullOpParams['groups']['include']);
216 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
217 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
218 $getGroup2_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup2['values']));
219 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
220 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
221 $getRecip2_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient2['values']));
222 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
224 // ** Pass 3: Update with different groups[include]
225 $updateParams = $createParams;
226 $updateParams['id'] = $createResult['id'];
227 $updateParams['groups']['include'] = array($groupIDs['b']);
228 $updateParams['api.mailing_job.create'] = 1;
229 $this->callAPISuccess('Mailing', 'create', $updateParams);
230 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
231 $getGroup3_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup3['values']));
232 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
233 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
234 $getRecipient3_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient3['values']));
235 $this->assertEquals(array($contactIDs['b']), $getRecipient3_ids);
238 public function testMailerPreview() {
240 $contactID = $this->individualCreate();
241 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
242 $displayName = $displayName['values'][$contactID]['display_name'];
243 $this->assertTrue(!empty($displayName));
245 $params = $this->_params
;
246 $params['api.Mailing.preview'] = array(
248 'contact_id' => $contactID,
250 $params['options']['force_rollback'] = 1;
254 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
255 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
256 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
257 'recipient' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
259 $result = $this->callAPISuccess('mailing', 'create', $params);
260 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
261 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
262 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
263 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
265 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
266 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
267 $this->assertContains("This is $displayName", $previewResult['values']['body_text']);
268 $this->assertContains("<p>This is $displayName.</p>", $previewResult['values']['body_html']);
271 public function testMailerPreviewRecipients() {
273 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
274 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
275 $contactIDs['include_me'] = $this->individualCreate(array(
276 'email' => 'include.me@example.org',
277 'first_name' => 'Includer',
278 'last_name' => 'Person',
280 $contactIDs['exclude_me'] = $this->individualCreate(array(
281 'email' => 'exclude.me@example.org',
282 'last_name' => 'Excluder',
284 $this->callAPISuccess('GroupContact', 'create', array(
285 'group_id' => $groupIDs['inc'],
286 'contact_id' => $contactIDs['include_me'],
288 $this->callAPISuccess('GroupContact', 'create', array(
289 'group_id' => $groupIDs['inc'],
290 'contact_id' => $contactIDs['exclude_me'],
292 $this->callAPISuccess('GroupContact', 'create', array(
293 'group_id' => $groupIDs['exc'],
294 'contact_id' => $contactIDs['exclude_me'],
297 $params = $this->_params
;
298 $params['groups']['include'] = array($groupIDs['inc']);
299 $params['groups']['exclude'] = array($groupIDs['exc']);
300 $params['mailings']['include'] = array();
301 $params['mailings']['exclude'] = array();
302 $params['options']['force_rollback'] = 1;
303 $params['api.MailingRecipients.get'] = array(
304 'mailing_id' => '$value.id',
305 'api.contact.getvalue' => array(
306 'return' => 'display_name',
308 'api.email.getvalue' => array(
315 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
316 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
318 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__
, __FILE__
);
319 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
320 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
322 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
323 $previewIds = array_values(CRM_Utils_Array
::collect('contact_id', $preview['values']));
324 $this->assertEquals(array((string) $contactIDs['include_me']), $previewIds);
325 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
326 $this->assertEquals(array('include.me@example.org'), $previewEmails);
327 $previewNames = array_values(CRM_Utils_Array
::collect('api.contact.getvalue', $preview['values']));
328 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
332 * Test if Mailing recipients include duplicate OR on_hold emails
334 public function testMailerPreviewRecipientsDeduplicateAndOnholdEmails() {
336 $groupIDs['grp'] = $this->groupCreate(array('name' => 'Example group', 'title' => 'Example group'));
337 $contactIDs['include_me'] = $this->individualCreate(array(
338 'email' => 'include.me@example.org',
339 'first_name' => 'Includer',
340 'last_name' => 'Person',
342 $contactIDs['include_me_duplicate'] = $this->individualCreate(array(
343 'email' => 'include.me@example.org',
344 'first_name' => 'IncluderDuplicate',
345 'last_name' => 'Person',
348 $contactIDs['include_me_onhold'] = $this->individualCreate(array(
349 'email' => 'onholdinclude.me@example.org',
350 'first_name' => 'Onhold',
351 'last_name' => 'Person',
353 $emailId = $this->callAPISuccessGetValue('Email', array(
355 'contact_id' => $contactIDs['include_me_onhold'],
357 $this->callAPISuccess('Email', 'create', array(
362 $this->callAPISuccess('GroupContact', 'create', array(
363 'group_id' => $groupIDs['grp'],
364 'contact_id' => $contactIDs['include_me'],
366 $this->callAPISuccess('GroupContact', 'create', array(
367 'group_id' => $groupIDs['grp'],
368 'contact_id' => $contactIDs['include_me_duplicate'],
370 $this->callAPISuccess('GroupContact', 'create', array(
371 'group_id' => $groupIDs['grp'],
372 'contact_id' => $contactIDs['include_me_onhold'],
375 $params = $this->_params
;
376 $params['groups']['include'] = array($groupIDs['grp']);
377 $params['mailings']['include'] = array();
378 $params['options']['force_rollback'] = 1;
379 $params['dedupe_email'] = 1;
380 $params['api.MailingRecipients.get'] = array(
381 'mailing_id' => '$value.id',
382 'api.contact.getvalue' => array(
383 'return' => 'display_name',
385 'api.email.getvalue' => array(
391 $create = $this->callAPISuccess('Mailing', 'create', $params);
393 //Recipient should not contain duplicate or on_hold emails.
394 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
395 $this->assertEquals(1, $preview['count']);
396 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
397 $this->assertEquals(array('include.me@example.org'), $previewEmails);
401 * Test sending a test mailing.
403 public function testMailerSendTest_email() {
404 $contactIDs['alice'] = $this->individualCreate(array(
405 'email' => 'alice@example.org',
406 'first_name' => 'Alice',
407 'last_name' => 'Person',
410 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
412 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
413 // Per https://lab.civicrm.org/dev/core/issues/229 ensure this is not passed through!
414 $params['id'] = $mail['id'];
415 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
416 $this->assertEquals(1, $deliveredInfo['count']); // verify mail has been sent to user by count
418 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
419 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
421 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
422 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
428 public function testMailerSendTest_group() {
430 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
431 $contactIDs['alice'] = $this->individualCreate(array(
432 'email' => 'alice@example.org',
433 'first_name' => 'Alice',
434 'last_name' => 'Person',
436 $contactIDs['bob'] = $this->individualCreate(array(
437 'email' => 'bob@example.org',
438 'first_name' => 'Bob',
439 'last_name' => 'Person',
441 $contactIDs['carol'] = $this->individualCreate(array(
442 'email' => 'carol@example.org',
443 'first_name' => 'Carol',
444 'last_name' => 'Person',
446 $this->callAPISuccess('GroupContact', 'create', array(
447 'group_id' => $groupIDs['inc'],
448 'contact_id' => $contactIDs['alice'],
450 $this->callAPISuccess('GroupContact', 'create', array(
451 'group_id' => $groupIDs['inc'],
452 'contact_id' => $contactIDs['bob'],
454 $this->callAPISuccess('GroupContact', 'create', array(
455 'group_id' => $groupIDs['inc'],
456 'contact_id' => $contactIDs['carol'],
460 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
461 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', array(
462 'mailing_id' => $mail['id'],
463 'test_email' => NULL,
464 'test_group' => $groupIDs['inc'],
466 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
468 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
469 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
471 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
472 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
478 public function submitProvider() {
479 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
482 array(), // createParams
483 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
484 FALSE, // expectedFailure
485 1, // expectedJobCount
489 array(), // createParams
490 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
491 "/Failed to determine current user/", // expectedFailure
492 0, // expectedJobCount
496 array(), // createParams
497 array('scheduled_date' => '2014-12-13 10:00:00'),
498 FALSE, // expectedFailure
499 1, // expectedJobCount
503 array(), // createParams
505 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
506 0, // expectedJobCount
510 array('name' => ''), // createParams
511 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
512 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./", // expectedFailure
513 0, // expectedJobCount
517 array('body_html' => '', 'body_text' => ''), // createParams
518 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
519 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./", // expectedFailure
520 0, // expectedJobCount
524 array('body_html' => 'Oops, did I leave my tokens at home?'), // createParams
525 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
526 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./", // expectedFailure
527 0, // expectedJobCount
531 array('body_text' => 'Oops, did I leave my tokens at home?'), // createParams
532 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
533 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./", // expectedFailure
534 0, // expectedJobCount
538 array('body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'), // createParams
539 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
540 FALSE, // expectedFailure
541 1, // expectedJobCount
545 array('body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'), // createParams
546 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
547 FALSE, // expectedFailure
548 1, // expectedJobCount
554 * @param bool $useLogin
555 * @param array $createParams
556 * @param array $submitParams
557 * @param null|string $expectedFailure
558 * @param int $expectedJobCount
559 * @dataProvider submitProvider
561 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
563 $this->createLoggedInUser();
566 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
567 $createParams['footer_id'] = $this->footer
['id'];
570 $id = $this->createDraftMailing($createParams);
572 $submitParams['id'] = $id;
573 if ($expectedFailure) {
574 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
575 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
578 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__
, __FILE__
);
579 $this->assertTrue(is_numeric($submitResult['id']));
580 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
581 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
583 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
584 1 => array($id, 'Integer'),
589 * Test unsubscribe list contains correct groups
590 * when include = 'previous mailing'
592 public function testUnsubscribeGroupList() {
593 // Create set of groups and add a contact to both of them.
594 $groupID2 = $this->groupCreate(array('name' => 'Test group 2', 'title' => 'group title 2'));
595 $groupID3 = $this->groupCreate(array('name' => 'Test group 3', 'title' => 'group title 3'));
596 $contactId = $this->individualCreate();
597 foreach (array($groupID2, $groupID3) as $grp) {
599 'contact_id' => $contactId,
602 $this->callAPISuccess('GroupContact', 'create', $params);
605 //Send mail to groupID3
606 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
607 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $groupID3);
608 $this->callAPISuccess($this->_entity
, 'send_test', $params);
611 'mailing_id' => $mail['id'],
612 'entity_table' => 'civicrm_group',
613 'entity_id' => $groupID3,
614 'group_type' => 'Include',
616 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
618 //Include previous mail in the mailing group.
619 $mail2 = $this->callAPISuccess('mailing', 'create', $this->_params
);
620 $params = array('mailing_id' => $mail2['id'], 'test_email' => NULL, 'test_group' => $groupID3);
621 $this->callAPISuccess($this->_entity
, 'send_test', $params);
624 'mailing_id' => $mail2['id'],
625 'entity_table' => 'civicrm_mailing',
626 'entity_id' => $mail['id'],
627 'group_type' => 'Include',
629 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
630 //CRM-20431 - Delete group id that matches first mailing id.
631 $this->callAPISuccess('Group', 'delete', array('id' => $this->_groupID
));
632 $jobId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_MailingJob', $mail2['id'], 'id', 'mailing_id');
633 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'hash', 'job_id');
634 $queueId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'id', 'job_id');
636 $group = CRM_Mailing_Event_BAO_Unsubscribe
::unsub_from_mailing($jobId, $queueId, $hash, TRUE);
637 //Assert only one group returns in the unsubscribe list.
638 $this->assertCount(1, $group);
639 $this->assertEquals($groupID3, key($group));
645 public function testMailerStats() {
646 $result = $this->groupContactCreate($this->_groupID
, 100);
647 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
649 //Create and send test mail first and change the mail job to live,
650 //because stats api only works on live mail
651 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
652 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
);
653 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
654 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
656 //Change the test mail into live
657 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
658 CRM_Core_DAO
::executeQuery($sql);
660 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
661 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
662 (event_queue_id int, time_stamp datetime, delivered_id int)
663 SELECT event_queue_id, time_stamp, id
664 FROM civicrm_mailing_event_delivered
665 WHERE id IN ($deliveredIds)
666 ORDER BY RAND() LIMIT 0,20;";
667 CRM_Core_DAO
::executeQuery($sql);
669 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
670 CRM_Core_DAO
::executeQuery($sql);
672 if ($type == 'unsubscribe') {
673 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
674 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
677 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
678 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
680 CRM_Core_DAO
::executeQuery($sql);
683 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
684 $expectedResult = array(
685 'Delivered' => 80, //since among 100 mails 20 has been bounced
688 'Unique Clicks' => 0,
689 'Unsubscribers' => 20,
690 'delivered_rate' => '80%',
691 'opened_rate' => '25%',
692 'clickthrough_rate' => '0%',
694 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
698 * Test civicrm_mailing_delete.
700 public function testMailerDeleteSuccess() {
701 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
702 $this->callAPIAndDocument($this->_entity
, 'delete', array('id' => $result['id']), __FUNCTION__
, __FILE__
);
703 $this->assertAPIDeleted($this->_entity
, $result['id']);
707 * Test Mailing.gettokens.
709 public function testMailGetTokens() {
710 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
711 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
712 $result = $this->callAPIAndDocument($this->_entity
, 'gettokens', array('entity' => array('Contact', 'Mailing')), __FUNCTION__
, __FILE__
, $description);
713 $this->assertContains('Contact Type', $result['values']);
715 // Check that passing "sequential" correctly outputs a hierarchical array
716 $result = $this->callAPISuccess($this->_entity
, 'gettokens', array('entity' => 'contact', 'sequential' => 1));
717 $this->assertArrayHasKey('text', $result['values'][0]);
718 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
721 public function testClone() {
723 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
724 $contactIDs['include_me'] = $this->individualCreate(array(
725 'email' => 'include.me@example.org',
726 'first_name' => 'Includer',
727 'last_name' => 'Person',
729 $this->callAPISuccess('GroupContact', 'create', array(
730 'group_id' => $groupIDs['inc'],
731 'contact_id' => $contactIDs['include_me'],
734 $params = $this->_params
;
735 $params['groups']['include'] = array($groupIDs['inc']);
736 $params['groups']['exclude'] = array();
737 $params['mailings']['include'] = array();
738 $params['mailings']['exclude'] = array();
741 $create = $this->callAPISuccess('Mailing', 'create', $params);
742 $created = $this->callAPISuccess('Mailing', 'get', []);
743 $createId = $create['id'];
744 $this->createLoggedInUser();
745 $clone = $this->callAPIAndDocument('Mailing', 'clone', array('id' => $create['id']), __FUNCTION__
, __FILE__
);
746 $cloneId = $clone['id'];
748 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
749 $this->assertTrue(is_numeric($cloneId));
751 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
752 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
754 // created_id is special - populated based on current user (ie the cloner).
755 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
756 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
758 // Target groups+mailings are special.
759 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $cloneId, 'sequential' => 1));
760 $this->assertEquals(1, $cloneGroups['count']);
761 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
762 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
763 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
766 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
768 //------------ civicrm_mailing_event_bounce methods------------
771 * Test civicrm_mailing_event_bounce with wrong params.
772 * Note that tests like this are slightly better than no test but an
773 * api function cannot be considered supported / 'part of the api' without a
776 public function testMailerBounceWrongParams() {
778 'job_id' => 'Wrong ID',
779 'event_queue_id' => 'Wrong ID',
780 'hash' => 'Wrong Hash',
782 'time_stamp' => '20111109212100',
784 $this->callAPIFailure('mailing_event', 'bounce', $params,
785 'Queue event could not be found'
789 //----------- civicrm_mailing_event_confirm methods -----------
792 * Test civicrm_mailing_event_confirm with wrong params.
793 * Note that tests like this are slightly better than no test but an
794 * api function cannot be considered supported / 'part of the api' without a
797 public function testMailerConfirmWrongParams() {
799 'contact_id' => 'Wrong ID',
800 'subscribe_id' => 'Wrong ID',
801 'hash' => 'Wrong Hash',
802 'event_subscribe_id' => '123',
803 'time_stamp' => '20111111010101',
805 $this->callAPIFailure('mailing_event', 'confirm', $params,
806 'contact_id is not a valid integer'
810 //---------- civicrm_mailing_event_reply methods -----------
813 * Test civicrm_mailing_event_reply with wrong params.
815 * Note that tests like this are slightly better than no test but an
816 * api function cannot be considered supported / 'part of the api' without a
819 public function testMailerReplyWrongParams() {
821 'job_id' => 'Wrong ID',
822 'event_queue_id' => 'Wrong ID',
823 'hash' => 'Wrong Hash',
824 'bodyTxt' => 'Body...',
825 'replyTo' => $this->_email
,
826 'time_stamp' => '20111111010101',
828 $this->callAPIFailure('mailing_event', 'reply', $params,
829 'Queue event could not be found'
834 //----------- civicrm_mailing_event_forward methods ----------
837 * Test civicrm_mailing_event_forward with wrong params.
838 * Note that tests like this are slightly better than no test but an
839 * api function cannot be considered supported / 'part of the api' without a
842 public function testMailerForwardWrongParams() {
844 'job_id' => 'Wrong ID',
845 'event_queue_id' => 'Wrong ID',
846 'hash' => 'Wrong Hash',
847 'email' => $this->_email
,
848 'time_stamp' => '20111111010101',
850 $this->callAPIFailure('mailing_event', 'forward', $params,
851 'Queue event could not be found'
856 * @param array $params
857 * Extra parameters for the draft mailing.
860 public function createDraftMailing($params = array()) {
861 $createParams = array_merge($this->_params
, $params);
862 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
863 $this->assertTrue(is_numeric($createResult['id']));
864 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
865 1 => array($createResult['id'], 'Integer'),
867 return $createResult['id'];
871 * Test to make sure that if the event queue hashes have been archived,
872 * we can still have working click-trough URLs working (CRM-17959).
874 public function testUrlWithMissingTrackingHash() {
875 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
876 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $mail['id']));
877 $this->assertEquals(1, $jobs['count']);
879 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
880 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
882 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
883 FROM civicrm_mailing_trackable_url as turl
884 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
885 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
886 ORDER BY turl.id DESC LIMIT 1";
888 $dao = CRM_Core_DAO
::executeQuery($sql);
889 $this->assertTrue($dao->fetch());
891 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
892 $this->assertContains('https://civicrm.org', $url);
894 // Now delete the event queue hashes and see if the tracking still works.
895 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
897 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
898 $this->assertContains('https://civicrm.org', $url);
902 * Test Trackable URL with unicode character
904 public function testTrackableURLWithUnicodeSign() {
905 $unicodeURL = "https://civiĆcrm.org";
906 $this->_params
['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_text']);
907 $this->_params
['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_html']);
909 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'));
911 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
912 $this->callAPISuccess($this->_entity
, 'send_test', $params);
914 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
915 FROM civicrm_mailing_trackable_url as turl
916 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
917 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
918 ORDER BY turl.id DESC LIMIT 1";
920 $dao = CRM_Core_DAO
::executeQuery($sql);
921 $this->assertTrue($dao->fetch());
923 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
924 $this->assertContains($unicodeURL, $url);
926 // Now delete the event queue hashes and see if the tracking still works.
927 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
929 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
930 $this->assertContains($unicodeURL, $url);
934 * CRM-20892 : Test if Mail.create API throws error on update,
935 * if modified_date less then the date when the mail was last updated/created
937 public function testModifiedDateMismatchOnMailingUpdate() {
938 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('modified_date' => 'now'));
940 $this->callAPISuccess('mailing', 'create', $this->_params +
array('id' => $mail['id'], 'modified_date' => '2 seconds ago'));
942 catch (Exception
$e) {
943 $this->assertRegExp("/Failure in api call for mailing create: Mailing has not been saved, Content maybe out of date, please refresh the page and try again/", $e->getMessage());