Merge pull request #15595 from eileenmcnaughton/dedupe3
[civicrm-core.git] / Civi / API / Provider / MagicFunctionProvider.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 namespace Civi\API\Provider;
29
30 use Civi\API\Events;
31 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
32
33 /**
34 * This class manages the loading of API's using strict file+function naming
35 * conventions.
36 */
37 class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterface {
38
39 /**
40 * @return array
41 */
42 public static function getSubscribedEvents() {
43 return [
44 Events::RESOLVE => [
45 ['onApiResolve', Events::W_MIDDLE],
46 ],
47 ];
48 }
49
50 /**
51 * @var array (string $cachekey => array('function' => string, 'is_generic' => bool))
52 */
53 private $cache;
54
55 /**
56 */
57 public function __construct() {
58 $this->cache = [];
59 }
60
61 /**
62 * @param \Civi\API\Event\ResolveEvent $event
63 * API resolution event.
64 */
65 public function onApiResolve(\Civi\API\Event\ResolveEvent $event) {
66 $apiRequest = $event->getApiRequest();
67 $resolved = $this->resolve($apiRequest);
68 if ($resolved['function']) {
69 $apiRequest += $resolved;
70 $event->setApiRequest($apiRequest);
71 $event->setApiProvider($this);
72 $event->stopPropagation();
73 }
74 }
75
76 /**
77 * @inheritDoc
78 * @param array $apiRequest
79 * @return array
80 */
81 public function invoke($apiRequest) {
82 $function = $apiRequest['function'];
83 if ($apiRequest['function'] && $apiRequest['is_generic']) {
84 // Unlike normal API implementations, generic implementations require explicit
85 // knowledge of the entity and action (as well as $params). Bundle up these bits
86 // into a convenient data structure.
87 if ($apiRequest['action'] === 'getsingle') {
88 // strip any api nested parts here as otherwise chaining may happen twice
89 // see https://lab.civicrm.org/dev/core/issues/643
90 // testCreateBAODefaults fails without this.
91 foreach ($apiRequest['params'] as $key => $param) {
92 if ($key !== 'api.has_parent' && substr($key, 0, 4) === 'api.' || substr($key, 0, 4) === 'api_') {
93 unset($apiRequest['params'][$key]);
94 }
95 }
96 }
97 $result = $function($apiRequest);
98
99 }
100 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
101 $result = $function($apiRequest['params']);
102 }
103 return $result;
104 }
105
106 /**
107 * @inheritDoc
108 * @param int $version
109 * @return array
110 */
111 public function getEntityNames($version) {
112 $entities = [];
113 $include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
114 #$include_dirs = array(dirname(__FILE__). '/../../');
115 foreach ($include_dirs as $include_dir) {
116 $api_dir = implode(DIRECTORY_SEPARATOR,
117 [$include_dir, 'api', 'v' . $version]);
118 if (!is_dir($api_dir)) {
119 continue;
120 }
121 $iterator = new \DirectoryIterator($api_dir);
122 foreach ($iterator as $fileinfo) {
123 $file = $fileinfo->getFilename();
124
125 // Check for entities with a master file ("api/v3/MyEntity.php")
126 $parts = explode(".", $file);
127 if (end($parts) == "php" && $file != "utils.php" && !preg_match('/Tests?.php$/', $file)) {
128 // without the ".php"
129 $entities[] = substr($file, 0, -4);
130 }
131
132 // Check for entities with standalone action files (eg "api/v3/MyEntity/MyAction.php").
133 $action_dir = $api_dir . DIRECTORY_SEPARATOR . $file;
134 if (preg_match('/^[A-Z][A-Za-z0-9]*$/', $file) && is_dir($action_dir)) {
135 if (count(glob("$action_dir/[A-Z]*.php")) > 0) {
136 $entities[] = $file;
137 }
138 }
139 }
140 }
141 $entities = array_diff($entities, ['Generic']);
142 $entities = array_unique($entities);
143 sort($entities);
144
145 return $entities;
146 }
147
148 /**
149 * @inheritDoc
150 * @param int $version
151 * @param string $entity
152 * @return array
153 */
154 public function getActionNames($version, $entity) {
155 $entity = _civicrm_api_get_camel_name($entity);
156 $entities = $this->getEntityNames($version);
157 if (!in_array($entity, $entities)) {
158 return [];
159 }
160 $this->loadEntity($entity, $version);
161
162 $functions = get_defined_functions();
163 $actions = [];
164 $prefix = 'civicrm_api' . $version . '_' . _civicrm_api_get_entity_name_from_camel($entity) . '_';
165 $prefixGeneric = 'civicrm_api' . $version . '_generic_';
166 foreach ($functions['user'] as $fct) {
167 if (strpos($fct, $prefix) === 0) {
168 $actions[] = substr($fct, strlen($prefix));
169 }
170 elseif (strpos($fct, $prefixGeneric) === 0) {
171 $actions[] = substr($fct, strlen($prefixGeneric));
172 }
173 }
174 return $actions;
175 }
176
177 /**
178 * Look up the implementation for a given API request.
179 *
180 * @param array $apiRequest
181 * Array with keys:
182 * - entity: string, required.
183 * - action: string, required.
184 * - params: array.
185 * - version: scalar, required.
186 *
187 * @return array
188 * Array with keys:
189 * - function: callback (mixed)
190 * - is_generic: boolean
191 */
192 protected function resolve($apiRequest) {
193 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
194 if (isset($this->cache[$cachekey])) {
195 return $this->cache[$cachekey];
196 }
197
198 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
199 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
200
201 // Determine if there is an entity-specific implementation of the action
202 $stdFunction = $this->getFunctionName($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
203 if (function_exists($stdFunction)) {
204 // someone already loaded the appropriate file
205 // FIXME: This has the affect of masking bugs in load order; this is
206 // included to provide bug-compatibility.
207 $this->cache[$cachekey] = ['function' => $stdFunction, 'is_generic' => FALSE];
208 return $this->cache[$cachekey];
209 }
210
211 $stdFiles = [
212 // By convention, the $camelName.php is more likely to contain the
213 // function, so test it first
214 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
215 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
216 ];
217 foreach ($stdFiles as $stdFile) {
218 if (\CRM_Utils_File::isIncludable($stdFile)) {
219 require_once $stdFile;
220 if (function_exists($stdFunction)) {
221 $this->cache[$cachekey] = ['function' => $stdFunction, 'is_generic' => FALSE];
222 return $this->cache[$cachekey];
223 }
224 }
225 }
226
227 // Determine if there is a generic implementation of the action
228 require_once 'api/v3/Generic.php';
229 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
230 $genericFunction = $this->getFunctionName('generic', $apiRequest['action'], $apiRequest['version']);
231 $genericFiles = [
232 // By convention, the Generic.php is more likely to contain the
233 // function, so test it first
234 'api/v' . $apiRequest['version'] . '/Generic.php',
235 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
236 ];
237 foreach ($genericFiles as $genericFile) {
238 if (\CRM_Utils_File::isIncludable($genericFile)) {
239 require_once $genericFile;
240 if (function_exists($genericFunction)) {
241 $this->cache[$cachekey] = ['function' => $genericFunction, 'is_generic' => TRUE];
242 return $this->cache[$cachekey];
243 }
244 }
245 }
246
247 $this->cache[$cachekey] = ['function' => FALSE, 'is_generic' => FALSE];
248 return $this->cache[$cachekey];
249 }
250
251 /**
252 * Determine the function name for a given API request.
253 *
254 * @param string $entity
255 * API entity name.
256 * @param string $action
257 * API action name.
258 * @param int $version
259 * API version.
260 *
261 * @return string
262 */
263 protected function getFunctionName($entity, $action, $version) {
264 $entity = _civicrm_api_get_entity_name_from_camel($entity);
265 return 'civicrm_api' . $version . '_' . $entity . '_' . $action;
266 }
267
268 /**
269 * Load/require all files related to an entity.
270 *
271 * This should not normally be called because it's does a file-system scan; it's
272 * only appropriate when introspection is really required (eg for "getActions").
273 *
274 * @param string $entity
275 * API entity name.
276 * @param int $version
277 * API version.
278 */
279 protected function loadEntity($entity, $version) {
280 $camelName = _civicrm_api_get_camel_name($entity, $version);
281
282 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
283 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
284 if (\CRM_Utils_File::isIncludable($stdFile)) {
285 require_once $stdFile;
286 }
287
288 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
289 // array($relativeFilePath => TRUE)
290 $loaded_files = [];
291 $include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
292 foreach ($include_dirs as $include_dir) {
293 foreach ([$camelName, 'Generic'] as $name) {
294 $action_dir = implode(DIRECTORY_SEPARATOR,
295 [$include_dir, 'api', "v${version}", $name]);
296 if (!is_dir($action_dir)) {
297 continue;
298 }
299
300 $iterator = new \DirectoryIterator($action_dir);
301 foreach ($iterator as $fileinfo) {
302 $file = $fileinfo->getFilename();
303 if (array_key_exists($file, $loaded_files)) {
304 // action provided by an earlier item on include_path
305 continue;
306 }
307
308 $parts = explode(".", $file);
309 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file)) {
310 require_once $action_dir . DIRECTORY_SEPARATOR . $file;
311 $loaded_files[$file] = TRUE;
312 }
313 }
314 }
315 }
316 }
317
318 }