Completed
Push — master ( cca51e...3afa85 )
by Nazar
04:12
created

Includes   D

Complexity

Total Complexity 126

Size/Duplication

Total Lines 833
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 126
c 4
b 0
f 0
lcom 1
cbo 10
dl 0
loc 833
rs 4.4444

32 Methods

Rating   Name   Duplication   Size   Complexity  
A init_includes() 0 11 1
A html() 0 3 1
C html_internal() 0 27 7
A js() 0 3 1
C js_internal() 0 26 7
A css() 0 3 1
C css_internal() 0 28 7
A config() 0 3 1
A config_internal() 0 16 2
B add_includes_on_page() 0 40 5
A webcomponents_polyfill() 0 17 4
B add_system_configs() 0 29 3
C get_includes_for_page_with_compression() 0 31 8
B get_includes_for_page_without_compression() 0 23 6
A get_includes_prepare() 0 23 3
B get_includes_is_dependency() 0 12 6
A absolute_path_to_relative() 0 3 1
A add_versions_hash() 0 12 3
C add_includes_on_page_manually_added() 0 22 7
B get_includes_list() 0 23 4
A get_includes_list_add_includes() 0 5 1
A get_includes_list_add_includes_internal() 0 3 2
A rebuild_cache() 0 17 2
A ie_edge() 0 9 2
A create_cached_includes_files() 0 9 2
B create_cached_includes_files_process_files() 0 37 6
B includes_dependencies_and_map() 0 47 4
B process_meta() 0 41 6
A process_map() 0 6 2
B process_map_internal() 0 27 5
C normalize_dependencies() 0 49 12
A clean_includes_arrays_without_files() 0 11 4

How to fix   Complexity   

Complex Class

Complex classes like Includes often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Includes, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @package   CleverStyle CMS
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2014-2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Page;
9
use
10
	cs\App,
11
	cs\Core,
12
	cs\Config,
13
	cs\Event,
14
	cs\Language,
15
	cs\Request,
16
	cs\User,
17
	h,
18
	cs\Page\Includes\RequireJS;
19
20
/**
21
 * Includes management for `cs\Page` class
22
 *
23
 * @property string $Title
24
 * @property string $Description
25
 * @property string $canonical_url
26
 * @property string $Head
27
 * @property string $post_Body
28
 * @property string $theme
29
 */
