Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-04-07-15-32-51
[civicrm-core.git] / Civi / API / Provider / MagicFunctionProvider.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 use Civi\API\Events;
30 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
31
32 /**
33 * This class manages the loading of API's using strict file+function naming
34 * conventions.
35 */
36 class MagicFunctionProvider implements EventSubscriberInterface, ProviderInterface {
37 public static function getSubscribedEvents() {
38 return array(
39 Events::RESOLVE => array(
40 array('onApiResolve', Events::W_MIDDLE),
41 ),
42 );
43 }
44
45 /**
46 * @var array (string $cachekey => array('function' => string, 'is_generic' => bool))
47 */
48 private $cache;
49
50 function __construct() {
51 $this->cache = array();
52 }
53
54 public function onApiResolve(\Civi\API\Event\ResolveEvent $event) {
55 $apiRequest = $event->getApiRequest();
56 $resolved = $this->resolve($apiRequest);
57 if ($resolved['function']) {
58 $apiRequest += $resolved;
59 $event->setApiRequest($apiRequest);
60 $event->setApiProvider($this);
61 $event->stopPropagation();
62 }
63 }
64
65 /**
66 * {inheritdoc}
67 */
68 public function invoke($apiRequest) {
69 $function = $apiRequest['function'];
70 if ($apiRequest['function'] && $apiRequest['is_generic']) {
71 // Unlike normal API implementations, generic implementations require explicit
72 // knowledge of the entity and action (as well as $params). Bundle up these bits
73 // into a convenient data structure.
74 $result = $function($apiRequest);
75 }
76 elseif ($apiRequest['function'] && !$apiRequest['is_generic']) {
77 $result = isset($extra) ? $function($apiRequest['params'], $extra) : $function($apiRequest['params']);
78 }
79 return $result;
80 }
81
82 /**
83 * {inheritdoc}
84 */
85 function getEntityNames($version) {
86 $entities = array();
87 $include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
88 #$include_dirs = array(dirname(__FILE__). '/../../');
89 foreach ($include_dirs as $include_dir) {
90 $api_dir = implode(DIRECTORY_SEPARATOR, array($include_dir, 'api', 'v' . $version));
91 if (! is_dir($api_dir)) {
92 continue;
93 }
94 $iterator = new \DirectoryIterator($api_dir);
95 foreach ($iterator as $fileinfo) {
96 $file = $fileinfo->getFilename();
97
98 // Check for entities with a master file ("api/v3/MyEntity.php")
99 $parts = explode(".", $file);
100 if (end($parts) == "php" && $file != "utils.php" && !preg_match('/Tests?.php$/', $file) ) {
101 // without the ".php"
102 $entities[] = substr($file, 0, -4);
103 }
104
105 // Check for entities with standalone action files ("api/v3/MyEntity/MyAction.php")
106 $action_dir = $api_dir . DIRECTORY_SEPARATOR . $file;
107 if (preg_match('/^[A-Z][A-Za-z0-9]*$/', $file) && is_dir($action_dir)) {
108 if (count(glob("$action_dir/[A-Z]*.php")) > 0) {
109 $entities[] = $file;
110 }
111 }
112 }
113 }
114 $entities = array_diff($entities, array('Generic'));
115 $entities = array_unique($entities);
116 sort($entities);
117
118 return $entities;
119 }
120
121 /**
122 * {inheritdoc}
123 */
124 public function getActionNames($version, $entity) {
125 $entities = $this->getEntityNames($version);
126 if (!in_array($entity, $entities)) {
127 return array();
128 }
129 $this->loadEntity($entity, $version);
130
131 $functions = get_defined_functions();
132 $actions = array();
133 $prefix = 'civicrm_api' . $version . '_' . strtolower($entity) . '_';
134 $prefixGeneric = 'civicrm_api' . $version . '_generic_';
135 foreach ($functions['user'] as $fct) {
136 if (strpos($fct, $prefix) === 0) {
137 $actions[] = substr($fct, strlen($prefix));
138 }
139 elseif (strpos($fct, $prefixGeneric) === 0) {
140 $actions[] = substr($fct, strlen($prefixGeneric));
141 }
142 }
143 return $actions;
144 }
145
146 /**
147 * Look up the implementation for a given API request
148 *
149 * @param $apiRequest array with keys:
150 * - entity: string, required
151 * - action: string, required
152 * - params: array
153 * - version: scalar, required
154 *
155 * @return array with keys
156 * - function: callback (mixed)
157 * - is_generic: boolean
158 */
159 protected function resolve($apiRequest) {
160 $cachekey = strtolower($apiRequest['entity']) . ':' . strtolower($apiRequest['action']) . ':' . $apiRequest['version'];
161 if (isset($this->cache[$cachekey])) {
162 return $this->cache[$cachekey];
163 }
164
165 $camelName = _civicrm_api_get_camel_name($apiRequest['entity'], $apiRequest['version']);
166 $actionCamelName = _civicrm_api_get_camel_name($apiRequest['action']);
167
168 // Determine if there is an entity-specific implementation of the action
169 $stdFunction = $this->getFunctionName($apiRequest['entity'], $apiRequest['action'], $apiRequest['version']);
170 if (function_exists($stdFunction)) {
171 // someone already loaded the appropriate file
172 // FIXME: This has the affect of masking bugs in load order; this is included to provide bug-compatibility
173 $this->cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
174 return $this->cache[$cachekey];
175 }
176
177 $stdFiles = array(
178 // By convention, the $camelName.php is more likely to contain the function, so test it first
179 'api/v' . $apiRequest['version'] . '/' . $camelName . '.php',
180 'api/v' . $apiRequest['version'] . '/' . $camelName . '/' . $actionCamelName . '.php',
181 );
182 foreach ($stdFiles as $stdFile) {
183 if (\CRM_Utils_File::isIncludable($stdFile)) {
184 require_once $stdFile;
185 if (function_exists($stdFunction)) {
186 $this->cache[$cachekey] = array('function' => $stdFunction, 'is_generic' => FALSE);
187 return $this->cache[$cachekey];
188 }
189 }
190 }
191
192 // Determine if there is a generic implementation of the action
193 require_once 'api/v3/Generic.php';
194 # $genericFunction = 'civicrm_api3_generic_' . $apiRequest['action'];
195 $genericFunction = $this->getFunctionName('generic', $apiRequest['action'], $apiRequest['version']);
196 $genericFiles = array(
197 // By convention, the Generic.php is more likely to contain the function, so test it first
198 'api/v' . $apiRequest['version'] . '/Generic.php',
199 'api/v' . $apiRequest['version'] . '/Generic/' . $actionCamelName . '.php',
200 );
201 foreach ($genericFiles as $genericFile) {
202 if (\CRM_Utils_File::isIncludable($genericFile)) {
203 require_once $genericFile;
204 if (function_exists($genericFunction)) {
205 $this->cache[$cachekey] = array('function' => $genericFunction, 'is_generic' => TRUE);
206 return $this->cache[$cachekey];
207 }
208 }
209 }
210
211 $this->cache[$cachekey] = array('function' => FALSE, 'is_generic' => FALSE);
212 return $this->cache[$cachekey];
213 }
214
215 /**
216 * @param string $entity
217 * @param string $action
218 * @return string
219 */
220 protected function getFunctionName($entity, $action, $version) {
221 $entity = _civicrm_api_get_entity_name_from_camel($entity);
222 return 'civicrm_api' . $version . '_' . $entity . '_' . $action;
223 }
224
225 /**
226 * Load/require all files related to an entity.
227 *
228 * This should not normally be called because it's does a file-system scan; it's
229 * only appropriate when introspection is really required (eg for "getActions").
230 *
231 * @param string $entity
232 * @param int $version
233 *
234 * @return void
235 */
236 protected function loadEntity($entity, $version) {
237 $camelName = _civicrm_api_get_camel_name($entity, $version);
238
239 // Check for master entity file; to match _civicrm_api_resolve(), only load the first one
240 $stdFile = 'api/v' . $version . '/' . $camelName . '.php';
241 if (\CRM_Utils_File::isIncludable($stdFile)) {
242 require_once $stdFile;
243 }
244
245 // Check for standalone action files; to match _civicrm_api_resolve(), only load the first one
246 $loaded_files = array(); // array($relativeFilePath => TRUE)
247 $include_dirs = array_unique(explode(PATH_SEPARATOR, get_include_path()));
248 foreach ($include_dirs as $include_dir) {
249 $action_dir = implode(DIRECTORY_SEPARATOR, array($include_dir, 'api', "v${version}", $camelName));
250 if (!is_dir($action_dir)) {
251 continue;
252 }
253
254 $iterator = new \DirectoryIterator($action_dir);
255 foreach ($iterator as $fileinfo) {
256 $file = $fileinfo->getFilename();
257 if (array_key_exists($file, $loaded_files)) {
258 continue; // action provided by an earlier item on include_path
259 }
260
261 $parts = explode(".", $file);
262 if (end($parts) == "php" && !preg_match('/Tests?\.php$/', $file)) {
263 require_once $action_dir . DIRECTORY_SEPARATOR . $file;
264 $loaded_files[$file] = TRUE;
265 }
266 }
267 }
268 }
269
270 }