3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
28 namespace Civi\API\Provider
;
31 use Symfony\Component\EventDispatcher\EventSubscriberInterface
;
34 * This class manages the loading of API's using strict file+function naming
37 class MagicFunctionProvider
implements EventSubscriberInterface
, ProviderInterface
{
42 public static function getSubscribedEvents() {
45 ['onApiResolve', Events
::W_MIDDLE
],
51 * @var array (string $cachekey => array('function' => string, 'is_generic' => bool))
57 public function __construct() {
62 * @param \Civi\API\Event\ResolveEvent $event
63 * API resolution event.
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();
78 * @param array $apiRequest
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]);
97 $result = $function($apiRequest);
100 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
101 $result = $function($apiRequest['params']);
108 * @param int $version
111 public function getEntityNames($version) {
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)) {
121 $iterator = new \
DirectoryIterator($api_dir);
122 foreach ($iterator as $fileinfo) {
123 $file = $fileinfo->getFilename();
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);
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) {
141 $entities = array_diff($entities, ['Generic']);
142 $entities = array_unique($entities);
150 * @param int $version
151 * @param string $entity
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)) {
160 $this->loadEntity($entity, $version);
162 $functions = get_defined_functions();
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));
170 elseif (strpos($fct, $prefixGeneric) === 0) {
171 $actions[] = substr($fct, strlen($prefixGeneric));
178 * Look up the implementation for a given API request.
180 * @param array $apiRequest
182 * - entity: string, required.
183 * - action: string, required.
185 * - version: scalar, required.
189 * - function: callback (mixed)
190 * - is_generic: boolean
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];
198 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
199 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
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];
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',
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];
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']);
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',
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];
247 $this->cache
[$cachekey] = ['function' => FALSE, 'is_generic' => FALSE];
248 return $this->cache
[$cachekey];
252 * Determine the function name for a given API request.
254 * @param string $entity
256 * @param string $action
258 * @param int $version
263 protected function getFunctionName($entity, $action, $version) {
264 $entity = _civicrm_api_get_entity_name_from_camel($entity);
265 return 'civicrm_api' . $version . '_' . $entity . '_' . $action;
269 * Load/require all files related to an entity.
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").
274 * @param string $entity
276 * @param int $version
279 protected function loadEntity($entity, $version) {
280 $camelName = _civicrm_api_get_camel_name($entity, $version);
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;
288 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
289 // array($relativeFilePath => TRUE)
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)) {
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
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;