]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiTheme.php
Patch 3024802 by Sébastien Le Callonnec: Error : sortables_init is not defined
[SourceForge/phpwiki.git] / lib / WikiTheme.php
1 <?php // rcs_id('$Id$');
2 /* Copyright (C) 2002,2004,2005,2006,2008,2009,2010 $ThePhpWikiProgrammingTeam
3  *
4  * This file is part of PhpWiki.
5  * 
6  * PhpWiki is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * 
11  * PhpWiki is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License
17  * along with PhpWiki; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /**
22  * Customize output by themes: templates, css, special links functions, 
23  * and more formatting.
24  */
25
26 //require_once(dirname(__FILE__).'/HtmlElement.php');
27
28 /**
29  * Make a link to a wiki page (in this wiki).
30  *
31  * This is a convenience function.
32  *
33  * @param mixed $page_or_rev
34  * Can be:<dl>
35  * <dt>A string</dt><dd>The page to link to.</dd>
36  * <dt>A WikiDB_Page object</dt><dd>The page to link to.</dd>
37  * <dt>A WikiDB_PageRevision object</dt><dd>A specific version of the page to link to.</dd>
38  * </dl>
39  *
40  * @param string $type
41  * One of:<dl>
42  * <dt>'unknown'</dt><dd>Make link appropriate for a non-existant page.</dd>
43  * <dt>'known'</dt><dd>Make link appropriate for an existing page.</dd>
44  * <dt>'auto'</dt><dd>Either 'unknown' or 'known' as appropriate.</dd>
45  * <dt>'button'</dt><dd>Make a button-style link.</dd>
46  * <dt>'if_known'</dt><dd>Only linkify if page exists.</dd>
47  * </dl>
48  * Unless $type of of the latter form, the link will be of class 'wiki', 'wikiunknown',
49  * 'named-wiki', or 'named-wikiunknown', as appropriate.
50  *
51  * @param mixed $label (string or XmlContent object)
52  * Label for the link.  If not given, defaults to the page name.
53  *
54  * @return XmlContent The link
55  */
56 function WikiLink ($page_or_rev, $type = 'known', $label = false) {
57     global $WikiTheme, $request;
58
59     if ($type == 'button') {
60         return $WikiTheme->makeLinkButton($page_or_rev, $label);
61     }
62
63     $version = false;
64     
65     if (isa($page_or_rev, 'WikiDB_PageRevision')) {
66         $version = $page_or_rev->getVersion();
67         if ($page_or_rev->isCurrent())
68             $version = false;
69         $page = $page_or_rev->getPage();
70         $pagename = $page->getName();
71         $wikipage = $pagename;
72         $exists = true;
73     }
74     elseif (isa($page_or_rev, 'WikiDB_Page')) {
75         $page = $page_or_rev;
76         $pagename = $page->getName();
77         $wikipage = $pagename;
78     }
79     elseif (isa($page_or_rev, 'WikiPageName')) {
80         $wikipage = $page_or_rev;
81         $pagename = $wikipage->name;
82         if (!$wikipage->isValid('strict'))
83             return $WikiTheme->linkBadWikiWord($wikipage, $label);
84     }
85     else {
86         $wikipage = new WikiPageName($page_or_rev, $request->getPage());
87         $pagename = $wikipage->name;
88         if (!$wikipage->isValid('strict'))
89             return $WikiTheme->linkBadWikiWord($wikipage, $label);
90     }
91     
92     if ($type == 'auto' or $type == 'if_known') {
93         if (isset($page)) {
94             $exists = $page->exists();
95         }
96         else {
97             $dbi =& $request->_dbi;
98             $exists = $dbi->isWikiPage($wikipage->name);
99         }
100     }
101     elseif ($type == 'unknown') {
102         $exists = false;
103     }
104     else {
105         $exists = true;
106     }
107
108     // FIXME: this should be somewhere else, if really needed.
109     // WikiLink makes A link, not a string of fancy ones.
110     // (I think that the fancy split links are just confusing.)
111     // Todo: test external ImageLinks http://some/images/next.gif
112     if (isa($wikipage, 'WikiPageName') and 
113         ! $label and 
114         strchr(substr($wikipage->shortName,1), SUBPAGE_SEPARATOR))
115     {
116         $parts = explode(SUBPAGE_SEPARATOR, $wikipage->shortName);
117         $last_part = array_pop($parts);
118         $sep = '';
119         $link = HTML::span();
120         foreach ($parts as $part) {
121             $path[] = $part;
122             $parent = join(SUBPAGE_SEPARATOR, $path);
123             if ($WikiTheme->_autosplitWikiWords)
124                 $part = " " . $part;
125             if ($part)
126                 $link->pushContent($WikiTheme->linkExistingWikiWord($parent, $sep . $part));
127             $sep = $WikiTheme->_autosplitWikiWords 
128                    ? ' ' . SUBPAGE_SEPARATOR : SUBPAGE_SEPARATOR;
129         }
130         if ($exists)
131             $link->pushContent($WikiTheme->linkExistingWikiWord($wikipage, $sep . $last_part, 
132                                                                 $version));
133         else
134             $link->pushContent($WikiTheme->linkUnknownWikiWord($wikipage, $sep . $last_part));
135         return $link;
136     }
137
138     if ($exists) {
139         return $WikiTheme->linkExistingWikiWord($wikipage, $label, $version);
140     }
141     elseif ($type == 'if_known') {
142         if (!$label && isa($wikipage, 'WikiPageName'))
143             $label = $wikipage->shortName;
144         return HTML($label ? $label : $pagename);
145     }
146     else {
147         return $WikiTheme->linkUnknownWikiWord($wikipage, $label);
148     }
149 }
150
151
152
153 /**
154  * Make a button.
155  *
156  * This is a convenience function.
157  *
158  * @param $action string
159  * One of <dl>
160  * <dt>[action]</dt><dd>Perform action (e.g. 'edit') on the selected page.</dd>
161  * <dt>[ActionPage]</dt><dd>Run the actionpage (e.g. 'BackLinks') on the selected page.</dd>
162  * <dt>'submit:'[name]</dt><dd>Make a form submission button with the given name.
163  *      ([name] can be blank for a nameless submit button.)</dd>
164  * <dt>a hash</dt><dd>Query args for the action. E.g.<pre>
165  *      array('action' => 'diff', 'previous' => 'author')
166  * </pre></dd>
167  * </dl>
168  *
169  * @param $label string
170  * A label for the button.  If ommited, a suitable default (based on the valued of $action)
171  * will be picked.
172  *
173  * @param $page_or_rev mixed
174  * Which page (& version) to perform the action on.
175  * Can be one of:<dl>
176  * <dt>A string</dt><dd>The pagename.</dd>
177  * <dt>A WikiDB_Page object</dt><dd>The page.</dd>
178  * <dt>A WikiDB_PageRevision object</dt><dd>A specific version of the page.</dd>
179  * </dl>
180  * ($Page_or_rev is ignored for submit buttons.)
181  */
182 function Button ($action, $label = false, $page_or_rev = false, $options = false) {
183     global $WikiTheme;
184
185     if (!is_array($action) && preg_match('/^submit:(.*)/', $action, $m))
186         return $WikiTheme->makeSubmitButton($label, $m[1], $page_or_rev, $options);
187     else
188         return $WikiTheme->makeActionButton($action, $label, $page_or_rev, $options);
189 }
190
191 class WikiTheme {
192     var $HTML_DUMP_SUFFIX = '';
193     var $DUMP_MODE = false, $dumped_images, $dumped_css; 
194
195     /**
196      * noinit: Do not initialize unnecessary items in default_theme fallback twice.
197      */
198     function WikiTheme ($theme_name = 'default', $noinit = false) {
199         $this->_name = $theme_name;
200         $this->_themes_dir = NormalizeLocalFileName("themes");
201         $this->_path  = defined('PHPWIKI_DIR') ? NormalizeLocalFileName("") : "";
202         $this->_theme = "themes/$theme_name";
203         $this->_parents = array();
204
205         if ($theme_name != 'default') {
206             $parent = $this;
207             /* derived classes should search all parent classes */
208             while ($parent = get_parent_class($parent)) {
209                 if (strtolower($parent) == 'wikitheme') {
210                     $this->_default_theme = new WikiTheme('default', true);
211                     $this->_parents[] = $this->_default_theme;
212                 } elseif ($parent) {
213                     $this->_parents[] = new WikiTheme
214                       (preg_replace("/^WikiTheme_/i", "", $parent), true);
215                 }
216             }
217         }
218         if ($noinit) return;
219         $this->_css = array();
220         
221         // on derived classes do not add headers twice
222         if (count($this->_parents) > 1) {
223             return;
224         }
225         $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("wikicommon.js"))));
226         if (!GFORGE) {
227             // Gforge already loads this
228             $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("sortable.js"))));
229         }
230         // by pixels
231         if ((is_object($GLOBALS['request']) // guard against unittests
232              and $GLOBALS['request']->getPref('doubleClickEdit'))
233             or ENABLE_DOUBLECLICKEDIT)
234             $this->initDoubleClickEdit();
235
236         // will be replaced by acDropDown
237         if (ENABLE_LIVESEARCH) { // by bitflux.ch
238             $this->initLiveSearch();
239         }
240         // replaces external LiveSearch
241         // enable ENABLE_AJAX for DynamicIncludePage
242         if (ENABLE_ACDROPDOWN or ENABLE_AJAX) {
243             $this->initMoAcDropDown();
244             if (ENABLE_AJAX and DEBUG) // minified all together
245                 $this->addMoreHeaders(JavaScript('',array('src' => $this->_findData("ajax.js"))));
246         }
247     }
248
249     function file ($file) {
250         return $this->_path . "$this->_theme/$file";
251    } 
252
253     function _findFile ($file, $missing_okay = false) {
254         if (file_exists($this->file($file)))
255             return "$this->_theme/$file";
256
257         // FIXME: this is a short-term hack.  Delete this after all files
258         // get moved into themes/...
259         // Needed for button paths in parent themes
260         if (file_exists($this->_path . $file))
261             return $file;
262
263         /* Derived classes should search all parent classes */
264         foreach ($this->_parents as $parent) {
265             $path = $parent->_findFile($file, 1);
266             if ($path) {
267                 return $path;
268             } elseif (0 and DEBUG & (_DEBUG_VERBOSE + _DEBUG_REMOTE)) {
269                 trigger_error("$parent->_theme/$file: not found", E_USER_NOTICE);
270             }
271         }
272         if (isset($this->_default_theme)) {
273             return $this->_default_theme->_findFile($file, $missing_okay);
274         }
275         else if (!$missing_okay) {
276             trigger_error("$this->_theme/$file: not found", E_USER_NOTICE);
277             if ((DEBUG & _DEBUG_TRACE) && function_exists('debug_backtrace')) { // >= 4.3.0
278                 echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
279             }
280         }
281         return false;
282     }
283
284     function _findData ($file, $missing_okay = false) {
285         if (!string_starts_with($file, "themes")) { // common case
286             $path = $this->_findFile($file, $missing_okay);
287         } else {
288             // _findButton only
289             if (file_exists($file)) {
290                 $path = $file;
291             } elseif (defined('DATA_PATH')
292                       and file_exists(DATA_PATH . "/$file")) {
293                 $path = $file;
294             } else { // fallback for buttons in parent themes
295                 $path = $this->_findFile($file, $missing_okay);
296             }
297         }
298         if (!$path)
299             return false;
300         if (!DEBUG) {
301             $min = preg_replace("/\.(css|js)$/", "-min.\\1", $file);
302             if ($min and ($x = $this->_findFile($min, true))) $path = $x;
303         }
304
305         if (defined('DATA_PATH'))
306             return DATA_PATH . "/$path";
307         return $path;
308     }
309
310     ////////////////////////////////////////////////////////////////
311     //
312     // Date and Time formatting
313     //
314     ////////////////////////////////////////////////////////////////
315
316     // Note:  Windows' implementation of strftime does not include certain
317         // format specifiers, such as %e (for date without leading zeros).  In
318         // general, see:
319         // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strftime.2c_.wcsftime.asp
320         // As a result, we have to use %d, and strip out leading zeros ourselves.
321
322     var $_dateFormat = "%B %d, %Y";
323     var $_timeFormat = "%I:%M %p";
324
325     var $_showModTime = true;
326
327     /**
328      * Set format string used for dates.
329      *
330      * @param $fs string Format string for dates.
331      *
332      * @param $show_mod_time bool If true (default) then times
333      * are included in the messages generated by getLastModifiedMessage(),
334      * otherwise, only the date of last modification will be shown.
335      */
336     function setDateFormat ($fs, $show_mod_time = true) {
337         $this->_dateFormat = $fs;
338         $this->_showModTime = $show_mod_time;
339     }
340
341     /**
342      * Set format string used for times.
343      *
344      * @param $fs string Format string for times.
345      */
346     function setTimeFormat ($fs) {
347         $this->_timeFormat = $fs;
348     }
349
350     /**
351      * Format a date.
352      *
353      * Any time zone offset specified in the users preferences is
354      * taken into account by this method.
355      *
356      * @param $time_t integer Unix-style time.
357      *
358      * @return string The date.
359      */
360     function formatDate ($time_t) {
361         global $request;
362
363         $offset_time = $time_t + 3600 * $request->getPref('timeOffset');
364         // strip leading zeros from date elements (ie space followed by zero
365         // or leading 0 as in French "09 mai 2009")
366         return preg_replace('/ 0/', ' ', preg_replace('/^0/', ' ',
367                             strftime($this->_dateFormat, $offset_time)));
368     }
369
370     /**
371      * Format a date.
372      *
373      * Any time zone offset specified in the users preferences is
374      * taken into account by this method.
375      *
376      * @param $time_t integer Unix-style time.
377      *
378      * @return string The time.
379      */
380     function formatTime ($time_t) {
381         //FIXME: make 24-hour mode configurable?
382         global $request;
383         $offset_time = $time_t + 3600 * $request->getPref('timeOffset');
384         return preg_replace('/^0/', ' ',
385                             strtolower(strftime($this->_timeFormat, $offset_time)));
386     }
387
388     /**
389      * Format a date and time.
390      *
391      * Any time zone offset specified in the users preferences is
392      * taken into account by this method.
393      *
394      * @param $time_t integer Unix-style time.
395      *
396      * @return string The date and time.
397      */
398     function formatDateTime ($time_t) {
399         if ($time_t == 0) {
400             // Do not display "01 January 1970 1:00" for nonexistent pages
401             return "";
402         } else {
403             return $this->formatDate($time_t) . ' ' . $this->formatTime($time_t);
404         }
405     }
406
407     /**
408      * Format a (possibly relative) date.
409      *
410      * If enabled in the users preferences, this method might
411      * return a relative day (e.g. 'Today', 'Yesterday').
412      *
413      * Any time zone offset specified in the users preferences is
414      * taken into account by this method.
415      *
416      * @param $time_t integer Unix-style time.
417      *
418      * @return string The day.
419      */
420     function getDay ($time_t) {
421         global $request;
422         
423         if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($time_t))) {
424             return ucfirst($date);
425         }
426         return $this->formatDate($time_t);
427     }
428     
429     /**
430      * Format the "last modified" message for a page revision.
431      *
432      * @param $revision object A WikiDB_PageRevision object.
433      *
434      * @param $show_version bool Should the page version number
435      * be included in the message.  (If this argument is omitted,
436      * then the version number will be shown only iff the revision
437      * is not the current one.
438      *
439      * @return string The "last modified" message.
440      */
441     function getLastModifiedMessage ($revision, $show_version = 'auto') {
442         global $request;
443         if (!$revision) return '';
444         
445         // dates >= this are considered invalid.
446         if (! defined('EPOCH'))
447             define('EPOCH', 0); // seconds since ~ January 1 1970
448         
449         $mtime = $revision->get('mtime');
450         if ($mtime <= EPOCH)
451             return fmt("Never edited");
452
453         if ($show_version == 'auto')
454             $show_version = !$revision->isCurrent();
455
456         if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($mtime))) {
457             if ($this->_showModTime)
458                 $date =  sprintf(_("%s at %s"),
459                                  $date, $this->formatTime($mtime));
460             
461             if ($show_version)
462                 return fmt("Version %s, saved %s", $revision->getVersion(), $date);
463             else
464                 return fmt("Last edited %s", $date);
465         }
466
467         if ($this->_showModTime)
468             $date = $this->formatDateTime($mtime);
469         else
470             $date = $this->formatDate($mtime);
471         
472         if ($show_version)
473             return fmt("Version %s, saved on %s", $revision->getVersion(), $date);
474         else
475             return fmt("Last edited on %s", $date);
476     }
477     
478     function _relativeDay ($time_t) {
479         global $request;
480         
481         if (is_numeric($request->getPref('timeOffset')))
482           $offset = 3600 * $request->getPref('timeOffset');
483         else 
484           $offset = 0;          
485
486         $now = time() + $offset;
487         $today = localtime($now, true);
488         $time = localtime($time_t + $offset, true);
489
490         if ($time['tm_yday'] == $today['tm_yday'] && $time['tm_year'] == $today['tm_year'])
491             return _("today");
492         
493         // Note that due to daylight savings chages (and leap seconds), $now minus
494         // 24 hours is not guaranteed to be yesterday.
495         $yesterday = localtime($now - (12 + $today['tm_hour']) * 3600, true);
496         if ($time['tm_yday'] == $yesterday['tm_yday'] 
497             and $time['tm_year'] == $yesterday['tm_year'])
498             return _("yesterday");
499
500         return false;
501     }
502
503     /**
504      * Format the "Author" and "Owner" messages for a page revision.
505      */
506     function getOwnerMessage ($page) {
507         if (!ENABLE_PAGEPERM or !class_exists("PagePermission"))
508             return '';
509         $dbi =& $GLOBALS['request']->_dbi;
510         $owner = $page->getOwner();
511         if ($owner) {
512             /*
513             if ( mayAccessPage('change',$page->getName()) )
514                 return fmt("Owner: %s", $this->makeActionButton(array('action'=>_("chown"),
515                                                                       's' => $page->getName()),
516                                                                 $owner, $page));
517             */
518             if ( $dbi->isWikiPage($owner) )
519                 return fmt("Owner: %s", WikiLink($owner));
520             else
521                 return fmt("Owner: %s", '"'.$owner.'"');
522         }
523     }
524
525     /* New behaviour: (by Matt Brown)
526        Prefer author (name) over internal author_id (IP) */
527     function getAuthorMessage ($revision) {
528         if (!$revision) return '';
529         $dbi =& $GLOBALS['request']->_dbi;
530         $author = $revision->get('author');
531         if (!$author) $author = $revision->get('author_id');
532             if (!$author) return '';
533         if ( $dbi->isWikiPage($author) ) {
534                 return fmt("by %s", WikiLink($author));
535         } else {
536                 return fmt("by %s", '"'.$author.'"');
537         }
538     }
539
540     ////////////////////////////////////////////////////////////////
541     //
542     // Hooks for other formatting
543     //
544     ////////////////////////////////////////////////////////////////
545
546     //FIXME: PHP 4.1 Warnings
547     //lib/WikiTheme.php:84: Notice[8]: The call_user_method() function is deprecated,
548     //use the call_user_func variety with the array(&$obj, "method") syntax instead
549
550     function getFormatter ($type, $format) {
551         $method = strtolower("get${type}Formatter");
552         if (method_exists($this, $method))
553             return $this->{$method}($format);
554         return false;
555     }
556
557     ////////////////////////////////////////////////////////////////
558     //
559     // Links
560     //
561     ////////////////////////////////////////////////////////////////
562
563     var $_autosplitWikiWords = false;
564     function setAutosplitWikiWords($autosplit=true) {
565         $this->_autosplitWikiWords = $autosplit ? true : false;
566     }
567
568     function maybeSplitWikiWord ($wikiword) {
569         if ($this->_autosplitWikiWords)
570             return SplitPagename($wikiword);
571         else
572             return $wikiword;
573     }
574
575     var $_anonEditUnknownLinks = true;
576     function setAnonEditUnknownLinks($anonedit=true) {
577         $this->_anonEditUnknownLinks = $anonedit ? true : false;
578     }
579
580     function linkExistingWikiWord($wikiword, $linktext = '', $version = false) {
581         global $request;
582
583         if ($version !== false and !$this->HTML_DUMP_SUFFIX)
584             $url = WikiURL($wikiword, array('version' => $version));
585         else
586             $url = WikiURL($wikiword);
587
588         // Extra steps for dumping page to an html file.
589         if ($this->HTML_DUMP_SUFFIX) {
590             $url = preg_replace('/^\./', '%2e', $url); // dot pages
591         }
592
593         $link = HTML::a(array('href' => $url));
594
595         if (isa($wikiword, 'WikiPageName'))
596              $default_text = $wikiword->shortName;
597          else
598              $default_text = $wikiword;
599          
600         if (!empty($linktext)) {
601             $link->pushContent($linktext);
602             $link->setAttr('class', 'named-wiki');
603             $link->setAttr('title', $this->maybeSplitWikiWord($default_text));
604         }
605         else {
606             $link->pushContent($this->maybeSplitWikiWord($default_text));
607             $link->setAttr('class', 'wiki');
608         }
609         if ($request->getArg('frame'))
610             $link->setAttr('target', '_top');
611         return $link;
612     }
613
614     function linkUnknownWikiWord($wikiword, $linktext = '') {
615         global $request;
616
617         // Get rid of anchors on unknown wikiwords
618         if (isa($wikiword, 'WikiPageName')) {
619             $default_text = $wikiword->shortName;
620             $wikiword = $wikiword->name;
621         }
622         else {
623             $default_text = $wikiword;
624         }
625         
626         if ($this->DUMP_MODE) { // HTML, PDF or XML
627             $link = HTML::span( empty($linktext) ? $wikiword : $linktext);
628             $link->setAttr('style', 'text-decoration: underline');
629             $link->addTooltip(sprintf(_("Empty link to: %s"), $wikiword));
630             $link->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown');
631             return $link;
632         } else {
633             // if AnonEditUnknownLinks show "?" only users which are allowed to edit this page
634             if (! $this->_anonEditUnknownLinks and 
635                 ( ! $request->_user->isSignedIn() 
636                   or ! mayAccessPage('edit', $request->getArg('pagename')))) 
637             {
638                 $text = HTML::span( empty($linktext) ? $wikiword : $linktext);
639                 $text->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown');
640                 return $text;
641             } else {
642                 $url = WikiURL($wikiword, array('action' => 'create'));
643                 $button = $this->makeButton('?', $url);
644                 $button->addTooltip(sprintf(_("Create: %s"), $wikiword));
645             }
646         }
647
648         $link = HTML::span();
649         if (!empty($linktext)) {
650             $link->pushContent(HTML::span($linktext));
651             $link->setAttr('style', 'text-decoration: underline');
652             $link->setAttr('class', 'named-wikiunknown');
653         }
654         else {
655             $link->pushContent(HTML::span($this->maybeSplitWikiWord($default_text)));
656             $link->setAttr('style', 'text-decoration: underline');
657             $link->setAttr('class', 'wikiunknown');
658         }
659         if (!isa($button, "ImageButton"))
660             $button->setAttr('rel', 'nofollow');
661         $link->pushContent($button);
662         if ($request->getPref('googleLink')) {
663             $gbutton = $this->makeButton('G', "http://www.google.com/search?q="
664                                          . urlencode($wikiword));
665             $gbutton->addTooltip(sprintf(_("Google:%s"), $wikiword));
666             $link->pushContent($gbutton);
667         }
668         if ($request->getArg('frame'))
669             $link->setAttr('target', '_top');
670
671         return $link;
672     }
673
674     function linkBadWikiWord($wikiword, $linktext = '') {
675         global $ErrorManager;
676         
677         if ($linktext) {
678             $text = $linktext;
679         }
680         elseif (isa($wikiword, 'WikiPageName')) {
681             $text = $wikiword->shortName;
682         }
683         else {
684             $text = $wikiword;
685         }
686
687         if (isa($wikiword, 'WikiPageName'))
688             $message = $wikiword->getWarnings();
689         else
690             $message = sprintf(_("'%s': Bad page name"), $wikiword);
691         $ErrorManager->warning($message);
692         
693         return HTML::span(array('class' => 'badwikiword'), $text);
694     }
695     
696     ////////////////////////////////////////////////////////////////
697     //
698     // Images and Icons
699     //
700     ////////////////////////////////////////////////////////////////
701     var $_imageAliases = array();
702     var $_imageAlt = array();
703
704     /**
705      *
706      * (To disable an image, alias the image to <code>false</code>.
707      */
708     function addImageAlias ($alias, $image_name) {
709         // fall back to the PhpWiki-supplied image if not found
710         if ((empty($this->_imageAliases[$alias])
711                and $this->_findFile("images/$image_name", true))
712             or $image_name === false)
713             $this->_imageAliases[$alias] = $image_name;
714     }
715
716     function addImageAlt ($alias, $alt_text) {
717         $this->_imageAlt[$alias] = $alt_text;
718     }
719     function getImageAlt ($alias) {
720         return $this->_imageAlt[$alias];
721     }
722
723     function getImageURL ($image) {
724         $aliases = &$this->_imageAliases;
725
726         if (isset($aliases[$image])) {
727             $image = $aliases[$image];
728             if (!$image)
729                 return false;
730         }
731
732         // If not extension, default to .png.
733         if (!preg_match('/\.\w+$/', $image))
734             $image .= '.png';
735
736         // FIXME: this should probably be made to fall back
737         //        automatically to .gif, .jpg.
738         //        Also try .gif before .png if browser doesn't like png.
739
740         $path = $this->_findData("images/$image", 'missing okay');
741         if (!$path) // search explicit images/ or button/ links also
742             $path = $this->_findData("$image", 'missing okay');
743
744         if ($this->DUMP_MODE) {
745             if (empty($this->dumped_images)) $this->dumped_images = array();
746             $path = "images/". basename($path);
747             if (!in_array($path,$this->dumped_images)) 
748                 $this->dumped_images[] = $path;
749         }
750         return $path;   
751     }
752
753     function setLinkIcon($proto, $image = false) {
754         if (!$image)
755             $image = $proto;
756
757         $this->_linkIcons[$proto] = $image;
758     }
759
760     function getLinkIconURL ($proto) {
761         $icons = &$this->_linkIcons;
762         if (!empty($icons[$proto]))
763             return $this->getImageURL($icons[$proto]);
764         elseif (!empty($icons['*']))
765             return $this->getImageURL($icons['*']);
766         return false;
767     }
768
769     var $_linkIcon = 'front'; // or 'after' or 'no'. 
770     // maybe also 'spanall': there is a scheme currently in effect with front, which 
771     // spans the icon only to the first, to let the next words wrap on line breaks
772     // see stdlib.php:PossiblyGlueIconToText()
773     function getLinkIconAttr () {
774         return $this->_linkIcon;
775     }
776     function setLinkIconAttr ($where) {
777         $this->_linkIcon = $where;
778     }
779
780     function addButtonAlias ($text, $alias = false) {
781         $aliases = &$this->_buttonAliases;
782
783         if (is_array($text))
784             $aliases = array_merge($aliases, $text);
785         elseif ($alias === false)
786             unset($aliases[$text]);
787         else
788             $aliases[$text] = $alias;
789     }
790
791     function getButtonURL ($text) {
792         $aliases = &$this->_buttonAliases;
793         if (isset($aliases[$text]))
794             $text = $aliases[$text];
795
796         $qtext = urlencode($text);
797         $url = $this->_findButton("$qtext.png");
798         if ($url && strstr($url, '%')) {
799             $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
800         }
801         if (!$url) {// Jeff complained about png not supported everywhere. 
802                     // This was not PC until 2005.
803             $url = $this->_findButton("$qtext.gif");
804             if ($url && strstr($url, '%')) {
805                 $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
806             }
807         }
808         if ($url and $this->DUMP_MODE) {
809             if (empty($this->dumped_buttons)) $this->dumped_buttons = array();
810             $file = $url;
811             if (defined('DATA_PATH'))
812                 $file = substr($url,strlen(DATA_PATH)+1);
813             $url = "images/buttons/".basename($file);
814             if (!array_key_exists($text, $this->dumped_buttons))
815                 $this->dumped_buttons[$text] = $file;
816         }
817         return $url;
818     }
819
820     function _findButton ($button_file) {
821         if (empty($this->_button_path))
822             $this->_button_path = $this->_getButtonPath();
823
824         foreach ($this->_button_path as $dir) {
825             if ($path = $this->_findData("$dir/$button_file", 1))
826                 return $path; 
827         }
828         return false;
829     }
830
831     function _getButtonPath () {
832         $button_dir = $this->_findFile("buttons");
833         $path_dir = $this->_path . $button_dir;
834         if (!file_exists($path_dir) || !is_dir($path_dir))
835             return array();
836         $path = array($button_dir);
837         
838         $dir = dir($path_dir);
839         while (($subdir = $dir->read()) !== false) {
840             if ($subdir[0] == '.')
841                 continue;
842             if ($subdir == 'CVS')
843                 continue;
844             if (is_dir("$path_dir/$subdir"))
845                 $path[] = "$button_dir/$subdir";
846         }
847         $dir->close();
848         // add default buttons
849         $path[] = "themes/default/buttons";
850         $path_dir = $this->_path . "themes/default/buttons";
851         $dir = dir($path_dir);
852         while (($subdir = $dir->read()) !== false) {
853             if ($subdir[0] == '.')
854                 continue;
855             if ($subdir == 'CVS')
856                 continue;
857             if (is_dir("$path_dir/$subdir"))
858                 $path[] = "themes/default/buttons/$subdir";
859         }
860         $dir->close();
861
862         return $path;
863     }
864
865     ////////////////////////////////////////////////////////////////
866     //
867     // Button style
868     //
869     ////////////////////////////////////////////////////////////////
870
871     function makeButton ($text, $url, $class = false, $options = false) {
872         // FIXME: don't always try for image button?
873
874         // Special case: URLs like 'submit:preview' generate form
875         // submission buttons.
876         if (preg_match('/^submit:(.*)$/', $url, $m))
877             return $this->makeSubmitButton($text, $m[1], $class, $options);
878
879         if (is_string($text))           
880             $imgurl = $this->getButtonURL($text);
881         else 
882             $imgurl = $text;
883         if ($imgurl)
884             return new ImageButton($text, $url, 
885                                    in_array($class,array("wikiaction","wikiadmin"))?"wikibutton":$class, 
886                                    $imgurl, $options);
887         else
888             return new Button($this->maybeSplitWikiWord($text), $url, 
889                               $class, $options);
890     }
891
892     function makeSubmitButton ($text, $name, $class = false, $options = false) {
893         $imgurl = $this->getButtonURL($text);
894
895         if ($imgurl)
896             return new SubmitImageButton($text, $name, !$class ? "wikibutton" : $class, $imgurl, $options);
897         else
898             return new SubmitButton($text, $name, $class, $options);
899     }
900
901     /**
902      * Make button to perform action.
903      *
904      * This constructs a button which performs an action on the
905      * currently selected version of the current page.
906      * (Or anotherpage or version, if you want...)
907      *
908      * @param $action string The action to perform (e.g. 'edit', 'lock').
909      * This can also be the name of an "action page" like 'LikePages'.
910      * Alternatively you can give a hash of query args to be applied
911      * to the page.
912      *
913      * @param $label string Textual label for the button.  If left empty,
914      * a suitable name will be guessed.
915      *
916      * @param $page_or_rev mixed  The page to link to.  This can be
917      * given as a string (the page name), a WikiDB_Page object, or as
918      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
919      * object, the button will link to a specific version of the
920      * designated page, otherwise the button links to the most recent
921      * version of the page.
922      *
923      * @return object A Button object.
924      */
925     function makeActionButton ($action, $label = false, 
926                                $page_or_rev = false, $options = false) 
927     {
928         extract($this->_get_name_and_rev($page_or_rev));
929
930         if (is_array($action)) {
931             $attr = $action;
932             $action = isset($attr['action']) ? $attr['action'] : 'browse';
933         }
934         else
935             $attr['action'] = $action;
936
937         $class = is_safe_action($action) ? 'wikiaction' : 'wikiadmin';
938         if ( !$label )
939             $label = $this->_labelForAction($action);
940
941         if ($version)
942             $attr['version'] = $version;
943
944         if ($action == 'browse')
945             unset($attr['action']);
946
947         $options = $this->fixAccesskey($options);
948
949         return $this->makeButton($label, WikiURL($pagename, $attr), $class, $options);
950     }
951     
952     function tooltipAccessKeyPrefix() {
953         static $tooltipAccessKeyPrefix = null;
954         if ($tooltipAccessKeyPrefix) return $tooltipAccessKeyPrefix;
955
956         $tooltipAccessKeyPrefix = 'alt';
957         if (isBrowserOpera()) $tooltipAccessKeyPrefix = 'shift-esc';
958         elseif (isBrowserSafari() or browserDetect("Mac") or isBrowserKonqueror()) 
959             $tooltipAccessKeyPrefix = 'ctrl';
960         // ff2 win and x11 only
961         elseif ((browserDetect("firefox/2") or browserDetect("minefield/3") or browserDetect("SeaMonkey/1.1")) 
962                 and ((browserDetect("windows") or browserDetect("x11"))))
963             $tooltipAccessKeyPrefix = 'alt-shift'; 
964         return $tooltipAccessKeyPrefix;
965     }
966
967     /** Define the accesskey in the title only, with ending [p] or [alt-p].
968      *  This fixes the prefix in the title and sets the accesskey.
969      */
970     function fixAccesskey($attrs) {
971         if (!empty($attrs['title']) and preg_match("/\[(alt-)?(.)\]$/", $attrs['title'], $m))
972         {
973             if (empty($attrs['accesskey'])) $attrs['accesskey'] = $m[2];
974             // firefox 'alt-shift', MSIE: 'alt', ... see wikibits.js
975             $attrs['title'] = preg_replace("/\[(alt-)?(.)\]$/", "[".$this->tooltipAccessKeyPrefix()."-\\2]", $attrs['title']);
976         }
977         return $attrs;
978     }
979     
980     /**
981      * Make a "button" which links to a wiki-page.
982      *
983      * These are really just regular WikiLinks, possibly
984      * disguised (e.g. behind an image button) by the theme.
985      *
986      * This method should probably only be used for links
987      * which appear in page navigation bars, or similar places.
988      *
989      * Use linkExistingWikiWord, or LinkWikiWord for normal links.
990      *
991      * @param $page_or_rev mixed The page to link to.  This can be
992      * given as a string (the page name), a WikiDB_Page object, or as
993      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
994      * object, the button will link to a specific version of the
995      * designated page, otherwise the button links to the most recent
996      * version of the page.
997      *
998      * @return object A Button object.
999      */
1000     function makeLinkButton ($page_or_rev, $label = false, $action = false) {
1001         extract($this->_get_name_and_rev($page_or_rev));
1002
1003         $args = $version ? array('version' => $version) : false;
1004         if ($action) $args['action'] = $action;
1005
1006         return $this->makeButton($label ? $label : $pagename, 
1007                                  WikiURL($pagename, $args), 'wiki');
1008     }
1009
1010     function _get_name_and_rev ($page_or_rev) {
1011         $version = false;
1012
1013         if (empty($page_or_rev)) {
1014             global $request;
1015             $pagename = $request->getArg("pagename");
1016             $version = $request->getArg("version");
1017         }
1018         elseif (is_object($page_or_rev)) {
1019             if (isa($page_or_rev, 'WikiDB_PageRevision')) {
1020                 $rev = $page_or_rev;
1021                 $page = $rev->getPage();
1022                 if (!$rev->isCurrent()) $version = $rev->getVersion();
1023             }
1024             else {
1025                 $page = $page_or_rev;
1026             }
1027             $pagename = $page->getName();
1028         }
1029         elseif (is_numeric($page_or_rev)) {
1030             $version = $page_or_rev;
1031         }
1032         else {
1033             $pagename = (string) $page_or_rev;
1034         }
1035         return compact('pagename', 'version');
1036     }
1037
1038     function _labelForAction ($action) {
1039         switch ($action) {
1040             case 'edit':   return _("Edit");
1041             case 'diff':   return _("Diff");
1042             case 'logout': return _("Sign Out");
1043             case 'login':  return _("Sign In");
1044             case 'rename': return _("Rename Page");
1045             case 'lock':   return _("Lock Page");
1046             case 'unlock': return _("Unlock Page");
1047             case 'remove': return _("Remove Page");
1048             case 'purge':  return _("Purge Page");
1049             default:
1050                 // I don't think the rest of these actually get used.
1051                 // 'setprefs'
1052                 // 'upload' 'dumpserial' 'loadfile' 'zip'
1053                 // 'save' 'browse'
1054                 return gettext(ucfirst($action));
1055         }
1056     }
1057
1058     //----------------------------------------------------------------
1059     var $_buttonSeparator = "\n | ";
1060
1061     function setButtonSeparator($separator) {
1062         $this->_buttonSeparator = $separator;
1063     }
1064
1065     function getButtonSeparator() {
1066         return $this->_buttonSeparator;
1067     }
1068
1069
1070     ////////////////////////////////////////////////////////////////
1071     //
1072     // CSS
1073     //
1074     // Notes:
1075     //
1076     // Based on testing with Galeon 1.2.7 (Mozilla 1.2):
1077     // Automatic media-based style selection (via <link> tags) only
1078     // seems to work for the default style, not for alternate styles.
1079     //
1080     // Doing
1081     //
1082     //  <link rel="stylesheet" type="text/css" href="phpwiki.css" />
1083     //  <link rel="stylesheet" type="text/css" href="phpwiki-printer.css" media="print" />
1084     //
1085     // works to make it so that the printer style sheet get used
1086     // automatically when printing (or print-previewing) a page
1087     // (but when only when the default style is selected.)
1088     //
1089     // Attempts like:
1090     //
1091     //  <link rel="alternate stylesheet" title="Modern"
1092     //        type="text/css" href="phpwiki-modern.css" />
1093     //  <link rel="alternate stylesheet" title="Modern"
1094     //        type="text/css" href="phpwiki-printer.css" media="print" />
1095     //
1096     // Result in two "Modern" choices when trying to select alternate style.
1097     // If one selects the first of those choices, one gets phpwiki-modern
1098     // both when browsing and printing.  If one selects the second "Modern",
1099     // one gets no CSS when browsing, and phpwiki-printer when printing.
1100     //
1101     // The Real Fix?
1102     // =============
1103     //
1104     // We should probably move to doing the media based style
1105     // switching in the CSS files themselves using, e.g.:
1106     //
1107     //  @import url(print.css) print;
1108     //
1109     ////////////////////////////////////////////////////////////////
1110
1111     function _CSSlink($title, $css_file, $media, $is_alt = false) {
1112         // Don't set title on default style.  This makes it clear to
1113         // the user which is the default (i.e. most supported) style.
1114         if ($is_alt and isBrowserKonqueror())
1115             return HTML();
1116         $link = HTML::link(array('rel'     => $is_alt ? 'alternate stylesheet' : 'stylesheet',
1117                                  'type'    => 'text/css',
1118                                  'charset' => $GLOBALS['charset'],
1119                                  'href'    => $this->_findData($css_file)));
1120         if ($is_alt)
1121             $link->setAttr('title', $title);
1122
1123         if ($media) 
1124             $link->setAttr('media', $media);
1125         if ($this->DUMP_MODE) {
1126             if (empty($this->dumped_css)) $this->dumped_css = array();
1127             if (!in_array($css_file,$this->dumped_css)) $this->dumped_css[] = $css_file;
1128             $link->setAttr('href', basename($link->getAttr('href')));
1129         }
1130         
1131         return $link;
1132     }
1133
1134     /** Set default CSS source for this theme.
1135      *
1136      * To set styles to be used for different media, pass a
1137      * hash for the second argument, e.g.
1138      *
1139      * $theme->setDefaultCSS('default', array('' => 'normal.css',
1140      *                                        'print' => 'printer.css'));
1141      *
1142      * If you call this more than once, the last one called takes
1143      * precedence as the default style.
1144      *
1145      * @param string $title Name of style (currently ignored, unless
1146      * you call this more than once, in which case, some of the style
1147      * will become alternate (rather than default) styles, and then their
1148      * titles will be used.
1149      *
1150      * @param mixed $css_files Name of CSS file, or hash containing a mapping
1151      * between media types and CSS file names.  Use a key of '' (the empty string)
1152      * to set the default CSS for non-specified media.  (See above for an example.)
1153      */
1154     function setDefaultCSS ($title, $css_files) {
1155         if (!is_array($css_files))
1156             $css_files = array('' => $css_files);
1157         // Add to the front of $this->_css
1158         unset($this->_css[$title]);
1159         $this->_css = array_merge(array($title => $css_files), $this->_css);
1160     }
1161
1162     /** Set alternate CSS source for this theme.
1163      *
1164      * @param string $title Name of style.
1165      * @param string $css_files Name of CSS file.
1166      */
1167     function addAlternateCSS ($title, $css_files) {
1168         if (!is_array($css_files))
1169             $css_files = array('' => $css_files);
1170         $this->_css[$title] = $css_files;
1171     }
1172
1173     /**
1174      * @return string HTML for CSS.
1175      */
1176     function getCSS () {
1177         $css = array();
1178         $is_alt = false;
1179         foreach ($this->_css as $title => $css_files) {
1180             ksort($css_files); // move $css_files[''] to front.
1181             foreach ($css_files as $media => $css_file) {
1182                 if (!empty($this->DUMP_MODE)) {
1183                     if ($media == 'print')
1184                         $css[] = $this->_CSSlink($title, $css_file, '', $is_alt);
1185                 } else {
1186                     $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt);
1187                 }
1188                 if ($is_alt) break;
1189             }
1190             $is_alt = true;
1191         }
1192         return HTML($css);
1193     }
1194
1195     function findTemplate ($name) {
1196         if ($tmp = $this->_findFile("templates/$name.tmpl", 1))
1197             return $this->_path . $tmp;
1198         else {
1199             $f1 = $this->file("templates/$name.tmpl");
1200             foreach ($this->_parents as $parent) {
1201                 if ($tmp = $parent->_findFile("templates/$name.tmpl", 1))
1202                     return $this->_path . $tmp;
1203             }
1204             trigger_error("$f1 not found", E_USER_ERROR);
1205             return false;
1206         }
1207     }
1208
1209     /**
1210      * Add a random header element to head
1211      * TODO: first css, then js. Maybe seperate it into addJSHeaders/addCSSHeaders
1212      * or use an optional type argument, and seperate it within _MoreHeaders[]
1213      */
1214     //$GLOBALS['request']->_MoreHeaders = array();
1215     function addMoreHeaders ($element) {
1216         $GLOBALS['request']->_MoreHeaders[] = $element;
1217         if (!empty($this->_headers_printed) and $this->_headers_printed) {
1218             trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.")
1219                           ."\n". $element->asXML(),
1220                            E_USER_NOTICE);
1221         }
1222     }
1223
1224     /**
1225       * Singleton. Only called once, by the head template. See the warning above.
1226       */
1227     function getMoreHeaders () {
1228         global $request;
1229         // actionpages cannot add headers, because recursive template expansion
1230         // already expanded the head template before.
1231         $this->_headers_printed = 1;
1232         if (empty($request->_MoreHeaders))
1233             return '';
1234         $out = '';
1235         if (false and ($file = $this->_findData('delayed.js'))) {
1236             $request->_MoreHeaders[] = JavaScript('
1237 // Add a script element as a child of the body
1238 function downloadJSAtOnload() {
1239 var element = document.createElement("script");
1240 element.src = "' . $file . '";
1241 document.body.appendChild(element);
1242 }
1243 // Check for browser support of event handling capability
1244 if (window.addEventListener)
1245 window.addEventListener("load", downloadJSAtOnload, false);
1246 else if (window.attachEvent)
1247 window.attachEvent("onload", downloadJSAtOnload);
1248 else window.onload = downloadJSAtOnload;');
1249         }
1250         //$out = "<!-- More Headers -->\n";
1251         foreach ($request->_MoreHeaders as $h) {
1252             if (is_object($h))
1253                 $out .= $h->printXML();
1254             else
1255                 $out .= "$h\n";
1256         }
1257         return $out;
1258     }
1259
1260     //$GLOBALS['request']->_MoreAttr = array();
1261     // new arg: named elements to be able to remove them. such as DoubleClickEdit for htmldumps
1262     function addMoreAttr ($tag, $name, $element) {
1263         global $request;
1264         // protect from duplicate attr (body jscript: themes, prefs, ...)
1265         static $_attr_cache = array();
1266         $hash = md5($tag."/".$element);
1267         if (!empty($_attr_cache[$hash])) return;
1268         $_attr_cache[$hash] = 1;
1269
1270         if (empty($request->_MoreAttr) or !is_array($request->_MoreAttr[$tag]))
1271             $request->_MoreAttr[$tag] = array($name => $element);
1272         else
1273             $request->_MoreAttr[$tag][$name] = $element;
1274     }
1275
1276     function getMoreAttr ($tag) {
1277         global $request;
1278         if (empty($request->_MoreAttr[$tag]))
1279             return '';
1280         $out = '';
1281         foreach ($request->_MoreAttr[$tag] as $name => $element) {
1282             if (is_object($element))
1283                 $out .= $element->printXML();
1284             else
1285                 $out .= "$element";
1286         }
1287         return $out;
1288     }
1289
1290     /**
1291      * Common Initialisations
1292      */
1293
1294     /**
1295      * The ->load() method replaces the formerly global code in themeinfo.php.
1296      * This is run only once for the selected theme, and not for the parent themes.
1297      * Without this you would not be able to derive from other themes.
1298      */
1299     function load() {
1300
1301         $this->initGlobals();
1302         
1303         // CSS file defines fonts, colors and background images for this
1304         // style.  The companion '*-heavy.css' file isn't defined, it's just
1305         // expected to be in the same directory that the base style is in.
1306
1307         // This should result in phpwiki-printer.css being used when
1308         // printing or print-previewing with style "PhpWiki" or "MacOSX" selected.
1309         $this->setDefaultCSS('PhpWiki',
1310                              array(''      => 'phpwiki.css',
1311                                    'print' => 'phpwiki-printer.css'));
1312
1313         // This allows one to manually select "Printer" style (when browsing page)
1314         // to see what the printer style looks like.
1315         $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen');
1316         $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css');
1317         $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css');
1318
1319         if (isBrowserIE()) {
1320             $this->addMoreHeaders($this->_CSSlink(0,
1321                                                   $this->_findFile('IEFixes.css'),'all'));
1322             $this->addMoreHeaders("\n");
1323         }
1324
1325         /**
1326          * The logo image appears on every page and links to the HomePage.
1327          */
1328         $this->addImageAlias('logo', WIKI_NAME . 'Logo.png');
1329         
1330         $this->addImageAlias('search', 'search.png');
1331
1332         /**
1333          * The Signature image is shown after saving an edited page. If this
1334          * is set to false then the "Thank you for editing..." screen will
1335          * be omitted.
1336          */
1337
1338         $this->addImageAlias('signature', WIKI_NAME . "Signature.png");
1339         // Uncomment this next line to disable the signature.
1340         //$this->addImageAlias('signature', false);
1341
1342         /*
1343          * Link icons.
1344          */
1345         $this->setLinkIcon('http');
1346         $this->setLinkIcon('https');
1347         $this->setLinkIcon('ftp');
1348         $this->setLinkIcon('mailto');
1349         $this->setLinkIcon('interwiki');
1350         $this->setLinkIcon('wikiuser');
1351         $this->setLinkIcon('*', 'url');
1352
1353         $this->setButtonSeparator("\n | ");
1354
1355         /**
1356          * WikiWords can automatically be split by inserting spaces between
1357          * the words. The default is to leave WordsSmashedTogetherLikeSo.
1358          */
1359         $this->setAutosplitWikiWords(false);
1360
1361         /**
1362          * Layout improvement with dangling links for mostly closed wiki's:
1363          * If false, only users with edit permissions will be presented the 
1364          * special wikiunknown class with "?" and Tooltip.
1365          * If true (default), any user will see the ?, but will be presented 
1366          * the PrintLoginForm on a click.
1367          */
1368         //$this->setAnonEditUnknownLinks(false);
1369
1370         /*
1371          * You may adjust the formats used for formatting dates and times
1372          * below.  (These examples give the default formats.)
1373          * Formats are given as format strings to PHP strftime() function See
1374          * http://www.php.net/manual/en/function.strftime.php for details.
1375          * Do not include the server's zone (%Z), times are converted to the
1376          * user's time zone.
1377          *
1378          * Suggestion for french: 
1379          *   $this->setDateFormat("%A %e %B %Y");
1380          *   $this->setTimeFormat("%H:%M:%S");
1381          * Suggestion for capable php versions, using the server locale:
1382          *   $this->setDateFormat("%x");
1383          *   $this->setTimeFormat("%X");
1384          */
1385         //$this->setDateFormat("%B %d, %Y");
1386         //$this->setTimeFormat("%I:%M %p");
1387
1388         /*
1389          * To suppress times in the "Last edited on" messages, give a
1390          * give a second argument of false:
1391          */
1392         //$this->setDateFormat("%B %d, %Y", false); 
1393
1394
1395         /**
1396          * Custom UserPreferences:
1397          * A list of name => _UserPreference class pairs.
1398          * Rationale: Certain themes should be able to extend the predefined list 
1399          * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1400          * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1401          * See themes/wikilens/themeinfo.php
1402          */
1403         //$this->customUserPreference(); 
1404
1405         /**
1406          * Register custom PageList type and define custom PageList classes.
1407          * Rationale: Certain themes should be able to extend the predefined list 
1408          * of pagelist types. E.g. certain plugins, like MostPopular might use 
1409          * info=pagename,hits,rating
1410          * which displays the rating column whenever the wikilens theme is active.
1411          * See themes/wikilens/themeinfo.php
1412          */
1413         //$this->addPageListColumn(); 
1414
1415     } // end of load
1416
1417     /**
1418      * Custom UserPreferences:
1419      * A list of name => _UserPreference class pairs.
1420      * Rationale: Certain themes should be able to extend the predefined list 
1421      * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1422      * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1423      * These values are just ignored if another theme is used.
1424      */
1425     function customUserPreferences($array) {
1426         global $customUserPreferenceColumns; // FIXME: really a global?
1427         if (empty($customUserPreferenceColumns)) $customUserPreferenceColumns = array();
1428         //array('wikilens' => new _UserPreference_wikilens());
1429         foreach ($array as $field => $prefobj) {
1430             $customUserPreferenceColumns[$field] = $prefobj;
1431         }
1432     }
1433
1434     /** addPageListColumn(array('rating' => new _PageList_Column_rating('rating', _("Rate"))))
1435      *  Register custom PageList types for special themes, like 
1436      *  'rating' for wikilens
1437      */
1438     function addPageListColumn ($array) {
1439         global $customPageListColumns;
1440         if (empty($customPageListColumns)) $customPageListColumns = array();
1441         foreach ($array as $column => $obj) {
1442             $customPageListColumns[$column] = $obj;
1443         }
1444     }
1445
1446     function initGlobals() {
1447         global $request;
1448         static $already = 0;
1449         if (!$already) {
1450             $script_url = deduce_script_name();
1451             if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
1452                 $script_url .= ("?start_debug=".$_GET['start_debug']);
1453             $folderArrowPath = dirname($this->_findData('images/folderArrowLoading.gif'));
1454             $pagename = $request->getArg('pagename');
1455             $js = "var data_path = '". javascript_quote_string(DATA_PATH) ."';\n"
1456                 // XSS warning with pagename
1457                 ."var pagename  = '". javascript_quote_string($pagename) ."';\n"
1458                 ."var script_url= '". javascript_quote_string($script_url) ."';\n"
1459                 ."var stylepath = data_path+'/".javascript_quote_string($this->_theme)."/';\n"
1460                 ."var folderArrowPath = '".javascript_quote_string($folderArrowPath)."';\n"
1461                 ."var use_path_info = " . (USE_PATH_INFO ? "true" : "false") .";\n";
1462             $this->addMoreHeaders(JavaScript($js));
1463             $already = 1;
1464         }
1465     }
1466
1467     // Works only on action=browse. Patch #970004 by pixels
1468     // Usage: call $WikiTheme->initDoubleClickEdit() from theme init or 
1469     // define ENABLE_DOUBLECLICKEDIT
1470     function initDoubleClickEdit() {
1471         if (!$this->HTML_DUMP_SUFFIX)
1472             $this->addMoreAttr('body', 'DoubleClickEdit', HTML::Raw(" OnDblClick=\"url = document.URL; url2 = url; if (url.indexOf('?') != -1) url2 = url.slice(0, url.indexOf('?')); if ((url.indexOf('action') == -1) || (url.indexOf('action=browse') != -1)) document.location = url2 + '?action=edit';\""));
1473     }
1474
1475     // Immediate title search results via XMLHTML(HttpRequest)
1476     // by Bitflux GmbH, bitflux.ch. You need to install the livesearch.js seperately.
1477     // Google's or acdropdown is better.
1478     function initLiveSearch() {
1479         //subclasses of Sidebar will init this twice 
1480         static $already = 0;
1481         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1482             $this->addMoreAttr('body', 'LiveSearch', 
1483                                HTML::Raw(" onload=\"liveSearchInit()"));
1484             $this->addMoreHeaders(JavaScript('var liveSearchURI="'
1485                                              .WikiURL(_("TitleSearch"),false,true).'";'));
1486             $this->addMoreHeaders(JavaScript('', array
1487                                              ('src' => $this->_findData('livesearch.js'))));
1488             $already = 1;
1489         }
1490     }
1491
1492     // Immediate title search results via XMLHttpRequest
1493     // using the shipped moacdropdown js-lib
1494     function initMoAcDropDown() {
1495         //subclasses of Sidebar will init this twice 
1496         static $already = 0;
1497         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1498             $dir = $this->_findData('moacdropdown');
1499             if (!DEBUG and ($css = $this->_findFile('moacdropdown/css/dropdown-min.css'))) {
1500                 $this->addMoreHeaders($this->_CSSlink(0, $css, 'all'));
1501             } else {
1502                 $this->addMoreHeaders(HTML::style(array('type' => 'text/css'), "  @import url( $dir/css/dropdown.css );\n"));
1503             }
1504             // if autocomplete_remote is used: (getobject2 also for calc. the showlist width)
1505             if (DEBUG) {
1506                 foreach (array("mobrowser.js","modomevent3.js","modomt.js",
1507                                "modomext.js","getobject2.js","xmlextras.js") as $js) 
1508                 {
1509                     $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js")));
1510                 }
1511                 $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js")));
1512             } else {
1513                 // already in wikicommon-min.js
1514                 ; //$this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js")));
1515             }
1516             /*
1517             // for local xmlrpc requests
1518             $xmlrpc_url = deduce_script_name();
1519             //if (1 or DATABASE_TYPE == 'dba')
1520             $xmlrpc_url = DATA_PATH . "/RPC2.php";
1521             if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
1522                 $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']);
1523             $this->addMoreHeaders(JavaScript("var xmlrpc_url = '$xmlrpc_url'"));
1524             */
1525             $already = 1;
1526         }
1527     }
1528
1529     function calendarLink($date = false) {
1530         return $this->calendarBase() . SUBPAGE_SEPARATOR . 
1531                strftime("%Y-%m-%d", $date ? $date : time());
1532     }
1533
1534     function calendarBase() {
1535         static $UserCalPageTitle = false;
1536         global $request;
1537
1538         if (!$UserCalPageTitle) 
1539             $UserCalPageTitle = $request->_user->getId() . 
1540                                 SUBPAGE_SEPARATOR . _("Calendar");
1541         if (!$UserCalPageTitle)
1542             $UserCalPageTitle = (BLOG_EMPTY_DEFAULT_PREFIX ? '' 
1543                                  : ($request->_user->getId() . SUBPAGE_SEPARATOR)) . "Blog";
1544         return $UserCalPageTitle;
1545     }
1546
1547     function calendarInit($force = false) {
1548         $dbi = $GLOBALS['request']->getDbh();
1549         // display flat calender dhtml in the sidebar
1550         if ($force or $dbi->isWikiPage($this->calendarBase())) {
1551             $jslang = @$GLOBALS['LANG'];
1552             $this->addMoreHeaders
1553                 (
1554                  $this->_CSSlink(0, 
1555                                  $this->_findFile('jscalendar/calendar-phpwiki.css'), 'all'));
1556             $this->addMoreHeaders
1557                 (JavaScript('',
1558                             array('src' => $this->_findData('jscalendar/calendar'.(DEBUG?'':'_stripped').'.js'))));
1559             if (!($langfile = $this->_findData("jscalendar/lang/calendar-$jslang.js")))
1560                 $langfile = $this->_findData("jscalendar/lang/calendar-en.js");
1561             $this->addMoreHeaders(JavaScript('',array('src' => $langfile)));
1562             $this->addMoreHeaders
1563                 (JavaScript('',
1564                             array('src' => 
1565                                   $this->_findData('jscalendar/calendar-setup'.(DEBUG?'':'_stripped').'.js'))));
1566
1567             // Get existing date entries for the current user
1568             require_once("lib/TextSearchQuery.php");
1569             $iter = $dbi->titleSearch(new TextSearchQuery("^".$this->calendarBase().SUBPAGE_SEPARATOR, true, "auto"));
1570             $existing = array();
1571             while ($page = $iter->next()) {
1572                 if ($page->exists())
1573                     $existing[] = basename($page->_pagename);
1574             }
1575             if (!empty($existing)) {
1576                 $js_exist = '{"'.join('":1,"',$existing).'":1}';
1577                 //var SPECIAL_DAYS = {"2004-05-11":1,"2004-05-12":1,"2004-06-01":1}
1578                 $this->addMoreHeaders(JavaScript('
1579 /* This table holds the existing calender entries for the current user
1580  *  calculated from the database 
1581  */
1582
1583 var SPECIAL_DAYS = '.javascript_quote_string($js_exist).';
1584
1585 /* This function returns true if the date exists in SPECIAL_DAYS */
1586 function dateExists(date, y, m, d) {
1587     var year = date.getFullYear();
1588     m = m + 1;
1589     m = m < 10 ? "0" + m : m;  // integer, 0..11
1590     d = d < 10 ? "0" + d : d;  // integer, 1..31
1591     var date = year+"-"+m+"-"+d;
1592     var exists = SPECIAL_DAYS[date];
1593     if (!exists) return false;
1594     else return true;
1595 }
1596 // This is the actual date status handler. 
1597 // Note that it receives the date object as well as separate 
1598 // values of year, month and date.
1599 function dateStatusFunc(date, y, m, d) {
1600     if (dateExists(date, y, m, d)) return "existing";
1601     else return false;
1602 }
1603 '));
1604             }
1605             else {
1606                 $this->addMoreHeaders(JavaScript('
1607 function dateStatusFunc(date, y, m, d) { return false;}'));
1608             }
1609         }
1610     }
1611
1612     ////////////////////////////////////////////////////////////////
1613     //
1614     // Events
1615     //
1616     ////////////////////////////////////////////////////////////////
1617
1618     /**  CbUserLogin (&$request, $userid)
1619      * Callback when a user logs in
1620     */
1621     function CbUserLogin (&$request, $userid) {
1622         ; // do nothing
1623     }
1624
1625     /** CbNewUserEdit (&$request, $userid)
1626      * Callback when a new user creates or edits a page 
1627      */
1628     function CbNewUserEdit (&$request, $userid) {
1629         ; // i.e. create homepage with Template/UserPage
1630     }
1631
1632     /** CbNewUserLogin (&$request, $userid)
1633      * Callback when a "new user" logs in. 
1634      *  What is new? We only record changes, not logins.
1635      *  Should we track user actions?
1636      *  Let's say a new user is a user without homepage.
1637      */
1638     function CbNewUserLogin (&$request, $userid) {
1639         ; // do nothing
1640     }
1641
1642     /** CbUserLogout (&$request, $userid) 
1643      * Callback when a user logs out
1644      */
1645     function CbUserLogout (&$request, $userid) {
1646         ; // do nothing
1647     }
1648
1649 };
1650
1651
1652 /**
1653  * A class representing a clickable "button".
1654  *
1655  * In it's simplest (default) form, a "button" is just a link associated
1656  * with some sort of wiki-action.
1657  */
1658 class Button extends HtmlElement {
1659     /** Constructor
1660      *
1661      * @param $text string The text for the button.
1662      * @param $url string The url (href) for the button.
1663      * @param $class string The CSS class for the button.
1664      * @param $options array Additional attributes for the &lt;input&gt; tag.
1665      */
1666     function Button ($text, $url, $class=false, $options=false) {
1667         global $request;
1668         //php5 workaround
1669         if (check_php_version(5)) {
1670             $this->_init('a', array('href' => $url));
1671         } else {
1672             $this->__construct('a', array('href' => $url));
1673         }
1674         if ($class)
1675             $this->setAttr('class', $class);
1676         if ($request->getArg('frame'))
1677             $this->setAttr('target', '_top');
1678         if (!empty($options) and is_array($options)) {
1679             foreach ($options as $key => $val)
1680                 $this->setAttr($key, $val);
1681         }
1682         // Google honors this
1683         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1684             and !$request->_user->isAuthenticated())
1685             $this->setAttr('rel', 'nofollow');
1686         $this->pushContent($GLOBALS['WikiTheme']->maybeSplitWikiWord($text));
1687     }
1688
1689 };
1690
1691
1692 /**
1693  * A clickable image button.
1694  */
1695 class ImageButton extends Button {
1696     /** Constructor
1697      *
1698      * @param $text string The text for the button.
1699      * @param $url string The url (href) for the button.
1700      * @param $class string The CSS class for the button.
1701      * @param $img_url string URL for button's image.
1702      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1703      */
1704     function ImageButton ($text, $url, $class, $img_url, $img_attr=false) {
1705         $this->__construct('a', array('href' => $url));
1706         if ($class)
1707             $this->setAttr('class', $class);
1708         // Google honors this
1709         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1710             and !$GLOBALS['request']->_user->isAuthenticated())
1711             $this->setAttr('rel', 'nofollow');
1712
1713         if (!is_array($img_attr))
1714             $img_attr = array();
1715         $img_attr['src'] = $img_url;
1716         $img_attr['alt'] = $text;
1717         $img_attr['class'] = 'wiki-button';
1718         $this->pushContent(HTML::img($img_attr));
1719     }
1720 };
1721
1722 /**
1723  * A class representing a form <samp>submit</samp> button.
1724  */
1725 class SubmitButton extends HtmlElement {
1726     /** Constructor
1727      *
1728      * @param $text string The text for the button.
1729      * @param $name string The name of the form field.
1730      * @param $class string The CSS class for the button.
1731      * @param $options array Additional attributes for the &lt;input&gt; tag.
1732      */
1733     function SubmitButton ($text, $name=false, $class=false, $options=false) {
1734         $this->__construct('input', array('type' => 'submit',
1735                                           'value' => $text));
1736         if ($name)
1737             $this->setAttr('name', $name);
1738         if ($class)
1739             $this->setAttr('class', $class);
1740         if (!empty($options)) {
1741             foreach ($options as $key => $val)
1742                 $this->setAttr($key, $val);
1743         }
1744     }
1745
1746 };
1747
1748
1749 /**
1750  * A class representing an image form <samp>submit</samp> button.
1751  */
1752 class SubmitImageButton extends SubmitButton {
1753     /** Constructor
1754      *
1755      * @param $text string The text for the button.
1756      * @param $name string The name of the form field.
1757      * @param $class string The CSS class for the button.
1758      * @param $img_url string URL for button's image.
1759      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1760      */
1761     function SubmitImageButton ($text, $name=false, $class=false, $img_url, $img_attr=false) {
1762         $this->__construct('input', array('type'  => 'image',
1763                                           'src'   => $img_url,
1764                                           'value' => $text,
1765                                           'alt'   => $text));
1766         if ($name)
1767             $this->setAttr('name', $name);
1768         if ($class)
1769             $this->setAttr('class', $class);
1770         if (!empty($img_attr)) {
1771             foreach ($img_attr as $key => $val)
1772                 $this->setAttr($key, $val);
1773         }
1774     }
1775
1776 };
1777
1778 /** 
1779  * A sidebar box with title and body, narrow fixed-width.
1780  * To represent abbrevated content of plugins, links or forms,
1781  * like "Getting Started", "Search", "Sarch Pagename", 
1782  * "Login", "Menu", "Recent Changes", "Last comments", "Last Blogs"
1783  * "Calendar"
1784  * ... See http://tikiwiki.org/
1785  *
1786  * Usage:
1787  * sidebar.tmpl:
1788  *   $menu = SidebarBox("Menu",HTML::dl(HTML::dt(...))); $menu->format();
1789  *   $menu = PluginSidebarBox("RecentChanges",array('limit'=>10)); $menu->format();
1790  */
1791 class SidebarBox {
1792
1793     function SidebarBox($title, $body) {
1794         require_once('lib/WikiPlugin.php');
1795         $this->title = $title;
1796         $this->body = $body;
1797     }
1798     function format() {
1799         return WikiPlugin::makeBox($this->title, $this->body);
1800     }
1801 }
1802
1803 /** 
1804  * A sidebar box for plugins.
1805  * Any plugin may provide a box($args=false, $request=false, $basepage=false)
1806  * method, with the help of WikiPlugin::makeBox()
1807  */
1808 class PluginSidebarBox extends SidebarBox {
1809
1810     var $_plugin, $_args = false, $_basepage = false;
1811
1812     function PluginSidebarBox($name, $args = false, $basepage = false) {
1813         require_once("lib/WikiPlugin.php");
1814
1815         $loader = new WikiPluginLoader();
1816         $plugin = $loader->getPlugin($name);
1817         if (!$plugin) {
1818             return $loader->_error(sprintf(_("Plugin %s: undefined"),
1819                                           $name));
1820         }/*
1821         if (!method_exists($plugin, 'box')) {
1822             return $loader->_error(sprintf(_("%s: has no box method"),
1823                                            get_class($plugin)));
1824         }*/
1825         $this->_plugin   =& $plugin;
1826         $this->_args     = $args ? $args : array();
1827         $this->_basepage = $basepage;
1828     }
1829
1830     function format($args = false) {
1831         return $this->_plugin->box($args ? array_merge($this->_args, $args) : $this->_args,
1832                                    $GLOBALS['request'], 
1833                                    $this->_basepage);
1834     }
1835 }
1836
1837 // Various boxes which are no plugins
1838 class RelatedLinksBox extends SidebarBox {
1839     function RelatedLinksBox($title = false, $body = '', $limit = 20) {
1840         global $request;
1841         $this->title = $title ? $title : _("Related Links");
1842         $this->body = HTML($body);
1843         $page = $request->getPage($request->getArg('pagename'));
1844         $revision = $page->getCurrentRevision();
1845         $page_content = $revision->getTransformedContent();
1846         //$cache = &$page->_wikidb->_cache;
1847         $counter = 0;
1848         $sp = HTML::Raw('&middot; ');
1849         foreach ($page_content->getWikiPageLinks() as $link) {
1850             $linkto = $link['linkto'];
1851             if (!$request->_dbi->isWikiPage($linkto)) continue;
1852             $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1853             $counter++;
1854             if ($limit and $counter > $limit) continue;
1855         }
1856     }
1857 }
1858
1859 class RelatedExternalLinksBox extends SidebarBox {
1860     function RelatedExternalLinksBox($title = false, $body = '', $limit = 20) {
1861         global $request;
1862         $this->title = $title ? $title : _("External Links");
1863         $this->body = HTML($body);
1864         $page = $request->getPage($request->getArg('pagename'));
1865         $cache = &$page->_wikidb->_cache;
1866         $counter = 0;
1867         $sp = HTML::Raw('&middot; ');
1868         foreach ($cache->getWikiPageLinks() as $link) {
1869             $linkto = $link['linkto'];
1870             if ($linkto) {
1871                 $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1872                 $counter++;
1873                 if ($limit and $counter > $limit) continue;
1874             }
1875         }
1876     }
1877 }
1878
1879 function listAvailableThemes() {
1880     $available_themes = array(); 
1881     $dir_root = 'themes';
1882     if (defined('PHPWIKI_DIR'))
1883         $dir_root = PHPWIKI_DIR . "/$dir_root";
1884     $dir = dir($dir_root);
1885     if ($dir) {
1886         while($entry = $dir->read()) {
1887             if (is_dir($dir_root.'/'.$entry) 
1888                 and file_exists($dir_root.'/'.$entry.'/themeinfo.php')) 
1889             {
1890                 array_push($available_themes, $entry);
1891             }
1892         }
1893         $dir->close();
1894     }
1895     return $available_themes;
1896 }
1897
1898 function listAvailableLanguages() {
1899     $available_languages = array('en');
1900     $dir_root = 'locale';
1901     if (defined('PHPWIKI_DIR'))
1902         $dir_root = PHPWIKI_DIR . "/$dir_root";
1903     if ($dir = dir($dir_root)) {
1904         while($entry = $dir->read()) {
1905             if (is_dir($dir_root."/".$entry) and is_dir($dir_root.'/'.$entry.'/LC_MESSAGES'))
1906             {
1907                 array_push($available_languages, $entry);
1908             }
1909         }
1910         $dir->close();
1911     }
1912     return $available_languages;
1913 }
1914
1915 // (c-file-style: "gnu")
1916 // Local Variables:
1917 // mode: php
1918 // tab-width: 8
1919 // c-basic-offset: 4
1920 // c-hanging-comment-ender-p: nil
1921 // indent-tabs-mode: nil
1922 // End:
1923 ?>