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 +--------------------------------------------------------------------+
13 namespace Civi\Api4\Utils
;
15 use Civi\API\Exception\NotImplementedException
;
18 use Civi\Api4\Event\CreateApi4RequestEvent
;
19 use CRM_Core_DAO_AllCoreTables
as AllCoreTables
;
26 * @return \CRM_Core_DAO|string
27 * The BAO name for use in static calls. Return doc block is hacked to allow
28 * auto-completion of static methods
30 public static function getBAOFromApiName($entityName) {
31 if ($entityName === 'CustomValue' ||
strpos($entityName, 'Custom_') === 0) {
32 return 'CRM_Core_BAO_CustomValue';
34 $dao = AllCoreTables
::getFullName($entityName);
35 return $dao ? AllCoreTables
::getBAOClassName($dao) : NULL;
40 * @return string|\Civi\Api4\Generic\AbstractEntity
42 public static function getApiClass($entityName) {
43 $e = new CreateApi4RequestEvent($entityName);
44 \Civi
::dispatcher()->dispatch('civi.api4.createRequest', $e);
49 * Get a piece of metadata about an entity
51 * @param string $entityName
52 * @param string $keyToReturn
55 public static function getInfoItem(string $entityName, string $keyToReturn) {
56 // Because this function might be called thousands of times per request, read directly
57 // from the cache set by Apiv4 Entity.get to avoid the processing overhead of the API wrapper.
58 $cached = \Civi
::cache('metadata')->get('api4.entities.info');
60 $info = $cached[$entityName] ??
NULL;
62 // If the cache is empty, calling Entity.get will populate it and we'll use it next time.
64 $info = Entity
::get(FALSE)
65 ->addWhere('name', '=', $entityName)
66 ->addSelect($keyToReturn)
69 return $info ?
$info[$keyToReturn] ??
NULL : NULL;
73 * Get name of unique identifier, typically "id"
74 * @param string $entityName
77 public static function getIdFieldName(string $entityName): string {
78 return self
::getInfoItem($entityName, 'primary_key')[0] ??
'id';
82 * Get table name of given entity
84 * @param string $entityName
88 public static function getTableName($entityName) {
89 if (strpos($entityName, 'Custom_') === 0) {
90 $customGroup = substr($entityName, 7);
91 return \CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroup, 'table_name', 'name');
93 return AllCoreTables
::getTableForEntityName($entityName);
97 * Given a sql table name, return the name of the api entity.
100 * @return string|NULL
102 public static function getApiNameFromTableName($tableName) {
103 $entityName = AllCoreTables
::getBriefName(AllCoreTables
::getClassForTable($tableName));
106 // Verify class exists
107 return self
::getApiClass($entityName) ?
$entityName : NULL;
109 // Multi-value custom group pseudo-entities
110 $customGroup = \CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $tableName, 'name', 'table_name');
111 return self
::isCustomEntity($customGroup) ?
"Custom_$customGroup" : NULL;
117 public static function getOperators() {
118 $operators = \CRM_Core_DAO
::acceptedSQLOperators();
119 $operators[] = 'CONTAINS';
120 $operators[] = 'IS EMPTY';
121 $operators[] = 'IS NOT EMPTY';
122 $operators[] = 'REGEXP';
123 $operators[] = 'NOT REGEXP';
128 * For a given API Entity, return the types of custom fields it supports and the column they join to.
130 * @param string $entityName
131 * @return array|mixed|null
132 * @throws \API_Exception
133 * @throws \Civi\API\Exception\UnauthorizedException
135 public static function getCustomGroupExtends(string $entityName) {
136 // Custom_group.extends pretty much maps 1-1 with entity names, except for a couple oddballs (Contact, Participant).
137 switch ($entityName) {
140 'extends' => array_merge(['Contact'], array_keys(\CRM_Core_SelectValues
::contactType())),
146 'extends' => ['Participant', 'ParticipantRole', 'ParticipantEventName', 'ParticipantEventType'],
150 case 'RelationshipCache':
152 'extends' => ['Relationship'],
153 'column' => 'relationship_id',
156 if (array_key_exists($entityName, \CRM_Core_SelectValues
::customGroupExtends())) {
158 'extends' => [$entityName],
166 * Checks if a custom group exists and is multivalued
168 * @param $customGroupName
170 * @throws \CRM_Core_Exception
172 public static function isCustomEntity($customGroupName) {
173 return $customGroupName && \CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupName, 'is_multiple', 'name');
177 * Check if current user is authorized to perform specified action on a given entity.
179 * @param \Civi\Api4\Generic\AbstractAction $apiRequest
180 * @param array $record
181 * @param int|string $userID
182 * Contact ID of the user we are testing,. 0 for the anonymous user.
184 * @throws \API_Exception
185 * @throws \CRM_Core_Exception
186 * @throws \Civi\API\Exception\NotImplementedException
187 * @throws \Civi\API\Exception\UnauthorizedException
189 public static function checkAccessRecord(\Civi\Api4\Generic\AbstractAction
$apiRequest, array $record, int $userID) {
191 // Super-admins always have access to everything
192 if (\CRM_Core_Permission
::check('all CiviCRM permissions and ACLs', $userID)) {
196 // For get actions, just run a get and ACLs will be applied to the query.
197 // It's a cheap trick and not as efficient as not running the query at all,
198 // but BAO::checkAccess doesn't consistently check permissions for the "get" action.
199 if (is_a($apiRequest, '\Civi\Api4\Generic\DAOGetAction')) {
200 return (bool) $apiRequest->addSelect('id')->addWhere('id', '=', $record['id'])->execute()->count();
203 $event = new \Civi\Api4\Event\
AuthorizeRecordEvent($apiRequest, $record, $userID);
204 \Civi
::dispatcher()->dispatch('civi.api4.authorizeRecord', $event);
206 // Note: $bao::_checkAccess() is a quasi-listener. TODO: Convert to straight-up listener.
207 if ($event->isAuthorized() === NULL) {
208 $baoName = self
::getBAOFromApiName($apiRequest->getEntityName());
209 if ($baoName && method_exists($baoName, '_checkAccess')) {
210 $authorized = $baoName::_checkAccess($event->getEntityName(), $event->getActionName(), $event->getRecord(), $event->getUserID());
211 $event->setAuthorized($authorized);
214 $event->setAuthorized(TRUE);
217 return $event->isAuthorized();
221 * If the permissions of record $A are based on record $B, then use `checkAccessDelegated($B...)`
222 * to make see if access to $B is permitted.
224 * @param string $entityName
225 * @param string $actionName
226 * @param array $record
228 * Contact ID of the user we are testing, or 0 for the anonymous user.
231 * @throws \API_Exception
232 * @throws \CRM_Core_Exception
234 public static function checkAccessDelegated(string $entityName, string $actionName, array $record, int $userID) {
235 $apiRequest = Request
::create($entityName, $actionName, ['version' => 4]);
236 // TODO: Should probably emit civi.api.authorize for checking guardian permission; but in APIv4 with std cfg, this is de-facto equivalent.
237 if (!$apiRequest->isAuthorized()) {
240 return static::checkAccessRecord($apiRequest, $record, $userID);
244 * @return \Civi\Api4\Service\Schema\SchemaMap
246 public static function getSchemaMap() {
247 $cache = \Civi
::cache('metadata');
248 $schemaMap = $cache->get('api4.schema.map');
250 $schemaMap = \Civi
::service('schema_map_builder')->build();
251 $cache->set('api4.schema.map', $schemaMap);
257 * Fetches database references + those returned by hook
259 * @see \CRM_Utils_Hook::referenceCounts()
260 * @param string $entityName
261 * @param int $entityId
262 * @return array{name: string, type: string, count: int, table: string|null, key: string|null}[]
263 * @throws NotImplementedException
265 public static function getRefCount(string $entityName, $entityId) {
266 $daoName = self
::getInfoItem($entityName, 'dao');
268 throw new NotImplementedException("Cannot getRefCount for $entityName - dao not found.");
270 /** @var \CRM_Core_DAO $dao */
271 $dao = new $daoName();
272 $dao->id
= $entityId;
273 return $dao->getReferenceCounts();