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 * @throws \CRM_Core_Exception
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');
121 * Per CRM-20316 the mailing should still create without created_id (not mandatory).
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');
132 public function testTemplateTypeOptions() {
133 $types = $this->callAPISuccess('Mailing', 'getoptions', ['field' => 'template_type']);
134 $this->assertTrue(isset($types['values']['traditional']));
138 * Check that default header+footer are available.
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']));
148 * The `template_options` field should be treated a JSON object.
150 * This test will create, read, and update the field.
152 * @throws \CRM_Core_Exception
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', [
163 $this->assertEquals('bar_1', $createResult['values'][$id]['template_options']['foo']);
165 // 2. Get mailing with template_options.
166 $getResult = $this->callAPISuccess('mailing', 'get', [
169 $this->assertEquals('bar_1', $getResult['values'][$id]['template_options']['foo']);
170 $getValueResult = $this->callAPISuccess('mailing', 'getvalue', [
172 'return' => 'template_options',
174 $this->assertEquals('bar_1', $getValueResult['foo']);
176 // 3. Update mailing with template_options.
177 $updateResult = $this->callAPISuccess('mailing', 'create', [
179 'template_options' => ['foo' => 'bar_2'],
181 $this->assertDBQuery('{"foo":"bar_2"}', 'SELECT template_options FROM civicrm_mailing WHERE id = %1', [
184 $this->assertEquals('bar_2', $updateResult['values'][$id]['template_options']['foo']);
188 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
189 * Make sure these work
191 * @throws \CRM_Core_Exception
193 public function testMagicGroups_create_update() {
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',
202 $contactIDs['b'] = $this->individualCreate([
203 'email' => 'exclude.me@example.org',
204 'last_name' => 'Excluder',
206 $this->callAPISuccess('GroupContact', 'create', [
207 'group_id' => $groupIDs['a'],
208 'contact_id' => $contactIDs['a'],
210 $this->callAPISuccess('GroupContact', 'create', [
211 'group_id' => $groupIDs['b'],
212 'contact_id' => $contactIDs['b'],
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);
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);
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);
258 public function testMailerPreview() {
260 $contactID = $this->individualCreate();
261 $displayName = $this->callAPISuccess('contact', 'get', ['id' => $contactID]);
262 $displayName = $displayName['values'][$contactID]['display_name'];
263 $this->assertTrue(!empty($displayName));
265 $params = $this->_params
;
266 $params['api.Mailing.preview'] = [
268 'contact_id' => $contactID,
270 $params['options']['force_rollback'] = 1;
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'),
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;reset=1&jid=&qid=&h=">Forward this email with no protocol</a>', $previewResult['values']['body_html']);
294 $this->assertNotContains("http://http://", $previewResult['values']['body_html']);
297 public function testMailerPreviewUnknownContact() {
298 $params = $this->_params
;
299 $params['api.Mailing.preview'] = [
303 $result = $this->callAPISuccess('mailing', 'create', $params);
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']);
314 public function testMailerPreviewRecipients() {
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',
323 $contactIDs['exclude_me'] = $this->individualCreate([
324 'email' => 'exclude.me@example.org',
325 'last_name' => 'Excluder',
327 $this->callAPISuccess('GroupContact', 'create', [
328 'group_id' => $groupIDs['inc'],
329 'contact_id' => $contactIDs['include_me'],
331 $this->callAPISuccess('GroupContact', 'create', [
332 'group_id' => $groupIDs['inc'],
333 'contact_id' => $contactIDs['exclude_me'],
335 $this->callAPISuccess('GroupContact', 'create', [
336 'group_id' => $groupIDs['exc'],
337 'contact_id' => $contactIDs['exclude_me'],
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',
351 'api.email.getvalue' => [
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'),
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');
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] . '"');
377 * Test if Mailing recipients include duplicate OR on_hold emails
379 * @throws \CRM_Core_Exception
381 public function testMailerPreviewRecipientsDeduplicateAndOnholdEmails() {
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',
389 $contactIDs['include_me_duplicate'] = $this->individualCreate([
390 'email' => 'include.me@example.org',
391 'first_name' => 'IncluderDuplicate',
392 'last_name' => 'Person',
395 $contactIDs['include_me_onhold'] = $this->individualCreate([
396 'email' => 'onholdinclude.me@example.org',
397 'first_name' => 'Onhold',
398 'last_name' => 'Person',
400 $emailId = $this->callAPISuccessGetValue('Email', [
402 'contact_id' => $contactIDs['include_me_onhold'],
404 $this->callAPISuccess('Email', 'create', [
409 $this->callAPISuccess('GroupContact', 'create', [
410 'group_id' => $groupIDs['grp'],
411 'contact_id' => $contactIDs['include_me'],
413 $this->callAPISuccess('GroupContact', 'create', [
414 'group_id' => $groupIDs['grp'],
415 'contact_id' => $contactIDs['include_me_duplicate'],
417 $this->callAPISuccess('GroupContact', 'create', [
418 'group_id' => $groupIDs['grp'],
419 'contact_id' => $contactIDs['include_me_onhold'],
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',
432 'api.email.getvalue' => [
438 $create = $this->callAPISuccess('Mailing', 'create', $params);
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);
448 * Test sending a test mailing.
450 public function testMailerSendTest_email() {
451 $contactIDs['alice'] = $this->individualCreate([
452 'email' => 'alice@example.org',
453 'first_name' => 'Alice',
454 'last_name' => 'Person',
457 $mail = $this->callAPISuccess('mailing', 'create', $this->_params
);
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']);
467 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
468 $this->assertEquals([$contactIDs['alice']], $deliveredContacts);
470 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
471 $this->assertEquals(['alice@example.org'], $deliveredEmails);
477 public function testMailerSendTest_group() {
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',
485 $contactIDs['bob'] = $this->individualCreate([
486 'email' => 'bob@example.org',
487 'first_name' => 'Bob',
488 'last_name' => 'Person',
490 $contactIDs['carol'] = $this->individualCreate([
491 'email' => 'carol@example.org',
492 'first_name' => 'Carol',
493 'last_name' => 'Person',
495 $this->callAPISuccess('GroupContact', 'create', [
496 'group_id' => $groupIDs['inc'],
497 'contact_id' => $contactIDs['alice'],
499 $this->callAPISuccess('GroupContact', 'create', [
500 'group_id' => $groupIDs['inc'],
501 'contact_id' => $contactIDs['bob'],
503 $this->callAPISuccess('GroupContact', 'create', [
504 'group_id' => $groupIDs['inc'],
505 'contact_id' => $contactIDs['carol'],
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'],
515 // verify mail has been sent to user by count
516 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__
);
518 $deliveredContacts = array_values(CRM_Utils_Array
::collect('contact_id', $deliveredInfo['values']));
519 $this->assertEquals([$contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']], $deliveredContacts);
521 $deliveredEmails = array_values(CRM_Utils_Array
::collect('email', $deliveredInfo['values']));
522 $this->assertEquals(['alice@example.org', 'bob@example.org', 'carol@example.org'], $deliveredEmails);
528 public function submitProvider() {
529 // $useLogin, $params, $expectedFailure, $expectedJobCount
536 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
547 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
549 "/Failed to determine current user/",
558 ['scheduled_date' => '2014-12-13 10:00:00'],
571 "/Missing parameter scheduled_date and.or approval_date/",
580 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
582 "/Mailing cannot be sent. There are missing or invalid fields \\(name\\)./",
590 ['body_html' => '', 'body_text' => ''],
591 ['scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'],
593 "/Mailing cannot be sent. There are missing or invalid fields \\(body\\)./",
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'],
604 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_html.*optOut.*\\)./",
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'],
615 "/Mailing cannot be sent. There are missing or invalid fields \\(.*body_text.*optOut.*\\)./",
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'],
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'],
645 * @param bool $useLogin
646 * @param array $createParams
647 * @param array $submitParams
648 * @param null|string $expectedFailure
649 * @param int $expectedJobCount
651 * @dataProvider submitProvider
652 * @throws \CRM_Core_Exception
654 public function testMailerSubmit($useLogin, $createParams, $submitParams, $expectedFailure, $expectedJobCount) {
656 $this->createLoggedInUser();
659 if (isset($createParams['footer_id']) && $createParams['footer_id'] === '%FOOTER%') {
660 $createParams['footer_id'] = $this->footer
['id'];
663 $id = $this->createDraftMailing($createParams);
665 $submitParams['id'] = $id;
666 if ($expectedFailure) {
667 $submitResult = $this->callAPIFailure('mailing', 'submit', $submitParams);
668 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
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']);
676 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', [
677 1 => [$id, 'Integer'],
682 * Test unsubscribe list contains correct groups
683 * when include = 'previous mailing'
685 * @throws \CiviCRM_API3_Exception
686 * @throws \CRM_Core_Exception
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) {
695 'contact_id' => $contactId,
698 $this->callAPISuccess('GroupContact', 'create', $params);
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);
707 'mailing_id' => $mail['id'],
708 'entity_table' => 'civicrm_group',
709 'entity_id' => $groupID3,
710 'group_type' => 'Include',
712 $mailingGroup = $this->callAPISuccess('MailingGroup', 'create', $mgParams);
714 //Include previous mail in the mailing group.
715 $mail2 = $this->callAPISuccess('mailing', 'create', $this->_params
);
716 $params = ['mailing_id' => $mail2['id'], 'test_email' => NULL, 'test_group' => $groupID3];
717 $this->callAPISuccess($this->_entity
, 'send_test', $params);
720 'mailing_id' => $mail2['id'],
721 'entity_table' => 'civicrm_mailing',
722 'entity_id' => $mail['id'],
723 'group_type' => 'Include',
725 $this->callAPISuccess('MailingGroup', 'create', $mgParams);
726 //CRM-20431 - Delete group id that matches first mailing id.
727 $this->callAPISuccess('Group', 'delete', ['id' => $this->_groupID
]);
728 $jobId = CRM_Core_DAO
::getFieldValue('CRM_Mailing_DAO_MailingJob', $mail2['id'], 'id', 'mailing_id');
729 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_Event_DAO_Queue', $jobId, 'hash', 'job_id');
730 $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));
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']);
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']));
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);
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();
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}";
769 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
770 SELECT event_queue_id, time_stamp FROM {$temporaryTableName}";
772 CRM_Core_DAO
::executeQuery($sql);
775 $result = $this->callAPISuccess('mailing', 'stats', ['mailing_id' => $mail['id']]);
777 //since among 100 mails 20 has been bounced
781 'Unique Clicks' => 0,
782 'Unsubscribers' => 20,
783 'delivered_rate' => '80%',
784 'opened_rate' => '25%',
785 'clickthrough_rate' => '0%',
787 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
788 $temporaryTable->drop();
792 * Test civicrm_mailing_delete.
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']);
801 * Test Mailing.gettokens.
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']);
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]);
816 * Test clone function.
818 * @throws \CRM_Core_Exception
820 public function testClone() {
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',
828 $this->callAPISuccess('GroupContact', 'create', [
829 'group_id' => $groupIDs['inc'],
830 'contact_id' => $contactIDs['include_me'],
833 $params = $this->_params
;
834 $params['groups']['include'] = [$groupIDs['inc']];
835 $params['groups']['exclude'] = [];
836 $params['mailings']['include'] = [];
837 $params['mailings']['exclude'] = [];
840 $create = $this->callAPISuccess('Mailing', 'create', $params);
841 $created = $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'];
847 $this->assertNotEquals($createId, $cloneId, 'Create and clone should return different records');
848 $this->assertTrue(is_numeric($cloneId));
850 $this->assertNotEmpty($clone['values'][$cloneId]['subject']);
851 $this->assertEquals($params['subject'], $clone['values'][$cloneId]['subject'], "Cloned subject should match");
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');
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']);
865 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
867 //------------ civicrm_mailing_event_bounce methods------------
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
875 public function testMailerBounceWrongParams() {
877 'job_id' => 'Wrong ID',
878 'event_queue_id' => 'Wrong ID',
879 'hash' => 'Wrong Hash',
881 'time_stamp' => '20111109212100',
883 $this->callAPIFailure('mailing_event', 'bounce', $params,
884 'Queue event could not be found'
888 //----------- civicrm_mailing_event_confirm methods -----------
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
896 public function testMailerConfirmWrongParams() {
898 'contact_id' => 'Wrong ID',
899 'subscribe_id' => 'Wrong ID',
900 'hash' => 'Wrong Hash',
901 'event_subscribe_id' => '123',
902 'time_stamp' => '20111111010101',
904 $this->callAPIFailure('mailing_event', 'confirm', $params,
905 'contact_id is not a valid integer'
909 //---------- civicrm_mailing_event_reply methods -----------
912 * Test civicrm_mailing_event_reply with wrong params.
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
918 public function testMailerReplyWrongParams() {
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',
927 $this->callAPIFailure('mailing_event', 'reply', $params,
928 'Queue event could not be found'
932 //----------- civicrm_mailing_event_forward methods ----------
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
940 public function testMailerForwardWrongParams() {
942 'job_id' => 'Wrong ID',
943 'event_queue_id' => 'Wrong ID',
944 'hash' => 'Wrong Hash',
945 'email' => $this->_email
,
946 'time_stamp' => '20111111010101',
948 $this->callAPIFailure('mailing_event', 'forward', $params,
949 'Queue event could not be found'
954 * @param array $params
955 * Extra parameters for the draft mailing.
958 public function createDraftMailing($params = []) {
959 $createParams = array_merge($this->_params
, $params);
960 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__
, __FILE__
);
961 $this->assertTrue(is_numeric($createResult['id']));
962 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', [
963 1 => [$createResult['id'], 'Integer'],
965 return $createResult['id'];
969 * Test to make sure that if the event queue hashes have been archived,
970 * we can still have working click-trough URLs working (CRM-17959).
972 * @throws \CRM_Core_Exception
974 public function testUrlWithMissingTrackingHash() {
975 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['scheduled_date' => 'now'], __FUNCTION__
, __FILE__
);
976 $jobs = $this->callAPISuccess('mailing_job', 'get', ['mailing_id' => $mail['id']]);
977 $this->assertEquals(1, $jobs['count']);
979 $params = ['mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL];
980 $deliveredInfo = $this->callAPISuccess($this->_entity
, 'send_test', $params);
982 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
983 FROM civicrm_mailing_trackable_url as turl
984 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
985 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
986 ORDER BY turl.id DESC LIMIT 1";
988 $dao = CRM_Core_DAO
::executeQuery($sql);
989 $this->assertTrue($dao->fetch());
991 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
992 $this->assertContains('https://civicrm.org', $url);
994 // Now delete the event queue hashes and see if the tracking still works.
995 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
997 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
998 $this->assertContains('https://civicrm.org', $url);
1000 // Ensure that Google CSS link is not tracked.
1001 $sql = "SELECT id FROM civicrm_mailing_trackable_url where url = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700|Zilla+Slab:500,700'";
1002 $this->assertEquals([], CRM_Core_DAO
::executeQuery($sql)->fetchAll());
1006 * Test Trackable URL with unicode character
1008 public function testTrackableURLWithUnicodeSign() {
1009 $unicodeURL = "https://civiĆcrm.org";
1010 $this->_params
['body_text'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_text']);
1011 $this->_params
['body_html'] = str_replace("https://civicrm.org", $unicodeURL, $this->_params
['body_html']);
1013 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['scheduled_date' => 'now']);
1015 $params = ['mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL];
1016 $this->callAPISuccess($this->_entity
, 'send_test', $params);
1018 $sql = "SELECT turl.id as url_id, turl.url, q.id as queue_id
1019 FROM civicrm_mailing_trackable_url as turl
1020 INNER JOIN civicrm_mailing_job as j ON turl.mailing_id = j.mailing_id
1021 INNER JOIN civicrm_mailing_event_queue q ON j.id = q.job_id
1022 ORDER BY turl.id DESC LIMIT 1";
1024 $dao = CRM_Core_DAO
::executeQuery($sql);
1025 $this->assertTrue($dao->fetch());
1027 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
1028 $this->assertContains($unicodeURL, $url);
1030 // Now delete the event queue hashes and see if the tracking still works.
1031 CRM_Core_DAO
::executeQuery('DELETE FROM civicrm_mailing_event_queue');
1033 $url = CRM_Mailing_Event_BAO_TrackableURLOpen
::track($dao->queue_id
, $dao->url_id
);
1034 $this->assertContains($unicodeURL, $url);
1038 * CRM-20892 : Test if Mail.create API throws error on update,
1039 * if modified_date less then the date when the mail was last updated/created
1041 public function testModifiedDateMismatchOnMailingUpdate() {
1042 $mail = $this->callAPISuccess('mailing', 'create', $this->_params +
['modified_date' => 'now']);
1044 $this->callAPISuccess('mailing', 'create', $this->_params +
['id' => $mail['id'], 'modified_date' => '2 seconds ago']);
1046 catch (Exception
$e) {
1047 $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());
1052 * Test that api Mailing.update_email_resetdate does not throw a core error.
1054 * @throws \CRM_Core_Exception
1056 public function testUpdateEmailResetdate() {
1057 $this->callAPISuccess('Mailing', 'update_email_resetdate', []);