4 +--------------------------------------------------------------------+
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2019 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
32 * @copyright CiviCRM LLC (c) 2004-2019
37 namespace Civi\Api4\Generic
;
39 use Civi\Api4\Utils\ReflectionUtils
;
40 use Civi\Api4\Utils\ActionUtil
;
43 * Base class for all api actions.
45 * @method $this setCheckPermissions(bool $value)
46 * @method bool getCheckPermissions()
47 * @method $this setChain(array $chain)
48 * @method array getChain()
50 abstract class AbstractAction
implements \ArrayAccess
{
53 * Api version number; cannot be changed.
57 protected $version = 4;
60 * Additional api requests - will be called once per result.
62 * Keys can be any string - this will be the name given to the output.
64 * You can reference other values in the api results in this call by prefixing them with $
66 * For example, you could create a contact and place them in a group by chaining the
67 * GroupContact api to the Contact api:
70 * ->setValue('first_name', 'Hello')
71 * ->addChain('add_to_a_group', GroupContact::create()->setValue('contact_id', '$id')->setValue('group_id', 123))
73 * This will substitute the id of the newly created contact with $id.
77 protected $chain = [];
80 * Whether to enforce acl permissions based on the current user.
82 * Setting to FALSE will disable permission checks and override ACLs.
83 * In REST/javascript this cannot be disabled.
87 protected $checkPermissions = TRUE;
92 protected $_entityName;
97 protected $_actionName;
100 * @var \ReflectionClass
102 private $_reflection;
112 private $_entityFields;
117 private $_arrayStorage = [];
121 * Used to identify api calls for transactions
122 * @see \Civi\Core\Transaction\Manager
127 * Action constructor.
129 * @param string $entityName
130 * @param string $actionName
131 * @throws \API_Exception
133 public function __construct($entityName, $actionName) {
134 // If a namespaced class name is passed in
135 if (strpos($entityName, '\\') !== FALSE) {
136 $entityName = substr($entityName, strrpos($entityName, '\\') +
1);
138 $this->_entityName
= $entityName;
139 $this->_actionName
= $actionName;
140 $this->_id
= \Civi\API\Request
::getNextId();
144 * Strictly enforce api parameters
149 public function __set($name, $value) {
150 throw new \
API_Exception('Unknown api parameter');
156 * @throws \API_Exception
158 public function setVersion($val) {
160 throw new \
API_Exception('Cannot modify api version');
166 * @param string $name
167 * Unique name for this chained request
168 * @param \Civi\Api4\Generic\AbstractAction $apiRequest
169 * @param string|int $index
170 * Either a string for how the results should be indexed e.g. 'name'
171 * or the index of a single result to return e.g. 0 for the first result.
174 public function addChain($name, AbstractAction
$apiRequest, $index = NULL) {
175 $this->chain
[$name] = [$apiRequest->getEntityName(), $apiRequest->getActionName(), $apiRequest->getParams(), $index];
180 * Magic function to provide addFoo, getFoo and setFoo for params.
184 * @return static|mixed
185 * @throws \API_Exception
187 public function __call($name, $arguments) {
188 $param = lcfirst(substr($name, 3));
189 if (!$param ||
$param[0] == '_') {
190 throw new \
API_Exception('Unknown api parameter: ' . $name);
192 $mode = substr($name, 0, 3);
193 // Handle plural when adding to e.g. $values with "addValue" method.
194 if ($mode == 'add' && $this->paramExists($param . 's')) {
197 if ($this->paramExists($param)) {
200 return $this->$param;
203 $this->$param = $arguments[0];
207 if (!is_array($this->$param)) {
208 throw new \
API_Exception('Cannot add to non-array param');
210 if (array_key_exists(1, $arguments)) {
211 $this->{$param}[$arguments[0]] = $arguments[1];
214 $this->{$param}[] = $arguments[0];
219 throw new \
API_Exception('Unknown api parameter: ' . $name);
225 * At this point all the params have been sent in and we initiate the api call & return the result.
226 * This is basically the outer wrapper for api v4.
228 * @return \Civi\Api4\Generic\Result
229 * @throws \Civi\API\Exception\UnauthorizedException
231 public function execute() {
232 /** @var \Civi\API\Kernel $kernel */
233 $kernel = \Civi
::service('civi_api_kernel');
235 return $kernel->runRequest($this);
239 * @param \Civi\Api4\Generic\Result $result
241 abstract public function _run(Result
$result);
244 * Serialize this object's params into an array
247 public function getParams() {
249 foreach ($this->reflect()->getProperties(\ReflectionProperty
::IS_PROTECTED
) as $property) {
250 $name = $property->getName();
251 // Skip variables starting with an underscore
252 if ($name[0] != '_') {
253 $params[$name] = $this->$name;
260 * Get documentation for one or all params
262 * @param string $param
263 * @return array of arrays [description, type, default, (comment)]
265 public function getParamInfo($param = NULL) {
266 if (!isset($this->_paramInfo
)) {
267 $defaults = $this->getParamDefaults();
268 foreach ($this->reflect()->getProperties(\ReflectionProperty
::IS_PROTECTED
) as $property) {
269 $name = $property->getName();
270 if ($name != 'version' && $name[0] != '_') {
271 $this->_paramInfo
[$name] = ReflectionUtils
::getCodeDocs($property, 'Property');
272 $this->_paramInfo
[$name]['default'] = $defaults[$name];
276 return $param ?
$this->_paramInfo
[$param] : $this->_paramInfo
;
282 public function getEntityName() {
283 return $this->_entityName
;
290 public function getActionName() {
291 return $this->_actionName
;
295 * @param string $param
298 public function paramExists($param) {
299 return array_key_exists($param, $this->getParams());
305 protected function getParamDefaults() {
306 return array_intersect_key($this->reflect()->getDefaultProperties(), $this->getParams());
312 public function offsetExists($offset) {
313 return in_array($offset, ['entity', 'action', 'params', 'version', 'check_permissions', 'id']) ||
isset($this->_arrayStorage
[$offset]);
319 public function &offsetGet($offset) {
321 if (in_array($offset, ['entity', 'action'])) {
324 if (in_array($offset, ['entityName', 'actionName', 'params', 'version'])) {
325 $getter = 'get' . ucfirst($offset);
326 $val = $this->$getter();
329 if ($offset == 'check_permissions') {
330 return $this->checkPermissions
;
332 if ($offset == 'id') {
335 if (isset($this->_arrayStorage
[$offset])) {
336 return $this->_arrayStorage
[$offset];
344 public function offsetSet($offset, $value) {
345 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'version', 'id'])) {
346 throw new \
API_Exception('Cannot modify api4 state via array access');
348 if ($offset == 'check_permissions') {
349 $this->setCheckPermissions($value);
352 $this->_arrayStorage
[$offset] = $value;
359 public function offsetUnset($offset) {
360 if (in_array($offset, ['entity', 'action', 'entityName', 'actionName', 'params', 'check_permissions', 'version', 'id'])) {
361 throw new \
API_Exception('Cannot modify api4 state via array access');
363 unset($this->_arrayStorage
[$offset]);
367 * Is this api call permitted?
369 * This function is called if checkPermissions is set to true.
373 public function isAuthorized() {
374 $permissions = $this->getPermissions();
375 return \CRM_Core_Permission
::check($permissions);
381 public function getPermissions() {
382 $permissions = call_user_func(["\\Civi\\Api4\\" . $this->_entityName
, 'permissions']);
384 // applies to getFields, getActions, etc.
385 'meta' => ['access CiviCRM'],
386 // catch-all, applies to create, get, delete, etc.
387 'default' => ['administer CiviCRM'],
389 $action = $this->getActionName();
390 if (isset($permissions[$action])) {
391 return $permissions[$action];
393 elseif (in_array($action, ['getActions', 'getFields'])) {
394 return $permissions['meta'];
396 return $permissions['default'];
400 * Returns schema fields for this entity & action.
402 * Here we bypass the api wrapper and execute the getFields action directly.
403 * This is because we DON'T want the wrapper to check permissions as this is an internal op,
404 * but we DO want permissions to be checked inside the getFields request so e.g. the api_key
405 * field can be conditionally included.
406 * @see \Civi\Api4\Action\Contact\GetFields
410 public function entityFields() {
411 if (!$this->_entityFields
) {
412 $getFields = ActionUtil
::getAction($this->getEntityName(), 'getFields');
413 $result = new Result();
414 if (method_exists($this, 'getBaoName')) {
415 $getFields->setIncludeCustom(FALSE);
418 ->setCheckPermissions($this->checkPermissions
)
419 ->setAction($this->getActionName())
421 $this->_entityFields
= (array) $result->indexBy('name');
423 return $this->_entityFields
;
427 * @return \ReflectionClass
429 public function reflect() {
430 if (!$this->_reflection
) {
431 $this->_reflection
= new \
ReflectionClass($this);
433 return $this->_reflection
;
437 * Validates required fields for actions which create a new object.
441 * @throws \API_Exception
443 protected function checkRequiredFields($values) {
445 foreach ($this->entityFields() as $fieldName => $fieldInfo) {
446 if (!isset($values[$fieldName]) ||
$values[$fieldName] === '') {
447 if (!empty($fieldInfo['required']) && !isset($fieldInfo['default_value'])) {
448 $unmatched[] = $fieldName;
450 elseif (!empty($fieldInfo['required_if'])) {
451 if ($this->evaluateCondition($fieldInfo['required_if'], ['values' => $values])) {
452 $unmatched[] = $fieldName;
461 * This function is used internally for evaluating field annotations.
463 * It should never be passed raw user input.
465 * @param string $expr
466 * Conditional in php format e.g. $foo > $bar
468 * Variable name => value
470 * @throws \API_Exception
473 protected function evaluateCondition($expr, $vars) {
474 if (strpos($expr, '}') !== FALSE ||
strpos($expr, '{') !== FALSE) {
475 throw new \
API_Exception('Illegal character in expression');
477 $tpl = "{if $expr}1{else}0{/if}";
478 return (bool) trim(\CRM_Core_Smarty
::singleton()->fetchWith('string:' . $tpl, $vars));