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