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();
51 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0;
52 $this->_contactID
= $this->individualCreate();
53 $this->_groupID
= $this->groupCreate();
54 $this->_email
= 'test@test.test';
55 $this->_params
= array(
56 'subject' => 'Hello {contact.display_name}',
57 'body_text' => "This is {contact.display_name}.\nhttps://civicrm.org\n{domain.address}{action.optOutUrl}",
58 'body_html' => "<link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Zilla+Slab:500,700' rel='stylesheet' type='text/css'><p>This is {contact.display_name}.</p><p><a href='https://civicrm.org/'>CiviCRM.org</a></p><p>{domain.address}{action.optOutUrl}</p>",
59 'name' => 'mailing name',
60 'created_id' => $this->_contactID
,
65 $this->footer
= civicrm_api3('MailingComponent', 'create', array(
66 'name' => 'test domain footer',
67 'component_type' => 'footer',
68 'body_html' => '<p>From {domain.address}. To opt out, go to {action.optOutUrl}.</p>',
69 'body_text' => 'From {domain.address}. To opt out, go to {action.optOutUrl}.',
73 public function tearDown() {
75 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0;
80 * Test civicrm_mailing_create.
82 public function testMailerCreateSuccess() {
83 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
84 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
85 $this->assertEquals(1, $jobs['count']);
86 // return isn't working on this in getAndCheck so lets not check it for now
87 unset($this->_params
['created_id']);
88 $this->getAndCheck($this->_params
, $result['id'], 'mailing');
92 * Tes that the parameter _skip_evil_bao_auto_schedule_ is respected & prevents jobs being created.
94 public function testSkipAutoSchedule() {
95 $this->callAPISuccess('Mailing', 'create', array_merge($this->_params
, [
96 '_skip_evil_bao_auto_schedule_' => TRUE,
97 'scheduled_date' => 'now',
99 $this->callAPISuccessGetCount('Mailing', [], 1);
100 $this->callAPISuccessGetCount('MailingJob', [], 0);
104 * Create a completed mailing (e.g when importing from a provider).
106 public function testMailerCreateCompleted() {
107 $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';
108 $this->_params
['is_completed'] = 1;
109 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
110 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
111 $this->assertEquals(1, $jobs['count']);
112 $this->assertEquals('Complete', $jobs['values'][$jobs['id']]['status']);
113 // return isn't working on this in getAndCheck so lets not check it for now
114 unset($this->_params
['created_id']);
115 $this->getAndCheck($this->_params
, $result['id'], 'mailing');
119 * Per CRM-20316 the mailing should still create without created_id (not mandatory).
121 public function testMailerCreateSuccessNoCreatedID() {
122 unset($this->_params
['created_id']);
123 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
124 $this->getAndCheck($this->_params
, $result['id'], 'mailing');
130 public function testTemplateTypeOptions() {
131 $types = $this->callAPISuccess('Mailing', 'getoptions', array('field' => 'template_type'));
132 $this->assertTrue(isset($types['values']['traditional']));
136 * The `template_options` field should be treated a JSON object.
138 * This test will create, read, and update the field.
140 public function testMailerCreateTemplateOptions() {
141 // 1. Create mailing with template_options.
142 $params = $this->_params
;
143 $params['template_options'] = json_encode(array('foo' => 'bar_1'));
144 $createResult = $this->callAPISuccess('mailing', 'create', $params);
145 $id = $createResult['id'];
146 $this->assertDBQuery('{"foo":"bar_1"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
147 1 => array($id, 'Int'),
149 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
151 // 2. Get mailing with template_options.
152 $getResult = $this->callAPISuccess('mailing', 'get', array(
155 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
156 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', array(
158 'return' => 'template_options',
160 $this->assertEquals('bar_1', $getValueResult['foo']);
162 // 3. Update mailing with template_options.
163 $updateResult = $this->callAPISuccess('mailing', 'create', array(
165 'template_options' => array('foo' => 'bar_2'),
167 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
168 1 => array($id, 'Int'),
170 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
174 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
175 * Make sure these work
177 public function testMagicGroups_create_update() {
179 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
180 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
181 $contactIDs['a'] = $this->individualCreate(array(
182 'email' => 'include.me@example.org',
183 'first_name' => 'Includer',
184 'last_name' => 'Person',
186 $contactIDs['b'] = $this->individualCreate(array(
187 'email' => 'exclude.me@example.org',
188 'last_name' => 'Excluder',
190 $this->callAPISuccess('GroupContact', 'create', array(
191 'group_id' => $groupIDs['a'],
192 'contact_id' => $contactIDs['a'],
194 $this->callAPISuccess('GroupContact', 'create', array(
195 'group_id' => $groupIDs['b'],
196 'contact_id' => $contactIDs['b'],
201 $createParams = $this->_params
;
202 $createParams['groups']['include'] = [$groupIDs['a']];
203 $createParams['groups']['exclude'] = [];
204 $createParams['mailings']['include'] = [];
205 $createParams['mailings']['exclude'] = [];
206 $createParams['scheduled_date'] = 'now';
207 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
208 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
209 $getGroup1_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup1['values']));
210 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
211 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
212 $getRecipient1_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient1['values']));
213 $this->assertEquals(array($contactIDs['a']), $getRecipient1_ids);
215 // ** Pass 2: Update without any changes to groups[include]
216 $nullOpParams = $createParams;
217 $nullOpParams['id'] = $createResult['id'];
218 $updateParams['api.mailing_job.create'] = 1;
219 unset($nullOpParams['groups']['include']);
220 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
221 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
222 $getGroup2_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup2['values']));
223 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
224 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
225 $getRecip2_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient2['values']));
226 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
228 // ** Pass 3: Update with different groups[include]
229 $updateParams = $createParams;
230 $updateParams['id'] = $createResult['id'];
231 $updateParams['groups']['include'] = array($groupIDs['b']);
232 $updateParams['scheduled_date'] = 'now';
233 $this->callAPISuccess('Mailing', 'create', $updateParams);
234 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
235 $getGroup3_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup3['values']));
236 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
237 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
238 $getRecipient3_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient3['values']));
239 $this->assertEquals(array($contactIDs['b']), $getRecipient3_ids);
242 public function testMailerPreview() {
244 $contactID = $this->individualCreate();
245 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
246 $displayName = $displayName['values'][$contactID]['display_name'];
247 $this->assertTrue(!empty($displayName));
249 $params = $this->_params
;
250 $params['api.Mailing.preview'] = array(
252 'contact_id' => $contactID,
254 $params['options']['force_rollback'] = 1;
258 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
259 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
260 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
261 'recipient' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
263 $result = $this->callAPISuccess('mailing', 'create', $params);
264 // 'Preview should not create any mailing records'
265 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing');
266 // 'Preview should not create any mailing_job record'
267 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job');
268 // 'Preview should not create any mailing_group records'
269 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group');
270 // 'Preview should not create any mailing_recipient records'
271 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients');
273 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
274 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
275 $this->assertContains("This is $displayName", $previewResult['values']['body_text']);
276 $this->assertContains("<p>This is $displayName.</p>", $previewResult['values']['body_html']);
279 public function testMailerPreviewRecipients() {
281 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
282 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
283 $contactIDs['include_me'] = $this->individualCreate(array(
284 'email' => 'include.me@example.org',
285 'first_name' => 'Includer',
286 'last_name' => 'Person',
288 $contactIDs['exclude_me'] = $this->individualCreate(array(
289 'email' => 'exclude.me@example.org',
290 'last_name' => 'Excluder',
292 $this->callAPISuccess('GroupContact', 'create', array(
293 'group_id' => $groupIDs['inc'],
294 'contact_id' => $contactIDs['include_me'],
296 $this->callAPISuccess('GroupContact', 'create', array(
297 'group_id' => $groupIDs['inc'],
298 'contact_id' => $contactIDs['exclude_me'],
300 $this->callAPISuccess('GroupContact', 'create', array(
301 'group_id' => $groupIDs['exc'],
302 'contact_id' => $contactIDs['exclude_me'],
305 $params = $this->_params
;
306 $params['groups']['include'] = array($groupIDs['inc']);
307 $params['groups']['exclude'] = array($groupIDs['exc']);
308 $params['mailings']['include'] = array();
309 $params['mailings']['exclude'] = array();
310 $params['options']['force_rollback'] = 1;
311 $params['api.MailingRecipients.get'] = array(
312 'mailing_id' => '$value.id',
313 'api.contact.getvalue' => array(
314 'return' => 'display_name',
316 'api.email.getvalue' => array(
323 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
324 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
326 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__
, __FILE__
);
327 // 'Preview should not create any mailing records'
328 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing');
329 // 'Preview should not create any mailing_group records'
330 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group');
332 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
333 $previewIds = array_values(CRM_Utils_Array
::collect('contact_id', $preview['values']));
334 $this->assertEquals(array((string) $contactIDs['include_me']), $previewIds);
335 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
336 $this->assertEquals(array('include.me@example.org'), $previewEmails);
337 $previewNames = array_values(CRM_Utils_Array
::collect('api.contact.getvalue', $preview['values']));
338 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
342 * Test if Mailing recipients include duplicate OR on_hold emails
344 public function testMailerPreviewRecipientsDeduplicateAndOnholdEmails() {
346 $groupIDs['grp'] = $this->groupCreate(array('name' => 'Example group', 'title' => 'Example group'));
347 $contactIDs['include_me'] = $this->individualCreate(array(
348 'email' => 'include.me@example.org',
349 'first_name' => 'Includer',
350 'last_name' => 'Person',
352 $contactIDs['include_me_duplicate'] = $this->individualCreate(array(
353 'email' => 'include.me@example.org',
354 'first_name' => 'IncluderDuplicate',
355 'last_name' => 'Person',
358 $contactIDs['include_me_onhold'] = $this->individualCreate(array(
359 'email' => 'onholdinclude.me@example.org',
360 'first_name' => 'Onhold',
361 'last_name' => 'Person',
363 $emailId = $this->callAPISuccessGetValue('Email', array(
365 'contact_id' => $contactIDs['include_me_onhold'],
367 $this->callAPISuccess('Email', 'create', array(
372 $this->callAPISuccess('GroupContact', 'create', array(
373 'group_id' => $groupIDs['grp'],
374 'contact_id' => $contactIDs['include_me'],
376 $this->callAPISuccess('GroupContact', 'create', array(
377 'group_id' => $groupIDs['grp'],
378 'contact_id' => $contactIDs['include_me_duplicate'],
380 $this->callAPISuccess('GroupContact', 'create', array(
381 'group_id' => $groupIDs['grp'],
382 'contact_id' => $contactIDs['include_me_onhold'],
385 $params = $this->_params
;
386 $params['groups']['include'] = array($groupIDs['grp']);
387 $params['mailings']['include'] = array();
388 $params['options']['force_rollback'] = 1;
389 $params['dedupe_email'] = 1;
390 $params['api.MailingRecipients.get'] = array(
391 'mailing_id' => '$value.id',
392 'api.contact.getvalue' => array(
393 'return' => 'display_name',
395 'api.email.getvalue' => array(
401 $create = $this->callAPISuccess('Mailing', 'create', $params);
403 //Recipient should not contain duplicate or on_hold emails.
404 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
405 $this->assertEquals(1, $preview['count']);
406 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
407 $this->assertEquals(array('include.me@example.org'), $previewEmails);
411 * Test sending a test mailing.
413 public function testMailerSendTest_email() {
414 $contactIDs['alice'] = $this->individualCreate(array(
415 'email' => 'alice@example.org',
416 'first_name' => 'Alice',
417 'last_name' => 'Person',
420 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
422 $params = array('mailing_id' => $mail['id'], 'test_email' => 'ALicE@example.org', 'test_group' => NULL);
423 // Per https://lab.civicrm.org/dev/core/issues/229 ensure this is not passed through!
424 // Per https://lab.civicrm.org/dev/mail/issues/32 test non-lowercase email
425 $params['id'] = $mail['id'];
426 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
427 // verify mail has been sent to user by count
428 $this->assertEquals(1, $deliveredInfo['count']);
430 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
431 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
433 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
434 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
440 public function testMailerSendTest_group() {
442 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
443 $contactIDs['alice'] = $this->individualCreate(array(
444 'email' => 'alice@example.org',
445 'first_name' => 'Alice',
446 'last_name' => 'Person',
448 $contactIDs['bob'] = $this->individualCreate(array(
449 'email' => 'bob@example.org',
450 'first_name' => 'Bob',
451 'last_name' => 'Person',
453 $contactIDs['carol'] = $this->individualCreate(array(
454 'email' => 'carol@example.org',
455 'first_name' => 'Carol',
456 'last_name' => 'Person',
458 $this->callAPISuccess('GroupContact', 'create', array(
459 'group_id' => $groupIDs['inc'],
460 'contact_id' => $contactIDs['alice'],
462 $this->callAPISuccess('GroupContact', 'create', array(
463 'group_id' => $groupIDs['inc'],
464 'contact_id' => $contactIDs['bob'],
466 $this->callAPISuccess('GroupContact', 'create', array(
467 'group_id' => $groupIDs['inc'],
468 'contact_id' => $contactIDs['carol'],
472 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
473 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', array(
474 'mailing_id' => $mail['id'],
475 'test_email' => NULL,
476 'test_group' => $groupIDs['inc'],
478 // verify mail has been sent to user by count
479 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
);
481 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
482 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
484 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
485 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
491 public function submitProvider() {
492 // $useLogin, $params, $expectedFailure, $expectedJobCount
499 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
510 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
512 "/Failed to determine current user/",
521 array('scheduled_date' => '2014-12-13 10:00:00'),
534 "/Missing parameter scheduled_date and.or approval_date/",
543 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
545 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./",
553 array('body_html' => '', 'body_text' => ''),
554 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
556 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./",
564 array('body_html' => 'Oops, did I leave my tokens at home?'),
565 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
567 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./",
575 array('body_text' => 'Oops, did I leave my tokens at home?'),
576 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
578 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./",
586 array('body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'),
587 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
597 array('body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'),
598 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
608 * @param bool $useLogin
609 * @param array $createParams
610 * @param array $submitParams
611 * @param null|string $expectedFailure
612 * @param int $expectedJobCount
613 * @dataProvider submitProvider
615 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
617 $this->createLoggedInUser();
620 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
621 $createParams['footer_id'] = $this->footer
['id'];
624 $id = $this->createDraftMailing($createParams);
626 $submitParams['id'] = $id;
627 if ($expectedFailure) {
628 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
629 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
632 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__
, __FILE__
);
633 $this->assertTrue(is_numeric($submitResult['id']));
634 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
635 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
637 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
638 1 => array($id, 'Integer'),
643 * Test unsubscribe list contains correct groups
644 * when include = 'previous mailing'
646 public function testUnsubscribeGroupList() {
647 // Create set of groups and add a contact to both of them.
648 $groupID2 = $this->groupCreate(array('name' => 'Test group 2', 'title' => 'group title 2'));
649 $groupID3 = $this->groupCreate(array('name' => 'Test group 3', 'title' => 'group title 3'));
650 $contactId = $this->individualCreate();
651 foreach (array($groupID2, $groupID3) as $grp) {
653 'contact_id' => $contactId,
656 $this->callAPISuccess('GroupContact', 'create', $params);
659 //Send mail to groupID3
660 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
661 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $groupID3);
662 $this->callAPISuccess($this->_entity
, 'send_test', $params);
665 'mailing_id' => $mail['id'],
666 'entity_table' => 'civicrm_group',
667 'entity_id' => $groupID3,
668 'group_type' => 'Include',
670 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
672 //Include previous mail in the mailing group.
673 $mail2 = $this->callAPISuccess('mailing', 'create', $this->_params
);
674 $params = array('mailing_id' => $mail2['id'], 'test_email' => NULL, 'test_group' => $groupID3);
675 $this->callAPISuccess($this->_entity
, 'send_test', $params);
678 'mailing_id' => $mail2['id'],
679 'entity_table' => 'civicrm_mailing',
680 'entity_id' => $mail['id'],
681 'group_type' => 'Include',
683 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
684 //CRM-20431 - Delete group id that matches first mailing id.
685 $this->callAPISuccess('Group', 'delete', array('id' => $this->_groupID
));
686 $jobId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_MailingJob', $mail2['id'], 'id', 'mailing_id');
687 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'hash', 'job_id');
688 $queueId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'id', 'job_id');
690 $group = CRM_Mailing_Event_BAO_Unsubscribe
::unsub_from_mailing($jobId, $queueId, $hash, TRUE);
691 //Assert only one group returns in the unsubscribe list.
692 $this->assertCount(1, $group);
693 $this->assertEquals($groupID3, key($group));
699 public function testMailerStats() {
700 $result = $this->groupContactCreate($this->_groupID
, 100);
701 //verify if 100 contacts are added for group
702 $this->assertEquals(100, $result['added']);
704 //Create and send test mail first and change the mail job to live,
705 //because stats api only works on live mail
706 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
707 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
);
708 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
709 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
711 //Change the test mail into live
712 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
713 CRM_Core_DAO
::executeQuery($sql);
715 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
716 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
717 (event_queue_id int, time_stamp datetime, delivered_id int)
718 SELECT event_queue_id, time_stamp, id
719 FROM civicrm_mailing_event_delivered
720 WHERE id IN ($deliveredIds)
721 ORDER BY RAND() LIMIT 0,20;";
722 CRM_Core_DAO
::executeQuery($sql);
724 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
725 CRM_Core_DAO
::executeQuery($sql);
727 if ($type == 'unsubscribe') {
728 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
729 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
732 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
733 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
735 CRM_Core_DAO
::executeQuery($sql);
738 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
739 $expectedResult = array(
740 //since among 100 mails 20 has been bounced
744 'Unique Clicks' => 0,
745 'Unsubscribers' => 20,
746 'delivered_rate' => '80%',
747 'opened_rate' => '25%',
748 'clickthrough_rate' => '0%',
750 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
754 * Test civicrm_mailing_delete.
756 public function testMailerDeleteSuccess() {
757 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
758 $this->callAPIAndDocument($this->_entity
, 'delete', array('id' => $result['id']), __FUNCTION__
, __FILE__
);
759 $this->assertAPIDeleted($this->_entity
, $result['id']);
763 * Test Mailing.gettokens.
765 public function testMailGetTokens() {
766 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
767 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
768 $result = $this->callAPIAndDocument($this->_entity
, 'gettokens', array('entity' => array('Contact', 'Mailing')), __FUNCTION__
, __FILE__
, $description);
769 $this->assertContains('Contact Type', $result['values']);
771 // Check that passing "sequential" correctly outputs a hierarchical array
772 $result = $this->callAPISuccess($this->_entity
, 'gettokens', array('entity' => 'contact', 'sequential' => 1));
773 $this->assertArrayHasKey('text', $result['values'][0]);
774 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
777 public function testClone() {
779 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
780 $contactIDs['include_me'] = $this->individualCreate(array(
781 'email' => 'include.me@example.org',
782 'first_name' => 'Includer',
783 'last_name' => 'Person',
785 $this->callAPISuccess('GroupContact', 'create', array(
786 'group_id' => $groupIDs['inc'],
787 'contact_id' => $contactIDs['include_me'],
790 $params = $this->_params
;
791 $params['groups']['include'] = array($groupIDs['inc']);
792 $params['groups']['exclude'] = array();
793 $params['mailings']['include'] = array();
794 $params['mailings']['exclude'] = array();
797 $create = $this->callAPISuccess('Mailing', 'create', $params);
798 $created = $this->callAPISuccess('Mailing', 'get', []);
799 $createId = $create['id'];
800 $this->createLoggedInUser();
801 $clone = $this->callAPIAndDocument('Mailing', 'clone', array('id' => $create['id']), __FUNCTION__
, __FILE__
);
802 $cloneId = $clone['id'];
804 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
805 $this->assertTrue(is_numeric($cloneId));
807 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
808 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
810 // created_id is special - populated based on current user (ie the cloner).
811 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
812 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
814 // Target groups+mailings are special.
815 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $cloneId, 'sequential' => 1));
816 $this->assertEquals(1, $cloneGroups['count']);
817 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
818 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
819 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
822 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
824 //------------ civicrm_mailing_event_bounce methods------------
827 * Test civicrm_mailing_event_bounce with wrong params.
828 * Note that tests like this are slightly better than no test but an
829 * api function cannot be considered supported / 'part of the api' without a
832 public function testMailerBounceWrongParams() {
834 'job_id' => 'Wrong ID',
835 'event_queue_id' => 'Wrong ID',
836 'hash' => 'Wrong Hash',
838 'time_stamp' => '20111109212100',
840 $this->callAPIFailure('mailing_event', 'bounce', $params,
841 'Queue event could not be found'
845 //----------- civicrm_mailing_event_confirm methods -----------
848 * Test civicrm_mailing_event_confirm with wrong params.
849 * Note that tests like this are slightly better than no test but an
850 * api function cannot be considered supported / 'part of the api' without a
853 public function testMailerConfirmWrongParams() {
855 'contact_id' => 'Wrong ID',
856 'subscribe_id' => 'Wrong ID',
857 'hash' => 'Wrong Hash',
858 'event_subscribe_id' => '123',
859 'time_stamp' => '20111111010101',
861 $this->callAPIFailure('mailing_event', 'confirm', $params,
862 'contact_id is not a valid integer'
866 //---------- civicrm_mailing_event_reply methods -----------
869 * Test civicrm_mailing_event_reply with wrong params.
871 * Note that tests like this are slightly better than no test but an
872 * api function cannot be considered supported / 'part of the api' without a
875 public function testMailerReplyWrongParams() {
877 'job_id' => 'Wrong ID',
878 'event_queue_id' => 'Wrong ID',
879 'hash' => 'Wrong Hash',
880 'bodyTxt' => 'Body...',
881 'replyTo' => $this->_email
,
882 'time_stamp' => '20111111010101',
884 $this->callAPIFailure('mailing_event', 'reply', $params,
885 'Queue event could not be found'
889 //----------- civicrm_mailing_event_forward methods ----------
892 * Test civicrm_mailing_event_forward with wrong params.
893 * Note that tests like this are slightly better than no test but an
894 * api function cannot be considered supported / 'part of the api' without a
897 public function testMailerForwardWrongParams() {
899 'job_id' => 'Wrong ID',
900 'event_queue_id' => 'Wrong ID',
901 'hash' => 'Wrong Hash',
902 'email' => $this->_email
,
903 'time_stamp' => '20111111010101',
905 $this->callAPIFailure('mailing_event', 'forward', $params,
906 'Queue event could not be found'
911 * @param array $params
912 * Extra parameters for the draft mailing.
915 public function createDraftMailing($params = array()) {
916 $createParams = array_merge($this->_params
, $params);
917 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
918 $this->assertTrue(is_numeric($createResult['id']));
919 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
920 1 => array($createResult['id'], 'Integer'),
922 return $createResult['id'];
926 * Test to make sure that if the event queue hashes have been archived,
927 * we can still have working click-trough URLs working (CRM-17959).
929 public function testUrlWithMissingTrackingHash() {
930 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
931 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $mail['id']));
932 $this->assertEquals(1, $jobs['count']);
934 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
935 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
937 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
938 FROM civicrm_mailing_trackable_url as turl
939 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
940 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
941 ORDER BY turl.id DESC LIMIT 1";
943 $dao = CRM_Core_DAO
::executeQuery($sql);
944 $this->assertTrue($dao->fetch());
946 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
947 $this->assertContains('https://civicrm.org', $url);
949 // Now delete the event queue hashes and see if the tracking still works.
950 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
952 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
953 $this->assertContains('https://civicrm.org', $url);
955 // Ensure that Google CSS link is not tracked.
956 $sql = "SELECT id FROM civicrm_mailing_trackable_url where url = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Zilla+Slab:500,700'";
957 $this->assertEquals([], CRM_Core_DAO
::executeQuery($sql)->fetchAll());
961 * Test Trackable URL with unicode character
963 public function testTrackableURLWithUnicodeSign() {
964 $unicodeURL = "https://civiĆcrm.org";
965 $this->_params
['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_text']);
966 $this->_params
['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_html']);
968 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'));
970 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
971 $this->callAPISuccess($this->_entity
, 'send_test', $params);
973 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
974 FROM civicrm_mailing_trackable_url as turl
975 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
976 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
977 ORDER BY turl.id DESC LIMIT 1";
979 $dao = CRM_Core_DAO
::executeQuery($sql);
980 $this->assertTrue($dao->fetch());
982 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
983 $this->assertContains($unicodeURL, $url);
985 // Now delete the event queue hashes and see if the tracking still works.
986 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
988 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
989 $this->assertContains($unicodeURL, $url);
993 * CRM-20892 : Test if Mail.create API throws error on update,
994 * if modified_date less then the date when the mail was last updated/created
996 public function testModifiedDateMismatchOnMailingUpdate() {
997 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('modified_date' => 'now'));
999 $this->callAPISuccess('mailing', 'create', $this->_params +
array('id' => $mail['id'], 'modified_date' => '2 seconds ago'));
1001 catch (Exception
$e) {
1002 $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());