-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathAbstractAction.php
604 lines (558 loc) · 17.8 KB
/
AbstractAction.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
namespace Civi\Api4\Generic;
use Civi\Api4\Utils\CoreUtil;
use Civi\Api4\Utils\FormattingUtil;
use Civi\Api4\Utils\ReflectionUtils;
/**
* Base class for all api actions.
*
* An api Action object stores the parameters of the api call, and defines a _run function to execute the action.
*
* Every `protected` class var is considered a parameter (unless it starts with an underscore).
*
* Adding a `protected` var to your Action named e.g. `$thing` will automatically:
* - Provide a getter/setter (via `__call` MagicMethod) named `getThing()` and `setThing()`.
* - Expose the param in the Api Explorer (be sure to add a doc-block as it displays in the help panel).
* - Require a value for the param if you add the "@required" annotation.
*
* @method bool getCheckPermissions()
* @method $this setDebug(bool $debug) Enable/disable debug output
* @method bool getDebug()
* @method $this setChain(array $chain)
* @method array getChain()
* @method $this setLanguage(string|null $language)
* @method string|null getLanguage()
*/
abstract class AbstractAction implements \ArrayAccess {
use \Civi\Schema\Traits\MagicGetterSetterTrait;
/**
* Api version number; cannot be changed.
*
* @var int
*/
protected $version = 4;
/**
* Preferred language (optional)
*
* This option will notify major localization subsystems (`ts()`, multilingual, etc)
* about which locale should be used for composing/formatting messaging.
*
* This indicates the preferred language. The effective language is determined
* by `Civi\Core\Locale::negotiate($preferredLanguage)`.
*
* @var string
* @optionsCallback getLanguageOptions
*/
protected $language;
/**
* Additional api requests - will be called once per result.
*
* Keys can be any string - this will be the name given to the output.
*
* You can reference other values in the api results in this call by prefixing them with `$`.
*
* For example, you could create a contact and place them in a group by chaining the
* `GroupContact` api to the `Contact` api:
*
* ```php
* Contact::create()
* ->setValue('first_name', 'Hello')
* ->addChain('add_a_group', GroupContact::create()
* ->setValue('contact_id', '$id')
* ->setValue('group_id', 123)
* )
* ```
*
* This will substitute the id of the newly created contact with `$id`.
*
* @var array
*/
protected $chain = [];
/**
* Whether to enforce acl permissions based on the current user.
*
* Setting to FALSE will disable permission checks and override ACLs.
* In REST/javascript this cannot be disabled.
*
* @var bool
*/
protected $checkPermissions = TRUE;
/**
* Add debugging info to the api result.
*
* When enabled, `$result->debug` will be populated with information about the api call,
* including sql queries executed.
*
* **Note:** with checkPermissions enabled, debug info will only be returned if the user has "view debug output" permission.
*
* @var bool
*/
protected $debug = FALSE;
/**
* @var string
*/
protected $_entityName;
/**
* @var string
*/
protected $_actionName;
/**
* @var \ReflectionClass
*/
private $_reflection;
/**
* @var array
*/
private $_paramInfo;
/**
* @var array
*/
private $_entityFields;
/**
* @var array
*/
private $_arrayStorage = [];
/**
* @var int
* Used to identify api calls for transactions
* @see \Civi\Core\Transaction\Manager
*/
private $_id;
public $_debugOutput = [];
/**
* Action constructor.
*
* @param string $entityName
* @param string $actionName
*/
public function __construct($entityName, $actionName) {
// If a namespaced class name is passed in, convert to entityName
$this->_entityName = CoreUtil::stripNamespace($entityName);
// Normalize action name case (because PHP is case-insensitive, we have to do an extra check)
$thisClassName = CoreUtil::stripNamespace(get_class($this));
// If this was called via magic method, $actionName won't necessarily have the
// correct case because PHP doesn't care about case when calling methods.
if (strtolower($thisClassName) === strtolower($actionName)) {
$this->_actionName = lcfirst($thisClassName);
}
// If called via static method, case should already be correct.
else {
$this->_actionName = $actionName;
}
$this->_id = \Civi\API\Request::getNextId();
}
/**
* Strictly enforce api parameters
* @param $name
* @param $value
* @throws \Exception
*/
public function __set($name, $value) {
throw new \CRM_Core_Exception('Unknown api parameter');
}
/**
* @param int $val
* @return $this
* @throws \CRM_Core_Exception
*/
public function setVersion($val) {
if ($val !== 4 && $val !== '4') {
throw new \CRM_Core_Exception('Cannot modify api version');
}
return $this;
}
/**
* @param bool $checkPermissions
* @return $this
*/
public function setCheckPermissions(bool $checkPermissions) {
$this->checkPermissions = $checkPermissions;
return $this;
}
/**
* @param string $name
* Unique name for this chained request
* @param \Civi\Api4\Generic\AbstractAction $apiRequest
* @param string|int|array $index
* See `civicrm_api4()` for documentation of `$index` param
* @return $this
*/
public function addChain($name, AbstractAction $apiRequest, $index = NULL) {
$this->chain[$name] = [$apiRequest->getEntityName(), $apiRequest->getActionName(), $apiRequest->getParams(), $index];
return $this;
}
/**
* Magic function to provide automatic getter/setter for params.
*
* @param $name
* @param $arguments
* @return static|mixed
* @throws \CRM_Core_Exception
*/
public function __call($name, $arguments) {
$param = lcfirst(substr($name, 3));
if (!$param || $param[0] == '_') {
throw new \CRM_Core_Exception('Unknown api parameter: ' . $name);
}
$mode = substr($name, 0, 3);
if ($this->paramExists($param)) {
switch ($mode) {
case 'get':
return $this->$param;
case 'set':
$this->$param = ReflectionUtils::castTypeSoftly($arguments[0], $this->getParamInfo()[$param] ?? []);
return $this;
}
}
throw new \CRM_Core_Exception('Unknown api parameter: ' . $name);
}
/**
* Invoke api call.
*
* At this point all the params have been sent in and we initiate the api call & return the result.
* This is basically the outer wrapper for api v4.
*
* @return \Civi\Api4\Generic\Result
* @throws \CRM_Core_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
public function execute() {
/** @var \Civi\API\Kernel $kernel */
$kernel = \Civi::service('civi_api_kernel');
$result = $kernel->runRequest($this);
if ($this->debug && (!$this->checkPermissions || \CRM_Core_Permission::check('view debug output'))) {
$result->debug['actionClass'] = get_class($this);
$result->debug = array_merge($result->debug, $this->_debugOutput);
}
else {
$result->debug = NULL;
}
return $result;
}
/**
* @param \Civi\Api4\Generic\Result $result
*/
abstract public function _run(Result $result);
/**
* Serialize this object's params into an array
* @return array
*/
public function getParams() {
$params = [];
$magicProperties = $this->getMagicProperties();
foreach ($magicProperties as $name => $bool) {
$params[$name] = $this->$name;
}
return $params;
}
/**
* Get documentation for one or all params
*
* @param string $param
* @return array of arrays [description, type, default, (comment)]
*/
public function getParamInfo($param = NULL) {
if (!isset($this->_paramInfo)) {
$defaults = $this->getParamDefaults();
$vars = [
'entity' => $this->getEntityName(),
'action' => $this->getActionName(),
];
// For actions like "getFields" and "getActions" they are not getting the entity itself.
// So generic docs will make more sense like this:
if (substr($vars['action'], 0, 3) === 'get' && substr($vars['action'], -1) === 's') {
$vars['entity'] = lcfirst(substr($vars['action'], 3, -1));
}
foreach ($this->reflect()->getProperties(\ReflectionProperty::IS_PROTECTED) as $property) {
$name = $property->getName();
if ($name != 'version' && $name[0] != '_') {
$docs = ReflectionUtils::getCodeDocs($property, 'Property', $vars);
$docs['default'] = $defaults[$name];
if (!empty($docs['optionsCallback'])) {
$docs['options'] = $this->{$docs['optionsCallback']}();
unset($docs['optionsCallback']);
}
$this->_paramInfo[$name] = $docs;
}
}
}
return $param ? $this->_paramInfo[$param] : $this->_paramInfo;
}
/**
* @return string
*/
public function getEntityName() {
return $this->_entityName;
}
/**
*
* @return string
*/
public function getActionName() {
return $this->_actionName;
}
/**
* @param string $param
* @return bool
*/
public function paramExists($param) {
return array_key_exists($param, $this->getMagicProperties());
}
/**
* @return array
*/
protected function getParamDefaults() {
return array_intersect_key($this->reflect()->getDefaultProperties(), $this->getMagicProperties());
}
/**
* @inheritDoc
*/
public function offsetExists($offset): bool {
return in_array($offset, ['entity', 'action', 'params', 'version', 'check_permissions', 'id']) || isset($this->_arrayStorage[$offset]);
}
/**
* @inheritDoc
*/
#[\ReturnTypeWillChange]
public function &offsetGet($offset) {
$val = NULL;
if (in_array($offset, ['entity', 'action'])) {
$offset .= 'Name';
}
if (in_array($offset, ['entityName', 'actionName', 'params', 'version'])) {
$getter = 'get' . ucfirst($offset);
$val = $this->$getter();
return $val;
}
if ($offset == 'check_permissions') {
return $this->checkPermissions;
}
if ($offset == 'id') {
return $this->_id;
}
if (isset($this->_arrayStorage[$offset])) {
return $this->_arrayStorage[$offset];
}
return $val;
}
/**
* @inheritDoc
*/
public function offsetSet($offset, $value): void {
if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'version', 'id'])) {
throw new \CRM_Core_Exception('Cannot modify api4 state via array access');
}
if ($offset == 'check_permissions') {
$this->setCheckPermissions($value);
}
else {
$this->_arrayStorage[$offset] = $value;
}
}
/**
* @inheritDoc
*/
public function offsetUnset($offset): void {
if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'check_permissions', 'version', 'id'])) {
throw new \CRM_Core_Exception('Cannot modify api4 state via array access');
}
unset($this->_arrayStorage[$offset]);
}
/**
* Is this api call permitted?
*
* This function is called if checkPermissions is set to true.
*
* @return bool
* @internal Implement/override in civicrm-core.git only. Signature may evolve.
*/
public function isAuthorized(): bool {
$permissions = $this->getPermissions();
return \CRM_Core_Permission::check($permissions);
}
/**
* @return array
*/
public function getPermissions() {
$permissions = call_user_func([CoreUtil::getApiClass($this->_entityName), 'permissions'], $this->_entityName);
$permissions += [
// applies to getFields, getActions, etc.
'meta' => ['access CiviCRM'],
// catch-all, applies to create, get, delete, etc.
'default' => ['administer CiviCRM'],
];
$action = $this->getActionName();
// Map specific action names to more generic versions
$map = [
'getActions' => 'meta',
'getFields' => 'meta',
'replace' => 'delete',
'save' => 'create',
];
$generic = $map[$action] ?? 'default';
return $permissions[$action] ?? $permissions[$generic] ?? $permissions['default'];
}
/**
* Returns schema fields for this entity & action.
*
* Here we bypass the api wrapper and run the getFields action directly.
* This is because we DON'T want the wrapper to check permissions as this is an internal op.
* @see \Civi\Api4\Action\Contact\GetFields
*
* @throws \CRM_Core_Exception
* @return array
*/
public function entityFields() {
if (!$this->_entityFields) {
$allowedTypes = ['Field', 'Filter', 'Extra'];
$getFields = \Civi\API\Request::create($this->getEntityName(), 'getFields', [
'version' => 4,
'checkPermissions' => FALSE,
'action' => $this->getActionName(),
'where' => [['type', 'IN', $allowedTypes]],
]);
$result = new Result();
// Pass TRUE for the private $isInternal param
$getFields->_run($result, TRUE);
$this->_entityFields = (array) $result->indexBy('name');
}
return $this->_entityFields;
}
/**
* @return \ReflectionClass
*/
public function reflect() {
if (!$this->_reflection) {
$this->_reflection = new \ReflectionClass($this);
}
return $this->_reflection;
}
/**
* Validates required fields for actions which create a new object.
*
* @param $values
* @return array
* @throws \CRM_Core_Exception
*/
protected function checkRequiredFields($values) {
$unmatched = [];
foreach ($this->entityFields() as $fieldName => $fieldInfo) {
if (!isset($values[$fieldName]) || $values[$fieldName] === '') {
if (!empty($fieldInfo['required']) && !isset($fieldInfo['default_value'])) {
$unmatched[] = $fieldName;
}
elseif (!empty($fieldInfo['required_if'])) {
if (self::evaluateCondition($fieldInfo['required_if'], ['values' => $values])) {
$unmatched[] = $fieldName;
}
}
}
}
return $unmatched;
}
/**
* Replaces pseudoconstants in input values
*
* @param array $record
* @throws \CRM_Core_Exception
*/
protected function formatWriteValues(&$record) {
$optionFields = [];
// Collect fieldnames with a :pseudoconstant suffix & remove them from $record array
foreach (array_keys($record) as $expr) {
$suffix = strrpos($expr, ':');
if ($suffix) {
$fieldName = substr($expr, 0, $suffix);
$field = $this->entityFields()[$fieldName] ?? NULL;
if ($field) {
$optionFields[$fieldName] = [
'val' => $record[$expr],
'name' => $fieldName,
'expr' => $expr,
'field' => $field,
'suffix' => substr($expr, $suffix + 1),
'input_attrs' => $field['input_attrs'] ?? [],
];
unset($record[$expr]);
}
}
}
// Sort lookups by `input_attrs.control_field`, so e.g. country_id is processed first, then state_province_id, then county_id
CoreUtil::topSortFields($optionFields);
// Replace pseudoconstants. Note this is a reverse lookup as we are evaluating input not output.
foreach ($optionFields as $info) {
$options = FormattingUtil::getPseudoconstantList($info['field'], $info['expr'], $record, 'create');
$record[$info['name']] = FormattingUtil::replacePseudoconstant($options, $info['val'], TRUE);
}
// The DAO works better with ints than booleans. See https://github.com/civicrm/civicrm-core/pull/23970
foreach ($record as $key => $value) {
if (is_bool($value)) {
$record[$key] = (int) $value;
}
}
}
/**
* This function is used internally for evaluating field annotations.
*
* It should never be passed raw user input.
*
* @param string $expr
* Conditional in php format e.g. $foo > $bar
* @param array $vars
* Variable name => value
* @return bool
* @throws \CRM_Core_Exception
* @throws \Exception
*/
public static function evaluateCondition($expr, $vars) {
if (strpos($expr, '}') !== FALSE || strpos($expr, '{') !== FALSE) {
throw new \CRM_Core_Exception('Illegal character in expression');
}
$tpl = "{if $expr}1{else}0{/if}";
return (bool) trim(\CRM_Core_Smarty::singleton()->fetchWith('string:' . $tpl, $vars));
}
/**
* When in debug mode, this logs the callback function being used by a Basic*Action class.
*
* @param callable $callable
*/
protected function addCallbackToDebugOutput($callable) {
if ($this->debug && empty($this->_debugOutput['callback'])) {
if (is_scalar($callable)) {
$this->_debugOutput['callback'] = (string) $callable;
}
elseif (is_array($callable)) {
foreach ($callable as $key => $unit) {
$this->_debugOutput['callback'][$key] = is_object($unit) ? get_class($unit) : (string) $unit;
}
}
elseif (is_object($callable)) {
$this->_debugOutput['callback'] = get_class($callable);
}
}
}
/**
* Get available preferred languages.
*
* @return array
*/
protected function getLanguageOptions(): array {
$languages = \CRM_Contact_BAO_Contact::buildOptions('preferred_language');
ksort($languages);
$result = array_keys($languages);
if (!\Civi::settings()->get('partial_locales')) {
$uiLanguages = \CRM_Core_I18n::uiLanguages(TRUE);
$result = array_values(array_intersect($result, $uiLanguages));
}
return $result;
}
}