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