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