]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
fix space in interwiki url images, like local:my picture.png
[SourceForge/phpwiki.git] / lib / stdlib.php
1 <?php //rcs_id('$Id: stdlib.php,v 1.275 2008-05-21 04:30:59 rurban Exp $');
2 /*
3  Copyright 1999-2008 $ThePhpWikiProgrammingTeam
4
5  This file is part of PhpWiki.
6
7  PhpWiki is free software; you can redistribute it and/or modify
8  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation; either version 2 of the License, or
10  (at your option) any later version.
11
12  PhpWiki is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  GNU General Public License for more details.
16
17  You should have received a copy of the GNU General Public License
18  along with PhpWiki; if not, write to the Free Software
19  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 /*
23   Standard functions for Wiki functionality
24     WikiURL ($pagename, $args, $get_abs_url)
25     AbsoluteURL ($url)
26     IconForLink ($protocol_or_url)
27     PossiblyGlueIconToText($proto_or_url, $text)
28     IsSafeURL($url)
29     LinkURL ($url, $linktext)
30     LinkImage ($url, $alt)
31     ImgObject ($img, $url)
32
33     SplitQueryArgs ($query_args)
34     LinkPhpwikiURL ($url, $text, $basepage)
35     ConvertOldMarkup ($content, $markup_type = "block")
36     MangleXmlIdentifier($str)
37     UnMangleXmlIdentifier($str)
38     
39     class Stack { push($item), pop(), cnt(), top() }
40     class Alert { show() }
41     class WikiPageName {getParent(),isValid(),getWarnings() }
42
43     expand_tabs($str, $tab_width = 8)
44     SplitPagename ($page)
45     NoSuchRevision ($request, $page, $version)
46     TimezoneOffset ($time, $no_colon)
47     Iso8601DateTime ($time)
48     Rfc2822DateTime ($time)
49     ParseRfc1123DateTime ($timestr)
50     CTime ($time)
51     ByteFormatter ($bytes = 0, $longformat = false)
52     __printf ($fmt)
53     __sprintf ($fmt)
54     __vsprintf ($fmt, $args)
55
56     file_mtime ($filename)
57     sort_file_mtime ($a, $b)
58     class fileSet {fileSet($directory, $filepattern = false), 
59                    getFiles($exclude='', $sortby='', $limit='') }
60     class ListRegexExpand { listMatchCallback($item, $key),  
61                             expandRegex ($index, &$pages) }
62
63     glob_to_pcre ($glob)
64     glob_match ($glob, $against, $case_sensitive = true)
65     explodeList ($input, $allnames, $glob_style = true, $case_sensitive = true)
66     explodePageList ($input, $perm = false)
67     isa ($object, $class)
68     can ($object, $method)
69     function_usable ($function_name)
70     wikihash ($x)
71     better_srand ($seed = '')
72     count_all ($arg)
73     isSubPage ($pagename)
74     subPageSlice ($pagename, $pos)
75
76     phpwiki_version ()
77     isWikiWord ($word)
78     obj2hash ($obj, $exclude = false, $fields = false)
79     isUtf8String ($s)
80     fixTitleEncoding ($s)
81     url_get_contents ($uri)
82     GenerateId ($name)
83     firstNWordsOfContent ($n, $content)
84     extractSection ($section, $content, $page, $quiet = false, $sectionhead = false)
85     isExternalReferrer()
86     
87     charset_convert($from, $to, $data)
88
89   function: LinkInterWikiLink($link, $linktext)
90   moved to: lib/interwiki.php
91   function: linkExistingWikiWord($wikiword, $linktext, $version)
92   moved to: lib/Theme.php
93   function: LinkUnknownWikiWord($wikiword, $linktext)
94   moved to: lib/Theme.php
95   function: UpdateRecentChanges($dbi, $pagename, $isnewpage) 
96   gone see: lib/plugin/RecentChanges.php
97 */
98 if (defined('_PHPWIKI_STDLIB_LOADED')) return;
99 else define('_PHPWIKI_STDLIB_LOADED', true);
100
101 define('MAX_PAGENAME_LENGTH', 100);
102             
103 /**
104  * Convert string to a valid XML identifier.
105  *
106  * XML 1.0 identifiers are of the form: [A-Za-z][A-Za-z0-9:_.-]*
107  *
108  * We would like to have, e.g. named anchors within wiki pages
109  * names like "Table of Contents" --- clearly not a valid XML
110  * fragment identifier.
111  *
112  * This function implements a one-to-one map from {any string}
113  * to {valid XML identifiers}.
114  *
115  * It does this by
116  * converting all bytes not in [A-Za-z0-9:_-],
117  * and any leading byte not in [A-Za-z] to 'xbb.',
118  * where 'bb' is the hexadecimal representation of the
119  * character.
120  *
121  * As a special case, the empty string is converted to 'empty.'
122  *
123  * @param string $str
124  * @return string
125  */
126 function MangleXmlIdentifier($str) {
127     if (!$str)
128         return 'empty.';
129     
130     return preg_replace('/[^-_:A-Za-z0-9]|(?<=^)[^A-Za-z]/e',
131                         "'x' . sprintf('%02x', ord('\\0')) . '.'",
132                         $str);
133 }
134
135 function UnMangleXmlIdentifier($str) {
136     if ($str == 'empty.')
137         return '';
138     return preg_replace('/x(\w\w)\./e',
139                         "sprintf('%c', hex('\\0'))",
140                         $str);
141 }
142
143 /**
144  * Returns a name for the WIKI_ID cookie that should be unique on the host.
145  * But for it to be unique you must have set a unique WIKI_NAME in your
146  * configuration file.
147  * @return string The name of the WIKI_ID cookie to use for this wiki.
148  */
149 function GetCookieName() {
150     return preg_replace("/[^\d\w]/", "_", WIKI_NAME) . "_WIKI_ID";
151 }
152
153 /**
154  * Generates a valid URL for a given Wiki pagename.
155  * @param mixed $pagename If a string this will be the name of the Wiki page to link to.
156  *                        If a WikiDB_Page object function will extract the name to link to.
157  *                        If a WikiDB_PageRevision object function will extract the name to link to.
158  * @param array $args 
159  * @param boolean $get_abs_url Default value is false.
160  * @return string The absolute URL to the page passed as $pagename.
161  */
162 function WikiURL($pagename, $args = '', $get_abs_url = false) {
163     global $request, $WikiTheme;
164     $anchor = false;
165     
166     if (is_object($pagename)) {
167         if (isa($pagename, 'WikiDB_Page')) {
168             $pagename = $pagename->getName();
169         }
170         elseif (isa($pagename, 'WikiDB_PageRevision')) {
171             $page = $pagename->getPage();
172             $args['version'] = $pagename->getVersion();
173             $pagename = $page->getName();
174         }
175         elseif (isa($pagename, 'WikiPageName')) {
176             $anchor = $pagename->anchor;
177             $pagename = $pagename->name;
178         } else { // php5
179             $anchor = $pagename->anchor;
180             $pagename = $pagename->name;
181         }
182     }
183     if (!$get_abs_url and DEBUG and $request->getArg('start_debug')) {
184         if (!$args)
185             $args = 'start_debug=' . $request->getArg('start_debug');
186         elseif (is_array($args))
187             $args['start_debug'] = $request->getArg('start_debug');
188         else 
189             $args .= '&start_debug=' . $request->getArg('start_debug');
190     }
191     if (is_array($args)) {
192         $enc_args = array();
193         foreach ($args as $key => $val) {
194             // avoid default args
195             if (USE_PATH_INFO and $key == 'pagename')
196                 ; 
197             elseif ($key == 'action' and $val == 'browse')
198                 ;
199             elseif (!is_array($val)) // ugly hack for getURLtoSelf() which also takes POST vars
200               $enc_args[] = urlencode($key) . '=' . urlencode($val);
201         }
202         $args = join('&', $enc_args);
203     }
204
205     if (USE_PATH_INFO or !empty($WikiTheme->HTML_DUMP_SUFFIX)) {
206         $url = $get_abs_url ? (SERVER_URL . VIRTUAL_PATH . "/") : "";
207         $base = preg_replace('/%2f/i', '/', rawurlencode($pagename));
208         $url .= $base;
209         if (!empty($WikiTheme->HTML_DUMP_SUFFIX)) {
210             if (!empty($WikiTheme->VALID_LINKS) and $request->getArg('action') == 'pdf') {
211                 if (!in_array($pagename, $WikiTheme->VALID_LINKS))
212                     $url = '';
213                 else    
214                     $url = $base . $WikiTheme->HTML_DUMP_SUFFIX;
215             } else {
216                 $url .= $WikiTheme->HTML_DUMP_SUFFIX;
217                 if ($args)
218                     $url .= "?$args";
219             }
220         } else {
221             if ($args)
222                 $url .= "?$args";
223         }
224     }
225     else {
226         $url = $get_abs_url ? SERVER_URL . SCRIPT_NAME : basename(SCRIPT_NAME);
227         $url .= "?pagename=" . rawurlencode($pagename);
228         if ($args)
229             $url .= "&$args";
230     }
231     if ($anchor)
232         $url .= "#" . MangleXmlIdentifier($anchor);
233     return $url;
234 }
235
236 /** Convert relative URL to absolute URL.
237  *
238  * This converts a relative URL to one of PhpWiki's support files
239  * to an absolute one.
240  *
241  * @param string $url
242  * @return string Absolute URL
243  */
244 function AbsoluteURL ($url) {
245     if (preg_match('/^https?:/', $url))
246         return $url;
247     if ($url[0] != '/') {
248         $base = USE_PATH_INFO ? VIRTUAL_PATH : dirname(SCRIPT_NAME);
249         while ($base != '/' and substr($url, 0, 3) == "../") {
250             $url = substr($url, 3);
251             $base = dirname($base);
252         }
253         if ($base != '/')
254             $base .= '/';
255         $url = $base . $url;
256     }
257     return SERVER_URL . $url;
258 }
259
260 function DataURL ($url) {
261     if (preg_match('/^https?:/', $url))
262         return $url;
263     $url = NormalizeWebFileName($url);
264     if (DEBUG and $GLOBALS['request']->getArg('start_debug') and substr($url,-4,4) == '.php')
265         $url .= "?start_debug=1"; // XMLRPC and SOAP debugging helper.
266     return AbsoluteURL($url);
267 }
268
269 /**
270  * Generates icon in front of links.
271  *
272  * @param string $protocol_or_url URL or protocol to determine which icon to use.
273  *
274  * @return HtmlElement HtmlElement object that contains data to create img link to
275  * icon for use with url or protocol passed to the function. False if no img to be
276  * displayed.
277  */
278 function IconForLink($protocol_or_url) {
279     global $WikiTheme;
280     if (0 and $filename_suffix == false) {
281         // display apache style icon for file type instead of protocol icon
282         // - archive: unix:gz,bz2,tgz,tar,z; mac:dmg,dmgz,bin,img,cpt,sit; pc:zip;
283         // - document: html, htm, text, txt, rtf, pdf, doc
284         // - non-inlined image: jpg,jpeg,png,gif,tiff,tif,swf,pict,psd,eps,ps
285         // - audio: mp3,mp2,aiff,aif,au
286         // - multimedia: mpeg,mpg,mov,qt
287     } else {
288         list ($proto) = explode(':', $protocol_or_url, 2);
289         $src = $WikiTheme->getLinkIconURL($proto);
290         if ($src)
291             return HTML::img(array('src' => $src, 'alt' => "", 'class' => 'linkicon', 'border' => 0));
292         else
293             return false;
294     }
295 }
296
297 /**
298  * Glue icon in front of or after text.
299  * Pref: 'noLinkIcons'  - ignore icon if set
300  * Theme: 'LinkIcons'   - 'yes'   at front
301  *                      - 'no'    display no icon
302  *                      - 'front' display at left
303  *                      - 'after' display at right
304  *
305  * @param string $protocol_or_url Protocol or URL.  Used to determine the
306  * proper icon.
307  * @param string $text The text.
308  * @return XmlContent.
309  */
310 function PossiblyGlueIconToText($proto_or_url, $text) {
311     global $request, $WikiTheme;
312     if ($request->getPref('noLinkIcons'))
313         return $text;
314     $icon = IconForLink($proto_or_url);
315     if (!$icon)
316         return $text;
317     if ($where = $WikiTheme->getLinkIconAttr()) {
318         if ($where == 'no') return $text;
319         if ($where != 'after') $where = 'front';
320     } else {
321         $where = 'front';
322     }
323     if ($where == 'after') {
324         // span the icon only to the last word (tie them together), 
325         // to let the previous words wrap on line breaks.
326         if (!is_object($text)) {
327             preg_match('/^(\s*\S*)(\s*)$/', $text, $m);
328             list (, $prefix, $last_word) = $m;
329         }
330         else {
331             $last_word = $text;
332             $prefix = false;
333         }
334         $text = HTML::span(array('style' => 'white-space: nowrap'),
335                            $last_word, HTML::Raw('&nbsp;'), $icon);
336         if ($prefix)
337             $text = HTML($prefix, $text);
338         return $text;
339     }
340     // span the icon only to the first word (tie them together), 
341     // to let the next words wrap on line breaks
342     if (!is_object($text)) {
343         preg_match('/^\s*(\S*)(.*?)\s*$/', $text, $m);
344         list (, $first_word, $tail) = $m;
345     }
346     else {
347         $first_word = $text;
348         $tail = false;
349     }
350     $text = HTML::span(array('style' => 'white-space: nowrap'),
351                        $icon, $first_word);
352     if ($tail)
353         $text = HTML($text, $tail);
354     return $text;
355 }
356
357 /**
358  * Determines if the url passed to function is safe, by detecting if the characters
359  * '<', '>', or '"' are present.
360  * Check against their urlencoded values also.
361  *
362  * @param string $url URL to check for unsafe characters.
363  * @return boolean True if same, false else.
364  */
365 function IsSafeURL($url) {
366     return !preg_match('/([<>"])|(%3C)|(%3E)|(%22)/', $url);
367 }
368
369 /**
370  * Generates an HtmlElement object to store data for a link.
371  *
372  * @param string $url URL that the link will point to.
373  * @param string $linktext Text to be displayed as link.
374  * @return HtmlElement HtmlElement object that contains data to construct an html link.
375  */
376 function LinkURL($url, $linktext = '') {
377     // FIXME: Is this needed (or sufficient?)
378     if(! IsSafeURL($url)) {
379         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
380                                      _("BAD URL -- remove all of <, >, \"")));
381     }
382     else {
383         if (!$linktext)
384             $linktext = preg_replace("/mailto:/A", "", $url);
385         $args = array('href' => $url);
386         if ( defined('EXTERNAL_LINK_TARGET') ) // can also be set in the css
387             $args['target'] = is_string(EXTERNAL_LINK_TARGET) ? EXTERNAL_LINK_TARGET : "_blank";
388         $link = HTML::a($args, PossiblyGlueIconToText($url, $linktext));
389     }
390     $link->setAttr('class', $linktext ? 'namedurl' : 'rawurl');
391     return $link;
392 }
393
394 /**
395  * Inline Images
396  *
397  * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=]
398  * Disallows sizes which are too small. 
399  * Spammers may use such (typically invisible) image attributes to raise their GoogleRank.
400  *
401  * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially.
402  */
403 function LinkImage($url, $alt = false) {
404     $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi";
405     // Disallow tags in img src urls. Typical CSS attacks.
406     // FIXME: Is this needed (or sufficient?)
407     // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png"
408     $ori_url = $url;
409     if(! IsSafeURL($url)) {
410         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
411                                      _("BAD URL -- remove all of <, >, \"")));
412         return $link;
413     } else {
414         // support new syntax: [prefix/image.jpg size=50% border=n]
415         //if (!preg_match("/\.(".$force_img.")/i", $url))
416         if (empty($alt)) $alt = basename($url);
417         $arr = split(' ',$url);
418         $link = HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
419         if (count($arr) > 1) {
420             $url = $arr[0];
421             array_shift($arr);
422             foreach ($arr as $attr) {
423                 if (preg_match('/^size=(\d+%)$/',$attr,$m)) {
424                     $link->setAttr('width',$m[1]);
425                     $link->setAttr('height',$m[1]);
426                 }
427                 elseif (preg_match('/^size=(\d+)x(\d+)$/',$attr,$m)) {
428                     $link->setAttr('width',$m[1]);
429                     $link->setAttr('height',$m[2]);
430                 }
431                 elseif (preg_match('/^width=(\d+[%p]?x?)$/',$attr,$m))
432                     $link->setAttr('width',$m[1]);
433                 elseif (preg_match('/^height=(\d+[%p]?x?)$/',$attr,$m))
434                     $link->setAttr('height',$m[1]);
435                 elseif (preg_match('/^border=(\d+)$/',$attr,$m))
436                     $link->setAttr('border',$m[1]);
437                 elseif (preg_match('/^align=(\w+)$/',$attr,$m))
438                     $link->setAttr('align',$m[1]);
439                 elseif (preg_match('/^hspace=(\d+)$/',$attr,$m))
440                     $link->setAttr('hspace',$m[1]);
441                 elseif (preg_match('/^vspace=(\d+)$/',$attr,$m))
442                     $link->setAttr('vspace',$m[1]);
443                 else {
444                     $url .= ' '.$attr;
445                     if(! IsSafeURL($url)) {
446                         $link = HTML::strong(HTML::u(array('class' => 'baduri'),
447                                                      _("BAD URL -- remove all of <, >, \"")));
448                         return $link;
449                     } else {
450                         $link->setAttr('src', $url);
451                     }
452                 }
453             }
454         }
455         // Check width and height as spam countermeasure
456         if (($width  = $link->getAttr('width')) and ($height = $link->getAttr('height'))) {
457             //$width  = (int) $width; // px or % or other suffix
458             //$height = (int) $height;
459             if (($width < 3 and $height < 10) or 
460                 ($height < 3 and $width < 20) or 
461                 ($height < 7 and $width < 7))
462             {
463                 trigger_error(_("Invalid image size"), E_USER_WARNING);
464                 return '';
465             }
466         } else {
467             $size = 0;  
468             // Prepare for getimagesize($url)
469             // $url only valid for external urls, otherwise local path
470             // Older php versions crash here with certain png's: 
471             // confirmed for 4.1.2, 4.1.3, 4.2.3; 4.3.2 and 4.3.7 are ok
472             //   http://phpwiki.sourceforge.net/demo/themes/default/images/http.png
473             // See http://bugs.php.net/search.php?cmd=display&search_for=getimagesize
474             if (DISABLE_GETIMAGESIZE)
475                 ;
476             elseif (! preg_match("/\.$force_img$/i", $url))
477                 ;  // only valid image extensions or scripts assumed to generate images
478             elseif (!check_php_version(4,3) and preg_match("/^http.+\.png$/i",$url))
479                 ; // it's safe to assume that this will fail.
480             elseif (preg_match("/^http/",$url)) { // external url
481                 $size = @getimagesize($url); 
482             } else { // local file
483                 if (file_exists($file = NormalizeLocalFileName($url))) {  // here
484                     $size = @getimagesize($file);
485                 } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) {
486                     $size = @getimagesize($file);
487                     $link->setAttr('src', rawurldecode($url));
488                 } elseif (string_starts_with($url, getUploadDataPath())) { // there
489                     $file = substr($file, strlen(getUploadDataPath())); 
490                     $size = @getimagesize(getUploadFilePath().rawurldecode($file));
491                     $link->setAttr('src', getUploadDataPath() . rawurldecode($file));
492                 } else { // elsewhere
493                     $size = @getimagesize($request->get('DOCUMENT_ROOT').urldecode($url));
494                 }
495             }
496             if ($size) {
497                 $width  = $size[0];
498                 $height = $size[1];
499                 if (($width < 3 and $height < 10) 
500                     or ($height < 3 and $width < 20)
501                     or ($height < 7 and $width < 7))
502                 {
503                     trigger_error(_("Invalid image size"), E_USER_WARNING);
504                     return '';
505                 }
506             }
507         }
508     }
509     $link->setAttr('class', 'inlineimage');
510
511     /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides
512      * png|jpg|gif|jpeg|bmp|pl|cgi
513      * Note: Allow cgi's (pl,cgi) returning images.
514      */
515     if (!preg_match("/\.(".$force_img.")/i", $url)) {
516         // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt));
517         // => HTML::object(array('src' => $url)) ...;
518         return ImgObject($link, $ori_url);
519     }
520     return $link;
521 }
522
523 /**
524  * <object> / <embed> tags instead of <img> for all non-image extensions 
525  * in INLINE_IMAGES.
526  * Called by LinkImage(), not directly.
527  * Syntax:  [image.svg size=50% alt=image.gif border=n align= hspace= vspace= width= height=]
528  * Samples: [Upload:song.mp3 type=audio/mpeg width=200 height=10]
529  *   $alt may be an alternate img
530  * TODO: Need to unify with WikiPluginCached::embedObject()
531  *
532  * Note that Safari 1.0 will crash with <object>, so use only <embed>
533  *   http://www.alleged.org.uk/pdc/2002/svg-object.html
534  *
535  * Allowed object tags:
536  *   DATA=URI (object data) 
537  *   CLASSID=URI (location of implementation) 
538  *   ARCHIVE=CDATA (archive files) 
539  *   CODEBASE=URI (base URI for CLASSID, DATA, ARCHIVE) 
540  *   WIDTH=Length (object width) 
541  *   HEIGHT=Length (object height) 
542  *   NAME=CDATA (name for form submission) 
543  *   USEMAP=URI (client-side image map) 
544  *   TYPE=ContentType (content-type of object) 
545  *   CODETYPE=ContentType (content-type of code) 
546  *   STANDBY=Text (message to show while loading) 
547  *   TABINDEX=NUMBER (position in tabbing order) 
548  *   DECLARE (do not instantiate object)
549  * The rest is added as <param name="" value="" /> tags
550  */
551 function ImgObject($img, $url) {
552     // get the url args: data="sample.svgz" type="image/svg+xml" width="400" height="300"
553     $args = split(' ', $url);
554     $params = array();
555     if (count($args) >= 1) {
556         $url = array_shift($args);
557         $found = array();
558         foreach ($args as $attr) {
559             foreach (explode(",","data,classid,archive,codebase,name,usemap,type,".
560                              "codetype,standby,tabindex,declare") as $param)
561             {
562                 if (preg_match("/^$param=(\S+)$/i",$attr,$m)) {
563                     $img->setAttr($param, $m[1]);
564                     $found[$attr]++;
565                     break;
566                 }
567             }
568         }
569         // now all remaing args are added as <param> to the object
570         foreach ($args as $attr) {
571             if (!$found[$attr] and preg_match("/^(\S+)=(\S+)$/i",$attr,$m)) {
572                 $params[] = HTML::param(array('name'  => $m[1],
573                                               'value' => $m[2]));
574             }
575         }
576     }
577     $type = $img->getAttr('type');
578     if (!$type) {
579         // TODO: map extension to mime-types if type is not given and php < 4.3
580         if (function_exists('mime_content_type'))
581             $type = mime_content_type($url);
582     }
583     $object = HTML::object(array_merge($img->_attr, array('src' => $url, 'type' => $type)),
584                         $img->_content);
585     $object->setAttr('class', 'inlineobject');
586     if ($params) {
587         foreach ($params as $param) $object->pushContent($param);
588     }
589     if (isBrowserSafari()) {
590         return HTML::embed($object->_attr, $object->_content);
591     }
592     $object->pushContent(HTML::embed($object->_attr));
593     return $object;
594 }
595
596
597 class Stack {
598
599     // var in php5 deprecated
600     function Stack() {
601         $this->items = array();
602         $this->size = 0;
603     }
604     function push($item) {
605         $this->items[$this->size] = $item;
606         $this->size++;
607         return true;
608     }  
609     
610     function pop() {
611         if ($this->size == 0) {
612             return false; // stack is empty
613         }  
614         $this->size--;
615         return $this->items[$this->size];
616     }  
617     
618     function cnt() {
619         return $this->size;
620     }  
621     
622     function top() {
623         if($this->size)
624             return $this->items[$this->size - 1];
625         else
626             return '';
627     }
628     
629 }  
630 // end class definition
631
632 function SplitQueryArgs ($query_args = '') 
633 {
634     // FIXME: use the arg-seperator which might not be &
635     $split_args = split('&', $query_args);
636     $args = array();
637     while (list($key, $val) = each($split_args))
638         if (preg_match('/^ ([^=]+) =? (.*) /x', $val, $m))
639             $args[$m[1]] = $m[2];
640     return $args;
641 }
642
643 function LinkPhpwikiURL($url, $text = '', $basepage = false) {
644     $args = array();
645     
646     if (!preg_match('/^ phpwiki: ([^?]*) [?]? (.*) $/x', $url, $m)) {
647         return HTML::strong(array('class' => 'rawurl'),
648                             HTML::u(array('class' => 'baduri'),
649                                     _("BAD phpwiki: URL")));
650     }
651
652     if ($m[1])
653         $pagename = urldecode($m[1]);
654     $qargs = $m[2];
655     
656     if (empty($pagename) &&
657         preg_match('/^(diff|edit|links|info)=([^&]+)$/', $qargs, $m)) {
658         // Convert old style links (to not break diff links in
659         // RecentChanges).
660         $pagename = urldecode($m[2]);
661         $args = array("action" => $m[1]);
662     }
663     else {
664         $args = SplitQueryArgs($qargs);
665     }
666
667     if (empty($pagename))
668         $pagename = $GLOBALS['request']->getArg('pagename');
669
670     if (isset($args['action']) && $args['action'] == 'browse')
671         unset($args['action']);
672     
673     /*FIXME:
674       if (empty($args['action']))
675       $class = 'wikilink';
676       else if (is_safe_action($args['action']))
677       $class = 'wikiaction';
678     */
679     if (empty($args['action']) || is_safe_action($args['action']))
680         $class = 'wikiaction';
681     else {
682         // Don't allow administrative links on unlocked pages.
683         $dbi = $GLOBALS['request']->getDbh();
684         $page = $dbi->getPage($basepage ? $basepage : $pagename);
685         if (!$page->get('locked'))
686             return HTML::span(array('class' => 'wikiunsafe'),
687                               HTML::u(_("Lock page to enable link")));
688         $class = 'wikiadmin';
689     }
690     
691     if (!$text)
692         $text = HTML::span(array('class' => 'rawurl'), $url);
693
694     $wikipage = new WikiPageName($pagename);
695     if (!$wikipage->isValid()) {
696         global $WikiTheme;
697         return $WikiTheme->linkBadWikiWord($wikipage, $url);
698     }
699     
700     return HTML::a(array('href'  => WikiURL($pagename, $args),
701                          'class' => $class),
702                    $text);
703 }
704
705 /**
706  * A class to assist in parsing wiki pagenames.
707  *
708  * Now with subpages and anchors, parsing and passing around
709  * pagenames is more complicated.  This should help.
710  */
711 class WikiPageName
712 {
713     /** Short name for page.
714      *
715      * This is the value of $name passed to the constructor.
716      * (For use, e.g. as a default label for links to the page.)
717      */
718     //var $shortName;
719
720     /** The full page name.
721      *
722      * This is the full name of the page (without anchor).
723      */
724     //var $name;
725     
726     /** The anchor.
727      *
728      * This is the referenced anchor within the page, or the empty string.
729      */
730     //var $anchor;
731     
732     /** Constructor
733      *
734      * @param mixed $name Page name.
735      * WikiDB_Page, WikiDB_PageRevision, or string.
736      * This can be a relative subpage name (like '/SubPage'),
737      * or can be the empty string to refer to the $basename.
738      *
739      * @param string $anchor For links to anchors in page.
740      *
741      * @param mixed $basename Page name from which to interpret
742      * relative or other non-fully-specified page names.
743      */
744     function WikiPageName($name, $basename=false, $anchor=false) {
745         if (is_string($name)) {
746             $this->shortName = $name;
747             if (strstr($name, ':')) {
748                 list($moniker, $shortName) = split (":", $name, 2);
749                 $map = getInterwikiMap(); // allow overrides to custom maps
750                 if (isset($map->_map[$moniker])) {
751                     $url = $map->_map[$moniker];
752                     if (strstr($url, '%s'))
753                         $url = sprintf($url, $shortName);
754                     else
755                         $url .= $shortName;
756                     $this->url = $url;
757                     // expand Talk or User, but not to absolute urls!
758                     if (strstr($url, '//')) {
759                         if ($moniker == 'Talk')
760                             $name = $name . SUBPAGE_SEPARATOR . _("Discussion");
761                         elseif ($moniker == 'User')
762                             $name = $name;
763                     } else {
764                         $name = $url;
765                     }
766                     if (strstr($shortName, '?')) {
767                         list($shortName, $dummy) = split("\?", $shortName, 2);
768                     }
769                     $this->shortName = $shortName;
770                 }
771             }
772             // FIXME: We should really fix the cause for "/PageName" in the WikiDB
773             if ($name == '' or $name[0] == SUBPAGE_SEPARATOR) {
774                 if ($basename)
775                     $name = $this->_pagename($basename) . $name;
776                 else {
777                     $name = $this->_normalize_bad_pagename($name);
778                     $this->shortName = $name;
779                 }
780             }
781         }
782         else {
783             $name = $this->_pagename($name);
784             $this->shortName = $name;
785         }
786
787         $this->name = $this->_check($name);
788         $this->anchor = (string)$anchor;
789     }
790
791     function getName() {
792         return $this->name;
793     }
794     
795     function getParent() {
796         $name = $this->name;
797         if (!($tail = strrchr($name, SUBPAGE_SEPARATOR)))
798             return false;
799         return substr($name, 0, -strlen($tail));
800     }
801
802     function isValid($strict = false) {
803         if ($strict)
804             return !isset($this->_errors);
805         return (is_string($this->name) and $this->name != '');
806     }
807
808     function getWarnings() {
809         $warnings = array();
810         if (isset($this->_warnings))
811             $warnings = array_merge($warnings, $this->_warnings);
812         if (isset($this->_errors))
813             $warnings = array_merge($warnings, $this->_errors);
814         if (!$warnings)
815             return false;
816         
817         return sprintf(_("'%s': Bad page name: %s"),
818                        $this->shortName, join(', ', $warnings));
819     }
820     
821     function _pagename($page) {
822         if (isa($page, 'WikiDB_Page'))
823             return $page->getName();
824         elseif (isa($page, 'WikiDB_PageRevision'))
825             return $page->getPageName();
826         elseif (isa($page, 'WikiPageName'))
827             return $page->name;
828         // '0' or e.g. '1984' should be allowed though
829         if (!is_string($page) and !is_integer($page)) {
830             trigger_error(sprintf("Non-string pagename '%s' (%s)(%s)",
831                                   $page, gettype($page), get_class($page)),
832                           E_USER_NOTICE);
833         }
834         //assert(is_string($page));
835         return $page;
836     }
837
838     function _normalize_bad_pagename($name) {
839         trigger_error("Bad pagename: " . $name, E_USER_WARNING);
840
841         // Punt...  You really shouldn't get here.
842         if (empty($name)) {
843             global $request;
844             return $request->getArg('pagename');
845         }
846         assert($name[0] == SUBPAGE_SEPARATOR);
847         $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
848         return substr($name, 1);
849     }
850
851     /**
852      * Compress internal white-space to single space character.
853      *
854      * This leads to problems with loading a foreign charset pagename, 
855      * which cannot be deleted anymore, because unknown chars are compressed.
856      * So BEFORE importing a file _check must be done !!!
857      */
858     function _check($pagename) {
859         // Compress internal white-space to single space character.
860         $pagename = preg_replace('/[\s\xa0]+/', ' ', $orig = $pagename);
861         if ($pagename != $orig)
862             $this->_warnings[] = _("White space converted to single space");
863     
864         // Delete any control characters.
865         if (DATABASE_TYPE == 'cvs' or DATABASE_TYPE == 'file' or DATABASE_TYPE == 'flatfile') {
866             $pagename = preg_replace('/[\x00-\x1f\x7f\x80-\x9f]/', '', $orig = $pagename);
867             if ($pagename != $orig)
868                 $this->_errors[] = _("Control characters not allowed");
869         }
870
871         // Strip leading and trailing white-space.
872         $pagename = trim($pagename);
873
874         $orig = $pagename;
875         while ($pagename and $pagename[0] == SUBPAGE_SEPARATOR)
876             $pagename = substr($pagename, 1);
877         if ($pagename != $orig)
878             $this->_errors[] = sprintf(_("Leading %s not allowed"), SUBPAGE_SEPARATOR);
879
880         // ";" is urlencoded, so safe from php arg-delim problems
881         /*if (strstr($pagename, ';')) {
882             $this->_warnings[] = _("';' is deprecated");
883             $pagename = str_replace(';', '', $pagename);
884         }*/
885         
886         // not only for SQL, also to restrict url length
887         if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
888             $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH);
889             $this->_errors[] = _("too long");
890         }
891
892         // disallow some chars only on file and cvs
893         if ((DATABASE_TYPE == 'cvs' 
894             or DATABASE_TYPE == 'file' 
895             or DATABASE_TYPE == 'flatfile') 
896             and preg_match('/(:|\.\.)/', $pagename, $m)) 
897         {
898             $this->_warnings[] = sprintf(_("Illegal chars %s removed"), $m[1]);
899             $pagename = str_replace('..', '', $pagename);
900             $pagename = str_replace(':', '', $pagename);
901         }
902         
903         return $pagename;
904     }
905 }
906
907 /**
908  * Convert old page markup to new-style markup.
909  *
910  * @param string $text Old-style wiki markup.
911  *
912  * @param string $markup_type
913  * One of: <dl>
914  * <dt><code>"block"</code>  <dd>Convert all markup.
915  * <dt><code>"inline"</code> <dd>Convert only inline markup.
916  * <dt><code>"links"</code>  <dd>Convert only link markup.
917  * </dl>
918  *
919  * @return string New-style wiki markup.
920  *
921  * @bugs Footnotes don't work quite as before (esp if there are
922  *   multiple references to the same footnote.  But close enough,
923  *   probably for now....
924  * @bugs  Apache2 and IIS crash with OldTextFormattingRules or
925  *   AnciennesR%E8glesDeFormatage. (at the 2nd attempt to do the anchored block regex)
926  *   It only crashes with CreateToc so far, but other pages (not in pgsrc) are 
927  *   also known to crash, even with Apache1.
928  */
929 function ConvertOldMarkup ($text, $markup_type = "block") {
930
931     static $subs;
932     static $block_re;
933     
934     // FIXME:
935     // Trying to detect why the 2nd paragraph of OldTextFormattingRules or
936     // AnciennesR%E8glesDeFormatage crashes. 
937     // It only crashes with CreateToc so far, but other pages (not in pgsrc) are 
938     // also known to crash, even with Apache1.
939     $debug_skip = false;
940     // I suspect this only to crash with Apache2 and IIS.
941     if (in_array(php_sapi_name(),array('apache2handler','apache2filter','isapi'))
942         and preg_match("/plugin CreateToc/", $text)) 
943     {
944         trigger_error(_("The CreateTocPlugin is not yet old markup compatible! ")
945                      ._("Please remove the CreateToc line to be able to reformat this page to old markup. ")
946                      ._("Skipped."), E_USER_WARNING);
947         $debug_skip = true;
948         //if (!DEBUG) return $text;
949         return $text;
950     }
951
952     if (empty($subs)) {
953         /*****************************************************************
954          * Conversions for inline markup:
955          */
956
957         // escape tilde's
958         $orig[] = '/~/';
959         $repl[] = '~~';
960
961         // escape escaped brackets
962         $orig[] = '/\[\[/';
963         $repl[] = '~[';
964
965         // change ! escapes to ~'s.
966         global $WikiNameRegexp, $request;
967         $bang_esc[] = "(?:" . ALLOWED_PROTOCOLS . "):[^\s<>\[\]\"'()]*[^\s<>\[\]\"'(),.?]";
968         // before 4.3.9 pcre had a memory release bug, which might hit us here. so be safe.
969         if (check_php_version(4,3,9)) {
970           $map = getInterwikiMap();
971           if ($map_regex = $map->getRegexp())
972             $bang_esc[] = $map_regex . ":[^\\s.,;?()]+"; // FIXME: is this really needed?
973         }
974         $bang_esc[] = $WikiNameRegexp;
975         $orig[] = '/!((?:' . join(')|(', $bang_esc) . '))/';
976         $repl[] = '~\\1';
977
978         $subs["links"] = array($orig, $repl);
979
980         // Temporarily URL-encode pairs of underscores in links to hide
981         // them from the re for bold markup.
982         $orig[] = '/\[[^\[\]]*?__[^\[\]]*?\]/e';
983         $repl[] = 'str_replace(\'__\', \'%5F%5F\', \'\\0\')';
984
985         // Escape '<'s
986         //$orig[] = '/<(?!\?plugin)|(?<!^)</m';
987         //$repl[] = '~<';
988         
989         // Convert footnote references.
990         $orig[] = '/(?<=.)(?<!~)\[\s*(\d+)\s*\]/m';
991         $repl[] = '#[|ftnt_ref_\\1]<sup>~[[\\1|#ftnt_\\1]~]</sup>';
992
993         // Convert old style emphases to HTML style emphasis.
994         $orig[] = '/__(.*?)__/';
995         $repl[] = '<strong>\\1</strong>';
996         $orig[] = "/''(.*?)''/";
997         $repl[] = '<em>\\1</em>';
998
999         // Escape nestled markup.
1000         $orig[] = '/^(?<=^|\s)[=_](?=\S)|(?<=\S)[=_*](?=\s|$)/m';
1001         $repl[] = '~\\0';
1002         
1003         // in old markup headings only allowed at beginning of line
1004         $orig[] = '/!/';
1005         $repl[] = '~!';
1006
1007         // Convert URL-encoded pairs of underscores in links back to
1008         // real underscores after bold markup has been converted.
1009         $orig = '/\[[^\[\]]*?%5F%5F[^\[\]]*?\]/e';
1010         $repl = 'str_replace(\'%5F%5F\', \'__\', \'\\0\')';
1011
1012         $subs["inline"] = array($orig, $repl);
1013
1014         /*****************************************************************
1015          * Patterns which match block markup constructs which take
1016          * special handling...
1017          */
1018
1019         // Indented blocks
1020         $blockpats[] = '[ \t]+\S(?:.*\s*\n[ \t]+\S)*';
1021         // Tables
1022         $blockpats[] = '\|(?:.*\n\|)*';
1023
1024         // List items
1025         $blockpats[] = '[#*;]*(?:[*#]|;.*?:)';
1026
1027         // Footnote definitions
1028         $blockpats[] = '\[\s*(\d+)\s*\]';
1029
1030         if (!$debug_skip) {
1031         // Plugins
1032         $blockpats[] = '<\?plugin(?:-form)?\b.*\?>\s*$';
1033         }
1034
1035         // Section Title
1036         $blockpats[] = '!{1,3}[^!]';
1037         /*
1038         removed .|\n in the anchor not to crash on /m because with /m "." already includes \n
1039         this breaks headings but it doesn't crash anymore (crash on non-cgi, non-cli only)
1040         */
1041         $block_re = ( '/\A((?:.|\n)*?)(^(?:'
1042                       . join("|", $blockpats)
1043                       . ').*$)\n?/m' );
1044         
1045     }
1046     
1047     if ($markup_type != "block") {
1048         list ($orig, $repl) = $subs[$markup_type];
1049         return preg_replace($orig, $repl, $text);
1050     }
1051     else {
1052         list ($orig, $repl) = $subs['inline'];
1053         $out = '';
1054         //FIXME:
1055         // php crashes here in the 2nd paragraph of OldTextFormattingRules, 
1056         // AnciennesR%E8glesDeFormatage and more 
1057         // See http://www.pcre.org/pcre.txt LIMITATIONS
1058          while (preg_match($block_re, $text, $m)) {
1059             $text = substr($text, strlen($m[0]));
1060             list (,$leading_text, $block) = $m;
1061             $suffix = "\n";
1062             
1063             if (strchr(" \t", $block[0])) {
1064                 // Indented block
1065                 $prefix = "<pre>\n";
1066                 $suffix = "\n</pre>\n";
1067             }
1068             elseif ($block[0] == '|') {
1069                 // Old-style table
1070                 $prefix = "<?plugin OldStyleTable\n";
1071                 $suffix = "\n?>\n";
1072             }
1073             elseif (strchr("#*;", $block[0])) {
1074                 // Old-style list item
1075                 preg_match('/^([#*;]*)([*#]|;.*?:) */', $block, $m);
1076                 list (,$ind,$bullet) = $m;
1077                 $block = substr($block, strlen($m[0]));
1078                 
1079                 $indent = str_repeat('     ', strlen($ind));
1080                 if ($bullet[0] == ';') {
1081                     //$term = ltrim(substr($bullet, 1));
1082                     //return $indent . $term . "\n" . $indent . '     ';
1083                     $prefix = $ind . $bullet;
1084                 }
1085                 else
1086                     $prefix = $indent . $bullet . ' ';
1087             }
1088             elseif ($block[0] == '[') {
1089                 // Footnote definition
1090                 preg_match('/^\[\s*(\d+)\s*\]/', $block, $m);
1091                 $footnum = $m[1];
1092                 $block = substr($block, strlen($m[0]));
1093                 $prefix = "#[|ftnt_".${footnum}."]~[[".${footnum}."|#ftnt_ref_".${footnum}."]~] ";
1094             }
1095             elseif ($block[0] == '<') {
1096                 // Plugin.
1097                 // HACK: no inline markup...
1098                 $prefix = $block;
1099                 $block = '';
1100             }
1101             elseif ($block[0] == '!') {
1102                 // Section heading
1103                 preg_match('/^!{1,3}/', $block, $m);
1104                 $prefix = $m[0];
1105                 $block = substr($block, strlen($m[0]));
1106             }
1107             else {
1108                 // AAck!
1109                 assert(0);
1110             }
1111             if ($leading_text) $leading_text = preg_replace($orig, $repl, $leading_text);
1112             if ($block) $block = preg_replace($orig, $repl, $block);
1113             $out .= $leading_text;
1114             $out .= $prefix;
1115             $out .= $block;
1116             $out .= $suffix;
1117         }
1118         return $out . preg_replace($orig, $repl, $text);
1119     }
1120 }
1121
1122
1123 /**
1124  * Expand tabs in string.
1125  *
1126  * Converts all tabs to (the appropriate number of) spaces.
1127  *
1128  * @param string $str
1129  * @param integer $tab_width
1130  * @return string
1131  */
1132 function expand_tabs($str, $tab_width = 8) {
1133     $split = split("\t", $str);
1134     $tail = array_pop($split);
1135     $expanded = "\n";
1136     foreach ($split as $hunk) {
1137         $expanded .= $hunk;
1138         $pos = strlen(strrchr($expanded, "\n")) - 1;
1139         $expanded .= str_repeat(" ", ($tab_width - $pos % $tab_width));
1140     }
1141     return substr($expanded, 1) . $tail;
1142 }
1143
1144 /**
1145  * Split WikiWords in page names.
1146  *
1147  * It has been deemed useful to split WikiWords (into "Wiki Words") in
1148  * places like page titles. This is rumored to help search engines
1149  * quite a bit.
1150  *
1151  * @param $page string The page name.
1152  *
1153  * @return string The split name.
1154  */
1155 function SplitPagename ($page) {
1156     
1157     if (preg_match("/\s/", $page))
1158         return $page;           // Already split --- don't split any more.
1159     
1160     // This algorithm is specialized for several languages.
1161     // (Thanks to Pierrick MEIGNEN)
1162     // Improvements for other languages welcome.
1163     static $RE;
1164     if (!isset($RE)) {
1165         // This mess splits between a lower-case letter followed by
1166         // either an upper-case or a numeral; except that it wont
1167         // split the prefixes 'Mc', 'De', or 'Di' off of their tails.
1168         switch ($GLOBALS['LANG']) {
1169         case 'en':
1170         case 'it':
1171         case 'es': 
1172         case 'de':
1173             $RE[] = '/([[:lower:]])((?<!Mc|De|Di)[[:upper:]]|\d)/';
1174             break;
1175         case 'fr': 
1176             $RE[] = '/([[:lower:]])((?<!Mc|Di)[[:upper:]]|\d)/';
1177             break;
1178         }
1179         $sep = preg_quote(SUBPAGE_SEPARATOR, '/');
1180         // This the single-letter words 'I' and 'A' from any following
1181         // capitalized words.
1182         switch ($GLOBALS['LANG']) {
1183         case 'en': 
1184             $RE[] = "/(?<= |${sep}|^)([AI])([[:upper:]][[:lower:]])/";
1185             break;
1186         case 'fr': 
1187             $RE[] = "/(?<= |${sep}|^)([À])([[:upper:]][[:lower:]])/";
1188             break;
1189         }
1190         // Split numerals from following letters.
1191         $RE[] = '/(\d)([[:alpha:]])/';
1192         // Split at subpage seperators. TBD in Theme.php
1193         $RE[] = "/([^${sep}]+)(${sep})/";
1194         $RE[] = "/(${sep})([^${sep}]+)/";
1195         
1196         foreach ($RE as $key)
1197             $RE[$key] = pcre_fix_posix_classes($key);
1198     }
1199
1200     foreach ($RE as $regexp) {
1201         $page = preg_replace($regexp, '\\1 \\2', $page);
1202     }
1203     return $page;
1204 }
1205
1206 function NoSuchRevision (&$request, $page, $version) {
1207     $html = HTML(HTML::h2(_("Revision Not Found")),
1208                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
1209                              $version, WikiLink($page, 'auto'))));
1210     include_once('lib/Template.php');
1211     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1212     $request->finish();
1213 }
1214
1215
1216 /**
1217  * Get time offset for local time zone.
1218  *
1219  * @param $time time_t Get offset for this time. Default: now.
1220  * @param $no_colon boolean Don't put colon between hours and minutes.
1221  * @return string Offset as a string in the format +HH:MM.
1222  */
1223 function TimezoneOffset ($time = false, $no_colon = false) {
1224     if ($time === false)
1225         $time = time();
1226     $secs = date('Z', $time);
1227
1228     if ($secs < 0) {
1229         $sign = '-';
1230         $secs = -$secs;
1231     }
1232     else {
1233         $sign = '+';
1234     }
1235     $colon = $no_colon ? '' : ':';
1236     $mins = intval(($secs + 30) / 60);
1237     return sprintf("%s%02d%s%02d",
1238                    $sign, $mins / 60, $colon, $mins % 60);
1239 }
1240
1241
1242 /**
1243  * Format time in ISO-8601 format.
1244  *
1245  * @param $time time_t Time.  Default: now.
1246  * @return string Date and time in ISO-8601 format.
1247  */
1248 function Iso8601DateTime ($time = false) {
1249     if ($time === false)
1250         $time = time();
1251     $tzoff = TimezoneOffset($time);
1252     $date  = date('Y-m-d', $time);
1253     $time  = date('H:i:s', $time);
1254     return $date . 'T' . $time . $tzoff;
1255 }
1256
1257 /**
1258  * Format time in RFC-2822 format.
1259  *
1260  * @param $time time_t Time.  Default: now.
1261  * @return string Date and time in RFC-2822 format.
1262  */
1263 function Rfc2822DateTime ($time = false) {
1264     if ($time === false)
1265         $time = time();
1266     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1267 }
1268
1269 /**
1270  * Format time in RFC-1123 format.
1271  *
1272  * @param $time time_t Time.  Default: now.
1273  * @return string Date and time in RFC-1123 format.
1274  */
1275 function Rfc1123DateTime ($time = false) {
1276     if ($time === false)
1277         $time = time();
1278     return gmdate('D, d M Y H:i:s \G\M\T', $time);
1279 }
1280
1281 /** Parse date in RFC-1123 format.
1282  *
1283  * According to RFC 1123 we must accept dates in the following
1284  * formats:
1285  *
1286  *   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
1287  *   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1288  *   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
1289  *
1290  * (Though we're only allowed to generate dates in the first format.)
1291  */
1292 function ParseRfc1123DateTime ($timestr) {
1293     $timestr = trim($timestr);
1294     if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1295                    .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1296                    $timestr, $m)) {
1297         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1298     }
1299     elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1300                        .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1301                        $timestr, $m)) {
1302         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1303         if ($year < 70) $year += 2000;
1304         elseif ($year < 100) $year += 1900;
1305     }
1306     elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1307                        .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1308                        $timestr, $m)) {
1309         list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1310     }
1311     else {
1312         // Parse failed.
1313         return false;
1314     }
1315
1316     $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1317     if ($time == -1)
1318         return false;           // failed
1319     return $time;
1320 }
1321
1322 /**
1323  * Format time to standard 'ctime' format.
1324  *
1325  * @param $time time_t Time.  Default: now.
1326  * @return string Date and time.
1327  */
1328 function CTime ($time = false)
1329 {
1330     if ($time === false)
1331         $time = time();
1332     return date("D M j H:i:s Y", $time);
1333 }
1334
1335
1336 /**
1337  * Format number as kilobytes or bytes.
1338  * Short format is used for PageList
1339  * Long format is used in PageInfo
1340  *
1341  * @param $bytes       int.  Default: 0.
1342  * @param $longformat  bool. Default: false.
1343  * @return class FormattedText (XmlElement.php).
1344  */
1345 function ByteFormatter ($bytes = 0, $longformat = false) {
1346     if ($bytes < 0)
1347         return fmt("-???");
1348     if ($bytes < 1024) {
1349         if (! $longformat)
1350             $size = fmt("%s b", $bytes);
1351         else
1352             $size = fmt("%s bytes", $bytes);
1353     }
1354     else {
1355         $kb = round($bytes / 1024, 1);
1356         if (! $longformat)
1357             $size = fmt("%s k", $kb);
1358         else
1359             $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1360     }
1361     return $size;
1362 }
1363
1364 /**
1365  * Internationalized printf.
1366  *
1367  * This is essentially the same as PHP's built-in printf
1368  * with the following exceptions:
1369  * <ol>
1370  * <li> It passes the format string through gettext().
1371  * <li> It supports the argument reordering extensions.
1372  * </ol>
1373  *
1374  * Example:
1375  *
1376  * In php code, use:
1377  * <pre>
1378  *    __printf("Differences between versions %s and %s of %s",
1379  *             $new_link, $old_link, $page_link);
1380  * </pre>
1381  *
1382  * Then in locale/po/de.po, one can reorder the printf arguments:
1383  *
1384  * <pre>
1385  *    msgid "Differences between %s and %s of %s."
1386  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1387  * </pre>
1388  *
1389  * (Note that while PHP tries to expand $vars within double-quotes,
1390  * the values in msgstr undergo no such expansion, so the '$'s
1391  * okay...)
1392  *
1393  * One shouldn't use reordered arguments in the default format string.
1394  * Backslashes in the default string would be necessary to escape the
1395  * '$'s, and they'll cause all kinds of trouble....
1396  */ 
1397 function __printf ($fmt) {
1398     $args = func_get_args();
1399     array_shift($args);
1400     echo __vsprintf($fmt, $args);
1401 }
1402
1403 /**
1404  * Internationalized sprintf.
1405  *
1406  * This is essentially the same as PHP's built-in printf with the
1407  * following exceptions:
1408  *
1409  * <ol>
1410  * <li> It passes the format string through gettext().
1411  * <li> It supports the argument reordering extensions.
1412  * </ol>
1413  *
1414  * @see __printf
1415  */ 
1416 function __sprintf ($fmt) {
1417     $args = func_get_args();
1418     array_shift($args);
1419     return __vsprintf($fmt, $args);
1420 }
1421
1422 /**
1423  * Internationalized vsprintf.
1424  *
1425  * This is essentially the same as PHP's built-in printf with the
1426  * following exceptions:
1427  *
1428  * <ol>
1429  * <li> It passes the format string through gettext().
1430  * <li> It supports the argument reordering extensions.
1431  * </ol>
1432  *
1433  * @see __printf
1434  */ 
1435 function __vsprintf ($fmt, $args) {
1436     $fmt = gettext($fmt);
1437     // PHP's sprintf doesn't support variable with specifiers,
1438     // like sprintf("%*s", 10, "x"); --- so we won't either.
1439     
1440     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1441         // Format string has '%2$s' style argument reordering.
1442         // PHP doesn't support this.
1443         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1444             // literal variable name substitution only to keep locale
1445             // strings uncluttered
1446             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1447                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
1448         
1449         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1450         $newargs = array();
1451         
1452         // Reorder arguments appropriately.
1453         foreach($m[1] as $argnum) {
1454             if ($argnum < 1 || $argnum > count($args))
1455                 trigger_error(sprintf(_("%s: argument index out of range"), 
1456                                       $argnum), E_USER_WARNING);
1457             $newargs[] = $args[$argnum - 1];
1458         }
1459         $args = $newargs;
1460     }
1461     
1462     // Not all PHP's have vsprintf, so...
1463     array_unshift($args, $fmt);
1464     return call_user_func_array('sprintf', $args);
1465 }
1466
1467 function file_mtime ($filename) {
1468     if ($stat = @stat($filename))
1469         return $stat[9];
1470     else 
1471         return false;
1472 }
1473
1474 function sort_file_mtime ($a, $b) {
1475     $ma = file_mtime($a);
1476     $mb = file_mtime($b);
1477     if (!$ma or !$mb or $ma == $mb) return 0;
1478     return ($ma > $mb) ? -1 : 1;
1479 }
1480
1481 class fileSet {
1482     /**
1483      * Build an array in $this->_fileList of files from $dirname.
1484      * Subdirectories are not traversed.
1485      *
1486      * (This was a function LoadDir in lib/loadsave.php)
1487      * See also http://www.php.net/manual/en/function.readdir.php
1488      */
1489     function getFiles($exclude='', $sortby='', $limit='') {
1490         $list = $this->_fileList;
1491
1492         if ($sortby) {
1493             require_once('lib/PageList.php');
1494             switch (Pagelist::sortby($sortby, 'db')) {
1495             case 'pagename ASC': break;
1496             case 'pagename DESC': 
1497                 $list = array_reverse($list); 
1498                 break;
1499             case 'mtime ASC': 
1500                 usort($list,'sort_file_mtime'); 
1501                 break;
1502             case 'mtime DESC': 
1503                 usort($list,'sort_file_mtime');
1504                 $list = array_reverse($list); 
1505                 break;
1506             }
1507         }
1508         if ($limit)
1509             return array_splice($list, 0, $limit);
1510         return $list;
1511     }
1512
1513     function _filenameSelector($filename) {
1514         if (! $this->_pattern )
1515             return true;
1516         else {
1517             if (! $this->_pcre_pattern )
1518                 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1519             return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'), 
1520                               $filename);
1521         }
1522     }
1523
1524     function fileSet($directory, $filepattern = false) {
1525         $this->_fileList = array();
1526         $this->_pattern = $filepattern;
1527         if ($filepattern) {
1528             $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1529         }
1530         $this->_case = !isWindows();
1531         $this->_pathsep = '/';
1532
1533         if (empty($directory)) {
1534             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1535                           E_USER_NOTICE);
1536             return; // early return
1537         }
1538
1539         @ $dir_handle = opendir($dir=$directory);
1540         if (empty($dir_handle)) {
1541             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1542                                   $dir), E_USER_NOTICE);
1543             return; // early return
1544         }
1545
1546         while ($filename = readdir($dir_handle)) {
1547             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1548                 continue;
1549             if ($this->_filenameSelector($filename)) {
1550                 array_push($this->_fileList, "$filename");
1551                 //trigger_error(sprintf(_("found file %s"), $filename),
1552                 //                      E_USER_NOTICE); //debugging
1553             }
1554         }
1555         closedir($dir_handle);
1556     }
1557 };
1558
1559 // File globbing
1560
1561 // expands a list containing regex's to its matching entries
1562 class ListRegexExpand {
1563     //var $match, $list, $index, $case_sensitive;
1564     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1565         $this->match = $match;
1566         $this->list = &$list;
1567         $this->case_sensitive = $case_sensitive;        
1568         //$this->index = false;
1569     }
1570     function listMatchCallback ($item, $key) {
1571         $quoted = str_replace('/','\/',$item);
1572         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), 
1573                        $quoted)) {
1574             unset($this->list[$this->index]);
1575             $this->list[] = $item;
1576         }
1577     }
1578     function expandRegex ($index, &$pages) {
1579         $this->index = $index;
1580         array_walk($pages, array($this, 'listMatchCallback'));
1581         return $this->list;
1582     }
1583 }
1584
1585 // Convert fileglob to regex style:
1586 // Convert some wildcards to pcre style, escape the rest
1587 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1588 // Fixed bug #994994: "/" in $glob.
1589 function glob_to_pcre ($glob) {
1590     // check simple case: no need to escape
1591     $escape = '\[](){}=!<>|:/';
1592     if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1593         return $glob;
1594     // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1595     $glob = strtr($glob, "\\", "\xff");
1596     $glob = str_replace("/", "\\/", $glob);
1597     // first convert some unescaped expressions to pcre style: . => \.
1598     $special = '.^$';
1599     $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/', 
1600                        "\\1\xff\\2", $glob);
1601
1602     // * => .*, ? => .
1603     $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1604     $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1605     if (!preg_match('/^[\?\*]/', $glob))
1606         $re = '^' . $re;
1607     if (!preg_match('/[\?\*]$/', $glob))
1608         $re = $re . '$';
1609
1610     // Fixes Bug 1182997
1611     // .*? handled above, now escape the rest
1612     //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1613     $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/', 
1614                        "\\1\xff\\2", $re);
1615     // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1616     // 'plugin/*.php'
1617     $re = preg_replace('/\xff/', '', $re);
1618     return $re;
1619 }
1620
1621 function glob_match ($glob, $against, $case_sensitive = true) {
1622     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), 
1623                       $against);
1624 }
1625
1626 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1627     $list = explode(',',$input);
1628     // expand wildcards from list of $allnames
1629     if (preg_match('/[\?\*]/',$input)) {
1630         // Optimizing loop invariants:
1631         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1632         for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1633             $f = $list[$i];
1634             if (preg_match('/[\?\*]/',$f)) {
1635                 reset($allnames);
1636                 $expand = new ListRegexExpand($list, 
1637                     $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1638                 $expand->expandRegex($i, $allnames);
1639             }
1640         }
1641     }
1642     return $list;
1643 }
1644
1645 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1646 function explodePageList($input, $include_empty=false, $sortby='pagename', 
1647                          $limit='', $exclude='') {
1648     include_once("lib/PageList.php");
1649     return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1650 }
1651
1652 // Class introspections
1653
1654 /** 
1655  * Determine whether object is of a specified type.
1656  * In PHP builtin since 4.2.0 as is_a()
1657  * is_a() deprecated in PHP 5, in favor of instanceof operator
1658
1659  * @param $object object An object.
1660  * @param $class string Class name.
1661  * @return bool True iff $object is a $class
1662  * or a sub-type of $class. 
1663  */
1664 function isa ($object, $class) {
1665     //if (check_php_version(5)) 
1666     //    return $object instanceof $class;
1667     if (check_php_version(4,2) and !check_php_version(5)) 
1668         return is_a($object, $class);
1669
1670     $lclass = check_php_version(5) ? $class : strtolower($class);
1671     return is_object($object)
1672         && ( strtolower(get_class($object)) == strtolower($class)
1673              || is_subclass_of($object, $lclass) );
1674 }
1675
1676 /** Determine whether (possible) object has method.
1677  *
1678  * @param $object mixed Object
1679  * @param $method string Method name
1680  * @return bool True iff $object is an object with has method $method.
1681  */
1682 function can ($object, $method) {
1683     return is_object($object) && method_exists($object, strtolower($method));
1684 }
1685
1686 /** Determine whether a function is okay to use.
1687  *
1688  * Some providers (e.g. Lycos) disable some of PHP functions for
1689  * "security reasons."  This makes those functions, of course,
1690  * unusable, despite the fact the function_exists() says they
1691  * exist.
1692  *
1693  * This function test to see if a function exists and is not
1694  * disallowed by PHP's disable_functions config setting.
1695  *
1696  * @param string $function_name  Function name
1697  * @return bool  True iff function can be used.
1698  */
1699 function function_usable($function_name) {
1700     static $disabled;
1701     if (!is_array($disabled)) {
1702         $disabled = array();
1703         // Use get_cfg_var since ini_get() is one of the disabled functions
1704         // (on Lycos, at least.)
1705         $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1706         foreach ($split as $f)
1707             $disabled[strtolower($f)] = true;
1708     }
1709
1710     return ( function_exists($function_name)
1711              and ! isset($disabled[strtolower($function_name)])
1712              );
1713 }
1714     
1715     
1716 /** Hash a value.
1717  *
1718  * This is used for generating ETags.
1719  */
1720 function wikihash ($x) {
1721     if (is_scalar($x)) {
1722         return $x;
1723     }
1724     elseif (is_array($x)) {            
1725         ksort($x);
1726         return md5(serialize($x));
1727     }
1728     elseif (is_object($x)) {
1729         return $x->hash();
1730     }
1731     trigger_error("Can't hash $x", E_USER_ERROR);
1732 }
1733
1734
1735 /**
1736  * Seed the random number generator.
1737  *
1738  * better_srand() ensures the randomizer is seeded only once.
1739  * 
1740  * How random do you want it? See:
1741  * http://www.php.net/manual/en/function.srand.php
1742  * http://www.php.net/manual/en/function.mt-srand.php
1743  */
1744 function better_srand($seed = '') {
1745     static $wascalled = FALSE;
1746     if (!$wascalled) {
1747         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1748         function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1749         $wascalled = TRUE;
1750         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1751     }
1752 }
1753
1754 function rand_ascii($length = 1) {
1755     better_srand();
1756     $s = "";
1757     for ($i = 1; $i <= $length; $i++) {
1758         // return only typeable 7 bit ascii, avoid quotes
1759         if (function_exists('mt_rand'))
1760             $s .= chr(mt_rand(40, 126)); 
1761         else
1762             // the usually bad glibc srand()
1763             $s .= chr(rand(40, 126));
1764     }
1765     return $s;
1766 }
1767
1768 /* by Dan Frankowski.
1769  */
1770 function rand_ascii_readable ($length = 6) {
1771     // Pick a few random letters or numbers
1772     $word = "";
1773     better_srand();
1774     // Don't use 1lI0O, because they're hard to read
1775     $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1776     $letter_len = strlen($letters);
1777     for ($i=0; $i < $length; $i++) {
1778         if (function_exists('mt_rand'))
1779             $word .= $letters[mt_rand(0, $letter_len-1)];
1780         else
1781             $word .= $letters[rand(0, $letter_len-1)];
1782     }
1783     return $word;
1784 }
1785
1786 /**
1787  * Recursively count all non-empty elements 
1788  * in array of any dimension or mixed - i.e. 
1789  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1790  * See http://www.php.net/manual/en/function.count.php
1791  */
1792 function count_all($arg) {
1793     // skip if argument is empty
1794     if ($arg) {
1795         //print_r($arg); //debugging
1796         $count = 0;
1797         // not an array, return 1 (base case) 
1798         if(!is_array($arg))
1799             return 1;
1800         // else call recursively for all elements $arg
1801         foreach($arg as $key => $val)
1802             $count += count_all($val);
1803         return $count;
1804     }
1805 }
1806
1807 function isSubPage($pagename) {
1808     return (strstr($pagename, SUBPAGE_SEPARATOR));
1809 }
1810
1811 function subPageSlice($pagename, $pos) {
1812     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1813     $pages = array_slice($pages,$pos,1);
1814     return $pages[0];
1815 }
1816
1817 /**
1818  * Alert
1819  *
1820  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1821  * pop up...)
1822  *
1823  * FIXME:
1824  * This is a hackish and needs to be refactored.  However it would be nice to
1825  * unify all the different methods we use for showing Alerts and Dialogs.
1826  * (E.g. "Page deleted", login form, ...)
1827  */
1828 class Alert {
1829     /** Constructor
1830      *
1831      * @param object $request
1832      * @param mixed $head  Header ("title") for alert box.
1833      * @param mixed $body  The text in the alert box.
1834      * @param hash $buttons  An array mapping button labels to URLs.
1835      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1836      */
1837     function Alert($head, $body, $buttons=false) {
1838         if ($buttons === false)
1839             $buttons = array();
1840
1841         if (is_array($body)) {
1842             $html = HTML::ol();
1843             foreach ($body as $li) {
1844                 $html->pushContent(HTML::li($li));
1845             }
1846             $body = $html;
1847         }
1848         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1849         $this->_buttons = $buttons;
1850     }
1851
1852     /**
1853      * Show the alert box.
1854      */
1855     function show() {
1856         global $request;
1857
1858         $tokens = $this->_tokens;
1859         $tokens['BUTTONS'] = $this->_getButtons();
1860         
1861         $request->discardOutput();
1862         $tmpl = new Template('dialog', $request, $tokens);
1863         $tmpl->printXML();
1864         $request->finish();
1865     }
1866
1867
1868     function _getButtons() {
1869         global $request;
1870
1871         $buttons = $this->_buttons;
1872         if (!$buttons)
1873             $buttons = array(_("Okay") => $request->getURLtoSelf());
1874         
1875         global $WikiTheme;
1876         foreach ($buttons as $label => $url)
1877             print "$label $url\n";
1878             $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1879         return new XmlContent($out);
1880     }
1881 }
1882
1883 // 1.3.8     => 1030.08
1884 // 1.3.9-p1  => 1030.091
1885 // 1.3.10pre => 1030.099
1886 // 1.3.11pre-20041120 => 1030.1120041120
1887 // 1.3.12-rc1 => 1030.119
1888 function phpwiki_version() {
1889     static $PHPWIKI_VERSION;
1890     if (!isset($PHPWIKI_VERSION)) {
1891         $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1892         $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1893         $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1894         if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1895             $PHPWIKI_VERSION -= 0.01;
1896     }
1897     return $PHPWIKI_VERSION;
1898 }
1899
1900 function phpwiki_gzhandler($ob) {
1901     if (function_exists('gzencode'))
1902         $ob = gzencode($ob);
1903         $GLOBALS['request']->_ob_get_length = strlen($ob);
1904     if (!headers_sent()) {
1905         header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1906     }
1907     return $ob;
1908 }
1909
1910 function isWikiWord($word) {
1911     global $WikiNameRegexp;
1912     //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1913     return preg_match("/^$WikiNameRegexp\$/",$word);
1914 }
1915
1916 // needed to store serialized objects-values only (perm, pref)
1917 function obj2hash ($obj, $exclude = false, $fields = false) {
1918     $a = array();
1919     if (! $fields ) $fields = get_object_vars($obj);
1920     foreach ($fields as $key => $val) {
1921         if (is_array($exclude)) {
1922             if (in_array($key, $exclude)) continue;
1923         }
1924         $a[$key] = $val;
1925     }
1926     return $a;
1927 }
1928
1929 /**
1930  * isUtf8String($string) - cheap utf-8 detection
1931  *
1932  * segfaults for strings longer than 10kb!
1933  * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1934  * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1935  */
1936 function isUtf8String( $s ) {
1937     $ptrASCII  = '[\x00-\x7F]';
1938     $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1939     $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1940     $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1941     $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1942     $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1943     return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1944 }
1945
1946 /** 
1947  * Check for UTF-8 URLs; Internet Explorer produces these if you
1948  * type non-ASCII chars in the URL bar or follow unescaped links.
1949  * Requires urldecoded pagename.
1950  * Fixes sf.net bug #953949
1951  *
1952  * src: languages/Language.php:checkTitleEncoding() from mediawiki
1953  */
1954 function fixTitleEncoding( $s ) {
1955     global $charset;
1956
1957     $s = trim($s);
1958     // print a warning?
1959     if (empty($s)) return $s;
1960
1961     $ishigh = preg_match( '/[\x80-\xff]/', $s);
1962     /*
1963     $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1964                                     '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1965     */
1966     $isutf = ($ishigh ? isUtf8String($s) : true);
1967     $locharset = strtolower($charset);
1968
1969     if( $locharset != "utf-8" and $ishigh and $isutf )
1970         $s = charset_convert('UTF-8', $locharset, $s);
1971     if ($locharset == "utf-8" and $ishigh and !$isutf )
1972         return utf8_encode( $s );
1973
1974     // Other languages can safely leave this function, or replace
1975     // it with one to detect and convert another legacy encoding.
1976     return $s;
1977 }
1978
1979 /** 
1980  * MySQL fulltext index doesn't grok utf-8, so we
1981  * need to fold cases and convert to hex.
1982  * src: languages/Language.php:stripForSearch() from mediawiki
1983  */
1984 /*
1985 function stripForSearch( $string ) {
1986     global $wikiLowerChars; 
1987     // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
1988     return preg_replace(
1989                         "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
1990                         "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
1991                         $string );
1992 }
1993 */
1994
1995 /** 
1996  * Workaround for allow_url_fopen, to get the content of an external URI.
1997  * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
1998  * and use fopen, fread chunkwise. (see lib/XmlParser.php)
1999  */
2000 function url_get_contents( $uri ) {
2001     if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2002         return @file_get_contents($uri);
2003     } else {
2004         require_once("lib/HttpClient.php");
2005         $bits = parse_url($uri);
2006         $host = $bits['host'];
2007         $port = isset($bits['port']) ? $bits['port'] : 80;
2008         $path = isset($bits['path']) ? $bits['path'] : '/';
2009         if (isset($bits['query'])) {
2010             $path .= '?'.$bits['query'];
2011         }
2012         $client = new HttpClient($host, $port);
2013         $client->use_gzip = false;
2014         if (!$client->get($path)) {
2015             return false;
2016         } else {
2017             return $client->getContent();
2018         }
2019     }
2020 }
2021
2022 /**
2023  * Generate consecutively named strings:
2024  *   Name, Name2, Name3, ...
2025  */
2026 function GenerateId($name) {
2027     static $ids = array();
2028     if (empty($ids[$name])) {
2029         $ids[$name] = 1;
2030         return $name;
2031     } else {
2032         $ids[$name]++;
2033         return $name . $ids[$name];
2034     }
2035 }
2036
2037 // from IncludePage. To be of general use.
2038 // content: string or array of strings
2039 function firstNWordsOfContent( $n, $content ) {
2040     if ($content and $n > 0) {
2041         if (is_array($content)) {
2042             // fixme: return a list of lines then?
2043             //$content = join("\n", $content);
2044             //$return_array = true;
2045             $wordcount = 0;
2046             foreach ($content as $line) {
2047                 $words = explode(' ', $line);
2048                 if ($wordcount + count($words) > $n) {
2049                     $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2050                            . sprintf(_("... (first %s words)"), $n);
2051                     return $new;
2052                 } else {
2053                     $wordcount += count($words);
2054                     $new[] = $line;
2055                 }
2056             }
2057             return $new;
2058         } else {
2059             // fixme: use better whitespace/word seperators
2060             $words = explode(' ', $content);
2061             if (count($words) > $n) {
2062                 return join(' ', array_slice($words, 0, $n))
2063                        . sprintf(_("... (first %s words)"), $n);
2064             } else {
2065                 return $content;
2066             }
2067         }
2068     } else {
2069         return '';
2070     }
2071 }
2072
2073 // moved from lib/plugin/IncludePage.php
2074 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2075     $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2076
2077     if (preg_match("/ ^(!{1,})\\s*$qsection" // section header
2078                    . "  \\s*$\\n?"           // possible blank lines
2079                    . "  ( (?: ^.*\\n? )*? )" // some lines
2080                    . "  (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2081                    implode("\n", $content),
2082                    $match)) {
2083         // Strip trailing blanks lines and ---- <hr>s
2084         $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2085         if ($sectionhead)
2086             $text = $match[1] . $section ."\n". $text;
2087         return explode("\n", $text);
2088     }
2089     if ($quiet)
2090         $mesg = $page ." ". $section;
2091     else
2092         $mesg = $section;
2093     return array(sprintf(_("<%s: no such section>"), $mesg));
2094 }
2095
2096 // use this faster version: only load ExternalReferrer if we came from an external referrer
2097 function isExternalReferrer(&$request) {
2098     if ($referrer = $request->get('HTTP_REFERER')) {
2099         $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2100         if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2101         require_once("lib/ExternalReferrer.php");
2102         $se = new SearchEngines();
2103         return $se->parseSearchQuery($referrer);
2104     }
2105     //if (DEBUG) return array('query' => 'wiki');
2106     return false;
2107 }
2108
2109 /**
2110  * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2111  */
2112 function loadPhpExtension($extension) {
2113     if (!extension_loaded($extension)) {
2114         $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2115         $soname = ($isWindows ? 'php_' : '') 
2116                 . $extension 
2117                 . ($isWindows ? '.dll' : '.so');
2118         if (!@dl($soname))
2119             return false;
2120     }
2121     return extension_loaded($extension);
2122 }
2123
2124 function charset_convert($from, $to, $data) {
2125     //global $CHARSET;
2126     //$wikicharset = strtolower($CHARSET);
2127     //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2128     if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2129         return utf8_decode($data);
2130     if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2131         return utf8_encode($data);
2132
2133     if (loadPhpExtension("iconv")) {
2134         $tmpdata = iconv($from, $to, $data);
2135         if (!$tmpdata)
2136             trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2137         else
2138             $data = $tmpdata;
2139     } else {
2140         trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2141     }
2142     return $data;
2143 }
2144
2145 function string_starts_with($string, $prefix) {
2146     return (substr($string, 0, strlen($prefix)) == $prefix);
2147 }
2148 function string_ends_with($string, $suffix) {
2149     return (substr($string, -strlen($suffix)) == $suffix);
2150 }
2151 function array_remove($arr,$value) {
2152    return array_values(array_diff($arr,array($value)));
2153 }
2154
2155 /** 
2156  * Ensure that the script will have another $secs time left. 
2157  * Works only if safe_mode is off.
2158  * For example not to timeout on waiting socket connections.
2159  *   Use the socket timeout as arg.
2160  */
2161 function longer_timeout($secs = 30) {
2162     $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2163     $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2164     if ($timeleft < $secs)
2165         @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2166 }
2167
2168 function printSimpleTrace($bt) {
2169     //print_r($bt);
2170     echo "\nTraceback:\n";
2171     if (function_exists('debug_print_backtrace')) { // >= 5
2172         debug_print_backtrace();
2173     } else {
2174         foreach ($bt as $i => $elem) {
2175             if (!array_key_exists('file', $elem)) {
2176                 continue;
2177             }
2178             //echo join(" ",array_values($elem)),"\n";
2179             echo "  ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2180         }
2181     }
2182 }
2183
2184 /**
2185  * Return the used process memory, in bytes.
2186  * Enable the section which will work for you. They are very slow.
2187  * Special quirks for Windows: Requires cygwin.
2188  */
2189 function getMemoryUsage() {
2190     //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2191     if (function_exists('memory_get_usage') and memory_get_usage()) {
2192         return memory_get_usage();
2193     } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2194         $mem = $u['ru_maxrss'];
2195     } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2196         // what we want is the process memory only: apache or php (if CGI)
2197         $pid = getmypid();
2198         $memstr = '';
2199         // win32_ps_stat_proc, win32_ps_stat_mem
2200         if (function_exists('win32_ps_list_procs')) {
2201             $info = win32_ps_stat_proc($pid);
2202             $memstr = $info['mem']['working_set_size'];
2203         } elseif(0) {
2204             // This works only if it's a cygwin process (apache or php).
2205             // Requires a newer cygwin
2206             $memstr = exec("cat /proc/$pid/statm |cut -f1");
2207
2208             // if it's native windows use something like this: 
2209             //   (requires pslist from sysinternals.com, grep, sed and perl)
2210             //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2211         }
2212         return (integer) trim($memstr);
2213     } elseif (1) {
2214         $pid = getmypid();
2215         //%MEM: Percentage of total memory in use by this process
2216         //VSZ: Total virtual memory size, in 1K blocks.
2217         //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2218         //CPU time used by process since it started.
2219         //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2220         $memstr = exec("ps -orss -p $pid|sed 1d");
2221         return (integer) trim($memstr);
2222     }
2223 }
2224
2225 /**
2226  * @param var $needle
2227  * @param array $haystack one-dimensional numeric array only, no hash
2228  * @return integer
2229  * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2230              It will return false if not found or the index where it was found.
2231   From dennis.decoene@moveit.be http://www.php.net/array_search
2232 */
2233 function binary_search($needle, $haystack) {
2234     $high = count($haystack);
2235     $low = 0;
2236    
2237     while (($high - $low) > 1) {
2238         $probe = floor(($high + $low) / 2);
2239         if ($haystack[$probe] < $needle) {
2240             $low = $probe;
2241         } elseif ($haystack[$probe] == $needle) {
2242             $high = $low = $probe;
2243         } else {
2244             $high = $probe;
2245         }
2246     }
2247
2248     if ($high == count($haystack) || $haystack[$high] != $needle) {
2249         return false;
2250     } else {
2251         return $high;
2252     }
2253 }
2254
2255 function is_localhost($url = false) {
2256     if (!$url) {
2257         global $HTTP_SERVER_VARS;
2258         return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2259     }
2260 }
2261
2262 /**
2263  * Take a string and quote it sufficiently to be passed as a Javascript
2264  * string between ''s
2265  */
2266 function javascript_quote_string($s) {
2267     return str_replace("'", "\'", $s);
2268 }
2269
2270 function isSerialized($s) {
2271     return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2272 }
2273
2274 // $Log: not supported by cvs2svn $
2275 // Revision 1.274  2008/05/06 19:29:06  rurban
2276 // support Upload:image_with_foreign_chars: do urldecode links to such files
2277 //
2278 // Revision 1.273  2008/03/22 21:43:21  rurban
2279 // Fix syntax error from r1.272
2280 //
2281 // Revision 1.272  2008/03/21 20:35:52  rurban
2282 // Improve upon embedded ImgObject, such as [ *.mp3 ], objects.
2283 // Object tags now render as label correctly and param tags are also added.
2284 //
2285 // Revision 1.271  2008/03/17 19:11:06  rurban
2286 // adedd isSerialized: get rid of @ error protection in unserialize
2287 // revert &amp; links
2288 // protect  $WikiTheme->VALID_LINKS
2289 // replace strtr by preg_replace; document problem (still exists?
2290 //   Todo: glob pattern test)
2291 //
2292 // Revision 1.270  2008/01/31 20:21:12  vargenau
2293 // Valid HTML: escape ampersand
2294 //
2295 // Revision 1.269  2008/01/24 19:17:03  rurban
2296 // add javascript_quote_string for Theme
2297 //
2298 // Revision 1.268  2007/09/15 12:28:46  rurban
2299 // Improve multi-page format handling: abstract _DumpHtmlToDir. get rid of non-external pdf, non-global VALID_LINKS
2300 //
2301 // Revision 1.267  2007/09/12 19:32:29  rurban
2302 // link only VALID_LINKS with pagelist HTML_DUMP
2303 //
2304 // Revision 1.266  2007/09/01 13:24:23  rurban
2305 // add INSECURE_ACTIONS_LOCALHOST_ONLY. advanced security settings
2306 //
2307 // Revision 1.265  2007/08/08 18:47:14  rurban
2308 // * Fix EmailNotify for Subpages: Unknown modifier ? at any page save.
2309 //   Quoting error on glob_match.
2310 // * Fix binary_search
2311 //
2312 // Revision 1.264  2007/07/15 17:39:42  rurban
2313 // add binary_search. enable memory ps calls
2314 //
2315 // Revision 1.263  2007/07/14 12:05:29  rurban
2316 // add url field to WikiPageName for interwiki expansion
2317 //
2318 // Revision 1.262  2007/06/07 17:02:01  rurban
2319 // fix display of pagenames containing ":" in certain lists
2320 //
2321 // Revision 1.261  2007/06/01 06:37:53  rurban
2322 // use native debug_print_backtrace
2323 //
2324 // Revision 1.260  2007/02/17 14:15:21  rurban
2325 // fix ImgLink params: $ori_url
2326 //
2327 // Revision 1.259  2007/01/20 11:41:38  rurban
2328 // WikiPagename::_check: add flatfile support
2329 //
2330 // Revision 1.258  2007/01/07 18:43:51  rurban
2331 // Remove FileFinder dependency for loadPhpExtension()
2332 //
2333 // Revision 1.257  2007/01/03 21:24:56  rurban
2334 // Disable noisy ps subprocess on DEBUG. Turn it on explicitly on memory debugging. Add convert_charset helper. Use convert_charset().
2335 //
2336 // Revision 1.256  2007/01/02 13:23:49  rurban
2337 // ftnt_${footnum}: do not confuse old php string definition parsers. Clarify API: sortby,limit and exclude are strings.
2338 //
2339 // Revision 1.255  2006/12/22 16:53:38  rurban
2340 // Try to dl() load the iconv extension, if not already loaded
2341 //
2342 // Revision 1.254  2006/12/02 19:53:05  rurban
2343 // Simplify DISABLE_MARKUP_WIKIWORD handling by adding the new function
2344 // stdlib: array_remove(). Hopefully PHP will not add this natively sooner
2345 // or later.
2346 //
2347 // Revision 1.253  2006/08/25 22:20:52  rurban
2348 // better split subpages at sep
2349 //
2350 // Revision 1.252  2006/06/18 11:03:36  rurban
2351 // support rc version
2352 //
2353 // Revision 1.251  2006/03/19 15:01:00  rurban
2354 // sf.net patch #1333957 by Matt Brown: Authentication cookie identical across all wikis on a host
2355 //
2356 // Revision 1.250  2006/03/07 20:45:44  rurban
2357 // wikihash for php-5.1
2358 //
2359 // Revision 1.249  2005/10/30 14:24:33  rurban
2360 // move rand_ascii_readable from Captcha to stdlib
2361 //
2362 // Revision 1.248  2005/10/29 14:18:30  uckelman
2363 // Added is_a() deprecation note.
2364 //
2365 // Revision 1.247  2005/10/10 20:31:21  rurban
2366 // fix win32ps call
2367 //
2368 // Revision 1.246  2005/10/10 19:38:48  rurban
2369 // add win32ps
2370 //
2371 // Revision 1.245  2005/09/18 16:01:09  rurban
2372 // trick to send the correct gzipped Content-Length
2373 //
2374 // Revision 1.244  2005/09/11 13:24:33  rurban
2375 // fix shortname, dont quote twice in ListRegexExpand
2376 //
2377 // Revision 1.243  2005/08/06 15:01:38  rurban
2378 // workaround php VBASIC alike limitation: allow integer pagenames
2379 //
2380 // Revision 1.242  2005/08/06 13:07:04  rurban
2381 // quote paths correctly (not the best method though)
2382 //
2383 // Revision 1.241  2005/05/06 16:54:19  rurban
2384 // support optional EXTERNAL_LINK_TARGET, default: _blank
2385 //
2386 // Revision 1.240  2005/04/23 11:15:49  rurban
2387 // handle allowed inlined objects within INLINE_IMAGES
2388 //
2389 // Revision 1.239  2005/04/01 16:11:42  rurban
2390 // just whitespace
2391 //
2392 // Revision 1.238  2005/03/04 16:29:14  rurban
2393 // Fixed bug #994994 (escape / in glob)
2394 // Optimized glob_to_pcre within fileSet() matching.
2395 //
2396 // Revision 1.237  2005/02/12 17:22:18  rurban
2397 // locale update: missing . : fixed. unified strings
2398 // proper linebreaks
2399 //
2400 // Revision 1.236  2005/02/08 13:41:32  rurban
2401 // add rand_ascii
2402 //
2403 // Revision 1.235  2005/02/04 11:54:48  rurban
2404 // fix Talk: names
2405 //
2406 // Revision 1.234  2005/02/03 05:09:25  rurban
2407 // Talk: + User: fix
2408 //
2409 // Revision 1.233  2005/02/02 20:40:12  rurban
2410 // fix Talk: and User: names and links
2411 //
2412 // Revision 1.232  2005/02/02 19:34:09  rurban
2413 // more maps: Talk, User
2414 //
2415 // Revision 1.231  2005/01/30 19:48:52  rurban
2416 // enable ps memory on unix
2417 //
2418 // Revision 1.230  2005/01/25 07:10:51  rurban
2419 // add getMemoryUsage to stdlib
2420 //
2421 // Revision 1.229  2005/01/21 11:51:22  rurban
2422 // changed (c)
2423 //
2424 // Revision 1.228  2005/01/17 20:28:30  rurban
2425 // Allow more pagename chars: Limit only on certain backends.
2426 // Re-Allow : and ; and control chars on non-file backends.
2427 //
2428 // Revision 1.227  2005/01/14 18:32:08  uckelman
2429 // ConvertOldMarkup did not properly handle links containing pairs of pairs
2430 // of underscores. (E.g., [http://example.com/foo__bar__.html] would be
2431 // munged by the regex for bold text.) Now '__' in links are hidden prior to
2432 // conversion of '__' into '<strong>', and then unhidden afterwards.
2433 //
2434 // Revision 1.226  2004/12/26 17:12:06  rurban
2435 // avoid stdargs in url, php5 fixes
2436 //
2437 // Revision 1.225  2004/12/22 19:02:29  rurban
2438 // fix glob for starting * or ?
2439 //
2440 // Revision 1.224  2004/12/20 12:11:50  rurban
2441 // fix "lib/stdlib.php:1348: Warning[2]: Compilation failed: unmatched parentheses at offset 2"
2442 //   not reproducable other than on sf.net, but this seems to fix it.
2443 //
2444 // Revision 1.223  2004/12/18 16:49:29  rurban
2445 // fix RPC for !USE_PATH_INFO, add debugging helper
2446 //
2447 // Revision 1.222  2004/12/17 16:40:45  rurban
2448 // add not yet used url helper
2449 //
2450 // Revision 1.221  2004/12/06 19:49:58  rurban
2451 // enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
2452 // renamed delete_page to purge_page.
2453 // enable action=edit&version=-1 to force creation of a new version.
2454 // added BABYCART_PATH config
2455 // fixed magiqc in adodb.inc.php
2456 // and some more docs
2457 //
2458 // Revision 1.220  2004/11/30 17:47:41  rurban
2459 // added mt_srand, check for native isa
2460 //
2461 // Revision 1.219  2004/11/26 18:39:02  rurban
2462 // new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
2463 //
2464 // Revision 1.218  2004/11/25 08:28:48  rurban
2465 // support exclude
2466 //
2467 // Revision 1.217  2004/11/16 17:31:03  rurban
2468 // re-enable old block markup conversion
2469 //
2470 // Revision 1.216  2004/11/11 18:31:26  rurban
2471 // add simple backtrace on such general failures to get at least an idea where
2472 //
2473 // Revision 1.215  2004/11/11 14:34:12  rurban
2474 // minor clarifications
2475 //
2476 // Revision 1.214  2004/11/11 11:01:20  rurban
2477 // fix loadPhpExtension
2478 //
2479 // Revision 1.213  2004/11/01 10:43:57  rurban
2480 // seperate PassUser methods into seperate dir (memory usage)
2481 // fix WikiUser (old) overlarge data session
2482 // remove wikidb arg from various page class methods, use global ->_dbi instead
2483 // ...
2484 //
2485 // Revision 1.212  2004/10/22 09:15:39  rurban
2486 // Alert::show has no arg anymore
2487 //
2488 // Revision 1.211  2004/10/22 09:05:11  rurban
2489 // added longer_timeout (HttpClient)
2490 // fixed warning
2491 //
2492 // Revision 1.210  2004/10/14 21:06:02  rurban
2493 // fix dumphtml with USE_PATH_INFO (again). fix some PageList refs
2494 //
2495 // Revision 1.209  2004/10/14 19:19:34  rurban
2496 // loadsave: check if the dumped file will be accessible from outside.
2497 // and some other minor fixes. (cvsclient native not yet ready)
2498 //
2499 // Revision 1.208  2004/10/12 13:13:20  rurban
2500 // php5 compatibility (5.0.1 ok)
2501 //
2502 // Revision 1.207  2004/09/26 12:21:40  rurban
2503 // removed old log entries.
2504 // added persistent start_debug on internal links and DEBUG
2505 // added isExternalReferrer (not yet used)
2506 //
2507 // Revision 1.206  2004/09/25 16:28:36  rurban
2508 // added to TOC, firstNWordsOfContent is now plugin compatible, added extractSection
2509 //
2510 // Revision 1.205  2004/09/23 13:59:35  rurban
2511 // Before removing a page display a sample of 100 words.
2512 //
2513 // Revision 1.204  2004/09/17 13:19:15  rurban
2514 // fix LinkPhpwikiURL bug reported in http://phpwiki.sourceforge.net/phpwiki/KnownBugs
2515 // by SteveBennett.
2516 //
2517 // Revision 1.203  2004/09/16 08:00:52  rurban
2518 // just some comments
2519 //
2520 // Revision 1.202  2004/09/14 10:11:44  rurban
2521 // start 2nd Id with ...Plugin2
2522 //
2523 // Revision 1.201  2004/09/14 10:06:42  rurban
2524 // generate iterated plugin ids, set plugin span id also
2525 //
2526 // Revision 1.200  2004/08/05 17:34:26  rurban
2527 // move require to sortby branch
2528 //
2529 // Revision 1.199  2004/08/05 10:38:15  rurban
2530 // fix Bug #993692:  Making Snapshots or Backups doesn't work anymore
2531 // in CVS version.
2532 //
2533 // Revision 1.198  2004/07/02 10:30:36  rurban
2534 // always disable getimagesize for < php-4.3 with external png's
2535 //
2536 // Revision 1.197  2004/07/02 09:55:58  rurban
2537 // more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
2538 //
2539 // Revision 1.196  2004/07/01 08:51:22  rurban
2540 // dumphtml: added exclude, print pagename before processing
2541 //
2542 // Revision 1.195  2004/06/29 08:52:22  rurban
2543 // Use ...version() $need_content argument in WikiDB also:
2544 // To reduce the memory footprint for larger sets of pagelists,
2545 // we don't cache the content (only true or false) and
2546 // we purge the pagedata (_cached_html) also.
2547 // _cached_html is only cached for the current pagename.
2548 // => Vastly improved page existance check, ACL check, ...
2549 //
2550 // Now only PagedList info=content or size needs the whole content, esp. if sortable.
2551 //
2552 // Revision 1.194  2004/06/29 06:48:04  rurban
2553 // Improve LDAP auth and GROUP_LDAP membership:
2554 //   no error message on false password,
2555 //   added two new config vars: LDAP_OU_USERS and LDAP_OU_GROUP with GROUP_METHOD=LDAP
2556 //   fixed two group queries (this -> user)
2557 // stdlib: ConvertOldMarkup still flawed
2558 //
2559 // Revision 1.193  2004/06/28 13:27:03  rurban
2560 // CreateToc disabled for old markup and Apache2 only
2561 //
2562 // Revision 1.192  2004/06/28 12:47:43  rurban
2563 // skip if non-DEBUG and old markup with CreateToc
2564 //
2565 // Revision 1.191  2004/06/25 14:31:56  rurban
2566 // avoid debug_skip warning
2567 //
2568 // Revision 1.190  2004/06/25 14:29:20  rurban
2569 // WikiGroup refactoring:
2570 //   global group attached to user, code for not_current user.
2571 //   improved helpers for special groups (avoid double invocations)
2572 // new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
2573 // fixed a XHTML validation error on userprefs.tmpl
2574 //
2575 // Revision 1.189  2004/06/20 09:45:35  rurban
2576 // php5 isa fix (wrong strtolower)
2577 //
2578 // Revision 1.188  2004/06/16 10:38:58  rurban
2579 // Disallow refernces in calls if the declaration is a reference
2580 // ("allow_call_time_pass_reference clean").
2581 //   PhpWiki is now allow_call_time_pass_reference = Off clean,
2582 //   but several external libraries may not.
2583 //   In detail these libs look to be affected (not tested):
2584 //   * Pear_DB odbc
2585 //   * adodb oracle
2586 //
2587 // Revision 1.187  2004/06/14 11:31:37  rurban
2588 // renamed global $Theme to $WikiTheme (gforge nameclash)
2589 // inherit PageList default options from PageList
2590 //   default sortby=pagename
2591 // use options in PageList_Selectable (limit, sortby, ...)
2592 // added action revert, with button at action=diff
2593 // added option regex to WikiAdminSearchReplace
2594 //
2595 // Revision 1.186  2004/06/13 13:54:25  rurban
2596 // Catch fatals on the four dump calls (as file and zip, as html and mimified)
2597 // FoafViewer: Check against external requirements, instead of fatal.
2598 // Change output for xhtmldumps: using file:// urls to the local fs.
2599 // Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
2600 // Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
2601 //
2602 // Revision 1.185  2004/06/11 09:07:30  rurban
2603 // support theme-specific LinkIconAttr: front or after or none
2604 //
2605 // Revision 1.184  2004/06/04 20:32:53  rurban
2606 // Several locale related improvements suggested by Pierrick Meignen
2607 // LDAP fix by John Cole
2608 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
2609 //
2610 // Revision 1.183  2004/06/01 10:22:56  rurban
2611 // added url_get_contents() used in XmlParser and elsewhere
2612 //
2613 // Revision 1.182  2004/05/25 12:40:48  rurban
2614 // trim the pagename
2615 //
2616 // Revision 1.181  2004/05/25 10:18:44  rurban
2617 // Check for UTF-8 URLs; Internet Explorer produces these if you
2618 // type non-ASCII chars in the URL bar or follow unescaped links.
2619 // Fixes sf.net bug #953949
2620 // src: languages/Language.php:checkTitleEncoding() from mediawiki
2621 //
2622 // Revision 1.180  2004/05/18 16:23:39  rurban
2623 // rename split_pagename to SplitPagename
2624 //
2625 // Revision 1.179  2004/05/18 16:18:37  rurban
2626 // AutoSplit at subpage seperators
2627 // RssFeed stability fix for empty feeds or broken connections
2628 //
2629 // Revision 1.178  2004/05/12 10:49:55  rurban
2630 // require_once fix for those libs which are loaded before FileFinder and
2631 //   its automatic include_path fix, and where require_once doesn't grok
2632 //   dirname(__FILE__) != './lib'
2633 // upgrade fix with PearDB
2634 // navbar.tmpl: remove spaces for IE &nbsp; button alignment
2635 //
2636 // Revision 1.177  2004/05/08 14:06:12  rurban
2637 // new support for inlined image attributes: [image.jpg size=50x30 align=right]
2638 // minor stability and portability fixes
2639 //
2640 // Revision 1.176  2004/05/08 11:25:15  rurban
2641 // php-4.0.4 fixes
2642 //
2643 // Revision 1.175  2004/05/06 17:30:38  rurban
2644 // CategoryGroup: oops, dos2unix eol
2645 // improved phpwiki_version:
2646 //   pre -= .0001 (1.3.10pre: 1030.099)
2647 //   -p1 += .001 (1.3.9-p1: 1030.091)
2648 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
2649 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
2650 //   backend->backendType(), backend->database(),
2651 //   backend->listOfFields(),
2652 //   backend->listOfTables(),
2653 //
2654 // Revision 1.174  2004/05/06 12:02:05  rurban
2655 // fix sf.net bug#949002: [ Link | ] assertion
2656 //
2657 // Revision 1.173  2004/05/03 15:00:31  rurban
2658 // added more database upgrading: session.sess_ip, page.id autp_increment
2659 //
2660 // Revision 1.172  2004/04/26 20:44:34  rurban
2661 // locking table specific for better databases
2662 //
2663 // Revision 1.171  2004/04/19 23:13:03  zorloc
2664 // Connect the rest of PhpWiki to the IniConfig system.  Also the keyword regular expression is not a config setting
2665 //
2666 // Revision 1.170  2004/04/19 18:27:45  rurban
2667 // Prevent from some PHP5 warnings (ref args, no :: object init)
2668 //   php5 runs now through, just one wrong XmlElement object init missing
2669 // Removed unneccesary UpgradeUser lines
2670 // Changed WikiLink to omit version if current (RecentChanges)
2671 //
2672 // Revision 1.169  2004/04/15 21:29:48  rurban
2673 // allow [0] with new markup: link to page "0"
2674 //
2675 // Revision 1.168  2004/04/10 02:30:49  rurban
2676 // Fixed gettext problem with VIRTUAL_PATH scripts (Windows only probably)
2677 // Fixed "cannot setlocale..." (sf.net problem)
2678 //
2679 // Revision 1.167  2004/04/02 15:06:55  rurban
2680 // fixed a nasty ADODB_mysql session update bug
2681 // improved UserPreferences layout (tabled hints)
2682 // fixed UserPreferences auth handling
2683 // improved auth stability
2684 // improved old cookie handling: fixed deletion of old cookies with paths
2685 //
2686 // Revision 1.166  2004/04/01 15:57:10  rurban
2687 // simplified Sidebar theme: table, not absolute css positioning
2688 // added the new box methods.
2689 // remaining problems: large left margin, how to override _autosplitWikiWords in Template only
2690 //
2691 // Revision 1.165  2004/03/24 19:39:03  rurban
2692 // php5 workaround code (plus some interim debugging code in XmlElement)
2693 //   php5 doesn't work yet with the current XmlElement class constructors,
2694 //   WikiUserNew does work better than php4.
2695 // rewrote WikiUserNew user upgrading to ease php5 update
2696 // fixed pref handling in WikiUserNew
2697 // added Email Notification
2698 // added simple Email verification
2699 // removed emailVerify userpref subclass: just a email property
2700 // changed pref binary storage layout: numarray => hash of non default values
2701 // print optimize message only if really done.
2702 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
2703 //   prefs should be stored in db or homepage, besides the current session.
2704 //
2705 // Revision 1.164  2004/03/18 21:41:09  rurban
2706 // fixed sqlite support
2707 // WikiUserNew: PHP5 fixes: don't assign $this (untested)
2708 //
2709 // Revision 1.163  2004/03/17 18:41:49  rurban
2710 // just reformatting
2711 //
2712 // Revision 1.162  2004/03/16 15:43:08  rurban
2713 // make fileSet sortable to please PageList
2714 //
2715 // Revision 1.161  2004/03/12 15:48:07  rurban
2716 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
2717 // simplified lib/stdlib.php:explodePageList
2718 //
2719 // Revision 1.160  2004/02/28 21:14:08  rurban
2720 // generally more PHPDOC docs
2721 //   see http://xarch.tu-graz.ac.at/home/rurban/phpwiki/xref/
2722 // fxied WikiUserNew pref handling: empty theme not stored, save only
2723 //   changed prefs, sql prefs improved, fixed password update,
2724 //   removed REPLACE sql (dangerous)
2725 // moved gettext init after the locale was guessed
2726 // + some minor changes
2727 //
2728
2729 // (c-file-style: "gnu")
2730 // Local Variables:
2731 // mode: php
2732 // tab-width: 8
2733 // c-basic-offset: 4
2734 // c-hanging-comment-ender-p: nil
2735 // indent-tabs-mode: nil
2736 // End:   
2737 ?>