3 * File for the TestMailing class
9 * This file is part of CiviCRM
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.
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.
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/>.
28 * Test APIv3 civicrm_mailing_* functions
33 class api_v3_MailingTest
extends CiviUnitTestCase
{
36 protected $_apiversion = 3;
37 protected $_params = [];
38 protected $_entity = 'Mailing';
39 protected $_contactID;
42 * APIv3 result from creating an example footer
47 public function setUp() {
49 $this->useTransaction();
51 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0;
52 $this->_contactID
= $this->individualCreate();
53 $this->_groupID
= $this->groupCreate();
54 $this->_email
= 'test@test.test';
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
,
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}.',
73 public function tearDown() {
75 CRM_Mailing_BAO_MailingJob
::$mailsProcessed = 0;
80 * Test civicrm_mailing_create.
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');
92 * Tes that the parameter _skip_evil_bao_auto_schedule_ is respected & prevents jobs being created.
94 public function testSkipAutoSchedule() {
95 $this->callAPISuccess('Mailing', 'create', array_merge($this->_params
, [
96 '_skip_evil_bao_auto_schedule_' => TRUE,
97 'scheduled_date' => 'now',
99 $this->callAPISuccessGetCount('Mailing', [], 1);
100 $this->callAPISuccessGetCount('MailingJob', [], 0);
104 * Create a completed mailing (e.g when importing from a provider).
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');
119 * Per CRM-20316 the mailing should still create without created_id (not mandatory).
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');
130 public function testTemplateTypeOptions() {
131 $types = $this->callAPISuccess('Mailing', 'getoptions', ['field' => 'template_type']);
132 $this->assertTrue(isset($types['values']['traditional']));
136 * Check that default header+footer are available.
138 public function testHeaderFooterOptions() {
139 $headers = $this->callAPISuccess('Mailing', 'getoptions', ['field' => 'header']);
140 $this->assertTrue(in_array('Mailing Header', $headers['values']));
141 $footers = $this->callAPISuccess('Mailing', 'getoptions', ['field' => 'footer']);
142 $this->assertTrue(in_array('Mailing Footer', $footers['values']));
146 * The `template_options` field should be treated a JSON object.
148 * This test will create, read, and update the field.
150 public function testMailerCreateTemplateOptions() {
151 // 1. Create mailing with template_options.
152 $params = $this->_params
;
153 $params['template_options'] = json_encode(['foo' => 'bar_1']);
154 $createResult = $this->callAPISuccess('mailing', 'create', $params);
155 $id = $createResult['id'];
156 $this->assertDBQuery('{"foo":"bar_1"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', [
159 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
161 // 2. Get mailing with template_options.
162 $getResult = $this->callAPISuccess('mailing', 'get', [
165 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
166 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', [
168 'return' => 'template_options',
170 $this->assertEquals('bar_1', $getValueResult['foo']);
172 // 3. Update mailing with template_options.
173 $updateResult = $this->callAPISuccess('mailing', 'create', [
175 'template_options' => ['foo' => 'bar_2'],
177 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', [
180 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
184 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
185 * Make sure these work
187 public function testMagicGroups_create_update() {
189 $groupIDs['a'] = $this->groupCreate(['name' => 'Example include group', 'title' => 'Example include group']);
190 $groupIDs['b'] = $this->groupCreate(['name' => 'Example exclude group', 'title' => 'Example exclude group']);
191 $contactIDs['a'] = $this->individualCreate([
192 'email' => 'include.me@example.org',
193 'first_name' => 'Includer',
194 'last_name' => 'Person',
196 $contactIDs['b'] = $this->individualCreate([
197 'email' => 'exclude.me@example.org',
198 'last_name' => 'Excluder',
200 $this->callAPISuccess('GroupContact', 'create', [
201 'group_id' => $groupIDs['a'],
202 'contact_id' => $contactIDs['a'],
204 $this->callAPISuccess('GroupContact', 'create', [
205 'group_id' => $groupIDs['b'],
206 'contact_id' => $contactIDs['b'],
211 $createParams = $this->_params
;
212 $createParams['groups']['include'] = [$groupIDs['a']];
213 $createParams['groups']['exclude'] = [];
214 $createParams['mailings']['include'] = [];
215 $createParams['mailings']['exclude'] = [];
216 $createParams['scheduled_date'] = 'now';
217 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
218 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', ['mailing_id' => $createResult['id']]);
219 $getGroup1_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup1['values']));
220 $this->assertEquals([$groupIDs['a']], $getGroup1_ids);
221 $getRecipient1 = $this->callAPISuccess('MailingRecipients', 'get', ['mailing_id' => $createResult['id']]);
222 $getRecipient1_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient1['values']));
223 $this->assertEquals([$contactIDs['a']], $getRecipient1_ids);
225 // ** Pass 2: Update without any changes to groups[include]
226 $nullOpParams = $createParams;
227 $nullOpParams['id'] = $createResult['id'];
228 $updateParams['api.mailing_job.create'] = 1;
229 unset($nullOpParams['groups']['include']);
230 $this->callAPISuccess('Mailing', 'create', $nullOpParams);
231 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', ['mailing_id' => $createResult['id']]);
232 $getGroup2_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup2['values']));
233 $this->assertEquals([$groupIDs['a']], $getGroup2_ids);
234 $getRecipient2 = $this->callAPISuccess('MailingRecipients', 'get', ['mailing_id' => $createResult['id']]);
235 $getRecip2_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient2['values']));
236 $this->assertEquals([$contactIDs['a']], $getRecip2_ids);
238 // ** Pass 3: Update with different groups[include]
239 $updateParams = $createParams;
240 $updateParams['id'] = $createResult['id'];
241 $updateParams['groups']['include'] = [$groupIDs['b']];
242 $updateParams['scheduled_date'] = 'now';
243 $this->callAPISuccess('Mailing', 'create', $updateParams);
244 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', ['mailing_id' => $createResult['id']]);
245 $getGroup3_ids = array_values(CRM_Utils_Array
::collect('entity_id', $getGroup3['values']));
246 $this->assertEquals([$groupIDs['b']], $getGroup3_ids);
247 $getRecipient3 = $this->callAPISuccess('MailingRecipients', 'get', ['mailing_id' => $createResult['id']]);
248 $getRecipient3_ids = array_values(CRM_Utils_Array
::collect('contact_id', $getRecipient3['values']));
249 $this->assertEquals([$contactIDs['b']], $getRecipient3_ids);
252 public function testMailerPreview() {
254 $contactID = $this->individualCreate();
255 $displayName = $this->callAPISuccess('contact', 'get', ['id' => $contactID]);
256 $displayName = $displayName['values'][$contactID]['display_name'];
257 $this->assertTrue(!empty($displayName));
259 $params = $this->_params
;
260 $params['api.Mailing.preview'] = [
262 'contact_id' => $contactID,
264 $params['options']['force_rollback'] = 1;
268 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
269 'job' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
270 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
271 'recipient' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
273 $result = $this->callAPISuccess('mailing', 'create', $params);
274 // 'Preview should not create any mailing records'
275 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing');
276 // 'Preview should not create any mailing_job record'
277 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job');
278 // 'Preview should not create any mailing_group records'
279 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group');
280 // 'Preview should not create any mailing_recipient records'
281 $this->assertDBQuery($maxIDs['recipient'], 'SELECT MAX(id) FROM civicrm_mailing_recipients');
282 $baseurl = CRM_Utils_System
::baseCMSURL();
283 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
284 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
285 $this->assertContains("This is $displayName", $previewResult['values']['body_text']);
286 $this->assertContains("<p>This is $displayName.</p>", $previewResult['values']['body_html']);
287 $this->assertContains('<a href="' . $baseurl . 'index.php?q=civicrm/mailing/forward&amp;reset=1&jid=&qid=&h=">Forward this email with no protocol</a>', $previewResult['values']['body_html']);
288 $this->assertNotContains("http://http://", $previewResult['values']['body_html']);
291 public function testMailerPreviewUnknownContact() {
292 $params = $this->_params
;
293 $params['api.Mailing.preview'] = [
297 $result = $this->callAPISuccess('mailing', 'create', $params);
299 // NOTE: It's highly debatable what's best to do with contact-tokens for an
300 // unknown-contact. However, changes should be purposeful, so we'll test
301 // for the current behavior (i.e. returning blanks).
302 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
303 $this->assertEquals("Hello ", $previewResult['values']['subject']);
304 $this->assertContains("This is .", $previewResult['values']['body_text']);
305 $this->assertContains("<p>This is .</p>", $previewResult['values']['body_html']);
308 public function testMailerPreviewRecipients() {
310 $groupIDs['inc'] = $this->groupCreate(['name' => 'Example include group', 'title' => 'Example include group']);
311 $groupIDs['exc'] = $this->groupCreate(['name' => 'Example exclude group', 'title' => 'Example exclude group']);
312 $contactIDs['include_me'] = $this->individualCreate([
313 'email' => 'include.me@example.org',
314 'first_name' => 'Includer',
315 'last_name' => 'Person',
317 $contactIDs['exclude_me'] = $this->individualCreate([
318 'email' => 'exclude.me@example.org',
319 'last_name' => 'Excluder',
321 $this->callAPISuccess('GroupContact', 'create', [
322 'group_id' => $groupIDs['inc'],
323 'contact_id' => $contactIDs['include_me'],
325 $this->callAPISuccess('GroupContact', 'create', [
326 'group_id' => $groupIDs['inc'],
327 'contact_id' => $contactIDs['exclude_me'],
329 $this->callAPISuccess('GroupContact', 'create', [
330 'group_id' => $groupIDs['exc'],
331 'contact_id' => $contactIDs['exclude_me'],
334 $params = $this->_params
;
335 $params['groups']['include'] = [$groupIDs['inc']];
336 $params['groups']['exclude'] = [$groupIDs['exc']];
337 $params['mailings']['include'] = [];
338 $params['mailings']['exclude'] = [];
339 $params['options']['force_rollback'] = 1;
340 $params['api.MailingRecipients.get'] = [
341 'mailing_id' => '$value.id',
342 'api.contact.getvalue' => [
343 'return' => 'display_name',
345 'api.email.getvalue' => [
352 'mailing' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
353 'group' => CRM_Core_DAO
::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
355 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__
, __FILE__
);
356 // 'Preview should not create any mailing records'
357 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing');
358 // 'Preview should not create any mailing_group records'
359 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group');
361 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
362 $previewIds = array_values(CRM_Utils_Array
::collect('contact_id', $preview['values']));
363 $this->assertEquals([(string) $contactIDs['include_me']], $previewIds);
364 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
365 $this->assertEquals(['include.me@example.org'], $previewEmails);
366 $previewNames = array_values(CRM_Utils_Array
::collect('api.contact.getvalue', $preview['values']));
367 $this->assertTrue((bool) preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
371 * Test if Mailing recipients include duplicate OR on_hold emails
373 public function testMailerPreviewRecipientsDeduplicateAndOnholdEmails() {
375 $groupIDs['grp'] = $this->groupCreate(['name' => 'Example group', 'title' => 'Example group']);
376 $contactIDs['include_me'] = $this->individualCreate([
377 'email' => 'include.me@example.org',
378 'first_name' => 'Includer',
379 'last_name' => 'Person',
381 $contactIDs['include_me_duplicate'] = $this->individualCreate([
382 'email' => 'include.me@example.org',
383 'first_name' => 'IncluderDuplicate',
384 'last_name' => 'Person',
387 $contactIDs['include_me_onhold'] = $this->individualCreate([
388 'email' => 'onholdinclude.me@example.org',
389 'first_name' => 'Onhold',
390 'last_name' => 'Person',
392 $emailId = $this->callAPISuccessGetValue('Email', [
394 'contact_id' => $contactIDs['include_me_onhold'],
396 $this->callAPISuccess('Email', 'create', [
401 $this->callAPISuccess('GroupContact', 'create', [
402 'group_id' => $groupIDs['grp'],
403 'contact_id' => $contactIDs['include_me'],
405 $this->callAPISuccess('GroupContact', 'create', [
406 'group_id' => $groupIDs['grp'],
407 'contact_id' => $contactIDs['include_me_duplicate'],
409 $this->callAPISuccess('GroupContact', 'create', [
410 'group_id' => $groupIDs['grp'],
411 'contact_id' => $contactIDs['include_me_onhold'],
414 $params = $this->_params
;
415 $params['groups']['include'] = [$groupIDs['grp']];
416 $params['mailings']['include'] = [];
417 $params['options']['force_rollback'] = 1;
418 $params['dedupe_email'] = 1;
419 $params['api.MailingRecipients.get'] = [
420 'mailing_id' => '$value.id',
421 'api.contact.getvalue' => [
422 'return' => 'display_name',
424 'api.email.getvalue' => [
430 $create = $this->callAPISuccess('Mailing', 'create', $params);
432 //Recipient should not contain duplicate or on_hold emails.
433 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
434 $this->assertEquals(1, $preview['count']);
435 $previewEmails = array_values(CRM_Utils_Array
::collect('api.email.getvalue', $preview['values']));
436 $this->assertEquals(['include.me@example.org'], $previewEmails);
440 * Test sending a test mailing.
442 public function testMailerSendTest_email() {
443 $contactIDs['alice'] = $this->individualCreate([
444 'email' => 'alice@example.org',
445 'first_name' => 'Alice',
446 'last_name' => 'Person',
449 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
451 $params = ['mailing_id' => $mail['id'], 'test_email' => 'ALicE@example.org', 'test_group' => NULL];
452 // Per https://lab.civicrm.org/dev/core/issues/229 ensure this is not passed through!
453 // Per https://lab.civicrm.org/dev/mail/issues/32 test non-lowercase email
454 $params['id'] = $mail['id'];
455 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
456 // verify mail has been sent to user by count
457 $this->assertEquals(1, $deliveredInfo['count']);
459 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
460 $this->assertEquals([$contactIDs['alice']], $deliveredContacts);
462 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
463 $this->assertEquals(['alice@example.org'], $deliveredEmails);
469 public function testMailerSendTest_group() {
471 $groupIDs['inc'] = $this->groupCreate(['name' => 'Example include group', 'title' => 'Example include group']);
472 $contactIDs['alice'] = $this->individualCreate([
473 'email' => 'alice@example.org',
474 'first_name' => 'Alice',
475 'last_name' => 'Person',
477 $contactIDs['bob'] = $this->individualCreate([
478 'email' => 'bob@example.org',
479 'first_name' => 'Bob',
480 'last_name' => 'Person',
482 $contactIDs['carol'] = $this->individualCreate([
483 'email' => 'carol@example.org',
484 'first_name' => 'Carol',
485 'last_name' => 'Person',
487 $this->callAPISuccess('GroupContact', 'create', [
488 'group_id' => $groupIDs['inc'],
489 'contact_id' => $contactIDs['alice'],
491 $this->callAPISuccess('GroupContact', 'create', [
492 'group_id' => $groupIDs['inc'],
493 'contact_id' => $contactIDs['bob'],
495 $this->callAPISuccess('GroupContact', 'create', [
496 'group_id' => $groupIDs['inc'],
497 'contact_id' => $contactIDs['carol'],
501 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
502 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', [
503 'mailing_id' => $mail['id'],
504 'test_email' => NULL,
505 'test_group' => $groupIDs['inc'],
507 // verify mail has been sent to user by count
508 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
);
510 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
511 $this->assertEquals([$contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']], $deliveredContacts);
513 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
514 $this->assertEquals(['alice@example.org', 'bob@example.org', 'carol@example.org'], $deliveredEmails);
520 public function submitProvider() {
521 // $useLogin, $params, $expectedFailure, $expectedJobCount
528 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
539 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
541 "/Failed to determine current user/",
550 ['scheduled_date' => '2014-12-13 10:00:00'],
563 "/Missing parameter scheduled_date and.or approval_date/",
572 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
574 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./",
582 ['body_html' => '', 'body_text' => ''],
583 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
585 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./",
593 ['body_html' => 'Oops, did I leave my tokens at home?'],
594 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
596 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./",
604 ['body_text' => 'Oops, did I leave my tokens at home?'],
605 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
607 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./",
615 ['body_text' => 'Look ma, magic tokens in the text!', 'footer_id' => '%FOOTER%'],
616 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
626 ['body_html' => '<p>Look ma, magic tokens in the markup!</p>', 'footer_id' => '%FOOTER%'],
627 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
637 * @param bool $useLogin
638 * @param array $createParams
639 * @param array $submitParams
640 * @param null|string $expectedFailure
641 * @param int $expectedJobCount
642 * @dataProvider submitProvider
644 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
646 $this->createLoggedInUser();
649 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
650 $createParams['footer_id'] = $this->footer
['id'];
653 $id = $this->createDraftMailing($createParams);
655 $submitParams['id'] = $id;
656 if ($expectedFailure) {
657 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
658 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
661 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $submitParams, __FUNCTION__
, __FILE__
);
662 $this->assertTrue(is_numeric($submitResult['id']));
663 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
664 $this->assertEquals($submitParams['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
666 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', [
667 1 => [$id, 'Integer'],
672 * Test unsubscribe list contains correct groups
673 * when include = 'previous mailing'
675 public function testUnsubscribeGroupList() {
676 // Create set of groups and add a contact to both of them.
677 $groupID2 = $this->groupCreate(['name' => 'Test group 2', 'title' => 'group title 2']);
678 $groupID3 = $this->groupCreate(['name' => 'Test group 3', 'title' => 'group title 3']);
679 $contactId = $this->individualCreate();
680 foreach ([$groupID2, $groupID3] as $grp) {
682 'contact_id' => $contactId,
685 $this->callAPISuccess('GroupContact', 'create', $params);
688 //Send mail to groupID3
689 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
690 $params = ['mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $groupID3];
691 $this->callAPISuccess($this->_entity
, 'send_test', $params);
694 'mailing_id' => $mail['id'],
695 'entity_table' => 'civicrm_group',
696 'entity_id' => $groupID3,
697 'group_type' => 'Include',
699 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
701 //Include previous mail in the mailing group.
702 $mail2 = $this->callAPISuccess('mailing', 'create', $this->_params
);
703 $params = ['mailing_id' => $mail2['id'], 'test_email' => NULL, 'test_group' => $groupID3];
704 $this->callAPISuccess($this->_entity
, 'send_test', $params);
707 'mailing_id' => $mail2['id'],
708 'entity_table' => 'civicrm_mailing',
709 'entity_id' => $mail['id'],
710 'group_type' => 'Include',
712 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
713 //CRM-20431 - Delete group id that matches first mailing id.
714 $this->callAPISuccess('Group', 'delete', ['id' => $this->_groupID
]);
715 $jobId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_MailingJob', $mail2['id'], 'id', 'mailing_id');
716 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'hash', 'job_id');
717 $queueId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'id', 'job_id');
719 $group = CRM_Mailing_Event_BAO_Unsubscribe
::unsub_from_mailing($jobId, $queueId, $hash, TRUE);
720 //Assert only one group returns in the unsubscribe list.
721 $this->assertCount(1, $group);
722 $this->assertEquals($groupID3, key($group));
728 public function testMailerStats() {
729 $result = $this->groupContactCreate($this->_groupID
, 100);
730 //verify if 100 contacts are added for group
731 $this->assertEquals(100, $result['added']);
733 //Create and send test mail first and change the mail job to live,
734 //because stats api only works on live mail
735 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
736 $params = ['mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID
];
737 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
738 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
740 //Change the test mail into live
741 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
742 CRM_Core_DAO
::executeQuery($sql);
744 foreach (['bounce', 'unsubscribe', 'opened'] as $type) {
745 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
746 (event_queue_id int, time_stamp datetime, delivered_id int)
747 SELECT event_queue_id, time_stamp, id
748 FROM civicrm_mailing_event_delivered
749 WHERE id IN ($deliveredIds)
750 ORDER BY RAND() LIMIT 0,20;";
751 CRM_Core_DAO
::executeQuery($sql);
753 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
754 CRM_Core_DAO
::executeQuery($sql);
756 if ($type == 'unsubscribe') {
757 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
758 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
761 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
762 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
764 CRM_Core_DAO
::executeQuery($sql);
767 $result = $this->callAPISuccess('mailing', 'stats', ['mailing_id' => $mail['id']]);
769 //since among 100 mails 20 has been bounced
773 'Unique Clicks' => 0,
774 'Unsubscribers' => 20,
775 'delivered_rate' => '80%',
776 'opened_rate' => '25%',
777 'clickthrough_rate' => '0%',
779 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
783 * Test civicrm_mailing_delete.
785 public function testMailerDeleteSuccess() {
786 $result = $this->callAPISuccess($this->_entity
, 'create', $this->_params
);
787 $this->callAPIAndDocument($this->_entity
, 'delete', ['id' => $result['id']], __FUNCTION__
, __FILE__
);
788 $this->assertAPIDeleted($this->_entity
, $result['id']);
792 * Test Mailing.gettokens.
794 public function testMailGetTokens() {
795 $description = "Demonstrates fetching tokens for one or more entities (in this case \"Contact\" and \"Mailing\").
796 Optionally pass sequential=1 to have output ready-formatted for the select2 widget.";
797 $result = $this->callAPIAndDocument($this->_entity
, 'gettokens', ['entity' => ['Contact', 'Mailing']], __FUNCTION__
, __FILE__
, $description);
798 $this->assertContains('Contact Type', $result['values']);
800 // Check that passing "sequential" correctly outputs a hierarchical array
801 $result = $this->callAPISuccess($this->_entity
, 'gettokens', ['entity' => 'contact', 'sequential' => 1]);
802 $this->assertArrayHasKey('text', $result['values'][0]);
803 $this->assertArrayHasKey('id', $result['values'][0]['children'][0]);
806 public function testClone() {
808 $groupIDs['inc'] = $this->groupCreate(['name' => 'Example include group', 'title' => 'Example include group']);
809 $contactIDs['include_me'] = $this->individualCreate([
810 'email' => 'include.me@example.org',
811 'first_name' => 'Includer',
812 'last_name' => 'Person',
814 $this->callAPISuccess('GroupContact', 'create', [
815 'group_id' => $groupIDs['inc'],
816 'contact_id' => $contactIDs['include_me'],
819 $params = $this->_params
;
820 $params['groups']['include'] = [$groupIDs['inc']];
821 $params['groups']['exclude'] = [];
822 $params['mailings']['include'] = [];
823 $params['mailings']['exclude'] = [];
826 $create = $this->callAPISuccess('Mailing', 'create', $params);
827 $created = $this->callAPISuccess('Mailing', 'get', []);
828 $createId = $create['id'];
829 $this->createLoggedInUser();
830 $clone = $this->callAPIAndDocument('Mailing', 'clone', ['id' => $create['id']], __FUNCTION__
, __FILE__
);
831 $cloneId = $clone['id'];
833 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
834 $this->assertTrue(is_numeric($cloneId));
836 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
837 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
839 // created_id is special - populated based on current user (ie the cloner).
840 $this->assertNotEmpty($clone['values'][$cloneId]['created_id']);
841 $this->assertNotEquals($create['values'][$createId]['created_id'], $clone['values'][$cloneId]['created_id'], 'Clone should be created by a different person');
843 // Target groups+mailings are special.
844 $cloneGroups = $this->callAPISuccess('MailingGroup', 'get', ['mailing_id' => $cloneId, 'sequential' => 1]);
845 $this->assertEquals(1, $cloneGroups['count']);
846 $this->assertEquals($cloneGroups['values'][0]['group_type'], 'Include');
847 $this->assertEquals($cloneGroups['values'][0]['entity_table'], 'civicrm_group');
848 $this->assertEquals($cloneGroups['values'][0]['entity_id'], $groupIDs['inc']);
851 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
853 //------------ civicrm_mailing_event_bounce methods------------
856 * Test civicrm_mailing_event_bounce with wrong params.
857 * Note that tests like this are slightly better than no test but an
858 * api function cannot be considered supported / 'part of the api' without a
861 public function testMailerBounceWrongParams() {
863 'job_id' => 'Wrong ID',
864 'event_queue_id' => 'Wrong ID',
865 'hash' => 'Wrong Hash',
867 'time_stamp' => '20111109212100',
869 $this->callAPIFailure('mailing_event', 'bounce', $params,
870 'Queue event could not be found'
874 //----------- civicrm_mailing_event_confirm methods -----------
877 * Test civicrm_mailing_event_confirm with wrong params.
878 * Note that tests like this are slightly better than no test but an
879 * api function cannot be considered supported / 'part of the api' without a
882 public function testMailerConfirmWrongParams() {
884 'contact_id' => 'Wrong ID',
885 'subscribe_id' => 'Wrong ID',
886 'hash' => 'Wrong Hash',
887 'event_subscribe_id' => '123',
888 'time_stamp' => '20111111010101',
890 $this->callAPIFailure('mailing_event', 'confirm', $params,
891 'contact_id is not a valid integer'
895 //---------- civicrm_mailing_event_reply methods -----------
898 * Test civicrm_mailing_event_reply with wrong params.
900 * Note that tests like this are slightly better than no test but an
901 * api function cannot be considered supported / 'part of the api' without a
904 public function testMailerReplyWrongParams() {
906 'job_id' => 'Wrong ID',
907 'event_queue_id' => 'Wrong ID',
908 'hash' => 'Wrong Hash',
909 'bodyTxt' => 'Body...',
910 'replyTo' => $this->_email
,
911 'time_stamp' => '20111111010101',
913 $this->callAPIFailure('mailing_event', 'reply', $params,
914 'Queue event could not be found'
918 //----------- civicrm_mailing_event_forward methods ----------
921 * Test civicrm_mailing_event_forward with wrong params.
922 * Note that tests like this are slightly better than no test but an
923 * api function cannot be considered supported / 'part of the api' without a
926 public function testMailerForwardWrongParams() {
928 'job_id' => 'Wrong ID',
929 'event_queue_id' => 'Wrong ID',
930 'hash' => 'Wrong Hash',
931 'email' => $this->_email
,
932 'time_stamp' => '20111111010101',
934 $this->callAPIFailure('mailing_event', 'forward', $params,
935 'Queue event could not be found'
940 * @param array $params
941 * Extra parameters for the draft mailing.
944 public function createDraftMailing($params = []) {
945 $createParams = array_merge($this->_params
, $params);
946 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
947 $this->assertTrue(is_numeric($createResult['id']));
948 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', [
949 1 => [$createResult['id'], 'Integer'],
951 return $createResult['id'];
955 * Test to make sure that if the event queue hashes have been archived,
956 * we can still have working click-trough URLs working (CRM-17959).
958 public function testUrlWithMissingTrackingHash() {
959 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['scheduled_date' => 'now'], __FUNCTION__
, __FILE__
);
960 $jobs = $this->callAPISuccess('mailing_job', 'get', ['mailing_id' => $mail['id']]);
961 $this->assertEquals(1, $jobs['count']);
963 $params = ['mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL];
964 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
966 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
967 FROM civicrm_mailing_trackable_url as turl
968 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
969 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
970 ORDER BY turl.id DESC LIMIT 1";
972 $dao = CRM_Core_DAO
::executeQuery($sql);
973 $this->assertTrue($dao->fetch());
975 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
976 $this->assertContains('https://civicrm.org', $url);
978 // Now delete the event queue hashes and see if the tracking still works.
979 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
981 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
982 $this->assertContains('https://civicrm.org', $url);
984 // Ensure that Google CSS link is not tracked.
985 $sql = "SELECT id FROM civicrm_mailing_trackable_url where url = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Zilla+Slab:500,700'";
986 $this->assertEquals([], CRM_Core_DAO
::executeQuery($sql)->fetchAll());
990 * Test Trackable URL with unicode character
992 public function testTrackableURLWithUnicodeSign() {
993 $unicodeURL = "https://civiĆcrm.org";
994 $this->_params
['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_text']);
995 $this->_params
['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_html']);
997 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['scheduled_date' => 'now']);
999 $params = ['mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL];
1000 $this->callAPISuccess($this->_entity
, 'send_test', $params);
1002 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
1003 FROM civicrm_mailing_trackable_url as turl
1004 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
1005 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
1006 ORDER BY turl.id DESC LIMIT 1";
1008 $dao = CRM_Core_DAO
::executeQuery($sql);
1009 $this->assertTrue($dao->fetch());
1011 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
1012 $this->assertContains($unicodeURL, $url);
1014 // Now delete the event queue hashes and see if the tracking still works.
1015 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
1017 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
1018 $this->assertContains($unicodeURL, $url);
1022 * CRM-20892 : Test if Mail.create API throws error on update,
1023 * if modified_date less then the date when the mail was last updated/created
1025 public function testModifiedDateMismatchOnMailingUpdate() {
1026 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['modified_date' => 'now']);
1028 $this->callAPISuccess('mailing', 'create', $this->_params +
['id' => $mail['id'], 'modified_date' => '2 seconds ago']);
1030 catch (Exception
$e) {
1031 $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());