forked from sbrl/Pepperminty-Wiki
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.php
More file actions
1873 lines (1706 loc) · 62.9 KB
/
core.php
File metadata and controls
1873 lines (1706 loc) · 62.9 KB
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
/** The Pepperminty Wiki core */
$start_time = microtime(true);
mb_internal_encoding("UTF-8");
//{settings}
/////////////////////////////////////////////////////////////////////////////
////// Do not edit below this line unless you know what you are doing! //////
/////////////////////////////////////////////////////////////////////////////
/** The version of Pepperminty Wiki currently running. */
$version = "{version}";
$commit = "{commit}";
/// Environment ///
/** Holds information about the current request environment. */
$env = new stdClass();
/** The action requested by the user. */
$env->action = $settings->defaultaction;
/** The page name requested by the remote client. */
$env->page = "";
/** The filename that the page is stored in. */
$env->page_filename = "";
/** Whether we are looking at a history revision. */
$env->is_history_revision = false;
/** An object holding history revision information for the current request */
$env->history = new stdClass();
/** The revision number requested of the current page */
$env->history->revision_number = -1;
/** The revision data object from the page index for the requested revision */
$env->history->revision_data = false;
/** The user's name if they are logged in. Defaults to `$settings->anonymous_user_name` if the user isn't currently logged in. @var string */
$env->user = $settings->anonymous_user_name;
/** Whether the user is logged in */
$env->is_logged_in = false;
/** Whether the user is an admin (moderator) @todo Refactor this to is_moderator, so that is_admin can be for the server owner. */
$env->is_admin = false;
/** The currently logged in user's data. Please see $settings->users->username if you need to edit this - this is here for convenience :-) */
$env->user_data = new stdClass();
/** The data storage directory. Page filenames should be prefixed with this if you want their content. */
$env->storage_prefix = $settings->data_storage_dir . DIRECTORY_SEPARATOR;
/** Contains performance data statistics for the current request. */
$env->perfdata = new stdClass();
/// Paths ///
/**
* Contains a bunch of useful paths to various important files.
* None of these need to be prefixed with `$env->storage_prefix`.
*/
$paths = new stdClass();
/** The pageindex. Contains extensive information about all pages currently in this wiki. Individual entries for pages may be extended with arbitrary properties. */
$paths->pageindex = "pageindex.json";
/** The inverted index used for searching. Use the `search` class to interact with this - otherwise your brain might explode :P */
$paths->searchindex = "invindex.json";
/** The index that maps ids to page names. Use the `ids` class to interact with it :-) */
$paths->idindex = "idindex.json";
/** The cache of the most recently calculated statistics. */
$paths->statsindex = "statsindex.json";
/** The interwiki index cache */
$paths->interwiki_index = "interwiki_index.json";
// Prepend the storage data directory to all the defined paths.
foreach ($paths as &$path) {
$path = $env->storage_prefix . $path;
}
/** The master settings file @var string */
$paths->settings_file = $settingsFilename;
/** The prefix to add to uploaded files */
$paths->upload_file_prefix = "Files/";
session_start();
// Make sure that the login cookie lasts beyond the end of the user's session
setcookie(session_name(), session_id(), time() + $settings->sessionlifetime, "", "", false, true);
///////// Login System /////////
// Clear expired sessions
if(isset($_SESSION[$settings->sessionprefix . "-expiretime"]) and
$_SESSION[$settings->sessionprefix . "-expiretime"] < time())
{
// Clear the session variables
$_SESSION = [];
session_destroy();
}
if(isset($_SESSION[$settings->sessionprefix . "-user"]) and
isset($_SESSION[$settings->sessionprefix . "-pass"]))
{
// Grab the session variables
$env->user = $_SESSION[$settings->sessionprefix . "-user"];
// The user is logged in
$env->is_logged_in = true;
$env->user_data = $settings->users->{$env->user};
}
// Check to see if the currently logged in user is an admin
$env->is_admin = false;
if($env->is_logged_in)
{
foreach($settings->admins as $admin_username)
{
if($admin_username == $env->user)
{
$env->is_admin = true;
break;
}
}
}
/////// Login System End ///////
////////////////////
// APIDoc strings //
////////////////////
/**
* @apiDefine Admin Only the wiki administrator may use this call.
*/
/**
* @apiDefine Moderator Only users loggged with a moderator account may use this call.
*/
/**
* @apiDefine User Only users loggged in may use this call.
*/
/**
* @apiDefine Anonymous Anybody may use this call.
*/
/**
* @apiDefine UserNotLoggedInError
* @apiError UserNotLoggedInError You didn't log in before sending this request.
*/
/**
* @apiDefine UserNotModeratorError
* @apiError UserNotModeratorError You weren't loggged in as a moderator before sending this request.
*/
/**
* @apiDefine PageParameter
* @apiParam {string} page The page to operate on.
*/
////////////////////
///////////////////////////////////////////////////////////////////////////////
////////////////////////////////// Functions //////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/**
* Get the actual absolute origin of the request sent by the user.
* @package core
* @param array $s The $_SERVER variable contents. Defaults to $_SERVER.
* @param bool $use_forwarded_host Whether to utilise the X-Forwarded-Host header when calculating the actual origin.
* @return string The actual origin of the user's request.
*/
function url_origin( $s = false, $use_forwarded_host = false )
{
if($s === false) $s = $_SERVER;
$ssl = ( ! empty( $s['HTTPS'] ) && $s['HTTPS'] == 'on' );
$sp = strtolower( $s['SERVER_PROTOCOL'] );
$protocol = substr( $sp, 0, strpos( $sp, '/' ) ) . ( ( $ssl ) ? 's' : '' );
$port = $s['SERVER_PORT'];
$port = ( ( ! $ssl && $port=='80' ) || ( $ssl && $port=='443' ) ) ? '' : ':'.$port;
$host = ( $use_forwarded_host && isset( $s['HTTP_X_FORWARDED_HOST'] ) ) ? $s['HTTP_X_FORWARDED_HOST'] : ( isset( $s['HTTP_HOST'] ) ? $s['HTTP_HOST'] : null );
$host = isset( $host ) ? $host : $s['SERVER_NAME'] . $port;
return $protocol . '://' . $host;
}
/**
* Get the full url, as requested by the client.
* @package core
* @see http://stackoverflow.com/a/8891890/1460422 This Stackoverflow answer.
* @param array $s The $_SERVER variable. Defaults to $_SERVER.
* @param bool $use_forwarded_host Whether to take the X-Forwarded-Host header into account.
* @return string The full url, as requested by the client.
*/
function full_url( $s = false, $use_forwarded_host = false )
{
if($s == false) $s = $_SERVER;
return url_origin( $s, $use_forwarded_host ) . $s['REQUEST_URI'];
}
/**
* Converts a filesize into a human-readable string.
* @package core
* @see http://php.net/manual/en/function.filesize.php#106569 The original source
* @author rommel
* @author Edited by Starbeamrainbowlabs
* @param number $bytes The number of bytes to convert.
* @param number $decimals The number of decimal places to preserve.
* @return string A human-readable filesize.
*/
function human_filesize($bytes, $decimals = 2)
{
$sz = ["b", "kb", "mb", "gb", "tb", "pb", "eb", "yb", "zb"];
$factor = floor((strlen($bytes) - 1) / 3);
$result = round($bytes / pow(1024, $factor), $decimals);
return $result . @$sz[$factor];
}
/**
* Calculates the time since a particular timestamp and returns a
* human-readable result.
* @package core
* @see http://goo.gl/zpgLgq The original source. No longer exists, maybe the wayback machine caught it :-(
* @param integer $time The timestamp to convert.
* @return string The time since the given timestamp as
* a human-readable string.
*/
function human_time_since($time)
{
return human_time(time() - $time);
}
/**
* Renders a given number of seconds as something that humans can understand more easily.
* @package core
* @param int $seconds The number of seconds to render.
* @return string The rendered time.
*/
function human_time($seconds)
{
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($seconds < $unit) continue;
$numberOfUnits = floor($seconds / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
}
}
/**
* A recursive glob() function.
* @package core
* @see http://in.php.net/manual/en/function.glob.php#106595 The original source
* @author Mike
* @param string $pattern The glob pattern to use to find filenames.
* @param integer $flags The glob flags to use when finding filenames.
* @return array An array of the filepaths that match the given glob.
*/
function glob_recursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
{
$prefix = "$dir/";
// Remove the "./" from the beginning if it exists
if(substr($prefix, 0, 2) == "./") $prefix = substr($prefix, 2);
$files = array_merge($files, glob_recursive($prefix . basename($pattern), $flags));
}
return $files;
}
/**
* Gets the name of the parent page to the specified page.
* @since 0.15
* @package core
* @param string $pagename The child page to get the parent
* page name for.
* @return string|bool
*/
function get_page_parent($pagename) {
if(mb_strpos($pagename, "/") === false)
return false;
return mb_substr($pagename, 0, mb_strrpos($pagename, "/"));
}
/**
* Gets a list of all the sub pages of the current page.
* @package core
* @param object $pageindex The pageindex to use to search.
* @param string $pagename The name of the page to list the sub pages of.
* @return object An object containing all the subpages and their
* respective distances from the given page name in the pageindex tree.
*/
function get_subpages($pageindex, $pagename)
{
$pagenames = get_object_vars($pageindex);
$result = new stdClass();
$stem = "$pagename/";
$stem_length = strlen($stem);
foreach($pagenames as $entry => $value)
{
if(substr($entry, 0, $stem_length) == $stem)
{
// We found a subpage
// Extract the subpage's key relative to the page that we are searching for
$subpage_relative_key = substr($entry, $stem_length, -3);
// Calculate how many times removed the current subpage is from the current page. 0 = direct descendant.
$times_removed = substr_count($subpage_relative_key, "/");
// Store the name of the subpage we found
$result->$entry = $times_removed;
}
}
unset($pagenames);
return $result;
}
/**
* Makes sure that a subpage's parents exist.
* Note this doesn't check the pagename itself.
* @package core
* @param $pagename The pagename to check.
*/
function check_subpage_parents($pagename)
{
global $pageindex, $paths, $env;
// Save the new pageindex and return if there aren't any more parent pages to check
if(strpos($pagename, "/") === false)
{
file_put_contents($paths->pageindex, json_encode($pageindex, JSON_PRETTY_PRINT));
return;
}
$parent_pagename = substr($pagename, 0, strrpos($pagename, "/"));
$parent_page_filename = "$parent_pagename.md";
if(!file_exists($env->storage_prefix . $parent_page_filename))
{
// This parent page doesn't exist! Create it and add it to the page index.
touch($env->storage_prefix . $parent_page_filename, 0);
$newentry = new stdClass();
$newentry->filename = $parent_page_filename;
$newentry->size = 0;
$newentry->lastmodified = 0;
$newentry->lasteditor = "none";
$pageindex->$parent_pagename = $newentry;
}
check_subpage_parents($parent_pagename);
}
/**
* Makes a path safe.
* Paths may only contain alphanumeric characters, spaces, underscores, and
* dashes.
* @package core
* @param string $string The string to make safe.
* @return string A safe version of the given string.
*/
function makepathsafe($string)
{
// Old restrictive system
//$string = preg_replace("/[^0-9a-zA-Z\_\-\ \/\.]/i", "", $string);
// Remove reserved characters
$string = preg_replace("/[?%*:|\"><()\\[\\]]/i", "", $string);
// Collapse multiple dots into a single dot
$string = preg_replace("/\.+/", ".", $string);
// Don't allow slashes at the beginning
$string = ltrim($string, "\\/");
return $string;
}
/**
* Hides an email address from bots by adding random html entities.
* @todo Make this more clevererer :D
* @package core
* @param string $str The original email address
* @return string The mangled email address.
*/
function hide_email($str)
{
$hidden_email = "";
for($i = 0; $i < strlen($str); $i++)
{
if($str[$i] == "@")
{
$hidden_email .= "&#" . ord("@") . ";";
continue;
}
if(rand(0, 1) == 0)
$hidden_email .= $str[$i];
else
$hidden_email .= "&#" . ord($str[$i]) . ";";
}
return $hidden_email;
}
/**
* Checks to see if $haystack starts with $needle.
* @package core
* @param string $haystack The string to search.
* @param string $needle The string to search for at the beginning
* of $haystack.
* @return boolean Whether $needle can be found at the beginning
* of $haystack.
*/
function starts_with($haystack, $needle)
{
$length = strlen($needle);
return (substr($haystack, 0, $length) === $needle);
}
/**
* Case-insensitively finds all occurrences of $needle in $haystack. Handles
* UTF-8 characters correctly.
* @package core
* @see http://www.pontikis.net/tip/?id=16 the source
* @see http://www.php.net/manual/en/function.strpos.php#87061 the source that the above was based on
* @param string $haystack The string to search.
* @param string $needle The string to find.
* @return array|false An array of match indices, or false if
* nothing was found.
*/
function mb_stripos_all($haystack, $needle) {
$s = 0; $i = 0;
while(is_integer($i)) {
$i = mb_stripos($haystack, $needle, $s);
if(is_integer($i)) {
$aStrPos[] = $i;
$s = $i + (function_exists("mb_strlen") ? mb_strlen($needle) : strlen($needle));
}
}
if(isset($aStrPos))
return $aStrPos;
else
return false;
}
/**
* Tests whether a string starts with a specified substring.
* @package core
* @param string $haystack The string to check against.
* @param string $needle The substring to look for.
* @return bool Whether the string starts with the specified substring.
*/
function startsWith($haystack, $needle) {
return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}
/**
* Tests whether a string ends with a given substring.
* @package core
* @param string $whole The string to test against.
* @param string $end The substring test for.
* @return bool Whether $whole ends in $end.
*/
function endsWith($whole, $end)
{
return (strpos($whole, $end, strlen($whole) - strlen($end)) !== false);
}
/**
* Replaces the first occurrence of $find with $replace.
* @package core
* @param string $find The string to search for.
* @param string $replace The string to replace the search string with.
* @param string $subject The string ot perform the search and replace on.
* @return string The source string after the find and replace has been performed.
*/
function str_replace_once($find, $replace, $subject)
{
$index = strpos($subject, $find);
if($index !== false)
return substr_replace($subject, $replace, $index, strlen($find));
return $subject;
}
/**
* Returns the system's mime type mappings, considering the first extension
* listed to be cacnonical.
* @package core
* @see http://stackoverflow.com/a/1147952/1460422 From this stackoverflow answer
* @author chaos
* @author Edited by Starbeamrainbowlabs
* @return array An array of mime type mappings.
*/
function system_mime_type_extensions()
{
global $settings;
$out = array();
$file = fopen($settings->mime_extension_mappings_location, 'r');
while(($line = fgets($file)) !== false) {
$line = trim(preg_replace('/#.*/', '', $line));
if(!$line)
continue;
$parts = preg_split('/\s+/', $line);
if(count($parts) == 1)
continue;
$type = array_shift($parts);
if(!isset($out[$type]))
$out[$type] = array_shift($parts);
}
fclose($file);
return $out;
}
/**
* Converts a given mime type to it's associated file extension.
* @package core
* @see http://stackoverflow.com/a/1147952/1460422 From this stackoverflow answer
* @author chaos
* @author Edited by Starbeamrainbowlabs
* @param string $type The mime type to convert.
* @return string The extension for the given mime type.
*/
function system_mime_type_extension($type)
{
static $exts;
if(!isset($exts))
$exts = system_mime_type_extensions();
return isset($exts[$type]) ? $exts[$type] : null;
}
/**
* Returns the system MIME type mapping of extensions to MIME types.
* @package core
* @see http://stackoverflow.com/a/1147952/1460422 From this stackoverflow answer
* @author chaos
* @author Edited by Starbeamrainbowlabs
* @return array An array mapping file extensions to their associated mime types.
*/
function system_extension_mime_types()
{
global $settings;
$out = array();
$file = fopen($settings->mime_extension_mappings_location, 'r');
while(($line = fgets($file)) !== false) {
$line = trim(preg_replace('/#.*/', '', $line));
if(!$line)
continue;
$parts = preg_split('/\s+/', $line);
if(count($parts) == 1)
continue;
$type = array_shift($parts);
foreach($parts as $part)
$out[$part] = $type;
}
fclose($file);
return $out;
}
/**
* Converts a given file extension to it's associated mime type.
* @package core
* @see http://stackoverflow.com/a/1147952/1460422 From this stackoverflow answer
* @author chaos
* @author Edited by Starbeamrainbowlabs
* @param string $ext The extension to convert.
* @return string The mime type associated with the given extension.
*/
function system_extension_mime_type($ext) {
static $types;
if(!isset($types))
$types = system_extension_mime_types();
$ext = strtolower($ext);
return isset($types[$ext]) ? $types[$ext] : null;
}
/**
* Generates a stack trace.
* @package core
* @param bool $log_trace Whether to send the stack trace to the error log.
* @param bool $full Whether to output a full description of all the variables involved.
* @return string A string prepresentation of a stack trace.
*/
function stack_trace($log_trace = true, $full = false)
{
$result = "";
$stackTrace = debug_backtrace();
$stackHeight = count($stackTrace);
foreach ($stackTrace as $i => $stackEntry)
{
$result .= "#" . ($stackHeight - $i) . ": ";
$result .= (isset($stackEntry["file"]) ? $stackEntry["file"] : "(unknown file)") . ":" . (isset($stackEntry["line"]) ? $stackEntry["line"] : "(unknown line)") . " - ";
if(isset($stackEntry["function"]))
{
$result .= "(calling " . $stackEntry["function"];
if(isset($stackEntry["args"]) && count($stackEntry["args"]))
{
$result .= ": ";
$result .= implode(", ", array_map($full ? "var_dump_ret" : "var_dump_short", $stackEntry["args"]));
}
}
$result .= ")\n";
}
if($log_trace)
error_log($result);
return $result;
}
/**
* Calls var_dump() and returns the output.
* @package core
* @param mixed $var The thing to pass to var_dump().
* @return string The output captured from var_dump().
*/
function var_dump_ret($var)
{
ob_start();
var_dump($var);
return ob_get_clean();
}
/**
* Calls var_dump(), shortening the output for various types.
* @package core
* @param mixed $var The thing to pass to var_dump().
* @return string A shortened version of the var_dump() output.
*/
function var_dump_short($var)
{
$result = trim(var_dump_ret($var));
if(substr($result, 0, 6) === "object" || substr($result, 0, 5) === "array")
{
$result = substr($result, 0, strpos($result, " ")) . " { ... }";
}
return $result;
}
if (!function_exists('getallheaders')) {
/**
* Polyfill for PHP's native getallheaders() function on platforms that
* don't have it.
* @package core
* @todo Identify which platforms don't have it and whether we still need this
*/
function getallheaders()
{
if (!is_array($_SERVER))
return [];
$headers = array();
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
/**
* Renders a timestamp in HTML.
* @package core
* @param int $timestamp The timestamp to render.
* @return string HTML representing the given timestamp.
*/
function render_timestamp($timestamp)
{
return "<time class='cursor-query' title='" . date("l jS \of F Y \a\\t h:ia T", $timestamp) . "'>" . human_time_since($timestamp) . "</time>";
}
/**
* Renders a page name in HTML.
* @package core
* @param object $rchange The recent change to render as a page name
* @return string HTML representing the name of the given page.
*/
function render_pagename($rchange)
{
global $pageindex;
$pageDisplayName = $rchange->page;
if(isset($pageindex->$pageDisplayName) and !empty($pageindex->$pageDisplayName->redirect))
$pageDisplayName = "<em>$pageDisplayName</em>";
$pageDisplayLink = "<a href='?page=" . rawurlencode($rchange->page) . "'>$pageDisplayName</a>";
return $pageDisplayName;
}
/**
* Renders an editor's or a group of editors name(s) in HTML.
* @package core
* @param string $editorName The name of the editor to render.
* @return string HTML representing the given editor's name.
*/
function render_editor($editorName)
{
return "<span class='editor'>✎ $editorName</span>";
}
/**
* Saves the settings file back to peppermint.json.
* @return bool Whether the settings were saved successfully.
*/
function save_settings() {
global $paths, $settings;
return file_put_contents($paths->settings_file, json_encode($settings, JSON_PRETTY_PRINT)) !== false;
}
/**
* Saves the currently logged in user's data back to peppermint.json.
* @package core
* @return bool Whether the user's data was saved successfully. Returns false if the user isn't logged in.
*/
function save_userdata()
{
global $env, $settings, $paths;
if(!$env->is_logged_in)
return false;
$settings->users->{$env->user} = $env->user_data;
return save_settings();
}
/**
* Figures out the path to the user page for a given username.
* Does not check to make sure the user acutally exists.
* @package core
* @param string $username The username to get the path to their user page for.
* @return string The path to the given user's page.
*/
function get_user_pagename($username) {
global $settings;
return "$settings->user_page_prefix/$username";
}
/**
* Extracts a username from a user page path.
* @package core
* @param string $userPagename The suer page path to extract from.
* @return string The name of the user that the user page belongs to.
*/
function extract_user_from_userpage($userPagename) {
global $settings;
$matches = [];
preg_match("/$settings->user_page_prefix\\/([^\\/]+)\\/?/", $userPagename, $matches);
return $matches[1];
}
/**
* Sends a plain text email to a user, replacing {username} with the specified username.
* @package core
* @param string $username The username to send the email to.
* @param string $subject The subject of the email.
* @param string $body The body of the email.
* @return boolean Whether the email was sent successfully or not. Currently, this may fail if the user doesn't have a registered email address.
*/
function email_user($username, $subject, $body)
{
global $version, $settings;
// If the user doesn't have an email address, then we can't email them :P
if(empty($settings->users->{$username}->emailAddress))
return false;
$subject = str_replace("{username}", $username, $subject);
$body = str_replace("{username}", $username, $body);
$headers = [
"content-type" => "text/plain",
"x-mailer" => "$settings->sitename Pepperminty-Wiki/$version PHP/" . phpversion(),
"reply-to" => "$settings->admindetails_name <$settings->admindetails_email>"
];
$compiled_headers = "";
foreach($headers as $header => $value)
$compiled_headers .= "$header: $value\r\n";
return mail($settings->users->{$username}->emailAddress, $subject, $body, $compiled_headers, "-t");
}
/**
* Sends a plain text email to a list of users, replacing {username} with each user's name.
* @package core
* @param string[] $usernames A list of usernames to email.
* @param string $subject The subject of the email.
* @param string $body The body of the email.
* @return integer The number of emails sent successfully.
*/
function email_users($usernames, $subject, $body)
{
$emailsSent = 0;
foreach($usernames as $username)
{
$emailsSent += email_user($username, $subject, $body) ? 1 : 0;
}
return $emailsSent;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
////////////////////// Security and Consistency Measures //////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
* Sort out the pageindex. Create it if it doesn't exist, and load + parse it
* if it does.
*/
if(!file_exists($paths->pageindex))
{
$glob_str = $env->storage_prefix . "*.md";
$existingpages = glob_recursive($glob_str);
// Debug statements. Uncomment when debugging the pageindex regenerator.
// var_dump($env->storage_prefix);
// var_dump($glob_str);
// var_dump($existingpages);
$pageindex = new stdClass();
// We use a for loop here because foreach doesn't loop over new values inserted
// while we were looping
for($i = 0; $i < count($existingpages); $i++)
{
$pagefilename = $existingpages[$i];
// Create a new entry
$newentry = new stdClass();
$newentry->filename = substr( // Store the filename, whilst trimming the storage prefix
$pagefilename,
mb_strlen(preg_replace("/^\.\//iu", "", $env->storage_prefix)) // glob_recursive trim the ./ from returned filenames , so we need to as well
);
// Remove the `./` from the beginning if it's still hanging around
if(substr($newentry->filename, 0, 2) == "./")
$newentry->filename = substr($newentry->filename, 2);
$newentry->size = filesize($pagefilename); // Store the page size
$newentry->lastmodified = filemtime($pagefilename); // Store the date last modified
// Todo find a way to keep the last editor independent of the page index
$newentry->lasteditor = "unknown"; // Set the editor to "unknown"
// Extract the name of the (sub)page without the ".md"
$pagekey = mb_substr($newentry->filename, 0, -3);
if(file_exists($env->storage_prefix . $pagekey) && // If it exists...
!is_dir($env->storage_prefix . $pagekey)) // ...and isn't a directory
{
// This page (potentially) has an associated file!
// Let's investigate.
// Blindly add the file to the pageindex for now.
// Future We might want to do a security check on the file later on.
// File a bug if you think we should do this.
$newentry->uploadedfile = true; // Yes this page does have an uploaded file associated with it
$newentry->uploadedfilepath = $pagekey; // It's stored here
// Work out what kind of file it really is
$mimechecker = finfo_open(FILEINFO_MIME_TYPE);
$newentry->uploadedfilemime = finfo_file($mimechecker, $env->storage_prefix . $pagekey);
}
// Debug statements. Uncomment when debugging the pageindex regenerator.
// echo("pagekey: ");
// var_dump($pagekey);
// echo("newentry: ");
// var_dump($newentry);
// Subpage parent checker
if(strpos($pagekey, "/") !== false)
{
// We have a sub page people
// Work out what our direct parent's key must be in order to check to
// make sure that it actually exists. If it doesn't, then we need to
// create it.
$subpage_parent_key = substr($pagekey, 0, strrpos($pagekey, "/"));
$subpage_parent_filename = "$env->storage_prefix$subpage_parent_key.md";
if(array_search($subpage_parent_filename, $existingpages) === false)
{
// Our parent page doesn't actually exist - create it
touch($subpage_parent_filename, 0);
// Furthermore, we should add this page to the list of existing pages
// in order for it to be indexed
$existingpages[] = $subpage_parent_filename;
}
}
// Store the new entry in the new page index
$pageindex->$pagekey = $newentry;
}
file_put_contents($paths->pageindex, json_encode($pageindex, JSON_PRETTY_PRINT));
unset($existingpages);
}
else
{
$pageindex_read_start = microtime(true);
$pageindex = json_decode(file_get_contents($paths->pageindex));
$env->perfdata->pageindex_decode_time = round((microtime(true) - $pageindex_read_start)*1000, 3);
header("x-pageindex-decode-time: " . $env->perfdata->pageindex_decode_time . "ms");
}
//////////////////////////
///// Page id system /////
//////////////////////////
if(!file_exists($paths->idindex))
file_put_contents($paths->idindex, "{}");
$idindex_decode_start = microtime(true);
$idindex = json_decode(file_get_contents($paths->idindex));
$env->perfdata->idindex_decode_time = round((microtime(true) - $idindex_decode_start)*1000, 3);
/**
* Provides an interface to interact with page ids.
* @package core
*/
class ids
{
/**
* Gets the page id associated with the given page name.
* If it doesn't exist in the id index, it will be added.
* @package core
* @param string $pagename The name of the page to fetch the id for.
* @return integer The id for the specified page name.
*/
public static function getid($pagename)
{
global $idindex;
$pagename_norm = Normalizer::normalize($pagename, Normalizer::FORM_C);
foreach ($idindex as $id => $entry)
{
// We don't need to normalise here because we normralise when assigning ids
if($entry == $pagename_norm)
return $id;
}
// This pagename doesn't have an id - assign it one quick!
return self::assign($pagename);
}
/**
* Gets the page name associated with the given page id.
* Be warned that if the id index is cleared (e.g. when the search index is
* rebuilt from scratch), the id associated with a page name may change!
* @package core
* @param int $id The id to fetch the page name for.
* @return string The page name currently associated with the specified id.
*/
public static function getpagename($id)
{
global $idindex;
if(!isset($idindex->$id))
return false;
else
return $idindex->$id;
}
/**
* Moves a page in the id index from $oldpagename to $newpagename.
* Note that this function doesn't perform any special checks to make sure
* that the destination name doesn't already exist.
* @package core
* @param string $oldpagename The old page name to move.
* @param string $newpagename The new page name to move the old page name to.
*/
public static function movepagename($oldpagename, $newpagename)
{
global $idindex, $paths;
$pageid = self::getid(Normalizer::normalize($oldpagename, Normalizer::FORM_C));
$idindex->$pageid = Normalizer::normalize($newpagename, Normalizer::FORM_C);
file_put_contents($paths->idindex, json_encode($idindex));
}
/**
* Removes the given page name from the id index.
* Note that this function doesn't handle multiple entries with the same
* name. Also note that it may get re-added during a search reindex if the
* page still exists.
* @package core
* @param string $pagename The page name to delete from the id index.
*/
public static function deletepagename($pagename)
{
global $idindex, $paths;
// Get the id of the specified page
$pageid = self::getid($pagename);
// Remove it from the pageindex
unset($idindex->$pageid);
// Save the id index
file_put_contents($paths->idindex, json_encode($idindex));
}
/**
* Clears the id index completely.
* Will break the inverted search index! Make sure you rebuild the search
* index (if the search module is installed, of course) if you want search
* to still work. Of course, note that will re-add all the pages to the id
* index.
* @package core
*/
public static function clear()
{
global $paths, $idindex;
// Delete the old id index
unlink($paths->idindex);
// Create the new id index
file_put_contents($paths->idindex, "{}");
// Reset the in-memory id index
$idindex = new stdClass();
}
/**
* Assigns an id to a pagename. Doesn't check to make sure that
* pagename doesn't already exist in the id index.
* @package core
* @param string $pagename The page name to assign an id to.
* @return integer The id assigned to the specified page name.
*/
protected static function assign($pagename)
{
global $idindex, $paths;
$pagename = Normalizer::normalize($pagename, Normalizer::FORM_C);
$nextid = count(array_keys(get_object_vars($idindex)));
// Increment the generated id until it's unique
while(isset($idindex->nextid))
$nextid++;
// Update the id index
$idindex->$nextid = $pagename;
// Save the id index
file_put_contents($paths->idindex, json_encode($idindex));
return $nextid;
}
}