30
trait Includes {
31
	use
32
		RequireJS;
33
	/**
34
	 * @var array[]
35
	 */
36
	protected $core_html;
37
	/**
38
	 * @var array[]
39
	 */
40
	protected $core_js;
41
	/**
42
	 * @var array[]
43
	 */
44
	protected $core_css;
45
	/**
46
	 * @var string
47
	 */
48
	protected $core_config;
49
	/**
50
	 * @var array[]
51
	 */
52
	protected $html;
53
	/**
54
	 * @var array[]
55
	 */
56
	protected $js;
57
	/**
58
	 * @var array[]
59
	 */
60
	protected $css;
61
	/**
62
	 * @var string
63
	 */
64
	protected $config;
65
	/**
66
	 * Base name is used as prefix when creating CSS/JS/HTML cache files in order to avoid collisions when having several themes and languages
67
	 * @var string
68
	 */
69
	protected $pcache_basename;
70
	protected function init_includes () {
71
		$this->core_html       = [0 => [], 1 => []];
72
		$this->core_js         = [0 => [], 1 => []];
73
		$this->core_css        = [0 => [], 1 => []];
74
		$this->core_config     = '';
75
		$this->html            = [0 => [], 1 => []];
76
		$this->js              = [0 => [], 1 => []];
77
		$this->css             = [0 => [], 1 => []];
78
		$this->config          = '';
79
		$this->pcache_basename = '';
80
	}
81
	/**
82
	 * Including of Web Components
83
	 *
84
	 * @param string|string[] $add  Path to including file, or code
85
	 * @param string          $mode Can be <b>file</b> or <b>code</b>
86
	 *
87
	 * @return \cs\Page
88
	 */
89
	function html ($add, $mode = 'file') {
90
		return $this->html_internal($add, $mode);
91
	}
92
	/**
93
	 * @param string|string[] $add
94
	 * @param string          $mode
95
	 * @param bool            $core
96
	 *
97
	 * @return \cs\Page
98
	 */
99
	protected function html_internal ($add, $mode = 'file', $core = false) {
100
		if (!$add) {
101
			return $this;
102
		}
103
		if (is_array($add)) {
104
			foreach (array_filter($add) as $script) {
105
				$this->html_internal($script, $mode, $core);
106
			}
107
		} else {
108
			if ($core) {
109
				$html = &$this->core_html;
110
			} else {
111
				$html = &$this->html;
112
			}
113
			if ($mode == 'file') {
114
				$html[0][] = h::link(
115
					[
116
						'href' => $add,
117
						'rel'  => 'import'
118
					]
119
				);
120
			} elseif ($mode == 'code') {
121
				$html[1][] = "$add\n";
122
			}
123
		}
124
		return $this;
125
	}
126
	/**
127
	 * Including of JavaScript
128
	 *
129
	 * @param string|string[] $add  Path to including file, or code
130
	 * @param string          $mode Can be <b>file</b> or <b>code</b>
131
	 *
132
	 * @return \cs\Page
133
	 */
134
	function js ($add, $mode = 'file') {
135
		return $this->js_internal($add, $mode);
136
	}
137
	/**
138
	 * @param string|string[] $add
139
	 * @param string          $mode
140
	 * @param bool            $core
141
	 *
142
	 * @return \cs\Page
143
	 */
144
	protected function js_internal ($add, $mode = 'file', $core = false) {
145
		if (!$add) {
146
			return $this;
147
		}
148
		if (is_array($add)) {
149
			foreach (array_filter($add) as $script) {
150
				$this->js_internal($script, $mode, $core);
151
			}
152
		} else {
153
			if ($core) {
154
				$js = &$this->core_js;
155
			} else {
156
				$js = &$this->js;
157
			}
158
			if ($mode == 'file') {
159
				$js[0][] = h::script(
160
					[
161
						'src' => $add
162
					]
163
				);
164
			} elseif ($mode == 'code') {
165
				$js[1][] = "$add\n";
166
			}
167
		}
168
		return $this;
169
	}
170
	/**
171
	 * Including of CSS
172
	 *
173
	 * @param string|string[] $add  Path to including file, or code
174
	 * @param string          $mode Can be <b>file</b> or <b>code</b>
175
	 *
176
	 * @return \cs\Page
177
	 */
178
	function css ($add, $mode = 'file') {
179
		return $this->css_internal($add, $mode);
180
	}
181
	/**
182
	 * @param string|string[] $add
183
	 * @param string          $mode
184
	 * @param bool            $core
185
	 *
186
	 * @return \cs\Page
187
	 */
188
	protected function css_internal ($add, $mode = 'file', $core = false) {
189
		if (!$add) {
190
			return $this;
191
		}
192
		if (is_array($add)) {
193
			foreach (array_filter($add) as $style) {
194
				$this->css_internal($style, $mode, $core);
195
			}
196
		} else {
197
			if ($core) {
198
				$css = &$this->core_css;
199
			} else {
200
				$css = &$this->css;
201
			}
202
			if ($mode == 'file') {
203
				$css[0][] = h::link(
204
					[
205
						'href'           => $add,
206
						'rel'            => 'stylesheet',
207
						'shim-shadowdom' => true
208
					]
209
				);
210
			} elseif ($mode == 'code') {
211
				$css[1][] = "$add\n";
212
			}
213
		}
214
		return $this;
215
	}
216
	/**
217
	 * Add config on page to make it available on frontend
218
	 *
219
	 * @param mixed  $config_structure        Any scalar type or array
220
	 * @param string $target                  Target is property of `window` object where config will be inserted as value, nested properties like `cs.sub.prop`
221
	 *                                        are supported and all nested properties are created on demand. It is recommended to use sub-properties of `cs`
222
	 *
223
	 * @return \cs\Page
224
	 */
225
	function config ($config_structure, $target) {
226
		return $this->config_internal($config_structure, $target);
227
	}
228
	/**
229
	 * @param mixed  $config_structure
230
	 * @param string $target
231
	 * @param bool   $core
232
	 *
233
	 * @return \cs\Page
234
	 */
235
	protected function config_internal ($config_structure, $target, $core = false) {
236
		$config = h::script(
237
			json_encode($config_structure, JSON_UNESCAPED_UNICODE),
238
			[
239
				'target' => $target,
240
				'class'  => 'cs-config',
241
				'type'   => 'application/json'
242
			]
243
		);
244
		if ($core) {
245
			$this->core_config .= $config;
246
		} else {
247
			$this->config .= $config;
248
		}
249
		return $this;
250
	}
251
	/**
252
	 * Getting of HTML, JS and CSS includes
253
	 *
254
	 * @return \cs\Page
255
	 */
256
	protected function add_includes_on_page () {
257
		$Config = Config::instance(true);
258
		if (!$Config) {
259
			return $this;
260
		}
261
		/**
262
		 * Base name for cache files
263
		 */
264
		$this->pcache_basename = "_{$this->theme}_".Language::instance()->clang;
265
		/**
266
		 * Some JS configs required by system
267
		 */
268
		$this->add_system_configs();
269
		// TODO: I hope some day we'll get rid of this sh*t :(
270
		$this->ie_edge();
271
		$Request = Request::instance();
272
		/**
273
		 * If CSS and JavaScript compression enabled
274
		 */
275
		if ($Config->core['cache_compress_js_css'] && !($Request->admin_path && isset($Request->query['debug']))) {
276
			$this->webcomponents_polyfill($Request, true);
277
			$includes = $this->get_includes_for_page_with_compression();
278
		} else {
279
			$this->webcomponents_polyfill($Request, false);
280
			/**
281
			 * Language translation is added explicitly only when compression is disabled, otherwise it will be in compressed JS file
282
			 */
283
			/**
284
			 * @var \cs\Page $this
285
			 */
286
			$this->config_internal(Language::instance(), 'cs.Language', true);
287
			$this->config_internal($this->get_requirejs_paths(), 'requirejs.paths', true);
288
			$includes = $this->get_includes_for_page_without_compression($Config);
289
		}
290
		$this->css_internal($includes['css'], 'file', true);
291
		$this->js_internal($includes['js'], 'file', true);
292
		$this->html_internal($includes['html'], 'file', true);
293
		$this->add_includes_on_page_manually_added($Config);
294
		return $this;
295
	}
296
	/**
297
	 * @param string[] $path
298
	 *
299
	 * @return string[]
300
	 */
301
	protected function absolute_path_to_relative ($path) {
302
		return _substr($path, strlen(DIR) + 1);
303
	}
304
	/**
305
	 * Add JS polyfills for IE/Edge
306
	 */
307
	protected function ie_edge () {
308
		if (preg_match('/Trident|Edge/', Request::instance()->header('user-agent'))) {
309
			$this->js_internal(
310
				get_files_list(DIR."/includes/js/microsoft_sh*t", "/.*\\.js$/i", 'f', "includes/js/microsoft_sh*t", true),
311
				'file',
312
				true
313
			);
314
		}
315
	}
316
	/**
317
	 * Hack: Add WebComponents Polyfill for browsers without native Shadow DOM support
318
	 *
319
	 * @param Request $Request
320
	 * @param bool    $with_compression
321
	 */
322
	protected function webcomponents_polyfill ($Request, $with_compression) {
323
		if ($Request->cookie('shadow_dom') != 1) {
324
			$file = 'includes/js/WebComponents-polyfill/webcomponents-custom.min.js';
325
			if ($with_compression) {
326
				$compressed_file = PUBLIC_CACHE.'/webcomponents.js';
327
				if (!file_exists($compressed_file)) {
328
					$content = file_get_contents(DIR."/$file");
329
					file_put_contents($compressed_file, gzencode($content, 9), LOCK_EX | FILE_BINARY);
330
					file_put_contents("$compressed_file.hash", substr(md5($content), 0, 5));
331
				}
332
				$hash = file_get_contents("$compressed_file.hash");
333
				$this->js_internal("storage/pcache/webcomponents.js?$hash", 'file', true);
334
			} else {
335
				$this->js_internal($file, 'file', true);
336
			}
337
		}
338
	}
339
	protected function add_system_configs () {
340
		$Config         = Config::instance();
341
		$Request        = Request::instance();
342
		$User           = User::instance();
343
		$current_module = $Request->current_module;
344
		$this->config_internal(
345
			[
346
				'base_url'              => $Config->base_url(),
347
				'current_base_url'      => $Config->base_url().'/'.($Request->admin_path ? 'admin/' : '').$current_module,
348
				'public_key'            => Core::instance()->public_key,
349
				'module'                => $current_module,
350
				'in_admin'              => (int)$Request->admin_path,
351
				'is_admin'              => (int)$User->admin(),
352
				'is_user'               => (int)$User->user(),
353
				'is_guest'              => (int)$User->guest(),
354
				'password_min_length'   => (int)$Config->core['password_min_length'],
355
				'password_min_strength' => (int)$Config->core['password_min_strength'],
356
				'debug'                 => (int)DEBUG,
357
				'route'                 => $Request->route,
358
				'route_path'            => $Request->route_path,
359
				'route_ids'             => $Request->route_ids
360
			],
361
			'cs',
362
			true
363
		);
364
		if ($User->admin()) {
365
			$this->config_internal((int)$Config->core['simple_admin_mode'], 'cs.simple_admin_mode', true);
366
		}
367
	}
368
	/**
369
	 * @return array[]
370
	 */
371
	protected function get_includes_for_page_with_compression () {
372
		/**
373
		 * Rebuild cache if necessary
374
		 */
375
		if (!file_exists(PUBLIC_CACHE."/$this->pcache_basename.json")) {
376
			$this->rebuild_cache();
377
		}
378
		list($dependencies, $structure) = file_get_json(PUBLIC_CACHE."/$this->pcache_basename.json");
379
		$system_includes = [
380
			'css'  => ["storage/pcache/$this->pcache_basename.css?{$structure['']['css']}"],
381
			'js'   => ["storage/pcache/$this->pcache_basename.js?{$structure['']['js']}"],
382
			'html' => ["storage/pcache/$this->pcache_basename.html?{$structure['']['html']}"]
383
		];
384
		list($includes, $dependencies_includes, $dependencies, $current_url) = $this->get_includes_prepare($dependencies, '+');
385
		foreach ($structure as $filename_prefix => $hashes) {
386
			if (!$filename_prefix) {
387
				continue;
388
			}
389
			$is_dependency = $this->get_includes_is_dependency($dependencies, $filename_prefix, '+');
390
			if ($is_dependency || mb_strpos($current_url, $filename_prefix) === 0) {
391
				foreach ($hashes as $extension => $hash) {
392
					if ($is_dependency) {
393
						$dependencies_includes[$extension][] = "storage/pcache/$filename_prefix$this->pcache_basename.$extension?$hash";
394
					} else {
395
						$includes[$extension][] = "storage/pcache/$filename_prefix$this->pcache_basename.$extension?$hash";
396
					}
397
				}
398
			}
399
		}
400
		return array_merge_recursive($system_includes, $dependencies_includes, $includes);
401
	}
402
	/**
403
	 * @param Config $Config
404
	 *
405
	 * @return array[]
406
	 */
407
	protected function get_includes_for_page_without_compression ($Config) {
408
		// To determine all dependencies and stuff we need `$Config` object to be already created
409
		if ($Config) {
410
			list($dependencies, $includes_map) = $this->includes_dependencies_and_map();
411
			$system_includes = $includes_map[''];
412
			list($includes, $dependencies_includes, $dependencies, $current_url) = $this->get_includes_prepare($dependencies, '/');
413
			foreach ($includes_map as $url => $local_includes) {
414
				if (!$url) {
415
					continue;
416
				}
417
				$is_dependency = $this->get_includes_is_dependency($dependencies, $url, '/');
418
				if ($is_dependency) {
419
					$dependencies_includes = array_merge_recursive($dependencies_includes, $local_includes);
420
				} elseif (mb_strpos($current_url, $url) === 0) {
421
					$includes = array_merge_recursive($includes, $local_includes);
422
				}
423
			}
424
			$includes = array_merge_recursive($system_includes, $dependencies_includes, $includes);
425
		} else {
426
			$includes = $this->get_includes_list();
427
		}
428
		return $this->add_versions_hash($this->absolute_path_to_relative($includes));
429
	}
430
	/**
431
	 * @param array  $dependencies
432
	 * @param string $separator `+` or `/`
433
	 *
434
	 * @return array
435
	 */
436
	protected function get_includes_prepare ($dependencies, $separator) {
437
		$Request               = Request::instance();
438
		$includes              = [
439
			'css'  => [],
440
			'js'   => [],
441
			'html' => []
442
		];
443
		$dependencies_includes = $includes;
444
		$current_module        = $Request->current_module;
445
		/**
446
		 * Current URL based on controller path (it better represents how page was rendered)
447
		 */
448
		$current_url = array_slice(App::instance()->controller_path, 1);
449
		$current_url = ($Request->admin_path ? "admin$separator" : '')."$current_module$separator".implode($separator, $current_url);
450
		/**
451
		 * Narrow the dependencies to current module only
452
		 */
453
		$dependencies = array_merge(
454
			isset($dependencies[$current_module]) ? $dependencies[$current_module] : [],
455
			$dependencies['System']
456
		);
457
		return [$includes, $dependencies_includes, $dependencies, $current_url];
458
	}
459
	/**
460
	 * @param array  $dependencies
461
	 * @param string $url
462
	 * @param string $separator `+` or `/`
463
	 *
464
	 * @return bool
465
	 */
466
	protected function get_includes_is_dependency ($dependencies, $url, $separator) {
467
		$url_exploded = explode($separator, $url);
468
		/** @noinspection NestedTernaryOperatorInspection */
469
		$url_module = $url_exploded[0] != 'admin' ? $url_exploded[0] : (@$url_exploded[1] ?: '');
470
		$Request    = Request::instance();
471
		return
472
			$url_module !== Config::SYSTEM_MODULE &&
473
			in_array($url_module, $dependencies) &&
474
			(
475
				$Request->admin_path || $Request->admin_path == ($url_exploded[0] == 'admin')
476
			);
477
	}
478
	protected function add_versions_hash ($includes) {
479
		$content = array_map('file_get_contents', get_files_list(DIR.'/components', '/^meta\.json$/', 'f', true, true));
480
		$content = implode('', $content);
481
		$hash    = substr(md5($content), 0, 5);
482
		foreach ($includes as &$files) {
483
			foreach ($files as &$file) {
484
				$file .= "?$hash";
485
			}
486
			unset($file);
487
		}
488
		return $includes;
489
	}
490
	/**
491
	 * @param Config $Config
492
	 */
493
	protected function add_includes_on_page_manually_added ($Config) {
494
		foreach (['core_html', 'core_js', 'core_css', 'html', 'js', 'css'] as $type) {
495
			foreach ($this->$type as &$elements) {
496
				$elements = implode('', array_unique($elements));
497
			}
498
			unset($elements);
499
		}
500
		$this->Head .=
501
			$this->core_config.
502
			$this->config.
503
			$this->core_css[0].$this->css[0].
504
			h::style($this->core_css[1].$this->css[1] ?: false);
505
		$js_html_insert_to = $Config->core['put_js_after_body'] ? 'post_Body' : 'Head';
506
		$js_html           =
507
			$this->core_js[0].
508
			h::script($this->core_js[1] ?: false).
509
			$this->js[0].
510
			h::script($this->js[1] ?: false).
511
			$this->core_html[0].$this->html[0].
512
			$this->core_html[1].$this->html[1];
513
		$this->$js_html_insert_to .= $js_html;
514
	}
515
	/**
516
	 * Getting of HTML, JS and CSS files list to be included
517
	 *
518
	 * @return string[][]
519
	 */
520
	protected function get_includes_list () {
521
		$includes = [];
522
		/**
523
		 * Get includes of system and theme
524
		 */
525
		$this->get_includes_list_add_includes(DIR.'/includes', $includes);
526
		$this->get_includes_list_add_includes(THEMES."/$this->theme", $includes);
527
		$Config = Config::instance();
528
		foreach ($Config->components['modules'] as $module_name => $module_data) {
529
			if ($module_data['active'] == Config\Module_Properties::UNINSTALLED) {
530
				continue;
531
			}
532
			$this->get_includes_list_add_includes(MODULES."/$module_name/includes", $includes);
533
		}
534
		foreach ($Config->components['plugins'] as $plugin_name) {
535
			$this->get_includes_list_add_includes(PLUGINS."/$plugin_name/includes", $includes);
536
		}
537
		return [
538
			'html' => array_merge(...$includes['html']),
539
			'js'   => array_merge(...$includes['js']),
540
			'css'  => array_merge(...$includes['css'])
541
		];
542
	}
543
	/**
544
	 * @param string     $base_dir
545
	 * @param string[][] $includes
546
	 */
547
	protected function get_includes_list_add_includes ($base_dir, &$includes) {
548
		$includes['html'][] = $this->get_includes_list_add_includes_internal($base_dir, 'html');
549
		$includes['js'][]   = $this->get_includes_list_add_includes_internal($base_dir, 'js');
550
		$includes['css'][]  = $this->get_includes_list_add_includes_internal($base_dir, 'css');
551
	}
552
	/**
553
	 * @param string $base_dir
554
	 * @param string $ext
555
	 *
556
	 * @return array
557
	 */
558
	protected function get_includes_list_add_includes_internal ($base_dir, $ext) {
559
		return get_files_list("$base_dir/$ext", "/.*\\.$ext\$/i", 'f', true, true, 'name', '!include') ?: [];
560
	}
561
	/**
562
	 * Rebuilding of HTML, JS and CSS cache
563
	 *
564
	 * @return \cs\Page
565
	 */
566
	protected function rebuild_cache () {
567
		list($dependencies, $includes_map) = $this->includes_dependencies_and_map();
568
		$structure = [];
569
		foreach ($includes_map as $filename_prefix => $includes) {
570
			// We replace `/` by `+` to make it suitable for filename
571
			$filename_prefix             = str_replace('/', '+', $filename_prefix);
572
			$structure[$filename_prefix] = $this->create_cached_includes_files($filename_prefix, $includes);
573
		}
574
		unset($includes_map, $filename_prefix, $includes);
575
		file_put_json(
576
			PUBLIC_CACHE."/$this->pcache_basename.json",
577
			[$dependencies, $structure]
578
		);
579
		unset($structure);
580
		Event::instance()->fire('System/Page/rebuild_cache');
581
		return $this;
582
	}
583
	/**
584
	 * Creates cached version of given HTML, JS and CSS files.
585
	 * Resulting file name consists of <b>$filename_prefix</b> and <b>$this->pcache_basename</b>
586
	 *
587
	 * @param string $filename_prefix
588
	 * @param array  $includes Array of paths to files, may have keys: <b>css</b> and/or <b>js</b> and/or <b>html</b>
589
	 *
590
	 * @return array
591
	 */
592
	protected function create_cached_includes_files ($filename_prefix, $includes) {
593
		$cache_hash = [];
594
		foreach ($includes as $extension => $files) {
595
			$content = $this->create_cached_includes_files_process_files($extension, $filename_prefix, $files);
596
			file_put_contents(PUBLIC_CACHE."/$filename_prefix$this->pcache_basename.$extension", gzencode($content, 9), LOCK_EX | FILE_BINARY);
597
			$cache_hash[$extension] = substr(md5($content), 0, 5);
598
		}
599
		return $cache_hash;
600
	}
601
	protected function create_cached_includes_files_process_files ($extension, $filename_prefix, $files) {
602
		$content = '';
603
		switch ($extension) {
604
			/**
605
			 * Insert external elements into resulting css file.
606
			 * It is needed, because those files will not be copied into new destination of resulting css file.
607
			 */
608
			case 'css':
609
				$callback = function ($content, $file) {
610
					return $content.Includes_processing::css(file_get_contents($file), $file);
611
				};
612
				break;
613
			/**
614
			 * Combine css and js files for Web Component into resulting files in order to optimize loading process
615
			 */
616
			case 'html':
617
				/**
618
				 * For CSP-compatible HTML files we need to know destination to put there additional JS/CSS files
619
				 */
620
				$destination = Config::instance()->core['vulcanization'] ? false : PUBLIC_CACHE;
621
				$callback    = function ($content, $file) use ($filename_prefix, $destination) {
622
					$base_filename = "$filename_prefix$this->pcache_basename-".basename($file).'+'.substr(md5($file), 0, 5);
623
					return $content.Includes_processing::html(file_get_contents($file), $file, $base_filename, $destination);
624
				};
625
				break;
626
			case 'js':
627
				$callback = function ($content, $file) {
628
					return $content.Includes_processing::js(file_get_contents($file));
629
				};
630
				if ($filename_prefix == '') {
631
					$content = 'window.cs={Language:'._json_encode(Language::instance()).'};';
632
					$content .= 'window.requirejs={paths:'._json_encode($this->get_requirejs_paths()).'};';
633
				}
634
		}
635
		/** @noinspection PhpUndefinedVariableInspection */
636
		return array_reduce($files, $callback, $content);
637
	}
638
	/**
639
	 * Get dependencies of components between each other (only that contains some HTML, JS and CSS files) and mapping HTML, JS and CSS files to URL paths
640
	 *
641
	 * @return array[] [$dependencies, $includes_map]
642
	 */
643
	protected function includes_dependencies_and_map () {
644
		/**
645
		 * Get all includes
646
		 */
647
		$all_includes = $this->get_includes_list();
648
		$includes_map = [];
649
		/**
650
		 * Array [package => [list of packages it depends on]]
651
		 */
652
		$dependencies    = [];
653
		$functionalities = [];
654
		/**
655
		 * According to components's maps some files should be included only on specific pages.
656
		 * Here we read this rules, and remove from whole includes list such items, that should be included only on specific pages.
657
		 * Also collect dependencies.
658
		 */
659
		$Config = Config::instance();
660
		foreach ($Config->components['modules'] as $module_name => $module_data) {
661
			if ($module_data['active'] == Config\Module_Properties::UNINSTALLED) {
662
				continue;
663
			}
664
			$this->process_meta(MODULES."/$module_name", $dependencies, $functionalities);
665
			$this->process_map(MODULES."/$module_name", $includes_map, $all_includes);
666
		}
667
		unset($module_name, $module_data);
668
		foreach ($Config->components['plugins'] as $plugin_name) {
669
			$this->process_meta(PLUGINS."/$plugin_name", $dependencies, $functionalities);
670
			$this->process_map(PLUGINS."/$plugin_name", $includes_map, $all_includes);
671
		}
672
		unset($plugin_name);
673
		/**
674
		 * For consistency
675
		 */
676
		$includes_map[''] = $all_includes;
677
		Event::instance()->fire(
678
			'System/Page/includes_dependencies_and_map',
679
			[
680
				'dependencies' => &$dependencies,
681
				'includes_map' => &$includes_map
682
			]
683
		);
684
		$dependencies = $this->normalize_dependencies($dependencies, $functionalities);
685
		$includes_map = $this->clean_includes_arrays_without_files($dependencies, $includes_map);
686
		$dependencies = array_map('array_values', $dependencies);
687
		$dependencies = array_filter($dependencies);
688
		return [$dependencies, $includes_map];
689
	}
690
	/**
691
	 * Process meta information and corresponding entries to dependencies and functionalities
692
	 *
693
	 * @param string $base_dir
694
	 * @param array  $dependencies
695
	 * @param array  $functionalities
696
	 */
697
	protected function process_meta ($base_dir, &$dependencies, &$functionalities) {
698
		if (!file_exists("$base_dir/meta.json")) {
699
			return;
700
		}
701
		$meta = file_get_json("$base_dir/meta.json");
702
		$meta += [
703
			'require'  => [],
704
			'optional' => [],
705
			'provide'  => []
706
		];
707
		$package = $meta['package'];
708
		foreach ((array)$meta['require'] as $r) {
709
			/**
710
			 * Get only name of package or functionality
711
			 */
712
			$r                        = preg_split('/[=<>]/', $r, 2)[0];
713
			$dependencies[$package][] = $r;
714
		}
715
		foreach ((array)$meta['optional'] as $o) {
716
			/**
717
			 * Get only name of package or functionality
718
			 */
719
			$o                        = preg_split('/[=<>]/', $o, 2)[0];
720
			$dependencies[$package][] = $o;
721
		}
722
		foreach ((array)$meta['provide'] as $p) {
723
			/**
724
			 * If provides sub-functionality for other component (for instance, `Blog/post_patch`) - inverse "providing" to "dependency"
725
			 * Otherwise it is just functionality alias to package name
726
			 */
727
			if (strpos($p, '/') !== false) {
728
				/**
729
				 * Get name of package or functionality
730
				 */
731
				$p                  = explode('/', $p)[0];
732
				$dependencies[$p][] = $package;
733
			} else {
734
				$functionalities[$p] = $package;
735
			}
736
		}
737
	}
738
	/**
739
	 * Process map structure, fill includes map and remove files from list of all includes (remaining files will be included on all pages)
740
	 *
741
	 * @param string $base_dir
742
	 * @param array  $includes_map
743
	 * @param array  $all_includes
744
	 */
745
	protected function process_map ($base_dir, &$includes_map, &$all_includes) {
746
		if (!file_exists("$base_dir/includes/map.json")) {
747
			return;
748
		}
749
		$this->process_map_internal(file_get_json("$base_dir/includes/map.json"), "$base_dir/includes", $includes_map, $all_includes);
750
	}
751
	/**
752
	 * Process map structure, fill includes map and remove files from list of all includes (remaining files will be included on all pages)
753
	 *
754
	 * @param array  $map
755
	 * @param string $includes_dir
756
	 * @param array  $includes_map
757
	 * @param array  $all_includes
758
	 */
759
	protected function process_map_internal ($map, $includes_dir, &$includes_map, &$all_includes) {
760
		foreach ($map as $path => $files) {
761
			foreach ((array)$files as $file) {
762
				$extension = file_extension($file);
763
				if (in_array($extension, ['css', 'js', 'html'])) {
764
					$file                              = "$includes_dir/$extension/$file";
765
					$includes_map[$path][$extension][] = $file;
766
					$all_includes[$extension]          = array_diff($all_includes[$extension], [$file]);
767
				} else {
768
					$file = rtrim($file, '*');
769
					/**
770
					 * Wildcard support, it is possible to specify just path prefix and all files with this prefix will be included
771
					 */
772
					$found_files = array_filter(
773
						get_files_list($includes_dir, '/.*\.(css|js|html)$/i', 'f', '', true, 'name', '!include') ?: [],
774
						function ($f) use ($file) {
775
							// We need only files with specified mask and only those located in directory that corresponds to file's extension
776
							return preg_match("#^(css|js|html)/$file.*\\1$#i", $f);
777
						}
778
					);
779
					// Drop first level directory
780
					$found_files = _preg_replace('#^[^/]+/(.*)#', '$1', $found_files);
781
					$this->process_map_internal([$path => $found_files], $includes_dir, $includes_map, $all_includes);
782
				}
783
			}
784
		}
785
	}
786
	/**
787
	 * Replace functionalities by real packages names, take into account recursive dependencies
788
	 *
789
	 * @param array $dependencies
790
	 * @param array $functionalities
791
	 *
792
	 * @return array
793
	 */
794
	protected function normalize_dependencies ($dependencies, $functionalities) {
795
		/**
796
		 * First of all remove packages without any dependencies
797
		 */
798
		$dependencies = array_filter($dependencies);
799
		/**
800
		 * First round, process aliases among keys
801
		 */
802
		foreach (array_keys($dependencies) as $d) {
803
			if (isset($functionalities[$d])) {
804
				$package = $functionalities[$d];
805
				/**
806
				 * Add dependencies to existing package dependencies
807
				 */
808
				foreach ($dependencies[$d] as $dependency) {
809
					$dependencies[$package][] = $dependency;
810
				}
811
				/**
812
				 * Drop alias
813
				 */
814
				unset($dependencies[$d]);
815
			}
816
		}
817
		unset($d, $dependency);
818
		/**
819
		 * Second round, process aliases among dependencies
820
		 */
821
		foreach ($dependencies as &$depends_on) {
822
			foreach ($depends_on as &$dependency) {
823
				if (isset($functionalities[$dependency])) {
824
					$dependency = $functionalities[$dependency];
825
				}
826
			}
827
		}
828
		unset($depends_on, $dependency);
829
		/**
830
		 * Third round, process recursive dependencies
831
		 */
832
		foreach ($dependencies as &$depends_on) {
833
			foreach ($depends_on as &$dependency) {
834
				if ($dependency != 'System' && isset($dependencies[$dependency])) {
835
					foreach (array_diff($dependencies[$dependency], $depends_on) as $new_dependency) {
836
						$depends_on[] = $new_dependency;
837
					}
838
				}
839
			}
840
		}
841
		return array_map('array_unique', $dependencies);
842
	}
843
	/**
844
	 * Includes array is composed from dependencies and sometimes dependencies doesn't have any files, so we'll clean that
845
	 *
846
	 * @param array $dependencies
847
	 * @param array $includes_map
848
	 *
849
	 * @return array
850
	 */
851
	protected function clean_includes_arrays_without_files ($dependencies, $includes_map) {
852
		foreach ($dependencies as &$depends_on) {
853
			foreach ($depends_on as $index => &$dependency) {
854
				if (!isset($includes_map[$dependency])) {
855
					unset($depends_on[$index]);
856
				}
857
			}
858
			unset($dependency);
859
		}
860
		return $includes_map;
861
	}
862
}
863