APIv4 - Enable getFields to find fields across implicit FK joins
[civicrm-core.git] / Civi / Angular / Manager.php
1 <?php
2 namespace Civi\Angular;
3
4 /**
5 * Manage Angular resources.
6 *
7 * @package Civi\Angular
8 */
9 class Manager {
10
11 /**
12 * @var \CRM_Core_Resources
13 */
14 protected $res = NULL;
15
16 /**
17 * Modules.
18 *
19 * @var array|null
20 * Each item has some combination of these keys:
21 * - ext: string
22 * The Civi extension which defines the Angular module.
23 * - js: array(string $relativeFilePath)
24 * List of JS files (relative to the extension).
25 * - css: array(string $relativeFilePath)
26 * List of CSS files (relative to the extension).
27 * - partials: array(string $relativeFilePath)
28 * A list of partial-HTML folders (relative to the extension).
29 * This will be mapped to "~/moduleName" by crmResource.
30 * - settings: array(string $key => mixed $value)
31 * List of settings to preload.
32 * - settingsFactory: callable
33 * Callback function to fetch settings.
34 * - permissions: array
35 * List of permissions to make available client-side
36 * - requires: array
37 * List of other modules required
38 */
39 protected $modules = NULL;
40
41 /**
42 * @var \CRM_Utils_Cache_Interface
43 */
44 protected $cache;
45
46 /**
47 * @var array
48 * Array(string $name => ChangeSet $change).
49 */
50 protected $changeSets = NULL;
51
52 /**
53 * @param \CRM_Core_Resources $res
54 * The resource manager.
55 * @param $cache
56 */
57 public function __construct($res, \CRM_Utils_Cache_Interface $cache = NULL) {
58 $this->res = $res;
59 $this->cache = $cache ? $cache : new \CRM_Utils_Cache_ArrayCache([]);
60 }
61
62 /**
63 * Clear out any runtime-cached metadata.
64 *
65 * This is useful if, eg, you have recently added or destroyed Angular modules.
66 *
67 * @return static
68 */
69 public function clear() {
70 $this->cache->clear();
71 $this->modules = NULL;
72 $this->changeSets = NULL;
73 return $this;
74 }
75
76 /**
77 * Get a list of AngularJS modules which should be autoloaded.
78 *
79 * @return array
80 * Each item has some combination of these keys:
81 * - ext: string
82 * The Civi extension which defines the Angular module.
83 * - js: array(string $relativeFilePath)
84 * List of JS files (relative to the extension).
85 * - css: array(string $relativeFilePath)
86 * List of CSS files (relative to the extension).
87 * - partials: array(string $relativeFilePath)
88 * A list of partial-HTML folders (relative to the extension).
89 * This will be mapped to "~/moduleName" by crmResource.
90 * - settings: array(string $key => mixed $value)
91 * List of settings to preload.
92 */
93 public function getModules() {
94 if ($this->modules === NULL) {
95 $config = \CRM_Core_Config::singleton();
96 global $civicrm_root;
97
98 // Note: It would be nice to just glob("$civicrm_root/ang/*.ang.php"), but at time
99 // of writing CiviMail and CiviCase have special conditionals.
100
101 $angularModules = [];
102 $angularModules['angularFileUpload'] = include "$civicrm_root/ang/angularFileUpload.ang.php";
103 $angularModules['checklist-model'] = include "$civicrm_root/ang/checklist-model.ang.php";
104 $angularModules['crmApp'] = include "$civicrm_root/ang/crmApp.ang.php";
105 $angularModules['crmAttachment'] = include "$civicrm_root/ang/crmAttachment.ang.php";
106 $angularModules['crmAutosave'] = include "$civicrm_root/ang/crmAutosave.ang.php";
107 $angularModules['crmCxn'] = include "$civicrm_root/ang/crmCxn.ang.php";
108 $angularModules['crmMonaco'] = include "$civicrm_root/ang/crmMonaco.ang.php";
109 $angularModules['crmResource'] = include "$civicrm_root/ang/crmResource.ang.php";
110 $angularModules['crmRouteBinder'] = include "$civicrm_root/ang/crmRouteBinder.ang.php";
111 $angularModules['crmUi'] = include "$civicrm_root/ang/crmUi.ang.php";
112 $angularModules['crmUtil'] = include "$civicrm_root/ang/crmUtil.ang.php";
113 $angularModules['dialogService'] = include "$civicrm_root/ang/dialogService.ang.php";
114 $angularModules['jsonFormatter'] = include "$civicrm_root/ang/jsonFormatter.ang.php";
115 $angularModules['ngRoute'] = include "$civicrm_root/ang/ngRoute.ang.php";
116 $angularModules['ngSanitize'] = include "$civicrm_root/ang/ngSanitize.ang.php";
117 $angularModules['ui.utils'] = include "$civicrm_root/ang/ui.utils.ang.php";
118 $angularModules['ui.bootstrap'] = include "$civicrm_root/ang/ui.bootstrap.ang.php";
119 $angularModules['ui.sortable'] = include "$civicrm_root/ang/ui.sortable.ang.php";
120 $angularModules['unsavedChanges'] = include "$civicrm_root/ang/unsavedChanges.ang.php";
121 $angularModules['crmStatusPage'] = include "$civicrm_root/ang/crmStatusPage.ang.php";
122 $angularModules['exportui'] = include "$civicrm_root/ang/exportui.ang.php";
123 $angularModules['api4Explorer'] = include "$civicrm_root/ang/api4Explorer.ang.php";
124 $angularModules['api4'] = include "$civicrm_root/ang/api4.ang.php";
125 $angularModules['crmDashboard'] = include "$civicrm_root/ang/crmDashboard.ang.php";
126 $angularModules['crmD3'] = include "$civicrm_root/ang/crmD3.ang.php";
127
128 foreach (\CRM_Core_Component::getEnabledComponents() as $component) {
129 $angularModules = array_merge($angularModules, $component->getAngularModules());
130 }
131 \CRM_Utils_Hook::angularModules($angularModules);
132 foreach ($angularModules as $module => $info) {
133 // Merge in defaults
134 $angularModules[$module] += ['basePages' => ['civicrm/a']];
135 // Validate settingsFactory callables
136 if (isset($info['settingsFactory'])) {
137 // To keep the cache small, we want `settingsFactory` to contain the string names of class & function, not an object
138 if (!is_array($info['settingsFactory']) && !is_string($info['settingsFactory'])) {
139 throw new \CRM_Core_Exception($module . ' settingsFactory must be a callable array or string');
140 }
141 // To keep the cache small, convert full object to just the class name
142 if (is_array($info['settingsFactory']) && is_object($info['settingsFactory'][0])) {
143 $angularModules[$module]['settingsFactory'][0] = get_class($info['settingsFactory'][0]);
144 }
145 }
146 }
147 $this->modules = $this->resolvePatterns($angularModules);
148 }
149
150 return $this->modules;
151 }
152
153 /**
154 * Get the descriptor for an Angular module.
155 *
156 * @param string $name
157 * Module name.
158 * @return array
159 * Details about the module:
160 * - ext: string, the name of the Civi extension which defines the module
161 * - js: array(string $relativeFilePath).
162 * - css: array(string $relativeFilePath).
163 * - partials: array(string $relativeFilePath).
164 * @throws \Exception
165 */
166 public function getModule($name) {
167 $modules = $this->getModules();
168 if (!isset($modules[$name])) {
169 throw new \Exception("Unrecognized Angular module");
170 }
171 return $modules[$name];
172 }
173
174 /**
175 * Resolve a full list of Angular dependencies.
176 *
177 * @param array $names
178 * List of Angular modules.
179 * Ex: array('crmMailing').
180 * @return array
181 * List of Angular modules, include all dependencies.
182 * Ex: array('crmMailing', 'crmUi', 'crmUtil', 'ngRoute').
183 * @throws \CRM_Core_Exception
184 */
185 public function resolveDependencies($names) {
186 $allModules = $this->getModules();
187 $visited = [];
188 $result = $names;
189 while (($missingModules = array_diff($result, array_keys($visited))) && !empty($missingModules)) {
190 foreach ($missingModules as $module) {
191 $visited[$module] = 1;
192 if (!isset($allModules[$module])) {
193 throw new \CRM_Core_Exception("Unrecognized Angular module {$module}. Please ensure that all Angular modules are declared.");
194 }
195 elseif (isset($allModules[$module]['requires'])) {
196 $result = array_unique(array_merge($result, $allModules[$module]['requires']));
197 }
198 }
199 }
200 sort($result);
201 return $result;
202 }
203
204 /**
205 * Get a list of Angular modules that should be loaded on the given
206 * base-page.
207 *
208 * @param string $basePage
209 * The name of the base-page for which we want a list of moudles.
210 * @return array
211 * List of Angular modules.
212 * Ex: array('crmMailing', 'crmUi', 'crmUtil', 'ngRoute').
213 */
214 public function resolveDefaultModules($basePage) {
215 $modules = $this->getModules();
216 $result = [];
217 foreach ($modules as $moduleName => $module) {
218 if (in_array($basePage, $module['basePages']) || in_array('*', $module['basePages'])) {
219 $result[] = $moduleName;
220 }
221 }
222 return $result;
223 }
224
225 /**
226 * Convert any globs in an Angular module to file names.
227 *
228 * @param array $modules
229 * List of Angular modules.
230 * @return array
231 * Updated list of Angular modules
232 */
233 protected function resolvePatterns($modules) {
234 $newModules = [];
235
236 foreach ($modules as $moduleKey => $module) {
237 foreach (['js', 'css', 'partials'] as $fileset) {
238 if (!isset($module[$fileset])) {
239 continue;
240 }
241 $module[$fileset] = $this->res->glob($module['ext'], $module[$fileset]);
242 }
243 $newModules[$moduleKey] = $module;
244 }
245
246 return $newModules;
247 }
248
249 /**
250 * Get the partial HTML documents for a module (unfiltered).
251 *
252 * @param string $name
253 * Angular module name.
254 * @return array
255 * Array(string $extFilePath => string $html)
256 * @throws \Exception
257 * Invalid partials configuration.
258 */
259 public function getRawPartials($name) {
260 $module = $this->getModule($name);
261 $result = !empty($module['partialsCallback'])
262 ? \Civi\Core\Resolver::singleton()->call($module['partialsCallback'], [$name, $module])
263 : [];
264 if (isset($module['partials'])) {
265 foreach ($module['partials'] as $partialDir) {
266 $partialDir = $this->res->getPath($module['ext']) . '/' . $partialDir;
267 $files = \CRM_Utils_File::findFiles($partialDir, '*.html', TRUE);
268 foreach ($files as $file) {
269 $filename = '~/' . $name . '/' . $file;
270 $result[$filename] = file_get_contents($partialDir . '/' . $file);
271 }
272 }
273 return $result;
274 }
275 return $result;
276 }
277
278 /**
279 * Get the partial HTML documents for a module.
280 *
281 * @param string $name
282 * Angular module name.
283 * @return array
284 * Array(string $extFilePath => string $html)
285 * @throws \Exception
286 * Invalid partials configuration.
287 */
288 public function getPartials($name) {
289 $cacheKey = "angular-partials_$name";
290 $cacheValue = $this->cache->get($cacheKey);
291 if ($cacheValue === NULL) {
292 $cacheValue = ChangeSet::applyResourceFilters($this->getChangeSets(), 'partials', $this->getRawPartials($name));
293 $this->cache->set($cacheKey, $cacheValue);
294 }
295 return $cacheValue;
296 }
297
298 /**
299 * Get list of translated strings for a module.
300 *
301 * @param string $name
302 * Angular module name.
303 * @return array
304 * Translated strings: array(string $orig => string $translated).
305 */
306 public function getTranslatedStrings($name) {
307 $module = $this->getModule($name);
308 $result = [];
309 $strings = $this->getStrings($name);
310 foreach ($strings as $string) {
311 // TODO: should we pass translation domain based on $module[ext] or $module[tsDomain]?
312 // It doesn't look like client side really supports the domain right now...
313 $translated = ts($string, [
314 'domain' => [$module['ext'], NULL],
315 ]);
316 if ($translated != $string) {
317 $result[$string] = $translated;
318 }
319 }
320 return $result;
321 }
322
323 /**
324 * Get list of translatable strings for a module.
325 *
326 * @param string $name
327 * Angular module name.
328 * @return array
329 * Translatable strings.
330 */
331 public function getStrings($name) {
332 $module = $this->getModule($name);
333 $result = [];
334 if (isset($module['js'])) {
335 foreach ($module['js'] as $file) {
336 $strings = $this->res->getStrings()->get(
337 $module['ext'],
338 $this->res->getPath($module['ext'], $file),
339 'text/javascript'
340 );
341 $result = array_unique(array_merge($result, $strings));
342 }
343 }
344 $partials = $this->getPartials($name);
345 foreach ($partials as $partial) {
346 $result = array_unique(array_merge($result, \CRM_Utils_JS::parseStrings($partial)));
347 }
348 return $result;
349 }
350
351 /**
352 * Get resources for one or more modules.
353 *
354 * @param string|array $moduleNames
355 * List of module names.
356 * @param string $resType
357 * Type of resource ('js', 'css', 'settings').
358 * @param string $refType
359 * Type of reference to the resource ('cacheUrl', 'rawUrl', 'path', 'settings').
360 * @return array
361 * List of URLs or paths.
362 * @throws \CRM_Core_Exception
363 */
364 public function getResources($moduleNames, $resType, $refType) {
365 $result = [];
366 $moduleNames = (array) $moduleNames;
367 foreach ($moduleNames as $moduleName) {
368 $module = $this->getModule($moduleName);
369 if (isset($module[$resType])) {
370 foreach ($module[$resType] as $file) {
371 $refTypeSuffix = '';
372 if (is_string($file) && preg_match(';^(assetBuilder|ext)://;', $file)) {
373 $refTypeSuffix = '-' . parse_url($file, PHP_URL_SCHEME);
374 }
375
376 switch ($refType . $refTypeSuffix) {
377 case 'path':
378 $result[] = $this->res->getPath($module['ext'], $file);
379 break;
380
381 case 'rawUrl':
382 $result[] = $this->res->getUrl($module['ext'], $file);
383 break;
384
385 case 'cacheUrl':
386 $result[] = $this->res->getUrl($module['ext'], $file, TRUE);
387 break;
388
389 case 'path-assetBuilder':
390 $assetName = parse_url($file, PHP_URL_HOST) . parse_url($file, PHP_URL_PATH);
391 $assetParams = [];
392 parse_str('' . parse_url($file, PHP_URL_QUERY), $assetParams);
393 $result[] = \Civi::service('asset_builder')->getPath($assetName, $assetParams);
394 break;
395
396 case 'rawUrl-assetBuilder':
397 case 'cacheUrl-assetBuilder':
398 $assetName = parse_url($file, PHP_URL_HOST) . parse_url($file, PHP_URL_PATH);
399 $assetParams = [];
400 parse_str('' . parse_url($file, PHP_URL_QUERY), $assetParams);
401 $result[] = \Civi::service('asset_builder')->getUrl($assetName, $assetParams);
402 break;
403
404 case 'path-ext':
405 $result[] = $this->res->getPath(parse_url($file, PHP_URL_HOST), ltrim(parse_url($file, PHP_URL_PATH), '/'));
406 break;
407
408 case 'rawUrl-ext':
409 $result[] = $this->res->getUrl(parse_url($file, PHP_URL_HOST), ltrim(parse_url($file, PHP_URL_PATH), '/'));
410 break;
411
412 case 'cacheUrl-ext':
413 $result[] = $this->res->getUrl(parse_url($file, PHP_URL_HOST), ltrim(parse_url($file, PHP_URL_PATH), '/'), TRUE);
414 break;
415
416 case 'settings':
417 case 'settingsFactory':
418 case 'requires':
419 case 'permissions':
420 case 'bundles':
421 if (!empty($module[$resType])) {
422 $result[$moduleName] = $module[$resType];
423 }
424 break;
425
426 default:
427 throw new \CRM_Core_Exception("Unrecognized resource format");
428 }
429 }
430 }
431 }
432
433 return ChangeSet::applyResourceFilters($this->getChangeSets(), $resType, $result);
434 }
435
436 /**
437 * @return array
438 * Array(string $name => ChangeSet $changeSet).
439 */
440 public function getChangeSets() {
441 if ($this->changeSets === NULL) {
442 $this->changeSets = [];
443 \CRM_Utils_Hook::alterAngular($this);
444 }
445 return $this->changeSets;
446 }
447
448 /**
449 * @param ChangeSet $changeSet
450 * @return \Civi\Angular\Manager
451 */
452 public function add($changeSet) {
453 $this->changeSets[$changeSet->getName()] = $changeSet;
454 return $this;
455 }
456
457 }