Merge pull request #16420 from civicrm/5.22
[civicrm-core.git] / Civi / Api4 / Generic / AbstractAction.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 * $Id$
18 *
19 */
20
21 namespace Civi\Api4\Generic;
22
23 use Civi\Api4\Utils\ReflectionUtils;
24 use Civi\Api4\Utils\ActionUtil;
25
26 /**
27 * Base class for all api actions.
28 *
29 * @method $this setCheckPermissions(bool $value) Enable/disable permission checks
30 * @method bool getCheckPermissions()
31 * @method $this setDebug(bool $value) Enable/disable debug output
32 * @method bool getDebug()
33 * @method $this setChain(array $chain)
34 * @method array getChain()
35 */
36 abstract class AbstractAction implements \ArrayAccess {
37
38 /**
39 * Api version number; cannot be changed.
40 *
41 * @var int
42 */
43 protected $version = 4;
44
45 /**
46 * Additional api requests - will be called once per result.
47 *
48 * Keys can be any string - this will be the name given to the output.
49 *
50 * You can reference other values in the api results in this call by prefixing them with $
51 *
52 * For example, you could create a contact and place them in a group by chaining the
53 * GroupContact api to the Contact api:
54 *
55 * Contact::create()
56 * ->setValue('first_name', 'Hello')
57 * ->addChain('add_to_a_group', GroupContact::create()->setValue('contact_id', '$id')->setValue('group_id', 123))
58 *
59 * This will substitute the id of the newly created contact with $id.
60 *
61 * @var array
62 */
63 protected $chain = [];
64
65 /**
66 * Whether to enforce acl permissions based on the current user.
67 *
68 * Setting to FALSE will disable permission checks and override ACLs.
69 * In REST/javascript this cannot be disabled.
70 *
71 * @var bool
72 */
73 protected $checkPermissions = TRUE;
74
75 /**
76 * Add debugging info to the api result.
77 *
78 * @var bool
79 */
80 protected $debug = FALSE;
81
82 /**
83 * @var string
84 */
85 protected $_entityName;
86
87 /**
88 * @var string
89 */
90 protected $_actionName;
91
92 /**
93 * @var \ReflectionClass
94 */
95 private $_reflection;
96
97 /**
98 * @var array
99 */
100 private $_paramInfo;
101
102 /**
103 * @var array
104 */
105 private $_entityFields;
106
107 /**
108 * @var array
109 */
110 private $_arrayStorage = [];
111
112 /**
113 * @var int
114 * Used to identify api calls for transactions
115 * @see \Civi\Core\Transaction\Manager
116 */
117 private $_id;
118
119 protected $_debugOutput = [];
120
121 /**
122 * Action constructor.
123 *
124 * @param string $entityName
125 * @param string $actionName
126 * @throws \API_Exception
127 */
128 public function __construct($entityName, $actionName) {
129 // If a namespaced class name is passed in
130 if (strpos($entityName, '\\') !== FALSE) {
131 $entityName = substr($entityName, strrpos($entityName, '\\') + 1);
132 }
133 $this->_entityName = $entityName;
134 $this->_actionName = $actionName;
135 $this->_id = \Civi\API\Request::getNextId();
136 }
137
138 /**
139 * Strictly enforce api parameters
140 * @param $name
141 * @param $value
142 * @throws \Exception
143 */
144 public function __set($name, $value) {
145 throw new \API_Exception('Unknown api parameter');
146 }
147
148 /**
149 * @param int $val
150 * @return $this
151 * @throws \API_Exception
152 */
153 public function setVersion($val) {
154 if ($val !== 4 && $val !== '4') {
155 throw new \API_Exception('Cannot modify api version');
156 }
157 return $this;
158 }
159
160 /**
161 * @param string $name
162 * Unique name for this chained request
163 * @param \Civi\Api4\Generic\AbstractAction $apiRequest
164 * @param string|int $index
165 * Either a string for how the results should be indexed e.g. 'name'
166 * or the index of a single result to return e.g. 0 for the first result.
167 * @return $this
168 */
169 public function addChain($name, AbstractAction $apiRequest, $index = NULL) {
170 $this->chain[$name] = [$apiRequest->getEntityName(), $apiRequest->getActionName(), $apiRequest->getParams(), $index];
171 return $this;
172 }
173
174 /**
175 * Magic function to provide automatic getter/setter for params.
176 *
177 * @param $name
178 * @param $arguments
179 * @return static|mixed
180 * @throws \API_Exception
181 */
182 public function __call($name, $arguments) {
183 $param = lcfirst(substr($name, 3));
184 if (!$param || $param[0] == '_') {
185 throw new \API_Exception('Unknown api parameter: ' . $name);
186 }
187 $mode = substr($name, 0, 3);
188 if ($this->paramExists($param)) {
189 switch ($mode) {
190 case 'get':
191 return $this->$param;
192
193 case 'set':
194 $this->$param = $arguments[0];
195 return $this;
196 }
197 }
198 throw new \API_Exception('Unknown api parameter: ' . $name);
199 }
200
201 /**
202 * Invoke api call.
203 *
204 * At this point all the params have been sent in and we initiate the api call & return the result.
205 * This is basically the outer wrapper for api v4.
206 *
207 * @return \Civi\Api4\Generic\Result
208 * @throws \API_Exception
209 * @throws \Civi\API\Exception\UnauthorizedException
210 */
211 public function execute() {
212 /** @var \Civi\API\Kernel $kernel */
213 $kernel = \Civi::service('civi_api_kernel');
214 $result = $kernel->runRequest($this);
215 if ($this->debug && (!$this->checkPermissions || \CRM_Core_Permission::check('view debug output'))) {
216 $result->debug = array_merge($result->debug, $this->_debugOutput);
217 }
218 else {
219 $result->debug = NULL;
220 }
221 return $result;
222 }
223
224 /**
225 * @param \Civi\Api4\Generic\Result $result
226 */
227 abstract public function _run(Result $result);
228
229 /**
230 * Serialize this object's params into an array
231 * @return array
232 */
233 public function getParams() {
234 $params = [];
235 foreach ($this->reflect()->getProperties(\ReflectionProperty::IS_PROTECTED) as $property) {
236 $name = $property->getName();
237 // Skip variables starting with an underscore
238 if ($name[0] != '_') {
239 $params[$name] = $this->$name;
240 }
241 }
242 return $params;
243 }
244
245 /**
246 * Get documentation for one or all params
247 *
248 * @param string $param
249 * @return array of arrays [description, type, default, (comment)]
250 */
251 public function getParamInfo($param = NULL) {
252 if (!isset($this->_paramInfo)) {
253 $defaults = $this->getParamDefaults();
254 foreach ($this->reflect()->getProperties(\ReflectionProperty::IS_PROTECTED) as $property) {
255 $name = $property->getName();
256 if ($name != 'version' && $name[0] != '_') {
257 $this->_paramInfo[$name] = ReflectionUtils::getCodeDocs($property, 'Property');
258 $this->_paramInfo[$name]['default'] = $defaults[$name];
259 }
260 }
261 }
262 return $param ? $this->_paramInfo[$param] : $this->_paramInfo;
263 }
264
265 /**
266 * @return string
267 */
268 public function getEntityName() {
269 return $this->_entityName;
270 }
271
272 /**
273 *
274 * @return string
275 */
276 public function getActionName() {
277 return $this->_actionName;
278 }
279
280 /**
281 * @param string $param
282 * @return bool
283 */
284 public function paramExists($param) {
285 return array_key_exists($param, $this->getParams());
286 }
287
288 /**
289 * @return array
290 */
291 protected function getParamDefaults() {
292 return array_intersect_key($this->reflect()->getDefaultProperties(), $this->getParams());
293 }
294
295 /**
296 * @inheritDoc
297 */
298 public function offsetExists($offset) {
299 return in_array($offset, ['entity', 'action', 'params', 'version', 'check_permissions', 'id']) || isset($this->_arrayStorage[$offset]);
300 }
301
302 /**
303 * @inheritDoc
304 */
305 public function &offsetGet($offset) {
306 $val = NULL;
307 if (in_array($offset, ['entity', 'action'])) {
308 $offset .= 'Name';
309 }
310 if (in_array($offset, ['entityName', 'actionName', 'params', 'version'])) {
311 $getter = 'get' . ucfirst($offset);
312 $val = $this->$getter();
313 return $val;
314 }
315 if ($offset == 'check_permissions') {
316 return $this->checkPermissions;
317 }
318 if ($offset == 'id') {
319 return $this->_id;
320 }
321 if (isset($this->_arrayStorage[$offset])) {
322 return $this->_arrayStorage[$offset];
323 }
324 return $val;
325 }
326
327 /**
328 * @inheritDoc
329 */
330 public function offsetSet($offset, $value) {
331 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'version', 'id'])) {
332 throw new \API_Exception('Cannot modify api4 state via array access');
333 }
334 if ($offset == 'check_permissions') {
335 $this->setCheckPermissions($value);
336 }
337 else {
338 $this->_arrayStorage[$offset] = $value;
339 }
340 }
341
342 /**
343 * @inheritDoc
344 */
345 public function offsetUnset($offset) {
346 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'check_permissions', 'version', 'id'])) {
347 throw new \API_Exception('Cannot modify api4 state via array access');
348 }
349 unset($this->_arrayStorage[$offset]);
350 }
351
352 /**
353 * Is this api call permitted?
354 *
355 * This function is called if checkPermissions is set to true.
356 *
357 * @return bool
358 */
359 public function isAuthorized() {
360 $permissions = $this->getPermissions();
361 return \CRM_Core_Permission::check($permissions);
362 }
363
364 /**
365 * @return array
366 */
367 public function getPermissions() {
368 $permissions = call_user_func(["\\Civi\\Api4\\" . $this->_entityName, 'permissions']);
369 $permissions += [
370 // applies to getFields, getActions, etc.
371 'meta' => ['access CiviCRM'],
372 // catch-all, applies to create, get, delete, etc.
373 'default' => ['administer CiviCRM'],
374 ];
375 $action = $this->getActionName();
376 if (isset($permissions[$action])) {
377 return $permissions[$action];
378 }
379 elseif (in_array($action, ['getActions', 'getFields'])) {
380 return $permissions['meta'];
381 }
382 return $permissions['default'];
383 }
384
385 /**
386 * Returns schema fields for this entity & action.
387 *
388 * Here we bypass the api wrapper and run the getFields action directly.
389 * This is because we DON'T want the wrapper to check permissions as this is an internal op,
390 * but we DO want permissions to be checked inside the getFields request so e.g. the api_key
391 * field can be conditionally included.
392 * @see \Civi\Api4\Action\Contact\GetFields
393 *
394 * @throws \API_Exception
395 * @return array
396 */
397 public function entityFields() {
398 if (!$this->_entityFields) {
399 $getFields = ActionUtil::getAction($this->getEntityName(), 'getFields');
400 $result = new Result();
401 if (method_exists($this, 'getBaoName')) {
402 $getFields->setIncludeCustom(FALSE);
403 }
404 $getFields
405 ->setCheckPermissions($this->checkPermissions)
406 ->setAction($this->getActionName())
407 ->_run($result);
408 $this->_entityFields = (array) $result->indexBy('name');
409 }
410 return $this->_entityFields;
411 }
412
413 /**
414 * @return \ReflectionClass
415 */
416 public function reflect() {
417 if (!$this->_reflection) {
418 $this->_reflection = new \ReflectionClass($this);
419 }
420 return $this->_reflection;
421 }
422
423 /**
424 * Validates required fields for actions which create a new object.
425 *
426 * @param $values
427 * @return array
428 * @throws \API_Exception
429 */
430 protected function checkRequiredFields($values) {
431 $unmatched = [];
432 foreach ($this->entityFields() as $fieldName => $fieldInfo) {
433 if (!isset($values[$fieldName]) || $values[$fieldName] === '') {
434 if (!empty($fieldInfo['required']) && !isset($fieldInfo['default_value'])) {
435 $unmatched[] = $fieldName;
436 }
437 elseif (!empty($fieldInfo['required_if'])) {
438 if ($this->evaluateCondition($fieldInfo['required_if'], ['values' => $values])) {
439 $unmatched[] = $fieldName;
440 }
441 }
442 }
443 }
444 return $unmatched;
445 }
446
447 /**
448 * This function is used internally for evaluating field annotations.
449 *
450 * It should never be passed raw user input.
451 *
452 * @param string $expr
453 * Conditional in php format e.g. $foo > $bar
454 * @param array $vars
455 * Variable name => value
456 * @return bool
457 * @throws \API_Exception
458 * @throws \Exception
459 */
460 protected function evaluateCondition($expr, $vars) {
461 if (strpos($expr, '}') !== FALSE || strpos($expr, '{') !== FALSE) {
462 throw new \API_Exception('Illegal character in expression');
463 }
464 $tpl = "{if $expr}1{else}0{/if}";
465 return (bool) trim(\CRM_Core_Smarty::singleton()->fetchWith('string:' . $tpl, $vars));
466 }
467
468 }