Merge pull request #22131 from civicrm/5.44
[civicrm-core.git] / Civi / Api4 / Utils / CoreUtil.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 namespace Civi\Api4\Utils;
14
15 use Civi\API\Exception\NotImplementedException;
16 use Civi\API\Request;
17 use Civi\Api4\Entity;
18 use Civi\Api4\Event\CreateApi4RequestEvent;
19 use CRM_Core_DAO_AllCoreTables as AllCoreTables;
20
21 class CoreUtil {
22
23 /**
24 * @param $entityName
25 *
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
29 */
30 public static function getBAOFromApiName($entityName) {
31 if ($entityName === 'CustomValue' || strpos($entityName, 'Custom_') === 0) {
32 return 'CRM_Core_BAO_CustomValue';
33 }
34 $dao = AllCoreTables::getFullName($entityName);
35 return $dao ? AllCoreTables::getBAOClassName($dao) : NULL;
36 }
37
38 /**
39 * @param $entityName
40 * @return string|\Civi\Api4\Generic\AbstractEntity
41 */
42 public static function getApiClass($entityName) {
43 $e = new CreateApi4RequestEvent($entityName);
44 \Civi::dispatcher()->dispatch('civi.api4.createRequest', $e);
45 return $e->className;
46 }
47
48 /**
49 * Get a piece of metadata about an entity
50 *
51 * @param string $entityName
52 * @param string $keyToReturn
53 * @return mixed
54 */
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');
59 if ($cached) {
60 $info = $cached[$entityName] ?? NULL;
61 }
62 // If the cache is empty, calling Entity.get will populate it and we'll use it next time.
63 else {
64 $info = Entity::get(FALSE)
65 ->addWhere('name', '=', $entityName)
66 ->addSelect($keyToReturn)
67 ->execute()->first();
68 }
69 return $info ? $info[$keyToReturn] ?? NULL : NULL;
70 }
71
72 /**
73 * Get name of unique identifier, typically "id"
74 * @param string $entityName
75 * @return string
76 */
77 public static function getIdFieldName(string $entityName): string {
78 return self::getInfoItem($entityName, 'primary_key')[0] ?? 'id';
79 }
80
81 /**
82 * Get table name of given entity
83 *
84 * @param string $entityName
85 *
86 * @return string
87 */
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');
92 }
93 return AllCoreTables::getTableForEntityName($entityName);
94 }
95
96 /**
97 * Given a sql table name, return the name of the api entity.
98 *
99 * @param $tableName
100 * @return string|NULL
101 */
102 public static function getApiNameFromTableName($tableName) {
103 $entityName = AllCoreTables::getBriefName(AllCoreTables::getClassForTable($tableName));
104 // Real entities
105 if ($entityName) {
106 // Verify class exists
107 return self::getApiClass($entityName) ? $entityName : NULL;
108 }
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;
112 }
113
114 /**
115 * @return string[]
116 */
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';
124 return $operators;
125 }
126
127 /**
128 * For a given API Entity, return the types of custom fields it supports and the column they join to.
129 *
130 * @param string $entityName
131 * @return array|mixed|null
132 * @throws \API_Exception
133 * @throws \Civi\API\Exception\UnauthorizedException
134 */
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) {
138 case 'Contact':
139 return [
140 'extends' => array_merge(['Contact'], array_keys(\CRM_Core_SelectValues::contactType())),
141 'column' => 'id',
142 ];
143
144 case 'Participant':
145 return [
146 'extends' => ['Participant', 'ParticipantRole', 'ParticipantEventName', 'ParticipantEventType'],
147 'column' => 'id',
148 ];
149
150 case 'RelationshipCache':
151 return [
152 'extends' => ['Relationship'],
153 'column' => 'relationship_id',
154 ];
155 }
156 if (array_key_exists($entityName, \CRM_Core_SelectValues::customGroupExtends())) {
157 return [
158 'extends' => [$entityName],
159 'column' => 'id',
160 ];
161 }
162 return NULL;
163 }
164
165 /**
166 * Checks if a custom group exists and is multivalued
167 *
168 * @param $customGroupName
169 * @return bool
170 * @throws \CRM_Core_Exception
171 */
172 public static function isCustomEntity($customGroupName) {
173 return $customGroupName && \CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupName, 'is_multiple', 'name');
174 }
175
176 /**
177 * Check if current user is authorized to perform specified action on a given entity.
178 *
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.
183 * @return bool
184 * @throws \API_Exception
185 * @throws \CRM_Core_Exception
186 * @throws \Civi\API\Exception\NotImplementedException
187 * @throws \Civi\API\Exception\UnauthorizedException
188 */
189 public static function checkAccessRecord(\Civi\Api4\Generic\AbstractAction $apiRequest, array $record, int $userID) {
190
191 // Super-admins always have access to everything
192 if (\CRM_Core_Permission::check('all CiviCRM permissions and ACLs', $userID)) {
193 return TRUE;
194 }
195
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();
201 }
202
203 $event = new \Civi\Api4\Event\AuthorizeRecordEvent($apiRequest, $record, $userID);
204 \Civi::dispatcher()->dispatch('civi.api4.authorizeRecord', $event);
205
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);
212 }
213 else {
214 $event->setAuthorized(TRUE);
215 }
216 }
217 return $event->isAuthorized();
218 }
219
220 /**
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.
223 *
224 * @param string $entityName
225 * @param string $actionName
226 * @param array $record
227 * @param int $userID
228 * Contact ID of the user we are testing, or 0 for the anonymous user.
229 *
230 * @return bool
231 * @throws \API_Exception
232 * @throws \CRM_Core_Exception
233 */
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()) {
238 return FALSE;
239 }
240 return static::checkAccessRecord($apiRequest, $record, $userID);
241 }
242
243 /**
244 * @return \Civi\Api4\Service\Schema\SchemaMap
245 */
246 public static function getSchemaMap() {
247 $cache = \Civi::cache('metadata');
248 $schemaMap = $cache->get('api4.schema.map');
249 if (!$schemaMap) {
250 $schemaMap = \Civi::service('schema_map_builder')->build();
251 $cache->set('api4.schema.map', $schemaMap);
252 }
253 return $schemaMap;
254 }
255
256 /**
257 * Fetches database references + those returned by hook
258 *
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
264 */
265 public static function getRefCount(string $entityName, $entityId) {
266 $daoName = self::getInfoItem($entityName, 'dao');
267 if (!$daoName) {
268 throw new NotImplementedException("Cannot getRefCount for $entityName - dao not found.");
269 }
270 /** @var \CRM_Core_DAO $dao */
271 $dao = new $daoName();
272 $dao->id = $entityId;
273 return $dao->getReferenceCounts();
274 }
275
276 }