forked from picocms/Pico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pico.php
2791 lines (2487 loc) · 98.8 KB
/
Pico.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This file is part of Pico. It's copyrighted by the contributors recorded
* in the version control history of the file, available from the following
* original location:
*
* <https://github.com/picocms/Pico/blob/master/lib/Pico.php>
*
* The file has been renamed in the past; the version control history of the
* original file applies accordingly, available from the following original
* location:
*
* <https://github.com/picocms/Pico/blob/adc356251ecd79689935ec1446c7c846db167d46/lib/pico.php>
*
* SPDX-License-Identifier: MIT
* License-Filename: LICENSE
*/
/**
* Pico
*
* Pico is a stupidly simple, blazing fast, flat file CMS.
*
* - Stupidly Simple: Pico makes creating and maintaining a
* website as simple as editing text files.
* - Blazing Fast: Pico is seriously lightweight and doesn't
* use a database, making it super fast.
* - No Database: Pico is a "flat file" CMS, meaning no
* database woes, no MySQL queries, nothing.
* - Markdown Formatting: Edit your website in your favourite
* text editor using simple Markdown formatting.
* - Twig Templates: Pico uses the Twig templating engine,
* for powerful and flexible themes.
* - Open Source: Pico is completely free and open source,
* released under the MIT license.
*
* See <http://picocms.org/> for more info.
*
* @author Gilbert Pellegrom
* @author Daniel Rudolf
* @link http://picocms.org
* @license http://opensource.org/licenses/MIT The MIT License
* @version 2.1
*/
class Pico
{
/**
* Pico version
*
* @var string
*/
const VERSION = '2.1.4';
/**
* Pico version ID
*
* @var int
*/
const VERSION_ID = 20104;
/**
* Pico API version
*
* @var int
*/
const API_VERSION = 3;
/**
* Sort files in alphabetical ascending order
*
* @see Pico::getFiles()
* @var int
*/
const SORT_ASC = 0;
/**
* Sort files in alphabetical descending order
*
* @see Pico::getFiles()
* @var int
*/
const SORT_DESC = 1;
/**
* Don't sort files
*
* @see Pico::getFiles()
* @var int
*/
const SORT_NONE = 2;
/**
* Root directory of this Pico instance
*
* @see Pico::getRootDir()
* @var string
*/
protected $rootDir;
/**
* Vendor directory of this Pico instance
*
* @see Pico::getVendorDir()
* @var string
*/
protected $vendorDir;
/**
* Config directory of this Pico instance
*
* @see Pico::getConfigDir()
* @var string
*/
protected $configDir;
/**
* Plugins directory of this Pico instance
*
* @see Pico::getPluginsDir()
* @var string
*/
protected $pluginsDir;
/**
* Themes directory of this Pico instance
*
* @see Pico::getThemesDir()
* @var string
*/
protected $themesDir;
/**
* Boolean indicating whether Pico started processing yet
*
* @var bool
*/
protected $locked = false;
/**
* List of loaded plugins
*
* @see Pico::getPlugins()
* @var object[]
*/
protected $plugins = array();
/**
* List of loaded plugins using the current API version
*
* @var PicoPluginInterface[]
*/
protected $nativePlugins = array();
/**
* Boolean indicating whether Pico loads plugins from the filesystem
*
* @see Pico::loadPlugins()
* @see Pico::loadLocalPlugins()
* @var bool
*/
protected $enableLocalPlugins = true;
/**
* Current configuration of this Pico instance
*
* @see Pico::getConfig()
* @var array|null
*/
protected $config;
/**
* Theme in use
*
* @see Pico::getTheme()
* @var string
*/
protected $theme;
/**
* API version of the current theme
*
* @see Pico::getThemeApiVersion()
* @var int
*/
protected $themeApiVersion;
/**
* Additional meta headers of the current theme
*
* @var array<string,string>|null
*/
protected $themeMetaHeaders;
/**
* Part of the URL describing the requested contents
*
* @see Pico::getRequestUrl()
* @var string|null
*/
protected $requestUrl;
/**
* Absolute path to the content file being served
*
* @see Pico::getRequestFile()
* @var string|null
*/
protected $requestFile;
/**
* Raw, not yet parsed contents to serve
*
* @see Pico::getRawContent()
* @var string|null
*/
protected $rawContent;
/**
* Boolean indicating whether Pico is serving a 404 page
*
* @see Pico::is404Content()
* @var bool
*/
protected $is404Content = false;
/**
* Symfony YAML instance used for meta header parsing
*
* @see Pico::getYamlParser()
* @var \Symfony\Component\Yaml\Parser|null
*/
protected $yamlParser;
/**
* List of known meta headers
*
* @see Pico::getMetaHeaders()
* @var array<string,string>|null
*/
protected $metaHeaders;
/**
* Meta data of the page to serve
*
* @see Pico::getFileMeta()
* @var array|null
*/
protected $meta;
/**
* Parsedown Extra instance used for markdown parsing
*
* @see Pico::getParsedown()
* @var Parsedown|null
*/
protected $parsedown;
/**
* Parsed content being served
*
* @see Pico::getFileContent()
* @var string|null
*/
protected $content;
/**
* List of known pages
*
* @see Pico::getPages()
* @var array[]|null
*/
protected $pages;
/**
* Data of the page being served
*
* @see Pico::getCurrentPage()
* @var array|null
*/
protected $currentPage;
/**
* Data of the previous page relative to the page being served
*
* @see Pico::getPreviousPage()
* @var array|null
*/
protected $previousPage;
/**
* Data of the next page relative to the page being served
*
* @see Pico::getNextPage()
* @var array|null
*/
protected $nextPage;
/**
* Tree structure of known pages
*
* @see Pico::getPageTree()
* @var array[]|null
*/
protected $pageTree;
/**
* Twig instance used for template parsing
*
* @see Pico::getTwig()
* @var Twig_Environment|null
*/
protected $twig;
/**
* Variables passed to the twig template
*
* @see Pico::getTwigVariables()
* @var array|null
*/
protected $twigVariables;
/**
* Name of the Twig template to render
*
* @see Pico::getTwigTemplate()
* @var string|null
*/
protected $twigTemplate;
/**
* Constructs a new Pico instance
*
* To carry out all the processing in Pico, call {@see Pico::run()}.
*
* @param string $rootDir root dir of this Pico instance
* @param string $configDir config dir of this Pico instance
* @param string $pluginsDir plugins dir of this Pico instance
* @param string $themesDir themes dir of this Pico instance
* @param bool $enableLocalPlugins enables (TRUE; default) or disables
* (FALSE) loading plugins from the filesystem
*/
public function __construct($rootDir, $configDir, $pluginsDir, $themesDir, $enableLocalPlugins = true)
{
$this->rootDir = rtrim($rootDir, '/\\') . '/';
$this->vendorDir = dirname(__DIR__) . '/';
$this->configDir = $this->getAbsolutePath($configDir);
$this->pluginsDir = $this->getAbsolutePath($pluginsDir);
$this->themesDir = $this->getAbsolutePath($themesDir);
$this->enableLocalPlugins = (bool) $enableLocalPlugins;
}
/**
* Returns the root directory of this Pico instance
*
* @return string root directory path
*/
public function getRootDir()
{
return $this->rootDir;
}
/**
* Returns the vendor directory of this Pico instance
*
* @return string vendor directory path
*/
public function getVendorDir()
{
return $this->vendorDir;
}
/**
* Returns the config directory of this Pico instance
*
* @return string config directory path
*/
public function getConfigDir()
{
return $this->configDir;
}
/**
* Returns the plugins directory of this Pico instance
*
* @return string plugins directory path
*/
public function getPluginsDir()
{
return $this->pluginsDir;
}
/**
* Returns the themes directory of this Pico instance
*
* @return string themes directory path
*/
public function getThemesDir()
{
return $this->themesDir;
}
/**
* Runs this Pico instance
*
* Loads plugins, evaluates the config file, does URL routing, parses
* meta headers, processes Markdown, does Twig processing and returns
* the rendered contents.
*
* @return string rendered Pico contents
*
* @throws Exception thrown when a irrecoverable error occurs
*/
public function run()
{
// check lock
if ($this->locked) {
throw new LogicException('You cannot run the same Pico instance multiple times');
}
// lock Pico
$this->locked = true;
// load plugins
$this->loadPlugins();
$this->sortPlugins();
$this->triggerEvent('onPluginsLoaded', array($this->plugins));
// load config
$this->loadConfig();
$this->triggerEvent('onConfigLoaded', array(&$this->config));
// check content dir
if (!is_dir($this->getConfig('content_dir'))) {
throw new RuntimeException('Invalid content directory "' . $this->getConfig('content_dir') . '"');
}
// load theme
$this->theme = $this->config['theme'];
$this->triggerEvent('onThemeLoading', array(&$this->theme));
$this->loadTheme();
$this->triggerEvent(
'onThemeLoaded',
array($this->theme, $this->themeApiVersion, &$this->config['theme_config'])
);
// evaluate request url
$this->evaluateRequestUrl();
$this->triggerEvent('onRequestUrl', array(&$this->requestUrl));
// discover requested file
$this->requestFile = $this->resolveFilePath($this->requestUrl);
$this->triggerEvent('onRequestFile', array(&$this->requestFile));
// load raw file content
$this->triggerEvent('onContentLoading');
$requestedPageId = $this->getPageId($this->requestFile) ?: $this->requestFile;
$hiddenFileRegex = '/(?:^|\/)(?:_|404' . preg_quote($this->getConfig('content_ext'), '/') . '$)/';
if (is_file($this->requestFile) && !preg_match($hiddenFileRegex, $requestedPageId)) {
$this->rawContent = $this->loadFileContent($this->requestFile);
} else {
$this->triggerEvent('on404ContentLoading');
$serverProtocol = !empty($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
header($serverProtocol . ' 404 Not Found');
$this->rawContent = $this->load404Content($this->requestFile);
$this->is404Content = true;
$this->triggerEvent('on404ContentLoaded', array(&$this->rawContent));
}
$this->triggerEvent('onContentLoaded', array(&$this->rawContent));
// parse file meta
$this->triggerEvent('onMetaParsing');
$this->meta = $this->parseFileMeta($this->rawContent, $this->getMetaHeaders());
$this->triggerEvent('onMetaParsed', array(&$this->meta));
// parse file content
$this->triggerEvent('onContentParsing');
$markdown = $this->prepareFileContent($this->rawContent, $this->meta);
$this->triggerEvent('onContentPrepared', array(&$markdown));
$this->content = $this->parseFileContent($markdown);
$this->triggerEvent('onContentParsed', array(&$this->content));
// read pages
$this->triggerEvent('onPagesLoading');
$this->readPages();
$this->triggerEvent('onPagesDiscovered', array(&$this->pages));
$this->sortPages();
$this->triggerEvent('onPagesLoaded', array(&$this->pages));
$this->discoverPageSiblings();
$this->discoverCurrentPage();
$this->triggerEvent(
'onCurrentPageDiscovered',
array(&$this->currentPage, &$this->previousPage, &$this->nextPage)
);
$this->buildPageTree();
$this->triggerEvent('onPageTreeBuilt', array(&$this->pageTree));
// render template
$this->twigVariables = $this->getTwigVariables();
$this->twigTemplate = $this->getTwigTemplate();
$this->triggerEvent('onPageRendering', array(&$this->twigTemplate, &$this->twigVariables));
$output = $this->getTwig()->render($this->twigTemplate, $this->twigVariables);
$this->triggerEvent('onPageRendered', array(&$output));
return $output;
}
/**
* Loads plugins from vendor/pico-plugin.php and Pico::$pluginsDir
*
* See {@see Pico::loadComposerPlugins()} for details about plugins loaded
* from `vendor/pico-plugin.php` (i.e. plugins that were installed using
* composer), and {@see Pico::loadLocalPlugins()} for details about plugins
* installed to {@see Pico::$pluginsDir}. Pico loads plugins from the
* filesystem only if {@see Pico::$enableLocalPlugins} is set to TRUE
* (this is the default).
*
* Pico always loads plugins from `vendor/pico-plugin.php` first and
* ignores conflicting plugins in {@see Pico::$pluginsDir}.
*
* The official PicoDeprecated plugin must be loaded when plugins that use
* an older API version than Pico's API version ({@see Pico::API_VERSION})
* are loaded.
*
* Please note that Pico will change the processing order when needed to
* incorporate plugin dependencies. See {@see Pico::sortPlugins()} for
* details.
*
* @see Pico::loadPlugin()
* @see Pico::getPlugin()
* @see Pico::getPlugins()
*
* @throws RuntimeException thrown when a plugin couldn't be loaded
*/
protected function loadPlugins()
{
$composerPlugins = $this->loadComposerPlugins();
if ($this->enableLocalPlugins) {
$this->loadLocalPlugins($composerPlugins);
}
if (!isset($this->plugins['PicoDeprecated']) && (count($this->plugins) !== count($this->nativePlugins))) {
throw new RuntimeException(
"Plugins using an older API than version " . static::API_VERSION . " found, "
. "but PicoDeprecated isn't loaded"
);
}
}
/**
* Loads plugins from vendor/pico-plugin.php
*
* This method loads all plugins installed using composer and Pico's
* `picocms/composer-installer` installer by reading the `pico-plugin.php`
* in composer's `vendor` dir.
*
* @see Pico::loadPlugins()
* @see Pico::loadLocalPlugins()
*
* @param string[] $pluginBlacklist class names of plugins not to load
*
* @return string[] installer names of the loaded plugins
*
* @throws RuntimeException thrown when a plugin couldn't be loaded
*/
protected function loadComposerPlugins(array $pluginBlacklist = array())
{
$composerPlugins = array();
if (is_file($this->getVendorDir() . 'vendor/pico-plugin.php')) {
// composer root package
$composerPlugins = require($this->getVendorDir() . 'vendor/pico-plugin.php') ?: array();
} elseif (is_file($this->getVendorDir() . '../../../vendor/pico-plugin.php')) {
// composer dependency package
$composerPlugins = require($this->getVendorDir() . '../../../vendor/pico-plugin.php') ?: array();
}
$pluginBlacklist = array_fill_keys($pluginBlacklist, true);
$loadedPlugins = array();
foreach ($composerPlugins as $package => $pluginData) {
$loadedPlugins[] = $pluginData['installerName'];
foreach ($pluginData['classNames'] as $className) {
$plugin = new $className($this);
$className = get_class($plugin);
if (isset($this->plugins[$className]) || isset($pluginBlacklist[$className])) {
continue;
}
if (!($plugin instanceof PicoPluginInterface)) {
throw new RuntimeException(
"Unable to load plugin '" . $className . "' via 'vendor/pico-plugin.php': "
. "Plugins installed by composer must implement 'PicoPluginInterface'"
);
}
$this->plugins[$className] = $plugin;
if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
$this->nativePlugins[$className] = $plugin;
}
}
}
return $loadedPlugins;
}
/**
* Loads plugins from Pico::$pluginsDir in alphabetical order
*
* Pico tries to load plugins from `<plugin name>/<plugin name>.php` and
* `<plugin name>.php` only. Plugin names are treated case insensitive.
* Pico will throw a RuntimeException if it can't load a plugin.
*
* Plugin files MAY be prefixed by a number (e.g. `00-PicoDeprecated.php`)
* to indicate their processing order. Plugins without a prefix will be
* loaded last. If you want to use a prefix, you MUST NOT use the reserved
* prefixes `00` to `09`. Prefixes are completely optional, however, you
* SHOULD take the following prefix classification into consideration:
* - 10 to 19: Reserved
* - 20 to 39: Low level code helper plugins
* - 40 to 59: Plugins manipulating routing or the pages array
* - 60 to 79: Plugins hooking into template or markdown parsing
* - 80 to 99: Plugins using the `onPageRendered` event
*
* @see Pico::loadPlugins()
* @see Pico::loadComposerPlugins()
*
* @param string[] $pluginBlacklist class names of plugins not to load
*
* @throws RuntimeException thrown when a plugin couldn't be loaded
*/
protected function loadLocalPlugins(array $pluginBlacklist = array())
{
// scope isolated require()
$includeClosure = function ($pluginFile) {
require($pluginFile);
};
if (PHP_VERSION_ID >= 50400) {
$includeClosure = $includeClosure->bindTo(null);
}
$pluginBlacklist = array_fill_keys($pluginBlacklist, true);
$files = scandir($this->getPluginsDir()) ?: array();
foreach ($files as $file) {
if ($file[0] === '.') {
continue;
}
$className = $pluginFile = null;
if (is_dir($this->getPluginsDir() . $file)) {
$className = preg_replace('/^[0-9]+-/', '', $file);
$pluginFile = $file . '/' . $className . '.php';
if (!is_file($this->getPluginsDir() . $pluginFile)) {
throw new RuntimeException(
"Unable to load plugin '" . $className . "' from '" . $pluginFile . "': File not found"
);
}
} elseif (substr($file, -4) === '.php') {
$className = preg_replace('/^[0-9]+-/', '', substr($file, 0, -4));
$pluginFile = $file;
} else {
throw new RuntimeException("Unable to load plugin from '" . $file . "': Not a valid plugin file");
}
if (isset($this->plugins[$className]) || isset($pluginBlacklist[$className])) {
continue;
}
$includeClosure($this->getPluginsDir() . $pluginFile);
if (class_exists($className, false)) {
// class name and file name can differ regarding case sensitivity
$plugin = new $className($this);
$className = get_class($plugin);
$this->plugins[$className] = $plugin;
if ($plugin instanceof PicoPluginInterface) {
if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
$this->nativePlugins[$className] = $plugin;
}
}
} else {
throw new RuntimeException(
"Unable to load plugin '" . $className . "' from '" . $pluginFile . "': Plugin class not found"
);
}
}
}
/**
* Manually loads a plugin
*
* Manually loaded plugins MUST implement {@see PicoPluginInterface}. They
* are simply appended to the plugins array without any additional checks,
* so you might get unexpected results, depending on *when* you're loading
* a plugin. You SHOULD NOT load plugins after a event has been triggered
* by Pico. In-depth knowledge of Pico's inner workings is strongly advised
* otherwise, and you MUST NOT rely on {@see PicoDeprecated} to maintain
* backward compatibility in such cases.
*
* If you e.g. load a plugin after the `onPluginsLoaded` event, Pico
* doesn't guarantee the plugin's order ({@see Pico::sortPlugins()}).
* Already triggered events won't get triggered on the manually loaded
* plugin. Thus you SHOULD load plugins either before {@see Pico::run()}
* is called, or via the constructor of another plugin (i.e. the plugin's
* `__construct()` method; plugins are instanced in
* {@see Pico::loadPlugins()}).
*
* This method triggers the `onPluginManuallyLoaded` event.
*
* @see Pico::loadPlugins()
* @see Pico::getPlugin()
* @see Pico::getPlugins()
*
* @param PicoPluginInterface|string $plugin either the class name of a
* plugin to instantiate or a plugin instance
*
* @return PicoPluginInterface instance of the loaded plugin
*
* @throws RuntimeException thrown when the plugin couldn't be loaded
*/
public function loadPlugin($plugin)
{
if (!is_object($plugin)) {
$className = (string) $plugin;
if (class_exists($className)) {
$plugin = new $className($this);
} else {
throw new RuntimeException("Unable to load plugin '" . $className . "': Class not found");
}
}
$className = get_class($plugin);
if (!($plugin instanceof PicoPluginInterface)) {
throw new RuntimeException(
"Unable to load plugin '" . $className . "': "
. "Manually loaded plugins must implement 'PicoPluginInterface'"
);
}
$this->plugins[$className] = $plugin;
if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) {
$this->nativePlugins[$className] = $plugin;
}
// trigger onPluginManuallyLoaded event
// the event is also triggered on the newly loaded plugin, allowing you to distinguish manual and auto loading
$this->triggerEvent('onPluginManuallyLoaded', array($plugin));
return $plugin;
}
/**
* Sorts all loaded plugins using a plugin dependency topology
*
* Execution order matters: if plugin A depends on plugin B, it usually
* means that plugin B does stuff which plugin A requires. However, Pico
* loads plugins in alphabetical order, so events might get fired on
* plugin A before plugin B.
*
* Hence plugins need to be sorted. Pico sorts plugins using a dependency
* topology, this means that it moves all plugins, on which a plugin
* depends, in front of that plugin. The order isn't touched apart from
* that, so they are still sorted alphabetically, as long as this doesn't
* interfere with the dependency topology. Circular dependencies are being
* ignored; their behavior is undefiend. Missing dependencies are being
* ignored until you try to enable the dependant plugin.
*
* This method bases on Marc J. Schmidt's Topological Sort library in
* version 1.1.0, licensed under the MIT license. It uses the `ArraySort`
* implementation (class `\MJS\TopSort\Implementations\ArraySort`).
*
* @see Pico::loadPlugins()
* @see Pico::getPlugins()
* @see https://github.com/marcj/topsort.php
* Marc J. Schmidt's Topological Sort / Dependency resolver in PHP
* @see https://github.com/marcj/topsort.php/blob/1.1.0/src/Implementations/ArraySort.php
* \MJS\TopSort\Implementations\ArraySort class
*/
protected function sortPlugins()
{
$plugins = $this->plugins;
$nativePlugins = $this->nativePlugins;
$sortedPlugins = array();
$sortedNativePlugins = array();
$visitedPlugins = array();
$visitPlugin = function ($plugin) use (
$plugins,
$nativePlugins,
&$sortedPlugins,
&$sortedNativePlugins,
&$visitedPlugins,
&$visitPlugin
) {
$pluginName = get_class($plugin);
// skip already visited plugins and ignore circular dependencies
if (!isset($visitedPlugins[$pluginName])) {
$visitedPlugins[$pluginName] = true;
$dependencies = array();
if ($plugin instanceof PicoPluginInterface) {
$dependencies = $plugin->getDependencies();
}
if (!isset($nativePlugins[$pluginName])) {
$dependencies[] = 'PicoDeprecated';
}
foreach ($dependencies as $dependency) {
// ignore missing dependencies
// this is only a problem when the user tries to enable this plugin
if (isset($plugins[$dependency])) {
$visitPlugin($plugins[$dependency]);
}
}
$sortedPlugins[$pluginName] = $plugin;
if (isset($nativePlugins[$pluginName])) {
$sortedNativePlugins[$pluginName] = $plugin;
}
}
};
if (isset($this->plugins['PicoDeprecated'])) {
$visitPlugin($this->plugins['PicoDeprecated']);
}
foreach ($this->plugins as $plugin) {
$visitPlugin($plugin);
}
$this->plugins = $sortedPlugins;
$this->nativePlugins = $sortedNativePlugins;
}
/**
* Returns the instance of a named plugin
*
* Plugins SHOULD implement {@see PicoPluginInterface}, but you MUST NOT
* rely on it. For more information see {@see PicoPluginInterface}.
*
* @see Pico::loadPlugins()
* @see Pico::getPlugins()
*
* @param string $pluginName name of the plugin
*
* @return object instance of the plugin
*
* @throws RuntimeException thrown when the plugin wasn't found
*/
public function getPlugin($pluginName)
{
if (isset($this->plugins[$pluginName])) {
return $this->plugins[$pluginName];
}
throw new RuntimeException("Missing plugin '" . $pluginName . "'");
}
/**
* Returns all loaded plugins
*
* @see Pico::loadPlugins()
* @see Pico::getPlugin()
*
* @return object[]|null
*/
public function getPlugins()
{
return $this->plugins;
}
/**
* Loads config.yml and any other *.yml from Pico::$configDir
*
* After loading {@path "config/config.yml"}, Pico proceeds with any other
* existing `config/*.yml` file in alphabetical order. The file order is
* crucial: Config values which have been set already, cannot be
* overwritten by a succeeding file. This is also true for arrays, i.e.
* when specifying `test: { foo: bar }` in `config/a.yml` and
* `test: { baz: 42 }` in `config/b.yml`, `{{ config.test.baz }}` will be
* undefined!
*
* @see Pico::setConfig()
* @see Pico::getConfig()
*/
protected function loadConfig()
{
// load config closure
$yamlParser = $this->getYamlParser();
$loadConfigClosure = function ($configFile) use ($yamlParser) {
$yaml = file_get_contents($configFile);
$config = $yamlParser->parse($yaml);
return is_array($config) ? $config : array();
};
// load main config file (config/config.yml)
$this->config = is_array($this->config) ? $this->config : array();
if (is_file($this->getConfigDir() . 'config.yml')) {
$this->config += $loadConfigClosure($this->getConfigDir() . 'config.yml');
}
// merge $config of config/*.yml files
$configFiles = $this->getFilesGlob($this->getConfigDir() . '*.yml');
foreach ($configFiles as $configFile) {
if ($configFile !== $this->getConfigDir() . 'config.yml') {
$this->config += $loadConfigClosure($configFile);
}
}
// merge default config
$this->config += array(
'site_title' => 'Pico',
'base_url' => null,
'rewrite_url' => null,
'debug' => null,
'timezone' => null,
'locale' => null,
'theme' => 'default',
'theme_config' => null,
'theme_meta' => null,
'themes_url' => null,
'twig_config' => null,
'date_format' => '%D %T',
'pages_order_by_meta' => 'author',
'pages_order_by' => 'alpha',
'pages_order' => 'asc',
'content_dir' => null,
'content_ext' => '.md',
'content_config' => null,
'assets_dir' => 'assets/',
'assets_url' => null,
'plugins_url' => null
);
if (!$this->config['base_url']) {
$this->config['base_url'] = $this->getBaseUrl();
} else {
$this->config['base_url'] = rtrim($this->config['base_url'], '/') . '/';
}
if ($this->config['rewrite_url'] === null) {
$this->config['rewrite_url'] = $this->isUrlRewritingEnabled();
}
if ($this->config['debug'] === null) {
$this->config['debug'] = $this->isDebugModeEnabled();
}
if (!$this->config['timezone']) {
// explicitly set a default timezone to prevent a E_NOTICE when no timezone is set;
// the `date_default_timezone_get()` function always returns a timezone, at least UTC
$this->config['timezone'] = @date_default_timezone_get();
}
date_default_timezone_set($this->config['timezone']);
if ($this->config['locale'] !== null) {
setlocale(LC_ALL, $this->config['locale']);
}
if (!$this->config['plugins_url']) {
$this->config['plugins_url'] = $this->getUrlFromPath($this->getPluginsDir());
} else {
$this->config['plugins_url'] = $this->getAbsoluteUrl($this->config['plugins_url']);
}
if (!$this->config['themes_url']) {
$this->config['themes_url'] = $this->getUrlFromPath($this->getThemesDir());
} else {
$this->config['themes_url'] = $this->getAbsoluteUrl($this->config['themes_url']);
}
if (!$this->config['content_dir']) {
// try to guess the content directory
if (is_file($this->getRootDir() . 'content/index' . $this->config['content_ext'])) {
$this->config['content_dir'] = $this->getRootDir() . 'content/';
} elseif (is_file($this->getRootDir() . 'content-sample/index' . $this->config['content_ext'])) {
$this->config['content_dir'] = $this->getRootDir() . 'content-sample/';
} else {