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