Globally reset angular hashPrefix
[civicrm-core.git] / Civi / Angular / AngularLoader.php
1 <?php
2 namespace Civi\Angular;
3
4 /**
5 * The AngularLoader loads any JS/CSS/JSON resources
6 * required for setting up AngularJS.
7 *
8 * The AngularLoader stops short of bootstrapping AngularJS. You may
9 * need to `<div ng-app="..."></div>` or `angular.bootstrap(...)`.
10 *
11 * ```
12 * $loader = new AngularLoader();
13 * $loader->setPageName('civicrm/case/a');
14 * $loader->setModules(array('crmApp'));
15 * $loader->load();
16 * ```
17 *
18 * @link https://docs.angularjs.org/guide/bootstrap
19 */
20 class AngularLoader {
21
22 /**
23 * The weight to assign to any Angular JS module files.
24 */
25 const DEFAULT_MODULE_WEIGHT = 200;
26
27 /**
28 * The resource manager.
29 *
30 * Do not use publicly. Inject your own copy!
31 *
32 * @var \CRM_Core_Resources
33 */
34 protected $res;
35
36 /**
37 * The Angular module manager.
38 *
39 * Do not use publicly. Inject your own copy!
40 *
41 * @var \Civi\Angular\Manager
42 */
43 protected $angular;
44
45 /**
46 * The region of the page into which JavaScript will be loaded.
47 *
48 * @var string
49 */
50 protected $region;
51
52 /**
53 * @var string
54 * Ex: 'civicrm/a'.
55 */
56 protected $pageName;
57
58 /**
59 * @var array
60 * A list of modules to load.
61 */
62 protected $modules;
63
64 /**
65 * @var array|null
66 */
67 protected $crmApp = NULL;
68
69 /**
70 * AngularLoader constructor.
71 */
72 public function __construct() {
73 $this->res = \CRM_Core_Resources::singleton();
74 $this->angular = \Civi::service('angular');
75 $this->region = \CRM_Utils_Request::retrieve('snippet', 'String') ? 'ajax-snippet' : 'html-header';
76 $this->pageName = \CRM_Utils_System::currentPath();
77 $this->modules = [];
78 }
79
80 /**
81 * Calling this method from outside this class is deprecated.
82 *
83 * The correct way to use this class is as a service, which will load automatically. E.g.:
84 *
85 * ```
86 * Civi::service('angularjs.loader')
87 * ->addModules('moduleFoo')
88 * ->useApp(); // Optional, if Civi's routing is desired (full-page apps only)
89 * ```
90 *
91 * @internal
92 * @deprecated
93 * @return AngularLoader
94 */
95 public function load() {
96 $angular = $this->getAngular();
97 $res = $this->getRes();
98
99 if ($this->crmApp !== NULL) {
100 $this->addModules($this->crmApp['modules']);
101
102 $this->res->addSetting([
103 'crmApp' => [
104 'defaultRoute' => $this->crmApp['defaultRoute'],
105 ],
106 ]);
107
108 // If trying to load an Angular page via AJAX, the route must be passed as a
109 // URL parameter, since the server doesn't receive information about
110 // URL fragments (i.e, what comes after the #).
111 $this->res->addSetting([
112 'angularRoute' => $this->crmApp['activeRoute'],
113 ]);
114 }
115
116 $moduleNames = $this->findActiveModules();
117 if (!$this->isAllModules($moduleNames)) {
118 $assetParams = ['modules' => implode(',', $moduleNames)];
119 }
120 else {
121 // The module list will be "all modules that the user can see".
122 $assetParams = ['nonce' => md5(implode(',', $moduleNames))];
123 }
124
125 $res->addSettingsFactory(function () use (&$moduleNames, $angular, $res, $assetParams) {
126 // Merge static settings with the results of settingsFactory functions
127 $settingsByModule = $angular->getResources($moduleNames, 'settings', 'settings');
128 foreach ($angular->getResources($moduleNames, 'settingsFactory', 'settingsFactory') as $moduleName => $factory) {
129 $settingsByModule[$moduleName] = array_merge($settingsByModule[$moduleName] ?? [], $factory());
130 }
131 // Add clientside permissions
132 $permissions = [];
133 $toCheck = $angular->getResources($moduleNames, 'permissions', 'permissions');
134 foreach ($toCheck as $perms) {
135 foreach ((array) $perms as $perm) {
136 if (!isset($permissions[$perm])) {
137 $permissions[$perm] = \CRM_Core_Permission::check($perm);
138 }
139 }
140 }
141 // TODO optimization; client-side caching
142 return array_merge($settingsByModule, ['permissions' => $permissions], [
143 'resourceUrls' => \CRM_Extension_System::singleton()->getMapper()->getActiveModuleUrls(),
144 'angular' => [
145 'modules' => $moduleNames,
146 'requires' => $angular->getResources($moduleNames, 'requires', 'requires'),
147 'cacheCode' => $res->getCacheCode(),
148 'bundleUrl' => \Civi::service('asset_builder')->getUrl('angular-modules.json', $assetParams),
149 ],
150 ]);
151 });
152
153 $res->addScriptFile('civicrm', 'bower_components/angular/angular.min.js', 100, $this->getRegion(), FALSE);
154
155 $headOffset = 0;
156 $config = \CRM_Core_Config::singleton();
157 if ($config->debug) {
158 $res->addScriptFile('civicrm', 'ang/resetLocationProviderHashPrefix.js', 101, $this->getRegion(), FALSE);
159 foreach ($moduleNames as $moduleName) {
160 foreach ($this->angular->getResources($moduleName, 'css', 'cacheUrl') as $url) {
161 $res->addStyleUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->getRegion());
162 }
163 foreach ($this->angular->getResources($moduleName, 'js', 'cacheUrl') as $url) {
164 $res->addScriptUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->getRegion());
165 // addScriptUrl() bypasses the normal string-localization of addScriptFile(),
166 // but that's OK because all Angular strings (JS+HTML) will load via crmResource.
167 }
168 }
169 }
170 else {
171 // Note: addScriptUrl() bypasses the normal string-localization of addScriptFile(),
172 // but that's OK because all Angular strings (JS+HTML) will load via crmResource.
173 // $aggScriptUrl = \CRM_Utils_System::url('civicrm/ajax/angular-modules', 'format=js&r=' . $res->getCacheCode(), FALSE, NULL, FALSE);
174 $aggScriptUrl = \Civi::service('asset_builder')->getUrl('angular-modules.js', $assetParams);
175 $res->addScriptUrl($aggScriptUrl, 120, $this->getRegion());
176
177 // FIXME: The following CSS aggregator doesn't currently handle path-adjustments - which can break icons.
178 //$aggStyleUrl = \CRM_Utils_System::url('civicrm/ajax/angular-modules', 'format=css&r=' . $res->getCacheCode(), FALSE, NULL, FALSE);
179 //$aggStyleUrl = \Civi::service('asset_builder')->getUrl('angular-modules.css', $assetParams);
180 //$res->addStyleUrl($aggStyleUrl, 120, $this->getRegion());
181
182 foreach ($this->angular->getResources($moduleNames, 'css', 'cacheUrl') as $url) {
183 $res->addStyleUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->getRegion());
184 }
185 }
186 // Add bundles
187 foreach ($this->angular->getResources($moduleNames, 'bundles', 'bundles') as $bundles) {
188 $res->addBundle($bundles);
189 }
190
191 return $this;
192 }
193
194 /**
195 * Use Civi's generic "application" module.
196 *
197 * This is suitable for use on a basic, standalone Angular page
198 * like `civicrm/a`. (If you need to integrate Angular with pre-existing,
199 * non-Angular pages... then this probably won't help.)
200 *
201 * The Angular bootstrap process requires an HTML directive like
202 * `<div ng-app="foo">`.
203 *
204 * Calling useApp() will replace the page's main body with the
205 * `<div ng-app="crmApp">...</div>` and apply some configuration options
206 * for the `crmApp` module.
207 *
208 * @param array $settings
209 * A list of settings. Accepted values:
210 * - activeRoute: string, the route to open up immediately
211 * Ex: '/case/list'
212 * - defaultRoute: string, use this to redirect the default route (`/`) to another page
213 * Ex: '/case/list'
214 * - region: string, the place on the page where we should insert the angular app
215 * Ex: 'page-body'
216 * @return AngularLoader
217 * @link https://code.angularjs.org/1.5.11/docs/guide/bootstrap
218 */
219 public function useApp($settings = []) {
220 $defaults = [
221 'modules' => ['crmApp'],
222 'activeRoute' => NULL,
223 'defaultRoute' => NULL,
224 'region' => 'page-body',
225 'file' => 'Civi/Angular/Page/Main.tpl',
226 ];
227 $this->crmApp = array_merge($defaults, $settings);
228 $region = \CRM_Core_Region::instance($this->crmApp['region']);
229 $region->update('default', ['disabled' => TRUE]);
230 $region->add(['template' => $this->crmApp['file'], 'weight' => 0]);
231 return $this;
232 }
233
234 /**
235 * Get a list of all Angular modules which should be activated on this
236 * page.
237 *
238 * @return array
239 * List of module names.
240 * Ex: array('angularFileUpload', 'crmUi', 'crmUtil').
241 */
242 public function findActiveModules() {
243 return $this->angular->resolveDependencies(array_merge(
244 $this->getModules(),
245 $this->angular->resolveDefaultModules($this->getPageName())
246 ));
247 }
248
249 /**
250 * @param $moduleNames
251 * @return int
252 */
253 private function isAllModules($moduleNames) {
254 $allModuleNames = array_keys($this->angular->getModules());
255 return count(array_diff($allModuleNames, $moduleNames)) === 0;
256 }
257
258 /**
259 * @return \CRM_Core_Resources
260 */
261 public function getRes() {
262 return $this->res;
263 }
264
265 /**
266 * @param \CRM_Core_Resources $res
267 * @return AngularLoader
268 */
269 public function setRes($res) {
270 $this->res = $res;
271 return $this;
272 }
273
274 /**
275 * @return \Civi\Angular\Manager
276 */
277 public function getAngular() {
278 return $this->angular;
279 }
280
281 /**
282 * @param \Civi\Angular\Manager $angular
283 * @return AngularLoader
284 */
285 public function setAngular($angular) {
286 $this->angular = $angular;
287 return $this;
288 }
289
290 /**
291 * @return string
292 */
293 public function getRegion() {
294 return $this->region;
295 }
296
297 /**
298 * @param string $region
299 * @return AngularLoader
300 */
301 public function setRegion($region) {
302 $this->region = $region;
303 return $this;
304 }
305
306 /**
307 * @return string
308 * Ex: 'civicrm/a'.
309 */
310 public function getPageName() {
311 return $this->pageName;
312 }
313
314 /**
315 * @param string $pageName
316 * Ex: 'civicrm/a'.
317 * @return AngularLoader
318 */
319 public function setPageName($pageName) {
320 $this->pageName = $pageName;
321 return $this;
322 }
323
324 /**
325 * @param array|string $modules
326 * @return AngularLoader
327 */
328 public function addModules($modules) {
329 $modules = (array) $modules;
330 $this->modules = array_unique(array_merge($this->modules, $modules));
331 return $this;
332 }
333
334 /**
335 * @return array
336 */
337 public function getModules() {
338 return $this->modules;
339 }
340
341 /**
342 * Replace all previously set modules.
343 *
344 * Use with caution, as it can cause conflicts with other extensions who have added modules.
345 *
346 * @param array $modules
347 * @return AngularLoader
348 */
349 public function setModules($modules) {
350 $this->modules = $modules;
351 return $this;
352 }
353
354 /**
355 * @param \Civi\Core\Event\GenericHookEvent $e
356 */
357 public function onRegionRender($e) {
358 if ($e->region->_name === $this->region && ($this->modules || $this->crmApp)) {
359 $this->load();
360 $this->res->addScriptFile('civicrm', 'js/crm-angularjs-loader.js', 200, $this->getRegion(), FALSE);
361 }
362 }
363
364 }