Merge pull request #19049 from colemanw/crmExampleGone
[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['crmResource'] = include "$civicrm_root/ang/crmResource.ang.php";
109 $angularModules['crmRouteBinder'] = include "$civicrm_root/ang/crmRouteBinder.ang.php";
110 $angularModules['crmUi'] = include "$civicrm_root/ang/crmUi.ang.php";
111 $angularModules['crmUtil'] = include "$civicrm_root/ang/crmUtil.ang.php";
112 $angularModules['dialogService'] = include "$civicrm_root/ang/dialogService.ang.php";
113 $angularModules['jsonFormatter'] = include "$civicrm_root/ang/jsonFormatter.ang.php";
114 $angularModules['ngRoute'] = include "$civicrm_root/ang/ngRoute.ang.php";
115 $angularModules['ngSanitize'] = include "$civicrm_root/ang/ngSanitize.ang.php";
116 $angularModules['ui.utils'] = include "$civicrm_root/ang/ui.utils.ang.php";
117 $angularModules['ui.bootstrap'] = include "$civicrm_root/ang/ui.bootstrap.ang.php";
118 $angularModules['ui.sortable'] = include "$civicrm_root/ang/ui.sortable.ang.php";
119 $angularModules['unsavedChanges'] = include "$civicrm_root/ang/unsavedChanges.ang.php";
120 $angularModules['statuspage'] = include "$civicrm_root/ang/crmStatusPage.ang.php";
121 $angularModules['exportui'] = include "$civicrm_root/ang/exportui.ang.php";
122 $angularModules['api4Explorer'] = include "$civicrm_root/ang/api4Explorer.ang.php";
123 $angularModules['api4'] = include "$civicrm_root/ang/api4.ang.php";
124 $angularModules['crmDashboard'] = include "$civicrm_root/ang/crmDashboard.ang.php";
125 $angularModules['crmD3'] = include "$civicrm_root/ang/crmD3.ang.php";
126
127 foreach (\CRM_Core_Component::getEnabledComponents() as $component) {
128 $angularModules = array_merge($angularModules, $component->getAngularModules());
129 }
130 \CRM_Utils_Hook::angularModules($angularModules);
131 foreach ($angularModules as $module => $info) {
132 // Merge in defaults
133 $angularModules[$module] += ['basePages' => ['civicrm/a']];
134 // Validate settingsFactory callables
135 if (isset($info['settingsFactory'])) {
136 // To keep the cache small, we want `settingsFactory` to contain the string names of class & function, not an object
137 if (!is_array($info['settingsFactory']) && !is_string($info['settingsFactory'])) {
138 throw new \CRM_Core_Exception($module . ' settingsFactory must be a callable array or string');
139 }
140 // To keep the cache small, convert full object to just the class name
141 if (is_array($info['settingsFactory']) && is_object($info['settingsFactory'][0])) {
142 $angularModules[$module]['settingsFactory'][0] = get_class($info['settingsFactory'][0]);
143 }
144 }
145 }
146 $this->modules = $this->resolvePatterns($angularModules);
147 }
148
149 return $this->modules;
150 }
151
152 /**
153 * Get the descriptor for an Angular module.
154 *
155 * @param string $name
156 * Module name.
157 * @return array
158 * Details about the module:
159 * - ext: string, the name of the Civi extension which defines the module
160 * - js: array(string $relativeFilePath).
161 * - css: array(string $relativeFilePath).
162 * - partials: array(string $relativeFilePath).
163 * @throws \Exception
164 */
165 public function getModule($name) {
166 $modules = $this->getModules();
167 if (!isset($modules[$name])) {
168 throw new \Exception("Unrecognized Angular module");
169 }
170 return $modules[$name];
171 }
172
173 /**
174 * Resolve a full list of Angular dependencies.
175 *
176 * @param array $names
177 * List of Angular modules.
178 * Ex: array('crmMailing').
179 * @return array
180 * List of Angular modules, include all dependencies.
181 * Ex: array('crmMailing', 'crmUi', 'crmUtil', 'ngRoute').
182 */
183 public function resolveDependencies($names) {
184 $allModules = $this->getModules();
185 $visited = [];
186 $result = $names;
187 while (($missingModules = array_diff($result, array_keys($visited))) && !empty($missingModules)) {
188 foreach ($missingModules as $module) {
189 $visited[$module] = 1;
190 if (!isset($allModules[$module])) {
191 \Civi::log()->warning('Unrecognized Angular module {name}. Please ensure that all Angular modules are declared.', [
192 'name' => $module,
193 'civi.tag' => 'deprecated',
194 ]);
195 }
196 elseif (isset($allModules[$module]['requires'])) {
197 $result = array_unique(array_merge($result, $allModules[$module]['requires']));
198 }
199 }
200 }
201 sort($result);
202 return $result;
203 }
204
205 /**
206 * Get a list of Angular modules that should be loaded on the given
207 * base-page.
208 *
209 * @param string $basePage
210 * The name of the base-page for which we want a list of moudles.
211 * @return array
212 * List of Angular modules.
213 * Ex: array('crmMailing', 'crmUi', 'crmUtil', 'ngRoute').
214 */
215 public function resolveDefaultModules($basePage) {
216 $modules = $this->getModules();
217 $result = [];
218 foreach ($modules as $moduleName => $module) {
219 if (in_array($basePage, $module['basePages']) || in_array('*', $module['basePages'])) {
220 $result[] = $moduleName;
221 }
222 }
223 return $result;
224 }
225
226 /**
227 * Convert any globs in an Angular module to file names.
228 *
229 * @param array $modules
230 * List of Angular modules.
231 * @return array
232 * Updated list of Angular modules
233 */
234 protected function resolvePatterns($modules) {
235 $newModules = [];
236
237 foreach ($modules as $moduleKey => $module) {
238 foreach (['js', 'css', 'partials'] as $fileset) {
239 if (!isset($module[$fileset])) {
240 continue;
241 }
242 $module[$fileset] = $this->res->glob($module['ext'], $module[$fileset]);
243 }
244 $newModules[$moduleKey] = $module;
245 }
246
247 return $newModules;
248 }
249
250 /**
251 * Get the partial HTML documents for a module (unfiltered).
252 *
253 * @param string $name
254 * Angular module name.
255 * @return array
256 * Array(string $extFilePath => string $html)
257 * @throws \Exception
258 * Invalid partials configuration.
259 */
260 public function getRawPartials($name) {
261 $module = $this->getModule($name);
262 $result = !empty($module['partialsCallback'])
263 ? \Civi\Core\Resolver::singleton()->call($module['partialsCallback'], [$name, $module])
264 : [];
265 if (isset($module['partials'])) {
266 foreach ($module['partials'] as $partialDir) {
267 $partialDir = $this->res->getPath($module['ext']) . '/' . $partialDir;
268 $files = \CRM_Utils_File::findFiles($partialDir, '*.html', TRUE);
269 foreach ($files as $file) {
270 $filename = '~/' . $name . '/' . $file;
271 $result[$filename] = file_get_contents($partialDir . '/' . $file);
272 }
273 }
274 return $result;
275 }
276 return $result;
277 }
278
279 /**
280 * Get the partial HTML documents for a module.
281 *
282 * @param string $name
283 * Angular module name.
284 * @return array
285 * Array(string $extFilePath => string $html)
286 * @throws \Exception
287 * Invalid partials configuration.
288 */
289 public function getPartials($name) {
290 $cacheKey = "angular-partials_$name";
291 $cacheValue = $this->cache->get($cacheKey);
292 if ($cacheValue === NULL) {
293 $cacheValue = ChangeSet::applyResourceFilters($this->getChangeSets(), 'partials', $this->getRawPartials($name));
294 $this->cache->set($cacheKey, $cacheValue);
295 }
296 return $cacheValue;
297 }
298
299 /**
300 * Get list of translated strings for a module.
301 *
302 * @param string $name
303 * Angular module name.
304 * @return array
305 * Translated strings: array(string $orig => string $translated).
306 */
307 public function getTranslatedStrings($name) {
308 $module = $this->getModule($name);
309 $result = [];
310 $strings = $this->getStrings($name);
311 foreach ($strings as $string) {
312 // TODO: should we pass translation domain based on $module[ext] or $module[tsDomain]?
313 // It doesn't look like client side really supports the domain right now...
314 $translated = ts($string, [
315 'domain' => [$module['ext'], NULL],
316 ]);
317 if ($translated != $string) {
318 $result[$string] = $translated;
319 }
320 }
321 return $result;
322 }
323
324 /**
325 * Get list of translatable strings for a module.
326 *
327 * @param string $name
328 * Angular module name.
329 * @return array
330 * Translatable strings.
331 */
332 public function getStrings($name) {
333 $module = $this->getModule($name);
334 $result = [];
335 if (isset($module['js'])) {
336 foreach ($module['js'] as $file) {
337 $strings = $this->res->getStrings()->get(
338 $module['ext'],
339 $this->res->getPath($module['ext'], $file),
340 'text/javascript'
341 );
342 $result = array_unique(array_merge($result, $strings));
343 }
344 }
345 $partials = $this->getPartials($name);
346 foreach ($partials as $partial) {
347 $result = array_unique(array_merge($result, \CRM_Utils_JS::parseStrings($partial)));
348 }
349 return $result;
350 }
351
352 /**
353 * Get resources for one or more modules.
354 *
355 * @param string|array $moduleNames
356 * List of module names.
357 * @param string $resType
358 * Type of resource ('js', 'css', 'settings').
359 * @param string $refType
360 * Type of reference to the resource ('cacheUrl', 'rawUrl', 'path', 'settings').
361 * @return array
362 * List of URLs or paths.
363 * @throws \CRM_Core_Exception
364 */
365 public function getResources($moduleNames, $resType, $refType) {
366 $result = [];
367 $moduleNames = (array) $moduleNames;
368 foreach ($moduleNames as $moduleName) {
369 $module = $this->getModule($moduleName);
370 if (isset($module[$resType])) {
371 foreach ($module[$resType] as $file) {
372 $refTypeSuffix = '';
373 if (is_string($file) && preg_match(';^(assetBuilder|ext)://;', $file)) {
374 $refTypeSuffix = '-' . parse_url($file, PHP_URL_SCHEME);
375 }
376
377 switch ($refType . $refTypeSuffix) {
378 case 'path':
379 $result[] = $this->res->getPath($module['ext'], $file);
380 break;
381
382 case 'rawUrl':
383 $result[] = $this->res->getUrl($module['ext'], $file);
384 break;
385
386 case 'cacheUrl':
387 $result[] = $this->res->getUrl($module['ext'], $file, TRUE);
388 break;
389
390 case 'path-assetBuilder':
391 $assetName = parse_url($file, PHP_URL_HOST) . parse_url($file, PHP_URL_PATH);
392 $assetParams = [];
393 parse_str('' . parse_url($file, PHP_URL_QUERY), $assetParams);
394 $result[] = \Civi::service('asset_builder')->getPath($assetName, $assetParams);
395 break;
396
397 case 'rawUrl-assetBuilder':
398 case 'cacheUrl-assetBuilder':
399 $assetName = parse_url($file, PHP_URL_HOST) . parse_url($file, PHP_URL_PATH);
400 $assetParams = [];
401 parse_str('' . parse_url($file, PHP_URL_QUERY), $assetParams);
402 $result[] = \Civi::service('asset_builder')->getUrl($assetName, $assetParams);
403 break;
404
405 case 'path-ext':
406 $result[] = $this->res->getPath(parse_url($file, PHP_URL_HOST), ltrim(parse_url($file, PHP_URL_PATH), '/'));
407 break;
408
409 case 'rawUrl-ext':
410 $result[] = $this->res->getUrl(parse_url($file, PHP_URL_HOST), ltrim(parse_url($file, PHP_URL_PATH), '/'));
411 break;
412
413 case 'cacheUrl-ext':
414 $result[] = $this->res->getUrl(parse_url($file, PHP_URL_HOST), ltrim(parse_url($file, PHP_URL_PATH), '/'), TRUE);
415 break;
416
417 case 'settings':
418 case 'settingsFactory':
419 case 'requires':
420 case 'permissions':
421 case 'bundles':
422 if (!empty($module[$resType])) {
423 $result[$moduleName] = $module[$resType];
424 }
425 break;
426
427 default:
428 throw new \CRM_Core_Exception("Unrecognized resource format");
429 }
430 }
431 }
432 }
433
434 return ChangeSet::applyResourceFilters($this->getChangeSets(), $resType, $result);
435 }
436
437 /**
438 * @return array
439 * Array(string $name => ChangeSet $changeSet).
440 */
441 public function getChangeSets() {
442 if ($this->changeSets === NULL) {
443 $this->changeSets = [];
444 \CRM_Utils_Hook::alterAngular($this);
445 }
446 return $this->changeSets;
447 }
448
449 /**
450 * @param ChangeSet $changeSet
451 * @return \Civi\Angular\Manager
452 */
453 public function add($changeSet) {
454 $this->changeSets[$changeSet->getName()] = $changeSet;
455 return $this;
456 }
457
458 }