Merge pull request #17037 from eileenmcnaughton/dupe
[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 $params['version'] = 3;
99 $dispatcher = new \Symfony\Component\EventDispatcher\EventDispatcher();
100 $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
101 $kernel = new \Civi\API\Kernel($dispatcher);
102 $apiRequest = \Civi\API\Request::create($entity, $action, $params);
103 try {
104 $kernel->authorize(NULL, $apiRequest);
105 return TRUE;
106 }
107 catch (\API_Exception $e) {
108 $extra = $e->getExtraParams();
109 if (!$throws && $extra['error_code'] == API_Exception::UNAUTHORIZED) {
110 return FALSE;
111 }
112 else {
113 throw $e;
114 }
115 }
116 }
117
118 /**
119 * Test verify mandatory - includes DAO & passed as well as empty & NULL fields
120 */
121 public function testVerifyMandatory() {
122 _civicrm_api3_initialize(TRUE);
123 $params = [
124 'entity_table' => 'civicrm_contact',
125 'note' => '',
126 'contact_id' => $this->_contactID,
127 'modified_date' => '2011-01-31',
128 'subject' => NULL,
129 'version' => $this->_apiversion,
130 ];
131 try {
132 civicrm_api3_verify_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
133 }
134 catch (Exception $expected) {
135 $this->assertEquals('Mandatory key(s) missing from params array: note, subject', $expected->getMessage());
136 return;
137 }
138
139 $this->fail('An expected exception has not been raised.');
140 }
141
142 /**
143 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
144 */
145 public function testVerifyOneMandatory() {
146 _civicrm_api3_initialize(TRUE);
147 $params = [
148 'entity_table' => 'civicrm_contact',
149 'note' => '',
150 'contact_id' => $this->_contactID,
151 'modified_date' => '2011-01-31',
152 'subject' => NULL,
153 'version' => $this->_apiversion,
154 ];
155
156 try {
157 civicrm_api3_verify_one_mandatory($params, 'CRM_Core_BAO_Note', ['note', 'subject']);
158 }
159 catch (Exception $expected) {
160 $this->assertEquals('Mandatory key(s) missing from params array: one of (note, subject)', $expected->getMessage());
161 return;
162 }
163
164 $this->fail('An expected exception has not been raised.');
165 }
166
167 /**
168 * Test verify one mandatory - includes DAO & passed as well as empty & NULL fields
169 */
170 public function testVerifyOneMandatoryOneSet() {
171 _civicrm_api3_initialize(TRUE);
172 $params = [
173 'version' => 3,
174 'entity_table' => 'civicrm_contact',
175 'note' => 'note',
176 'contact_id' => $this->_contactID,
177 'modified_date' => '2011-01-31',
178 'subject' => NULL,
179 ];
180
181 try {
182 civicrm_api3_verify_one_mandatory($params, NULL, ['note', 'subject']);
183 }
184 catch (Exception$expected) {
185 $this->fail('Exception raised when it shouldn\'t have been in line ' . __LINE__);
186 }
187 }
188
189 /**
190 * Test GET DAO function returns DAO.
191 */
192 public function testGetDAO() {
193 $params = [
194 'civicrm_api3_custom_group_get' => 'CRM_Core_DAO_CustomGroup',
195 'custom_group' => 'CRM_Core_DAO_CustomGroup',
196 'CustomGroup' => 'CRM_Core_DAO_CustomGroup',
197 'civicrm_api3_custom_field_get' => 'CRM_Core_DAO_CustomField',
198 'civicrm_api3_survey_get' => 'CRM_Campaign_DAO_Survey',
199 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_DAO_PledgePayment',
200 'civicrm_api3_website_get' => 'CRM_Core_DAO_Website',
201 'Membership' => 'CRM_Member_DAO_Membership',
202 ];
203 foreach ($params as $input => $expected) {
204 $result = _civicrm_api3_get_DAO($input);
205 $this->assertEquals($expected, $result);
206 }
207 }
208
209 /**
210 * Test GET BAO function returns BAO when it exists.
211 */
212 public function testGetBAO() {
213 $params = [
214 'civicrm_api3_website_get' => 'CRM_Core_BAO_Website',
215 'civicrm_api3_survey_get' => 'CRM_Campaign_BAO_Survey',
216 'civicrm_api3_pledge_payment_get' => 'CRM_Pledge_BAO_PledgePayment',
217 'Household' => 'CRM_Contact_BAO_Contact',
218 // Note this one DOES NOT have a BAO so we expect to fall back on returning the DAO
219 'mailing_group' => 'CRM_Mailing_DAO_MailingGroup',
220 // Make sure we get null back with nonexistant entities
221 'civicrm_this_does_not_exist' => NULL,
222 ];
223 foreach ($params as $input => $expected) {
224 $result = _civicrm_api3_get_BAO($input);
225 $this->assertEquals($expected, $result);
226 }
227 }
228
229 /**
230 * Test the validate function transforms dates.
231 *
232 * @throws \CiviCRM_API3_Exception
233 * @throws \Exception
234 */
235 public function test_civicrm_api3_validate_fields() {
236 $params = ['relationship_start_date' => '2010-12-20', 'relationship_end_date' => ''];
237 $fields = civicrm_api3('relationship', 'getfields', ['action' => 'get']);
238 _civicrm_api3_validate_fields('relationship', 'get', $params, $fields['values']);
239 $this->assertEquals('20101220000000', $params['relationship_start_date']);
240 $this->assertEquals('', $params['relationship_end_date']);
241 }
242
243 public function test_civicrm_api3_validate_fields_membership() {
244 $params = [
245 'start_date' => '2010-12-20',
246 'end_date' => '',
247 'membership_end_date' => '0',
248 'membership_join_date' => '2010-12-20',
249 'membership_start_date' => '2010-12-20',
250 ];
251 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
252 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
253 $this->assertEquals('2010-12-20', $params['start_date']);
254 $this->assertEquals('20101220000000', $params['membership_start_date']);
255 $this->assertEquals('', $params['end_date']);
256 $this->assertEquals('20101220000000', $params['membership_join_date'], 'join_date not set in line ' . __LINE__);
257 }
258
259 public function test_civicrm_api3_validate_fields_event() {
260
261 $params = [
262 'registration_start_date' => 20080601,
263 'registration_end_date' => '2008-10-15',
264 'start_date' => '2010-12-20',
265 'end_date' => '',
266 ];
267 $fields = civicrm_api3('Event', 'getfields', ['action' => 'create']);
268 _civicrm_api3_validate_fields('event', 'create', $params, $fields['values']);
269 $this->assertEquals('20101220000000', $params['start_date']);
270 $this->assertEquals('20081015000000', $params['registration_end_date']);
271 $this->assertEquals('', $params['end_date']);
272 $this->assertEquals('20080601000000', $params['registration_start_date']);
273 }
274
275 public function test_civicrm_api3_validate_fields_exception() {
276 $params = [
277 'membership_join_date' => 'abc',
278 ];
279 try {
280 $fields = civicrm_api3('Membership', 'getfields', ['action' => 'get']);
281 _civicrm_api3_validate_fields('Membership', 'get', $params, $fields['values']);
282 }
283 catch (Exception$expected) {
284 $this->assertEquals('membership_join_date is not a valid date: abc', $expected->getMessage());
285 }
286 }
287
288 public function testGetFields() {
289 $result = $this->callAPISuccess('membership', 'getfields', []);
290 $this->assertArrayHasKey('values', $result);
291 $result = $this->callAPISuccess('relationship', 'getfields', []);
292 $this->assertArrayHasKey('values', $result);
293 $result = $this->callAPISuccess('event', 'getfields', []);
294 $this->assertArrayHasKey('values', $result);
295 }
296
297 public function testGetFields_AllOptions() {
298 $result = $this->callAPISuccess('contact', 'getfields', [
299 'options' => [
300 'get_options' => 'all',
301 ],
302 ]);
303 $this->assertEquals('Household', $result['values']['contact_type']['options']['Household']);
304 $this->assertEquals('HTML', $result['values']['preferred_mail_format']['options']['HTML']);
305 }
306
307 public function basicArrayCases() {
308 $records = [
309 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
310 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
311 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
312 ['snack_id' => 'd', 'fruit' => 'apple', 'cheese' => 'gouda'],
313 ['snack_id' => 'e', 'fruit' => 'apple', 'cheese' => 'provolone'],
314 ];
315
316 $cases[] = [
317 $records,
318 // params
319 ['version' => 3],
320 // expected results
321 ['a', 'b', 'c', 'd', 'e'],
322 ];
323
324 $cases[] = [
325 $records,
326 // params
327 ['version' => 3, 'fruit' => 'apple'],
328 // expected results
329 ['a', 'c', 'd', 'e'],
330 ];
331
332 $cases[] = [
333 $records,
334 ['version' => 3, 'cheese' => 'cheddar'],
335 ['b', 'c'],
336 ];
337
338 $cases[] = [
339 $records,
340 ['version' => 3, 'id' => 'd'],
341 ['d'],
342 ];
343
344 return $cases;
345 }
346
347 /**
348 * Make a basic API (Widget.get) which allows getting data out of a simple in-memory
349 * list of records.
350 *
351 * @param $records
352 * The list of all records.
353 * @param $params
354 * The filter criteria
355 * @param array $resultIds
356 * The records which are expected to match.
357 * @dataProvider basicArrayCases
358 */
359 public function testBasicArrayGet($records, $params, $resultIds) {
360 $params['version'] = 3;
361
362 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
363
364 $provider = new \Civi\API\Provider\AdhocProvider($params['version'], 'Widget');
365 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
366 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
367 });
368 $kernel->registerApiProvider($provider);
369
370 $r1 = $kernel->runSafe('Widget', 'get', $params);
371 $this->assertEquals(count($resultIds), $r1['count']);
372 $this->assertEquals($resultIds, array_keys($r1['values']));
373 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r1['values'])));
374 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r1['values'])));
375
376 $r2 = $kernel->runSafe('Widget', 'get', $params + ['sequential' => 1]);
377 $this->assertEquals(count($resultIds), $r2['count']);
378 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('snack_id', $r2['values'])));
379 $this->assertEquals($resultIds, array_values(CRM_Utils_Array::collect('id', $r2['values'])));
380
381 $r3 = $kernel->runSafe('Widget', 'get', $params + ['options' => ['offset' => 1, 'limit' => 2]]);
382 $slice = array_slice($resultIds, 1, 2);
383 $this->assertEquals(count($slice), $r3['count']);
384 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('snack_id', $r3['values'])));
385 $this->assertEquals($slice, array_values(CRM_Utils_Array::collect('id', $r3['values'])));
386 }
387
388 public function testBasicArrayGetReturn() {
389 $records = [
390 ['snack_id' => 'a', 'fruit' => 'apple', 'cheese' => 'swiss'],
391 ['snack_id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar'],
392 ['snack_id' => 'c', 'fruit' => 'apple', 'cheese' => 'cheddar'],
393 ];
394
395 $kernel = new \Civi\API\Kernel(new \Symfony\Component\EventDispatcher\EventDispatcher());
396 $provider = new \Civi\API\Provider\AdhocProvider(3, 'Widget');
397 $provider->addAction('get', 'access CiviCRM', function ($apiRequest) use ($records) {
398 return _civicrm_api3_basic_array_get('Widget', $apiRequest['params'], $records, 'snack_id', ['snack_id', 'fruit', 'cheese']);
399 });
400 $kernel->registerApiProvider($provider);
401
402 $r1 = $kernel->runSafe('Widget', 'get', [
403 'version' => 3,
404 'snack_id' => 'b',
405 'return' => 'fruit',
406 ]);
407 $this->assertAPISuccess($r1);
408 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape']], $r1['values']);
409
410 $r2 = $kernel->runSafe('Widget', 'get', [
411 'version' => 3,
412 'snack_id' => 'b',
413 'return' => ['fruit', 'cheese'],
414 ]);
415 $this->assertAPISuccess($r2);
416 $this->assertEquals(['b' => ['id' => 'b', 'fruit' => 'grape', 'cheese' => 'cheddar']], $r2['values']);
417
418 $r3 = $kernel->runSafe('Widget', 'get', [
419 'version' => 3,
420 'cheese' => 'cheddar',
421 'return' => ['fruit'],
422 ]);
423 $this->assertAPISuccess($r3);
424 $this->assertEquals([
425 'b' => ['id' => 'b', 'fruit' => 'grape'],
426 'c' => ['id' => 'c', 'fruit' => 'apple'],
427 ], $r3['values']);
428 }
429
430 /**
431 * CRM-20892 Add Tests of new timestamp checking function
432 *
433 * @throws \CRM_Core_Exception
434 */
435 public function testTimeStampChecking() {
436 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_mailing (id, modified_date) VALUES (25, '2016-06-30 12:52:52')");
437 $this->assertTrue(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
438 $this->callAPISuccess('Mailing', 'create', ['id' => 25, 'subject' => 'Test Subject']);
439 $this->assertFalse(_civicrm_api3_compare_timestamps('2017-02-15 16:00:00', 25, 'Mailing'));
440 $this->callAPISuccess('Mailing', 'delete', ['id' => 25]);
441 }
442
443 /**
444 * Test that the foreign key constraint test correctly interprets pseudoconstants.
445 *
446 * @throws \CRM_Core_Exception
447 * @throws \API_Exception
448 */
449 public function testKeyConstraintCheck() {
450 $fieldInfo = $this->callAPISuccess('Contribution', 'getfields', [])['values']['financial_type_id'];
451 _civicrm_api3_validate_constraint(1, 'financial_type_id', $fieldInfo, 'Contribution');
452 _civicrm_api3_validate_constraint('Donation', 'financial_type_id', $fieldInfo, 'Contribution');
453 try {
454 _civicrm_api3_validate_constraint('Blah', 'financial_type_id', $fieldInfo, 'Contribution');
455 }
456 catch (API_Exception $e) {
457 $this->assertEquals("'Blah' is not a valid option for field financial_type_id", $e->getMessage());
458 return;
459 }
460 $this->fail('Last function call should have thrown an exception');
461 }
462
463 }