-
Notifications
You must be signed in to change notification settings - Fork 21
/
wikilib.php
5870 lines (5180 loc) · 177 KB
/
wikilib.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
// Copyright 2003-2022 Won-Kyu Park <wkpark at kldp.org> all rights reserved.
// distributable under GPL see COPYING
//
// many codes are imported from the MoinMoin
// some codes are reused from the Phiki
//
// * MoinMoin is a python based wiki clone based on the PikiPiki
// by Ju"rgen Hermann <jhs at web.de>
// * PikiPiki is a python based wiki clone by MartinPool
// * Phiki is a php based wiki clone based on the MoinMoin
// by Fred C. Yankowski <fcy at acm.org>
//
function _preg_escape($val) {
return preg_replace('/([\$\^\.\[\]\{\}\|\(\)\+\*\/\\\\!\?]{1})/','\\\\\1',$val);
}
function _preg_search_escape($val) {
return preg_replace('/([\/]{1})/','\\\\\1',$val);
}
function _mkdir_p($target,$mode=0777) {
// from php.net/mkdir user contributed notes
if (file_exists($target)) {
if (!is_dir($target)) return false;
else return true;
}
// recursivly create dirs.
return (_mkdir_p(dirname($target),$mode) and mkdir($target,$mode));
}
/**
* Check double slashes in the REQUEST_URI
* and try to get the PATH_INFO or parse the PHP_SELF.
*
* @author Won-Kyu Park <[email protected]>
* @since 2015/12/14
* @since 1.2.5
*
* @return string
*/
function get_pathinfo() {
if (!isset($_SERVER['PATH_INFO'])) {
// the PATH_INFO not available.
// try to get the PATH_INFO from the PHP_SELF.
$path_parts = explode('/', $_SERVER['PHP_SELF']);
// remove all real path parts from PHP_SELF
$root = $_SERVER['DOCUMENT_ROOT'];
$path = $root;
foreach ($path_parts as $k=>$part) {
if ($part === '')
continue;
$path .= '/'.$part;
if (file_exists($path))
unset($path_parts[$k]);
else
break;
}
// combine remaining parts
$_SERVER['PATH_INFO'] = implode('/', $path_parts);
}
// if REQUEST_URI is not available.
if (!isset($_SERVER['REQUEST_URI']))
return $_SERVER['PATH_INFO'];
// check double slashes in the REQUEST_URI if it available
//
// from MediaWikiSrc:WebRequest.php source code
// by Apache 2.x, double slashes are converted to single slashes.
// and PATH_INFO is mangled due to https://bugs.php.net/bug.php?id=31892
$uri = $_SERVER['REQUEST_URI'];
if (($p = strpos($uri, '?')) !== false) {
// remove the query string part.
$uri = substr($uri, 0, $p);
}
// rawurldecode REQUEST_URI
$decoded_uri = rawurldecode($uri);
if (strpos($decoded_uri, '//') === false)
return $_SERVER['PATH_INFO'];
return guess_pathinfo($decoded_uri);
}
/**
* Try to get PATH_INFO from the REQUEST_URI
*
* @author Won-Kyu Park <[email protected]>
* @since 2015/12/14
* @since 1.2.5
*
* @return string
*/
function guess_pathinfo($decoded_uri) {
// try to get PATH_INFO from the REQUEST_URI
// $uri = rawurldecode($_SERVER['REQUEST_URI']);
// split all parts of REQUEST_URI.
$parts = preg_split('@(/)@', $decoded_uri, -1, PREG_SPLIT_DELIM_CAPTURE);
// /foo//bar/foo => '','/','foo','/','','/','bar','/','foo'
// try to get the PATH_INFO path parts
if ($_SERVER['PATH_INFO'] == '/') {
$pos = count($parts) - 1;
} else {
$path = explode('/', $_SERVER['PATH_INFO']);
// search unmatch REQUEST_URI part
$pos = count($parts) - 1;
for (; $pos > 0; $pos--) {
if ($parts[$pos] == '' || $parts[$pos] == '/')
continue;
$part = end($path);
if ($parts[$pos] != $part)
break;
array_pop($path);
}
}
// skip all path components
for (; $pos > 0; $pos--) {
if ($parts[$pos] == '' || $parts[$pos] == '/')
continue;
else
break;
}
// remove non path components.
for (; $pos > 0; $pos--)
unset($parts[$pos]);
// merge all path components.
return implode('', $parts);
}
function get_scriptname() {
// Return full URL of current page.
// $_SERVER["SCRIPT_NAME"] has bad value under CGI mode
// set 'cgi.fix_pathinfo=1' in the php.ini under
// apache 2.0.x + php4.2.x Win32
// check mod_rewrite
if (strpos($_SERVER['REQUEST_URI'],$_SERVER['SCRIPT_NAME'])===false) {
if ($_SERVER['REQUEST_URI'][0] == '/' and ($p = strpos($_SERVER['REQUEST_URI'], '/', 1)) !== false) {
$prefix = substr($_SERVER['REQUEST_URI'], 0, $p);
if (($p = strpos($_SERVER['SCRIPT_NAME'], $prefix)) === 0)
return $prefix;
}
return '';
}
return $_SERVER['SCRIPT_NAME'];
}
/**
* get the number of lines in a file
*
* @author [email protected]
* @since 2010/09/13
*
*/
function get_file_lines($filename) {
$fp = fopen($filename, 'r');
if (!is_resource($fp)) return 0;
// test \n or \r or \r\n
$i = 0;
while(($test = fgets($fp, 4096)) and !preg_match("/(\r|\r\n|\n)$/", $test, $match)) $i++;
$i = 1;
$bsz = 1024 * 8;
if (isset($match[1])) {
while ($chunk = fread($fp, $bsz))
$i += substr_count($chunk, $match[1]);
}
fclose($fp);
return $i;
}
/**
* counting add/del lines of a given diff
*
* @author [email protected]
* @since 2015/06/08
* @param string $diff - diff -u output
* @return array - return added/deleted lines
*/
function diffcount_simple($diff) {
$retval = &$params['retval'];
$lines = explode("\n", $diff);
$lsz = sizeof($lines);
$add = 0;
$del = 0;
for ($i = 0; $i < $lsz; $i++) {
$marker = $lines[$i][0];
if (!in_array($marker, array('-','+'))) {
continue;
}
if ($marker == '-')
$del++;
else
$add++;
}
return array($add, $del, 0, 0);
}
/**
* counting add/del lines and chars of a given diff
*
* @author [email protected]
* @since 2015/06/08
* @param string $diff - diff -u output
* @return array - return added/deleted chars and lines
*/
function diffcount_lines($diff, $charset) {
$lines = explode("\n", $diff);
$lsz = sizeof($lines);
if ($lines[$lsz - 1] == '') {
// trash last empty line
array_pop($lines);
$lsz--;
}
$add = 0;
$del = 0;
$add_chars = 0;
$del_chars = 0;
$minorfix = true;
$orig = array();
$new = array();
$om = false;
for ($i = 0; $i < $lsz; $i++) {
$line = &$lines[$i];
if (!isset($line[0])) break;
$mark = $line[0];
if (!$om && $mark == '-' && isset($line[3]) && substr($line, 0, 4) == '--- ') {
// trash first --- blah\n+++ blah\n lines
$i++;
continue;
}
$line = substr($line, 1);
if ($mark == '@') {
continue;
} else if ($mark == '-') {
$om = true;
$orig[] = $line;
$del++;
continue;
} else if ($mark == '+') {
$om = true;
$new[] = $line;
$add++;
continue;
} else if ($om) {
$om = false;
$diffchars = diffcount_chars($orig, $new, $charset);
if ($diffchars === false) {
// simply check the difference of strlen
$nc = mb_strlen(implode("\n", $new), $charset);
$oc = mb_strlen(implode("\n", $orig), $charset);
$added = $nc - $oc;
if ($added > 0)
$add_chars+= $added;
else
$del_chars+= -$added;
} else {
$add_chars+= $diffchars[0];
$del_chars+= $diffchars[1];
}
// is it minorfix ?
if (!$diffchars[2]) $minorfix = false;
$orig = array();
$new = array();
}
}
if (!empty($orig) or !empty($new)) {
$diffchars = diffcount_chars($orig, $new, $charset);
if ($diffchars === false) {
// simply check the difference of strlen
$nc = mb_strlen(implode("\n", $new), $charset);
$oc = mb_strlen(implode("\n", $orig), $charset);
$added = $nc - $oc;
if ($added > 0)
$add_chars+= $added;
else
$del_chars+= -$added;
} else {
$add_chars+= $diffchars[0];
$del_chars+= $diffchars[1];
}
// is it minorfix ?
if (!$diffchars[2]) $minorfix = false;
}
return array($add, $del, $add_chars, $del_chars, $minorfix);
}
/**
* counting add/del chars of a given array
*
* @author [email protected]
* @since 2015/06/08
* @param array $orig - original lines
* @param array $new - modified lines
* @param string $charet - character set
* @return array added,deleted chars
*/
function diffcount_chars($orig, $new, $charset) {
$oc = count($orig);
$nc = count($new);
if ($oc > 200 or $nc > 200) {
// too big to call WordLevelDiff.
return false;
}
include_once('lib/difflib.php');
$add_chars = 0;
$del_chars = 0;
$minorfix = true;
$result = new WordLevelDiff($orig, $new, $charset);
foreach ($result->edits as $edit) {
if (is_a($edit, '_DiffOp_Copy')) {
continue;
} elseif (is_a($edit, '_DiffOp_Add')) {
$chunk = str_replace(' ', "\n", implode('', $edit->_final));
$chunk = preg_replace('@(\n|\s)+@m', '', $chunk);
$add = mb_strlen($chunk, $charset);
if ($add > 3) $minorfix = false;
$add_chars+= $add;
} elseif (is_a($edit, '_DiffOp_Delete')) {
$del = mb_strlen(implode('', $edit->orig), $charset);
if ($del > 3) $minorfix = false;
$del_chars+= $del;
} elseif (is_a($edit, '_DiffOp_Change')) {
$del_change = mb_strlen(implode('', $edit->orig), $charset);
$add_change = mb_strlen(implode('', $edit->_final), $charset);
if (abs($add_change - $del_change) > 5) $minorfix = false;
$del_chars+= $del_change;
$add_chars+= $add_change;
}
}
return array($add_chars, $del_chars, $minorfix);
}
/**
* Extracted from Gallery Plugin
*
* make pagelist to paginate.
*
* @author [email protected]
* @since 2003/08/10
* @param integer $pages - the number of pages
* @param string $action - link to page action
* @param integer $curpage - current page
* @param integer $listcount - the number of pages to show
*/
function get_pagelist($formatter,$pages,$action,$curpage=1,$listcount=10,$bra="[",$cat="]",$sep="|",$prev="«",$next="»",$first="",$last="",$ellip="...") {
if ($curpage >=0)
if ($curpage > $pages)
$curpage=$pages;
if ($curpage <= 0)
$curpage=1;
$startpage=intval(($curpage-1) / $listcount)*$listcount +1;
$pnut="";
if ($startpage > 1) {
$prevref=$startpage-1;
if (!$first) {
$prev_l=$formatter->link_tag('',$action.$prevref,$prev);
$prev_1=$formatter->link_tag('',$action."1","1");
$pnut="$prev_l".$bra.$prev_1.$cat.$ellip.$bar;
}
} else {
$pnut=$prev.$bra."";
}
for ($i=$startpage;$i < ($startpage + $listcount) && $i <=$pages; $i++) {
if ($i != $startpage)
$pnut.=$sep;
if ($i != $curpage) {
$link=$formatter->link_tag('',$action.$i,$i);
$pnut.=$link;
} else
$pnut.="<b>$i</b>";
}
if ($i <= $pages) {
if (!$last) {
$next_l=$formatter->link_tag('',$action.$pages,$pages);
$next_i=$formatter->link_tag('',$action.$i,$next);
$pnut.=$cat.$ellip.$bra.$next_l.$cat.$next_i;
}
} else {
$pnut.="".$cat.$next;
}
return $pnut;
}
function _html_escape($string) {
return preg_replace(array("@<(?=/?\s*\w+[^<>]*)@", '@"@', '@&(?!#?[a-zA-Z0-9]+;)@'), array("<", '"', '&'), $string);
}
function _rawurlencode($url) {
$name=rawurlencode($url);
$urlname = str_replace(array('%2F', '%7E', '%3A'), array('/', '~', ':'), $name);
$urlname= preg_replace('#:+#',':',$urlname);
return $urlname;
}
/**
* do not encode already urlencoded chars.
*
* @author wkpark at gmail.com
* @since 2015/07/03
*/
function _urlencode($url) {
$url = preg_replace('#:+#', ':', $url);
$chunks = preg_split("@([a-zA-Z0-9/?.~#&:;=%_-]+)@", $url, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $sz = count($chunks); $i < $sz; $i++) {
if ($i % 2 == 0) {
$chunks[$i] = strtr(rawurlencode($chunks[$i]), array(
'%23'=>'#',
'%26'=>'&',
'%2F'=>'/',
'%3A'=>':',
'%3B'=>';',
'%3D'=>'=',
'%3F'=>'?',
)
);
}
}
return preg_replace("/%(?![a-fA-Z0-9]{2})/", '%25', implode('', $chunks));
}
/**
* auto detect the encoding of a given URL and fix it
*
* @since 2014/03/21
*/
function _autofixencode($str) {
global $DBInfo;
if (isset($DBInfo->url_encodings)) {
$charset = mb_detect_encoding($str, $DBInfo->url_encodings);
if ($charset !== false) {
$tmp = iconv($charset, $DBInfo->charset, $str);
if ($tmp !== false) return $tmp;
}
}
return $str;
}
if (!function_exists('_stripslashes')) {
function _stripslashes($str) {
if (PHP_VERSION_ID >= 50400) return $str;
return get_magic_quotes_gpc() ? stripslashes($str):$str;
}
}
/**
* get random string to test regex
* from http://stackoverflow.com/questions/4356289/php-random-string-generator
*/
function _str_random($len, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ;:%#@",`abcdefghijklmnopqrstuvwxyz1234567890') {
$clen = strlen($chars);
$str = '';
for ($i = 0; $i < $len; $i++) {
$str.= $chars[rand(0, $clen - 1)];
}
return $str;
}
function qualifiedUrl($url) {
if (substr($url,0,7)=='http://' or substr($url,0,8) == 'https://')
return $url;
$port= ($_SERVER['SERVER_PORT'] != 80) ? ':'.$_SERVER['SERVER_PORT']:'';
$proto= 'http';
if (!empty($_SERVER['HTTPS'])) $proto= 'https';
else $proto= strtolower(strtok($_SERVER['SERVER_PROTOCOL'],'/'));
if (empty($url[0]) or $url[0] != '/') $url='/'.$url; // XXX
if (strpos($_SERVER['HTTP_HOST'],':') !== false)
$port = '';
return $proto.'://'.$_SERVER['HTTP_HOST'].$port.$url;
}
function find_needle($body,$needle,$exclude='',$count=0) {
if (!$body) return '';
$test=@preg_match("/$needle/","",$match);
if ($test === false) {
return '';
}
$lines=explode("\n",$body);
$out="";
$matches=preg_grep("/($needle)/i",$lines);
if ($exclude)
if (preg_grep("/($exclude)/i",$matches)) return '';
if (count($matches) > $count) $matches=array_slice($matches,0,$count);
foreach ($matches as $line) {
$line=preg_replace("/($needle)/i","<strong>\\1</strong>",str_replace("<","<",$line));
$out.="<br />\n ".$line;
}
return $out;
}
function normalize($title) {
if (strpos($title," "))
#return preg_replace("/[\?!$%\.\^;&\*()_\+\|\[\] ]/","",ucwords($title));
return str_replace(" ","",ucwords($title));
return $title;
}
function normalize_word($word,$group='',$pagename='',$nogroup=0,$islink=1) {
if ($word[0]=='[') $word=substr($word,1,-1);
if ($word[0]=='"') $word=substr($word,1,-1);
$page=$word;
$text='';
$main_page='';
# User namespace extension
if ($page[0]=='~' and ($p=strpos($page,'/'))) {
# change ~User/Page to User~Page
$main_page=$page;
$page=$text=substr($page,1,$p-1).'~'.substr($page,$p+1);
return array($page,$text,$main_page);
}
if ($page[0]=='.' and preg_match('/^(\.{1,2})\//',$page,$match)) {
if ($match[1] == '..') {
if (($pos = strrpos($pagename,'/')) > 0) {
$upper=substr($pagename,0,$pos);
$page=substr($page,2);
if ($page == '/') $page=$upper;
else $page=$upper.$page;
} else {
$page=substr($page,3);
if ($page == '') $page=substr($pagename,strlen($group));
else if ($group) $page=$group.$page;
}
} else {
$page=substr($page,1);
if ($page == '/') $page='';
$page=$pagename.$page;
}
return array($page,$text,$main_page);
}
#if ($nogroup and $page[0]=='/') { # SubPage without group support. XXX disabled
if ($page[0]=='/') { # SubPage
$page=$pagename.$page;
} else if (!empty($islink) && $tok=strtok($page,'.')) {
# print $tok;
if ($tok=='Main') {
# Main.MoniWiki => MoniWiki
$page=$text=strtok('');
return array($page,$text,$main_page);
} else if (strpos($tok,'~') === false and strpos($tok,'/') === false) {
# Ko~Hello.World =x=> Ko~Hello~World
# Ko.Hello => Ko~Hello
#$page=preg_replace('/\./','~',$page,1);
$npage=preg_replace('/(?<!\\\\)\./','~',$page,1);
if ($npage == $page) $page=preg_replace('/(\\\.)/','.',$page,1);
else $page=$npage;
$text=$main_page=strtok('');
}
}
if (!$nogroup and $group and !strpos($page,'~')) {
# UserNameSpace pages: e.g.) Ko~MoniWiki etc.
if ($page[0]=='/') {
# /MoniWiki => MoniWiki
$page=$text=substr($page,1);
} else {
$main_page=$text=$page;
$page=$group.$page;
}
}
if (preg_match("/^wiki:/", $page)) { # wiki:
$text=$page=substr($page,5);
if (preg_match("/^\"([^\"]+)\"\s?(.*)$/", $page, $m)) {
// [[wiki:"Page with space" goto Page]] case
list($page, $text) = array($m[1], $m[2]);
} else if (strpos($page,' ')) { # have a space ?
list($page,$text)= explode(' ',$page,2);
}
if ($page[0]=='/') $page= $pagename.$page;
}
return array($page,$text,$main_page);
}
if (function_exists('str_getcsv')) {
function get_csv($str) {
return str_getcsv($str);
}
} else {
function get_csv($str) {
// csv_regex from Mastering regular expressions p480, 481
$csv_regex = '{
\G(?:^|\s*,)\s* # spaces are added
(?:
# Either a double quoted filed
" # field opening quote
( [^"]*+ (?: "" [^"]*+ )*+ )
" # closing quote
| # .. or ...
# ... some non-quote/non-comma text...
( [^",]*+ )
)
}x';
preg_match_all($csv_regex, $str, $all_matches);
$ret = array();
for ($i = 0; $i < count($all_matches[0]); $i++) {
if (strlen($all_matches[2][$i]) > 0)
$ret[] = $all_matches[2][$i];
else
// a quoted value.
$ret[] = preg_replace('/""/', '"', $all_matches[1][$i]);
}
return $ret;
}
}
/**
* get aliases from alias file
*
* @author [email protected]
* @since 2010/08/12
*
*/
function get_aliases($file) {
$lines = array();
if (file_exists($file)) $lines = file($file);
if (empty($lines))
return array();
$alias = array();
foreach ($lines as $line) {
$line=trim($line);
if (empty($line) or $line[0]=='#') continue;
# support three types of aliases
#
# dest<alias1,alias2,...
# dest,alias1,alias2,...
# alias>dest1,dest2,dest3,...
#
if (($p=strpos($line,'>')) !== false) {
list($key, $list) = explode('>',$line,2);
$vals = get_csv($list);
$alias[$key] = $vals;
} else {
if (($p = strpos($line, '<')) !== false) {
list($val, $keys) = explode('<', $line, 2);
$keys = get_csv($keys);
} else {
$keys = get_csv($line);
$val = array_shift($keys);
}
foreach ($keys as $k) {
if (!isset($alias[$k])) $alias[$k] = array();
$alias[$k][] = $val;
}
}
}
return $alias;
}
/**
* Store aliases
*
* @author Won-Kyu Park <[email protected]>
*/
function store_aliases($pagename, $aliases) {
$cache = new Cache_Text('alias');
$cur = $cache->fetch($pagename);
if (!is_array($cur)) $cur = array();
if (empty($cur) and empty($aliases))
return;
// inverted index
$icache = new Cache_Text('aliasname');
if (key($cur) == $pagename)
$cur = $cur[$pagename];
$add = array_diff($aliases, $cur);
$del = array_diff($cur, $aliases);
// merge new aliases
foreach ($add as $a) {
if (!isset($a[0])) continue;
$i = $icache->fetch($a);
if (!is_array($i)) $i = array();
$i = array_merge($i, array($pagename));
$i = array_unique($i);
$icache->update($a, $i);
}
// remove deleted aliases
foreach ($del as $d) {
if (!isset($d[0])) continue;
$i = $icache->fetch($d);
if (!is_array($i)) $i = array();
$i = array_diff($i, array($pagename));
if (empty($i))
$icache->remove($d);
else
$icache->update($d, $i);
}
// update pagealiases
if (!empty($aliases))
$cache->update($pagename, array($pagename => $aliases));
else
$cache->remove($pagename);
}
/**
* Store pagelinks
*
* @author Won-Kyu Park <[email protected]>
*/
function store_pagelinks($pagename, $pagelinks) {
global $DBInfo;
$bcache = new Cache_Text('backlinks');
$cache = new Cache_Text('pagelinks');
unset($pagelinks['TwinPages']);
$cur = $cache->fetch($pagename);
if (!is_array($cur)) $cur = array();
$add = array_diff($pagelinks, $cur);
$del = array_diff($cur, $pagelinks);
// merge new backlinks
foreach ($add as $a) {
if (!isset($a[0])) continue;
$bl = $bcache->fetch($a);
if (!is_array($bl)) $bl = array();
$bl = array_merge($bl, array($pagename));
$bl = array_unique($bl);
sort($bl);
$bcache->update($a, $bl);
}
// remove deleted backlinks
foreach ($del as $d) {
if (!isset($d[0])) continue;
$bl = $bcache->fetch($d);
if (!is_array($bl)) $bl = array();
$bl = array_diff($bl, array($pagename));
sort($bl);
$bcache->update($d, $bl);
}
if (!empty($pagelinks))
$cache->update($pagename, $pagelinks);
else
$cache->remove($pagename);
}
/**
* Get pagelinks from the wiki text
*
* @author Won-Kyu Park <[email protected]>
*/
function get_pagelinks($formatter, $text) {
// split into chunks
$chunk = preg_split("/({{{
(?:(?:[^{}]+|
{[^{}]+}(?!})|
(?<!{){{1,2}(?!{)|
(?<!})}{1,2}(?!}))|(?1)
)++}}})/x",$text,-1,PREG_SPLIT_DELIM_CAPTURE);
$inline = array(); // save inline nowikis
if (count($chunk) > 1) {
// protect inline nowikis
$nc = '';
$k = 1;
$idx = 1;
foreach ($chunk as $c) {
if ($k % 2) {
$nc.= $c.' ';
}
$k++;
}
$text = $nc;
}
// check wordrule
if (empty($formatter->wordrule)) $formatter->set_wordrule();
preg_match_all("/(".$formatter->wordrule.")/", $text, $match);
$words = array();
foreach ($match[0] as $k=>$v) {
if (preg_match('/^\!/', $v)) continue;
if (preg_match('/^\?/', $v)) {
$words[] = substr($v, 1);
} else if (preg_match('/^\[?wiki:[^`\'\{\]\^\*\(]/', $v) || !preg_match('/^\[?'.$formatter->urls.':/', $v)) {
$extended = false;
$creole = false;
$word = rtrim($v, '`'); // XXX
if (preg_match('/^\[\[(.*)\]\]$/', $word, $m)) {
// MediaWiki/WikiCreole like links
$creole = true;
$word = $m[1];
} else if (preg_match('/^\[(.*)\]$/', $word, $m)) {
$word = $m[1];
}
if (preg_match('/^(wiki:)?/', $word, $m)) {
if (!empty($m[1])) $word = substr($word, 5);
$word = ltrim($word); // ltrim wikiwords
if (preg_match("/^\"([^\"]*)\"\s?/", $word, $m1)) {
$extended = true;
$word = $m1[1];
} else if (!empty($m[1]) and ($p = strpos($word, " ")) !== false) {
$word = substr($word, 0, $p);
}
} else if ($creole and ($p = strpos($word, '|')) !== false) {
$word = substr($word, 0, $p);
}
if (!$extended and empty($formatter->mediawiki_style) and strpos($word, " ") !== false) {
$word = normalize($word);
}
if (preg_match("/^([^\(:]+)(\((.*)\))?$/", $word, $m)) {
if (isset($m[1])) {
$name = $m[1];
} else {
$name = $word;
}
// check macro
$myname = getPlugin($name);
if (!empty($myname)) {
// this is macro
continue;
}
}
$word = strtok($word, '#?'); // trim anchor tag
$words[] = $word;
}
}
return array_values(array_unique($words));
}
/**
* Update redirect cache and it's index
*
* @author Won-Kyu Park <wkpark at gmail.com>
* @param timestamp $timestamp lastmodified time of the cache file
* @return void
*/
function update_redirects($pagename, $redirect, $refresh = false) {
// update #redirect cache
$rd = new Cache_Text('redirect');
$old = $rd->fetch($pagename);
// FIXME for legacy case
if (is_array($old)) $old = $old[0];
if ($old === false && !isset($redirect[0]))
return;
// update invert redirect index
$rds = new Cache_Text('redirects');
if (!$refresh || $old != $redirect) {
// update direct cache
$rd->update($pagename, array($redirect));
$nr = $redirect;
if (($p = strpos($nr, '#')) > 0) {
// get pagename only
//$anchor = substr($nr, $p);
$nr = substr($nr, 0, $p);
}
if (!isset($nr[0])) {
$rd->remove($pagename);
} else if (!preg_match('@^https?://@', $nr)) { // not a URL redirect
// add redirect links
$redirects = $rds->fetch($nr);
if (empty($redirects)) $redirects = array();
$redirects = array_merge($redirects, array($pagename));
$rds->update($nr, $redirects);
}
while ($old != '' and $old != false) {
// get pagename only
if (($p = strpos($old, '#')) > 0) {
//$anchor = substr($old, $p);
$old = substr($old, 0, $p);
}
if ($nr == $old) break; // same redirect check A#s-1 ~ A#s-2 redirects
// delete redirect links
$l = $rds->fetch($old);
if ($l !== false and is_array($l)) {
$redirects = array_diff($l, array($pagename));
if (empty($redirects)) $rds->remove($old);
else $rds->update($old, $redirects);
}
break;
}
}
}
/**
* Checks and sets HTTP headers for conditional HTTP requests
* slightly modified to set $etag separatly by [email protected]
*
* @author Simon Willison <[email protected]>
* @link http://simon.incutio.com/archive/2003/04/23/conditionalGet
* @param timestamp $timestamp lastmodified time of the cache file
* @returns void or exits with previously header() commands executed
*/
function http_need_cond_request($mtime, $last_modified = '', $etag = '') {
// A PHP implementation of conditional get, see
// http://fishbowl.pastiche.org/archives/001132.html
if (empty($last_modified)) // is it timestamp ?
$last_modified = substr(gmdate('r', $mtime), 0, -5).'GMT';
if (empty($etag)) // pseudo etag
$etag = md5($last_modified);
if ($etag[0] != '"')
$etag = '"' . $etag . '"';
// See if the client has provided the required headers
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
// fix broken IEx
$if_modified_since = preg_replace('/;.*$/', '', _stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE']));
}else{
$if_modified_since = false;
}
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$if_none_match = _stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
}else{
$if_none_match = false;
}
if (!$if_modified_since && !$if_none_match) {
return true;
}
// At least one of the headers is there - check them
while ($if_none_match && $if_none_match != $etag) {
// it is weak ETag ?
if (preg_match('@^W/(.*)@', $if_none_match, $m)) {
if ($m[1] == $etag)
break;
}
return true; // etag is there but doesn't match
}
if ($if_modified_since) {
// calculate time
$mytime = @strtotime( $if_modified_since );
if ( $mtime > $mytime) {
header('X-Check: '.$mtime.' '.$mytime);