forked from WonderCMS/wondercms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
3068 lines (2803 loc) · 96.7 KB
/
index.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
/**
* @package WonderCMS
* @author Robert Isoski (https://robert.si)
* @see https://www.wondercms.com
* @license MIT
*/
session_start();
define('VERSION', '3.4.3');
mb_internal_encoding('UTF-8');
if (defined('PHPUNIT_TESTING') === false) {
$Wcms = new Wcms();
$Wcms->init();
$Wcms->render();
}
class Wcms
{
private const MODULES_JSON_VERSION = 1;
private const THEMES_DIR = 'themes';
private const PLUGINS_DIR = 'plugins';
private const VALID_DIRS = [self::THEMES_DIR, self::PLUGINS_DIR];
private const THEME_PLUGINS_TYPES = [
'installs' => 'install',
'updates' => 'update',
'exists' => 'exist',
];
/** Database main keys */
public const DB_CONFIG = 'config';
public const DB_MENU_ITEMS = 'menuItems';
public const DB_MENU_ITEMS_SUBPAGE = 'subpages';
public const DB_PAGES_KEY = 'pages';
public const DB_PAGES_SUBPAGE_KEY = 'subpages';
/** @var int MIN_PASSWORD_LENGTH minimum number of characters */
public const MIN_PASSWORD_LENGTH = 8;
/** @var string WCMS_REPO - repo URL */
public const WCMS_REPO = 'https://raw.githubusercontent.com/WonderCMS/wondercms/main/';
/** @var string WCMS_CDN_REPO - CDN repo URL */
public const WCMS_CDN_REPO = 'https://raw.githubusercontent.com/WonderCMS/wondercms-cdn-files/main/';
/** @var string $currentPage - current page */
public $currentPage = '';
/** @var array $currentPageTree - Tree hierarchy of the current page */
public $currentPageTree = [];
/** @var array $installedPlugins - Currently installed plugins */
public $installedPlugins = [];
/** @var bool $currentPageExists - check if current page exists */
public $currentPageExists = false;
/** @var object $db - content of database.js */
protected $db;
/** @var bool $loggedIn - check if admin is logged in */
public $loggedIn = false;
/** @var array $listeners for hooks */
public $listeners = [];
/** @var string $dataPath path to data folder */
public $dataPath;
/** @var string $modulesCachePath path to cached json file with Themes/Plugins data */
protected $modulesCachePath;
/** @var string $securityCachePath path to security json file with force https caching data */
protected $securityCachePath;
/** @var string $dbPath path to database.js */
protected $dbPath;
/** @var string $filesPath path to uploaded files */
public $filesPath;
/** @var string $rootDir root dir of the install (where index.php is) */
public $rootDir;
/** @var bool $headerResponseDefault read default header response */
public $headerResponseDefault = true;
/** @var string $headerResponse header status */
public $headerResponse = 'HTTP/1.0 200 OK';
/**
* Constructor
*
* @param string $dataFolder
* @param string $filesFolder
* @param string $dbName
* @param string $rootDir
* @throws Exception
*/
public function __construct(
string $dataFolder = 'data',
string $filesFolder = 'files',
string $dbName = 'database.js',
string $rootDir = __DIR__
) {
$this->rootDir = $rootDir;
$this->setPaths($dataFolder, $filesFolder, $dbName);
$this->db = $this->getDb();
}
/**
* Setting default paths
*
* @param string $dataFolder
* @param string $filesFolder
* @param string $dbName
*/
public function setPaths(
string $dataFolder = 'data',
string $filesFolder = 'files',
string $dbName = 'database.js'
): void {
$this->dataPath = sprintf('%s/%s', $this->rootDir, $dataFolder);
$this->dbPath = sprintf('%s/%s', $this->dataPath, $dbName);
$this->filesPath = sprintf('%s/%s', $this->dataPath, $filesFolder);
$this->modulesCachePath = sprintf('%s/%s', $this->dataPath, 'cache.json');
$this->securityCachePath = sprintf('%s/%s', $this->dataPath, 'security.json');
}
/**
* Init function called on each page load
*
* @return void
* @throws Exception
*/
public function init(): void
{
$this->forceSSL();
$this->loginStatus();
$this->getSiteLanguage();
$this->pageStatus();
$this->logoutAction();
$this->loginAction();
$this->notFoundResponse();
$this->loadPlugins();
if ($this->loggedIn) {
$this->manuallyRefreshCacheData();
$this->addCustomModule();
$this->installUpdateModuleAction();
$this->changePasswordAction();
$this->deleteFileModuleAction();
$this->changePageThemeAction();
$this->backupAction();
$this->forceHttpsAction();
$this->saveChangesPopupAction();
$this->saveLogoutToLoginScreenAction();
$this->deletePageAction();
$this->saveAction();
$this->updateAction();
$this->uploadFileAction();
$this->notifyAction();
}
}
/**
* Set site language based on logged-in user
* @return string
* @throws Exception
*/
public function getSiteLanguage(): string
{
if ($this->loggedIn) {
$lang = $this->get('config', 'adminLang');
} else {
$lang = $this->get('config', 'siteLang');
}
if (gettype($lang) === 'object' && empty(get_object_vars($lang))) {
$lang = 'en';
$this->set('config', 'siteLang', $lang);
$this->set('config', 'adminLang', $lang);
}
return $lang;
}
/**
* Display the HTML. Called after init()
* @return void
*/
public function render(): void
{
header($this->headerResponse);
// Alert admin that page is hidden
if ($this->loggedIn) {
$loadingPage = null;
foreach ($this->get('config', 'menuItems') as $item) {
if ($this->currentPage === $item->slug) {
$loadingPage = $item;
}
}
if ($loadingPage && $loadingPage->visibility === 'hide') {
$this->alert('info',
'This page (' . $this->currentPage . ') is currently hidden from the menu. <a data-toggle="wcms-modal" href="#settingsModal" data-target-tab="#menu"><b>Open menu visibility settings</b></a>');
}
}
$this->loadThemeAndFunctions();
}
/**
* Function used by plugins to add a hook
*
* @param string $hook
* @param callable $functionName
*/
public function addListener(string $hook, callable $functionName): void
{
$this->listeners[$hook][] = $functionName;
}
/**
* Add alert message for admin
*
* @param string $class see bootstrap alerts classes
* @param string $message the message to display
* @param bool $sticky can it be closed?
* @return void
*/
public function alert(string $class, string $message, bool $sticky = false): void
{
if (isset($_SESSION['alert'][$class])) {
foreach ($_SESSION['alert'][$class] as $v) {
if ($v['message'] === $message) {
return;
}
}
}
$_SESSION['alert'][$class][] = ['class' => $class, 'message' => $this->hook('alert', $message)[0], 'sticky' => $sticky];
}
/**
* Display alert message to the admin
* @return string
*/
public function alerts(): string
{
if (!isset($_SESSION['alert'])) {
return '';
}
$output = '<div id="alertWrapperId" class="alertWrapper" style="">';
$output .= '<script>
const displayAlerts = localStorage.getItem("displayAlerts");
if (displayAlerts === "false") {
const alertWrapper = document.getElementById("alertWrapperId");
if (alertWrapper) {
alertWrapper.style.display = "none";
}
}
</script>';
foreach ($_SESSION['alert'] as $alertClass) {
foreach ($alertClass as $alert) {
$output .= '<div class="alert alert-'
. $alert['class']
. (!$alert['sticky'] ? ' alert-dismissible' : '')
. '">'
. (!$alert['sticky'] ? '<button type="button" class="close" data-dismiss="alert" onclick="parentNode.remove();">×</button>' : '')
. $alert['message']
. $this->hideAlerts();
}
}
$output .= '</div>';
unset($_SESSION['alert']);
return $output;
}
/**
* Allow admin to dismiss alerts
* @return string
*/
public function hideAlerts(): string
{
if (!$this->loggedIn) {
return '';
}
$output = '';
$output .= '<br><a href="" onclick="localStorage.setItem(\'displayAlerts\', \'false\');"><small>Hide all alerts until next login</small></a></div>';
return $output;
}
/**
* Get an asset (returns URL of the asset)
*
* @param string $location
* @return string
*/
public function asset(string $location): string
{
return self::url('themes/' . $this->get('config', 'theme') . '/' . $location);
}
/**
* Backup whole WonderCMS installation
*
* @return void
* @throws Exception
*/
public function backupAction(): void
{
if (!$this->loggedIn) {
return;
}
$backupList = glob($this->filesPath . '/*-backup-*.zip');
if (!empty($backupList)) {
$this->alert('danger',
'Backup files detected. <a data-toggle="wcms-modal" href="#settingsModal" data-target-tab="#files"><b>View and delete unnecessary backup files</b></a>');
}
if (isset($_POST['backup']) && $this->verifyFormActions()) {
$this->zipBackup();
}
}
/**
* Save if WCMS should force https
* @return void
* @throws Exception
*/
public function forceHttpsAction(): void
{
if (isset($_POST['forceHttps']) && $this->verifyFormActions()) {
$this->set('config', 'forceHttps', $_POST['forceHttps'] === 'true');
$this->updateSecurityCache();
$this->alert('success', 'Force HTTPs was successfully changed.');
$this->redirect();
}
}
/**
* Save if WCMS should show the popup before saving the page content changes
* @return void
* @throws Exception
*/
public function saveChangesPopupAction(): void
{
if (isset($_POST['saveChangesPopup']) && $this->verifyFormActions()) {
$this->set('config', 'saveChangesPopup', $_POST['saveChangesPopup'] === 'true');
$this->alert('success', 'Saving the confirmation popup settings changed.');
$this->redirect();
}
}
/**
* Save if admin should be redirected to login/last viewed page after logging out.
* @return void
* @throws Exception
*/
public function saveLogoutToLoginScreenAction(): void
{
if (isset($_POST['logoutToLoginScreen']) && $this->verifyFormActions()) {
$redirectToLogin = $_POST['logoutToLoginScreen'] === 'true';
$message = $redirectToLogin
? 'You will be redirected to login screen after logging out.'
: 'You will be redirected to last viewed screen after logging out.';
$this->set('config', 'logoutToLoginScreen', $_POST['logoutToLoginScreen'] === 'true');
$this->alert('success', $message);
$this->redirect();
}
}
/**
* Update cache for security settings.
* @return void
*/
public function updateSecurityCache(): void
{
$content = ['forceHttps' => $this->isHttpsForced()];
$json = json_encode($content, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
file_put_contents($this->securityCachePath, $json, LOCK_EX);
}
/**
* Get a static block
*
* @param string $key name of the block
* @return string
*/
public function block(string $key): string
{
$blocks = $this->get('blocks');
$content = '';
if (isset($blocks->{$key})) {
$content = $this->loggedIn
? $this->editable($key, $blocks->{$key}->content, 'blocks')
: $blocks->{$key}->content;
}
return $this->hook('block', $content, $key)[0];
}
/**
* Change password
* @return void
* @throws Exception
*/
public function changePasswordAction(): void
{
if (isset($_POST['old_password'], $_POST['new_password'], $_POST['repeat_password'])
&& $_SESSION['token'] === $_POST['token']
&& $this->loggedIn
&& $this->hashVerify($_POST['token'])) {
if (!password_verify($_POST['old_password'], $this->get('config', 'password'))) {
$this->alert('danger',
'Wrong password. <a data-toggle="wcms-modal" href="#settingsModal" data-target-tab="#security"><b>Re-open security settings</b></a>');
$this->redirect();
return;
}
if (strlen($_POST['new_password']) < self::MIN_PASSWORD_LENGTH) {
$this->alert('danger',
sprintf('Password must be longer than %d characters. <a data-toggle="wcms-modal" href="#settingsModal" data-target-tab="#security"><b>Re-open security settings</b></a>',
self::MIN_PASSWORD_LENGTH));
$this->redirect();
return;
}
if ($_POST['new_password'] !== $_POST['repeat_password']) {
$this->alert('danger',
'New passwords do not match. <a data-toggle="wcms-modal" href="#settingsModal" data-target-tab="#security"><b>Re-open security settings</b></a>');
$this->redirect();
return;
}
$this->set('config', 'password', password_hash($_POST['new_password'], PASSWORD_DEFAULT));
$this->set('config', 'forceLogout', true);
$this->logoutAction(true);
$this->alert('success', '<center><b>Password changed. Log in again.</b></center>', 1);
}
}
/**
* Check if folders are writable
* Executed once before creating the database file
*
* @param string $folder the relative path of the folder to check/create
* @return void
* @throws Exception
*/
public function checkFolder(string $folder): void
{
if (!is_dir($folder) && !mkdir($folder, 0755) && !is_dir($folder)) {
throw new Exception('Could not create data folder.');
}
if (!is_writable($folder)) {
throw new Exception('Could write to data folder.');
}
}
/**
* Initialize the JSON database if it doesn't exist
* @return void
* @throws Exception
*/
public function createDb(): void
{
// Check php requirements
$this->checkMinimumRequirements();
$password = $this->generatePassword();
$this->db = (object)[
self::DB_CONFIG => [
'siteTitle' => 'Website title',
'siteLang' => 'en',
'adminLang' => 'en',
'theme' => 'sky',
'defaultPage' => 'home',
'login' => 'loginURL',
'forceLogout' => false,
'forceHttps' => false,
'saveChangesPopup' => false,
'password' => password_hash($password, PASSWORD_DEFAULT),
'lastLogins' => [],
'lastModulesSync' => null,
'customModules' => $this->defaultCustomModules(),
'menuItems' => [
'0' => [
'name' => 'Home',
'slug' => 'home',
'visibility' => 'show',
self::DB_MENU_ITEMS_SUBPAGE => new stdClass()
],
'1' => [
'name' => 'How to',
'slug' => 'how-to',
'visibility' => 'show',
self::DB_MENU_ITEMS_SUBPAGE => new stdClass()
]
]
],
'pages' => [
'404' => [
'title' => '404',
'keywords' => '404',
'description' => '404',
'content' => '<center><h1>404 - Page not found</h1></center>',
self::DB_PAGES_SUBPAGE_KEY => new stdClass()
],
'home' => [
'title' => 'Home',
'keywords' => 'Enter, page, keywords, for, search, engines',
'description' => 'A page description is also good for search engines.',
'content' => '<h1>Welcome to your website</h1>
<p>Your password for editing everything is: <b>' . $password . '</b></p>
<p><a href="' . self::url('loginURL') . '" class="button">Click here to login</a></p>
<p>To install an awesome editor, open Settings/Plugins and click Install Summernote.</p>',
self::DB_PAGES_SUBPAGE_KEY => new stdClass()
],
'how-to' => [
'title' => 'How to',
'keywords' => 'Enter, keywords, for, this page',
'description' => 'A page description is also good for search engines.',
'content' => '<h2>Easy editing</h2>
<p>After logging in, click anywhere to edit and click outside to save. Changes are live and shown immediately.</p>
<h2>Create new page</h2>
<p>Pages can be created in the Settings.</p>
<h2>Start a blog or change your theme</h2>
<p>To install, update or remove themes/plugins, visit the Settings.</p>
<h2><b>Support WonderCMS</b></h2>
<p>WonderCMS is free for over 12 years.<br>
<a href="https://swag.wondercms.com" target="_blank"><u>Click here to support us by getting a T-shirt</u></a> or <a href="https://www.wondercms.com/donate" target="_blank"><u>with a donation</u></a>.</p>',
self::DB_PAGES_SUBPAGE_KEY => new stdClass()
]
],
'blocks' => [
'subside' => [
'content' => '<h2>About your website</h2>
<br>
<p>Website description, contact form, mini map or anything else.</p>
<p>This editable area is visible on all pages.</p>'
],
'footer' => [
'content' => '©' . date('Y') . ' Your website'
]
]
];
$this->save();
}
/**
* Default data for the Custom Modules
* @return array[]
*/
private function defaultCustomModules(): array {
return [
'themes' => [],
'plugins' => []
];
}
/**
* Create menu item
*
* @param string $name
* @param string|null $menu
* @param bool $createPage
* @param string $visibility show or hide
* @return void
* @throws Exception
*/
public function createMenuItem(
string $name,
string $menu = null,
string $visibility = 'hide',
bool $createPage = false
): void {
if (!in_array($visibility, ['show', 'hide'], true)) {
return;
}
$name = empty($name) ? 'empty' : str_replace([PHP_EOL, '<br>'], '', $name);
$slug = $this->createUniqueSlug($name, $menu);
$menuItems = $menuSelectionObject = clone $this->get(self::DB_CONFIG, self::DB_MENU_ITEMS);
$menuTree = !empty($menu) || $menu === '0' ? explode('-', $menu) : [];
$slugTree = [];
if (count($menuTree)) {
foreach ($menuTree as $childMenuKey) {
$childMenu = $menuSelectionObject->{$childMenuKey};
if (!property_exists($childMenu, self::DB_MENU_ITEMS_SUBPAGE)) {
$childMenu->{self::DB_MENU_ITEMS_SUBPAGE} = new StdClass;
}
$menuSelectionObject = $childMenu->{self::DB_MENU_ITEMS_SUBPAGE};
$slugTree[] = $childMenu->slug;
}
}
$slugTree[] = $slug;
$menuCount = count(get_object_vars($menuSelectionObject));
$menuSelectionObject->{$menuCount} = new stdClass;
$menuSelectionObject->{$menuCount}->name = $name;
$menuSelectionObject->{$menuCount}->slug = $slug;
$menuSelectionObject->{$menuCount}->visibility = $visibility;
$menuSelectionObject->{$menuCount}->{self::DB_MENU_ITEMS_SUBPAGE} = new StdClass;
$this->set(self::DB_CONFIG, self::DB_MENU_ITEMS, $menuItems);
if ($createPage) {
$this->createPage($slugTree);
$_SESSION['redirect_to_name'] = $name;
$_SESSION['redirect_to'] = implode('/', $slugTree);
}
}
/**
* Update menu item
*
* @param string $name
* @param string $menu
* @param string $visibility show or hide
* @return void
* @throws Exception
*/
public function updateMenuItem(string $name, string $menu, string $visibility = 'hide'): void
{
if (!in_array($visibility, ['show', 'hide'], true)) {
return;
}
$name = empty($name) ? 'empty' : str_replace([PHP_EOL, '<br>'], '', $name);
$slug = $this->createUniqueSlug($name, $menu);
$menuItems = $menuSelectionObject = clone $this->get(self::DB_CONFIG, self::DB_MENU_ITEMS);
$menuTree = explode('-', $menu);
$slugTree = [];
$menuKey = array_pop($menuTree);
if (count($menuTree) > 0) {
foreach ($menuTree as $childMenuKey) {
$childMenu = $menuSelectionObject->{$childMenuKey};
if (!property_exists($childMenu, self::DB_MENU_ITEMS_SUBPAGE)) {
$childMenu->{self::DB_MENU_ITEMS_SUBPAGE} = new StdClass;
}
$menuSelectionObject = $childMenu->{self::DB_MENU_ITEMS_SUBPAGE};
$slugTree[] = $childMenu->slug;
}
}
$slugTree[] = $menuSelectionObject->{$menuKey}->slug;
$menuSelectionObject->{$menuKey}->name = $name;
$menuSelectionObject->{$menuKey}->slug = $slug;
$menuSelectionObject->{$menuKey}->visibility = $visibility;
$menuSelectionObject->{$menuKey}->{self::DB_MENU_ITEMS_SUBPAGE} = $menuSelectionObject->{$menuKey}->{self::DB_MENU_ITEMS_SUBPAGE} ?? new StdClass;
$this->set(self::DB_CONFIG, self::DB_MENU_ITEMS, $menuItems);
$this->updatePageSlug($slugTree, $slug);
if ($this->get(self::DB_CONFIG, 'defaultPage') === implode('/', $slugTree)) {
// Change old slug with new one
array_pop($slugTree);
$slugTree[] = $slug;
$this->set(self::DB_CONFIG, 'defaultPage', implode('/', $slugTree));
}
}
/**
* Check if slug already exists and creates unique one
*
* @param string $slug
* @param string|null $menu
* @return string
*/
public function createUniqueSlug(string $slug, string $menu = null): string
{
$slug = $this->slugify($slug);
$allMenuItems = $this->get(self::DB_CONFIG, self::DB_MENU_ITEMS);
$menuCount = count(get_object_vars($allMenuItems));
// Check if it is subpage
$menuTree = $menu ? explode('-', $menu) : [];
if (count($menuTree)) {
foreach ($menuTree as $childMenuKey) {
$allMenuItems = $allMenuItems->{$childMenuKey}->subpages;
}
}
foreach ($allMenuItems as $value) {
if ($value->slug === $slug) {
$slug .= '-' . $menuCount;
break;
}
}
return $slug;
}
/**
* Create new page
*
* @param array|null $slugTree
* @param bool $createMenuItem
* @return void
* @throws Exception
*/
public function createPage(array $slugTree = null, bool $createMenuItem = false): void
{
$pageExists = false;
$pageData = null;
foreach ($slugTree as $parentPage) {
if (!$pageData) {
$pageData = $this->get(self::DB_PAGES_KEY)->{$parentPage};
continue;
}
$pageData = $pageData->subpages->{$parentPage} ?? null;
$pageExists = !empty($pageData);
}
if ($pageExists) {
$this->alert('danger', 'Cannot create page with existing slug.');
return;
}
$slug = array_pop($slugTree);
$pageSlug = $slug ?: $this->slugify($this->currentPage);
$allPages = $selectedPage = clone $this->get(self::DB_PAGES_KEY);
$menuKey = null;
if (!empty($slugTree)) {
foreach ($slugTree as $childSlug) {
// Find menu key tree
if ($createMenuItem) {
$menuKey = $this->findAndUpdateMenuKey($menuKey, $childSlug);
}
// Create new parent page if it doesn't exist
if (!$selectedPage->{$childSlug}) {
$parentTitle = mb_convert_case(str_replace('-', ' ', $childSlug), MB_CASE_TITLE);
$selectedPage->{$childSlug}->title = $parentTitle;
$selectedPage->{$childSlug}->keywords = 'Keywords, are, good, for, search, engines';
$selectedPage->{$childSlug}->description = 'A short description is also good.';
if ($createMenuItem) {
$this->createMenuItem($parentTitle, $menuKey);
$menuKey = $this->findAndUpdateMenuKey($menuKey, $childSlug); // Add newly added menu key
}
}
if (!property_exists($selectedPage->{$childSlug}, self::DB_PAGES_SUBPAGE_KEY)) {
$selectedPage->{$childSlug}->{self::DB_PAGES_SUBPAGE_KEY} = new StdClass;
}
$selectedPage = $selectedPage->{$childSlug}->{self::DB_PAGES_SUBPAGE_KEY};
}
}
$pageTitle = !$slug ? str_replace('-', ' ', $pageSlug) : $pageSlug;
$selectedPage->{$slug} = new stdClass;
$selectedPage->{$slug}->title = mb_convert_case($pageTitle, MB_CASE_TITLE);
$selectedPage->{$slug}->keywords = 'Keywords, are, good, for, search, engines';
$selectedPage->{$slug}->description = 'A short description is also good.';
$selectedPage->{$slug}->{self::DB_PAGES_SUBPAGE_KEY} = new StdClass;
$this->set(self::DB_PAGES_KEY, $allPages);
if ($createMenuItem) {
$this->createMenuItem($pageTitle, $menuKey);
}
}
/**
* Find and update menu key tree based on newly requested slug
* @param string|null $menuKey
* @param string $slug
* @return string
*/
private function findAndUpdateMenuKey(?string $menuKey, string $slug): string
{
$menuKeys = $menuKey !== null ? explode('-', $menuKey) : $menuKey;
$menuItems = json_decode(json_encode($this->get(self::DB_CONFIG, self::DB_MENU_ITEMS)), true);
foreach ($menuKeys as $key) {
$menuItems = $menuItems[$key][self::DB_MENU_ITEMS_SUBPAGE] ?? [];
}
if (false !== ($index = array_search($slug, array_column($menuItems, 'slug'), true))) {
$menuKey = $menuKey === null ? $index : $menuKey . '-' . $index;
} elseif ($menuKey === null) {
$menuKey = count($menuItems);
}
return $menuKey;
}
/**
* Update page data
*
* @param array $slugTree
* @param string $fieldname
* @param string $content
* @return void
* @throws Exception
*/
public function updatePage(array $slugTree, string $fieldname, string $content): void
{
$slug = array_pop($slugTree);
$allPages = $selectedPage = clone $this->get(self::DB_PAGES_KEY);
if (!empty($slugTree)) {
foreach ($slugTree as $childSlug) {
if (!property_exists($selectedPage->{$childSlug}, self::DB_PAGES_SUBPAGE_KEY)) {
$selectedPage->{$childSlug}->{self::DB_PAGES_SUBPAGE_KEY} = new StdClass;
}
$selectedPage = $selectedPage->{$childSlug}->{self::DB_PAGES_SUBPAGE_KEY};
}
}
$selectedPage->{$slug}->{$fieldname} = $content;
$this->set(self::DB_PAGES_KEY, $allPages);
}
/**
* Delete page key
*
* @param array $slugTree
* @param string $fieldname
*
* @return void
* @throws Exception
*/
public function deletePageKey(array $slugTree, string $fieldname): void
{
$slug = array_pop($slugTree);
$selectedPage = clone $this->get(self::DB_PAGES_KEY);
if (!empty($slugTree)) {
foreach ($slugTree as $childSlug) {
if (!property_exists($selectedPage->{$childSlug}, self::DB_PAGES_SUBPAGE_KEY)) {
$selectedPage->{$childSlug}->{self::DB_PAGES_SUBPAGE_KEY} = new StdClass;
}
$selectedPage = $selectedPage->{$childSlug}->{self::DB_PAGES_SUBPAGE_KEY};
}
}
unset($selectedPage->{$slug}->{$fieldname});
$this->save();
}
/**
* Delete existing page by slug
*
* @param array|null $slugTree
* @throws Exception
*/
public function deletePageFromDb(array $slugTree = null): void
{
$slug = array_pop($slugTree);
$selectedPage = $this->db->{self::DB_PAGES_KEY};
if (!empty($slugTree)) {
foreach ($slugTree as $childSlug) {
$selectedPage = $selectedPage->{$childSlug}->subpages;
}
}
unset($selectedPage->{$slug});
$this->save();
}
/**
* Update existing page slug
*
* @param array $slugTree
* @param string $newSlugName
* @throws Exception
*/
public function updatePageSlug(array $slugTree, string $newSlugName): void
{
$slug = array_pop($slugTree);
$selectedPage = $this->db->{self::DB_PAGES_KEY};
if (!empty($slugTree)) {
foreach ($slugTree as $childSlug) {
$selectedPage = $selectedPage->{$childSlug}->subpages;
}
}
$selectedPage->{$newSlugName} = $selectedPage->{$slug};
unset($selectedPage->{$slug});
$this->save();
}
/**
* Load CSS and enable plugins to load CSS
* @return string
*/
public function css(): string
{
if ($this->loggedIn) {
$styles = <<<'EOT'
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/WonderCMS/[email protected]/wcms-admin.min.css" crossorigin="anonymous">
EOT;
return $this->hook('css', $styles)[0];
}
return $this->hook('css', '')[0];
}
/**
* Get database content
* @return stdClass
* @throws Exception
*/
public function getDb(): stdClass
{
// initialize database if it doesn't exist
if (!file_exists($this->dbPath)) {
// this code only runs one time (on first page load/install)
$this->checkFolder(dirname($this->dbPath));
$this->checkFolder($this->filesPath);
$this->checkFolder($this->rootDir . '/' . self::THEMES_DIR);
$this->checkFolder($this->rootDir . '/' . self::PLUGINS_DIR);
$this->createDb();
}
return json_decode(file_get_contents($this->dbPath), false);
}
/**
* Get data from any json file
* @param string $path
* @return stdClass|null
*/
public function getJsonFileData(string $path): ?array
{
if (is_file($path) && file_exists($path)) {
return json_decode(file_get_contents($path), true);
}
return null;
}
/**
* Delete theme
* @return void
*/
public function deleteFileModuleAction(): void
{
if (!$this->loggedIn) {
return;
}
if (isset($_REQUEST['deleteModule'], $_REQUEST['type']) && $this->verifyFormActions(true)) {
$allowedDeleteTypes = ['files', 'plugins', 'themes'];
$filename = str_ireplace(
['/', './', '../', '..', '~', '~/', '\\'],
null,
trim($_REQUEST['deleteModule'])
);
$type = str_ireplace(
['/', './', '../', '..', '~', '~/', '\\'],
null,
trim($_REQUEST['type'])
);
if (!in_array($type, $allowedDeleteTypes, true)) {
$this->alert('danger',
'Wrong delete folder path.');
$this->redirect();
}
if ($filename === $this->get('config', 'theme')) {
$this->alert('danger',
'Cannot delete currently active theme. <a data-toggle="wcms-modal" href="#settingsModal" data-target-tab="#themes"><b>Re-open theme settings</b></a>');
$this->redirect();
}
$folder = $type === 'files' ? $this->filesPath : sprintf('%s/%s', $this->rootDir, $type);
$path = realpath("{$folder}/{$filename}");
if (file_exists($path)) {
$this->recursiveDelete($path);
$this->alert('success', "Deleted {$filename}.");
$this->redirect();
}
}
}
public function changePageThemeAction(): void
{
if (isset($_REQUEST['selectModule'], $_REQUEST['type']) && $this->verifyFormActions(true)) {
$theme = $_REQUEST['selectModule'];
if (!is_dir($this->rootDir . '/' . $_REQUEST['type'] . '/' . $theme)) {
return;
}
$this->set('config', 'theme', $theme);
$this->redirect();
}
}
/**
* Delete page
* @return void
* @throws Exception