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 * The `template_options` field should be treated a JSON object.
138 * This test will create, read, and update the field.
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', [
149 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
151 // 2. Get mailing with template_options.
152 $getResult = $this->callAPISuccess('mailing', 'get', [
155 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
156 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', [
158 'return' => 'template_options',
160 $this->assertEquals('bar_1', $getValueResult['foo']);
162 // 3. Update mailing with template_options.
163 $updateResult = $this->callAPISuccess('mailing', 'create', [
165 'template_options' => ['foo' => 'bar_2'],
167 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', [
170 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
174 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
175 * Make sure these work
177 public function testMagicGroups_create_update() {
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',
186 $contactIDs['b'] = $this->individualCreate([
187 'email' => 'exclude.me@example.org',
188 'last_name' => 'Excluder',
190 $this->callAPISuccess('GroupContact', 'create', [
191 'group_id' => $groupIDs['a'],
192 'contact_id' => $contactIDs['a'],
194 $this->callAPISuccess('GroupContact', 'create', [
195 'group_id' => $groupIDs['b'],
196 'contact_id' => $contactIDs['b'],
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);
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);
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);
242 public function testMailerPreview() {
244 $contactID = $this->individualCreate();
245 $displayName = $this->callAPISuccess('contact', 'get', ['id' => $contactID]);
246 $displayName = $displayName['values'][$contactID]['display_name'];
247 $this->assertTrue(!empty($displayName));
249 $params = $this->_params
;
250 $params['api.Mailing.preview'] = [
252 'contact_id' => $contactID,
254 $params['options']['force_rollback'] = 1;
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'),
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;reset=1&jid=&qid=&h=">Forward this email with no protocol</a>', $previewResult['values']['body_html']);
278 $this->assertNotContains("http://http://", $previewResult['values']['body_html']);
281 public function testMailerPreviewUnknownContact() {
282 $params = $this->_params
;
283 $params['api.Mailing.preview'] = [
287 $result = $this->callAPISuccess('mailing', 'create', $params);
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']);
298 public function testMailerPreviewRecipients() {
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',
307 $contactIDs['exclude_me'] = $this->individualCreate([
308 'email' => 'exclude.me@example.org',
309 'last_name' => 'Excluder',
311 $this->callAPISuccess('GroupContact', 'create', [
312 'group_id' => $groupIDs['inc'],
313 'contact_id' => $contactIDs['include_me'],
315 $this->callAPISuccess('GroupContact', 'create', [
316 'group_id' => $groupIDs['inc'],
317 'contact_id' => $contactIDs['exclude_me'],
319 $this->callAPISuccess('GroupContact', 'create', [
320 'group_id' => $groupIDs['exc'],
321 'contact_id' => $contactIDs['exclude_me'],
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',
335 'api.email.getvalue' => [
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'),
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');
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] . '"');
361 * Test if Mailing recipients include duplicate OR on_hold emails
363 public function testMailerPreviewRecipientsDeduplicateAndOnholdEmails() {
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',
371 $contactIDs['include_me_duplicate'] = $this->individualCreate([
372 'email' => 'include.me@example.org',
373 'first_name' => 'IncluderDuplicate',
374 'last_name' => 'Person',
377 $contactIDs['include_me_onhold'] = $this->individualCreate([
378 'email' => 'onholdinclude.me@example.org',
379 'first_name' => 'Onhold',
380 'last_name' => 'Person',
382 $emailId = $this->callAPISuccessGetValue('Email', [
384 'contact_id' => $contactIDs['include_me_onhold'],
386 $this->callAPISuccess('Email', 'create', [
391 $this->callAPISuccess('GroupContact', 'create', [
392 'group_id' => $groupIDs['grp'],
393 'contact_id' => $contactIDs['include_me'],
395 $this->callAPISuccess('GroupContact', 'create', [
396 'group_id' => $groupIDs['grp'],
397 'contact_id' => $contactIDs['include_me_duplicate'],
399 $this->callAPISuccess('GroupContact', 'create', [
400 'group_id' => $groupIDs['grp'],
401 'contact_id' => $contactIDs['include_me_onhold'],
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',
414 'api.email.getvalue' => [
420 $create = $this->callAPISuccess('Mailing', 'create', $params);
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);
430 * Test sending a test mailing.
432 public function testMailerSendTest_email() {
433 $contactIDs['alice'] = $this->individualCreate([
434 'email' => 'alice@example.org',
435 'first_name' => 'Alice',
436 'last_name' => 'Person',
439 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
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']);
449 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
450 $this->assertEquals([$contactIDs['alice']], $deliveredContacts);
452 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
453 $this->assertEquals(['alice@example.org'], $deliveredEmails);
459 public function testMailerSendTest_group() {
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',
467 $contactIDs['bob'] = $this->individualCreate([
468 'email' => 'bob@example.org',
469 'first_name' => 'Bob',
470 'last_name' => 'Person',
472 $contactIDs['carol'] = $this->individualCreate([
473 'email' => 'carol@example.org',
474 'first_name' => 'Carol',
475 'last_name' => 'Person',
477 $this->callAPISuccess('GroupContact', 'create', [
478 'group_id' => $groupIDs['inc'],
479 'contact_id' => $contactIDs['alice'],
481 $this->callAPISuccess('GroupContact', 'create', [
482 'group_id' => $groupIDs['inc'],
483 'contact_id' => $contactIDs['bob'],
485 $this->callAPISuccess('GroupContact', 'create', [
486 'group_id' => $groupIDs['inc'],
487 'contact_id' => $contactIDs['carol'],
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'],
497 // verify mail has been sent to user by count
498 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
);
500 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
501 $this->assertEquals([$contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']], $deliveredContacts);
503 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
504 $this->assertEquals(['alice@example.org', 'bob@example.org', 'carol@example.org'], $deliveredEmails);
510 public function submitProvider() {
511 // $useLogin, $params, $expectedFailure, $expectedJobCount
518 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
529 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
531 "/Failed to determine current user/",
540 ['scheduled_date' => '2014-12-13 10:00:00'],
553 "/Missing parameter scheduled_date and.or approval_date/",
562 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
564 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./",
572 ['body_html' => '', 'body_text' => ''],
573 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
575 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./",
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'],
586 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./",
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'],
597 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./",
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'],
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'],
627 * @param bool $useLogin
628 * @param array $createParams
629 * @param array $submitParams
630 * @param null|string $expectedFailure
631 * @param int $expectedJobCount
632 * @dataProvider submitProvider
634 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
636 $this->createLoggedInUser();
639 if (isset($createParams['footer_id']) && $createParams['footer_id'] == '%FOOTER%') {
640 $createParams['footer_id'] = $this->footer
['id'];
643 $id = $this->createDraftMailing($createParams);
645 $submitParams['id'] = $id;
646 if ($expectedFailure) {
647 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
648 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
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']);
656 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', [
657 1 => [$id, 'Integer'],
662 * Test unsubscribe list contains correct groups
663 * when include = 'previous mailing'
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) {
672 'contact_id' => $contactId,
675 $this->callAPISuccess('GroupContact', 'create', $params);
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);
684 'mailing_id' => $mail['id'],
685 'entity_table' => 'civicrm_group',
686 'entity_id' => $groupID3,
687 'group_type' => 'Include',
689 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
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);
697 'mailing_id' => $mail2['id'],
698 'entity_table' => 'civicrm_mailing',
699 'entity_id' => $mail['id'],
700 'group_type' => 'Include',
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');
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));
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']);
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']));
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);
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);
743 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
744 CRM_Core_DAO
::executeQuery($sql);
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";
751 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
752 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
754 CRM_Core_DAO
::executeQuery($sql);
757 $result = $this->callAPISuccess('mailing', 'stats', ['mailing_id' => $mail['id']]);
759 //since among 100 mails 20 has been bounced
763 'Unique Clicks' => 0,
764 'Unsubscribers' => 20,
765 'delivered_rate' => '80%',
766 'opened_rate' => '25%',
767 'clickthrough_rate' => '0%',
769 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
773 * Test civicrm_mailing_delete.
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']);
782 * Test Mailing.gettokens.
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']);
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]);
796 public function testClone() {
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',
804 $this->callAPISuccess('GroupContact', 'create', [
805 'group_id' => $groupIDs['inc'],
806 'contact_id' => $contactIDs['include_me'],
809 $params = $this->_params
;
810 $params['groups']['include'] = [$groupIDs['inc']];
811 $params['groups']['exclude'] = [];
812 $params['mailings']['include'] = [];
813 $params['mailings']['exclude'] = [];
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'];
823 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
824 $this->assertTrue(is_numeric($cloneId));
826 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
827 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
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');
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']);
841 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
843 //------------ civicrm_mailing_event_bounce methods------------
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
851 public function testMailerBounceWrongParams() {
853 'job_id' => 'Wrong ID',
854 'event_queue_id' => 'Wrong ID',
855 'hash' => 'Wrong Hash',
857 'time_stamp' => '20111109212100',
859 $this->callAPIFailure('mailing_event', 'bounce', $params,
860 'Queue event could not be found'
864 //----------- civicrm_mailing_event_confirm methods -----------
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
872 public function testMailerConfirmWrongParams() {
874 'contact_id' => 'Wrong ID',
875 'subscribe_id' => 'Wrong ID',
876 'hash' => 'Wrong Hash',
877 'event_subscribe_id' => '123',
878 'time_stamp' => '20111111010101',
880 $this->callAPIFailure('mailing_event', 'confirm', $params,
881 'contact_id is not a valid integer'
885 //---------- civicrm_mailing_event_reply methods -----------
888 * Test civicrm_mailing_event_reply with wrong params.
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
894 public function testMailerReplyWrongParams() {
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',
903 $this->callAPIFailure('mailing_event', 'reply', $params,
904 'Queue event could not be found'
908 //----------- civicrm_mailing_event_forward methods ----------
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
916 public function testMailerForwardWrongParams() {
918 'job_id' => 'Wrong ID',
919 'event_queue_id' => 'Wrong ID',
920 'hash' => 'Wrong Hash',
921 'email' => $this->_email
,
922 'time_stamp' => '20111111010101',
924 $this->callAPIFailure('mailing_event', 'forward', $params,
925 'Queue event could not be found'
930 * @param array $params
931 * Extra parameters for the draft mailing.
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'],
941 return $createResult['id'];
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).
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']);
953 $params = ['mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL];
954 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
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";
962 $dao = CRM_Core_DAO
::executeQuery($sql);
963 $this->assertTrue($dao->fetch());
965 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
966 $this->assertContains('https://civicrm.org', $url);
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');
971 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
972 $this->assertContains('https://civicrm.org', $url);
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());
980 * Test Trackable URL with unicode character
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']);
987 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['scheduled_date' => 'now']);
989 $params = ['mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL];
990 $this->callAPISuccess($this->_entity
, 'send_test', $params);
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";
998 $dao = CRM_Core_DAO
::executeQuery($sql);
999 $this->assertTrue($dao->fetch());
1001 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
1002 $this->assertContains($unicodeURL, $url);
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');
1007 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
1008 $this->assertContains($unicodeURL, $url);
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
1015 public function testModifiedDateMismatchOnMailingUpdate() {
1016 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['modified_date' => 'now']);
1018 $this->callAPISuccess('mailing', 'create', $this->_params +
['id' => $mail['id'], 'modified_date' => '2 seconds ago']);
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());