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