Merge pull request #9121 from totten/master-zanzibar
[civicrm-core.git] / tests / phpunit / api / v3 / MailingTest.php
1 <?php
2 /*
3 * File for the TestMailing class
4 *
5 * (PHP 5)
6 *
7 * @package CiviCRM
8 *
9 * This file is part of CiviCRM
10 *
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.
15 *
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.
20 *
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/>.
24 */
25
26
27 /**
28 * Test APIv3 civicrm_mailing_* functions
29 *
30 * @package CiviCRM
31 * @group headless
32 */
33 class api_v3_MailingTest extends CiviUnitTestCase {
34 protected $_groupID;
35 protected $_email;
36 protected $_apiversion = 3;
37 protected $_params = array();
38 protected $_entity = 'Mailing';
39 protected $_contactID;
40
41 /**
42 * APIv3 result from creating an example footer
43 * @var array
44 */
45 protected $footer;
46
47 public function setUp() {
48 parent::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,
60 'header_id' => '',
61 'footer_id' => '',
62 );
63
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}.',
69 ));
70 }
71
72 public function tearDown() {
73 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
74 parent::tearDown();
75 }
76
77 /**
78 * Test civicrm_mailing_create.
79 */
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');
86 }
87
88 /**
89 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
90 * Make sure these work
91 */
92 public function testMagicGroups_create_update() {
93 // BEGIN SAMPLE DATA
94 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
95 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
96 $contactIDs['a'] = $this->individualCreate(array(
97 'email' => 'include.me@example.org',
98 'first_name' => 'Includer',
99 'last_name' => 'Person',
100 ));
101 $contactIDs['b'] = $this->individualCreate(array(
102 'email' => 'exclude.me@example.org',
103 'last_name' => 'Excluder',
104 ));
105 $this->callAPISuccess('GroupContact', 'create', array(
106 'group_id' => $groupIDs['a'],
107 'contact_id' => $contactIDs['a'],
108 ));
109 $this->callAPISuccess('GroupContact', 'create', array(
110 'group_id' => $groupIDs['b'],
111 'contact_id' => $contactIDs['b'],
112 ));
113 // END SAMPLE DATA
114
115 // ** Pass 1: Create
116 $createParams = $this->_params;
117 $createParams['groups']['include'] = array($groupIDs['a']);
118 $createParams['groups']['exclude'] = array();
119 $createParams['mailings']['include'] = array();
120 $createParams['mailings']['exclude'] = array();
121 $createParams['api.mailing_job.create'] = 1;
122 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
123 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
124 $getGroup1_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup1['values']));
125 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
126 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
127 $getRecipient1_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient1['values']));
128 $this->assertEquals(array($contactIDs['a']), $getRecipient1_ids);
129
130 // ** Pass 2: Update without any changes to groups[include]
131 $nullOpParams = $createParams;
132 $nullOpParams['id'] = $createResult['id'];
133 $updateParams['api.mailing_job.create'] = 1;
134 unset($nullOpParams['groups']['include']);
135 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
136 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
137 $getGroup2_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup2['values']));
138 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
139 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
140 $getRecip2_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient2['values']));
141 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
142
143 // ** Pass 3: Update with different groups[include]
144 $updateParams = $createParams;
145 $updateParams['id'] = $createResult['id'];
146 $updateParams['groups']['include'] = array($groupIDs['b']);
147 $updateParams['api.mailing_job.create'] = 1;
148 $this->callAPISuccess('Mailing', 'create', $updateParams);
149 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
150 $getGroup3_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup3['values']));
151 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
152 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
153 $getRecipient3_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient3['values']));
154 $this->assertEquals(array($contactIDs['b']), $getRecipient3_ids);
155 }
156
157 public function testMailerPreview() {
158 // BEGIN SAMPLE DATA
159 $contactID = $this->individualCreate();
160 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
161 $displayName = $displayName['values'][$contactID]['display_name'];
162 $this->assertTrue(!empty($displayName));
163
164 $params = $this->_params;
165 $params['api.Mailing.preview'] = array(
166 'id' => '$value.id',
167 'contact_id' => $contactID,
168 );
169 $params['options']['force_rollback'] = 1;
170 // END SAMPLE DATA
171
172 $maxIDs = array(
173 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
174 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
175 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
176 'recipient' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
177 );
178 $result = $this->callAPISuccess('mailing', 'create', $params);
179 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
180 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
181 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
182 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
183
184 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
185 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
186 $this->assertContains("This is $displayName", $previewResult['values']['body_text']);
187 $this->assertContains("<p>This is $displayName.</p>", $previewResult['values']['body_html']);
188 }
189
190 public function testMailerPreviewRecipients() {
191 // BEGIN SAMPLE DATA
192 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
193 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
194 $contactIDs['include_me'] = $this->individualCreate(array(
195 'email' => 'include.me@example.org',
196 'first_name' => 'Includer',
197 'last_name' => 'Person',
198 ));
199 $contactIDs['exclude_me'] = $this->individualCreate(array(
200 'email' => 'exclude.me@example.org',
201 'last_name' => 'Excluder',
202 ));
203 $this->callAPISuccess('GroupContact', 'create', array(
204 'group_id' => $groupIDs['inc'],
205 'contact_id' => $contactIDs['include_me'],
206 ));
207 $this->callAPISuccess('GroupContact', 'create', array(
208 'group_id' => $groupIDs['inc'],
209 'contact_id' => $contactIDs['exclude_me'],
210 ));
211 $this->callAPISuccess('GroupContact', 'create', array(
212 'group_id' => $groupIDs['exc'],
213 'contact_id' => $contactIDs['exclude_me'],
214 ));
215
216 $params = $this->_params;
217 $params['groups']['include'] = array($groupIDs['inc']);
218 $params['groups']['exclude'] = array($groupIDs['exc']);
219 $params['mailings']['include'] = array();
220 $params['mailings']['exclude'] = array();
221 $params['options']['force_rollback'] = 1;
222 $params['api.mailing_job.create'] = 1;
223 $params['api.MailingRecipients.get'] = array(
224 'mailing_id' => '$value.id',
225 'api.contact.getvalue' => array(
226 'return' => 'display_name',
227 ),
228 'api.email.getvalue' => array(
229 'return' => 'email',
230 ),
231 );
232 // END SAMPLE DATA
233
234 $maxIDs = array(
235 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
236 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
237 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
238 );
239 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__, __FILE__);
240 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
241 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
242 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
243
244 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
245 $previewIds = array_values(CRM_Utils_Array::collect('contact_id', $preview['values']));
246 $this->assertEquals(array((string) $contactIDs['include_me']), $previewIds);
247 $previewEmails = array_values(CRM_Utils_Array::collect('api.email.getvalue', $preview['values']));
248 $this->assertEquals(array('include.me@example.org'), $previewEmails);
249 $previewNames = array_values(CRM_Utils_Array::collect('api.contact.getvalue', $preview['values']));
250 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
251 }
252
253 /**
254 *
255 */
256 public function testMailerSendTest_email() {
257 $contactIDs['alice'] = $this->individualCreate(array(
258 'email' => 'alice@example.org',
259 'first_name' => 'Alice',
260 'last_name' => 'Person',
261 ));
262
263 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
264
265 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
266 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
267 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
268
269 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
270 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
271
272 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
273 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
274 }
275
276 /**
277 *
278 */
279 public function testMailerSendTest_group() {
280 // BEGIN SAMPLE DATA
281 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
282 $contactIDs['alice'] = $this->individualCreate(array(
283 'email' => 'alice@example.org',
284 'first_name' => 'Alice',
285 'last_name' => 'Person',
286 ));
287 $contactIDs['bob'] = $this->individualCreate(array(
288 'email' => 'bob@example.org',
289 'first_name' => 'Bob',
290 'last_name' => 'Person',
291 ));
292 $contactIDs['carol'] = $this->individualCreate(array(
293 'email' => 'carol@example.org',
294 'first_name' => 'Carol',
295 'last_name' => 'Person',
296 ));
297 $this->callAPISuccess('GroupContact', 'create', array(
298 'group_id' => $groupIDs['inc'],
299 'contact_id' => $contactIDs['alice'],
300 ));
301 $this->callAPISuccess('GroupContact', 'create', array(
302 'group_id' => $groupIDs['inc'],
303 'contact_id' => $contactIDs['bob'],
304 ));
305 $this->callAPISuccess('GroupContact', 'create', array(
306 'group_id' => $groupIDs['inc'],
307 'contact_id' => $contactIDs['carol'],
308 ));
309 // END SAMPLE DATA
310
311 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
312 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', array(
313 'mailing_id' => $mail['id'],
314 'test_email' => NULL,
315 'test_group' => $groupIDs['inc'],
316 ));
317 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
318
319 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
320 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
321
322 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
323 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
324 }
325
326 /**
327 * @return array
328 */
329 public function submitProvider() {
330 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
331 $cases[] = array(
332 TRUE, //useLogin
333 array(), // createParams
334 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
335 FALSE, // expectedFailure
336 1, // expectedJobCount
337 );
338 $cases[] = array(
339 FALSE, //useLogin
340 array(), // createParams
341 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
342 "/Failed to determine current user/", // expectedFailure
343 0, // expectedJobCount
344 );
345 $cases[] = array(
346 TRUE, //useLogin
347 array(), // createParams
348 array('scheduled_date' => '2014-12-13 10:00:00'),
349 FALSE, // expectedFailure
350 1, // expectedJobCount
351 );
352 $cases[] = array(
353 TRUE, //useLogin
354 array(), // createParams
355 array(),
356 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
357 0, // expectedJobCount
358 );
359 $cases[] = array(
360 TRUE, //useLogin
361 array('name' => ''), // createParams
362 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
363 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./", // expectedFailure
364 0, // expectedJobCount
365 );
366 $cases[] = array(
367 TRUE, //useLogin
368 array('body_html' => '', 'body_text' => ''), // createParams
369 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
370 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./", // expectedFailure
371 0, // expectedJobCount
372 );
373 $cases[] = array(
374 TRUE, //useLogin
375 array('body_html' => 'Oops, did I leave my tokens at home?'), // createParams
376 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
377 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./", // expectedFailure
378 0, // expectedJobCount
379 );
380 $cases[] = array(
381 TRUE, //useLogin
382 array('body_text' => 'Oops, did I leave my tokens at home?'), // createParams
383 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
384 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./", // expectedFailure
385 0, // expectedJobCount
386 );
387 $cases[] = array(
388 TRUE, //useLogin
389 array('body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'), // createParams
390 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
391 FALSE, // expectedFailure
392 1, // expectedJobCount
393 );
394 $cases[] = array(
395 TRUE, //useLogin
396 array('body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'), // createParams
397 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
398 FALSE, // expectedFailure
399 1, // expectedJobCount
400 );
401 return $cases;
402 }
403
404 /**
405 * @param bool $useLogin
406 * @param array $createParams
407 * @param array $submitParams
408 * @param null|string $expectedFailure
409 * @param int $expectedJobCount
410 * @dataProvider submitProvider
411 */
412 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
413 if ($useLogin) {
414 $this->createLoggedInUser();
415 }
416
417 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
418 $createParams['footer_id'] = $this->footer['id'];
419 }
420
421 $id = $this->createDraftMailing($createParams);
422
423 $submitParams['id'] = $id;
424 if ($expectedFailure) {
425 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
426 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
427 }
428 else {
429 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__, __FILE__);
430 $this->assertTrue(is_numeric($submitResult['id']));
431 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
432 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
433 }
434 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
435 1 => array($id, 'Integer'),
436 ));
437 }
438
439 /**
440 *
441 */
442 public function testMailerStats() {
443 $result = $this->groupContactCreate($this->_groupID, 100);
444 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
445
446 //Create and send test mail first and change the mail job to live,
447 //because stats api only works on live mail
448 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
449 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID);
450 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
451 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
452
453 //Change the test mail into live
454 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
455 CRM_Core_DAO::executeQuery($sql);
456
457 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
458 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
459 (event_queue_id int, time_stamp datetime, delivered_id int)
460 SELECT event_queue_id, time_stamp, id
461 FROM civicrm_mailing_event_delivered
462 WHERE id IN ($deliveredIds)
463 ORDER BY RAND() LIMIT 0,20;";
464 CRM_Core_DAO::executeQuery($sql);
465
466 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
467 CRM_Core_DAO::executeQuery($sql);
468
469 if ($type == 'unsubscribe') {
470 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
471 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
472 }
473 else {
474 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
475 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
476 }
477 CRM_Core_DAO::executeQuery($sql);
478 }
479
480 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
481 $expectedResult = array(
482 'Delivered' => 80, //since among 100 mails 20 has been bounced
483 'Bounces' => 20,
484 'Opened' => 20,
485 'Unique Clicks' => 0,
486 'Unsubscribers' => 20,
487 );
488 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
489 }
490
491 /**
492 * Test civicrm_mailing_delete.
493 */
494 public function testMailerDeleteSuccess() {
495 $result = $this->callAPISuccess($this->_entity, 'create', $this->_params);
496 $this->callAPIAndDocument($this->_entity, 'delete', array('id' => $result['id']), __FUNCTION__, __FILE__);
497 $this->assertAPIDeleted($this->_entity, $result['id']);
498 }
499
500 /**
501 * Test Mailing.gettokens.
502 */
503 public function testMailGetTokens() {
504 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
505 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
506 $result = $this->callAPIAndDocument($this->_entity, 'gettokens', array('entity' => array('Contact', 'Mailing')), __FUNCTION__, __FILE__, $description);
507 $this->assertContains('Contact Type', $result['values']);
508
509 // Check that passing "sequential" correctly outputs a hierarchical array
510 $result = $this->callAPISuccess($this->_entity, 'gettokens', array('entity' => 'contact', 'sequential' => 1));
511 $this->assertArrayHasKey('text', $result['values'][0]);
512 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
513 }
514
515 public function testClone() {
516 // BEGIN SAMPLE DATA
517 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
518 $contactIDs['include_me'] = $this->individualCreate(array(
519 'email' => 'include.me@example.org',
520 'first_name' => 'Includer',
521 'last_name' => 'Person',
522 ));
523 $this->callAPISuccess('GroupContact', 'create', array(
524 'group_id' => $groupIDs['inc'],
525 'contact_id' => $contactIDs['include_me'],
526 ));
527
528 $params = $this->_params;
529 $params['groups']['include'] = array($groupIDs['inc']);
530 $params['groups']['exclude'] = array();
531 $params['mailings']['include'] = array();
532 $params['mailings']['exclude'] = array();
533 // END SAMPLE DATA
534
535 $create = $this->callAPISuccess('Mailing', 'create', $params);
536 $createId = $create['id'];
537 $this->createLoggedInUser();
538 $clone = $this->callAPIAndDocument('Mailing', 'clone', array('id' => $create['id']), __FUNCTION__, __FILE__);
539 $cloneId = $clone['id'];
540
541 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
542 $this->assertTrue(is_numeric($cloneId));
543
544 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
545 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
546
547 // created_id is special - populated based on current user (ie the cloner).
548 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
549 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
550
551 // Target groups+mailings are special.
552 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $cloneId, 'sequential' => 1));
553 $this->assertEquals(1, $cloneGroups['count']);
554 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
555 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
556 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
557 }
558
559 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
560
561 //------------ civicrm_mailing_event_bounce methods------------
562
563 /**
564 * Test civicrm_mailing_event_bounce with wrong params.
565 * Note that tests like this are slightly better than no test but an
566 * api function cannot be considered supported / 'part of the api' without a
567 * success test
568 */
569 public function testMailerBounceWrongParams() {
570 $params = array(
571 'job_id' => 'Wrong ID',
572 'event_queue_id' => 'Wrong ID',
573 'hash' => 'Wrong Hash',
574 'body' => 'Body...',
575 'time_stamp' => '20111109212100',
576 );
577 $this->callAPIFailure('mailing_event', 'bounce', $params,
578 'Queue event could not be found'
579 );
580 }
581
582 //----------- civicrm_mailing_event_confirm methods -----------
583
584 /**
585 * Test civicrm_mailing_event_confirm with wrong params.
586 * Note that tests like this are slightly better than no test but an
587 * api function cannot be considered supported / 'part of the api' without a
588 * success test
589 */
590 public function testMailerConfirmWrongParams() {
591 $params = array(
592 'contact_id' => 'Wrong ID',
593 'subscribe_id' => 'Wrong ID',
594 'hash' => 'Wrong Hash',
595 'event_subscribe_id' => '123',
596 'time_stamp' => '20111111010101',
597 );
598 $this->callAPIFailure('mailing_event', 'confirm', $params,
599 'contact_id is not a valid integer'
600 );
601 }
602
603 //---------- civicrm_mailing_event_reply methods -----------
604
605 /**
606 * Test civicrm_mailing_event_reply with wrong params.
607 *
608 * Note that tests like this are slightly better than no test but an
609 * api function cannot be considered supported / 'part of the api' without a
610 * success test
611 */
612 public function testMailerReplyWrongParams() {
613 $params = array(
614 'job_id' => 'Wrong ID',
615 'event_queue_id' => 'Wrong ID',
616 'hash' => 'Wrong Hash',
617 'bodyTxt' => 'Body...',
618 'replyTo' => $this->_email,
619 'time_stamp' => '20111111010101',
620 );
621 $this->callAPIFailure('mailing_event', 'reply', $params,
622 'Queue event could not be found'
623 );
624 }
625
626
627 //----------- civicrm_mailing_event_forward methods ----------
628
629 /**
630 * Test civicrm_mailing_event_forward with wrong params.
631 * Note that tests like this are slightly better than no test but an
632 * api function cannot be considered supported / 'part of the api' without a
633 * success test
634 */
635 public function testMailerForwardWrongParams() {
636 $params = array(
637 'job_id' => 'Wrong ID',
638 'event_queue_id' => 'Wrong ID',
639 'hash' => 'Wrong Hash',
640 'email' => $this->_email,
641 'time_stamp' => '20111111010101',
642 );
643 $this->callAPIFailure('mailing_event', 'forward', $params,
644 'Queue event could not be found'
645 );
646 }
647
648 /**
649 * @param array $params
650 * Extra parameters for the draft mailing.
651 * @return array|int
652 */
653 public function createDraftMailing($params = array()) {
654 $createParams = array_merge($this->_params, $params);
655 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__, __FILE__);
656 $this->assertTrue(is_numeric($createResult['id']));
657 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
658 1 => array($createResult['id'], 'Integer'),
659 ));
660 return $createResult['id'];
661 }
662
663 /**
664 * Test to make sure that if the event queue hashes have been archived,
665 * we can still have working click-trough URLs working (CRM-17959).
666 */
667 public function testUrlWithMissingTrackingHash() {
668 $mail = $this->callAPIAndDocument('mailing', 'create', $this->_params + array('scheduled_date' => 'now'), __FUNCTION__, __FILE__);
669 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $mail['id']));
670 $this->assertEquals(1, $jobs['count']);
671
672 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
673 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
674
675 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
676 FROM civicrm_mailing_trackable_url as turl
677 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
678 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
679 ORDER BY turl.id DESC LIMIT 1";
680
681 $dao = CRM_Core_DAO::executeQuery($sql);
682 $this->assertTrue($dao->fetch());
683
684 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
685 $this->assertContains('https://civicrm.org', $url);
686
687 // Now delete the event queue hashes and see if the tracking still works.
688 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_mailing_event_queue');
689
690 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
691 $this->assertContains('https://civicrm.org', $url);
692 }
693
694 /**
695 * Test Trackable URL with unicode character
696 */
697 public function testTrackableURLWithUnicodeSign() {
698 $unicodeURL = "https://civiƄcrm.org";
699 $this->_params['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params['body_text']);
700 $this->_params['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params['body_html']);
701
702 $mail = $this->callAPIAndDocument('mailing', 'create', $this->_params + array('scheduled_date' => 'now'), __FUNCTION__, __FILE__);
703
704 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
705 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
706
707 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
708 FROM civicrm_mailing_trackable_url as turl
709 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
710 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
711 ORDER BY turl.id DESC LIMIT 1";
712
713 $dao = CRM_Core_DAO::executeQuery($sql);
714 $this->assertTrue($dao->fetch());
715
716 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
717 $this->assertContains($unicodeURL, $url);
718
719 // Now delete the event queue hashes and see if the tracking still works.
720 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_mailing_event_queue');
721
722 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
723 $this->assertContains($unicodeURL, $url);
724 }
725
726 }