4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 namespace Civi\Api4\Generic
;
23 use Civi\Api4\Utils\ReflectionUtils
;
24 use Civi\Api4\Utils\ActionUtil
;
27 * Base class for all api actions.
29 * @method $this setCheckPermissions(bool $value)
30 * @method bool getCheckPermissions()
31 * @method $this setChain(array $chain)
32 * @method array getChain()
34 abstract class AbstractAction
implements \ArrayAccess
{
37 * Api version number; cannot be changed.
41 protected $version = 4;
44 * Additional api requests - will be called once per result.
46 * Keys can be any string - this will be the name given to the output.
48 * You can reference other values in the api results in this call by prefixing them with $
50 * For example, you could create a contact and place them in a group by chaining the
51 * GroupContact api to the Contact api:
54 * ->setValue('first_name', 'Hello')
55 * ->addChain('add_to_a_group', GroupContact::create()->setValue('contact_id', '$id')->setValue('group_id', 123))
57 * This will substitute the id of the newly created contact with $id.
61 protected $chain = [];
64 * Whether to enforce acl permissions based on the current user.
66 * Setting to FALSE will disable permission checks and override ACLs.
67 * In REST/javascript this cannot be disabled.
71 protected $checkPermissions = TRUE;
76 protected $_entityName;
81 protected $_actionName;
84 * @var \ReflectionClass
96 private $_entityFields;
101 private $_arrayStorage = [];
105 * Used to identify api calls for transactions
106 * @see \Civi\Core\Transaction\Manager
111 * Action constructor.
113 * @param string $entityName
114 * @param string $actionName
115 * @throws \API_Exception
117 public function __construct($entityName, $actionName) {
118 // If a namespaced class name is passed in
119 if (strpos($entityName, '\\') !== FALSE) {
120 $entityName = substr($entityName, strrpos($entityName, '\\') +
1);
122 $this->_entityName
= $entityName;
123 $this->_actionName
= $actionName;
124 $this->_id
= \Civi\API\Request
::getNextId();
128 * Strictly enforce api parameters
133 public function __set($name, $value) {
134 throw new \
API_Exception('Unknown api parameter');
140 * @throws \API_Exception
142 public function setVersion($val) {
144 throw new \
API_Exception('Cannot modify api version');
150 * @param string $name
151 * Unique name for this chained request
152 * @param \Civi\Api4\Generic\AbstractAction $apiRequest
153 * @param string|int $index
154 * Either a string for how the results should be indexed e.g. 'name'
155 * or the index of a single result to return e.g. 0 for the first result.
158 public function addChain($name, AbstractAction
$apiRequest, $index = NULL) {
159 $this->chain
[$name] = [$apiRequest->getEntityName(), $apiRequest->getActionName(), $apiRequest->getParams(), $index];
164 * Magic function to provide addFoo, getFoo and setFoo for params.
168 * @return static|mixed
169 * @throws \API_Exception
171 public function __call($name, $arguments) {
172 $param = lcfirst(substr($name, 3));
173 if (!$param ||
$param[0] == '_') {
174 throw new \
API_Exception('Unknown api parameter: ' . $name);
176 $mode = substr($name, 0, 3);
177 // Handle plural when adding to e.g. $values with "addValue" method.
178 if ($mode == 'add' && $this->paramExists($param . 's')) {
181 if ($this->paramExists($param)) {
184 return $this->$param;
187 $this->$param = $arguments[0];
191 if (!is_array($this->$param)) {
192 throw new \
API_Exception('Cannot add to non-array param');
194 if (array_key_exists(1, $arguments)) {
195 $this->{$param}[$arguments[0]] = $arguments[1];
198 $this->{$param}[] = $arguments[0];
203 throw new \
API_Exception('Unknown api parameter: ' . $name);
209 * At this point all the params have been sent in and we initiate the api call & return the result.
210 * This is basically the outer wrapper for api v4.
212 * @return \Civi\Api4\Generic\Result
213 * @throws \Civi\API\Exception\UnauthorizedException
215 public function execute() {
216 /** @var \Civi\API\Kernel $kernel */
217 $kernel = \Civi
::service('civi_api_kernel');
219 return $kernel->runRequest($this);
223 * @param \Civi\Api4\Generic\Result $result
225 abstract public function _run(Result
$result);
228 * Serialize this object's params into an array
231 public function getParams() {
233 foreach ($this->reflect()->getProperties(\ReflectionProperty
::IS_PROTECTED
) as $property) {
234 $name = $property->getName();
235 // Skip variables starting with an underscore
236 if ($name[0] != '_') {
237 $params[$name] = $this->$name;
244 * Get documentation for one or all params
246 * @param string $param
247 * @return array of arrays [description, type, default, (comment)]
249 public function getParamInfo($param = NULL) {
250 if (!isset($this->_paramInfo
)) {
251 $defaults = $this->getParamDefaults();
252 foreach ($this->reflect()->getProperties(\ReflectionProperty
::IS_PROTECTED
) as $property) {
253 $name = $property->getName();
254 if ($name != 'version' && $name[0] != '_') {
255 $this->_paramInfo
[$name] = ReflectionUtils
::getCodeDocs($property, 'Property');
256 $this->_paramInfo
[$name]['default'] = $defaults[$name];
260 return $param ?
$this->_paramInfo
[$param] : $this->_paramInfo
;
266 public function getEntityName() {
267 return $this->_entityName
;
274 public function getActionName() {
275 return $this->_actionName
;
279 * @param string $param
282 public function paramExists($param) {
283 return array_key_exists($param, $this->getParams());
289 protected function getParamDefaults() {
290 return array_intersect_key($this->reflect()->getDefaultProperties(), $this->getParams());
296 public function offsetExists($offset) {
297 return in_array($offset, ['entity', 'action', 'params', 'version', 'check_permissions', 'id']) ||
isset($this->_arrayStorage
[$offset]);
303 public function &offsetGet($offset) {
305 if (in_array($offset, ['entity', 'action'])) {
308 if (in_array($offset, ['entityName', 'actionName', 'params', 'version'])) {
309 $getter = 'get' . ucfirst($offset);
310 $val = $this->$getter();
313 if ($offset == 'check_permissions') {
314 return $this->checkPermissions
;
316 if ($offset == 'id') {
319 if (isset($this->_arrayStorage
[$offset])) {
320 return $this->_arrayStorage
[$offset];
328 public function offsetSet($offset, $value) {
329 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'version', 'id'])) {
330 throw new \
API_Exception('Cannot modify api4 state via array access');
332 if ($offset == 'check_permissions') {
333 $this->setCheckPermissions($value);
336 $this->_arrayStorage
[$offset] = $value;
343 public function offsetUnset($offset) {
344 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'check_permissions', 'version', 'id'])) {
345 throw new \
API_Exception('Cannot modify api4 state via array access');
347 unset($this->_arrayStorage
[$offset]);
351 * Is this api call permitted?
353 * This function is called if checkPermissions is set to true.
357 public function isAuthorized() {
358 $permissions = $this->getPermissions();
359 return \CRM_Core_Permission
::check($permissions);
365 public function getPermissions() {
366 $permissions = call_user_func(["\\Civi\\Api4\\" . $this->_entityName
, 'permissions']);
368 // applies to getFields, getActions, etc.
369 'meta' => ['access CiviCRM'],
370 // catch-all, applies to create, get, delete, etc.
371 'default' => ['administer CiviCRM'],
373 $action = $this->getActionName();
374 if (isset($permissions[$action])) {
375 return $permissions[$action];
377 elseif (in_array($action, ['getActions', 'getFields'])) {
378 return $permissions['meta'];
380 return $permissions['default'];
384 * Returns schema fields for this entity & action.
386 * Here we bypass the api wrapper and execute the getFields action directly.
387 * This is because we DON'T want the wrapper to check permissions as this is an internal op,
388 * but we DO want permissions to be checked inside the getFields request so e.g. the api_key
389 * field can be conditionally included.
390 * @see \Civi\Api4\Action\Contact\GetFields
394 public function entityFields() {
395 if (!$this->_entityFields
) {
396 $getFields = ActionUtil
::getAction($this->getEntityName(), 'getFields');
397 $result = new Result();
398 if (method_exists($this, 'getBaoName')) {
399 $getFields->setIncludeCustom(FALSE);
402 ->setCheckPermissions($this->checkPermissions
)
403 ->setAction($this->getActionName())
405 $this->_entityFields
= (array) $result->indexBy('name');
407 return $this->_entityFields
;
411 * @return \ReflectionClass
413 public function reflect() {
414 if (!$this->_reflection
) {
415 $this->_reflection
= new \
ReflectionClass($this);
417 return $this->_reflection
;
421 * Validates required fields for actions which create a new object.
425 * @throws \API_Exception
427 protected function checkRequiredFields($values) {
429 foreach ($this->entityFields() as $fieldName => $fieldInfo) {
430 if (!isset($values[$fieldName]) ||
$values[$fieldName] === '') {
431 if (!empty($fieldInfo['required']) && !isset($fieldInfo['default_value'])) {
432 $unmatched[] = $fieldName;
434 elseif (!empty($fieldInfo['required_if'])) {
435 if ($this->evaluateCondition($fieldInfo['required_if'], ['values' => $values])) {
436 $unmatched[] = $fieldName;
445 * This function is used internally for evaluating field annotations.
447 * It should never be passed raw user input.
449 * @param string $expr
450 * Conditional in php format e.g. $foo > $bar
452 * Variable name => value
454 * @throws \API_Exception
457 protected function evaluateCondition($expr, $vars) {
458 if (strpos($expr, '}') !== FALSE ||
strpos($expr, '{') !== FALSE) {
459 throw new \
API_Exception('Illegal character in expression');
461 $tpl = "{if $expr}1{else}0{/if}";
462 return (bool) trim(\CRM_Core_Smarty
::singleton()->fetchWith('string:' . $tpl, $vars));