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