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);
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 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
414 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
416 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
417 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
419 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
420 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
426 public function testMailerSendTest_group() {
428 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
429 $contactIDs['alice'] = $this->individualCreate(array(
430 'email' => 'alice@example.org',
431 'first_name' => 'Alice',
432 'last_name' => 'Person',
434 $contactIDs['bob'] = $this->individualCreate(array(
435 'email' => 'bob@example.org',
436 'first_name' => 'Bob',
437 'last_name' => 'Person',
439 $contactIDs['carol'] = $this->individualCreate(array(
440 'email' => 'carol@example.org',
441 'first_name' => 'Carol',
442 'last_name' => 'Person',
444 $this->callAPISuccess('GroupContact', 'create', array(
445 'group_id' => $groupIDs['inc'],
446 'contact_id' => $contactIDs['alice'],
448 $this->callAPISuccess('GroupContact', 'create', array(
449 'group_id' => $groupIDs['inc'],
450 'contact_id' => $contactIDs['bob'],
452 $this->callAPISuccess('GroupContact', 'create', array(
453 'group_id' => $groupIDs['inc'],
454 'contact_id' => $contactIDs['carol'],
458 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
459 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', array(
460 'mailing_id' => $mail['id'],
461 'test_email' => NULL,
462 'test_group' => $groupIDs['inc'],
464 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
466 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
467 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
469 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
470 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
476 public function submitProvider() {
477 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
480 array(), // createParams
481 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
482 FALSE, // expectedFailure
483 1, // expectedJobCount
487 array(), // createParams
488 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
489 "/Failed to determine current user/", // expectedFailure
490 0, // expectedJobCount
494 array(), // createParams
495 array('scheduled_date' => '2014-12-13 10:00:00'),
496 FALSE, // expectedFailure
497 1, // expectedJobCount
501 array(), // createParams
503 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
504 0, // expectedJobCount
508 array('name' => ''), // createParams
509 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
510 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./", // expectedFailure
511 0, // expectedJobCount
515 array('body_html' => '', 'body_text' => ''), // createParams
516 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
517 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./", // expectedFailure
518 0, // expectedJobCount
522 array('body_html' => 'Oops, did I leave my tokens at home?'), // createParams
523 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
524 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./", // expectedFailure
525 0, // expectedJobCount
529 array('body_text' => 'Oops, did I leave my tokens at home?'), // createParams
530 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
531 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./", // expectedFailure
532 0, // expectedJobCount
536 array('body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'), // createParams
537 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
538 FALSE, // expectedFailure
539 1, // expectedJobCount
543 array('body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'), // createParams
544 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
545 FALSE, // expectedFailure
546 1, // expectedJobCount
552 * @param bool $useLogin
553 * @param array $createParams
554 * @param array $submitParams
555 * @param null|string $expectedFailure
556 * @param int $expectedJobCount
557 * @dataProvider submitProvider
559 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
561 $this->createLoggedInUser();
564 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
565 $createParams['footer_id'] = $this->footer
['id'];
568 $id = $this->createDraftMailing($createParams);
570 $submitParams['id'] = $id;
571 if ($expectedFailure) {
572 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
573 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
576 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__
, __FILE__
);
577 $this->assertTrue(is_numeric($submitResult['id']));
578 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
579 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
581 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
582 1 => array($id, 'Integer'),
587 * Test unsubscribe list contains correct groups
588 * when include = 'previous mailing'
590 public function testUnsubscribeGroupList() {
591 // Create set of groups and add a contact to both of them.
592 $groupID2 = $this->groupCreate(array('name' => 'Test group 2', 'title' => 'group title 2'));
593 $groupID3 = $this->groupCreate(array('name' => 'Test group 3', 'title' => 'group title 3'));
594 $contactId = $this->individualCreate();
595 foreach (array($groupID2, $groupID3) as $grp) {
597 'contact_id' => $contactId,
600 $this->callAPISuccess('GroupContact', 'create', $params);
603 //Send mail to groupID3
604 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
605 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $groupID3);
606 $this->callAPISuccess($this->_entity
, 'send_test', $params);
609 'mailing_id' => $mail['id'],
610 'entity_table' => 'civicrm_group',
611 'entity_id' => $groupID3,
612 'group_type' => 'Include',
614 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
616 //Include previous mail in the mailing group.
617 $mail2 = $this->callAPISuccess('mailing', 'create', $this->_params
);
618 $params = array('mailing_id' => $mail2['id'], 'test_email' => NULL, 'test_group' => $groupID3);
619 $this->callAPISuccess($this->_entity
, 'send_test', $params);
622 'mailing_id' => $mail2['id'],
623 'entity_table' => 'civicrm_mailing',
624 'entity_id' => $mail['id'],
625 'group_type' => 'Include',
627 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
628 //CRM-20431 - Delete group id that matches first mailing id.
629 $this->callAPISuccess('Group', 'delete', array('id' => $this->_groupID
));
630 $jobId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_MailingJob', $mail2['id'], 'id', 'mailing_id');
631 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'hash', 'job_id');
632 $queueId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'id', 'job_id');
634 $group = CRM_Mailing_Event_BAO_Unsubscribe
::unsub_from_mailing($jobId, $queueId, $hash, TRUE);
635 //Assert only one group returns in the unsubscribe list.
636 $this->assertCount(1, $group);
637 $this->assertEquals($groupID3, key($group));
643 public function testMailerStats() {
644 $result = $this->groupContactCreate($this->_groupID
, 100);
645 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
647 //Create and send test mail first and change the mail job to live,
648 //because stats api only works on live mail
649 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
650 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
);
651 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
652 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
654 //Change the test mail into live
655 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
656 CRM_Core_DAO
::executeQuery($sql);
658 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
659 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
660 (event_queue_id int, time_stamp datetime, delivered_id int)
661 SELECT event_queue_id, time_stamp, id
662 FROM civicrm_mailing_event_delivered
663 WHERE id IN ($deliveredIds)
664 ORDER BY RAND() LIMIT 0,20;";
665 CRM_Core_DAO
::executeQuery($sql);
667 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
668 CRM_Core_DAO
::executeQuery($sql);
670 if ($type == 'unsubscribe') {
671 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
672 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
675 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
676 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
678 CRM_Core_DAO
::executeQuery($sql);
681 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
682 $expectedResult = array(
683 'Delivered' => 80, //since among 100 mails 20 has been bounced
686 'Unique Clicks' => 0,
687 'Unsubscribers' => 20,
689 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
693 * Test civicrm_mailing_delete.
695 public function testMailerDeleteSuccess() {
696 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
697 $this->callAPIAndDocument($this->_entity
, 'delete', array('id' => $result['id']), __FUNCTION__
, __FILE__
);
698 $this->assertAPIDeleted($this->_entity
, $result['id']);
702 * Test Mailing.gettokens.
704 public function testMailGetTokens() {
705 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
706 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
707 $result = $this->callAPIAndDocument($this->_entity
, 'gettokens', array('entity' => array('Contact', 'Mailing')), __FUNCTION__
, __FILE__
, $description);
708 $this->assertContains('Contact Type', $result['values']);
710 // Check that passing "sequential" correctly outputs a hierarchical array
711 $result = $this->callAPISuccess($this->_entity
, 'gettokens', array('entity' => 'contact', 'sequential' => 1));
712 $this->assertArrayHasKey('text', $result['values'][0]);
713 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
716 public function testClone() {
718 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
719 $contactIDs['include_me'] = $this->individualCreate(array(
720 'email' => 'include.me@example.org',
721 'first_name' => 'Includer',
722 'last_name' => 'Person',
724 $this->callAPISuccess('GroupContact', 'create', array(
725 'group_id' => $groupIDs['inc'],
726 'contact_id' => $contactIDs['include_me'],
729 $params = $this->_params
;
730 $params['groups']['include'] = array($groupIDs['inc']);
731 $params['groups']['exclude'] = array();
732 $params['mailings']['include'] = array();
733 $params['mailings']['exclude'] = array();
736 $create = $this->callAPISuccess('Mailing', 'create', $params);
737 $createId = $create['id'];
738 $this->createLoggedInUser();
739 $clone = $this->callAPIAndDocument('Mailing', 'clone', array('id' => $create['id']), __FUNCTION__
, __FILE__
);
740 $cloneId = $clone['id'];
742 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
743 $this->assertTrue(is_numeric($cloneId));
745 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
746 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
748 // created_id is special - populated based on current user (ie the cloner).
749 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
750 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
752 // Target groups+mailings are special.
753 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $cloneId, 'sequential' => 1));
754 $this->assertEquals(1, $cloneGroups['count']);
755 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
756 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
757 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
760 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
762 //------------ civicrm_mailing_event_bounce methods------------
765 * Test civicrm_mailing_event_bounce with wrong params.
766 * Note that tests like this are slightly better than no test but an
767 * api function cannot be considered supported / 'part of the api' without a
770 public function testMailerBounceWrongParams() {
772 'job_id' => 'Wrong ID',
773 'event_queue_id' => 'Wrong ID',
774 'hash' => 'Wrong Hash',
776 'time_stamp' => '20111109212100',
778 $this->callAPIFailure('mailing_event', 'bounce', $params,
779 'Queue event could not be found'
783 //----------- civicrm_mailing_event_confirm methods -----------
786 * Test civicrm_mailing_event_confirm with wrong params.
787 * Note that tests like this are slightly better than no test but an
788 * api function cannot be considered supported / 'part of the api' without a
791 public function testMailerConfirmWrongParams() {
793 'contact_id' => 'Wrong ID',
794 'subscribe_id' => 'Wrong ID',
795 'hash' => 'Wrong Hash',
796 'event_subscribe_id' => '123',
797 'time_stamp' => '20111111010101',
799 $this->callAPIFailure('mailing_event', 'confirm', $params,
800 'contact_id is not a valid integer'
804 //---------- civicrm_mailing_event_reply methods -----------
807 * Test civicrm_mailing_event_reply with wrong params.
809 * Note that tests like this are slightly better than no test but an
810 * api function cannot be considered supported / 'part of the api' without a
813 public function testMailerReplyWrongParams() {
815 'job_id' => 'Wrong ID',
816 'event_queue_id' => 'Wrong ID',
817 'hash' => 'Wrong Hash',
818 'bodyTxt' => 'Body...',
819 'replyTo' => $this->_email
,
820 'time_stamp' => '20111111010101',
822 $this->callAPIFailure('mailing_event', 'reply', $params,
823 'Queue event could not be found'
828 //----------- civicrm_mailing_event_forward methods ----------
831 * Test civicrm_mailing_event_forward with wrong params.
832 * Note that tests like this are slightly better than no test but an
833 * api function cannot be considered supported / 'part of the api' without a
836 public function testMailerForwardWrongParams() {
838 'job_id' => 'Wrong ID',
839 'event_queue_id' => 'Wrong ID',
840 'hash' => 'Wrong Hash',
841 'email' => $this->_email
,
842 'time_stamp' => '20111111010101',
844 $this->callAPIFailure('mailing_event', 'forward', $params,
845 'Queue event could not be found'
850 * @param array $params
851 * Extra parameters for the draft mailing.
854 public function createDraftMailing($params = array()) {
855 $createParams = array_merge($this->_params
, $params);
856 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
857 $this->assertTrue(is_numeric($createResult['id']));
858 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
859 1 => array($createResult['id'], 'Integer'),
861 return $createResult['id'];
865 * Test to make sure that if the event queue hashes have been archived,
866 * we can still have working click-trough URLs working (CRM-17959).
868 public function testUrlWithMissingTrackingHash() {
869 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
870 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $mail['id']));
871 $this->assertEquals(1, $jobs['count']);
873 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
874 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
876 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
877 FROM civicrm_mailing_trackable_url as turl
878 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
879 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
880 ORDER BY turl.id DESC LIMIT 1";
882 $dao = CRM_Core_DAO
::executeQuery($sql);
883 $this->assertTrue($dao->fetch());
885 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
886 $this->assertContains('https://civicrm.org', $url);
888 // Now delete the event queue hashes and see if the tracking still works.
889 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
891 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
892 $this->assertContains('https://civicrm.org', $url);
896 * Test Trackable URL with unicode character
898 public function testTrackableURLWithUnicodeSign() {
899 $unicodeURL = "https://civiĆcrm.org";
900 $this->_params
['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_text']);
901 $this->_params
['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_html']);
903 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'));
905 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
906 $this->callAPISuccess($this->_entity
, 'send_test', $params);
908 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
909 FROM civicrm_mailing_trackable_url as turl
910 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
911 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
912 ORDER BY turl.id DESC LIMIT 1";
914 $dao = CRM_Core_DAO
::executeQuery($sql);
915 $this->assertTrue($dao->fetch());
917 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
918 $this->assertContains($unicodeURL, $url);
920 // Now delete the event queue hashes and see if the tracking still works.
921 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
923 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
924 $this->assertContains($unicodeURL, $url);
928 * CRM-20892 : Test if Mail.create API throws error on update,
929 * if modified_date less then the date when the mail was last updated/created
931 public function testModifiedDateMismatchOnMailingUpdate() {
932 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('modified_date' => 'now'));
934 $this->callAPISuccess('mailing', 'create', $this->_params +
array('id' => $mail['id'], 'modified_date' => '2 seconds ago'));
936 catch (Exception
$e) {
937 $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());