Merge pull request #13809 from sushantpaste/auto-complete-search
[civicrm-core.git] / CRM / Extension / Mapper.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This class proivdes various helper functions for locating extensions
14 * data. It's designed for compatibility with pre-existing functions from
15 * CRM_Core_Extensions.
16 *
17 * Most of these helper functions originate with the first major iteration
18 * of extensions -- a time when every extension had one eponymous PHP class,
19 * when there was no PHP class-loader, and when there was special-case logic
20 * sprinkled around to handle loading of "extension classes".
21 *
22 * With module-extensions (Civi 4.2+), there are no eponymous classes --
23 * instead, module-extensions follow the same class-naming and class-loading
24 * practices as core (and don't require special-case logic for class
25 * loading). Consequently, the helpers in here aren't much used with
26 * module-extensions.
27 *
28 * @package CRM
29 * @copyright CiviCRM LLC https://civicrm.org/licensing
30 */
31 class CRM_Extension_Mapper {
32
33 /**
34 * An URL for public extensions repository.
35 */
36
37 /**
38 * Extension info file name.
39 */
40 const EXT_TEMPLATES_DIRNAME = 'templates';
41
42 /**
43 * @var CRM_Extension_Container_Interface
44 */
45 protected $container;
46
47 /**
48 * @var \CRM_Extension_Info[]
49 * (key => CRM_Extension_Info)
50 */
51 protected $infos = [];
52
53 /**
54 * @var array
55 */
56 protected $moduleExtensions = NULL;
57
58 /**
59 * @var CRM_Utils_Cache_Interface
60 */
61 protected $cache;
62
63 protected $cacheKey;
64
65 protected $civicrmPath;
66
67 protected $civicrmUrl;
68
69 /**
70 * @param CRM_Extension_Container_Interface $container
71 * @param CRM_Utils_Cache_Interface $cache
72 * @param null $cacheKey
73 * @param null $civicrmPath
74 * @param null $civicrmUrl
75 */
76 public function __construct(CRM_Extension_Container_Interface $container, CRM_Utils_Cache_Interface $cache = NULL, $cacheKey = NULL, $civicrmPath = NULL, $civicrmUrl = NULL) {
77 $this->container = $container;
78 $this->cache = $cache;
79 $this->cacheKey = $cacheKey;
80 if ($civicrmUrl) {
81 $this->civicrmUrl = rtrim($civicrmUrl, '/');
82 }
83 else {
84 $config = CRM_Core_Config::singleton();
85 $this->civicrmUrl = rtrim($config->resourceBase, '/');
86 }
87 if ($civicrmPath) {
88 $this->civicrmPath = rtrim($civicrmPath, '/');
89 }
90 else {
91 global $civicrm_root;
92 $this->civicrmPath = rtrim($civicrm_root, '/');
93 }
94 }
95
96 /**
97 * Given the class, provides extension's key.
98 *
99 *
100 * @param string $clazz
101 * Extension class name.
102 *
103 * @return string
104 * name of extension key
105 */
106 public function classToKey($clazz) {
107 return str_replace('_', '.', $clazz);
108 }
109
110 /**
111 * Given the class, provides extension path.
112 *
113 *
114 * @param $clazz
115 *
116 * @return string
117 * full path the extension .php file
118 */
119 public function classToPath($clazz) {
120 $elements = explode('_', $clazz);
121 $key = implode('.', $elements);
122 return $this->keyToPath($key);
123 }
124
125 /**
126 * Given the string, returns true or false if it's an extension key.
127 *
128 *
129 * @param string $key
130 * A string which might be an extension key.
131 *
132 * @return bool
133 * true if given string is an extension name
134 */
135 public function isExtensionKey($key) {
136 // check if the string is an extension name or the class
137 return (strpos($key, '.') !== FALSE) ? TRUE : FALSE;
138 }
139
140 /**
141 * Given the string, returns true or false if it's an extension class name.
142 *
143 *
144 * @param string $clazz
145 * A string which might be an extension class name.
146 *
147 * @return bool
148 * true if given string is an extension class name
149 */
150 public function isExtensionClass($clazz) {
151
152 if (substr($clazz, 0, 4) != 'CRM_') {
153 return (bool) preg_match('/^[a-z0-9]+(_[a-z0-9]+)+$/', $clazz);
154 }
155 return FALSE;
156 }
157
158 /**
159 * @param string $key
160 * Extension fully-qualified-name.
161 * @param bool $fresh
162 *
163 * @throws CRM_Extension_Exception
164 *
165 * @return CRM_Extension_Info
166 */
167 public function keyToInfo($key, $fresh = FALSE) {
168 if ($fresh || !array_key_exists($key, $this->infos)) {
169 try {
170 $this->infos[$key] = CRM_Extension_Info::loadFromFile($this->container->getPath($key) . DIRECTORY_SEPARATOR . CRM_Extension_Info::FILENAME);
171 }
172 catch (CRM_Extension_Exception $e) {
173 // file has more detailed info, but we'll fallback to DB if it's missing -- DB has enough info to uninstall
174 $this->infos[$key] = CRM_Extension_System::singleton()->getManager()->createInfoFromDB($key);
175 if (!$this->infos[$key]) {
176 throw $e;
177 }
178 }
179 }
180 return $this->infos[$key];
181 }
182
183 /**
184 * Given the key, provides extension's class name.
185 *
186 *
187 * @param string $key
188 * Extension key.
189 *
190 * @return string
191 * name of extension's main class
192 */
193 public function keyToClass($key) {
194 return str_replace('.', '_', $key);
195 }
196
197 /**
198 * Given the key, provides the path to file containing
199 * extension's main class.
200 *
201 *
202 * @param string $key
203 * Extension key.
204 *
205 * @return string
206 * path to file containing extension's main class
207 */
208 public function keyToPath($key) {
209 $info = $this->keyToInfo($key);
210 return $this->container->getPath($key) . DIRECTORY_SEPARATOR . $info->file . '.php';
211 }
212
213 /**
214 * Given the key, provides the path to file containing
215 * extension's main class.
216 *
217 * @param string $key
218 * Extension key.
219 * @return string
220 * local path of the extension source tree
221 */
222 public function keyToBasePath($key) {
223 if ($key == 'civicrm') {
224 return $this->civicrmPath;
225 }
226 return $this->container->getPath($key);
227 }
228
229 /**
230 * Given the key, provides the path to file containing
231 * extension's main class.
232 *
233 *
234 * @param string $key
235 * Extension key.
236 *
237 * @return string
238 * url for resources in this extension
239 *
240 * @throws \CRM_Extension_Exception_MissingException
241 */
242 public function keyToUrl($key) {
243 if ($key === 'civicrm') {
244 // CRM-12130 Workaround: If the domain's config_backend is NULL at the start of the request,
245 // then the Mapper is wrongly constructed with an empty value for $this->civicrmUrl.
246 if (empty($this->civicrmUrl)) {
247 $config = CRM_Core_Config::singleton();
248 return rtrim($config->resourceBase, '/');
249 }
250 return $this->civicrmUrl;
251 }
252
253 return $this->container->getResUrl($key);
254 }
255
256 /**
257 * Fetch the list of active extensions of type 'module'
258 *
259 * @param bool $fresh
260 * whether to forcibly reload extensions list from canonical store.
261 * @return array
262 * array(array('prefix' => $, 'fullName' => $, 'filePath' => $))
263 */
264 public function getActiveModuleFiles($fresh = FALSE) {
265 if (!defined('CIVICRM_DSN')) {
266 // hmm, ok
267 return [];
268 }
269
270 // The list of module files is cached in two tiers. The tiers are slightly
271 // different:
272 //
273 // 1. The persistent tier (cache) stores
274 // names WITHOUT absolute paths.
275 // 2. The ephemeral/thread-local tier (statics) stores names
276 // WITH absolute paths.
277 // Return static value instead of re-running query
278 if (isset(Civi::$statics[__CLASS__]['moduleExtensions']) && !$fresh) {
279 return Civi::$statics[__CLASS__]['moduleExtensions'];
280 }
281
282 $moduleExtensions = NULL;
283
284 // Checked if it's stored in the persistent cache.
285 if ($this->cache && !$fresh) {
286 $moduleExtensions = $this->cache->get($this->cacheKey . '_moduleFiles');
287 }
288
289 // If cache is empty we build it from database.
290 if (!is_array($moduleExtensions)) {
291 $compat = CRM_Extension_System::getCompatibilityInfo();
292
293 // Check canonical module list
294 $moduleExtensions = [];
295 $sql = '
296 SELECT full_name, file
297 FROM civicrm_extension
298 WHERE is_active = 1
299 AND type = "module"
300 ';
301 $dao = CRM_Core_DAO::executeQuery($sql);
302 while ($dao->fetch()) {
303 if (!empty($compat[$dao->full_name]['force-uninstall'])) {
304 continue;
305 }
306 $moduleExtensions[] = [
307 'prefix' => $dao->file,
308 'fullName' => $dao->full_name,
309 'filePath' => NULL,
310 ];
311 }
312
313 if ($this->cache) {
314 $this->cache->set($this->cacheKey . '_moduleFiles', $moduleExtensions);
315 }
316 }
317
318 // Since we're not caching the full path we add it now.
319 array_walk($moduleExtensions, function(&$value, $key) {
320 try {
321 if (!$value['filePath']) {
322 $value['filePath'] = $this->keyToPath($value['fullName']);
323 }
324 }
325 catch (CRM_Extension_Exception $e) {
326 // Putting a stub here provides more consistency
327 // in how getActiveModuleFiles when racing between
328 // dirty file-removals and cache-clears.
329 CRM_Core_Session::setStatus($e->getMessage(), '', 'error');
330 $value['filePath'] = NULL;
331 }
332 });
333
334 Civi::$statics[__CLASS__]['moduleExtensions'] = $moduleExtensions;
335
336 return $moduleExtensions;
337 }
338
339 /**
340 * Get a list of base URLs for all active modules.
341 *
342 * @return array
343 * (string $extKey => string $baseUrl)
344 *
345 * @throws \CRM_Extension_Exception_MissingException
346 */
347 public function getActiveModuleUrls() {
348 // TODO optimization/caching
349 $urls = [];
350 $urls['civicrm'] = $this->keyToUrl('civicrm');
351 foreach ($this->getModules() as $module) {
352 /** @var $module CRM_Core_Module */
353 if ($module->is_active) {
354 try {
355 $urls[$module->name] = $this->keyToUrl($module->name);
356 }
357 catch (CRM_Extension_Exception_MissingException $e) {
358 CRM_Core_Session::setStatus(ts('An enabled extension is missing from the extensions directory') . ':' . $module->name);
359 }
360 }
361 }
362 return $urls;
363 }
364
365 /**
366 * Get a list of extension keys, filtered by the corresponding file path.
367 *
368 * @param string $pattern
369 * A file path. To search subdirectories, append "*".
370 * Ex: "/var/www/extensions/*"
371 * Ex: "/var/www/extensions/org.foo.bar"
372 * @return array
373 * Array(string $key).
374 * Ex: array("org.foo.bar").
375 */
376 public function getKeysByPath($pattern) {
377 $keys = [];
378
379 if (CRM_Utils_String::endsWith($pattern, '*')) {
380 $prefix = rtrim($pattern, '*');
381 foreach ($this->container->getKeys() as $key) {
382 $path = CRM_Utils_File::addTrailingSlash($this->container->getPath($key));
383 if (realpath($prefix) == realpath($path) || CRM_Utils_File::isChildPath($prefix, $path)) {
384 $keys[] = $key;
385 }
386 }
387 }
388 else {
389 foreach ($this->container->getKeys() as $key) {
390 $path = CRM_Utils_File::addTrailingSlash($this->container->getPath($key));
391 if (realpath($pattern) == realpath($path)) {
392 $keys[] = $key;
393 }
394 }
395 }
396
397 return $keys;
398 }
399
400 /**
401 * Get a list of extensions which match a given tag.
402 *
403 * @param string $tag
404 * Ex: 'foo'
405 * @return array
406 * Array(string $key).
407 * Ex: array("org.foo.bar").
408 */
409 public function getKeysByTag($tag) {
410 $allTags = $this->getAllTags();
411 return $allTags[$tag] ?? [];
412 }
413
414 /**
415 * Get a list of extension tags.
416 *
417 * @return array
418 * Ex: ['form-building' => ['org.civicrm.afform-gui', 'org.civicrm.afform-html']]
419 */
420 public function getAllTags() {
421 $tags = Civi::cache('short')->get('extension_tags', NULL);
422 if ($tags !== NULL) {
423 return $tags;
424 }
425
426 $tags = [];
427 $allInfos = $this->getAllInfos();
428 foreach ($allInfos as $key => $info) {
429 foreach ($info->tags as $tag) {
430 $tags[$tag][] = $key;
431 }
432 }
433 return $tags;
434 }
435
436 /**
437 * @return array
438 * Ex: $result['org.civicrm.foobar'] = new CRM_Extension_Info(...).
439 * @throws \CRM_Extension_Exception
440 * @throws \Exception
441 */
442 public function getAllInfos() {
443 foreach ($this->container->getKeys() as $key) {
444 $this->keyToInfo($key);
445 }
446 return $this->infos;
447 }
448
449 /**
450 * @param string $name
451 *
452 * @return bool
453 */
454 public function isActiveModule($name) {
455 $activeModules = $this->getActiveModuleFiles();
456 foreach ($activeModules as $activeModule) {
457 if ($activeModule['prefix'] == $name) {
458 return TRUE;
459 }
460 }
461 return FALSE;
462 }
463
464 /**
465 * Get a list of all installed modules, including enabled and disabled ones
466 *
467 * @return array
468 * CRM_Core_Module
469 */
470 public function getModules() {
471 $result = [];
472 $dao = new CRM_Core_DAO_Extension();
473 $dao->type = 'module';
474 $dao->find();
475 while ($dao->fetch()) {
476 $result[] = new CRM_Core_Module($dao->full_name, $dao->is_active);
477 }
478 return $result;
479 }
480
481 /**
482 * Given the class, provides the template path.
483 *
484 *
485 * @param string $clazz
486 * Extension class name.
487 *
488 * @return string
489 * path to extension's templates directory
490 */
491 public function getTemplatePath($clazz) {
492 $path = $this->container->getPath($this->classToKey($clazz));
493 return $path . DIRECTORY_SEPARATOR . self::EXT_TEMPLATES_DIRNAME;
494 /*
495 $path = $this->classToPath($clazz);
496 $pathElm = explode(DIRECTORY_SEPARATOR, $path);
497 array_pop($pathElm);
498 return implode(DIRECTORY_SEPARATOR, $pathElm) . DIRECTORY_SEPARATOR . self::EXT_TEMPLATES_DIRNAME;
499 */
500 }
501
502 /**
503 * Given te class, provides the template name.
504 * @todo consider multiple templates, support for one template for now
505 *
506 *
507 * @param string $clazz
508 * Extension class name.
509 *
510 * @return string
511 * extension's template name
512 */
513 public function getTemplateName($clazz) {
514 $info = $this->keyToInfo($this->classToKey($clazz));
515 return (string) $info->file . '.tpl';
516 }
517
518 public function refresh() {
519 $this->infos = [];
520 $this->moduleExtensions = NULL;
521 if ($this->cache) {
522 $this->cache->delete($this->cacheKey . '_moduleFiles');
523 }
524 // FIXME: How can code so code wrong be so right?
525 CRM_Extension_System::singleton()->getClassLoader()->refresh();
526 }
527
528 }