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');
91 public function testTemplateTypeOptions() {
92 $types = $this->callAPISuccess('Mailing', 'getoptions', array('field' => 'template_type'));
93 $this->assertTrue(isset($types['values']['traditional']));
97 * The `template_options` field should be treated a JSON object.
99 * This test will create, read, and update the field.
101 public function testMailerCreateTemplateOptions() {
102 // 1. Create mailing with template_options.
103 $params = $this->_params
;
104 $params['template_options'] = json_encode(array('foo' => 'bar_1'));
105 $createResult = $this->callAPISuccess('mailing', 'create', $params);
106 $id = $createResult['id'];
107 $this->assertDBQuery('{"foo":"bar_1"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
108 1 => array($id, 'Int'),
110 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
112 // 2. Get mailing with template_options.
113 $getResult = $this->callAPISuccess('mailing', 'get', array(
116 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
117 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', array(
119 'return' => 'template_options',
121 $this->assertEquals('bar_1', $getValueResult['foo']);
123 // 3. Update mailing with template_options.
124 $updateResult = $this->callAPISuccess('mailing', 'create', array(
126 'template_options' => array('foo' => 'bar_2'),
128 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
129 1 => array($id, 'Int'),
131 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
135 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
136 * Make sure these work
138 public function testMagicGroups_create_update() {
140 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
141 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
142 $contactIDs['a'] = $this->individualCreate(array(
143 'email' => 'include.me@example.org',
144 'first_name' => 'Includer',
145 'last_name' => 'Person',
147 $contactIDs['b'] = $this->individualCreate(array(
148 'email' => 'exclude.me@example.org',
149 'last_name' => 'Excluder',
151 $this->callAPISuccess('GroupContact', 'create', array(
152 'group_id' => $groupIDs['a'],
153 'contact_id' => $contactIDs['a'],
155 $this->callAPISuccess('GroupContact', 'create', array(
156 'group_id' => $groupIDs['b'],
157 'contact_id' => $contactIDs['b'],
162 $createParams = $this->_params
;
163 $createParams['groups']['include'] = array($groupIDs['a']);
164 $createParams['groups']['exclude'] = array();
165 $createParams['mailings']['include'] = array();
166 $createParams['mailings']['exclude'] = array();
167 $createParams['api.mailing_job.create'] = 1;
168 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
169 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
170 $getGroup1_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup1['values']));
171 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
172 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
173 $getRecipient1_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient1['values']));
174 $this->assertEquals(array($contactIDs['a']), $getRecipient1_ids);
176 // ** Pass 2: Update without any changes to groups[include]
177 $nullOpParams = $createParams;
178 $nullOpParams['id'] = $createResult['id'];
179 $updateParams['api.mailing_job.create'] = 1;
180 unset($nullOpParams['groups']['include']);
181 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
182 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
183 $getGroup2_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup2['values']));
184 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
185 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
186 $getRecip2_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient2['values']));
187 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
189 // ** Pass 3: Update with different groups[include]
190 $updateParams = $createParams;
191 $updateParams['id'] = $createResult['id'];
192 $updateParams['groups']['include'] = array($groupIDs['b']);
193 $updateParams['api.mailing_job.create'] = 1;
194 $this->callAPISuccess('Mailing', 'create', $updateParams);
195 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
196 $getGroup3_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup3['values']));
197 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
198 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
199 $getRecipient3_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient3['values']));
200 $this->assertEquals(array($contactIDs['b']), $getRecipient3_ids);
203 public function testMailerPreview() {
205 $contactID = $this->individualCreate();
206 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
207 $displayName = $displayName['values'][$contactID]['display_name'];
208 $this->assertTrue(!empty($displayName));
210 $params = $this->_params
;
211 $params['api.Mailing.preview'] = array(
213 'contact_id' => $contactID,
215 $params['options']['force_rollback'] = 1;
219 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
220 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
221 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
222 'recipient' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
224 $result = $this->callAPISuccess('mailing', 'create', $params);
225 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
226 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
227 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
228 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
230 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
231 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
232 $this->assertContains("This is $displayName", $previewResult['values']['body_text']);
233 $this->assertContains("<p>This is $displayName.</p>", $previewResult['values']['body_html']);
236 public function testMailerPreviewRecipients() {
238 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
239 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
240 $contactIDs['include_me'] = $this->individualCreate(array(
241 'email' => 'include.me@example.org',
242 'first_name' => 'Includer',
243 'last_name' => 'Person',
245 $contactIDs['exclude_me'] = $this->individualCreate(array(
246 'email' => 'exclude.me@example.org',
247 'last_name' => 'Excluder',
249 $this->callAPISuccess('GroupContact', 'create', array(
250 'group_id' => $groupIDs['inc'],
251 'contact_id' => $contactIDs['include_me'],
253 $this->callAPISuccess('GroupContact', 'create', array(
254 'group_id' => $groupIDs['inc'],
255 'contact_id' => $contactIDs['exclude_me'],
257 $this->callAPISuccess('GroupContact', 'create', array(
258 'group_id' => $groupIDs['exc'],
259 'contact_id' => $contactIDs['exclude_me'],
262 $params = $this->_params
;
263 $params['groups']['include'] = array($groupIDs['inc']);
264 $params['groups']['exclude'] = array($groupIDs['exc']);
265 $params['mailings']['include'] = array();
266 $params['mailings']['exclude'] = array();
267 $params['options']['force_rollback'] = 1;
268 $params['api.mailing_job.create'] = 1;
269 $params['api.MailingRecipients.get'] = array(
270 'mailing_id' => '$value.id',
271 'api.contact.getvalue' => array(
272 'return' => 'display_name',
274 'api.email.getvalue' => array(
281 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
282 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
283 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
285 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__
, __FILE__
);
286 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
287 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
288 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
290 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
291 $previewIds = array_values(CRM_Utils_Array
::collect('contact_id', $preview['values']));
292 $this->assertEquals(array((string) $contactIDs['include_me']), $previewIds);
293 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
294 $this->assertEquals(array('include.me@example.org'), $previewEmails);
295 $previewNames = array_values(CRM_Utils_Array
::collect('api.contact.getvalue', $preview['values']));
296 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
299 public function testMailerPreviewRecipientsDeduplicate() {
301 $groupIDs['grp'] = $this->groupCreate(array('name' => 'Example group', 'title' => 'Example group'));
302 $contactIDs['include_me'] = $this->individualCreate(array(
303 'email' => 'include.me@example.org',
304 'first_name' => 'Includer',
305 'last_name' => 'Person',
307 $contactIDs['include_me_duplicate'] = $this->individualCreate(array(
308 'email' => 'include.me@example.org',
309 'first_name' => 'IncluderDuplicate',
310 'last_name' => 'Person',
312 $this->callAPISuccess('GroupContact', 'create', array(
313 'group_id' => $groupIDs['grp'],
314 'contact_id' => $contactIDs['include_me'],
316 $this->callAPISuccess('GroupContact', 'create', array(
317 'group_id' => $groupIDs['grp'],
318 'contact_id' => $contactIDs['include_me_duplicate'],
321 $params = $this->_params
;
322 $params['groups']['include'] = array($groupIDs['grp']);
323 $params['mailings']['include'] = array();
324 $params['options']['force_rollback'] = 1;
325 $params['dedupe_email'] = 1;
326 $params['api.mailing_job.create'] = 1;
327 $params['api.MailingRecipients.get'] = array(
328 'mailing_id' => '$value.id',
329 'api.contact.getvalue' => array(
330 'return' => 'display_name',
332 'api.email.getvalue' => array(
338 $create = $this->callAPISuccess('Mailing', 'create', $params);
340 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
341 $this->assertEquals(1, $preview['count']);
342 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
343 $this->assertEquals(array('include.me@example.org'), $previewEmails);
349 public function testMailerSendTest_email() {
350 $contactIDs['alice'] = $this->individualCreate(array(
351 'email' => 'alice@example.org',
352 'first_name' => 'Alice',
353 'last_name' => 'Person',
356 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
358 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
359 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
360 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
362 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
363 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
365 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
366 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
372 public function testMailerSendTest_group() {
374 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
375 $contactIDs['alice'] = $this->individualCreate(array(
376 'email' => 'alice@example.org',
377 'first_name' => 'Alice',
378 'last_name' => 'Person',
380 $contactIDs['bob'] = $this->individualCreate(array(
381 'email' => 'bob@example.org',
382 'first_name' => 'Bob',
383 'last_name' => 'Person',
385 $contactIDs['carol'] = $this->individualCreate(array(
386 'email' => 'carol@example.org',
387 'first_name' => 'Carol',
388 'last_name' => 'Person',
390 $this->callAPISuccess('GroupContact', 'create', array(
391 'group_id' => $groupIDs['inc'],
392 'contact_id' => $contactIDs['alice'],
394 $this->callAPISuccess('GroupContact', 'create', array(
395 'group_id' => $groupIDs['inc'],
396 'contact_id' => $contactIDs['bob'],
398 $this->callAPISuccess('GroupContact', 'create', array(
399 'group_id' => $groupIDs['inc'],
400 'contact_id' => $contactIDs['carol'],
404 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
405 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', array(
406 'mailing_id' => $mail['id'],
407 'test_email' => NULL,
408 'test_group' => $groupIDs['inc'],
410 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
); // verify mail has been sent to user by count
412 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
413 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
415 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
416 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
422 public function submitProvider() {
423 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
426 array(), // createParams
427 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
428 FALSE, // expectedFailure
429 1, // expectedJobCount
433 array(), // createParams
434 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
435 "/Failed to determine current user/", // expectedFailure
436 0, // expectedJobCount
440 array(), // createParams
441 array('scheduled_date' => '2014-12-13 10:00:00'),
442 FALSE, // expectedFailure
443 1, // expectedJobCount
447 array(), // createParams
449 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
450 0, // expectedJobCount
454 array('name' => ''), // createParams
455 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
456 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./", // expectedFailure
457 0, // expectedJobCount
461 array('body_html' => '', 'body_text' => ''), // createParams
462 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
463 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./", // expectedFailure
464 0, // expectedJobCount
468 array('body_html' => 'Oops, did I leave my tokens at home?'), // createParams
469 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
470 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./", // expectedFailure
471 0, // expectedJobCount
475 array('body_text' => 'Oops, did I leave my tokens at home?'), // createParams
476 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
477 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./", // expectedFailure
478 0, // expectedJobCount
482 array('body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'), // 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('body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'), // createParams
490 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
491 FALSE, // expectedFailure
492 1, // expectedJobCount
498 * @param bool $useLogin
499 * @param array $createParams
500 * @param array $submitParams
501 * @param null|string $expectedFailure
502 * @param int $expectedJobCount
503 * @dataProvider submitProvider
505 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
507 $this->createLoggedInUser();
510 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
511 $createParams['footer_id'] = $this->footer
['id'];
514 $id = $this->createDraftMailing($createParams);
516 $submitParams['id'] = $id;
517 if ($expectedFailure) {
518 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
519 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
522 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__
, __FILE__
);
523 $this->assertTrue(is_numeric($submitResult['id']));
524 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
525 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
527 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
528 1 => array($id, 'Integer'),
535 public function testMailerStats() {
536 $result = $this->groupContactCreate($this->_groupID
, 100);
537 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
539 //Create and send test mail first and change the mail job to live,
540 //because stats api only works on live mail
541 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
542 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
);
543 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
544 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
546 //Change the test mail into live
547 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
548 CRM_Core_DAO
::executeQuery($sql);
550 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
551 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
552 (event_queue_id int, time_stamp datetime, delivered_id int)
553 SELECT event_queue_id, time_stamp, id
554 FROM civicrm_mailing_event_delivered
555 WHERE id IN ($deliveredIds)
556 ORDER BY RAND() LIMIT 0,20;";
557 CRM_Core_DAO
::executeQuery($sql);
559 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
560 CRM_Core_DAO
::executeQuery($sql);
562 if ($type == 'unsubscribe') {
563 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
564 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
567 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
568 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
570 CRM_Core_DAO
::executeQuery($sql);
573 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
574 $expectedResult = array(
575 'Delivered' => 80, //since among 100 mails 20 has been bounced
578 'Unique Clicks' => 0,
579 'Unsubscribers' => 20,
581 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
585 * Test civicrm_mailing_delete.
587 public function testMailerDeleteSuccess() {
588 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
589 $this->callAPIAndDocument($this->_entity
, 'delete', array('id' => $result['id']), __FUNCTION__
, __FILE__
);
590 $this->assertAPIDeleted($this->_entity
, $result['id']);
594 * Test Mailing.gettokens.
596 public function testMailGetTokens() {
597 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
598 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
599 $result = $this->callAPIAndDocument($this->_entity
, 'gettokens', array('entity' => array('Contact', 'Mailing')), __FUNCTION__
, __FILE__
, $description);
600 $this->assertContains('Contact Type', $result['values']);
602 // Check that passing "sequential" correctly outputs a hierarchical array
603 $result = $this->callAPISuccess($this->_entity
, 'gettokens', array('entity' => 'contact', 'sequential' => 1));
604 $this->assertArrayHasKey('text', $result['values'][0]);
605 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
608 public function testClone() {
610 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
611 $contactIDs['include_me'] = $this->individualCreate(array(
612 'email' => 'include.me@example.org',
613 'first_name' => 'Includer',
614 'last_name' => 'Person',
616 $this->callAPISuccess('GroupContact', 'create', array(
617 'group_id' => $groupIDs['inc'],
618 'contact_id' => $contactIDs['include_me'],
621 $params = $this->_params
;
622 $params['groups']['include'] = array($groupIDs['inc']);
623 $params['groups']['exclude'] = array();
624 $params['mailings']['include'] = array();
625 $params['mailings']['exclude'] = array();
628 $create = $this->callAPISuccess('Mailing', 'create', $params);
629 $createId = $create['id'];
630 $this->createLoggedInUser();
631 $clone = $this->callAPIAndDocument('Mailing', 'clone', array('id' => $create['id']), __FUNCTION__
, __FILE__
);
632 $cloneId = $clone['id'];
634 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
635 $this->assertTrue(is_numeric($cloneId));
637 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
638 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
640 // created_id is special - populated based on current user (ie the cloner).
641 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
642 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
644 // Target groups+mailings are special.
645 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $cloneId, 'sequential' => 1));
646 $this->assertEquals(1, $cloneGroups['count']);
647 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
648 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
649 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
652 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
654 //------------ civicrm_mailing_event_bounce methods------------
657 * Test civicrm_mailing_event_bounce with wrong params.
658 * Note that tests like this are slightly better than no test but an
659 * api function cannot be considered supported / 'part of the api' without a
662 public function testMailerBounceWrongParams() {
664 'job_id' => 'Wrong ID',
665 'event_queue_id' => 'Wrong ID',
666 'hash' => 'Wrong Hash',
668 'time_stamp' => '20111109212100',
670 $this->callAPIFailure('mailing_event', 'bounce', $params,
671 'Queue event could not be found'
675 //----------- civicrm_mailing_event_confirm methods -----------
678 * Test civicrm_mailing_event_confirm with wrong params.
679 * Note that tests like this are slightly better than no test but an
680 * api function cannot be considered supported / 'part of the api' without a
683 public function testMailerConfirmWrongParams() {
685 'contact_id' => 'Wrong ID',
686 'subscribe_id' => 'Wrong ID',
687 'hash' => 'Wrong Hash',
688 'event_subscribe_id' => '123',
689 'time_stamp' => '20111111010101',
691 $this->callAPIFailure('mailing_event', 'confirm', $params,
692 'contact_id is not a valid integer'
696 //---------- civicrm_mailing_event_reply methods -----------
699 * Test civicrm_mailing_event_reply with wrong params.
701 * Note that tests like this are slightly better than no test but an
702 * api function cannot be considered supported / 'part of the api' without a
705 public function testMailerReplyWrongParams() {
707 'job_id' => 'Wrong ID',
708 'event_queue_id' => 'Wrong ID',
709 'hash' => 'Wrong Hash',
710 'bodyTxt' => 'Body...',
711 'replyTo' => $this->_email
,
712 'time_stamp' => '20111111010101',
714 $this->callAPIFailure('mailing_event', 'reply', $params,
715 'Queue event could not be found'
720 //----------- civicrm_mailing_event_forward methods ----------
723 * Test civicrm_mailing_event_forward with wrong params.
724 * Note that tests like this are slightly better than no test but an
725 * api function cannot be considered supported / 'part of the api' without a
728 public function testMailerForwardWrongParams() {
730 'job_id' => 'Wrong ID',
731 'event_queue_id' => 'Wrong ID',
732 'hash' => 'Wrong Hash',
733 'email' => $this->_email
,
734 'time_stamp' => '20111111010101',
736 $this->callAPIFailure('mailing_event', 'forward', $params,
737 'Queue event could not be found'
742 * @param array $params
743 * Extra parameters for the draft mailing.
746 public function createDraftMailing($params = array()) {
747 $createParams = array_merge($this->_params
, $params);
748 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
749 $this->assertTrue(is_numeric($createResult['id']));
750 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
751 1 => array($createResult['id'], 'Integer'),
753 return $createResult['id'];
757 * Test to make sure that if the event queue hashes have been archived,
758 * we can still have working click-trough URLs working (CRM-17959).
760 public function testUrlWithMissingTrackingHash() {
761 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'), __FUNCTION__
, __FILE__
);
762 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $mail['id']));
763 $this->assertEquals(1, $jobs['count']);
765 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
766 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
768 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
769 FROM civicrm_mailing_trackable_url as turl
770 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
771 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
772 ORDER BY turl.id DESC LIMIT 1";
774 $dao = CRM_Core_DAO
::executeQuery($sql);
775 $this->assertTrue($dao->fetch());
777 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
778 $this->assertContains('https://civicrm.org', $url);
780 // Now delete the event queue hashes and see if the tracking still works.
781 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
783 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
784 $this->assertContains('https://civicrm.org', $url);
788 * Test Trackable URL with unicode character
790 public function testTrackableURLWithUnicodeSign() {
791 $unicodeURL = "https://civiĆcrm.org";
792 $this->_params
['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_text']);
793 $this->_params
['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_html']);
795 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
array('scheduled_date' => 'now'));
797 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
798 $this->callAPISuccess($this->_entity
, 'send_test', $params);
800 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
801 FROM civicrm_mailing_trackable_url as turl
802 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
803 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
804 ORDER BY turl.id DESC LIMIT 1";
806 $dao = CRM_Core_DAO
::executeQuery($sql);
807 $this->assertTrue($dao->fetch());
809 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
810 $this->assertContains($unicodeURL, $url);
812 // Now delete the event queue hashes and see if the tracking still works.
813 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
815 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
816 $this->assertContains($unicodeURL, $url);