]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/stdlib.php
Test if empty after trim
[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 numerals from following letters.
1211         $RE[] = '/(\d)([[:alpha:]])/';
1212         // Split at subpage seperators. TBD in WikiTheme.php
1213         $RE[] = "/([^${sep}]+)(${sep})/";
1214         $RE[] = "/(${sep})([^${sep}]+)/";
1215         
1216         foreach ($RE as $key)
1217             $RE[$key] = pcre_fix_posix_classes($key);
1218     }
1219
1220     foreach ($RE as $regexp) {
1221         $page = preg_replace($regexp, '\\1 \\2', $page);
1222     }
1223     return $page;
1224 }
1225
1226 function NoSuchRevision (&$request, $page, $version) {
1227     $html = HTML(HTML::h2(_("Revision Not Found")),
1228                  HTML::p(fmt("I'm sorry.  Version %d of %s is not in the database.",
1229                              $version, WikiLink($page, 'auto'))));
1230     include_once('lib/Template.php');
1231     GeneratePage($html, _("Bad Version"), $page->getCurrentRevision());
1232     $request->finish();
1233 }
1234
1235
1236 /**
1237  * Get time offset for local time zone.
1238  *
1239  * @param $time time_t Get offset for this time. Default: now.
1240  * @param $no_colon boolean Don't put colon between hours and minutes.
1241  * @return string Offset as a string in the format +HH:MM.
1242  */
1243 function TimezoneOffset ($time = false, $no_colon = false) {
1244     if ($time === false)
1245         $time = time();
1246     $secs = date('Z', $time);
1247
1248     if ($secs < 0) {
1249         $sign = '-';
1250         $secs = -$secs;
1251     }
1252     else {
1253         $sign = '+';
1254     }
1255     $colon = $no_colon ? '' : ':';
1256     $mins = intval(($secs + 30) / 60);
1257     return sprintf("%s%02d%s%02d",
1258                    $sign, $mins / 60, $colon, $mins % 60);
1259 }
1260
1261
1262 /**
1263  * Format time in ISO-8601 format.
1264  *
1265  * @param $time time_t Time.  Default: now.
1266  * @return string Date and time in ISO-8601 format.
1267  */
1268 function Iso8601DateTime ($time = false) {
1269     if ($time === false)
1270         $time = time();
1271     $tzoff = TimezoneOffset($time);
1272     $date  = date('Y-m-d', $time);
1273     $time  = date('H:i:s', $time);
1274     return $date . 'T' . $time . $tzoff;
1275 }
1276
1277 /**
1278  * Format time in RFC-2822 format.
1279  *
1280  * @param $time time_t Time.  Default: now.
1281  * @return string Date and time in RFC-2822 format.
1282  */
1283 function Rfc2822DateTime ($time = false) {
1284     if ($time === false)
1285         $time = time();
1286     return date('D, j M Y H:i:s ', $time) . TimezoneOffset($time, 'no colon');
1287 }
1288
1289 /**
1290  * Format time in RFC-1123 format.
1291  *
1292  * @param $time time_t Time.  Default: now.
1293  * @return string Date and time in RFC-1123 format.
1294  */
1295 function Rfc1123DateTime ($time = false) {
1296     if ($time === false)
1297         $time = time();
1298     return gmdate('D, d M Y H:i:s \G\M\T', $time);
1299 }
1300
1301 /** Parse date in RFC-1123 format.
1302  *
1303  * According to RFC 1123 we must accept dates in the following
1304  * formats:
1305  *
1306  *   Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
1307  *   Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
1308  *   Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format
1309  *
1310  * (Though we're only allowed to generate dates in the first format.)
1311  */
1312 function ParseRfc1123DateTime ($timestr) {
1313     $timestr = trim($timestr);
1314     if (preg_match('/^ \w{3},\s* (\d{1,2}) \s* (\w{3}) \s* (\d{4}) \s*'
1315                    .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1316                    $timestr, $m)) {
1317         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1318     }
1319     elseif (preg_match('/^ \w+,\s* (\d{1,2})-(\w{3})-(\d{2}|\d{4}) \s*'
1320                        .'(\d\d):(\d\d):(\d\d) \s* GMT $/ix',
1321                        $timestr, $m)) {
1322         list(, $mday, $mon, $year, $hh, $mm, $ss) = $m;
1323         if ($year < 70) $year += 2000;
1324         elseif ($year < 100) $year += 1900;
1325     }
1326     elseif (preg_match('/^\w+\s* (\w{3}) \s* (\d{1,2}) \s*'
1327                        .'(\d\d):(\d\d):(\d\d) \s* (\d{4})$/ix',
1328                        $timestr, $m)) {
1329         list(, $mon, $mday, $hh, $mm, $ss, $year) = $m;
1330     }
1331     else {
1332         // Parse failed.
1333         return false;
1334     }
1335
1336     $time = strtotime("$mday $mon $year ${hh}:${mm}:${ss} GMT");
1337     if ($time == -1)
1338         return false;           // failed
1339     return $time;
1340 }
1341
1342 /**
1343  * Format time to standard 'ctime' format.
1344  *
1345  * @param $time time_t Time.  Default: now.
1346  * @return string Date and time.
1347  */
1348 function CTime ($time = false)
1349 {
1350     if ($time === false)
1351         $time = time();
1352     return date("D M j H:i:s Y", $time);
1353 }
1354
1355
1356 /**
1357  * Format number as kilobytes or bytes.
1358  * Short format is used for PageList
1359  * Long format is used in PageInfo
1360  *
1361  * @param $bytes       int.  Default: 0.
1362  * @param $longformat  bool. Default: false.
1363  * @return class FormattedText (XmlElement.php).
1364  */
1365 function ByteFormatter ($bytes = 0, $longformat = false) {
1366     if ($bytes < 0)
1367         return fmt("-???");
1368     if ($bytes < 1024) {
1369         if (! $longformat)
1370             $size = fmt("%s b", $bytes);
1371         else
1372             $size = fmt("%s bytes", $bytes);
1373     }
1374     else {
1375         $kb = round($bytes / 1024, 1);
1376         if (! $longformat)
1377             $size = fmt("%s k", $kb);
1378         else
1379             $size = fmt("%s Kb (%s bytes)", $kb, $bytes);
1380     }
1381     return $size;
1382 }
1383
1384 /**
1385  * Internationalized printf.
1386  *
1387  * This is essentially the same as PHP's built-in printf
1388  * with the following exceptions:
1389  * <ol>
1390  * <li> It passes the format string through gettext().
1391  * <li> It supports the argument reordering extensions.
1392  * </ol>
1393  *
1394  * Example:
1395  *
1396  * In php code, use:
1397  * <pre>
1398  *    __printf("Differences between versions %s and %s of %s",
1399  *             $new_link, $old_link, $page_link);
1400  * </pre>
1401  *
1402  * Then in locale/po/de.po, one can reorder the printf arguments:
1403  *
1404  * <pre>
1405  *    msgid "Differences between %s and %s of %s."
1406  *    msgstr "Der Unterschiedsergebnis von %3$s, zwischen %1$s und %2$s."
1407  * </pre>
1408  *
1409  * (Note that while PHP tries to expand $vars within double-quotes,
1410  * the values in msgstr undergo no such expansion, so the '$'s
1411  * okay...)
1412  *
1413  * One shouldn't use reordered arguments in the default format string.
1414  * Backslashes in the default string would be necessary to escape the
1415  * '$'s, and they'll cause all kinds of trouble....
1416  */ 
1417 function __printf ($fmt) {
1418     $args = func_get_args();
1419     array_shift($args);
1420     echo __vsprintf($fmt, $args);
1421 }
1422
1423 /**
1424  * Internationalized sprintf.
1425  *
1426  * This is essentially the same as PHP's built-in printf with the
1427  * following exceptions:
1428  *
1429  * <ol>
1430  * <li> It passes the format string through gettext().
1431  * <li> It supports the argument reordering extensions.
1432  * </ol>
1433  *
1434  * @see __printf
1435  */ 
1436 function __sprintf ($fmt) {
1437     $args = func_get_args();
1438     array_shift($args);
1439     return __vsprintf($fmt, $args);
1440 }
1441
1442 /**
1443  * Internationalized vsprintf.
1444  *
1445  * This is essentially the same as PHP's built-in printf with the
1446  * following exceptions:
1447  *
1448  * <ol>
1449  * <li> It passes the format string through gettext().
1450  * <li> It supports the argument reordering extensions.
1451  * </ol>
1452  *
1453  * @see __printf
1454  */ 
1455 function __vsprintf ($fmt, $args) {
1456     $fmt = gettext($fmt);
1457     // PHP's sprintf doesn't support variable with specifiers,
1458     // like sprintf("%*s", 10, "x"); --- so we won't either.
1459     
1460     if (preg_match_all('/(?<!%)%(\d+)\$/x', $fmt, $m)) {
1461         // Format string has '%2$s' style argument reordering.
1462         // PHP doesn't support this.
1463         if (preg_match('/(?<!%)%[- ]?\d*[^- \d$]/x', $fmt))
1464             // literal variable name substitution only to keep locale
1465             // strings uncluttered
1466             trigger_error(sprintf(_("Can't mix '%s' with '%s' type format strings"),
1467                                   '%1\$s','%s'), E_USER_WARNING); //php+locale error
1468         
1469         $fmt = preg_replace('/(?<!%)%\d+\$/x', '%', $fmt);
1470         $newargs = array();
1471         
1472         // Reorder arguments appropriately.
1473         foreach($m[1] as $argnum) {
1474             if ($argnum < 1 || $argnum > count($args))
1475                 trigger_error(sprintf(_("%s: argument index out of range"), 
1476                                       $argnum), E_USER_WARNING);
1477             $newargs[] = $args[$argnum - 1];
1478         }
1479         $args = $newargs;
1480     }
1481     
1482     // Not all PHP's have vsprintf, so...
1483     array_unshift($args, $fmt);
1484     return call_user_func_array('sprintf', $args);
1485 }
1486
1487 function file_mtime ($filename) {
1488     if ($stat = @stat($filename))
1489         return $stat[9];
1490     else 
1491         return false;
1492 }
1493
1494 function sort_file_mtime ($a, $b) {
1495     $ma = file_mtime($a);
1496     $mb = file_mtime($b);
1497     if (!$ma or !$mb or $ma == $mb) return 0;
1498     return ($ma > $mb) ? -1 : 1;
1499 }
1500
1501 class fileSet {
1502     /**
1503      * Build an array in $this->_fileList of files from $dirname.
1504      * Subdirectories are not traversed.
1505      *
1506      * (This was a function LoadDir in lib/loadsave.php)
1507      * See also http://www.php.net/manual/en/function.readdir.php
1508      */
1509     function getFiles($exclude='', $sortby='', $limit='') {
1510         $list = $this->_fileList;
1511
1512         if ($sortby) {
1513             require_once('lib/PageList.php');
1514             switch (Pagelist::sortby($sortby, 'db')) {
1515             case 'pagename ASC': break;
1516             case 'pagename DESC': 
1517                 $list = array_reverse($list); 
1518                 break;
1519             case 'mtime ASC': 
1520                 usort($list,'sort_file_mtime'); 
1521                 break;
1522             case 'mtime DESC': 
1523                 usort($list,'sort_file_mtime');
1524                 $list = array_reverse($list); 
1525                 break;
1526             }
1527         }
1528         if ($limit)
1529             return array_splice($list, 0, $limit);
1530         return $list;
1531     }
1532
1533     function _filenameSelector($filename) {
1534         if (! $this->_pattern )
1535             return true;
1536         else {
1537             if (! $this->_pcre_pattern )
1538                 $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1539             return preg_match('/' . $this->_pcre_pattern . ($this->_case ? '/' : '/i'), 
1540                               $filename);
1541         }
1542     }
1543
1544     function fileSet($directory, $filepattern = false) {
1545         $this->_fileList = array();
1546         $this->_pattern = $filepattern;
1547         if ($filepattern) {
1548             $this->_pcre_pattern = glob_to_pcre($this->_pattern);
1549         }
1550         $this->_case = !isWindows();
1551         $this->_pathsep = '/';
1552
1553         if (empty($directory)) {
1554             trigger_error(sprintf(_("%s is empty."), 'directoryname'),
1555                           E_USER_NOTICE);
1556             return; // early return
1557         }
1558
1559         @ $dir_handle = opendir($dir=$directory);
1560         if (empty($dir_handle)) {
1561             trigger_error(sprintf(_("Unable to open directory '%s' for reading"),
1562                                   $dir), E_USER_NOTICE);
1563             return; // early return
1564         }
1565
1566         while ($filename = readdir($dir_handle)) {
1567             if ($filename[0] == '.' || filetype($dir . $this->_pathsep . $filename) != 'file')
1568                 continue;
1569             if ($this->_filenameSelector($filename)) {
1570                 array_push($this->_fileList, "$filename");
1571                 //trigger_error(sprintf(_("found file %s"), $filename),
1572                 //                      E_USER_NOTICE); //debugging
1573             }
1574         }
1575         closedir($dir_handle);
1576     }
1577 };
1578
1579 // File globbing
1580
1581 // expands a list containing regex's to its matching entries
1582 class ListRegexExpand {
1583     //var $match, $list, $index, $case_sensitive;
1584     function ListRegexExpand (&$list, $match, $case_sensitive = true) {
1585         $this->match = $match;
1586         $this->list = &$list;
1587         $this->case_sensitive = $case_sensitive;        
1588         //$this->index = false;
1589     }
1590     function listMatchCallback ($item, $key) {
1591         $quoted = str_replace('/','\/',$item);
1592         if (preg_match('/' . $this->match . ($this->case_sensitive ? '/' : '/i'), 
1593                        $quoted)) {
1594             unset($this->list[$this->index]);
1595             $this->list[] = $item;
1596         }
1597     }
1598     function expandRegex ($index, &$pages) {
1599         $this->index = $index;
1600         array_walk($pages, array($this, 'listMatchCallback'));
1601         return $this->list;
1602     }
1603 }
1604
1605 // Convert fileglob to regex style:
1606 // Convert some wildcards to pcre style, escape the rest
1607 // Escape . \\ + * ? [ ^ ] $ ( ) { } = ! < > | : /
1608 // Fixed bug #994994: "/" in $glob.
1609 function glob_to_pcre ($glob) {
1610     // check simple case: no need to escape
1611     $escape = '\[](){}=!<>|:/';
1612     if (strcspn($glob, $escape . ".+*?^$") == strlen($glob))
1613         return $glob;
1614     // preg_replace cannot handle "\\\\\\2" so convert \\ to \xff
1615     $glob = strtr($glob, "\\", "\xff");
1616     $glob = str_replace("/", "\\/", $glob);
1617     // first convert some unescaped expressions to pcre style: . => \.
1618     $special = '.^$';
1619     $re = preg_replace('/([^\xff])?(['.preg_quote($special).'])/', 
1620                        "\\1\xff\\2", $glob);
1621
1622     // * => .*, ? => .
1623     $re = preg_replace('/([^\xff])?\*/', '$1.*', $re);
1624     $re = preg_replace('/([^\xff])?\?/', '$1.', $re);
1625     if (!preg_match('/^[\?\*]/', $glob))
1626         $re = '^' . $re;
1627     if (!preg_match('/[\?\*]$/', $glob))
1628         $re = $re . '$';
1629
1630     // Fixes Bug 1182997
1631     // .*? handled above, now escape the rest
1632     //while (strcspn($re, $escape) != strlen($re)) // loop strangely needed
1633     $re = preg_replace('/([^\xff])(['.preg_quote($escape, "/").'])/', 
1634                        "\\1\xff\\2", $re);
1635     // Problem with 'Date/Time' => 'Date\/Time' => 'Date\xff\/Time' => 'Date\/Time'
1636     // 'plugin/*.php'
1637     $re = preg_replace('/\xff/', '', $re);
1638     return $re;
1639 }
1640
1641 function glob_match ($glob, $against, $case_sensitive = true) {
1642     return preg_match('/' . glob_to_pcre($glob) . ($case_sensitive ? '/' : '/i'), 
1643                       $against);
1644 }
1645
1646 function explodeList($input, $allnames, $glob_style = true, $case_sensitive = true) {
1647     $list = explode(',',$input);
1648     // expand wildcards from list of $allnames
1649     if (preg_match('/[\?\*]/',$input)) {
1650         // Optimizing loop invariants:
1651         // http://phplens.com/lens/php-book/optimizing-debugging-php.php
1652         for ($i = 0, $max = sizeof($list); $i < $max; $i++) {
1653             $f = $list[$i];
1654             if (preg_match('/[\?\*]/',$f)) {
1655                 reset($allnames);
1656                 $expand = new ListRegexExpand($list, 
1657                     $glob_style ? glob_to_pcre($f) : $f, $case_sensitive);
1658                 $expand->expandRegex($i, $allnames);
1659             }
1660         }
1661     }
1662     return $list;
1663 }
1664
1665 // echo implode(":",explodeList("Test*",array("xx","Test1","Test2")));
1666 function explodePageList($input, $include_empty=false, $sortby='pagename', 
1667                          $limit='', $exclude='') {
1668     include_once("lib/PageList.php");
1669     return PageList::explodePageList($input, $include_empty, $sortby, $limit, $exclude);
1670 }
1671
1672 // Class introspections
1673
1674 /** 
1675  * Determine whether object is of a specified type.
1676  * In PHP builtin since 4.2.0 as is_a()
1677  * is_a() deprecated in PHP 5, in favor of instanceof operator
1678
1679  * @param $object object An object.
1680  * @param $class string Class name.
1681  * @return bool True iff $object is a $class
1682  * or a sub-type of $class. 
1683  */
1684 function isa ($object, $class) {
1685     //if (check_php_version(5)) 
1686     //    return $object instanceof $class;
1687     if (check_php_version(4,2) and !check_php_version(5)) 
1688         return is_a($object, $class);
1689
1690     $lclass = check_php_version(5) ? $class : strtolower($class);
1691     return is_object($object)
1692         && ( strtolower(get_class($object)) == strtolower($class)
1693              || is_subclass_of($object, $lclass) );
1694 }
1695
1696 /** Determine whether (possible) object has method.
1697  *
1698  * @param $object mixed Object
1699  * @param $method string Method name
1700  * @return bool True iff $object is an object with has method $method.
1701  */
1702 function can ($object, $method) {
1703     return is_object($object) && method_exists($object, strtolower($method));
1704 }
1705
1706 /** Determine whether a function is okay to use.
1707  *
1708  * Some providers (e.g. Lycos) disable some of PHP functions for
1709  * "security reasons."  This makes those functions, of course,
1710  * unusable, despite the fact the function_exists() says they
1711  * exist.
1712  *
1713  * This function test to see if a function exists and is not
1714  * disallowed by PHP's disable_functions config setting.
1715  *
1716  * @param string $function_name  Function name
1717  * @return bool  True iff function can be used.
1718  */
1719 function function_usable($function_name) {
1720     static $disabled;
1721     if (!is_array($disabled)) {
1722         $disabled = array();
1723         // Use get_cfg_var since ini_get() is one of the disabled functions
1724         // (on Lycos, at least.)
1725         $split = preg_split('/\s*,\s*/', trim(get_cfg_var('disable_functions')));
1726         foreach ($split as $f)
1727             $disabled[strtolower($f)] = true;
1728     }
1729
1730     return ( function_exists($function_name)
1731              and ! isset($disabled[strtolower($function_name)])
1732              );
1733 }
1734     
1735     
1736 /** Hash a value.
1737  *
1738  * This is used for generating ETags.
1739  */
1740 function wikihash ($x) {
1741     if (is_scalar($x)) {
1742         return $x;
1743     }
1744     elseif (is_array($x)) {            
1745         ksort($x);
1746         return md5(serialize($x));
1747     }
1748     elseif (is_object($x)) {
1749         return $x->hash();
1750     }
1751     trigger_error("Can't hash $x", E_USER_ERROR);
1752 }
1753
1754
1755 /**
1756  * Seed the random number generator.
1757  *
1758  * better_srand() ensures the randomizer is seeded only once.
1759  * 
1760  * How random do you want it? See:
1761  * http://www.php.net/manual/en/function.srand.php
1762  * http://www.php.net/manual/en/function.mt-srand.php
1763  */
1764 function better_srand($seed = '') {
1765     static $wascalled = FALSE;
1766     if (!$wascalled) {
1767         $seed = $seed === '' ? (double) microtime() * 1000000 : $seed;
1768         function_exists('mt_srand') ? mt_srand($seed) : srand($seed);
1769         $wascalled = TRUE;
1770         //trigger_error("new random seed", E_USER_NOTICE); //debugging
1771     }
1772 }
1773
1774 function rand_ascii($length = 1) {
1775     better_srand();
1776     $s = "";
1777     for ($i = 1; $i <= $length; $i++) {
1778         // return only typeable 7 bit ascii, avoid quotes
1779         if (function_exists('mt_rand'))
1780             $s .= chr(mt_rand(40, 126)); 
1781         else
1782             // the usually bad glibc srand()
1783             $s .= chr(rand(40, 126));
1784     }
1785     return $s;
1786 }
1787
1788 /* by Dan Frankowski.
1789  */
1790 function rand_ascii_readable ($length = 6) {
1791     // Pick a few random letters or numbers
1792     $word = "";
1793     better_srand();
1794     // Don't use 1lI0O, because they're hard to read
1795     $letters = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
1796     $letter_len = strlen($letters);
1797     for ($i=0; $i < $length; $i++) {
1798         if (function_exists('mt_rand'))
1799             $word .= $letters[mt_rand(0, $letter_len-1)];
1800         else
1801             $word .= $letters[rand(0, $letter_len-1)];
1802     }
1803     return $word;
1804 }
1805
1806 /**
1807  * Recursively count all non-empty elements 
1808  * in array of any dimension or mixed - i.e. 
1809  * array('1' => 2, '2' => array('1' => 3, '2' => 4))
1810  * See http://www.php.net/manual/en/function.count.php
1811  */
1812 function count_all($arg) {
1813     // skip if argument is empty
1814     if ($arg) {
1815         //print_r($arg); //debugging
1816         $count = 0;
1817         // not an array, return 1 (base case) 
1818         if(!is_array($arg))
1819             return 1;
1820         // else call recursively for all elements $arg
1821         foreach($arg as $key => $val)
1822             $count += count_all($val);
1823         return $count;
1824     }
1825 }
1826
1827 function isSubPage($pagename) {
1828     return (strstr($pagename, SUBPAGE_SEPARATOR));
1829 }
1830
1831 function subPageSlice($pagename, $pos) {
1832     $pages = explode(SUBPAGE_SEPARATOR,$pagename);
1833     $pages = array_slice($pages,$pos,1);
1834     return $pages[0];
1835 }
1836
1837 /**
1838  * Alert
1839  *
1840  * Class for "popping up" and alert box.  (Except that right now, it doesn't
1841  * pop up...)
1842  *
1843  * FIXME:
1844  * This is a hackish and needs to be refactored.  However it would be nice to
1845  * unify all the different methods we use for showing Alerts and Dialogs.
1846  * (E.g. "Page deleted", login form, ...)
1847  */
1848 class Alert {
1849     /** Constructor
1850      *
1851      * @param object $request
1852      * @param mixed $head  Header ("title") for alert box.
1853      * @param mixed $body  The text in the alert box.
1854      * @param hash $buttons  An array mapping button labels to URLs.
1855      *    The default is a single "Okay" button pointing to $request->getURLtoSelf().
1856      */
1857     function Alert($head, $body, $buttons=false) {
1858         if ($buttons === false)
1859             $buttons = array();
1860
1861         if (is_array($body)) {
1862             $html = HTML::ol();
1863             foreach ($body as $li) {
1864                 $html->pushContent(HTML::li($li));
1865             }
1866             $body = $html;
1867         }
1868         $this->_tokens = array('HEADER' => $head, 'CONTENT' => $body);
1869         $this->_buttons = $buttons;
1870     }
1871
1872     /**
1873      * Show the alert box.
1874      */
1875     function show() {
1876         global $request;
1877
1878         $tokens = $this->_tokens;
1879         $tokens['BUTTONS'] = $this->_getButtons();
1880         
1881         $request->discardOutput();
1882         $tmpl = new Template('dialog', $request, $tokens);
1883         $tmpl->printXML();
1884         $request->finish();
1885     }
1886
1887
1888     function _getButtons() {
1889         global $request;
1890
1891         $buttons = $this->_buttons;
1892         if (!$buttons)
1893             $buttons = array(_("Okay") => $request->getURLtoSelf());
1894         
1895         global $WikiTheme;
1896         foreach ($buttons as $label => $url)
1897             print "$label $url\n";
1898             $out[] = $WikiTheme->makeButton($label, $url, 'wikiaction');
1899         return new XmlContent($out);
1900     }
1901 }
1902
1903 // 1.3.8     => 1030.08
1904 // 1.3.9-p1  => 1030.091
1905 // 1.3.10pre => 1030.099
1906 // 1.3.11pre-20041120 => 1030.1120041120
1907 // 1.3.12-rc1 => 1030.119
1908 function phpwiki_version() {
1909     static $PHPWIKI_VERSION;
1910     if (!isset($PHPWIKI_VERSION)) {
1911         $arr = explode('.',preg_replace('/\D+$/','', PHPWIKI_VERSION)); // remove the pre
1912         $arr[2] = preg_replace('/\.+/','.',preg_replace('/\D/','.',$arr[2]));
1913         $PHPWIKI_VERSION = $arr[0]*1000 + $arr[1]*10 + 0.01*$arr[2];
1914         if (strstr(PHPWIKI_VERSION, 'pre') or strstr(PHPWIKI_VERSION, 'rc'))
1915             $PHPWIKI_VERSION -= 0.01;
1916     }
1917     return $PHPWIKI_VERSION;
1918 }
1919
1920 function phpwiki_gzhandler($ob) {
1921     if (function_exists('gzencode'))
1922         $ob = gzencode($ob);
1923         $GLOBALS['request']->_ob_get_length = strlen($ob);
1924     if (!headers_sent()) {
1925         header(sprintf("Content-Length: %d", $GLOBALS['request']->_ob_get_length));
1926     }
1927     return $ob;
1928 }
1929
1930 function isWikiWord($word) {
1931     global $WikiNameRegexp;
1932     //or preg_match('/\A' . $WikiNameRegexp . '\z/', $word) ??
1933     return preg_match("/^$WikiNameRegexp\$/",$word);
1934 }
1935
1936 // needed to store serialized objects-values only (perm, pref)
1937 function obj2hash ($obj, $exclude = false, $fields = false) {
1938     $a = array();
1939     if (! $fields ) $fields = get_object_vars($obj);
1940     foreach ($fields as $key => $val) {
1941         if (is_array($exclude)) {
1942             if (in_array($key, $exclude)) continue;
1943         }
1944         $a[$key] = $val;
1945     }
1946     return $a;
1947 }
1948
1949 /**
1950  * isUtf8String($string) - cheap utf-8 detection
1951  *
1952  * segfaults for strings longer than 10kb!
1953  * Use http://www.phpdiscuss.com/article.php?id=565&group=php.i18n or
1954  * checkTitleEncoding() at http://cvs.sourceforge.net/viewcvs.py/wikipedia/phase3/languages/Language.php
1955  */
1956 function isUtf8String( $s ) {
1957     $ptrASCII  = '[\x00-\x7F]';
1958     $ptr2Octet = '[\xC2-\xDF][\x80-\xBF]';
1959     $ptr3Octet = '[\xE0-\xEF][\x80-\xBF]{2}';
1960     $ptr4Octet = '[\xF0-\xF4][\x80-\xBF]{3}';
1961     $ptr5Octet = '[\xF8-\xFB][\x80-\xBF]{4}';
1962     $ptr6Octet = '[\xFC-\xFD][\x80-\xBF]{5}';
1963     return preg_match("/^($ptrASCII|$ptr2Octet|$ptr3Octet|$ptr4Octet|$ptr5Octet|$ptr6Octet)*$/s", $s);
1964 }
1965
1966 /** 
1967  * Check for UTF-8 URLs; Internet Explorer produces these if you
1968  * type non-ASCII chars in the URL bar or follow unescaped links.
1969  * Requires urldecoded pagename.
1970  * Fixes sf.net bug #953949
1971  *
1972  * src: languages/Language.php:checkTitleEncoding() from mediawiki
1973  */
1974 function fixTitleEncoding( $s ) {
1975     global $charset;
1976
1977     $s = trim($s);
1978     // print a warning?
1979     if (empty($s)) return $s;
1980
1981     $ishigh = preg_match( '/[\x80-\xff]/', $s);
1982     /*
1983     $isutf = ($ishigh ? preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1984                                     '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s ) : true );
1985     */
1986     $isutf = ($ishigh ? isUtf8String($s) : true);
1987     $locharset = strtolower($charset);
1988
1989     if( $locharset != "utf-8" and $ishigh and $isutf )
1990         $s = charset_convert('UTF-8', $locharset, $s);
1991     if ($locharset == "utf-8" and $ishigh and !$isutf )
1992         return utf8_encode( $s );
1993
1994     // Other languages can safely leave this function, or replace
1995     // it with one to detect and convert another legacy encoding.
1996     return $s;
1997 }
1998
1999 /** 
2000  * MySQL fulltext index doesn't grok utf-8, so we
2001  * need to fold cases and convert to hex.
2002  * src: languages/Language.php:stripForSearch() from mediawiki
2003  */
2004 /*
2005 function stripForSearch( $string ) {
2006     global $wikiLowerChars; 
2007     // '/(?:[a-z]|\xc3[\x9f-\xbf]|\xc4[\x81\x83\x85\x87])/' => "a-z\xdf-\xf6\xf8-\xff"
2008     return preg_replace(
2009                         "/([\\xc0-\\xff][\\x80-\\xbf]*)/e",
2010                         "'U8' . bin2hex( strtr( \"\$1\", \$wikiLowerChars ) )",
2011                         $string );
2012 }
2013 */
2014
2015 /** 
2016  * Workaround for allow_url_fopen, to get the content of an external URI.
2017  * It returns the contents in one slurp. Parsers might want to check for allow_url_fopen
2018  * and use fopen, fread chunkwise. (see lib/XmlParser.php)
2019  */
2020 function url_get_contents( $uri ) {
2021     if (get_cfg_var('allow_url_fopen')) { // was ini_get('allow_url_fopen'))
2022         return @file_get_contents($uri);
2023     } else {
2024         require_once("lib/HttpClient.php");
2025         $bits = parse_url($uri);
2026         $host = $bits['host'];
2027         $port = isset($bits['port']) ? $bits['port'] : 80;
2028         $path = isset($bits['path']) ? $bits['path'] : '/';
2029         if (isset($bits['query'])) {
2030             $path .= '?'.$bits['query'];
2031         }
2032         $client = new HttpClient($host, $port);
2033         $client->use_gzip = false;
2034         if (!$client->get($path)) {
2035             return false;
2036         } else {
2037             return $client->getContent();
2038         }
2039     }
2040 }
2041
2042 /**
2043  * Generate consecutively named strings:
2044  *   Name, Name2, Name3, ...
2045  */
2046 function GenerateId($name) {
2047     static $ids = array();
2048     if (empty($ids[$name])) {
2049         $ids[$name] = 1;
2050         return $name;
2051     } else {
2052         $ids[$name]++;
2053         return $name . $ids[$name];
2054     }
2055 }
2056
2057 // from IncludePage. To be of general use.
2058 // content: string or array of strings
2059 function firstNWordsOfContent( $n, $content ) {
2060     if ($content and $n > 0) {
2061         if (is_array($content)) {
2062             // fixme: return a list of lines then?
2063             //$content = join("\n", $content);
2064             //$return_array = true;
2065             $wordcount = 0;
2066             foreach ($content as $line) {
2067                 $words = explode(' ', $line);
2068                 if ($wordcount + count($words) > $n) {
2069                     $new[] = implode(' ', array_slice($words, 0, $n - $wordcount))
2070                            . sprintf(_("... (first %s words)"), $n);
2071                     return $new;
2072                 } else {
2073                     $wordcount += count($words);
2074                     $new[] = $line;
2075                 }
2076             }
2077             return $new;
2078         } else {
2079             // fixme: use better whitespace/word seperators
2080             $words = explode(' ', $content);
2081             if (count($words) > $n) {
2082                 return join(' ', array_slice($words, 0, $n))
2083                        . sprintf(_("... (first %s words)"), $n);
2084             } else {
2085                 return $content;
2086             }
2087         }
2088     } else {
2089         return '';
2090     }
2091 }
2092
2093 // moved from lib/plugin/IncludePage.php
2094 function extractSection ($section, $content, $page, $quiet = false, $sectionhead = false) {
2095     $qsection = preg_replace('/\s+/', '\s+', preg_quote($section, '/'));
2096
2097     if (preg_match("/ ^(!{1,}|={2,})\\s*$qsection" // section header
2098                    . "  \\s*$\\n?"           // possible blank lines
2099                    . "  ( (?: ^.*\\n? )*? )" // some lines
2100                    . "  (?= ^\\1 | \\Z)/xm", // sec header (same or higher level) (or EOF)
2101                    implode("\n", $content),
2102                    $match)) {
2103         // Strip trailing blanks lines and ---- <hr>s
2104         $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[2]);
2105         if ($sectionhead)
2106             $text = $match[1] . $section ."\n". $text;
2107         return explode("\n", $text);
2108     }
2109     if ($quiet)
2110         $mesg = $page ." ". $section;
2111     else
2112         $mesg = $section;
2113     return array(sprintf(_("<%s: no such section>"), $mesg));
2114 }
2115
2116 // Extract the first $sections sections of the page
2117 function extractSections ($sections, $content, $page, $quiet = false, $sectionhead = false) {
2118
2119     $mycontent = $content;
2120     $result = "";
2121
2122     while ($sections > 0) {
2123
2124         if (preg_match("/ ^(!{1,})\\s*(.*)\\n"   // section header
2125                        . "  \\s*$\\n?"           // possible blank lines
2126                        . "  ( (?: ^.*\\n? )*? )" // some lines
2127                        . "  ( ^\\1 (.|\\n)* | \\Z)/xm", // sec header (same or higher level) (or EOF)
2128                        implode("\n", $mycontent),
2129                        $match)) {
2130             $section = $match[2];
2131             // Strip trailing blanks lines and ---- <hr>s
2132             $text = preg_replace("/\\s*^-{4,}\\s*$/m", "", $match[3]);
2133             if ($sectionhead)
2134                 $text = $match[1] . $section ."\n". $text;
2135             $result .= $text; 
2136
2137             $mycontent = explode("\n", $match[4]);
2138             $sections--;
2139             if ($sections === 0) {
2140                 return explode("\n", $result);
2141             }
2142         }
2143     }
2144 }
2145
2146 // use this faster version: only load ExternalReferrer if we came from an external referrer
2147 function isExternalReferrer(&$request) {
2148     if ($referrer = $request->get('HTTP_REFERER')) {
2149         $home = SERVER_URL; // SERVER_URL or SCRIPT_NAME, if we want to check sister wiki's also
2150         if (string_starts_with(strtolower($referrer), strtolower($home))) return false;
2151         require_once("lib/ExternalReferrer.php");
2152         $se = new SearchEngines();
2153         return $se->parseSearchQuery($referrer);
2154     }
2155     //if (DEBUG) return array('query' => 'wiki');
2156     return false;
2157 }
2158
2159 /**
2160  * Useful for PECL overrides: cvsclient, ldap, soap, xmlrpc, pdo, pdo_<driver>
2161  */
2162 function loadPhpExtension($extension) {
2163     if (!extension_loaded($extension)) {
2164         $isWindows = (substr(PHP_OS,0,3) == 'WIN');
2165         $soname = ($isWindows ? 'php_' : '') 
2166                 . $extension 
2167                 . ($isWindows ? '.dll' : '.so');
2168         if (!@dl($soname))
2169             return false;
2170     }
2171     return extension_loaded($extension);
2172 }
2173
2174 function charset_convert($from, $to, $data) {
2175     //global $CHARSET;
2176     //$wikicharset = strtolower($CHARSET);
2177     //$systemcharset = strtolower(get_cfg_var('iconv.internal_encoding')); // 'iso-8859-1';
2178     if (strtolower($from) == 'utf-8' and strtolower($to) == 'iso-8859-1')
2179         return utf8_decode($data);
2180     if (strtolower($to) == 'utf-8' and strtolower($from) == 'iso-8859-1')
2181         return utf8_encode($data);
2182
2183     if (loadPhpExtension("iconv")) {
2184         $tmpdata = iconv($from, $to, $data);
2185         if (!$tmpdata)
2186             trigger_error("charset conversion $from => $to failed. Wrong source charset?", E_USER_WARNING);
2187         else
2188             $data = $tmpdata;
2189     } else {
2190         trigger_error("The iconv extension cannot be loaded", E_USER_WARNING);
2191     }
2192     return $data;
2193 }
2194
2195 function string_starts_with($string, $prefix) {
2196     return (substr($string, 0, strlen($prefix)) == $prefix);
2197 }
2198 function string_ends_with($string, $suffix) {
2199     return (substr($string, -strlen($suffix)) == $suffix);
2200 }
2201 function array_remove($arr,$value) {
2202    return array_values(array_diff($arr,array($value)));
2203 }
2204
2205 /** 
2206  * Ensure that the script will have another $secs time left. 
2207  * Works only if safe_mode is off.
2208  * For example not to timeout on waiting socket connections.
2209  *   Use the socket timeout as arg.
2210  */
2211 function longer_timeout($secs = 30) {
2212     $timeout = @ini_get("max_execution_time") ? ini_get("max_execution_time") : 30;
2213     $timeleft = $timeout - $GLOBALS['RUNTIMER']->getTime();
2214     if ($timeleft < $secs)
2215         @set_time_limit(max($timeout,(integer)($secs + $timeleft)));
2216 }
2217
2218 function printSimpleTrace($bt) {
2219     //print_r($bt);
2220     echo "\nTraceback:\n";
2221     if (function_exists('debug_print_backtrace')) { // >= 5
2222         debug_print_backtrace();
2223     } else {
2224         foreach ($bt as $i => $elem) {
2225             if (!array_key_exists('file', $elem)) {
2226                 continue;
2227             }
2228             //echo join(" ",array_values($elem)),"\n";
2229             echo "  ",$elem['file'],':',$elem['line']," ",$elem['function'],"\n";
2230         }
2231     }
2232 }
2233
2234 /**
2235  * Return the used process memory, in bytes.
2236  * Enable the section which will work for you. They are very slow.
2237  * Special quirks for Windows: Requires cygwin.
2238  */
2239 function getMemoryUsage() {
2240     //if (!(DEBUG & _DEBUG_VERBOSE)) return;
2241     if (function_exists('memory_get_usage') and memory_get_usage()) {
2242         return memory_get_usage();
2243     } elseif (function_exists('getrusage') and ($u = @getrusage()) and !empty($u['ru_maxrss'])) {
2244         $mem = $u['ru_maxrss'];
2245     } elseif (substr(PHP_OS,0,3) == 'WIN') { // may require a newer cygwin
2246         // what we want is the process memory only: apache or php (if CGI)
2247         $pid = getmypid();
2248         $memstr = '';
2249         // win32_ps_stat_proc, win32_ps_stat_mem
2250         if (function_exists('win32_ps_list_procs')) {
2251             $info = win32_ps_stat_proc($pid);
2252             $memstr = $info['mem']['working_set_size'];
2253         } elseif(0) {
2254             // This works only if it's a cygwin process (apache or php).
2255             // Requires a newer cygwin
2256             $memstr = exec("cat /proc/$pid/statm |cut -f1");
2257
2258             // if it's native windows use something like this: 
2259             //   (requires pslist from sysinternals.com, grep, sed and perl)
2260             //$memstr = exec("pslist $pid|grep -A1 Mem|sed 1d|perl -ane\"print \$"."F[5]\"");
2261         }
2262         return (integer) trim($memstr);
2263     } elseif (1) {
2264         $pid = getmypid();
2265         //%MEM: Percentage of total memory in use by this process
2266         //VSZ: Total virtual memory size, in 1K blocks.
2267         //RSS: Real Set Size, the actual amount of physical memory allocated to this process.
2268         //CPU time used by process since it started.
2269         //echo "%",`ps -o%mem,vsz,rss,time -p $pid|sed 1d`,"\n";
2270         $memstr = exec("ps -orss -p $pid|sed 1d");
2271         return (integer) trim($memstr);
2272     }
2273 }
2274
2275 /**
2276  * @param var $needle
2277  * @param array $haystack one-dimensional numeric array only, no hash
2278  * @return integer
2279  * @desc Feed a sorted array to $haystack and a value to search for to $needle.
2280              It will return false if not found or the index where it was found.
2281   From dennis.decoene@moveit.be http://www.php.net/array_search
2282 */
2283 function binary_search($needle, $haystack) {
2284     $high = count($haystack);
2285     $low = 0;
2286    
2287     while (($high - $low) > 1) {
2288         $probe = floor(($high + $low) / 2);
2289         if ($haystack[$probe] < $needle) {
2290             $low = $probe;
2291         } elseif ($haystack[$probe] == $needle) {
2292             $high = $low = $probe;
2293         } else {
2294             $high = $probe;
2295         }
2296     }
2297
2298     if ($high == count($haystack) || $haystack[$high] != $needle) {
2299         return false;
2300     } else {
2301         return $high;
2302     }
2303 }
2304
2305 function is_localhost($url = false) {
2306     if (!$url) {
2307         global $HTTP_SERVER_VARS;
2308         return $HTTP_SERVER_VARS['SERVER_ADDR'] == '127.0.0.1';
2309     }
2310 }
2311
2312 /**
2313  * Take a string and quote it sufficiently to be passed as a Javascript
2314  * string between ''s
2315  */
2316 function javascript_quote_string($s) {
2317     return str_replace("'", "\'", $s);
2318 }
2319
2320 function isSerialized($s) {
2321     return (!empty($s) and (strlen($s) > 3) and (substr($s,1,1) == ':'));
2322 }
2323
2324 /**
2325  * Take a string and return an array of pairs (attribute name, attribute value)
2326  *
2327  * We allow attributes with or without double quotes (")
2328  * Attribute-value pairs may be separated by space or comma
2329  * Space is normal HTML attributes, comma is for RichTable compatibility
2330  * border=1, cellpadding="5"
2331  * border=1 cellpadding="5"
2332  * style="font-family: sans-serif; border-top:1px solid #dddddd;"
2333  * style="font-family: Verdana, Arial, Helvetica, sans-serif"
2334  */
2335 function parse_attributes($line) {
2336
2337     $options = array();
2338
2339     if (empty($line)) return $options;
2340     $line = trim($line);
2341     if (empty($line)) return $options;
2342     $line = trim($line, ",");
2343     if (empty($line)) return $options;
2344
2345     // First we have an attribute name.
2346     $attribute = "";
2347     $value = "";
2348
2349     $i = 0;
2350     while (($i < strlen($line)) && ($line[$i] != '=')) {
2351         $i++;
2352     }
2353     $attribute = substr($line, 0, $i);
2354     $attribute = strtolower($attribute);
2355
2356     $line = substr($line, $i+1);
2357     $line = trim ($line);
2358     $line = trim ($line, "=");
2359     $line = trim ($line);
2360
2361     if (empty($line)) return $options;
2362
2363     // Then we have the attribute value.
2364
2365     $i = 0;
2366     // Attribute value might be between double quotes
2367     // In that case we have to find the closing double quote
2368     if ($line[0] == '"') {
2369         $i++; // skip first '"'
2370         while (($i < strlen($line)) && ($line[$i] != '"')) {
2371             $i++;
2372         }
2373         $value = substr($line, 0, $i);
2374         $value = trim ($value, '"');
2375         $value = trim ($value);
2376
2377     // If there are no double quotes, we have to find the next space or comma
2378     } else {
2379         while (($i < strlen($line)) && (($line[$i] != ' ') && ($line[$i] != ','))) {
2380             $i++;
2381         }
2382         $value = substr($line, 0, $i);
2383         $value = trim ($value);
2384         $value = trim ($value, ",");
2385         $value = trim ($value);
2386     }
2387
2388     $options[$attribute] = $value;
2389     
2390     $line = substr($line, $i+1);
2391     $line = trim ($line);
2392     $line = trim ($line, ",");
2393     $line = trim ($line);
2394
2395     return $options + parse_attributes($line);
2396 }
2397
2398 /**
2399  * Returns true if the filename ends with an image suffix.
2400  * Uses INLINE_IMAGES if defined, else "png|jpg|jpeg|gif"
2401  */
2402 function is_image ($filename) {
2403
2404     if (defined('INLINE_IMAGES')) {
2405         $inline_images = INLINE_IMAGES;
2406     } else {
2407         $inline_images = "png|jpg|jpeg|gif";
2408     }
2409
2410     foreach (explode("|", $inline_images) as $suffix) {
2411         if (string_ends_with(strtolower($filename), "." . $suffix)) {
2412             return true;
2413         }
2414     }
2415     return false;
2416 }
2417
2418 /**
2419  * Compute cell in spreadsheet table
2420  * $table: two-dimensional table
2421  * $i and $j: indexes of cell to compute
2422  * $imax and $jmax: table dimensions
2423  */
2424 function compute_tablecell ($table, $i, $j, $imax, $jmax) {
2425
2426     // What is implemented:
2427     // @@=SUM(R)@@ : sum of cells in current row
2428     // @@=SUM(C)@@ : sum of cells in current column
2429     // @@=AVERAGE(R)@@ : average of cells in current row
2430     // @@=AVERAGE(C)@@ : average of cells in current column
2431     // @@=MAX(R)@@ : maximum value of cells in current row
2432     // @@=MAX(C)@@ : maximum value of cells in current column
2433     // @@=MIN(R)@@ : minimum value of cells in current row
2434     // @@=MIN(C)@@ : minimum value of cells in current column
2435     // @@=COUNT(R)@@ : number of cells in current row
2436     //                (numeric or not, excluding headers and current cell)
2437     // @@=COUNT(C)@@ : number of cells in current column
2438     //                (numeric or not, excluding headers and current cell)
2439
2440     $result=0;
2441     $counter=0;
2442     $found=false;
2443
2444     if (strpos($table[$i][$j], "@@=SUM(C)@@") !== false) {
2445         for ($index=0; $index<$imax; $index++) {
2446             if (is_numeric($table[$index][$j])) {
2447                 $result += $table[$index][$j];
2448             }
2449         }
2450         return str_replace("@@=SUM(C)@@", $result, $table[$i][$j]);
2451
2452     } else if (strpos($table[$i][$j], "@@=SUM(R)@@") !== false) {
2453         for ($index=0; $index<$jmax; $index++) {
2454             if (is_numeric($table[$i][$index])) {
2455                 $result += $table[$i][$index];
2456             }
2457         }
2458         return str_replace("@@=SUM(R)@@", $result, $table[$i][$j]);
2459
2460     } else if (strpos($table[$i][$j], "@@=AVERAGE(C)@@") !== false) {
2461         for ($index=0; $index<$imax; $index++) {
2462             if (is_numeric($table[$index][$j])) {
2463                 $result += $table[$index][$j];
2464                 $counter++;
2465             }
2466         }
2467         $result=$result/$counter;
2468         return str_replace("@@=AVERAGE(C)@@", $result, $table[$i][$j]);
2469
2470     } else if (strpos($table[$i][$j], "@@=AVERAGE(R)@@") !== false) {
2471         for ($index=0; $index<$jmax; $index++) {
2472             if (is_numeric($table[$i][$index])) {
2473                 $result += $table[$i][$index];
2474                 $counter++;
2475             }
2476         }
2477         $result=$result/$counter;
2478         return str_replace("@@=AVERAGE(R)@@", $result, $table[$i][$j]);
2479
2480     } else if (strpos($table[$i][$j], "@@=MAX(C)@@") !== false) {
2481         for ($index=0; $index<$imax; $index++) {
2482             if (is_numeric($table[$index][$j])) {
2483                 if (!$found) {
2484                     $found=true;
2485                     $result=$table[$index][$j];
2486                 } else {
2487                     $result = max($result, $table[$index][$j]);
2488                 }
2489             }
2490         }
2491         if (!$found) {
2492             $result="";
2493         }
2494         return str_replace("@@=MAX(C)@@", $result, $table[$i][$j]);
2495
2496     } else if (strpos($table[$i][$j], "@@=MAX(R)@@") !== false) {
2497         for ($index=0; $index<$jmax; $index++) {
2498             if (is_numeric($table[$i][$index])) {
2499                 if (!$found) {
2500                     $found=true;
2501                     $result=$table[$i][$index];
2502                 } else {
2503                     $result = max($result, $table[$i][$index]);
2504                 }
2505             }
2506         }
2507         if (!$found) {
2508             $result="";
2509         }
2510         return str_replace("@@=MAX(R)@@", $result, $table[$i][$j]);
2511
2512     } else if (strpos($table[$i][$j], "@@=MIN(C)@@") !== false) {
2513         for ($index=0; $index<$imax; $index++) {
2514             if (is_numeric($table[$index][$j])) {
2515                 if (!$found) {
2516                     $found=true;
2517                     $result=$table[$index][$j];
2518                 } else {
2519                     $result = min($result, $table[$index][$j]);
2520                 }
2521             }
2522         }
2523         if (!$found) {
2524             $result="";
2525         }
2526         return str_replace("@@=MIN(C)@@", $result, $table[$i][$j]);
2527
2528     } else if (strpos($table[$i][$j], "@@=MIN(R)@@") !== false) {
2529         for ($index=0; $index<$jmax; $index++) {
2530             if (is_numeric($table[$i][$index])) {
2531                 if (!$found) {
2532                     $found=true;
2533                     $result=$table[$i][$index];
2534                 } else {
2535                     $result = min($result, $table[$i][$index]);
2536                 }
2537             }
2538         }
2539         if (!$found) {
2540             $result="";
2541         }
2542         return str_replace("@@=MIN(R)@@", $result, $table[$i][$j]);
2543
2544     } else if (strpos($table[$i][$j], "@@=COUNT(C)@@") !== false) {
2545         for ($index=0; $index<$imax; $index++) {
2546             if (!string_starts_with(trim($table[$index][$j]), "=")) { // exclude header
2547                 $counter++;
2548             }
2549         }
2550         $result = $counter-1; // exclude self
2551         return str_replace("@@=COUNT(C)@@", $result, $table[$i][$j]);
2552
2553     } else if (strpos($table[$i][$j], "@@=COUNT(R)@@") !== false) {
2554         for ($index=0; $index<$jmax; $index++) {
2555             if (!string_starts_with(trim($table[$i][$index]), "=")) { // exclude header
2556                 $counter++;
2557             }
2558         }
2559         $result = $counter-1; // exclude self
2560         return str_replace("@@=COUNT(R)@@", $result, $table[$i][$j]);
2561     }
2562
2563     return $table[$i][$j];
2564 }
2565
2566 /**
2567  * Remove accents from given text.
2568  */
2569 function strip_accents($text) {
2570     $res = utf8_decode($text);
2571     $res = strtr($res,
2572                 utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'),
2573                                         'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
2574     return utf8_encode($res);
2575 }
2576 // (c-file-style: "gnu")
2577 // Local Variables:
2578 // mode: php
2579 // tab-width: 8
2580 // c-basic-offset: 4
2581 // c-hanging-comment-ender-p: nil
2582 // indent-tabs-mode: nil
2583 // End:   
2584 ?>