forked from YesWiki/yeswiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wakka.php
1775 lines (1621 loc) · 60.5 KB
/
wakka.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
/*
$Id: wakka.php 864 2007-11-28 12:44:52Z nepote $
Copyright (c) 2002, Hendrik Mans <[email protected]>
Copyright 2003 Carlo Zottmann
Copyright 2002, 2003, 2005 David DELON
Copyright 2002, 2003, 2004, 2006 Charles N?POTE
Copyright 2002, 2003 Patrick PAUL
Copyright 2003 Eric DELORD
Copyright 2003 Eric FELDSTEIN
Copyright 2004-2006 Jean-Christophe ANDR?
Copyright 2005-2006 Didier LOISEAU
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Yes, most of the formatting used in this file is HORRIBLY BAD STYLE. However,
most of the action happens outside of this file, and I really wanted the code
to look as small as what it does. Basically. Oh, I just suck. :)
*/
// do not change this line, you fool. In fact, don't change anything! Ever!
define("WAKKA_VERSION", "0.1.1");
define("WIKINI_VERSION", "0.5.0");
require 'includes/constants.php';
include 'includes/urlutils.inc.php';
// start the compute time
list($g_usec, $g_sec) = explode(" ",microtime());
define ("t_start", (float)$g_usec + (float)$g_sec);
$t_SQL=0;
class Wiki
{
var $dblink;
var $page;
var $tag;
var $parameter = array();
var $queryLog = array();
var $interWiki = array();
var $VERSION;
var $CookiePath = '/';
var $inclusions = array();
/**
* an array containing all the actions that are implemented by an object
* @access private
*/
var $actionObjects;
// LinkTrackink
var $isTrackingLinks = false;
var $linktable = array();
var $pageCache = array();
var $_groupsCache = array();
var $_actionsAclsCache = array();
// constructor
function Wiki($config)
{
$this->config = $config;
// some host do not allow mysql_pconnect
$this->dblink = @mysql_connect (
$this->config["mysql_host"],
$this->config["mysql_user"],
$this->config["mysql_password"]);
if ($this->dblink)
{
if (!@mysql_select_db($this->config["mysql_database"], $this->dblink))
{
@mysql_close($this->dblink);
$this->dblink = false;
}
}
$this->VERSION = WAKKA_VERSION;
// determine le chemin pour les cookies
$a = parse_url($this->GetConfigValue('base_url'));
$this->CookiePath = dirname($a['path']);
// Fixe la gestion des cookie sous les OS utilisant le \ comme s?parteur de chemin
$this->CookiePath = str_replace("\\","/",$this->CookiePath);
// ajoute un '/' terminal sauf si on est ? la racine web
if ($this->CookiePath != '/') $this->CookiePath .= '/';
}
// DATABASE
function Query($query)
{
if($this->GetConfigValue("debug")) $start = $this->GetMicroTime();
if (!$result = mysql_query($query, $this->dblink))
{
ob_end_clean();
die("Query failed: ".$query." (".mysql_error().")");
}
if($this->GetConfigValue("debug"))
{
$time = $this->GetMicroTime() - $start;
$this->queryLog[] = array(
"query" => $query,
"time" => $time);
}
return $result;
}
function LoadSingle($query) {
if ($data = $this->LoadAll($query)) return $data[0];
return null;
}
function LoadAll($query)
{
$data=array();
if ($r = $this->Query($query))
{
while ($row = mysql_fetch_assoc($r)) $data[] = $row;
mysql_free_result($r);
}
return $data;
}
// MISC
function GetMicroTime()
{
list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec);
}
function IncludeBuffered($filename, $notfoundText = "", $vars = "", $path = "")
{
if ($path) $dirs = explode(":", $path);
else $dirs = array("");
foreach($dirs as $dir)
{
if ($dir) $dir .= "/";
$fullfilename = $dir.$filename;
if (file_exists($fullfilename))
{
if (is_array($vars)) extract($vars);
ob_start();
include($fullfilename);
$output = ob_get_contents();
ob_end_clean();
return $output;
}
}
if ($notfoundText) return $notfoundText;
else return false;
}
// VARIABLES
function GetPageTag() { return $this->tag; }
function GetPageTime() { return $this->page["time"]; }
function GetMethod() { return $this->method; }
function GetConfigValue($name) { return isset($this->config[$name]) ? trim($this->config[$name]) : ''; }
function GetWakkaName() { return $this->GetConfigValue("wakka_name"); }
function GetWakkaVersion() { return $this->VERSION; }
function GetWikiNiVersion() { return WIKINI_VERSION; }
/**
* Retrieves all the triples that match some criteria.
* This allows to search triples by their approximate resource or property names.
* The allowed operators are the sql LIKE and the sql =
* @param string $resource The resource of the triples
* @param string $property The property of the triple to retrieve or null
* @param string $res_op The operator of comparison between the effective resource and $resource (default: 'LIKE')
* @param string $prop_op The operator of comparison between the effective property and $property (default: '=')
* @return array The list of all the triples that match the asked criteria
*/
function GetMatchingTriples($resource, $property = null, $res_op = 'LIKE', $prop_op = '=')
{
static $operators = array('=', 'LIKE'); // we might want to add other operators later
$res_op = strtoupper($res_op);
if (!in_array($res_op, $operators)) $res_op = '=';
$sql = 'SELECT * FROM ' . $this->GetConfigValue('table_prefix') . 'triples '
. 'WHERE resource ' . $res_op . ' "' . addslashes($resource) . '"';
if ($property !== null)
{
$prop_op = strtoupper($prop_op);
if (!in_array($prop_op, $operators)) $prop_op = '=';
$sql .= ' AND property ' . $prop_op . ' "' . addslashes($property) . '"';
}
return $this->LoadAll($sql);
}
/**
* Retrieves all the values for a given couple (resource, property)
* @param string $resource The resource of the triples
* @param string $property The property of the triple to retrieve
* @param string $re_prefix The prefix to add to $resource (defaults to THISWIKI_PREFIX)
* @param string $prop_prefix The prefix to add to $property (defaults to WIKINI_VOC_PREFIX)
* @return array An array of the retrieved values, in the form
* array(
* 0 => array(id = 7 , 'value' => $value1),
* 1 => array(id = 34, 'value' => $value2),
* ...
* )
*/
function GetAllTriplesValues($resource, $property, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX)
{
$sql = 'SELECT id, value FROM ' . $this->GetConfigValue('table_prefix') . 'triples '
. 'WHERE resource = "' . addslashes($re_prefix . $resource) . '" '
. 'AND property = "' . addslashes($prop_prefix . $property) . '" ';
return $this->LoadAll($sql);
}
/**
* Retrieves a single value for a given couple (resource, property)
* @param string $resource The resource of the triples
* @param string $property The property of the triple to retrieve
* @param string $re_prefix The prefix to add to $resource (defaults to <tt>THISWIKI_PREFIX</tt>)
* @param string $prop_prefix The prefix to add to $property (defaults to <tt>WIKINI_VOC_PREFIX</tt>)
* @return string The value corresponding to ($resource, $property) or null if
* there is no such couple in the triples table.
*/
function GetTripleValue($resource, $property, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX)
{
$res = $this->GetAllTriplesValues($resource, $property, $re_prefix, $prop_prefix);
if ($res) return $res[0]['value'];
return null;
}
/**
* Checks whether a triple exists or not
* @param string $resource The resource of the triple to find
* @param string $property The property of the triple to find
* @param string $value The value of the triple to find
* @param string $re_prefix The prefix to add to $resource (defaults to <tt>THISWIKI_PREFIX</tt>)
* @param string $prop_prefix The prefix to add to $property (defaults to <tt>WIKINI_VOC_PREFIX</tt>)
* @param int The id of the found triple or 0 if there is no such triple.
*/
function TripleExists($resource, $property, $value, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX)
{
$sql = 'SELECT id FROM ' . $this->GetConfigValue('table_prefix') . 'triples '
. 'WHERE resource = "' . addslashes($re_prefix . $resource) . '" '
. 'AND property = "' . addslashes($prop_prefix . $property) . '" '
. 'AND value = "' . addslashes($value) . '"';
$res = $this->LoadSingle($sql);
if (!$res) return 0;
return $res['id'];
}
/**
* Inserts a new triple ($resource, $property, $value) in the triples' table
* @param string $resource The resource of the triple to insert
* @param string $property The property of the triple to insert
* @param string $value The value of the triple to insert
* @param string $re_prefix The prefix to add to $resource (defaults to <tt>THISWIKI_PREFIX</tt>)
* @param string $prop_prefix The prefix to add to $property (defaults to <tt>WIKINI_VOC_PREFIX</tt>)
* @return int An error code: 0 (success), 1 (failure) or 3 (already exists)
*/
function InsertTriple($resource, $property, $value, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX)
{
if ($this->TripleExists($resource, $property, $value, $re_prefix, $prop_prefix))
{
return 3;
}
$sql = 'INSERT INTO ' . $this->GetConfigValue('table_prefix') . 'triples (resource, property, value)'
. 'VALUES ("' . addslashes($re_prefix . $resource) . '", "'
. addslashes($prop_prefix . $property) . '", "'
. addslashes($value) . '")';
return $this->Query($sql) ? 0 : 1;
}
/**
* Updates a triple ($resource, $property, $value) in the triples' table
* @param string $resource The resource of the triple to update
* @param string $property The property of the triple to update
* @param string $oldvalue The old value of the triple to update
* @param string $newvalue The new value of the triple to update
* @param string $re_prefix The prefix to add to $resource (defaults to <tt>THISWIKI_PREFIX</tt>)
* @param string $prop_prefix The prefix to add to $property (defaults to <tt>WIKINI_VOC_PREFIX</tt>)
* @return int An error code: 0 (succ?s), 1 (?chec),
* 2 ($resource, $property, $oldvalue does not exist)
* or 3 ($resource, $property, $newvalue already exists)
*/
function UpdateTriple($resource, $property, $oldvalue, $newvalue, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX)
{
$id = $this->TripleExists($resource, $property, $oldvalue, $re_prefix, $prop_prefix);
if (!$id) return 2;
if ($this->TripleExists($resource, $property, $newvalue, $re_prefix, $prop_prefix))
{
return 3;
}
$sql = 'UPDATE ' . $this->GetConfigValue('table_prefix') . 'triples '
. 'SET value = "' . addslashes($newvalue) . '" '
. 'WHERE id = ' . $id;
return $this->Query($sql) ? 0 : 1;
}
/**
* Deletes a triple ($resource, $property, $value) from the triples' table
* @param string $resource The resource of the triple to delete
* @param string $property The property of the triple to delete
* @param string $value The value of the triple to delete. If set to <tt>null</tt>,
* deletes all the triples corresponding to ($resource, $property). (defaults to <tt>null</tt>)
* @param string $re_prefix The prefix to add to $resource (defaults to <tt>THISWIKI_PREFIX</tt>)
* @param string $prop_prefix The prefix to add to $property (defaults to <tt>WIKINI_VOC_PREFIX</tt>)
*/
function DeleteTriple($resource, $property, $value = null, $re_prefix = THISWIKI_PREFIX, $prop_prefix = WIKINI_VOC_PREFIX)
{
$sql = 'DELETE FROM ' . $this->GetConfigValue('table_prefix') . 'triples '
. 'WHERE resource = "' . addslashes($re_prefix . $resource) . '" '
. 'AND property = "' . addslashes($prop_prefix . $property) . '" ';
if ($value !== null) $sql .= 'AND value = "' . addslashes($value) . '"';
$this->Query($sql);
}
// inclusions
/**
* Enr?gistre une nouvelle inclusion dans la pile d'inclusions.
*
* @param string $pageTag Le nom de la page qui va ?tre inclue
* @return int Le nombre d'?l?ments dans la pile
*/
function RegisterInclusion($pageTag)
{
return array_unshift($this->inclusions, strtolower(trim($pageTag)));
}
/**
* Retire le dernier ?l?ment de la pile d'inclusions.
*
* @return string Le nom de la page dont l'inclusion devrait se terminer.
* null s'il n'y a plus d'inclusion dans la pile.
*/
function UnregisterLastInclusion()
{
return array_shift($this->inclusions);
}
/**
* Renvoie le nom de la page en cours d'inclusion.
*
* @example // dans le cas d'une action comme l'ActionEcrivezMoi
* if($inc = $this->CurrentInclusion() && strtolower($this->GetPageTag()) != $inc)
* echo 'Cette action ne peut ?tre appel?e depuis une page inclue';
* @return string Le nom (tag) de la page (en minuscules)
* false si la pile est vide.
*/
function GetCurrentInclusion()
{
return isset($this->inclusions[0]) ? $this->inclusions[0]: false ;
}
/**
* V?rifie si on est ? l'int?rieur d'une inclusion par $pageTag (sans tenir compte de la casse)
*
* @param string $pageTag Le nom de la page ? v?rifier
* @return bool True si on est ? l'int?rieur d'une inclusion par $pageTag (false sinon)
*/
function IsIncludedBy($pageTag)
{
return in_array(strtolower($pageTag), $this->inclusions);
}
/**
*
* @return array La pile d'inclusions
* L'?l?ment 0 sera la derni?re inclusion, l'?l?ment 1 sera son parent et ainsi de suite.
*/
function GetAllInclusions()
{
return $this->inclusions;
}
/**
* Remplace la pile des inclusions par une nouvelle pile (par d?faut une pile vide)
* Permet de formatter une page sans tenir compte des inclusions pr?c?dentes.
*
* @param array $ La nouvelle pile d'inclusions.
* L'?l?ment 0 doit repr?senter la derni?re inclusion, l'?l?ment 1 son parent et ainsi de suite.
* @return array L'ancienne pile d'inclusions, avec les noms des pages en minuscules.
*/
function SetInclusions($pile = array())
{
$temp = $this->inclusions;
$this->inclusions = $pile;
return $temp;
}
// PAGES
function LoadPage($tag, $time = "", $cache = 1)
{
// retrieve from cache
if (!$time && $cache && (($cachedPage = $this->GetCachedPage($tag)) !== false))
{
$page = $cachedPage;
}
else // load page
{
$sql = "SELECT * FROM ".$this->config["table_prefix"]."pages"
. " WHERE tag = '".mysql_real_escape_string($tag)."' AND "
. ($time ? "time = '".mysql_real_escape_string($time)."'" : "latest = 'Y'") . " LIMIT 1";
$page = $this->LoadSingle($sql);
// cache result
if (!$time) $this->CachePage($page, $tag);
}
return $page;
}
/**
* Retrieves the cached version of a page.
*
* Notice that this method null or false, use
* $this->GetCachedPage($tag) === false
* to check if a page is not in the cache.
* @return mixed The cached version of a page:
* - the page DB line if the page exists and is in cache
* - null if the cache knows that the page does not exists
* - false is the cache does not know the page
*/
function GetCachedPage($tag) {return (array_key_exists($tag, $this->pageCache) ? $this->pageCache[$tag] : false); }
/**
* Caches a page's DB line.
*
* @param array $page The page (full) DB line or null if the page does not exists
* @param string $pageTag The tag of the page to cache. Defaults to $page['tag'] but is mendatory when $page === null
*/
function CachePage($page, $pageTag = null) {
if ($pageTag === null)
{
$pageTag = $page["tag"];
}
$this->pageCache[$pageTag] = $page;
}
function SetPage($page) { $this->page = $page; if ($this->page["tag"]) $this->tag = $this->page["tag"]; }
function LoadPageById($id) { return $this->LoadSingle("select * from ".$this->config["table_prefix"]."pages where id = '".mysql_real_escape_string($id)."' limit 1"); }
function LoadRevisions($page) { return $this->LoadAll("select * from ".$this->config["table_prefix"]."pages where tag = '".mysql_real_escape_string($page)."' order by time desc"); }
function LoadPagesLinkingTo($tag) { return $this->LoadAll("select from_tag as tag from ".$this->config["table_prefix"]."links where to_tag = '".mysql_real_escape_string($tag)."' order by tag"); }
function LoadRecentlyChanged($limit=50)
{
$limit= (int) $limit;
if ($pages = $this->LoadAll("select id, tag, time, user, owner from ".$this->config["table_prefix"]."pages where latest = 'Y' and comment_on = '' order by time desc limit $limit"))
{
foreach ($pages as $page)
{
$this->CachePage($page);
}
return $pages;
}
}
function LoadAllPages() { return $this->LoadAll("select * from ".$this->config["table_prefix"]."pages where latest = 'Y' order by tag"); }
function FullTextSearch($phrase) { return $this->LoadAll("select * from ".$this->config["table_prefix"]."pages where latest = 'Y' and match(tag, body) against('".mysql_real_escape_string($phrase)."')"); }
function LoadWantedPages() {
$p = $this->config["table_prefix"];
$r = "SELECT ${p}links.to_tag AS tag, COUNT(${p}links.from_tag) AS count "
. "FROM ${p}links LEFT JOIN ${p}pages ON ${p}links.to_tag = ${p}pages.tag "
. "WHERE ${p}pages.tag IS NULL GROUP BY ${p}links.to_tag ORDER BY count DESC, tag ASC";
return $this->LoadAll($r);
}
function LoadOrphanedPages() { return $this->LoadAll("select distinct tag from ".$this->config["table_prefix"]."pages as p left join ".$this->config["table_prefix"]."links as l on p.tag = l.to_tag where l.to_tag is NULL and p.comment_on = '' and p.latest = 'Y' order by tag"); }
function IsOrphanedPage($tag) { return $this->LoadAll("select distinct tag from ".$this->config['table_prefix']."pages as p left join ".$this->config['table_prefix']."links as l on p.tag = l.to_tag where l.to_tag is NULL and p.latest = 'Y' and tag = '".mysql_real_escape_string($tag)."'"); }
function DeleteOrphanedPage($tag) {
$p = $this->config["table_prefix"];
$this->Query("DELETE FROM ${p}pages WHERE tag='".mysql_real_escape_string($tag)."' OR comment_on='".mysql_real_escape_string($tag)."'");
$this->Query("DELETE FROM ${p}links WHERE from_tag='".mysql_real_escape_string($tag)."' ");
$this->Query("DELETE FROM ${p}acls WHERE page_tag='".mysql_real_escape_string($tag)."' ");
$this->Query("DELETE FROM ${p}referrers WHERE page_tag='".mysql_real_escape_string($tag)."' ");
}
/**
* SavePage
* Sauvegarde un contenu dans une page donn?e
*
* @param string $body Contenu ? sauvegarder dans la page
* @param string $tag Nom de la page
* @param string $comment_on Indication si c'est un commentaire
* @param boolean $bypass_acls Indication si on bypasse les droits d'?criture
* @return int Code d'erreur : 0 (succ?s), 1 (l'utilisateur n'a pas les droits)
*/
function SavePage($tag, $body, $comment_on = "", $bypass_acls = false)
{
// get current user
$user = $this->GetUserName();
// check bypass of rights or write privilege
$rights = $bypass_acls || ($comment_on ? $this->HasAccess("comment", $comment_on) : $this->HasAccess("write", $tag));
if ($rights)
{
// is page new?
if (!$oldPage = $this->LoadPage($tag))
{
// create default write acl. store empty write ACL for comments.
$this->SaveAcl($tag, "write", ($comment_on ? $user : $this->GetConfigValue("default_write_acl")));
// create default read acl
$this->SaveAcl($tag, "read", $this->GetConfigValue("default_read_acl"));
// create default comment acl.
$this->SaveAcl($tag, "comment", ($comment_on ? "" : $this->GetConfigValue("default_comment_acl")));
// current user is owner; if user is logged in! otherwise, no owner.
if ($this->GetUser()) $owner = $user;
else $owner = '';
}
else
{
// aha! page isn't new. keep owner!
$owner = $oldPage["owner"];
// ...and comment_on, eventualy?
if ($comment_on == '') $comment_on = $oldPage['comment_on'];
}
// set all other revisions to old
$this->Query("update ".$this->config["table_prefix"]."pages set latest = 'N' where tag = '".mysql_real_escape_string($tag)."'");
// add new revision
$this->Query("insert into ".$this->config["table_prefix"]."pages set ".
"tag = '".mysql_real_escape_string($tag)."', ".
($comment_on ? "comment_on = '".mysql_real_escape_string($comment_on)."', " : "").
"time = now(), ".
"owner = '".mysql_real_escape_string($owner)."', ".
"user = '".mysql_real_escape_string($user)."', ".
"latest = 'Y', ".
"body = '".mysql_real_escape_string(chop($body))."'");
unset($this->pageCache[$tag]);
return 0;
}
else return 1;
}
/**
* AppendContentToPage
* Ajoute du contenu ? la fin d'une page
*
* @param string $content Contenu ? ajouter ? la page
* @param string $page Nom de la page
* @param boolean $bypass_acls Boul?en pour savoir s'il faut bypasser les ACLs
* @return int Code d'erreur : 0 (succ?s), 1 (pas de contenu sp?cifi?)
*/
function AppendContentToPage($content, $page, $bypass_acls = false)
{
// Si un contenu est sp?cifi?
if (isset($content))
{
// -- D?termine quelle est la page :
// -- pass?e en param?tre (que se passe-t'il si elle n'existe pas ?)
// -- ou la page en cours par d?faut
$page = isset($page) ? $page : $this->GetPageTag();
// -- Chargement de la page
$result = $this->LoadPage($page);
$body = $result['body'];
// -- Ajout du contenu ? la fin de la page
$body .= $content;
// -- Sauvegarde de la page
// TODO : que se passe-t-il si la page est pleine ou si l'utilisateur n'a pas les droits ?
$this->SavePage($page, $body, "", $bypass_acls);
// now we render it internally so we can write the updated link table.
$this->ClearLinkTable();
$this->StartLinkTracking();
$temp = $this->SetInclusions();
$this->RegisterInclusion($this->GetPageTag()); // on simule totalement un affichage normal
$this->Format($body);
$this->SetInclusions($temp);
if($user = $this->GetUser())
{
$this->TrackLinkTo($user['name']);
}
if($owner = $this->GetPageOwner())
{
$this->TrackLinkTo($owner);
}
$this->StopLinkTracking();
$this->WriteLinkTable();
$this->ClearLinkTable();/**/
// Retourne 0 seulement si tout c'est bien pass?
return 0;
}
else return 1;
}
/**
* LogAdministrativeAction($user, $content, $page = "")
*
* @param string $user Utilisateur
* @param string $content Contenu de l'enregistrement
* @param string $page Page de log
*
* @return int Code d'erreur : 0 (succ?s), 1 (pas de contenu sp?cifi?)
*/
function LogAdministrativeAction($user, $content, $page = "")
{
$order = array("\r\n", "\n", "\r");
$replace = '\\n';
$content = str_replace($order, $replace, $content);
$contentToAppend = "\n" . date("Y-m-d H:i:s") . " . . . . " . $user . " . . . . " . $content . "\n";
$page = $page ? $page : "LogDesActionsAdministratives" . date("Ymd");
return $this->AppendContentToPage($contentToAppend, $page, true);
}
/**
* Make the purge of page versions that are older than the last version older than 3 "pages_purge_time"
* This method permits to allways keep a version that is older than that period.
*/
function PurgePages() {
if ($days = $this->GetConfigValue("pages_purge_time")) { // is purge active ?
// let's search which pages versions we have to remove
// this is necessary beacause even MySQL does not handel multi-tables deletes before version 4.0
$wnPages = $this->GetConfigValue('table_prefix') . 'pages';
$sql = 'SELECT DISTINCT a.id FROM ' . $wnPages . ' a,' . $wnPages . ' b WHERE a.latest = \'N\' AND a.time < date_sub(now(), INTERVAL \'' . addslashes($days) . '\' DAY) AND a.tag = b.tag AND a.time < b.time AND b.time < date_sub(now(), INTERVAL \'' . addslashes($days) . '\' DAY)';
$ids = $this->LoadAll($sql);
if (count($ids)) { // there are some versions to remove from DB
// let's build one big request, that's better...
$sql = 'DELETE FROM ' . $wnPages . ' WHERE id IN (';
foreach($ids as $key => $line){
$sql .= ($key ? ', ':'') . $line['id']; // NB.: id is an int, no need of quotes
}
$sql .= ')';
// ... and send it !
$this->Query($sql);
}
}
}
// COOKIES
function SetSessionCookie($name, $value)
{
SetCookie($name, $value, 0, $this->CookiePath);
$_COOKIE[$name] = $value;
}
function SetPersistentCookie($name, $value, $remember = 0)
{
SetCookie($name, $value, time() + ($remember ? 90*24*60*60 : 60 * 60), $this->CookiePath);
$_COOKIE[$name] = $value;
}
function DeleteCookie($name)
{
SetCookie($name, "", 1, $this->CookiePath);
$_COOKIE[$name] = "";
}
function GetCookie($name) { return $_COOKIE[$name]; }
// HTTP/REQUEST/LINK RELATED
function SetMessage($message) { $_SESSION["message"] = $message; }
function GetMessage()
{
if (isset($_SESSION["message"])) $message = $_SESSION["message"];
else $message = "";
$_SESSION["message"] = "";
return $message;
}
function Redirect($url)
{
header("Location: $url");
exit;
}
// returns just PageName[/method].
function MiniHref($method = "", $tag = "")
{
if (!$tag = trim($tag)) $tag = $this->tag;
return $tag.($method ? "/".$method : "");
}
// returns the full url to a page/method.
function Href($method = "", $tag = "", $params = "", $htmlspchars = true)
{
$href = $this->config["base_url"].$this->MiniHref($method, $tag);
if ($params)
{
$href .= ($this->config["rewrite_mode"] ? "?" : ($htmlspchars ? "&" : '&')).$params;
}
return $href;
}
function Link($tag, $method = "", $text = "", $track = 1)
{
$displayText = $text ? $text : $tag;
// is this an interwiki link?
if (preg_match('/^' . WN_INTERWIKI_CAPTURE . '$/', $tag, $matches))
{
if ($tagInterWiki = $this->GetInterWikiUrl($matches[1], $matches[2])) {
return '<a href="'.htmlspecialchars($tagInterWiki, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'">'
.htmlspecialchars($displayText, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).' (interwiki)</a>';
}
else return '<a href="'.htmlspecialchars($tag, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'">'
.htmlspecialchars($displayText, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).' (interwiki inconnu)</a>';
}
// is this a full link? ie, does it contain non alpha-numeric characters?
// Note : [:alnum:] is equivalent [0-9A-Za-z]
// [^[:alnum:]] means : some caracters other than [0-9A-Za-z]
// For example : "www.adress.com", "mailto:[email protected]", "http://www.adress.com"
else if (preg_match("/[^[:alnum:]]/", $tag))
{
// check for various modifications to perform on $tag
if (preg_match("/^[\w.-]+\@[\w.-]+$/", $tag))
{ // email addresses
$tag = 'mailto:'.$tag;
}
// Note : in Perl regexp, (?: ... ) is a non-catching cluster
else if (preg_match('/^[[:alnum:]][[:alnum:].-]*(?:\/|$)/', $tag))
{ // protocol-less URLs
$tag = 'http://'.$tag;
}
// Finally, block script schemes (see RFC 3986 about
// schemes) and allow relative link & protocol-full URLs
else if (preg_match('/^[a-z0-9.+-]*script[a-z0-9.+-]*:/i', $tag)
|| !(preg_match('/^\.?\.?\//', $tag)
|| preg_match('/^[a-z0-9.+-]+:\/\//i', $tag)))
{
// If does't fit, we can't qualify $tag as an URL.
// There is a high risk that $tag is just XSS (bad
// javascript: code) or anything nasty. So we must not
// produce any link at all.
return htmlspecialchars($tag.($text ? ' '.$text : ''), ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET);
}
// Important: Here, we know that $tag is not something bad
// and that we must produce a link with it
// An inline image? (text!=tag and url ends by png,gif,jpeg)
if ($text and preg_match("/\.(gif|jpeg|png|jpg)$/i",$tag))
{
return '<img src="'.htmlspecialchars($tag, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET)
.'" alt="'.htmlspecialchars($displayText, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'"/>';
}
else
{
// Even if we know $tag is harmless, we MUST encode it
// in HTML with htmlspecialchars() before echoing it.
// This is not about being paranoiac. This is about
// being compliant to the HTML standard.
return '<a href="'.htmlspecialchars($tag, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'">'
.htmlspecialchars($displayText, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'</a>';
}
}
else
{
// it's a Wiki link!
if (!empty($track)) $this->TrackLinkTo($tag);
if ($this->LoadPage($tag))
return '<a href="'.htmlspecialchars($this->href($method, $tag), ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'">'
.htmlspecialchars($displayText, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'</a>';
else
return '<span class="missingpage">'.htmlspecialchars($displayText, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET)
.'</span><a href="'.htmlspecialchars($this->href("edit", $tag), ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET).'">?</a>';
}
}
function ComposeLinkToPage($tag, $method = "", $text = "", $track = 1) {
if (!$text) $text = $tag;
$text = htmlspecialchars($text, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET);
if ($track)
$this->TrackLinkTo($tag);
return '<a href="'.$this->href($method, $tag).'">'.$text.'</a>';
}
function IsWikiName($text) {
return preg_match('/^' . WN_CAMEL_CASE . '$/', $text);
}
// LinkTracking management
/**
* Tracks the link to a given page (only if the LinkTracking is activated)
* @param string $tag The tag (name) of the page to track a link to.
*/
function TrackLinkTo($tag) {
if ($this->LinkTracking()) $this->linktable[] = $tag;
}
/**
* @return array The current link tracking table
*/
function GetLinkTable() { return $this->linktable; }
/**
* Clears the link tracking table
*/
function ClearLinkTable() { $this->linktable = array(); }
/**
* Starts the LinkTracking
* @return bool The previous state of the link tracking
*/
function StartLinkTracking() {
return $this->LinkTracking(true);
}
/**
* Stops the LinkTracking
* @return bool The previous state of the link tracking
*/
function StopLinkTracking() {
return $this->LinkTracking(false);
}
/**
* Sets and/or retrieve the state of the LinkTracking
* @param bool $newStatus The new status of the LinkTracking
* (defaults to <tt>null</tt> which lets it unchanged)
* @return bool The previous state of the link tracking
*/
function LinkTracking($newStatus = null)
{
$old = $this->isTrackingLinks;
if ($newStatus !== null) $this->isTrackingLinks = $newStatus;
return $old;
}
function WriteLinkTable() {
// delete old link table
$this->Query("delete from ".$this->config["table_prefix"]."links where from_tag = '".mysql_real_escape_string($this->GetPageTag())."'");
if ($linktable = $this->GetLinkTable())
{
$from_tag = mysql_real_escape_string($this->GetPageTag());
foreach ($linktable as $to_tag)
{
$lower_to_tag = strtolower($to_tag);
if (!isset($written[$lower_to_tag]))
{
$this->Query("insert into ".$this->config["table_prefix"]."links set from_tag = '".$from_tag."', to_tag = '".mysql_real_escape_string($to_tag)."'");
$written[$lower_to_tag] = 1;
}
}
}
}
function Header() {
$action = $this->GetConfigValue("header_action");
if (($actionObj = &$this->GetActionObject($action)) && is_object($actionObj))
{
return $actionObj->GenerateHeader();
}
return $this->Action($action, 1);
}
function Footer() {
$action = $this->GetConfigValue("footer_action");
if (($actionObj = &$this->GetActionObject($action)) && is_object($actionObj))
{
return $actionObj->GenerateFooter();
}
return $this->Action($action, 1);
}
// FORMS
function FormOpen($method = "", $tag = "", $formMethod = "post") {
$result = "<form action=\"".$this->href($method, $tag)."\" method=\"".$formMethod."\">\n";
if (!$this->config["rewrite_mode"]) $result .= "<input type=\"hidden\" name=\"wiki\" value=\"".$this->MiniHref($method, $tag)."\" />\n";
return $result;
}
function FormClose() {
return "</form>\n";
}
// INTERWIKI STUFF
function ReadInterWikiConfig() {
if ($lines = file("interwiki.conf"))
{
foreach ($lines as $line)
{
if ($line = trim($line))
{
list($wikiName, $wikiUrl) = explode(" ", trim($line));
$this->AddInterWiki($wikiName, $wikiUrl);
}
}
}
}
function AddInterWiki($name, $url) {
$this->interWiki[strtolower($name)] = $url;
}
function GetInterWikiUrl($name, $tag)
{
if (isset($this->interWiki[strtolower($name)])) return $this->interWiki[strtolower($name)].$tag;
else return FALSE;
}
// REFERRERS
function LogReferrer($tag = "", $referrer = "") {
// fill values
if (!$tag = trim($tag)) $tag = $this->GetPageTag();
if (!$referrer = trim($referrer) AND isset($_SERVER["HTTP_REFERER"])) $referrer = $_SERVER["HTTP_REFERER"];
// check if it's coming from another site
if ($referrer && !preg_match("/^".preg_quote($this->GetConfigValue("base_url"), "/")."/", $referrer))
{
// avoid XSS (with urls like "javascript:alert()" and co)
// by forcing http/https prefix
// NB.: this does NOT exempt to htmlspecialchars() the collected URIs !
if (!preg_match('`^https?://`', $referrer)) return;
$this->Query("insert into ".$this->config["table_prefix"]."referrers set ".
"page_tag = '".mysql_real_escape_string($tag)."', ".
"referrer = '".mysql_real_escape_string($referrer)."', ".
"time = now()");
}
}
function LoadReferrers($tag = "") {
return $this->LoadAll("select referrer, count(referrer) as num from ".$this->config["table_prefix"]."referrers ".($tag = trim($tag) ? "where page_tag = '".mysql_real_escape_string($tag)."'" : "")." group by referrer order by num desc");
}
function PurgeReferrers() {
if ($days = $this->GetConfigValue("referrers_purge_time")) {
$this->Query("delete from ".$this->config["table_prefix"]."referrers where time < date_sub(now(), interval '".mysql_real_escape_string($days)."' day)");
}
}
// PLUGINS
/**
* Exacutes an "action" module and returns the generated output
* @param string $action The name of the action and its eventual parameters,
* as it appears in the page between "{{" and "}}"
* @param boolean $forceLinkTracking By default, the link tracking will be disabled
* during the call of an action. Set this value to <code>true</code> to allow it.
* @param array $vars An array of additionnal parameters to give to the action, in the form
* array( 'param' => 'value').
* This allows you to call Action() internally, setting $action to the name of the action
* you want to call and it's parameters in an array, wich is more efficient than
* the pattern-matching algorithm used to extract the parameters from $action.
* @return The output generated by the action.
*/
function Action($action, $forceLinkTracking = 0, $vars = array())
{
$cmd = trim($action);
// extract $action and $vars_temp ("raw" attributes)
if (!preg_match("/^([a-zA-Z-0-9]+)\/?(.*)$/", $cmd, $matches))
{
return '<i>Action invalide "' . htmlspecialchars($cmd, ENT_COMPAT, TEMPLATES_DEFAULT_CHARSET) . '"</i>';
}
list(, $action, $vars_temp) = $matches;
$vars[$vars_temp] = $vars_temp; // usefull for {{action/vars_temp}}
// now that we have the action's name, we can check if the user satisfies the ACLs
if (!$this->CheckModuleACL($action, 'action'))
{
return 'Erreur: vous n\'avez pas accès à l\'action ' . $action . '.';
}
// match all attributes (key and value)
// prepare an array for extract() to work with (in $this->IncludeBuffered())
if (preg_match_all("/([a-zA-Z0-9]*)=\"(.*)\"/U", $vars_temp, $matches))
{
for ($a = 0; $a < count($matches[1]); $a++)
{
$vars[$matches[1][$a]] = $matches[2][$a];
}
}
if (!$forceLinkTracking) $this->StopLinkTracking();
if ($actionObj = &$this->GetActionObject($action))
{
if (is_object($actionObj))
{
$result = $actionObj->PerformAction($vars, $cmd);
}
else // $actionObj is an error message
{
$result = $actionObj;
}
}
else // $actionObj == null (not found, no error message)
{
$this->parameter = &$vars;
$result = $this->IncludeBuffered(strtolower($action).".php", "<i>Action inconnue "$action"</i>", $vars, $this->config["action_path"]);
unset($this->parameter);
}
$this->StartLinkTracking(); // shouldn't we restore the previous status ?
return $result;
}
/**
* Finds the object corresponding to an action, if it exists.
* @param string $name The name of an action (should be alphanumeric)
* @return mixed
* - null if the corresponding file was not found or the corresponding class didn't exist after inclusion
* - an error string if the corresponding file was found but an error append while loading it
* - the object corresponding to this action if no problem happend