-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.php
2094 lines (1970 loc) · 79.4 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
/*
PmWiki
Copyright 2001-2010 Patrick R. Michaud
http://www.pmichaud.com/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
----
Note from Pm: Trying to understand the PmWiki code? Wish it had
more comments? If you want help with any of the code here,
write me at <[email protected]> with your question(s) and I'll
provide explanations (and add comments) that answer them.
*/
error_reporting(E_ALL ^ E_NOTICE);
StopWatch('PmWiki');
@ini_set('magic_quotes_runtime', 0);
@ini_set('magic_quotes_sybase', 0);
if (@ini_get('pcre.backtrack_limit') < 1000000)
@ini_set('pcre.backtrack_limit', 1000000);
if (ini_get('register_globals'))
foreach($_REQUEST as $k=>$v) {
if (preg_match('/^(GLOBALS|_SERVER|_GET|_POST|_COOKIE|_FILES|_ENV|_REQUEST|_SESSION|FarmD|WikiDir)$/i', $k)) exit();
${$k}=''; unset(${$k});
}
$UnsafeGlobals = array_keys($GLOBALS); $GCount=0; $FmtV=array();
SDV($FarmD,dirname(__FILE__));
SDV($WorkDir,'wiki.d');
define('PmWiki',1);
if (preg_match('/\\w\\w:/', $FarmD)) exit();
@include_once("$FarmD/scripts/version.php");
$GroupPattern = '[[:upper:]][\\w]*(?:-\\w+)*';
$NamePattern = '[[:upper:]\\d][\\w]*(?:-\\w+)*';
$BlockPattern = 'form|div|table|t[rdh]|p|[uo]l|d[ltd]|h[1-6r]|pre|blockquote';
$WikiWordPattern = '[[:upper:]][[:alnum:]]*(?:[[:upper:]][[:lower:]0-9]|[[:lower:]0-9][[:upper:]])[[:alnum:]]*';
$WikiDir = new PageStore('wiki.d/{$FullName}');
$WikiLibDirs = array(&$WikiDir,new PageStore('$FarmD/wikilib.d/{$FullName}'));
$LocalDir = 'local';
$InterMapFiles = array("$FarmD/scripts/intermap.txt",
"$FarmD/local/farmmap.txt", '$SiteGroup.InterMap', 'local/localmap.txt');
$Newline = "\263"; # deprecated, 2.0.0
$KeepToken = "\235\235";
$Now=time();
define('READPAGE_CURRENT', $Now+604800);
$TimeFmt = '%B %d, %Y, at %I:%M %p';
$TimeISOFmt = '%Y-%m-%dT%H:%M:%S';
$TimeISOZFmt = '%Y-%m-%dT%H:%M:%SZ';
$MessagesFmt = array();
$BlockMessageFmt = "<h3 class='wikimessage'>$[This post has been blocked by the administrator]</h3>";
$EditFields = array('text');
$EditFunctions = array('EditTemplate', 'RestorePage', 'ReplaceOnSave',
'SaveAttributes', 'PostPage', 'PostRecentChanges', 'AutoCreateTargets',
'PreviewPage');
$EnablePost = 1;
$ChangeSummary = substr(preg_replace('/[\\x00-\\x1f]|=\\]/', '',
stripmagic(@$_REQUEST['csum'])), 0, 100);
$AsSpacedFunction = 'AsSpaced';
$SpaceWikiWords = 0;
$RCDelimPattern = ' ';
$RecentChangesFmt = array(
'$SiteGroup.AllRecentChanges' =>
'* [[{$Group}.{$Name}]] . . . $CurrentTime $[by] $AuthorLink: [=$ChangeSummary=]',
'$Group.RecentChanges' =>
'* [[{$Group}/{$Name}]] . . . $CurrentTime $[by] $AuthorLink: [=$ChangeSummary=]');
$UrlScheme = (@$_SERVER['HTTPS']=='on' || @$_SERVER['SERVER_PORT']==443)
? 'https' : 'http';
$ScriptUrl = $UrlScheme.'://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
$PubDirUrl = preg_replace('#/[^/]*$#', '/pub', $ScriptUrl, 1);
$HTMLVSpace = "<vspace>";
$HTMLPNewline = '';
$MarkupFrame = array();
$MarkupFrameBase = array('cs' => array(), 'vs' => '', 'ref' => 0,
'closeall' => array(), 'is' => array(),
'escape' => 1);
$WikiWordCountMax = 1000000;
$WikiWordCount['PmWiki'] = 1;
$TableRowIndexMax = 1;
$UrlExcludeChars = '<>"{}|\\\\^`()[\\]\'';
$QueryFragPattern = "[?#][^\\s$UrlExcludeChars]*";
$SuffixPattern = '(?:-?[[:alnum:]]+)*';
$LinkPageSelfFmt = "<a class='selflink' href='\$LinkUrl'>\$LinkText</a>";
$LinkPageExistsFmt = "<a class='wikilink' href='\$LinkUrl'>\$LinkText</a>";
$LinkPageCreateFmt =
"<a class='createlinktext' rel='nofollow'
href='{\$PageUrl}?action=edit'>\$LinkText</a><a rel='nofollow'
class='createlink' href='{\$PageUrl}?action=edit'>?</a>";
$UrlLinkFmt =
"<a class='urllink' href='\$LinkUrl' rel='nofollow'>\$LinkText</a>";
umask(002);
$CookiePrefix = '';
$SiteGroup = 'Site';
$SiteAdminGroup = 'SiteAdmin';
$DefaultGroup = 'Main';
$DefaultName = 'HomePage';
$GroupHeaderFmt = '(:include {$Group}.GroupHeader self=0 basepage={*$FullName}:)(:nl:)';
$GroupFooterFmt = '(:nl:)(:include {$Group}.GroupFooter self=0 basepage={*$FullName}:)';
$PagePathFmt = array('{$Group}.$1','$1.$1','$1.{$DefaultName}');
$PageAttributes = array(
'passwdread' => '$[Set new read password:]',
'passwdedit' => '$[Set new edit password:]',
'passwdattr' => '$[Set new attribute password:]');
$XLLangs = array('en');
if (preg_match('/^C$|\.UTF-?8/i',setlocale(LC_ALL,0)))
setlocale(LC_ALL,'en_US');
$FmtP = array();
$FmtPV = array(
# '$ScriptUrl' => 'PUE($ScriptUrl)', ## $ScriptUrl is special
'$PageUrl' =>
'PUE(($EnablePathInfo)
? "$ScriptUrl/$group/$name"
: "$ScriptUrl?n=$group.$name")',
'$FullName' => '"$group.$name"',
'$Groupspaced' => '$AsSpacedFunction($group)',
'$Namespaced' => '$AsSpacedFunction($name)',
'$Group' => '$group',
'$Name' => '$name',
'$Titlespaced' => '@$page["title"] ?
str_replace("$", "$", $page["title"]) : $AsSpacedFunction($name)',
'$Title' => '@$page["title"] ?
str_replace("$", "$", $page["title"]) :
($GLOBALS["SpaceWikiWords"] ? $AsSpacedFunction($name) : $name)',
'$LastModifiedBy' => '@$page["author"]',
'$LastModifiedHost' => '@$page["host"]',
'$LastModified' => 'strftime($GLOBALS["TimeFmt"], $page["time"])',
'$LastModifiedSummary' => '@$page["csum"]',
'$LastModifiedTime' => '$page["time"]',
'$Description' => '@$page["description"]',
'$SiteGroup' => '$GLOBALS["SiteGroup"]',
'$VersionNum' => '$GLOBALS["VersionNum"]',
'$Version' => '$GLOBALS["Version"]',
'$Author' => 'NoCache($GLOBALS["Author"])',
'$AuthId' => 'NoCache($GLOBALS["AuthId"])',
'$DefaultGroup' => '$GLOBALS["DefaultGroup"]',
'$DefaultName' => '$GLOBALS["DefaultName"]',
'$BaseName' => 'MakeBaseName($pn)',
'$Action' => '$GLOBALS["action"]',
'$PasswdRead' => 'PasswdVar($pn, "read")',
'$PasswdEdit' => 'PasswdVar($pn, "edit")',
'$PasswdAttr' => 'PasswdVar($pn, "attr")',
);
$SaveProperties = array('title', 'description', 'keywords');
$PageTextVarPatterns = array(
'var:' => '/^(:*\\s*(\\w[-\\w]*)\\s*:[ \\t]?)(.*)($)/m',
'(:var:...:)' => '/(\\(: *(\\w[-\\w]*) *:(?!\\))\\s?)(.*?)(:\\))/s'
);
$WikiTitle = 'PmWiki';
$Charset = 'ISO-8859-1';
$HTTPHeaders = array(
"Expires: Tue, 01 Jan 2002 00:00:00 GMT",
"Cache-Control: no-store, no-cache, must-revalidate",
"Content-type: text/html; charset=ISO-8859-1;");
$CacheActions = array('browse','diff','print');
$EnableHTMLCache = 0;
$NoHTMLCache = 0;
$HTMLDoctypeFmt =
"<!DOCTYPE html
PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'><head>\n";
$HTMLStylesFmt['pmwiki'] = "
ul, ol, pre, dl, p { margin-top:0px; margin-bottom:0px; }
code.escaped { white-space: nowrap; }
.vspace { margin-top:1.33em; }
.indent { margin-left:40px; }
.outdent { margin-left:40px; text-indent:-40px; }
a.createlinktext { text-decoration:none; border-bottom:1px dotted gray; }
a.createlink { text-decoration:none; position:relative; top:-0.5em;
font-weight:bold; font-size:smaller; border-bottom:none; }
img { border:0px; }
";
$HTMLHeaderFmt['styles'] = array(
"<style type='text/css'><!--",&$HTMLStylesFmt,"\n--></style>");
$HTMLBodyFmt = "</head>\n<body>";
$HTMLStartFmt = array('headers:',&$HTMLDoctypeFmt,&$HTMLHeaderFmt,
&$HTMLBodyFmt);
$HTMLEndFmt = "\n</body>\n</html>";
$PageStartFmt = array(&$HTMLStartFmt,"\n<div id='contents'>\n");
$PageEndFmt = array('</div>',&$HTMLEndFmt);
$HandleActions = array(
'browse' => 'HandleBrowse', 'print' => 'HandleBrowse',
'edit' => 'HandleEdit', 'source' => 'HandleSource',
'attr' => 'HandleAttr', 'postattr' => 'HandlePostAttr',
'logout' => 'HandleLogoutA', 'login' => 'HandleLoginA');
$HandleAuth = array(
'browse' => 'read', 'source' => 'read', 'print' => 'read',
'edit' => 'edit', 'attr' => 'attr', 'postattr' => 'attr',
'logout' => 'read', 'login' => 'login');
$ActionTitleFmt = array(
'edit' => '| $[Edit]',
'attr' => '| $[Attributes]',
'login' => '| $[Login]');
$DefaultPasswords = array('admin'=>'*','read'=>'','edit'=>'','attr'=>'');
$AuthCascade = array('edit'=>'read', 'attr'=>'edit');
$AuthList = array('' => 1, 'nopass:' => 1, '@nopass' => 1);
$SessionEncode = 'base64_encode';
$SessionDecode = 'base64_decode';
$Conditions['enabled'] = '(boolean)@$GLOBALS[$condparm]';
$Conditions['false'] = 'false';
$Conditions['true'] = 'true';
$Conditions['group'] =
"(boolean)MatchPageNames(\$pagename, FixGlob(\$condparm, '$1$2.*'))";
$Conditions['name'] =
"(boolean)MatchPageNames(\$pagename, FixGlob(\$condparm, '$1*.$2'))";
$Conditions['match'] = 'preg_match("!$condparm!",$pagename)';
$Conditions['authid'] = 'NoCache(@$GLOBALS["AuthId"] > "")';
$Conditions['exists'] = 'PageExists(MakePageName($pagename, $condparm))';
$Conditions['equal'] = 'CompareArgs($condparm) == 0';
function CompareArgs($arg)
{ $arg = ParseArgs($arg); return strcmp(@$arg[''][0], @$arg[''][1]); }
$Conditions['auth'] = 'NoCache(CondAuth($pagename, $condparm))';
function CondAuth($pagename, $condparm) {
@list($level, $pn) = explode(' ', $condparm, 2);
$pn = ($pn > '') ? MakePageName($pagename, $pn) : $pagename;
return (boolean)RetrieveAuthPage($pn, $level, false, READPAGE_CURRENT);
}
## CondExpr handles complex conditions (expressions)
## Portions Copyright 2005 by D. Faure ([email protected])
function CondExpr($pagename, $condname, $condparm) {
global $CondExprOps;
SDV($CondExprOps, 'and|x?or|&&|\\|\\||[!()]');
if ($condname == '(' || $condname == '[')
$condparm = preg_replace('/[\\]\\)]\\s*$/', '', $condparm);
$condparm = str_replace('&&', '&&', $condparm);
$terms = preg_split("/(?<!\\S)($CondExprOps)(?!\\S)/i", $condparm, -1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach($terms as $i => $t) {
$t = trim($t);
if (preg_match("/^($CondExprOps)$/i", $t)) continue;
if ($t) $terms[$i] = CondText($pagename, "if $t", 'TRUE') ? '1' : '0';
}
return @eval('return(' . implode(' ', $terms) . ');');
}
$Conditions['expr'] = 'CondExpr($pagename, $condname, $condparm)';
$Conditions['('] = 'CondExpr($pagename, $condname, $condparm)';
$Conditions['['] = 'CondExpr($pagename, $condname, $condparm)';
$MarkupTable['_begin']['seq'] = 'B';
$MarkupTable['_end']['seq'] = 'E';
Markup('fulltext','>_begin');
Markup('split','>fulltext',"\n",
'$RedoMarkupLine=1; return explode("\n",$x);');
Markup('directives','>split');
Markup('inline','>directives');
Markup('links','>inline');
Markup('block','>links');
Markup('style','>block');
Markup('closeall', '_begin',
'/^\\(:closeall:\\)$/e',
"'<:block>' . MarkupClose()");
$ImgExtPattern="\\.(?:gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG)";
$ImgTagFmt="<img src='\$LinkUrl' alt='\$LinkAlt' title='\$LinkAlt' />";
$BlockMarkups = array(
'block' => array('','','',0),
'ul' => array('<ul><li>','</li><li>','</li></ul>',1),
'dl' => array('<dl>','</dd>','</dd></dl>',1),
'ol' => array('<ol><li>','</li><li>','</li></ol>',1),
'p' => array('<p>','','</p>',0),
'indent' =>
array("<div class='indent'>","</div><div class='indent'>",'</div>',1),
'outdent' =>
array("<div class='outdent'>","</div><div class='outdent'>",'</div>',1),
'pre' => array('<pre>','','</pre>',0),
'table' => array("<table width='100%'>",'','</table>',0));
foreach(array('http:','https:','mailto:','ftp:','news:','gopher:','nap:',
'file:') as $m)
{ $LinkFunctions[$m] = 'LinkIMap'; $IMap[$m]="$m$1"; }
$LinkFunctions['<:page>'] = 'LinkPage';
$q = preg_replace('/(\\?|%3f)([-\\w]+=)/', '&$2', @$_SERVER['QUERY_STRING']);
if ($q != @$_SERVER['QUERY_STRING']) {
unset($_GET);
parse_str($q, $_GET);
$_REQUEST = array_merge($_REQUEST, $_GET, $_POST);
}
if (isset($_GET['action'])) $action = $_GET['action'];
elseif (isset($_POST['action'])) $action = $_POST['action'];
else $action = 'browse';
$pagename = @$_REQUEST['n'];
if (!$pagename) $pagename = @$_REQUEST['pagename'];
if (!$pagename &&
preg_match('!^'.preg_quote($_SERVER['SCRIPT_NAME'],'!').'/?([^?]*)!',
$_SERVER['REQUEST_URI'],$match))
$pagename = urldecode($match[1]);
if (preg_match('/[\\x80-\\xbf]/',$pagename))
$pagename=utf8_decode($pagename);
$pagename = preg_replace('![^[:alnum:]\\x80-\\xff]+$!','',$pagename);
$FmtPV['$RequestedPage'] = "'".htmlspecialchars($pagename, ENT_QUOTES)."'";
$Cursor['*'] = &$pagename;
if (function_exists("date_default_timezone_get") ) { # fix PHP5.3 warnings
@date_default_timezone_set(@date_default_timezone_get());
}
if (file_exists("$FarmD/local/farmconfig.php"))
include_once("$FarmD/local/farmconfig.php");
if (IsEnabled($EnableLocalConfig,1)) {
if (file_exists("$LocalDir/config.php"))
include_once("$LocalDir/config.php");
elseif (file_exists('config.php'))
include_once('config.php');
}
// if (file_exists("$FarmD/cookbook/markdown.php")
// include_once(".cookbook/markdown.php");
SDV($CurrentTime, strftime($TimeFmt, $Now));
SDV($CurrentTimeISO, strftime($TimeISOFmt, $Now));
if (IsEnabled($EnableStdConfig,1))
include_once("$FarmD/scripts/stdconfig.php");
foreach((array)$InterMapFiles as $f) {
$f = FmtPageName($f, $pagename);
if (($v = @file($f)))
$v = preg_replace('/^\\s*(?>\\w[-\\w]*)(?!:)/m', '$0:', implode('', $v));
else if (PageExists($f)) {
$p = ReadPage($f, READPAGE_CURRENT);
$v = $p['text'];
} else continue;
if (!preg_match_all("/^\\s*(\\w[-\\w]*:)[^\\S\n]+(\\S*)/m", $v,
$match, PREG_SET_ORDER)) continue;
foreach($match as $m) {
if (strpos($m[2], '$1') === false) $m[2] .= '$1';
$LinkFunctions[$m[1]] = 'LinkIMap';
$IMap[$m[1]] = FmtPageName($m[2], $pagename);
}
}
$LinkPattern = implode('|',array_keys($LinkFunctions));
SDV($LinkPageCreateSpaceFmt,$LinkPageCreateFmt);
$keys = array_keys($AuthCascade);
while ($keys) {
$k = array_shift($keys); $t = $AuthCascade[$k];
if (in_array($t, $keys))
{ unset($AuthCascade[$k]); $AuthCascade[$k] = $t; array_push($keys, $k); }
}
$ActionTitle = FmtPageName(@$ActionTitleFmt[$action], $pagename);
if (!@$HandleActions[$action] || !function_exists($HandleActions[$action]))
$action='browse';
if (IsEnabled($EnableActions, 1)) HandleDispatch($pagename, $action);
Lock(0);
return;
## HandleDispatch() is used to dispatch control to the appropriate
## action handler with the appropriate permissions.
## If a message is supplied, it is added to $MessagesFmt.
function HandleDispatch($pagename, $action, $msg=NULL) {
global $MessagesFmt, $HandleActions, $HandleAuth;
if ($msg) $MessagesFmt[] = "<div class='wikimessage'>$msg</div>";
$fn = $HandleActions[$action];
$auth = $HandleAuth[$action];
if (!$auth) $auth = 'read';
return $fn($pagename, $auth);
}
## helper functions
function stripmagic($x)
{ return get_magic_quotes_gpc() ? stripslashes($x) : $x; }
function pre_r(&$x)
{ return '<pre>'.htmlspecialchars(print_r($x, true)).'</pre>'; }
function PSS($x)
{ return str_replace('\\"','"',$x); }
function PVS($x)
{ return preg_replace("/\n[^\\S\n]*(?=\n)/", "\n<:vspace>", $x); }
function PVSE($x) { return PVS(htmlspecialchars($x, ENT_NOQUOTES)); }
function PZZ($x,$y='') { return ''; }
function PRR($x=NULL)
{ if ($x || is_null($x)) $GLOBALS['RedoMarkupLine']++; return $x; }
function PUE($x)
{ return preg_replace('/[\\x80-\\xff \'"<>]/e', "'%'.dechex(ord('$0'))", $x); }
function PQA($x) {
$out = '';
if (preg_match_all('/([a-zA-Z]+)\\s*=\\s*("[^"]*"|\'[^\']*\'|\\S*)/',
$x, $attr, PREG_SET_ORDER)) {
foreach($attr as $a) {
if (preg_match('/^on/i', $a[1])) continue;
$out .= $a[1] . '='
. preg_replace( '/^(?![\'"]).*$/e',
"\"'\".str_replace(\"'\", ''', PSS('$0')).\"'\"", $a[2])
. ' ';
}
}
return $out;
}
function SDV(&$v,$x) { if (!isset($v)) $v=$x; }
function SDVA(&$var,$val)
{ foreach($val as $k=>$v) if (!isset($var[$k])) $var[$k]=$v; }
function IsEnabled(&$var,$f=0)
{ return (isset($var)) ? $var : $f; }
function SetTmplDisplay($var, $val)
{ NoCache(); $GLOBALS['TmplDisplay'][$var] = $val; }
function NoCache($x = '') { $GLOBALS['NoHTMLCache'] |= 1; return $x; }
function ParseArgs($x, $optpat = '(?>(\\w+)[:=])') {
$z = array();
preg_match_all("/($optpat|[-+])?(\"[^\"]*\"|'[^']*'|\\S+)/",
$x, $terms, PREG_SET_ORDER);
foreach($terms as $t) {
$v = preg_replace('/^([\'"])?(.*)\\1$/', '$2', $t[3]);
if ($t[2]) { $z['#'][] = $t[2]; $z[$t[2]] = $v; }
else { $z['#'][] = $t[1]; $z[$t[1]][] = $v; }
$z['#'][] = $v;
}
return $z;
}
function StopWatch($x) {
global $StopWatch, $EnableStopWatch;
if (!$EnableStopWatch) return;
static $wstart = 0, $ustart = 0;
list($usec,$sec) = explode(' ',microtime());
$wtime = ($sec+$usec);
if (!$wstart) $wstart = $wtime;
if ($EnableStopWatch != 2)
{ $StopWatch[] = sprintf("%05.2f %s", $wtime-$wstart, $x); return; }
$dat = getrusage();
$utime = ($dat['ru_utime.tv_sec']+$dat['ru_utime.tv_usec']/1000000);
if (!$ustart) $ustart=$utime;
$StopWatch[] =
sprintf("%05.2f %05.2f %s", $wtime-$wstart, $utime-$ustart, $x);
}
## DRange converts a variety of string formats into date (ranges).
## It returns the start and end timestamps (+1 second) of the specified date.
function DRange($when) {
global $Now;
## unix/posix @timestamp dates
if (preg_match('/^\\s*@(\\d+)\\s*(.*)$/', $when, $m)) {
$t0 = $m[2] ? strtotime($m[2], $m[1]) : $m[1];
return array($t0, $t0+1);
}
## ISO-8601 dates
$dpat = '/
(?<!\\d) # non-digit
(19\\d\\d|20[0-3]\\d) # year ($1)
([-.\\/]?) # date separator ($2)
(0\\d|1[0-2]) # month ($3)
(?: \\2 # repeat date separator
([0-2]\\d|3[0-1]) # day ($4)
(?: T # time marker
([01]\\d|2[0-4]) # hour ($5)
([.:]?) # time separator ($6)
([0-5]\\d) # minute ($7)
(?: \\6 # repeat time separator
([0-5]\\d|60) # seconds ($8)
)? # optional :ss
)? # optional Thh:mm:ss
)? # optional -ddThh:mm:ss
(?!\d) # non-digit
/x';
if (preg_match($dpat, $when, $m)) {
$n = $m;
## if no time given, assume range of 1 day (except when full month)
if (@$m[4]>'' && @$m[5] == '') { @$n[4]++; }
## if no day given, assume 1st of month and full month range
if (@$m[4] == '') { $m[4] = 1; $n[4] = 1; $n[3]++; }
## if no seconds given, assume range of 1 minute (except when full day)
if (@$m[7]>'' && @$m[8] == '') { @$n[7]++; }
$t0 = @mktime($m[5], $m[7], $m[8], $m[3], $m[4], $m[1]);
$t1 = @mktime($n[5], $n[7], $n[8], $n[3], $n[4], $n[1]);
return array($t0, $t1);
}
## now, today, tomorrow, yesterday
NoCache();
if ($when == 'now') return array($Now, $Now+1);
$m = localtime(time());
if ($when == 'tomorrow') { $m[3]++; $when = 'today'; }
if ($when == 'yesterday') { $m[3]--; $when = 'today'; }
if ($when == 'today')
return array(mktime(0, 0, 0, $m[4]+1, $m[3] , $m[5]+1900),
mktime(0, 0, 0, $m[4]+1, $m[3]+1, $m[5]+1900));
if (preg_match('/^\\s*$/', $when)) return array(-1, -1);
$t0 = strtotime($when);
$t1 = strtotime("+1 day", $t0);
return array($t0, $t1);
}
## AsSpaced converts a string with WikiWords into a spaced version
## of that string. (It can be overridden via $AsSpacedFunction.)
function AsSpaced($text) {
$text = preg_replace("/([[:lower:]\\d])([[:upper:]])/", '$1 $2', $text);
$text = preg_replace('/([^-\\d])(\\d[-\\d]*( |$))/','$1 $2',$text);
return preg_replace("/([[:upper:]])([[:upper:]][[:lower:]\\d])/",
'$1 $2', $text);
}
## Lock is used to make sure only one instance of PmWiki is running when
## files are being written. It does not "lock pages" for editing.
function Lock($op) {
global $WorkDir, $LockFile, $EnableReadOnly;
if ($op > 0 && IsEnabled($EnableReadOnly, 0))
Abort('Cannot modify site -- $EnableReadOnly is set', 'readonly');
SDV($LockFile, "$WorkDir/.flock");
mkdirp(dirname($LockFile));
static $lockfp,$curop;
if (!$lockfp) $lockfp = @fopen($LockFile, "w");
if (!$lockfp) {
if ($op <= 0) return;
@unlink($LockFile);
$lockfp = fopen($LockFile,"w") or
Abort('Cannot acquire lockfile', 'flock');
fixperms($LockFile);
}
if ($op<0) { flock($lockfp,LOCK_UN); fclose($lockfp); $lockfp=0; $curop=0; }
elseif ($op==0) { flock($lockfp,LOCK_UN); $curop=0; }
elseif ($op==1 && $curop<1)
{ session_write_close(); flock($lockfp,LOCK_SH); $curop=1; }
elseif ($op==2 && $curop<2)
{ session_write_close(); flock($lockfp,LOCK_EX); $curop=2; }
}
## mkdirp creates a directory and its parents as needed, and sets
## permissions accordingly.
function mkdirp($dir) {
global $ScriptUrl;
if (file_exists($dir)) return;
if (!file_exists(dirname($dir))) mkdirp(dirname($dir));
if (mkdir($dir, 0777)) {
fixperms($dir);
if (@touch("$dir/xxx")) { unlink("$dir/xxx"); return; }
rmdir($dir);
}
$parent = realpath(dirname($dir));
$bdir = basename($dir);
$perms = decoct(fileperms($parent) & 03777);
$msg = "PmWiki needs to have a writable <tt>$dir/</tt> directory
before it can continue. You can create the directory manually
by executing the following commands on your server:
<pre> mkdir $parent/$bdir\n chmod 777 $parent/$bdir</pre>
Then, <a href='{$ScriptUrl}'>reload this page</a>.";
$safemode = ini_get('safe_mode');
if (!$safemode) $msg .= "<br /><br />Or, for a slightly more
secure installation, try executing <pre> chmod 2777 $parent</pre>
on your server and following <a target='_blank' href='$ScriptUrl'>
this link</a>. Afterwards you can restore the permissions to
their current setting by executing <pre> chmod $perms $parent</pre>.";
Abort($msg);
}
## fixperms attempts to correct permissions on a file or directory
## so that both PmWiki and the account (current dir) owner can manipulate it
function fixperms($fname, $add = 0) {
clearstatcache();
if (!file_exists($fname)) Abort('?no such file');
$bp = 0;
if (fileowner($fname)!=@fileowner('.')) $bp = (is_dir($fname)) ? 007 : 006;
if (filegroup($fname)==@filegroup('.')) $bp <<= 3;
$bp |= $add;
if ($bp && (fileperms($fname) & $bp) != $bp)
@chmod($fname,fileperms($fname)|$bp);
}
## GlobToPCRE converts wildcard patterns into pcre patterns for
## inclusion and exclusion. Wildcards beginning with '-' or '!'
## are treated as things to be excluded.
function GlobToPCRE($pat) {
$pat = preg_quote($pat, '/');
$pat = str_replace(array('\\*', '\\?', '\\[', '\\]', '\\^', '\\-', '\\!'),
array('.*', '.', '[', ']', '^', '-', '!'), $pat);
$excl = array(); $incl = array();
foreach(preg_split('/,+\s?/', $pat, -1, PREG_SPLIT_NO_EMPTY) as $p) {
if ($p{0} == '-' || $p{0} == '!') $excl[] = '^'.substr($p, 1).'$';
else $incl[] = "^$p$";
}
return array(implode('|', $incl), implode('|', $excl));
}
## FixGlob changes wildcard patterns without '.' to things like
## '*.foo' (name matches) or 'foo.*' (group matches).
function FixGlob($x, $rep = '$1*.$2') {
return preg_replace('/([\\s,][-!]?)([^\\/.\\s,]+)(?=[\\s,])/', $rep, ",$x,");
}
## MatchPageNames reduces $pagelist to those pages with names
## matching the pattern(s) in $pat. Patterns can be either
## regexes to include ('/'), regexes to exclude ('!'), or
## wildcard patterns (all others).
function MatchPageNames($pagelist, $pat) {
global $Charset;
$pcre8 = ($Charset == 'UTF-8')? 'u' : ''; # allow range matches in utf8
$pagelist = (array)$pagelist;
foreach((array)$pat as $p) {
if (count($pagelist) < 1) break;
if (!$p) continue;
switch ($p{0}) {
case '/':
$pagelist = preg_grep($p, $pagelist);
continue;
case '!':
$pagelist = array_diff($pagelist, preg_grep($p, $pagelist));
continue;
default:
list($inclp, $exclp) = GlobToPCRE(str_replace('/', '.', $p));
if ($exclp)
$pagelist = array_diff($pagelist, preg_grep("/$exclp/i$pcre8", $pagelist));
if ($inclp)
$pagelist = preg_grep("/$inclp/i$pcre8", $pagelist);
}
}
return $pagelist;
}
## ResolvePageName "normalizes" a pagename based on the current
## settings of $DefaultPage and $PagePathFmt. It's normally used
## during initialization to fix up any missing or partial pagenames.
function ResolvePageName($pagename) {
global $DefaultPage, $DefaultGroup, $DefaultName,
$GroupPattern, $NamePattern, $EnableFixedUrlRedirect;
SDV($DefaultPage, "$DefaultGroup.$DefaultName");
$pagename = preg_replace('!([./][^./]+)\\.html$!', '$1', $pagename);
if ($pagename == '') return $DefaultPage;
$p = MakePageName($DefaultPage, $pagename);
if (!preg_match("/^($GroupPattern)[.\\/]($NamePattern)$/i", $p)) {
header('HTTP/1.1 404 Not Found');
Abort('$[?invalid page name]');
}
if (preg_match("/^($GroupPattern)[.\\/]($NamePattern)$/i", $pagename))
return $p;
if (IsEnabled($EnableFixedUrlRedirect, 1)
&& $p && (PageExists($p) || preg_match('/[\\/.]/', $pagename)))
{ Redirect($p); exit(); }
return MakePageName($DefaultPage, "$pagename.$pagename");
}
## MakePageName is used to convert a string $str into a fully-qualified
## pagename. If $str doesn't contain a group qualifier, then
## MakePageName uses $basepage and $PagePathFmt to determine the
## group of the returned pagename.
function MakePageName($basepage, $str) {
global $MakePageNameFunction, $PageNameChars, $PagePathFmt,
$MakePageNamePatterns;
if (@$MakePageNameFunction) return $MakePageNameFunction($basepage, $str);
SDV($PageNameChars,'-[:alnum:]');
SDV($MakePageNamePatterns, array(
"/'/" => '', # strip single-quotes
"/[^$PageNameChars]+/" => ' ', # convert everything else to space
'/((^|[^-\\w])\\w)/e' => "strtoupper('$1')",
'/ /' => ''));
$str = preg_replace('/[#?].*$/', '', $str);
$m = preg_split('/[.\\/]/', $str);
if (count($m)<1 || count($m)>2 || $m[0]=='') return '';
## handle "Group.Name" conversions
if (@$m[1] > '') {
$group = preg_replace(array_keys($MakePageNamePatterns),
array_values($MakePageNamePatterns), $m[0]);
$name = preg_replace(array_keys($MakePageNamePatterns),
array_values($MakePageNamePatterns), $m[1]);
return "$group.$name";
}
$name = preg_replace(array_keys($MakePageNamePatterns),
array_values($MakePageNamePatterns), $m[0]);
$isgrouphome = count($m) > 1;
foreach((array)$PagePathFmt as $pg) {
if ($isgrouphome && strncmp($pg, '$1.', 3) !== 0) continue;
$pn = FmtPageName(str_replace('$1', $name, $pg), $basepage);
if (PageExists($pn)) return $pn;
}
if ($isgrouphome) {
foreach((array)$PagePathFmt as $pg)
if (strncmp($pg, '$1.', 3) == 0)
return FmtPageName(str_replace('$1', $name, $pg), $basepage);
return "$name.$name";
}
return preg_replace('/[^\\/.]+$/', $name, $basepage);
}
## MakeBaseName uses $BaseNamePatterns to return the "base" form
## of a given pagename -- i.e., stripping any recipe-defined
## prefixes or suffixes from the page.
function MakeBaseName($pagename, $patlist = NULL) {
global $BaseNamePatterns;
if (is_null($patlist)) $patlist = (array)@$BaseNamePatterns;
foreach($patlist as $pat => $rep)
$pagename = preg_replace($pat, $rep, $pagename);
return $pagename;
}
## PCache caches basic information about a page and its attributes--
## usually everything except page text and page history. This makes
## for quicker access to certain values in PageVar below.
function PCache($pagename, $page) {
global $PCache;
foreach($page as $k=>$v)
if ($k!='text' && strpos($k,':')===false) $PCache[$pagename][$k]=$v;
}
## SetProperty saves a page property into $PCache. For convenience
## it returns the $value of the property just set. If $sep is supplied,
## then $value is appended to the current property (with $sep as
## as separator) instead of replacing it. If $keep is suplied and the
## property already exists, then $value will be ignored.
function SetProperty($pagename, $prop, $value, $sep=NULL, $keep=NULL) {
global $PCache, $KeepToken;
NoCache();
$prop = "=p_$prop";
$value = preg_replace("/$KeepToken(\\d.*?)$KeepToken/e",
"\$GLOBALS['KPV']['$1']", $value);
if (!is_null($sep) && isset($PCache[$pagename][$prop]))
$value = $PCache[$pagename][$prop] . $sep . $value;
if (is_null($keep) || !isset($PCache[$pagename][$prop]))
$PCache[$pagename][$prop] = $value;
return $PCache[$pagename][$prop];
}
## PageTextVar loads a page's text variables (defined by
## $PageTextVarPatterns) into a page's $PCache entry, and returns
## the property associated with $var.
function PageTextVar($pagename, $var) {
global $PCache, $PageTextVarPatterns, $MaxPageTextVars;
SDV($MaxPageTextVars, 500);
static $status;
if(@$status["$pagename:$var"]++ > $MaxPageTextVars) return '';
if (!@$PCache[$pagename]['=pagetextvars']) {
$pc = &$PCache[$pagename];
$pc['=pagetextvars'] = 1;
$page = RetrieveAuthPage($pagename, 'read', false, READPAGE_CURRENT);
if ($page) {
foreach((array)$PageTextVarPatterns as $pat)
if (preg_match_all($pat, IsEnabled($PCache[$pagename]['=preview'],@$page['text']),
$match, PREG_SET_ORDER))
foreach($match as $m) {
$t = preg_replace("/\\{\\$:{$m[2]}\\}/", '', $m[3]);
$pc["=p_{$m[2]}"] = Qualify($pagename, $t);
}
}
}
return @$PCache[$pagename]["=p_$var"];
}
function PageVar($pagename, $var, $pn = '') {
global $Cursor, $PCache, $FmtPV, $AsSpacedFunction, $ScriptUrl,
$EnablePathInfo;
if ($var == '$ScriptUrl') return PUE($ScriptUrl);
if ($pn) {
$pn = isset($Cursor[$pn]) ? $Cursor[$pn] : MakePageName($pagename, $pn);
} else $pn = $pagename;
if ($pn) {
if (preg_match('/^(.+)[.\\/]([^.\\/]+)$/', $pn, $match)
&& !isset($PCache[$pn]['time'])
&& (!@$FmtPV[$var] || strpos($FmtPV[$var], '$page') !== false))
{ $page = ReadPage($pn, READPAGE_CURRENT); PCache($pn, $page); }
@list($d, $group, $name) = $match;
$page = &$PCache[$pn];
} else { $group = ''; $name = ''; }
if (@$FmtPV[$var]) return eval("return ({$FmtPV[$var]});");
if (strncmp($var, '$:', 2)==0) return PageTextVar($pn, substr($var, 2));
return '';
}
## FmtPageName handles $[internationalization] and $Variable
## substitutions in strings based on the $pagename argument.
function FmtPageName($fmt, $pagename) {
# Perform $-substitutions on $fmt relative to page given by $pagename
global $GroupPattern, $NamePattern, $EnablePathInfo, $ScriptUrl,
$GCount, $UnsafeGlobals, $FmtV, $FmtP, $FmtPV, $PCache, $AsSpacedFunction;
if (strpos($fmt,'$')===false) return $fmt;
$fmt = preg_replace('/\\$([A-Z]\\w*Fmt)\\b/e','$GLOBALS[\'$1\']',$fmt);
$fmt = preg_replace('/\\$\\[(?>([^\\]]+))\\]/e',"XL(PSS('$1'))",$fmt);
$fmt = str_replace('{$ScriptUrl}', '$ScriptUrl', $fmt);
$fmt =
preg_replace('/\\{(\\$[A-Z]\\w+)\\}/e', "PageVar(\$pagename, '$1')", $fmt);
if (strpos($fmt,'$')===false) return $fmt;
if ($FmtP) $fmt = preg_replace(array_keys($FmtP), array_values($FmtP), $fmt);
static $pv, $pvpat;
if ($pv != count($FmtPV)) {
$pvpat = str_replace('$', '\\$', implode('|', array_keys($FmtPV)));
$pv = count($FmtPV);
}
$fmt = preg_replace("/(?:$pvpat)\\b/e", "PageVar(\$pagename, '$0')", $fmt);
$fmt = preg_replace('!\\$ScriptUrl/([^?#\'"\\s<>]+)!e',
(@$EnablePathInfo) ? "'$ScriptUrl/'.PUE('$1')" :
"'$ScriptUrl?n='.str_replace('/','.',PUE('$1'))",
$fmt);
if (strpos($fmt,'$')===false) return $fmt;
static $g;
if ($GCount != count($GLOBALS)+count($FmtV)) {
$g = array();
foreach($GLOBALS as $n=>$v) {
if (is_array($v) || is_object($v) ||
isset($FmtV["\$$n"]) || in_array($n,$UnsafeGlobals)) continue;
$g["\$$n"] = $v;
}
$GCount = count($GLOBALS)+count($FmtV);
krsort($g); reset($g);
}
$fmt = str_replace(array_keys($g),array_values($g),$fmt);
$fmt = preg_replace('/(?>(\\$[[:alpha:]]\\w+))/e',
"isset(\$FmtV['$1']) ? \$FmtV['$1'] : '$1'", $fmt);
return $fmt;
}
## FmtTemplateVars uses $vars to replace all occurrences of
## {$$key} in $text with $vars['key'].
function FmtTemplateVars($text, $vars, $pagename = NULL) {
global $FmtPV;
if ($pagename) {
$pat = implode('|', array_map('preg_quote', array_keys($FmtPV)));
$text = preg_replace("/\\{\\$($pat)\\}/e",
"PageVar('$pagename', '$1')", $text);
}
foreach(preg_grep('/^[\\w$]/', array_keys($vars)) as $k)
if (!is_array($vars[$k]))
$text = str_replace("{\$\$$k}", $vars[$k], $text);
return $text;
}
## The XL functions provide translation tables for $[i18n] strings
## in FmtPageName().
function XL($key) {
global $XL,$XLLangs;
foreach($XLLangs as $l) if (isset($XL[$l][$key])) return $XL[$l][$key];
return $key;
}
function XLSDV($lang,$a) {
global $XL;
foreach($a as $k=>$v) { if (!isset($XL[$lang][$k])) $XL[$lang][$k]=$v; }
}
function XLPage($lang,$p) {
global $TimeFmt,$XLLangs,$FarmD;
$page = ReadPage($p, READPAGE_CURRENT);
if (!$page) return;
$text = preg_replace("/=>\\s*\n/",'=> ',@$page['text']);
foreach(explode("\n",$text) as $l)
if (preg_match('/^\\s*[\'"](.+?)[\'"]\\s*=>\\s*[\'"](.+)[\'"]/',$l,$match))
$xl[stripslashes($match[1])] = stripslashes($match[2]);
if (isset($xl)) {
if (@$xl['xlpage-i18n']) {
$i18n = preg_replace('/[^-\\w]/','',$xl['xlpage-i18n']);
include_once("$FarmD/scripts/xlpage-$i18n.php");
}
if (@$xl['Locale']) setlocale(LC_ALL,$xl['Locale']);
if (@$xl['TimeFmt']) $TimeFmt=$xl['TimeFmt'];
if (!in_array($lang, $XLLangs)) array_unshift($XLLangs, $lang);
XLSDV($lang,$xl);
}
}
## CmpPageAttr is used with uksort to order a page's elements with
## the latest items first. This can make some operations more efficient.
function CmpPageAttr($a, $b) {
@list($x, $agmt) = explode(':', $a);
@list($x, $bgmt) = explode(':', $b);
if ($agmt != $bgmt)
return ($agmt==0 || $bgmt==0) ? $agmt - $bgmt : $bgmt - $agmt;
return strcmp($a, $b);
}
## class PageStore holds objects that store pages via the native
## filesystem.
class PageStore {
var $dirfmt;
var $iswrite;
var $attr;
function PageStore($d='$WorkDir/$FullName', $w=0, $a=NULL) {
$this->dirfmt = $d; $this->iswrite = $w; $this->attr = (array)$a;
$GLOBALS['PageExistsCache'] = array();
}
function pagefile($pagename) {
global $FarmD;
$dfmt = $this->dirfmt;
if ($pagename > '') {
$pagename = str_replace('/', '.', $pagename);
if ($dfmt == 'wiki.d/{$FullName}') # optimizations for
return "wiki.d/$pagename"; # standard locations
if ($dfmt == '$FarmD/wikilib.d/{$FullName}') #
return "$FarmD/wikilib.d/$pagename"; #
if ($dfmt == 'wiki.d/{$Group}/{$FullName}')
return preg_replace('/([^.]+).*/', 'wiki.d/$1/$0', $pagename);
}
return FmtPageName($dfmt, $pagename);
}
function read($pagename, $since=0) {
$newline = '';
$urlencoded = false;
$pagefile = $this->pagefile($pagename);
if ($pagefile && ($fp=@fopen($pagefile, "r"))) {
$page = $this->attr;
while (!feof($fp)) {
$line = fgets($fp, 4096);
while (substr($line, -1, 1) != "\n" && !feof($fp))
{ $line .= fgets($fp, 4096); }
$line = rtrim($line);
if ($urlencoded) $line = urldecode(str_replace('+', '%2b', $line));
@list($k,$v) = explode('=', $line, 2);
if (!$k) continue;
if ($k == 'version') {
$ordered = (strpos($v, 'ordered=1') !== false);
$urlencoded = (strpos($v, 'urlencoded=1') !== false);
if (strpos($v, 'pmwiki-0.')!==false) $newline="\262";
}
if ($k == 'newline') { $newline = $v; continue; }
if ($since > 0 && preg_match('/:(\\d+)/', $k, $m) && $m[1] < $since) {
if ($ordered) break;
continue;
}
if ($newline) $v = str_replace($newline, "\n", $v);
$page[$k] = $v;
}
fclose($fp);
}
return @$page;
}
function write($pagename,$page) {
global $Now, $Version;
$page['name'] = $pagename;
$page['time'] = $Now;
$page['host'] = $_SERVER['REMOTE_ADDR'];
$page['agent'] = @$_SERVER['HTTP_USER_AGENT'];
$page['rev'] = @$page['rev']+1;
unset($page['version']); unset($page['newline']);
uksort($page, 'CmpPageAttr');
$s = false;
$pagefile = $this->pagefile($pagename);
$dir = dirname($pagefile); mkdirp($dir);
if (!file_exists("$dir/.htaccess") && $fp = @fopen("$dir/.htaccess", "w"))
{ fwrite($fp, "Order Deny,Allow\nDeny from all\n"); fclose($fp); }
if ($pagefile && ($fp=fopen("$pagefile,new","w"))) {
$r0 = array('%', "\n", '<');
$r1 = array('%25', '%0a', '%3c');
$x = "version=$Version ordered=1 urlencoded=1\n";
$s = true && fputs($fp, $x); $sz = strlen($x);
foreach($page as $k=>$v)
if ($k > '' && $k{0} != '=') {
$x = str_replace($r0, $r1, "$k=$v") . "\n";
$s = $s && fputs($fp, $x); $sz += strlen($x);
}
$s = fclose($fp) && $s;
$s = $s && (filesize("$pagefile,new") > $sz * 0.95);
if (file_exists($pagefile)) $s = $s && unlink($pagefile);
$s = $s && rename("$pagefile,new", $pagefile);
}
$s && fixperms($pagefile);
if (!$s)
Abort("Cannot write page to $pagename ($pagefile)...changes not saved");
PCache($pagename, $page);
}
function exists($pagename) {
if (!$pagename) return false;
$pagefile = $this->pagefile($pagename);
return ($pagefile && file_exists($pagefile));
}
function delete($pagename) {
global $Now;
$pagefile = $this->pagefile($pagename);
@rename($pagefile,"$pagefile,del-$Now");
}
function ls($pats=NULL) {
global $GroupPattern, $NamePattern;
StopWatch("PageStore::ls begin {$this->dirfmt}");
$pats=(array)$pats;
array_push($pats, "/^$GroupPattern\.$NamePattern$/");
$dir = $this->pagefile('$Group.$Name');
$maxslash = substr_count($dir, '/');
$dirlist = array(preg_replace('!/*[^/]*\\$.*$!','',$dir));
$out = array();
while (count($dirlist)>0) {
$dir = array_shift($dirlist);
$dfp = @opendir($dir); if (!$dfp) { continue; }
$dirslash = substr_count($dir, '/') + 1;
$o = array();
while ( ($pagefile = readdir($dfp)) !== false) {
if ($pagefile{0} == '.') continue;
if ($dirslash < $maxslash && is_dir("$dir/$pagefile"))
{ array_push($dirlist,"$dir/$pagefile"); continue; }
if ($dirslash == $maxslash) $o[] = $pagefile;
}
closedir($dfp);
StopWatch("PageStore::ls merge {$this->dirfmt}");
$out = array_merge($out, MatchPageNames($o, $pats));
}
StopWatch("PageStore::ls end {$this->dirfmt}");