Completed
Push — master ( 80dd6e...5fe464 )
by Nazar
03:51
created

Includes::process_map()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

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