Merge pull request #15699 from mattwire/participant_cleanup_completeOrderPBRef
[civicrm-core.git] / tests / phpunit / api / v3 / UtilsTest.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 require_once 'CRM/Utils/DeprecatedUtils.php';
29
30 /**
31 * Test class for API utils
32 *
33 * @package CiviCRM
34 * @group headless
35 */
36 class api_v3_UtilsTest extends CiviUnitTestCase {
37 protected $_apiversion = 3;
38 public $DBResetRequired = FALSE;
39
40 public $_contactID = 1;
41
42 /**
43 * Sets up the fixture, for example, opens a network connection.
44 *
45 * This method is called before a test is executed.
46 */
47 protected function setUp() {
48 parent::setUp();
49 $this->useTransaction(TRUE);
50 }
51
52 public function testAddFormattedParam() {
53 $values = ['contact_type' => 'Individual'];
54 $params = ['something' => 1];
55 $result = _civicrm_api3_deprecated_add_formatted_param($values, $params);
56 $this->assertTrue($result);
57 }
58
59 public function testCheckPermissionReturn() {
60 $check = ['check_permissions' => TRUE];
61 $config = CRM_Core_Config::singleton();
62 $config->userPermissionClass->permissions = [];
63 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'empty permissions should not be enough');
64 $config->userPermissionClass->permissions = ['access CiviCRM'];
65 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
66 $config->userPermissionClass->permissions = ['add contacts'];
67 $this->assertFalse($this->runPermissionCheck('contact', 'create', $check), 'lacking permissions should not be enough');
68
69 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts'];
70 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'exact permissions should be enough');
71
72 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts', 'import contacts'];
73 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should be enough');
74 }
75
76 public function testCheckPermissionThrow() {
77 $check = ['check_permissions' => TRUE];
78 $config = CRM_Core_Config::singleton();
79 try {
80 $config->userPermissionClass->permissions = ['access CiviCRM'];
81 $this->runPermissionCheck('contact', 'create', $check, TRUE);
82 }
83 catch (Exception $e) {
84 $message = $e->getMessage();
85 }
86 $this->assertEquals($message, 'API permission check failed for Contact/create call; insufficient permission: require access CiviCRM and add contacts', 'lacking permissions should throw an exception');
87
88 $config->userPermissionClass->permissions = ['access CiviCRM', 'add contacts', 'import contacts'];
89 $this->assertTrue($this->runPermissionCheck('contact', 'create', $check), 'overfluous permissions should return true');
90 }
91
92 public function testCheckPermissionSkip() {
93 $config = CRM_Core_Config::singleton();
94 $config->userPermissionClass->permissions = ['access CiviCRM'];
95 $params = ['check_permissions' => TRUE];
96 $this->assertFalse($this->runPermissionCheck('contact', 'create', $params), 'lacking permissions should not be enough');
97 $params = ['check_permissions' => FALSE];
98 $this->assertTrue($this->runPermissionCheck('contact', 'create', $params), 'permission check should be skippable');
99 }
100
101 /**
102 * @param string $entity
103 * @param string $action
104 * @param array $params
105 * @param bool $throws
106 * Whether we should pass any exceptions for authorization failures.
107 *
108 * @throws API_Exception
109 * @throws Exception
110 * @return bool
111 * TRUE or FALSE depending on the outcome of the authorization check
112 */
113 public function runPermissionCheck($entity, $action, $params, $throws = FALSE) {
114 $dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
115 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
116 $kernel = new \Civi\API\Kernel($dispatcher);
117 $apiRequest = \Civi\API\Request::create($entity, $action, $params, NULL);
118 try {
119 $kernel->authorize(NULL, $apiRequest);
120 return TRUE;
121 }
122 catch (\API_Exception $e) {
123 $extra = $e->getExtraParams();
124 if (!$throws && $extra['error_code'] == API_Exception::UNAUTHORIZED) {
125 return FALSE;
126 }
127 else {
128 throw $e;
129 }
130 }
131 }
132
133 /**
134 * Test verify mandatory - includes DAO & passed as well as empty & NULL fields
135 */
136 public function testVerifyMandatory() {
137 _civicrm_api3_initialize(TRUE);
138 $params = [
139 'entity_table' => 'civicrm_contact',
140 'note' => '',
141 'contact_id' => $this->_contactID,
142 'modified_date' => '2011-01-31',
143 'subject' => NULL,
144 'version' => $this->_apiversion,
145 ];
146 try {
147 civicrm_api3_verify_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
148 }
149 catch (Exception $expected) {
150 $this->assertEquals('Mandatory key(s) missing from params array: note, subject', $expected->getMessage());
151 return;
152 }
153
154 $this->fail('An expected exception has not been raised.');
155 }
156
157 /**
158 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
159 */
160 public function testVerifyOneMandatory() {
161 _civicrm_api3_initialize(TRUE);
162 $params = [
163 'entity_table' => 'civicrm_contact',
164 'note' => '',
165 'contact_id' => $this->_contactID,
166 'modified_date' => '2011-01-31',
167 'subject' => NULL,
168 'version' => $this->_apiversion,
169 ];
170
171 try {
172 civicrm_api3_verify_one_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
173 }
174 catch (Exception $expected) {
175 $this->assertEquals('Mandatory key(s) missing from params array: one of (note, subject)', $expected->getMessage());
176 return;
177 }
178
179 $this->fail('An expected exception has not been raised.');
180 }
181
182 /**
183 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
184 */
185 public function testVerifyOneMandatoryOneSet() {
186 _civicrm_api3_initialize(TRUE);
187 $params = [
188 'version' => 3,
189 'entity_table' => 'civicrm_contact',
190 'note' => 'note',
191 'contact_id' => $this->_contactID,
192 'modified_date' => '2011-01-31',
193 'subject' => NULL,
194 ];
195
196 try {
197 civicrm_api3_verify_one_mandatory($params, NULL, ['note', 'subject']);
198 }
199 catch (Exception$expected) {
200 $this->fail('Exception raised when it shouldn\'t have been in line ' . __LINE__);
201 }
202 }
203
204 /**
205 * Test GET DAO function returns DAO.
206 */
207 public function testGetDAO() {
208 $params = [
209 'civicrm_api3_custom_group_get' => 'CRM_Core_DAO_CustomGroup',
210 'custom_group' => 'CRM_Core_DAO_CustomGroup',
211 'CustomGroup' => 'CRM_Core_DAO_CustomGroup',
212 'civicrm_api3_custom_field_get' => 'CRM_Core_DAO_CustomField',
213 'civicrm_api3_survey_get' => 'CRM_Campaign_DAO_Survey',
214 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_DAO_PledgePayment',
215 'civicrm_api3_website_get' => 'CRM_Core_DAO_Website',
216 'Membership' => 'CRM_Member_DAO_Membership',
217 ];
218 foreach ($params as $input => $expected) {
219 $result = _civicrm_api3_get_DAO($input);
220 $this->assertEquals($expected, $result);
221 }
222 }
223
224 /**
225 * Test GET BAO function returns BAO when it exists.
226 */
227 public function testGetBAO() {
228 $params = [
229 'civicrm_api3_website_get' => 'CRM_Core_BAO_Website',
230 'civicrm_api3_survey_get' => 'CRM_Campaign_BAO_Survey',
231 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_BAO_PledgePayment',
232 'Household' => 'CRM_Contact_BAO_Contact',
233 // Note this one DOES NOT have a BAO so we expect to fall back on returning the DAO
234 'mailing_group' => 'CRM_Mailing_DAO_MailingGroup',
235 // Make sure we get null back with nonexistant entities
236 'civicrm_this_does_not_exist' => NULL,
237 ];
238 foreach ($params as $input => $expected) {
239 $result = _civicrm_api3_get_BAO($input);
240 $this->assertEquals($expected, $result);
241 }
242 }
243
244 /**
245 * Test the validate function transforms dates.
246 *
247 * @throws \CiviCRM_API3_Exception
248 * @throws \Exception
249 */
250 public function test_civicrm_api3_validate_fields() {
251 $params = ['relationship_start_date' => '2010-12-20', 'relationship_end_date' => ''];
252 $fields = civicrm_api3('relationship', 'getfields', ['action' => 'get']);
253 _civicrm_api3_validate_fields('relationship', 'get', $params, $fields['values']);
254 $this->assertEquals('20101220000000', $params['relationship_start_date']);
255 $this->assertEquals('', $params['relationship_end_date']);
256 }
257
258 public function test_civicrm_api3_validate_fields_membership() {
259 $params = [
260 'start_date' => '2010-12-20',
261 'end_date' => '',
262 'membership_end_date' => '0',
263 'membership_join_date' => '2010-12-20',
264 'membership_start_date' => '2010-12-20',
265 ];
266 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
267 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
268 $this->assertEquals('2010-12-20', $params['start_date']);
269 $this->assertEquals('20101220000000', $params['membership_start_date']);
270 $this->assertEquals('', $params['end_date']);
271 $this->assertEquals('20101220000000', $params['membership_join_date'], 'join_date not set in line ' . __LINE__);
272 }
273
274 public function test_civicrm_api3_validate_fields_event() {
275
276 $params = [
277 'registration_start_date' => 20080601,
278 'registration_end_date' => '2008-10-15',
279 'start_date' => '2010-12-20',
280 'end_date' => '',
281 ];
282 $fields = civicrm_api3('Event', 'getfields', ['action' => 'create']);
283 _civicrm_api3_validate_fields('event', 'create', $params, $fields['values']);
284 $this->assertEquals('20101220000000', $params['start_date']);
285 $this->assertEquals('20081015000000', $params['registration_end_date']);
286 $this->assertEquals('', $params['end_date']);
287 $this->assertEquals('20080601000000', $params['registration_start_date']);
288 }
289
290 public function test_civicrm_api3_validate_fields_exception() {
291 $params = [
292 'membership_join_date' => 'abc',
293 ];
294 try {
295 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
296 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
297 }
298 catch (Exception$expected) {
299 $this->assertEquals('membership_join_date is not a valid date: abc', $expected->getMessage());
300 }
301 }
302
303 public function testGetFields() {
304 $result = $this->callAPISuccess('membership', 'getfields', []);
305 $this->assertArrayHasKey('values', $result);
306 $result = $this->callAPISuccess('relationship', 'getfields', []);
307 $this->assertArrayHasKey('values', $result);
308 $result = $this->callAPISuccess('event', 'getfields', []);
309 $this->assertArrayHasKey('values', $result);
310 }
311
312 public function testGetFields_AllOptions() {
313 $result = $this->callAPISuccess('contact', 'getfields', [
314 'options' => [
315 'get_options' => 'all',
316 ],
317 ]);
318 $this->assertEquals('Household', $result['values']['contact_type']['options']['Household']);
319 $this->assertEquals('HTML', $result['values']['preferred_mail_format']['options']['HTML']);
320 }
321
322 public function basicArrayCases() {
323 $records = [
324 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
325 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
326 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
327 ['snack_id' => 'd', 'fruit' => 'apple', 'cheese' => 'gouda'],
328 ['snack_id' => 'e', 'fruit' => 'apple', 'cheese' => 'provolone'],
329 ];
330
331 $cases[] = [
332 $records,
333 // params
334 ['version' => 3],
335 // expected results
336 ['a', 'b', 'c', 'd', 'e'],
337 ];
338
339 $cases[] = [
340 $records,
341 // params
342 ['version' => 3, 'fruit' => 'apple'],
343 // expected results
344 ['a', 'c', 'd', 'e'],
345 ];
346
347 $cases[] = [
348 $records,
349 ['version' => 3, 'cheese' => 'cheddar'],
350 ['b', 'c'],
351 ];
352
353 $cases[] = [
354 $records,
355 ['version' => 3, 'id' => 'd'],
356 ['d'],
357 ];
358
359 return $cases;
360 }
361
362 /**
363 * Make a basic API (Widget.get) which allows getting data out of a simple in-memory
364 * list of records.
365 *
366 * @param $records
367 * The list of all records.
368 * @param $params
369 * The filter criteria
370 * @param array $resultIds
371 * The records which are expected to match.
372 * @dataProvider basicArrayCases
373 */
374 public function testBasicArrayGet($records, $params, $resultIds) {
375 $params['version'] = 3;
376
377 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
378
379 $provider = new \Civi\API\Provider\AdhocProvider($params['version'], 'Widget');
380 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
381 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
382 });
383 $kernel->registerApiProvider($provider);
384
385 $r1 = $kernel->run('Widget', 'get', $params);
386 $this->assertEquals(count($resultIds), $r1['count']);
387 $this->assertEquals($resultIds, array_keys($r1['values']));
388 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r1['values'])));
389 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r1['values'])));
390
391 $r2 = $kernel->run('Widget', 'get', $params + ['sequential' => 1]);
392 $this->assertEquals(count($resultIds), $r2['count']);
393 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r2['values'])));
394 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r2['values'])));
395
396 $r3 = $kernel->run('Widget', 'get', $params + ['options' => ['offset' => 1, 'limit' => 2]]);
397 $slice = array_slice($resultIds, 1, 2);
398 $this->assertEquals(count($slice), $r3['count']);
399 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('snack_id', $r3['values'])));
400 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('id', $r3['values'])));
401 }
402
403 public function testBasicArrayGetReturn() {
404 $records = [
405 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
406 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
407 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
408 ];
409
410 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
411 $provider = new \Civi\API\Provider\AdhocProvider(3, 'Widget');
412 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
413 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
414 });
415 $kernel->registerApiProvider($provider);
416
417 $r1 = $kernel->run('Widget', 'get', [
418 'version' => 3,
419 'snack_id' => 'b',
420 'return' => 'fruit',
421 ]);
422 $this->assertAPISuccess($r1);
423 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape']], $r1['values']);
424
425 $r2 = $kernel->run('Widget', 'get', [
426 'version' => 3,
427 'snack_id' => 'b',
428 'return' => ['fruit', 'cheese'],
429 ]);
430 $this->assertAPISuccess($r2);
431 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar']], $r2['values']);
432
433 $r3 = $kernel->run('Widget', 'get', [
434 'version' => 3,
435 'cheese' => 'cheddar',
436 'return' => ['fruit'],
437 ]);
438 $this->assertAPISuccess($r3);
439 $this->assertEquals([
440 'b' => ['id' => 'b', 'fruit' => 'grape'],
441 'c' => ['id' => 'c', 'fruit' => 'apple'],
442 ], $r3['values']);
443 }
444
445 /**
446 * CRM-20892 Add Tests of new timestamp checking function
447 */
448 public function testTimeStampChecking() {
449 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_mailing (id, modified_date) VALUES (25, '2016-06-30 12:52:52')");
450 $this->assertTrue(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
451 $this->callAPISuccess('Mailing', 'create', ['id' => 25, 'subject' => 'Test Subject']);
452 $this->assertFalse(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
453 $this->callAPISuccess('Mailing', 'delete', ['id' => 25]);
454 }
455
456 }