Merge pull request #10006 from JMAConsulting/CRM-20022
[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 *
90 */
91 public function testTemplateTypeOptions() {
92 $types = $this->callAPISuccess('Mailing', 'getoptions', array('field' => 'template_type'));
93 $this->assertTrue(isset($types['values']['traditional']));
94 }
95
96 /**
97 * The `template_options` field should be treated a JSON object.
98 *
99 * This test will create, read, and update the field.
100 */
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'),
109 ));
110 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
111
112 // 2. Get mailing with template_options.
113 $getResult = $this->callAPISuccess('mailing', 'get', array(
114 'id' => $id,
115 ));
116 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
117 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', array(
118 'id' => $id,
119 'return' => 'template_options',
120 ));
121 $this->assertEquals('bar_1', $getValueResult['foo']);
122
123 // 3. Update mailing with template_options.
124 $updateResult = $this->callAPISuccess('mailing', 'create', array(
125 'id' => $id,
126 'template_options' => array('foo' => 'bar_2'),
127 ));
128 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
129 1 => array($id, 'Int'),
130 ));
131 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
132 }
133
134 /**
135 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
136 * Make sure these work
137 */
138 public function testMagicGroups_create_update() {
139 // BEGIN SAMPLE DATA
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',
146 ));
147 $contactIDs['b'] = $this->individualCreate(array(
148 'email' => 'exclude.me@example.org',
149 'last_name' => 'Excluder',
150 ));
151 $this->callAPISuccess('GroupContact', 'create', array(
152 'group_id' => $groupIDs['a'],
153 'contact_id' => $contactIDs['a'],
154 ));
155 $this->callAPISuccess('GroupContact', 'create', array(
156 'group_id' => $groupIDs['b'],
157 'contact_id' => $contactIDs['b'],
158 ));
159 // END SAMPLE DATA
160
161 // ** Pass 1: Create
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);
175
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);
188
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);
201 }
202
203 public function testMailerPreview() {
204 // BEGIN SAMPLE DATA
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));
209
210 $params = $this->_params;
211 $params['api.Mailing.preview'] = array(
212 'id' => '$value.id',
213 'contact_id' => $contactID,
214 );
215 $params['options']['force_rollback'] = 1;
216 // END SAMPLE DATA
217
218 $maxIDs = array(
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'),
223 );
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'
229
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']);
234 }
235
236 public function testMailerPreviewRecipients() {
237 // BEGIN SAMPLE DATA
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',
244 ));
245 $contactIDs['exclude_me'] = $this->individualCreate(array(
246 'email' => 'exclude.me@example.org',
247 'last_name' => 'Excluder',
248 ));
249 $this->callAPISuccess('GroupContact', 'create', array(
250 'group_id' => $groupIDs['inc'],
251 'contact_id' => $contactIDs['include_me'],
252 ));
253 $this->callAPISuccess('GroupContact', 'create', array(
254 'group_id' => $groupIDs['inc'],
255 'contact_id' => $contactIDs['exclude_me'],
256 ));
257 $this->callAPISuccess('GroupContact', 'create', array(
258 'group_id' => $groupIDs['exc'],
259 'contact_id' => $contactIDs['exclude_me'],
260 ));
261
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',
273 ),
274 'api.email.getvalue' => array(
275 'return' => 'email',
276 ),
277 );
278 // END SAMPLE DATA
279
280 $maxIDs = 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'),
284 );
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'
289
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] . '"');
297 }
298
299 public function testMailerPreviewRecipientsDeduplicate() {
300 // BEGIN SAMPLE DATA
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',
306 ));
307 $contactIDs['include_me_duplicate'] = $this->individualCreate(array(
308 'email' => 'include.me@example.org',
309 'first_name' => 'IncluderDuplicate',
310 'last_name' => 'Person',
311 ));
312 $this->callAPISuccess('GroupContact', 'create', array(
313 'group_id' => $groupIDs['grp'],
314 'contact_id' => $contactIDs['include_me'],
315 ));
316 $this->callAPISuccess('GroupContact', 'create', array(
317 'group_id' => $groupIDs['grp'],
318 'contact_id' => $contactIDs['include_me_duplicate'],
319 ));
320
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',
331 ),
332 'api.email.getvalue' => array(
333 'return' => 'email',
334 ),
335 );
336 // END SAMPLE DATA
337
338 $create = $this->callAPISuccess('Mailing', 'create', $params);
339
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);
344 }
345
346 /**
347 *
348 */
349 public function testMailerSendTest_email() {
350 $contactIDs['alice'] = $this->individualCreate(array(
351 'email' => 'alice@example.org',
352 'first_name' => 'Alice',
353 'last_name' => 'Person',
354 ));
355
356 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
357
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
361
362 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
363 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
364
365 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
366 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
367 }
368
369 /**
370 *
371 */
372 public function testMailerSendTest_group() {
373 // BEGIN SAMPLE DATA
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',
379 ));
380 $contactIDs['bob'] = $this->individualCreate(array(
381 'email' => 'bob@example.org',
382 'first_name' => 'Bob',
383 'last_name' => 'Person',
384 ));
385 $contactIDs['carol'] = $this->individualCreate(array(
386 'email' => 'carol@example.org',
387 'first_name' => 'Carol',
388 'last_name' => 'Person',
389 ));
390 $this->callAPISuccess('GroupContact', 'create', array(
391 'group_id' => $groupIDs['inc'],
392 'contact_id' => $contactIDs['alice'],
393 ));
394 $this->callAPISuccess('GroupContact', 'create', array(
395 'group_id' => $groupIDs['inc'],
396 'contact_id' => $contactIDs['bob'],
397 ));
398 $this->callAPISuccess('GroupContact', 'create', array(
399 'group_id' => $groupIDs['inc'],
400 'contact_id' => $contactIDs['carol'],
401 ));
402 // END SAMPLE DATA
403
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'],
409 ));
410 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
411
412 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
413 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
414
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);
417 }
418
419 /**
420 * @return array
421 */
422 public function submitProvider() {
423 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
424 $cases[] = array(
425 TRUE, //useLogin
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
430 );
431 $cases[] = array(
432 FALSE, //useLogin
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
437 );
438 $cases[] = array(
439 TRUE, //useLogin
440 array(), // createParams
441 array('scheduled_date' => '2014-12-13 10:00:00'),
442 FALSE, // expectedFailure
443 1, // expectedJobCount
444 );
445 $cases[] = array(
446 TRUE, //useLogin
447 array(), // createParams
448 array(),
449 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
450 0, // expectedJobCount
451 );
452 $cases[] = array(
453 TRUE, //useLogin
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
458 );
459 $cases[] = array(
460 TRUE, //useLogin
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
465 );
466 $cases[] = array(
467 TRUE, //useLogin
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
472 );
473 $cases[] = array(
474 TRUE, //useLogin
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
479 );
480 $cases[] = array(
481 TRUE, //useLogin
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
486 );
487 $cases[] = array(
488 TRUE, //useLogin
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
493 );
494 return $cases;
495 }
496
497 /**
498 * @param bool $useLogin
499 * @param array $createParams
500 * @param array $submitParams
501 * @param null|string $expectedFailure
502 * @param int $expectedJobCount
503 * @dataProvider submitProvider
504 */
505 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
506 if ($useLogin) {
507 $this->createLoggedInUser();
508 }
509
510 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
511 $createParams['footer_id'] = $this->footer['id'];
512 }
513
514 $id = $this->createDraftMailing($createParams);
515
516 $submitParams['id'] = $id;
517 if ($expectedFailure) {
518 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
519 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
520 }
521 else {
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']);
526 }
527 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
528 1 => array($id, 'Integer'),
529 ));
530 }
531
532 /**
533 *
534 */
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
538
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']));
545
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);
549
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);
558
559 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
560 CRM_Core_DAO::executeQuery($sql);
561
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";
565 }
566 else {
567 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
568 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
569 }
570 CRM_Core_DAO::executeQuery($sql);
571 }
572
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
576 'Bounces' => 20,
577 'Opened' => 20,
578 'Unique Clicks' => 0,
579 'Unsubscribers' => 20,
580 );
581 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
582 }
583
584 /**
585 * Test civicrm_mailing_delete.
586 */
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']);
591 }
592
593 /**
594 * Test Mailing.gettokens.
595 */
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']);
601
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]);
606 }
607
608 public function testClone() {
609 // BEGIN SAMPLE DATA
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',
615 ));
616 $this->callAPISuccess('GroupContact', 'create', array(
617 'group_id' => $groupIDs['inc'],
618 'contact_id' => $contactIDs['include_me'],
619 ));
620
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();
626 // END SAMPLE DATA
627
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'];
633
634 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
635 $this->assertTrue(is_numeric($cloneId));
636
637 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
638 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
639
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');
643
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']);
650 }
651
652 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
653
654 //------------ civicrm_mailing_event_bounce methods------------
655
656 /**
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
660 * success test
661 */
662 public function testMailerBounceWrongParams() {
663 $params = array(
664 'job_id' => 'Wrong ID',
665 'event_queue_id' => 'Wrong ID',
666 'hash' => 'Wrong Hash',
667 'body' => 'Body...',
668 'time_stamp' => '20111109212100',
669 );
670 $this->callAPIFailure('mailing_event', 'bounce', $params,
671 'Queue event could not be found'
672 );
673 }
674
675 //----------- civicrm_mailing_event_confirm methods -----------
676
677 /**
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
681 * success test
682 */
683 public function testMailerConfirmWrongParams() {
684 $params = array(
685 'contact_id' => 'Wrong ID',
686 'subscribe_id' => 'Wrong ID',
687 'hash' => 'Wrong Hash',
688 'event_subscribe_id' => '123',
689 'time_stamp' => '20111111010101',
690 );
691 $this->callAPIFailure('mailing_event', 'confirm', $params,
692 'contact_id is not a valid integer'
693 );
694 }
695
696 //---------- civicrm_mailing_event_reply methods -----------
697
698 /**
699 * Test civicrm_mailing_event_reply with wrong params.
700 *
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
703 * success test
704 */
705 public function testMailerReplyWrongParams() {
706 $params = array(
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',
713 );
714 $this->callAPIFailure('mailing_event', 'reply', $params,
715 'Queue event could not be found'
716 );
717 }
718
719
720 //----------- civicrm_mailing_event_forward methods ----------
721
722 /**
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
726 * success test
727 */
728 public function testMailerForwardWrongParams() {
729 $params = array(
730 'job_id' => 'Wrong ID',
731 'event_queue_id' => 'Wrong ID',
732 'hash' => 'Wrong Hash',
733 'email' => $this->_email,
734 'time_stamp' => '20111111010101',
735 );
736 $this->callAPIFailure('mailing_event', 'forward', $params,
737 'Queue event could not be found'
738 );
739 }
740
741 /**
742 * @param array $params
743 * Extra parameters for the draft mailing.
744 * @return array|int
745 */
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'),
752 ));
753 return $createResult['id'];
754 }
755
756 /**
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).
759 */
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']);
764
765 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
766 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
767
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";
773
774 $dao = CRM_Core_DAO::executeQuery($sql);
775 $this->assertTrue($dao->fetch());
776
777 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
778 $this->assertContains('https://civicrm.org', $url);
779
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');
782
783 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
784 $this->assertContains('https://civicrm.org', $url);
785 }
786
787 /**
788 * Test Trackable URL with unicode character
789 */
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']);
794
795 $mail = $this->callAPISuccess('mailing', 'create', $this->_params + array('scheduled_date' => 'now'));
796
797 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
798 $this->callAPISuccess($this->_entity, 'send_test', $params);
799
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";
805
806 $dao = CRM_Core_DAO::executeQuery($sql);
807 $this->assertTrue($dao->fetch());
808
809 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
810 $this->assertContains($unicodeURL, $url);
811
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');
814
815 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
816 $this->assertContains($unicodeURL, $url);
817 }
818
819 }