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