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