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