Merge pull request #4789 from totten/master-test-tx
[civicrm-core.git] / tests / phpunit / api / v3 / MailingTest.php
1 <?php
2 /*
3 * File for the TestMailing class
4 *
5 * (PHP 5)
6 *
7 * @package CiviCRM
8 *
9 * This file is part of CiviCRM
10 *
11 * CiviCRM is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Affero General Public License
13 * as published by the Free Software Foundation; either version 3 of
14 * the License, or (at your option) any later version.
15 *
16 * CiviCRM is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU Affero General Public License for more details.
20 *
21 * You should have received a copy of the GNU Affero General Public
22 * License along with this program. If not, see
23 * <http://www.gnu.org/licenses/>.
24 */
25
26 require_once 'CiviTest/CiviUnitTestCase.php';
27
28
29 /**
30 * Test APIv3 civicrm_mailing_* functions
31 *
32 * @package CiviCRM
33 */
34 class api_v3_MailingTest extends CiviUnitTestCase {
35 protected $_groupID;
36 protected $_email;
37 protected $_apiversion = 3;
38 protected $_params = array();
39 protected $_entity = 'Mailing';
40 protected $_contactID;
41
42 function setUp() {
43 parent::setUp();
44 $this->useTransaction();
45 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
46 $this->_contactID = $this->individualCreate();
47 $this->_groupID = $this->groupCreate();
48 $this->_email = 'test@test.test';
49 $this->_params = array(
50 'subject' => 'Hello {contact.display_name}',
51 'body_text' => "This is {contact.display_name}",
52 'body_html' => "<p>This is {contact.display_name}</p>",
53 'name' => 'mailing name',
54 'created_id' => $this->_contactID,
55 );
56 }
57
58 function tearDown() {
59 CRM_Mailing_BAO_MailingJob::$mailsProcessed = 0; // DGW
60 parent::tearDown();
61 }
62
63 /**
64 * Test civicrm_mailing_create
65 */
66 public function testMailerCreateSuccess() {
67 $result = $this->callAPIAndDocument('mailing', 'create', $this->_params, __FUNCTION__, __FILE__);
68 $jobs = $this->callAPISuccess('mailing_job', 'get', array('mailing_id' => $result['id']));
69 $this->assertEquals(1, $jobs['count']);
70 unset($this->_params['created_id']); // return isn't working on this in getAndCheck so lets not check it for now
71 $this->getAndCheck($this->_params, $result['id'], 'mailing');
72 }
73
74 /**
75 * The Mailing.create API supports magic properties "groups[include,enclude]" and "mailings[include,exclude]".
76 * Make sure these work
77 */
78 public function testMagicGroups_create_update() {
79 // BEGIN SAMPLE DATA
80 $groupIDs['a'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
81 $groupIDs['b'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
82 $contactIDs['a'] = $this->individualCreate(array('email' => 'include.me@example.org', 'first_name' => 'Includer', 'last_name' => 'Person'));
83 $contactIDs['b'] = $this->individualCreate(array('email' => 'exclude.me@example.org', 'last_name' => 'Excluder', 'last_name' => 'Excluder'));
84 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['a'], 'contact_id' => $contactIDs['a']));
85 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['b'], 'contact_id' => $contactIDs['b']));
86 // END SAMPLE DATA
87
88 // ** Pass 1: Create
89 $createParams = $this->_params;
90 $createParams['groups']['include'] = array($groupIDs['a']);
91 $createParams['groups']['exclude'] = array();
92 $createParams['mailings']['include'] = array();
93 $createParams['mailings']['exclude'] = array();
94 $createResult = $this->callAPISuccess('Mailing', 'create', $createParams);
95 $getGroup1 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
96 $getGroup1_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup1['values']));
97 $this->assertEquals(array($groupIDs['a']), $getGroup1_ids);
98 $getRecip1 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
99 $getRecip1_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecip1['values']));
100 $this->assertEquals(array($contactIDs['a']), $getRecip1_ids);
101
102 // ** Pass 2: Update without any changes to groups[include]
103 $nullopParams = $createParams;
104 $nullopParams['id'] = $createResult['id'];
105 $updateParams['api.mailing_job.create'] = 1;
106 unset($nullopParams['groups']['include']);
107 $this->callAPISuccess('Mailing', 'create', $nullopParams);
108 $getGroup2 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
109 $getGroup2_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup2['values']));
110 $this->assertEquals(array($groupIDs['a']), $getGroup2_ids);
111 $getRecip2 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
112 $getRecip2_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecip2['values']));
113 $this->assertEquals(array($contactIDs['a']), $getRecip2_ids);
114
115 // ** Pass 3: Update with different groups[include]
116 $updateParams = $createParams;
117 $updateParams['id'] = $createResult['id'];
118 $updateParams['groups']['include'] = array($groupIDs['b']);
119 $updateParams['api.mailing_job.create'] = 1;
120 $this->callAPISuccess('Mailing', 'create', $updateParams);
121 $getGroup3 = $this->callAPISuccess('MailingGroup', 'get', array('mailing_id' => $createResult['id']));
122 $getGroup3_ids = array_values(CRM_Utils_Array::collect('entity_id', $getGroup3['values']));
123 $this->assertEquals(array($groupIDs['b']), $getGroup3_ids);
124 $getRecip3 = $this->callAPISuccess('MailingRecipients', 'get', array('mailing_id' => $createResult['id']));
125 $getRecip3_ids = array_values(CRM_Utils_Array::collect('contact_id', $getRecip3['values']));
126 $this->assertEquals(array($contactIDs['b']), $getRecip3_ids);
127 }
128
129 public function testMailerPreview() {
130 // BEGIN SAMPLE DATA
131 $contactID = $this->individualCreate();
132 $displayName = $this->callAPISuccess('contact', 'get', array('id' => $contactID));
133 $displayName = $displayName['values'][$contactID]['display_name'];
134 $this->assertTrue(!empty($displayName));
135
136 $params = $this->_params;
137 $params['api.Mailing.preview'] = array(
138 'id' => '$value.id',
139 'contact_id' => $contactID,
140 );
141 $params['options']['force_rollback'] = 1;
142 // END SAMPLE DATA
143
144 $maxIDs = array(
145 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
146 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
147 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
148 'recip' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_recipients'),
149 );
150 $result = $this->callAPISuccess('mailing', 'create', $params);
151 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
152 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
153 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
154 $this->assertDBQuery($maxIDs['recip'], 'SELECT MAX(id) FROM civicrm_mailing_recipients'); // 'Preview should not create any mailing_recipient records'
155
156 $previewResult = $result['values'][$result['id']]['api.Mailing.preview'];
157 $this->assertEquals("Hello $displayName", $previewResult['values']['subject']);
158 $this->assertEquals("This is $displayName", $previewResult['values']['body_text']);
159 $this->assertContains("<p>This is $displayName</p>", $previewResult['values']['body_html']);
160 }
161
162 public function testMailerPreviewRecipients() {
163 // BEGIN SAMPLE DATA
164 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
165 $groupIDs['exc'] = $this->groupCreate(array('name' => 'Example exclude group', 'title' => 'Example exclude group'));
166 $contactIDs['includeme'] = $this->individualCreate(array('email' => 'include.me@example.org', 'first_name' => 'Includer', 'last_name' => 'Person'));
167 $contactIDs['excludeme'] = $this->individualCreate(array('email' => 'exclude.me@example.org', 'last_name' => 'Excluder', 'last_name' => 'Excluder'));
168 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['includeme']));
169 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['excludeme']));
170 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['exc'], 'contact_id' => $contactIDs['excludeme']));
171
172 $params = $this->_params;
173 $params['groups']['include'] = array($groupIDs['inc']);
174 $params['groups']['exclude'] = array($groupIDs['exc']);
175 $params['mailings']['include'] = array();
176 $params['mailings']['exclude'] = array();
177 $params['options']['force_rollback'] = 1;
178 $params['api.MailingRecipients.get'] = array(
179 'mailing_id' => '$value.id',
180 'api.contact.getvalue' => array(
181 'return' => 'display_name',
182 ),
183 'api.email.getvalue' => array(
184 'return' => 'email',
185 ),
186 );
187 // END SAMPLE DATA
188
189 $maxIDs = array(
190 'mailing' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing'),
191 'job' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_job'),
192 'group' => CRM_Core_DAO::singleValueQuery('SELECT MAX(id) FROM civicrm_mailing_group'),
193 );
194 $create = $this->callAPIAndDocument('Mailing', 'create', $params, __FUNCTION__, __FILE__);
195 $this->assertDBQuery($maxIDs['mailing'], 'SELECT MAX(id) FROM civicrm_mailing'); // 'Preview should not create any mailing records'
196 $this->assertDBQuery($maxIDs['job'], 'SELECT MAX(id) FROM civicrm_mailing_job'); // 'Preview should not create any mailing_job record'
197 $this->assertDBQuery($maxIDs['group'], 'SELECT MAX(id) FROM civicrm_mailing_group'); // 'Preview should not create any mailing_group records'
198
199 $preview = $create['values'][$create['id']]['api.MailingRecipients.get'];
200 $previewIds = array_values(CRM_Utils_Array::collect('contact_id', $preview['values']));
201 $this->assertEquals(array((string)$contactIDs['includeme']), $previewIds);
202 $previewEmails = array_values(CRM_Utils_Array::collect('api.email.getvalue', $preview['values']));
203 $this->assertEquals(array('include.me@example.org'), $previewEmails);
204 $previewNames = array_values(CRM_Utils_Array::collect('api.contact.getvalue', $preview['values']));
205 $this->assertTrue((bool)preg_match('/Includer Person/', $previewNames[0]), "Name 'Includer Person' should appear in '" . $previewNames[0] . '"');
206 }
207
208 public function testMailerSendTest_email() {
209 $contactIDs['alice'] = $this->individualCreate(array('email' => 'alice@example.org', 'first_name' => 'Alice', 'last_name' => 'Person'));
210
211 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
212
213 $params = array('mailing_id' => $mail['id'], 'test_email' => 'alice@example.org', 'test_group' => NULL);
214 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
215 $this->assertEquals(1, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
216
217 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
218 $this->assertEquals(array($contactIDs['alice']), $deliveredContacts);
219
220 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
221 $this->assertEquals(array('alice@example.org'), $deliveredEmails);
222 }
223
224 public function testMailerSendTest_group() {
225 // BEGIN SAMPLE DATA
226 $groupIDs['inc'] = $this->groupCreate(array('name' => 'Example include group', 'title' => 'Example include group'));
227 $contactIDs['alice'] = $this->individualCreate(array('email' => 'alice@example.org', 'first_name' => 'Alice', 'last_name' => 'Person'));
228 $contactIDs['bob'] = $this->individualCreate(array('email' => 'bob@example.org', 'first_name' => 'Bob', 'last_name' => 'Person'));
229 $contactIDs['carol'] = $this->individualCreate(array('email' => 'carol@example.org', 'first_name' => 'Carol', 'last_name' => 'Person'));
230 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['alice']));
231 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['bob']));
232 $this->callAPISuccess('GroupContact', 'create', array('group_id' => $groupIDs['inc'], 'contact_id' => $contactIDs['carol']));
233 // END SAMPLE DATA
234
235 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
236 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', array(
237 'mailing_id' => $mail['id'],
238 'test_email' => NULL,
239 'test_group' => $groupIDs['inc'],
240 ));
241 $this->assertEquals(3, $deliveredInfo['count'], "in line " . __LINE__); // verify mail has been sent to user by count
242
243 $deliveredContacts = array_values(CRM_Utils_Array::collect('contact_id', $deliveredInfo['values']));
244 $this->assertEquals(array($contactIDs['alice'], $contactIDs['bob'], $contactIDs['carol']), $deliveredContacts);
245
246 $deliveredEmails = array_values(CRM_Utils_Array::collect('email', $deliveredInfo['values']));
247 $this->assertEquals(array('alice@example.org', 'bob@example.org', 'carol@example.org'), $deliveredEmails);
248 }
249
250 public function submitProvider() {
251 $cases = array(); // $useLogin, $params, $expectedFailure, $expectedJobCount
252 $cases[] = array(
253 TRUE, //useLogin
254 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
255 FALSE, // expectedFailure
256 1, // expectedJobCount
257 );
258 $cases[] = array(
259 FALSE, //useLogin
260 array('scheduled_date' => '2014-12-13 10:00:00', 'approval_date' => '2014-12-13 00:00:00'),
261 "/Failed to determine current user/", // expectedFailure
262 0, // expectedJobCount
263 );
264 $cases[] = array(
265 TRUE, //useLogin
266 array('scheduled_date' => '2014-12-13 10:00:00'),
267 FALSE, // expectedFailure
268 1, // expectedJobCount
269 );
270 $cases[] = array(
271 TRUE, //useLogin
272 array(),
273 "/Missing parameter scheduled_date and.or approval_date/", // expectedFailure
274 0, // expectedJobCount
275 );
276 return $cases;
277 }
278
279 /**
280 * @param bool $useLogin
281 * @param array $params
282 * @param null|string $expectedFailure
283 * @param int $expectedJobCount
284 * @dataProvider submitProvider
285 */
286 public function testMailerSubmit($useLogin, $params, $expectedFailure, $expectedJobCount) {
287 if ($useLogin) {
288 $this->createLoggedInUser();
289 }
290
291 $id = $this->createDraftMailing();
292
293 $params['id'] = $id;
294 if ($expectedFailure) {
295 $submitResult = $this->callAPIFailure('mailing', 'submit', $params);
296 $this->assertRegExp($expectedFailure, $submitResult['error_message']);
297 }
298 else {
299 $submitResult = $this->callAPIAndDocument('mailing', 'submit', $params, __FUNCTION__, __FILE__);
300 $this->assertTrue(is_numeric($submitResult['id']));
301 $this->assertTrue(is_numeric($submitResult['values'][$id]['scheduled_id']));
302 $this->assertEquals($params['scheduled_date'], $submitResult['values'][$id]['scheduled_date']);
303 }
304 $this->assertDBQuery($expectedJobCount, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
305 1 => array($id, 'Integer')
306 ));
307 }
308
309 public function testMailerStats() {
310 $result = $this->groupContactCreate($this->_groupID, 100);
311 $this->assertEquals(100, $result['added']); //verify if 100 contacts are added for group
312
313 //Create and send test mail first and change the mail job to live,
314 //because stats api only works on live mail
315 $mail = $this->callAPISuccess('mailing', 'create', $this->_params);
316 $params = array('mailing_id' => $mail['id'], 'test_email' => NULL, 'test_group' => $this->_groupID);
317 $deliveredInfo = $this->callAPISuccess($this->_entity, 'send_test', $params);
318 $deliveredIds = implode(',', array_keys($deliveredInfo['values']));
319
320 //Change the test mail into live
321 $sql = "UPDATE civicrm_mailing_job SET is_test = 0 WHERE mailing_id = {$mail['id']}";
322 CRM_Core_DAO::executeQuery($sql);
323
324 foreach (array('bounce', 'unsubscribe', 'opened') as $type) {
325 $sql = "CREATE TEMPORARY TABLE mail_{$type}_temp
326 (event_queue_id int, time_stamp datetime, delivered_id int)
327 SELECT event_queue_id, time_stamp, id
328 FROM civicrm_mailing_event_delivered
329 WHERE id IN ($deliveredIds)
330 ORDER BY RAND() LIMIT 0,20;";
331 CRM_Core_DAO::executeQuery($sql);
332
333 $sql = "DELETE FROM civicrm_mailing_event_delivered WHERE id IN (SELECT delivered_id FROM mail_{$type}_temp);";
334 CRM_Core_DAO::executeQuery($sql);
335
336 if ($type == 'unsubscribe') {
337 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp, org_unsubscribe)
338 SELECT event_queue_id, time_stamp, 1 FROM mail_{$type}_temp";
339 }
340 else {
341 $sql = "INSERT INTO civicrm_mailing_event_{$type} (event_queue_id, time_stamp)
342 SELECT event_queue_id, time_stamp FROM mail_{$type}_temp";
343 }
344 CRM_Core_DAO::executeQuery($sql);
345 }
346
347 $result = $this->callAPISuccess('mailing', 'stats', array('mailing_id' => $mail['id']));
348 $expectedResult = array(
349 'Delivered' => 80, //since among 100 mails 20 has been bounced
350 'Bounces' => 20,
351 'Opened' => 20,
352 'Unique Clicks' => 0,
353 'Unsubscribers' => 20
354 );
355 $this->checkArrayEquals($expectedResult, $result['values'][$mail['id']]);
356 }
357 /**
358 * Test civicrm_mailing_delete
359 */
360 public function testMailerDeleteSuccess() {
361 $result = $this->callAPISuccess($this->_entity, 'create', $this->_params);
362 $jobs = $this->callAPIAndDocument($this->_entity, 'delete', array('id' => $result['id']), __FUNCTION__, __FILE__);
363 $this->assertAPIDeleted($this->_entity, $result['id']);
364 }
365
366 //@ todo tests below here are all failure tests which are not hugely useful - need success tests
367
368 //------------ civicrm_mailing_event_bounce methods------------
369
370 /**
371 * Test civicrm_mailing_event_bounce with wrong params.
372 * Note that tests like this are slightly better than no test but an
373 * api function cannot be considered supported / 'part of the api' without a
374 * success test
375 */
376 public function testMailerBounceWrongParams() {
377 $params = array(
378 'job_id' => 'Wrong ID',
379 'event_queue_id' => 'Wrong ID',
380 'hash' => 'Wrong Hash',
381 'body' => 'Body...',
382 'time_stamp' => '20111109212100',
383 );
384 $result = $this->callAPIFailure('mailing_event', 'bounce', $params,
385 'Queue event could not be found'
386 );
387 }
388
389 //----------- civicrm_mailing_event_confirm methods -----------
390
391 /**
392 * Test civicrm_mailing_event_confirm with wrong params.
393 * Note that tests like this are slightly better than no test but an
394 * api function cannot be considered supported / 'part of the api' without a
395 * success test
396 */
397 public function testMailerConfirmWrongParams() {
398 $params = array(
399 'contact_id' => 'Wrong ID',
400 'subscribe_id' => 'Wrong ID',
401 'hash' => 'Wrong Hash',
402 'event_subscribe_id' => '123',
403 'time_stamp' => '20111111010101',
404 );
405 $result = $this->callAPIFailure('mailing_event', 'confirm', $params,
406 'Confirmation failed'
407 );
408 }
409
410 //---------- civicrm_mailing_event_reply methods -----------
411
412 /**
413 * Test civicrm_mailing_event_reply with wrong params.
414 *
415 * Note that tests like this are slightly better than no test but an
416 * api function cannot be considered supported / 'part of the api' without a
417 * success test
418 */
419 public function testMailerReplyWrongParams() {
420 $params = array(
421 'job_id' => 'Wrong ID',
422 'event_queue_id' => 'Wrong ID',
423 'hash' => 'Wrong Hash',
424 'bodyTxt' => 'Body...',
425 'replyTo' => $this->_email,
426 'time_stamp' => '20111111010101',
427 );
428 $result = $this->callAPIFailure('mailing_event', 'reply', $params,
429 'Queue event could not be found'
430 );
431 }
432
433
434 //----------- civicrm_mailing_event_forward methods ----------
435
436 /**
437 * Test civicrm_mailing_event_forward with wrong params.
438 * Note that tests like this are slightly better than no test but an
439 * api function cannot be considered supported / 'part of the api' without a
440 * success test
441 */
442 public function testMailerForwardWrongParams() {
443 $params = array(
444 'job_id' => 'Wrong ID',
445 'event_queue_id' => 'Wrong ID',
446 'hash' => 'Wrong Hash',
447 'email' => $this->_email,
448 'time_stamp' => '20111111010101',
449 );
450 $result = $this->callAPIFailure('mailing_event', 'forward', $params,
451 'Queue event could not be found'
452 );
453 }
454
455 /**
456 * @return array|int
457 */
458 public function createDraftMailing() {
459 $createParams = $this->_params;
460 $createParams['api.mailing_job.create'] = 0; // note: exact match to API default
461 $createResult = $this->callAPISuccess('mailing', 'create', $createParams, __FUNCTION__, __FILE__);
462 $this->assertTrue(is_numeric($createResult['id']));
463 $this->assertDBQuery(0, 'SELECT count(*) FROM civicrm_mailing_job WHERE mailing_id = %1', array(
464 1 => array($createResult['id'], 'Integer')
465 ));
466 return $createResult['id'];
467 }
468
469 //----------- civicrm_mailing_create ----------
470
471 }