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