Merge pull request #13983 from seamuslee001/new_coder_tests
[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 // DGW
51 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0;
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}.\nhttps://civicrm.org\n{domain.address}{action.optOutUrl}",
58 'body_html' => "<link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Zilla+Slab:500,700' rel='stylesheet' type='text/css'><p>This is {contact.display_name}.</p><p><a href='https://civicrm.org/'>CiviCRM.org</a></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 'name' => 'test domain footer',
67 'component_type' => 'footer',
68 'body_html' => '<p>From {domain.address}. To opt out, go to {action.optOutUrl}.</p>',
69 'body_text' => 'From {domain.address}. To opt out, go to {action.optOutUrl}.',
70 ));
71 }
72
73 public function tearDown() {
74 // DGW
75 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0;
76 parent::tearDown();
77 }
78
79 /**
80 * Test civicrm_mailing_create.
81 */
82 public function testMailerCreateSuccess() {
83 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params + array('scheduled_date' => 'now'), __FUNCTION__, __FILE__);
84 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
85 $this->assertEquals(1, $jobs['count']);
86 // return isn't working on this in getAndCheck so lets not check it for now
87 unset($this->_params['created_id']);
88 $this->getAndCheck($this->_params, $result['id'], 'mailing');
89 }
90
91 /**
92 * Tes that the parameter _skip_evil_bao_auto_schedule_ is respected & prevents jobs being created.
93 */
94 public function testSkipAutoSchedule() {
95 $this->callAPISuccess('Mailing', 'create', array_merge($this->_params, [
96 '_skip_evil_bao_auto_schedule_' => TRUE,
97 'scheduled_date' => 'now',
98 ]));
99 $this->callAPISuccessGetCount('Mailing', [], 1);
100 $this->callAPISuccessGetCount('MailingJob', [], 0);
101 }
102
103 /**
104 * Create a completed mailing (e.g when importing from a provider).
105 */
106 public function testMailerCreateCompleted() {
107 $this->_params['body_html'] = 'I am completed so it does not matter if there is an opt out link since I have already been sent by another system';
108 $this->_params['is_completed'] = 1;
109 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params + array('scheduled_date' => 'now'), __FUNCTION__, __FILE__);
110 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
111 $this->assertEquals(1, $jobs['count']);
112 $this->assertEquals('Complete', $jobs['values'][$jobs['id']]['status']);
113 // return isn't working on this in getAndCheck so lets not check it for now
114 unset($this->_params['created_id']);
115 $this->getAndCheck($this->_params, $result['id'], 'mailing');
116 }
117
118 /**
119 * Per CRM-20316 the mailing should still create without created_id (not mandatory).
120 */
121 public function testMailerCreateSuccessNoCreatedID() {
122 unset($this->_params['created_id']);
123 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params + array('scheduled_date' => 'now'), __FUNCTION__, __FILE__);
124 $this->getAndCheck($this->_params, $result['id'], 'mailing');
125 }
126
127 /**
128 *
129 */
130 public function testTemplateTypeOptions() {
131 $types = $this->callAPISuccess('Mailing', 'getoptions', array('field' => 'template_type'));
132 $this->assertTrue(isset($types['values']['traditional']));
133 }
134
135 /**
136 * The `template_options` field should be treated a JSON object.
137 *
138 * This test will create, read, and update the field.
139 */
140 public function testMailerCreateTemplateOptions() {
141 // 1. Create mailing with template_options.
142 $params = $this->_params;
143 $params['template_options'] = json_encode(array('foo' => 'bar_1'));
144 $createResult = $this->callAPISuccess('mailing', 'create', $params);
145 $id = $createResult['id'];
146 $this->assertDBQuery('{"foo":"bar_1"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
147 1 => array($id, 'Int'),
148 ));
149 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
150
151 // 2. Get mailing with template_options.
152 $getResult = $this->callAPISuccess('mailing', 'get', array(
153 'id' => $id,
154 ));
155 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
156 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', array(
157 'id' => $id,
158 'return' => 'template_options',
159 ));
160 $this->assertEquals('bar_1', $getValueResult['foo']);
161
162 // 3. Update mailing with template_options.
163 $updateResult = $this->callAPISuccess('mailing', 'create', array(
164 'id' => $id,
165 'template_options' => array('foo' => 'bar_2'),
166 ));
167 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', array(
168 1 => array($id, 'Int'),
169 ));
170 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
171 }
172
173 /**
174 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
175 * Make sure these work
176 */
177 public function testMagicGroups_create_update() {
178 // BEGIN SAMPLE DATA
179 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
180 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
181 $contactIDs['a'] = $this->individualCreate(array(
182 'email' => 'include.me@example.org',
183 'first_name' => 'Includer',
184 'last_name' => 'Person',
185 ));
186 $contactIDs['b'] = $this->individualCreate(array(
187 'email' => 'exclude.me@example.org',
188 'last_name' => 'Excluder',
189 ));
190 $this->callAPISuccess('GroupContact', 'create', array(
191 'group_id' => $groupIDs['a'],
192 'contact_id' => $contactIDs['a'],
193 ));
194 $this->callAPISuccess('GroupContact', 'create', array(
195 'group_id' => $groupIDs['b'],
196 'contact_id' => $contactIDs['b'],
197 ));
198 // END SAMPLE DATA
199
200 // ** Pass 1: Create
201 $createParams = $this->_params;
202 $createParams['groups']['include'] = [$groupIDs['a']];
203 $createParams['groups']['exclude'] = [];
204 $createParams['mailings']['include'] = [];
205 $createParams['mailings']['exclude'] = [];
206 $createParams['scheduled_date'] = 'now';
207 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
208 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
209 $getGroup1_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup1['values']));
210 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
211 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
212 $getRecipient1_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient1['values']));
213 $this->assertEquals(array($contactIDs['a']), $getRecipient1_ids);
214
215 // ** Pass 2: Update without any changes to groups[include]
216 $nullOpParams = $createParams;
217 $nullOpParams['id'] = $createResult['id'];
218 $updateParams['api.mailing_job.create'] = 1;
219 unset($nullOpParams['groups']['include']);
220 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
221 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
222 $getGroup2_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup2['values']));
223 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
224 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
225 $getRecip2_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient2['values']));
226 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
227
228 // ** Pass 3: Update with different groups[include]
229 $updateParams = $createParams;
230 $updateParams['id'] = $createResult['id'];
231 $updateParams['groups']['include'] = array($groupIDs['b']);
232 $updateParams['scheduled_date'] = 'now';
233 $this->callAPISuccess('Mailing', 'create', $updateParams);
234 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
235 $getGroup3_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup3['values']));
236 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
237 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
238 $getRecipient3_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecipient3['values']));
239 $this->assertEquals(array($contactIDs['b']), $getRecipient3_ids);
240 }
241
242 public function testMailerPreview() {
243 // BEGIN SAMPLE DATA
244 $contactID = $this->individualCreate();
245 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
246 $displayName = $displayName['values'][$contactID]['display_name'];
247 $this->assertTrue(!empty($displayName));
248
249 $params = $this->_params;
250 $params['api.Mailing.preview'] = array(
251 'id' => '$value.id',
252 'contact_id' => $contactID,
253 );
254 $params['options']['force_rollback'] = 1;
255 // END SAMPLE DATA
256
257 $maxIDs = array(
258 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
259 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
260 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
261 'recipient' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
262 );
263 $result = $this->callAPISuccess('mailing', 'create', $params);
264 // 'Preview should not create any mailing records'
265 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing');
266 // 'Preview should not create any mailing_job record'
267 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job');
268 // 'Preview should not create any mailing_group records'
269 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group');
270 // 'Preview should not create any mailing_recipient records'
271 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients');
272
273 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
274 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
275 $this->assertContains("This is $displayName", $previewResult['values']['body_text']);
276 $this->assertContains("<p>This is $displayName.</p>", $previewResult['values']['body_html']);
277 }
278
279 public function testMailerPreviewRecipients() {
280 // BEGIN SAMPLE DATA
281 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
282 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
283 $contactIDs['include_me'] = $this->individualCreate(array(
284 'email' => 'include.me@example.org',
285 'first_name' => 'Includer',
286 'last_name' => 'Person',
287 ));
288 $contactIDs['exclude_me'] = $this->individualCreate(array(
289 'email' => 'exclude.me@example.org',
290 'last_name' => 'Excluder',
291 ));
292 $this->callAPISuccess('GroupContact', 'create', array(
293 'group_id' => $groupIDs['inc'],
294 'contact_id' => $contactIDs['include_me'],
295 ));
296 $this->callAPISuccess('GroupContact', 'create', array(
297 'group_id' => $groupIDs['inc'],
298 'contact_id' => $contactIDs['exclude_me'],
299 ));
300 $this->callAPISuccess('GroupContact', 'create', array(
301 'group_id' => $groupIDs['exc'],
302 'contact_id' => $contactIDs['exclude_me'],
303 ));
304
305 $params = $this->_params;
306 $params['groups']['include'] = array($groupIDs['inc']);
307 $params['groups']['exclude'] = array($groupIDs['exc']);
308 $params['mailings']['include'] = array();
309 $params['mailings']['exclude'] = array();
310 $params['options']['force_rollback'] = 1;
311 $params['api.MailingRecipients.get'] = array(
312 'mailing_id' => '$value.id',
313 'api.contact.getvalue' => array(
314 'return' => 'display_name',
315 ),
316 'api.email.getvalue' => array(
317 'return' => 'email',
318 ),
319 );
320 // END SAMPLE DATA
321
322 $maxIDs = array(
323 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
324 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
325 );
326 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__, __FILE__);
327 // 'Preview should not create any mailing records'
328 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing');
329 // 'Preview should not create any mailing_group records'
330 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group');
331
332 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
333 $previewIds = array_values(CRM_Utils_Array::collect('contact_id', $preview['values']));
334 $this->assertEquals(array((string) $contactIDs['include_me']), $previewIds);
335 $previewEmails = array_values(CRM_Utils_Array::collect('api.email.getvalue', $preview['values']));
336 $this->assertEquals(array('include.me@example.org'), $previewEmails);
337 $previewNames = array_values(CRM_Utils_Array::collect('api.contact.getvalue', $preview['values']));
338 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
339 }
340
341 /**
342 * Test if Mailing recipients include duplicate OR on_hold emails
343 */
344 public function testMailerPreviewRecipientsDeduplicateAndOnholdEmails() {
345 // BEGIN SAMPLE DATA
346 $groupIDs['grp'] = $this->groupCreate(array('name' => 'Example group', 'title' => 'Example group'));
347 $contactIDs['include_me'] = $this->individualCreate(array(
348 'email' => 'include.me@example.org',
349 'first_name' => 'Includer',
350 'last_name' => 'Person',
351 ));
352 $contactIDs['include_me_duplicate'] = $this->individualCreate(array(
353 'email' => 'include.me@example.org',
354 'first_name' => 'IncluderDuplicate',
355 'last_name' => 'Person',
356 ));
357
358 $contactIDs['include_me_onhold'] = $this->individualCreate(array(
359 'email' => 'onholdinclude.me@example.org',
360 'first_name' => 'Onhold',
361 'last_name' => 'Person',
362 ));
363 $emailId = $this->callAPISuccessGetValue('Email', array(
364 'return' => 'id',
365 'contact_id' => $contactIDs['include_me_onhold'],
366 ));
367 $this->callAPISuccess('Email', 'create', array(
368 'id' => $emailId,
369 'on_hold' => 1,
370 ));
371
372 $this->callAPISuccess('GroupContact', 'create', array(
373 'group_id' => $groupIDs['grp'],
374 'contact_id' => $contactIDs['include_me'],
375 ));
376 $this->callAPISuccess('GroupContact', 'create', array(
377 'group_id' => $groupIDs['grp'],
378 'contact_id' => $contactIDs['include_me_duplicate'],
379 ));
380 $this->callAPISuccess('GroupContact', 'create', array(
381 'group_id' => $groupIDs['grp'],
382 'contact_id' => $contactIDs['include_me_onhold'],
383 ));
384
385 $params = $this->_params;
386 $params['groups']['include'] = array($groupIDs['grp']);
387 $params['mailings']['include'] = array();
388 $params['options']['force_rollback'] = 1;
389 $params['dedupe_email'] = 1;
390 $params['api.MailingRecipients.get'] = array(
391 'mailing_id' => '$value.id',
392 'api.contact.getvalue' => array(
393 'return' => 'display_name',
394 ),
395 'api.email.getvalue' => array(
396 'return' => 'email',
397 ),
398 );
399 // END SAMPLE DATA
400
401 $create = $this->callAPISuccess('Mailing', 'create', $params);
402
403 //Recipient should not contain duplicate or on_hold emails.
404 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
405 $this->assertEquals(1, $preview['count']);
406 $previewEmails = array_values(CRM_Utils_Array::collect('api.email.getvalue', $preview['values']));
407 $this->assertEquals(array('include.me@example.org'), $previewEmails);
408 }
409
410 /**
411 * Test sending a test mailing.
412 */
413 public function testMailerSendTest_email() {
414 $contactIDs['alice'] = $this->individualCreate(array(
415 'email' => 'alice@example.org',
416 'first_name' => 'Alice',
417 'last_name' => 'Person',
418 ));
419
420 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
421
422 $params = array('mailing_id' => $mail['id'], 'test_email' => 'ALicE@example.org', 'test_group' => NULL);
423 // Per https://lab.civicrm.org/dev/core/issues/229 ensure this is not passed through!
424 // Per https://lab.civicrm.org/dev/mail/issues/32 test non-lowercase email
425 $params['id'] = $mail['id'];
426 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
427 // verify mail has been sent to user by count
428 $this->assertEquals(1, $deliveredInfo['count']);
429
430 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
431 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
432
433 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
434 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
435 }
436
437 /**
438 *
439 */
440 public function testMailerSendTest_group() {
441 // BEGIN SAMPLE DATA
442 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
443 $contactIDs['alice'] = $this->individualCreate(array(
444 'email' => 'alice@example.org',
445 'first_name' => 'Alice',
446 'last_name' => 'Person',
447 ));
448 $contactIDs['bob'] = $this->individualCreate(array(
449 'email' => 'bob@example.org',
450 'first_name' => 'Bob',
451 'last_name' => 'Person',
452 ));
453 $contactIDs['carol'] = $this->individualCreate(array(
454 'email' => 'carol@example.org',
455 'first_name' => 'Carol',
456 'last_name' => 'Person',
457 ));
458 $this->callAPISuccess('GroupContact', 'create', array(
459 'group_id' => $groupIDs['inc'],
460 'contact_id' => $contactIDs['alice'],
461 ));
462 $this->callAPISuccess('GroupContact', 'create', array(
463 'group_id' => $groupIDs['inc'],
464 'contact_id' => $contactIDs['bob'],
465 ));
466 $this->callAPISuccess('GroupContact', 'create', array(
467 'group_id' => $groupIDs['inc'],
468 'contact_id' => $contactIDs['carol'],
469 ));
470 // END SAMPLE DATA
471
472 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
473 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', array(
474 'mailing_id' => $mail['id'],
475 'test_email' => NULL,
476 'test_group' => $groupIDs['inc'],
477 ));
478 // verify mail has been sent to user by count
479 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__);
480
481 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
482 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
483
484 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
485 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
486 }
487
488 /**
489 * @return array
490 */
491 public function submitProvider() {
492 // $useLogin, $params, $expectedFailure, $expectedJobCount
493 $cases = array();
494 $cases[] = array(
495 //useLogin
496 TRUE,
497 // createParams
498 array(),
499 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
500 // expectedFailure
501 FALSE,
502 // expectedJobCount
503 1,
504 );
505 $cases[] = array(
506 //useLogin
507 FALSE,
508 // createParams
509 array(),
510 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
511 // expectedFailure
512 "/Failed to determine current user/",
513 // expectedJobCount
514 0,
515 );
516 $cases[] = array(
517 //useLogin
518 TRUE,
519 // createParams
520 array(),
521 array('scheduled_date' => '2014-12-13 10:00:00'),
522 // expectedFailure
523 FALSE,
524 // expectedJobCount
525 1,
526 );
527 $cases[] = array(
528 //useLogin
529 TRUE,
530 // createParams
531 array(),
532 array(),
533 // expectedFailure
534 "/Missing parameter scheduled_date and.or approval_date/",
535 // expectedJobCount
536 0,
537 );
538 $cases[] = array(
539 //useLogin
540 TRUE,
541 // createParams
542 array('name' => ''),
543 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
544 // expectedFailure
545 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./",
546 // expectedJobCount
547 0,
548 );
549 $cases[] = array(
550 //useLogin
551 TRUE,
552 // createParams
553 array('body_html' => '', 'body_text' => ''),
554 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
555 // expectedFailure
556 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./",
557 // expectedJobCount
558 0,
559 );
560 $cases[] = array(
561 //useLogin
562 TRUE,
563 // createParams
564 array('body_html' => 'Oops, did I leave my tokens at home?'),
565 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
566 // expectedFailure
567 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./",
568 // expectedJobCount
569 0,
570 );
571 $cases[] = array(
572 //useLogin
573 TRUE,
574 // createParams
575 array('body_text' => 'Oops, did I leave my tokens at home?'),
576 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
577 // expectedFailure
578 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./",
579 // expectedJobCount
580 0,
581 );
582 $cases[] = array(
583 //useLogin
584 TRUE,
585 // createParams
586 array('body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'),
587 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
588 // expectedFailure
589 FALSE,
590 // expectedJobCount
591 1,
592 );
593 $cases[] = array(
594 //useLogin
595 TRUE,
596 // createParams
597 array('body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'),
598 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
599 // expectedFailure
600 FALSE,
601 // expectedJobCount
602 1,
603 );
604 return $cases;
605 }
606
607 /**
608 * @param bool $useLogin
609 * @param array $createParams
610 * @param array $submitParams
611 * @param null|string $expectedFailure
612 * @param int $expectedJobCount
613 * @dataProvider submitProvider
614 */
615 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
616 if ($useLogin) {
617 $this->createLoggedInUser();
618 }
619
620 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
621 $createParams['footer_id'] = $this->footer['id'];
622 }
623
624 $id = $this->createDraftMailing($createParams);
625
626 $submitParams['id'] = $id;
627 if ($expectedFailure) {
628 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
629 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
630 }
631 else {
632 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__, __FILE__);
633 $this->assertTrue(is_numeric($submitResult['id']));
634 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
635 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
636 }
637 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
638 1 => array($id, 'Integer'),
639 ));
640 }
641
642 /**
643 * Test unsubscribe list contains correct groups
644 * when include = 'previous mailing'
645 */
646 public function testUnsubscribeGroupList() {
647 // Create set of groups and add a contact to both of them.
648 $groupID2 = $this->groupCreate(array('name' => 'Test group 2', 'title' => 'group title 2'));
649 $groupID3 = $this->groupCreate(array('name' => 'Test group 3', 'title' => 'group title 3'));
650 $contactId = $this->individualCreate();
651 foreach (array($groupID2, $groupID3) as $grp) {
652 $params = array(
653 'contact_id' => $contactId,
654 'group_id' => $grp,
655 );
656 $this->callAPISuccess('GroupContact', 'create', $params);
657 }
658
659 //Send mail to groupID3
660 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
661 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $groupID3);
662 $this->callAPISuccess($this->_entity, 'send_test', $params);
663
664 $mgParams = array(
665 'mailing_id' => $mail['id'],
666 'entity_table' => 'civicrm_group',
667 'entity_id' => $groupID3,
668 'group_type' => 'Include',
669 );
670 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
671
672 //Include previous mail in the mailing group.
673 $mail2 = $this->callAPISuccess('mailing', 'create', $this->_params);
674 $params = array('mailing_id' => $mail2['id'], 'test_email' => NULL, 'test_group' => $groupID3);
675 $this->callAPISuccess($this->_entity, 'send_test', $params);
676
677 $mgParams = array(
678 'mailing_id' => $mail2['id'],
679 'entity_table' => 'civicrm_mailing',
680 'entity_id' => $mail['id'],
681 'group_type' => 'Include',
682 );
683 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
684 //CRM-20431 - Delete group id that matches first mailing id.
685 $this->callAPISuccess('Group', 'delete', array('id' => $this->_groupID));
686 $jobId = CRM_Core_DAO::getFieldValue('CRM_Mailing_DAO_MailingJob', $mail2['id'], 'id', 'mailing_id');
687 $hash = CRM_Core_DAO::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'hash', 'job_id');
688 $queueId = CRM_Core_DAO::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'id', 'job_id');
689
690 $group = CRM_Mailing_Event_BAO_Unsubscribe::unsub_from_mailing($jobId, $queueId, $hash, TRUE);
691 //Assert only one group returns in the unsubscribe list.
692 $this->assertCount(1, $group);
693 $this->assertEquals($groupID3, key($group));
694 }
695
696 /**
697 *
698 */
699 public function testMailerStats() {
700 $result = $this->groupContactCreate($this->_groupID, 100);
701 //verify if 100 contacts are added for group
702 $this->assertEquals(100, $result['added']);
703
704 //Create and send test mail first and change the mail job to live,
705 //because stats api only works on live mail
706 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
707 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID);
708 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
709 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
710
711 //Change the test mail into live
712 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
713 CRM_Core_DAO::executeQuery($sql);
714
715 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
716 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
717 (event_queue_id int, time_stamp datetime, delivered_id int)
718 SELECT event_queue_id, time_stamp, id
719 FROM civicrm_mailing_event_delivered
720 WHERE id IN ($deliveredIds)
721 ORDER BY RAND() LIMIT 0,20;";
722 CRM_Core_DAO::executeQuery($sql);
723
724 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
725 CRM_Core_DAO::executeQuery($sql);
726
727 if ($type == 'unsubscribe') {
728 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
729 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
730 }
731 else {
732 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
733 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
734 }
735 CRM_Core_DAO::executeQuery($sql);
736 }
737
738 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
739 $expectedResult = array(
740 //since among 100 mails 20 has been bounced
741 'Delivered' => 80,
742 'Bounces' => 20,
743 'Opened' => 20,
744 'Unique Clicks' => 0,
745 'Unsubscribers' => 20,
746 'delivered_rate' => '80%',
747 'opened_rate' => '25%',
748 'clickthrough_rate' => '0%',
749 );
750 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
751 }
752
753 /**
754 * Test civicrm_mailing_delete.
755 */
756 public function testMailerDeleteSuccess() {
757 $result = $this->callAPISuccess($this->_entity, 'create', $this->_params);
758 $this->callAPIAndDocument($this->_entity, 'delete', array('id' => $result['id']), __FUNCTION__, __FILE__);
759 $this->assertAPIDeleted($this->_entity, $result['id']);
760 }
761
762 /**
763 * Test Mailing.gettokens.
764 */
765 public function testMailGetTokens() {
766 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
767 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
768 $result = $this->callAPIAndDocument($this->_entity, 'gettokens', array('entity' => array('Contact', 'Mailing')), __FUNCTION__, __FILE__, $description);
769 $this->assertContains('Contact Type', $result['values']);
770
771 // Check that passing "sequential" correctly outputs a hierarchical array
772 $result = $this->callAPISuccess($this->_entity, 'gettokens', array('entity' => 'contact', 'sequential' => 1));
773 $this->assertArrayHasKey('text', $result['values'][0]);
774 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
775 }
776
777 public function testClone() {
778 // BEGIN SAMPLE DATA
779 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
780 $contactIDs['include_me'] = $this->individualCreate(array(
781 'email' => 'include.me@example.org',
782 'first_name' => 'Includer',
783 'last_name' => 'Person',
784 ));
785 $this->callAPISuccess('GroupContact', 'create', array(
786 'group_id' => $groupIDs['inc'],
787 'contact_id' => $contactIDs['include_me'],
788 ));
789
790 $params = $this->_params;
791 $params['groups']['include'] = array($groupIDs['inc']);
792 $params['groups']['exclude'] = array();
793 $params['mailings']['include'] = array();
794 $params['mailings']['exclude'] = array();
795 // END SAMPLE DATA
796
797 $create = $this->callAPISuccess('Mailing', 'create', $params);
798 $created = $this->callAPISuccess('Mailing', 'get', []);
799 $createId = $create['id'];
800 $this->createLoggedInUser();
801 $clone = $this->callAPIAndDocument('Mailing', 'clone', array('id' => $create['id']), __FUNCTION__, __FILE__);
802 $cloneId = $clone['id'];
803
804 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
805 $this->assertTrue(is_numeric($cloneId));
806
807 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
808 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
809
810 // created_id is special - populated based on current user (ie the cloner).
811 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
812 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
813
814 // Target groups+mailings are special.
815 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $cloneId, 'sequential' => 1));
816 $this->assertEquals(1, $cloneGroups['count']);
817 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
818 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
819 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
820 }
821
822 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
823
824 //------------ civicrm_mailing_event_bounce methods------------
825
826 /**
827 * Test civicrm_mailing_event_bounce with wrong params.
828 * Note that tests like this are slightly better than no test but an
829 * api function cannot be considered supported / 'part of the api' without a
830 * success test
831 */
832 public function testMailerBounceWrongParams() {
833 $params = array(
834 'job_id' => 'Wrong ID',
835 'event_queue_id' => 'Wrong ID',
836 'hash' => 'Wrong Hash',
837 'body' => 'Body...',
838 'time_stamp' => '20111109212100',
839 );
840 $this->callAPIFailure('mailing_event', 'bounce', $params,
841 'Queue event could not be found'
842 );
843 }
844
845 //----------- civicrm_mailing_event_confirm methods -----------
846
847 /**
848 * Test civicrm_mailing_event_confirm with wrong params.
849 * Note that tests like this are slightly better than no test but an
850 * api function cannot be considered supported / 'part of the api' without a
851 * success test
852 */
853 public function testMailerConfirmWrongParams() {
854 $params = array(
855 'contact_id' => 'Wrong ID',
856 'subscribe_id' => 'Wrong ID',
857 'hash' => 'Wrong Hash',
858 'event_subscribe_id' => '123',
859 'time_stamp' => '20111111010101',
860 );
861 $this->callAPIFailure('mailing_event', 'confirm', $params,
862 'contact_id is not a valid integer'
863 );
864 }
865
866 //---------- civicrm_mailing_event_reply methods -----------
867
868 /**
869 * Test civicrm_mailing_event_reply with wrong params.
870 *
871 * Note that tests like this are slightly better than no test but an
872 * api function cannot be considered supported / 'part of the api' without a
873 * success test
874 */
875 public function testMailerReplyWrongParams() {
876 $params = array(
877 'job_id' => 'Wrong ID',
878 'event_queue_id' => 'Wrong ID',
879 'hash' => 'Wrong Hash',
880 'bodyTxt' => 'Body...',
881 'replyTo' => $this->_email,
882 'time_stamp' => '20111111010101',
883 );
884 $this->callAPIFailure('mailing_event', 'reply', $params,
885 'Queue event could not be found'
886 );
887 }
888
889 //----------- civicrm_mailing_event_forward methods ----------
890
891 /**
892 * Test civicrm_mailing_event_forward with wrong params.
893 * Note that tests like this are slightly better than no test but an
894 * api function cannot be considered supported / 'part of the api' without a
895 * success test
896 */
897 public function testMailerForwardWrongParams() {
898 $params = array(
899 'job_id' => 'Wrong ID',
900 'event_queue_id' => 'Wrong ID',
901 'hash' => 'Wrong Hash',
902 'email' => $this->_email,
903 'time_stamp' => '20111111010101',
904 );
905 $this->callAPIFailure('mailing_event', 'forward', $params,
906 'Queue event could not be found'
907 );
908 }
909
910 /**
911 * @param array $params
912 * Extra parameters for the draft mailing.
913 * @return array|int
914 */
915 public function createDraftMailing($params = array()) {
916 $createParams = array_merge($this->_params, $params);
917 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__, __FILE__);
918 $this->assertTrue(is_numeric($createResult['id']));
919 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
920 1 => array($createResult['id'], 'Integer'),
921 ));
922 return $createResult['id'];
923 }
924
925 /**
926 * Test to make sure that if the event queue hashes have been archived,
927 * we can still have working click-trough URLs working (CRM-17959).
928 */
929 public function testUrlWithMissingTrackingHash() {
930 $mail = $this->callAPISuccess('mailing', 'create', $this->_params + array('scheduled_date' => 'now'), __FUNCTION__, __FILE__);
931 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $mail['id']));
932 $this->assertEquals(1, $jobs['count']);
933
934 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
935 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
936
937 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
938 FROM civicrm_mailing_trackable_url as turl
939 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
940 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
941 ORDER BY turl.id DESC LIMIT 1";
942
943 $dao = CRM_Core_DAO::executeQuery($sql);
944 $this->assertTrue($dao->fetch());
945
946 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
947 $this->assertContains('https://civicrm.org', $url);
948
949 // Now delete the event queue hashes and see if the tracking still works.
950 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_mailing_event_queue');
951
952 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
953 $this->assertContains('https://civicrm.org', $url);
954
955 // Ensure that Google CSS link is not tracked.
956 $sql = "SELECT id FROM civicrm_mailing_trackable_url where url = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Zilla+Slab:500,700'";
957 $this->assertEquals([], CRM_Core_DAO::executeQuery($sql)->fetchAll());
958 }
959
960 /**
961 * Test Trackable URL with unicode character
962 */
963 public function testTrackableURLWithUnicodeSign() {
964 $unicodeURL = "https://civiƄcrm.org";
965 $this->_params['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params['body_text']);
966 $this->_params['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params['body_html']);
967
968 $mail = $this->callAPISuccess('mailing', 'create', $this->_params + array('scheduled_date' => 'now'));
969
970 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
971 $this->callAPISuccess($this->_entity, 'send_test', $params);
972
973 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
974 FROM civicrm_mailing_trackable_url as turl
975 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
976 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
977 ORDER BY turl.id DESC LIMIT 1";
978
979 $dao = CRM_Core_DAO::executeQuery($sql);
980 $this->assertTrue($dao->fetch());
981
982 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
983 $this->assertContains($unicodeURL, $url);
984
985 // Now delete the event queue hashes and see if the tracking still works.
986 CRM_Core_DAO::executeQuery('DELETE FROM civicrm_mailing_event_queue');
987
988 $url = CRM_Mailing_Event_BAO_TrackableURLOpen::track($dao->queue_id, $dao->url_id);
989 $this->assertContains($unicodeURL, $url);
990 }
991
992 /**
993 * CRM-20892 : Test if Mail.create API throws error on update,
994 * if modified_date less then the date when the mail was last updated/created
995 */
996 public function testModifiedDateMismatchOnMailingUpdate() {
997 $mail = $this->callAPISuccess('mailing', 'create', $this->_params + array('modified_date' => 'now'));
998 try {
999 $this->callAPISuccess('mailing', 'create', $this->_params + array('id' => $mail['id'], 'modified_date' => '2 seconds ago'));
1000 }
1001 catch (Exception $e) {
1002 $this->assertRegExp("/Failure in api call for mailing create: Mailing has not been saved, Content maybe out of date, please refresh the page and try again/", $e->getMessage());
1003 }
1004 }
1005
1006 }