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