forked from WonderCMS/wondercms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
2172 lines (2033 loc) · 70.6 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
* @see https://www.wondercms.com
* @license MIT
*/
session_start();
define('VERSION', '3.1.4');
mb_internal_encoding('UTF-8');
if (defined('PHPUNIT_TESTING') === false) {
$Wcms = new Wcms();
$Wcms->init();
$Wcms->render();
}
class Wcms
{
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',
];
/** @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/robiso/wondercms/master/';
/** @var string WCMS_CDN_REPO - CDN repo URL */
public const WCMS_CDN_REPO = 'https://raw.githubusercontent.com/robiso/wondercms-cdn-files/master/';
/** @var string $currentPage - current page */
public $currentPage = '';
/** @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 $themesPluginsCachePath path to cached json file with Themes/Plugins data */
protected $themesPluginsCachePath;
/** @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->themesPluginsCachePath = sprintf('%s/%s', $this->dataPath, 'cache.json');
}
/**
* Init function called on each page load
*
* @return void
* @throws Exception
*/
public function init(): void
{
$this->pageStatus();
$this->loginStatus();
$this->logoutAction();
$this->loginAction();
$this->notFoundResponse();
$this->loadPlugins();
if ($this->loggedIn) {
$this->manuallyRefreshCacheData();
$this->addCustomThemePluginRepository();
$this->installUpdateThemePluginAction();
$this->changePasswordAction();
$this->deleteFileThemePluginAction();
$this->changePageThemeAction();
$this->backupAction();
$this->betterSecurityAction();
$this->deletePageAction();
$this->saveAction();
$this->updateAction();
$this->uploadFileAction();
$this->notifyAction();
}
}
/**
* 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' => $message, 'sticky' => $sticky];
}
/**
* Display alert message to the admin
* @return string
*/
public function alerts(): string
{
if (!isset($_SESSION['alert'])) {
return '';
}
$output = '';
$output .= '<div class="alertWrapper">';
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">×</button>' : '')
. $alert['message']
. '</div>';
}
}
$output .= '</div>';
unset($_SESSION['alert']);
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();
}
}
/**
* Replace the .htaccess with one adding security settings
* @return void
*/
public function betterSecurityAction(): void
{
if (isset($_POST['betterSecurity']) && $this->verifyFormActions()) {
if ($_POST['betterSecurity'] === 'on') {
if ($contents = $this->getFileFromRepo('htaccess-ultimate', self::WCMS_CDN_REPO)) {
file_put_contents('.htaccess', trim($contents));
}
$this->alert('success', 'Improved security turned ON.');
$this->redirect();
} elseif ($_POST['betterSecurity'] === 'off') {
if ($contents = $this->getFileFromRepo('htaccess', self::WCMS_CDN_REPO)) {
file_put_contents('.htaccess', trim($contents));
}
$this->alert('success', 'Improved security turned OFF.');
$this->redirect();
}
}
}
/**
* 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
*/
public function changePasswordAction(): void
{
if (isset($_POST['old_password'], $_POST['new_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;
}
$this->set('config', 'password', password_hash($_POST['new_password'], PASSWORD_DEFAULT));
$this->set('config', 'forceLogout', true);
$this->logoutAction(true);
}
}
/**
* Check if we can run WonderCMS properly
* 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 doesn't exist
* @return void
*/
public function createDb(): void
{
// Check php requirements
$this->checkMinimumRequirements();
$password = $this->generatePassword();
$this->db = (object)[
'config' => [
'siteTitle' => 'Website title',
'theme' => 'essence',
'defaultPage' => 'home',
'login' => 'loginURL',
'forceLogout' => false,
'password' => password_hash($password, PASSWORD_DEFAULT),
'lastLogins' => [],
'defaultRepos' => [
'themes' => [],
'plugins' => [],
'lastSync' => null,
],
'customRepos' => [
'themes' => [],
'plugins' => []
],
'menuItems' => [
'0' => [
'name' => 'Home',
'slug' => 'home',
'visibility' => 'show'
],
'1' => [
'name' => 'Example',
'slug' => 'example',
'visibility' => 'show'
]
]
],
'pages' => [
'404' => [
'title' => '404',
'keywords' => '404',
'description' => '404',
'content' => '<h1>Sorry, page not found. :(</h1>'
],
'home' => [
'title' => 'Home',
'keywords' => 'Keywords, are, good, for, search, engines',
'description' => 'A short description is also good.',
'content' => '<h1>It\'s alive!</h1>
<h4><a href="' . self::url('loginURL') . '">Click here to login.</a> Your password is: <b>' . $password . '</b></a></h4>
<p class="mt-4">To install an awesome editor, open Settings -> Plugins -> Install Summernote.</p>'
],
'example' => [
'title' => 'Example',
'keywords' => 'Keywords, are, good, for, search, engines',
'description' => 'A short description is also good.',
'content' => '<h1 class="mb-3">Easy editing</h1>
<p>Click anywhere to edit, click outside the area to save. Changes are live and shown immediately.</p>
<h2 class="mt-5 mb-3">Create new page</h2>
<p>Pages can be created in the Menu above.</p>
<h2 class="mt-5 mb-3">Install themes and plugins</h2>
<p>To install, update or remove themes/plugins, visit the Settings.</p>
<h2 class="mt-5 mb-3"><b>Please support WonderCMS</b></h2>
<p>WonderCMS has been free for over 10 years.</p>
<p><a href="https://swag.wondercms.com"><u>Click here to support us by getting a t-shirt</u></a> or <a href="https://www.wondercms.com/donate"><u>here to donate</u></a>.</p>'
]
],
'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();
}
/**
* Create menu item
*
* @param string $content
* @param string $menu
* @param string $visibility show or hide
* @return void
* @throws Exception
*/
public function createMenuItem(string $content, string $menu, string $visibility = 'hide'): void
{
$conf = 'config';
$field = 'menuItems';
$exist = is_numeric($menu);
$content = empty($content) ? 'empty' : str_replace([PHP_EOL, '<br>'], '', $content);
$slug = $this->slugify($content);
$menuCount = count(get_object_vars($this->get($conf, $field)));
$db = $this->getDb();
foreach ($db->config->{$field} as $value) {
if ($value->slug === $slug) {
$slug .= '-' . $menuCount;
break;
}
}
if (!$exist) {
$this->set($conf, $field, $menuCount, new StdClass);
$this->set($conf, $field, $menuCount, 'name', str_replace('-', ' ', $content));
$this->set($conf, $field, $menuCount, 'slug', $slug);
$this->set($conf, $field, $menuCount, 'visibility', $visibility);
if ($menu) {
$this->createPage($slug);
$_SESSION['redirect_to_name'] = $content;
$_SESSION['redirect_to'] = $slug;
}
} else {
$oldSlug = $this->get($conf, $field, $menu, 'slug');
$this->set($conf, $field, $menu, 'name', $content);
$this->set($conf, $field, $menu, 'slug', $slug);
$this->set($conf, $field, $menu, 'visibility', $visibility);
$oldPageContent = $this->get('pages', $oldSlug);
$this->unset('pages', $oldSlug);
$this->set('pages', $slug, $oldPageContent);
$this->set('pages', $slug, 'title', $content);
if ($this->get('config', 'defaultPage') === $oldSlug) {
$this->set('config', 'defaultPage', $slug);
}
}
}
/**
* Create new page
*
* @param string $slug the name of the page in URL
* @return void
* @throws Exception
*/
public function createPage($slug = ''): void
{
$this->db->pages->{$slug ?: $this->currentPage} = new stdClass;
$this->save();
$pageName = $slug ?: $this->slugify($this->currentPage);
$this->set('pages', $pageName, 'title', (!$slug)
? mb_convert_case(str_replace('-', ' ', $this->currentPage), MB_CASE_TITLE)
: mb_convert_case(str_replace('-', ' ', $slug), MB_CASE_TITLE));
$this->set('pages', $pageName, 'keywords',
'Keywords, are, good, for, search, engines');
$this->set('pages', $pageName, 'description',
'A short description is also good.');
if (!$slug) {
$this->createMenuItem($this->slugify($this->currentPage), '');
}
}
/**
* 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/robiso/[email protected]/wcms-admin.min.css" integrity="sha384-/NVs/Bv65kKsmmBcoBvW2ZaxIjHtNffpV17gGDivO2CQaFW1vY6ndJFKOiB1rH7m" 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 deleteFileThemePluginAction(): void
{
if (!$this->loggedIn) {
return;
}
if (isset($_REQUEST['deleteThemePlugin'], $_REQUEST['type']) && $this->verifyFormActions(true)) {
$allowedDeleteTypes = ['files', 'plugins', 'themes'];
$filename = str_ireplace(
['/', './', '../', '..', '~', '~/', '\\'],
null,
trim($_REQUEST['deleteThemePlugin'])
);
$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['selectThemePlugin'], $_REQUEST['type']) && $this->verifyFormActions(true)) {
$theme = $_REQUEST['selectThemePlugin'];
if (!is_dir($this->rootDir . '/' . $_REQUEST['type'] . '/' . $theme)) {
return;
}
$this->set('config', 'theme', $theme);
$this->redirect();
}
}
/**
* Delete page
* @return void
*/
public function deletePageAction(): void
{
if (!isset($_GET['delete']) || !$this->verifyFormActions(true)) {
return;
}
$slug = $_GET['delete'];
if (isset($this->get('pages')->{$slug})) {
$this->unset('pages', $slug);
}
$menuItems = json_decode(json_encode($this->get('config', 'menuItems')), true);
if (false !== ($index = array_search($slug, array_column($menuItems, 'slug'), true))) {
unset($menuItems[$index]);
$newMenu = array_values($menuItems);
$this->set('config', 'menuItems', json_decode(json_encode($newMenu), false));
if ($this->get('config', 'defaultPage') === $slug) {
$allMenuItems = $this->get('config', 'menuItems') ?? [];
$firstMenuItem = reset($allMenuItems);
$this->set('config', 'defaultPage', $firstMenuItem->slug ?? $slug);
}
}
$this->alert('success', 'Page <b>' . $slug . '</b> deleted.');
$this->redirect();
}
/**
* Get editable block
*
* @param string $id id for the block
* @param string $content html content
* @param string $dataTarget
* @return string
*/
public function editable(string $id, string $content, string $dataTarget = ''): string
{
return '<div' . ($dataTarget !== '' ? ' data-target="' . $dataTarget . '"' : '') . ' id="' . $id . '" class="editText editable">' . $content . '</div>';
}
/**
* Get main website title, show edit icon if logged in
* @return string
*/
public function siteTitle(): string
{
$output = $this->get('config', 'siteTitle');
if ($this->loggedIn) {
$output .= "<a data-toggle='wcms-modal' href='#settingsModal' data-target-tab='#menu'><i class='editIcon'></i></a>";
}
return $output;
}
/**
* Get footer, make it editable and show login link if it's set to default
* @return string
*/
public function footer(): string
{
if ($this->loggedIn) {
$output = '<div data-target="blocks" id="footer" class="editText editable">' . $this->get('blocks',
'footer')->content . '</div>';
} else {
$output = $this->get('blocks', 'footer')->content .
(!$this->loggedIn && $this->get('config', 'login') === 'loginURL'
? ' • <a href="' . self::url('loginURL') . '">Login</a>'
: '');
}
return $this->hook('footer', $output)[0];
}
/**
* Generate random password
* @return string
*/
public function generatePassword(): string
{
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
return substr(str_shuffle($characters), 0, self::MIN_PASSWORD_LENGTH);
}
/**
* Get CSRF token
* @return string
* @throws Exception
*/
public function getToken(): string
{
return $_SESSION['token'] ?? $_SESSION['token'] = bin2hex(random_bytes(32));
}
/**
* Get something from database
*/
public function get()
{
$args = func_get_args();
$object = $this->db;
foreach ($args as $key => $arg) {
$object = $object->{$arg} ?? $this->set(...array_merge($args, [null]));
}
return $object;
}
/**
* Get content of a file from master branch
*
* @param string $file the file we want
* @param string $repo
* @return string
*/
public function getFileFromRepo(string $file, string $repo = self::WCMS_REPO): string
{
$repo = str_replace('https://github.com/', 'https://raw.githubusercontent.com/', $repo);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $repo . $file);
$content = curl_exec($ch);
if (false === $content) {
$this->alert('danger', 'Cannot get content from repository.');
}
curl_close($ch);
return (string)$content;
}
/**
* Get the latest version from master branch
* @param string $repo
* @return null|string
*/
public function getOfficialVersion(string $repo = self::WCMS_REPO): ?string
{
return $this->getCheckFileFromRepo('version', $repo);
}
/**
* Get the files from master branch
* @param string $fileName
* @param string $repo
* @return null|string
*/
public function getCheckFileFromRepo(string $fileName, string $repo = self::WCMS_REPO): ?string
{
$version = trim($this->getFileFromRepo($fileName, $repo));
return $version === '404: Not Found' || $version === '400: Invalid request' ? null : $version;
}
/**
* Compare token with hash_equals
*
* @param string $token
* @return bool
*/
public function hashVerify(string $token): bool
{
return hash_equals($token, $this->getToken());
}
/**
* Return hooks from plugins
* @return array
*/
public function hook(): array
{
$numArgs = func_num_args();
$args = func_get_args();
if ($numArgs < 2) {
trigger_error('Insufficient arguments', E_USER_ERROR);
}
$hookName = array_shift($args);
if (!isset($this->listeners[$hookName])) {
return $args;
}
foreach ($this->listeners[$hookName] as $func) {
$args = $func($args);
}
return $args;
}
/**
* Return array with all themes and their data
* @param string $type
* @return array
* @throws Exception
*/
public function listAllThemesPlugins(string $type = self::THEMES_DIR): array
{
$newData = [];
if ($this->loggedIn) {
$data = $this->getThemePluginCachedData($type);
foreach ($data as $repo => $addon) {
$dirName = $addon['dirName'];
$exists = is_dir($this->rootDir . "/$type/" . $dirName);
$currentVersion = $exists ? $this->getThemePluginVersion($type, $dirName) : null;
$newVersion = $addon['newVersion'];
$update = $newVersion !== null && $currentVersion !== null && $newVersion > $currentVersion;
if ($update) {
$this->alert('info',
'New ' . $type . ' update available. <b><a data-toggle="wcms-modal" href="#settingsModal" data-target-tab="#' . $type . '">Open ' . $type . '</a></b>');
}
$addonType = $exists ? self::THEME_PLUGINS_TYPES['exists'] : self::THEME_PLUGINS_TYPES['installs'];
$addonType = $update ? self::THEME_PLUGINS_TYPES['updates'] : $addonType;
$newData[$addonType][$repo] = $addon;
$newData[$addonType][$repo]['update'] = $update;
$newData[$addonType][$repo]['install'] = !$exists;
$newData[$addonType][$repo]['currentVersion'] = $currentVersion;
}
}
return $newData;
}
/**
* Get all repos from CDN
* @param string $type
* @return array
* @throws Exception
*/
public function getThemePluginRepos(string $type = self::THEMES_DIR): array
{
$db = $this->getDb();
$array = (array)$db->config->defaultRepos->{$type};
$arrayCustom = (array)$db->config->customRepos->{$type};
$data = $this->getJsonFileData($this->themesPluginsCachePath);
$lastSync = $db->config->defaultRepos->lastSync;
if (empty($array) || empty($data) || strtotime($lastSync) < strtotime('-1 days')) {
$this->updateAndCacheThemePluginRepos();
$array = (array)$db->config->defaultRepos->{$type};
}
return array_merge($array, $arrayCustom);
}
/**
* Retrieve cached Themes/Plugins data
* @param string $type
* @return array|null
* @throws Exception
*/
public function getThemePluginCachedData(string $type = self::THEMES_DIR): array
{
$this->getThemePluginRepos($type);
$data = $this->getJsonFileData($this->themesPluginsCachePath);
return $data !== null && array_key_exists($type, $data) ? $data[$type] : [];
}
/**
* Force cache refresh for updates
*/
public function manuallyRefreshCacheData(): void
{
if (!isset($_REQUEST['manuallyResetCacheData']) || !$this->verifyFormActions(true)) {
return;
}
$this->updateAndCacheThemePluginRepos();
$this->checkWcmsCoreUpdate();
$this->set('config', 'defaultRepos', 'lastSync', date('Y/m/d'));
$this->redirect();
}
/**
* Method checks for new repos and caches them
*/
private function updateAndCacheThemePluginRepos(): void
{
$plugins = trim($this->getFileFromRepo('plugins-list.json', self::WCMS_CDN_REPO));
$themes = trim($this->getFileFromRepo('themes-list.json', self::WCMS_CDN_REPO));
if ($plugins !== '404: Not Found') {
$plugins = explode("\n", $plugins);
$this->set('config', 'defaultRepos', 'plugins', $plugins);
}
if ($themes !== '404: Not Found') {
$themes = explode("\n", $themes);
$this->set('config', 'defaultRepos', 'themes', $themes);
}
$this->set('config', 'defaultRepos', 'lastSync', date('Y/m/d'));
$this->cacheThemesPluginsData();
}
/**
* Cache themes and plugins data
*/
private function cacheThemesPluginsData(): void
{
$returnArray = [];
$db = $this->getDb();
$array = (array)$db->config->defaultRepos;
$arrayCustom = (array)$db->config->customRepos;
$savedData = $this->getJsonFileData($this->themesPluginsCachePath);
foreach ($array as $type => $repos) {
if ($type === 'lastSync') {
continue;
}
$concatenatedRepos = array_merge((array)$repos, (array)$arrayCustom[$type]);
foreach ($concatenatedRepos as $repo) {
$repoData = $this->downloadThemePluginsData($repo, $type, $savedData);
if (null === $repoData) {
continue;
}
$returnArray[$type][$repo] = $repoData;
}
}
$this->save($this->themesPluginsCachePath, (object)$returnArray);
}
/**
* Cache single theme or plugin data
* @param string $repo
* @param string $type
*/
private function cacheSingleCacheThemePluginData(string $repo, string $type): void
{
$returnArray = $this->getJsonFileData($this->themesPluginsCachePath);
$repoData = $this->downloadThemePluginsData($repo, $type, $returnArray);
if (null === $repoData) {
return;
}
$returnArray[$type][$repo] = $repoData;
$this->save($this->themesPluginsCachePath, (object)$returnArray);
}
/**
* Gathers single theme/plugin data from repository
* @param string $repo
* @param string $type
* @param array $savedData
* @return array|null
*/
private function downloadThemePluginsData(string $repo, string $type, ?array $savedData = []): ?array
{
$branch = 'master';
if (!$this->checkBranch($repo, $branch)) {
$branch = 'main';
}
$repoParts = explode('/', $repo);
$name = array_pop($repoParts);
$repoReadmeUrl = sprintf('%s/blob/%s/README.md', $repo, $branch);
$repoFilesUrl = sprintf('%s/%s/', $repo, $branch);
$repoZipUrl = sprintf('%s/archive/%s.zip', $repo, $branch);
$newVersion = $this->getOfficialVersion($repoFilesUrl);
if (empty($repo) || empty($name) || $newVersion === null) {
return null;
}
$image = $savedData[$type][$repo]['image'] ?? $this->getCheckFileFromRepo('preview.jpg', $repoFilesUrl);
return [
'name' => ucfirst(str_replace('-', ' ', $name)),
'dirName' => $name,
'repo' => $repo,
'zip' => $repoZipUrl,
'newVersion' => htmlentities($newVersion),
'image' => $image !== null
? str_replace('https://github.com/', 'https://raw.githubusercontent.com/',
$repoFilesUrl) . 'preview.jpg'
: null,
'readme' => htmlentities($this->getCheckFileFromRepo('summary', $repoFilesUrl)),
'readmeUrl' => $repoReadmeUrl,
];
}
/**
* Check if branch is master or main
* @return bool
*/
private function checkBranch(string $repo, string $branch): bool
{
$repoFilesUrl = sprintf('%s/%s/', $repo, $branch);
return $this->getOfficialVersion($repoFilesUrl) !== null;
}