]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiTheme.php
rcs_id no longer makes sense with Subversion global version number
[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 (!DEBUG and (!defined('GFORGE') or !GFORGE)) {
227             // Gforge and non-debug already load 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::u( empty($linktext) ? $wikiword : $linktext);
628             $link->addTooltip(sprintf(_("Empty link to: %s"), $wikiword));
629             $link->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown');
630             return $link;
631         } else {
632             // if AnonEditUnknownLinks show "?" only users which are allowed to edit this page
633             if (! $this->_anonEditUnknownLinks and 
634                 ( ! $request->_user->isSignedIn() 
635                   or ! mayAccessPage('edit', $request->getArg('pagename')))) 
636             {
637                 $text = HTML::span( empty($linktext) ? $wikiword : $linktext);
638                 $text->setAttr('class', empty($linktext) ? 'wikiunknown' : 'named-wikiunknown');
639                 return $text;
640             } else {
641                 $url = WikiURL($wikiword, array('action' => 'create'));
642                 $button = $this->makeButton('?', $url);
643                 $button->addTooltip(sprintf(_("Create: %s"), $wikiword));
644             }
645         }
646
647         $link = HTML::span();
648         if (!empty($linktext)) {
649             $link->pushContent(HTML::u($linktext));
650             $link->setAttr('class', 'named-wikiunknown');
651         }
652         else {
653             $link->pushContent(HTML::u($this->maybeSplitWikiWord($default_text)));
654             $link->setAttr('class', 'wikiunknown');
655         }
656         if (!isa($button, "ImageButton"))
657             $button->setAttr('rel', 'nofollow');
658         $link->pushContent($button);
659         if ($request->getPref('googleLink')) {
660             $gbutton = $this->makeButton('G', "http://www.google.com/search?q="
661                                          . urlencode($wikiword));
662             $gbutton->addTooltip(sprintf(_("Google:%s"), $wikiword));
663             $link->pushContent($gbutton);
664         }
665         if ($request->getArg('frame'))
666             $link->setAttr('target', '_top');
667
668         return $link;
669     }
670
671     function linkBadWikiWord($wikiword, $linktext = '') {
672         global $ErrorManager;
673         
674         if ($linktext) {
675             $text = $linktext;
676         }
677         elseif (isa($wikiword, 'WikiPageName')) {
678             $text = $wikiword->shortName;
679         }
680         else {
681             $text = $wikiword;
682         }
683
684         if (isa($wikiword, 'WikiPageName'))
685             $message = $wikiword->getWarnings();
686         else
687             $message = sprintf(_("'%s': Bad page name"), $wikiword);
688         $ErrorManager->warning($message);
689         
690         return HTML::span(array('class' => 'badwikiword'), $text);
691     }
692     
693     ////////////////////////////////////////////////////////////////
694     //
695     // Images and Icons
696     //
697     ////////////////////////////////////////////////////////////////
698     var $_imageAliases = array();
699     var $_imageAlt = array();
700
701     /**
702      *
703      * (To disable an image, alias the image to <code>false</code>.
704      */
705     function addImageAlias ($alias, $image_name) {
706         // fall back to the PhpWiki-supplied image if not found
707         if ((empty($this->_imageAliases[$alias])
708                and $this->_findFile("images/$image_name", true))
709             or $image_name === false)
710             $this->_imageAliases[$alias] = $image_name;
711     }
712
713     function addImageAlt ($alias, $alt_text) {
714         $this->_imageAlt[$alias] = $alt_text;
715     }
716     function getImageAlt ($alias) {
717         return $this->_imageAlt[$alias];
718     }
719
720     function getImageURL ($image) {
721         $aliases = &$this->_imageAliases;
722
723         if (isset($aliases[$image])) {
724             $image = $aliases[$image];
725             if (!$image)
726                 return false;
727         }
728
729         // If not extension, default to .png.
730         if (!preg_match('/\.\w+$/', $image))
731             $image .= '.png';
732
733         // FIXME: this should probably be made to fall back
734         //        automatically to .gif, .jpg.
735         //        Also try .gif before .png if browser doesn't like png.
736
737         $path = $this->_findData("images/$image", 'missing okay');
738         if (!$path) // search explicit images/ or button/ links also
739             $path = $this->_findData("$image", 'missing okay');
740
741         if ($this->DUMP_MODE) {
742             if (empty($this->dumped_images)) $this->dumped_images = array();
743             $path = "images/". basename($path);
744             if (!in_array($path,$this->dumped_images)) 
745                 $this->dumped_images[] = $path;
746         }
747         return $path;   
748     }
749
750     function setLinkIcon($proto, $image = false) {
751         if (!$image)
752             $image = $proto;
753
754         $this->_linkIcons[$proto] = $image;
755     }
756
757     function getLinkIconURL ($proto) {
758         $icons = &$this->_linkIcons;
759         if (!empty($icons[$proto]))
760             return $this->getImageURL($icons[$proto]);
761         elseif (!empty($icons['*']))
762             return $this->getImageURL($icons['*']);
763         return false;
764     }
765
766     var $_linkIcon = 'front'; // or 'after' or 'no'. 
767     // maybe also 'spanall': there is a scheme currently in effect with front, which 
768     // spans the icon only to the first, to let the next words wrap on line breaks
769     // see stdlib.php:PossiblyGlueIconToText()
770     function getLinkIconAttr () {
771         return $this->_linkIcon;
772     }
773     function setLinkIconAttr ($where) {
774         $this->_linkIcon = $where;
775     }
776
777     function addButtonAlias ($text, $alias = false) {
778         $aliases = &$this->_buttonAliases;
779
780         if (is_array($text))
781             $aliases = array_merge($aliases, $text);
782         elseif ($alias === false)
783             unset($aliases[$text]);
784         else
785             $aliases[$text] = $alias;
786     }
787
788     function getButtonURL ($text) {
789         $aliases = &$this->_buttonAliases;
790         if (isset($aliases[$text]))
791             $text = $aliases[$text];
792
793         $qtext = urlencode($text);
794         $url = $this->_findButton("$qtext.png");
795         if ($url && strstr($url, '%')) {
796             $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
797         }
798         if (!$url) {// Jeff complained about png not supported everywhere. 
799                     // This was not PC until 2005.
800             $url = $this->_findButton("$qtext.gif");
801             if ($url && strstr($url, '%')) {
802                 $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
803             }
804         }
805         if ($url and $this->DUMP_MODE) {
806             if (empty($this->dumped_buttons)) $this->dumped_buttons = array();
807             $file = $url;
808             if (defined('DATA_PATH'))
809                 $file = substr($url,strlen(DATA_PATH)+1);
810             $url = "images/buttons/".basename($file);
811             if (!array_key_exists($text, $this->dumped_buttons))
812                 $this->dumped_buttons[$text] = $file;
813         }
814         return $url;
815     }
816
817     function _findButton ($button_file) {
818         if (empty($this->_button_path))
819             $this->_button_path = $this->_getButtonPath();
820
821         foreach ($this->_button_path as $dir) {
822             if ($path = $this->_findData("$dir/$button_file", 1))
823                 return $path; 
824         }
825         return false;
826     }
827
828     function _getButtonPath () {
829         $button_dir = $this->_findFile("buttons");
830         $path_dir = $this->_path . $button_dir;
831         if (!file_exists($path_dir) || !is_dir($path_dir))
832             return array();
833         $path = array($button_dir);
834         
835         $dir = dir($path_dir);
836         while (($subdir = $dir->read()) !== false) {
837             if ($subdir[0] == '.')
838                 continue;
839             if ($subdir == 'CVS')
840                 continue;
841             if (is_dir("$path_dir/$subdir"))
842                 $path[] = "$button_dir/$subdir";
843         }
844         $dir->close();
845         // add default buttons
846         $path[] = "themes/default/buttons";
847         $path_dir = $this->_path . "themes/default/buttons";
848         $dir = dir($path_dir);
849         while (($subdir = $dir->read()) !== false) {
850             if ($subdir[0] == '.')
851                 continue;
852             if ($subdir == 'CVS')
853                 continue;
854             if (is_dir("$path_dir/$subdir"))
855                 $path[] = "themes/default/buttons/$subdir";
856         }
857         $dir->close();
858
859         return $path;
860     }
861
862     ////////////////////////////////////////////////////////////////
863     //
864     // Button style
865     //
866     ////////////////////////////////////////////////////////////////
867
868     function makeButton ($text, $url, $class = false, $options = false) {
869         // FIXME: don't always try for image button?
870
871         // Special case: URLs like 'submit:preview' generate form
872         // submission buttons.
873         if (preg_match('/^submit:(.*)$/', $url, $m))
874             return $this->makeSubmitButton($text, $m[1], $class, $options);
875
876         if (is_string($text))           
877             $imgurl = $this->getButtonURL($text);
878         else 
879             $imgurl = $text;
880         if ($imgurl)
881             return new ImageButton($text, $url, 
882                                    in_array($class,array("wikiaction","wikiadmin"))?"wikibutton":$class, 
883                                    $imgurl, $options);
884         else
885             return new Button($this->maybeSplitWikiWord($text), $url, 
886                               $class, $options);
887     }
888
889     function makeSubmitButton ($text, $name, $class = false, $options = false) {
890         $imgurl = $this->getButtonURL($text);
891
892         if ($imgurl)
893             return new SubmitImageButton($text, $name, !$class ? "wikibutton" : $class, $imgurl, $options);
894         else
895             return new SubmitButton($text, $name, $class, $options);
896     }
897
898     /**
899      * Make button to perform action.
900      *
901      * This constructs a button which performs an action on the
902      * currently selected version of the current page.
903      * (Or anotherpage or version, if you want...)
904      *
905      * @param $action string The action to perform (e.g. 'edit', 'lock').
906      * This can also be the name of an "action page" like 'LikePages'.
907      * Alternatively you can give a hash of query args to be applied
908      * to the page.
909      *
910      * @param $label string Textual label for the button.  If left empty,
911      * a suitable name will be guessed.
912      *
913      * @param $page_or_rev mixed  The page to link to.  This can be
914      * given as a string (the page name), a WikiDB_Page object, or as
915      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
916      * object, the button will link to a specific version of the
917      * designated page, otherwise the button links to the most recent
918      * version of the page.
919      *
920      * @return object A Button object.
921      */
922     function makeActionButton ($action, $label = false, 
923                                $page_or_rev = false, $options = false) 
924     {
925         extract($this->_get_name_and_rev($page_or_rev));
926
927         if (is_array($action)) {
928             $attr = $action;
929             $action = isset($attr['action']) ? $attr['action'] : 'browse';
930         }
931         else
932             $attr['action'] = $action;
933
934         $class = is_safe_action($action) ? 'wikiaction' : 'wikiadmin';
935         if ( !$label )
936             $label = $this->_labelForAction($action);
937
938         if ($version)
939             $attr['version'] = $version;
940
941         if ($action == 'browse')
942             unset($attr['action']);
943
944         $options = $this->fixAccesskey($options);
945
946         return $this->makeButton($label, WikiURL($pagename, $attr), $class, $options);
947     }
948     
949     function tooltipAccessKeyPrefix() {
950         static $tooltipAccessKeyPrefix = null;
951         if ($tooltipAccessKeyPrefix) return $tooltipAccessKeyPrefix;
952
953         $tooltipAccessKeyPrefix = 'alt';
954         if (isBrowserOpera()) $tooltipAccessKeyPrefix = 'shift-esc';
955         elseif (isBrowserSafari() or browserDetect("Mac") or isBrowserKonqueror()) 
956             $tooltipAccessKeyPrefix = 'ctrl';
957         // ff2 win and x11 only
958         elseif ((browserDetect("firefox/2") or browserDetect("minefield/3") or browserDetect("SeaMonkey/1.1")) 
959                 and ((browserDetect("windows") or browserDetect("x11"))))
960             $tooltipAccessKeyPrefix = 'alt-shift'; 
961         return $tooltipAccessKeyPrefix;
962     }
963
964     /** Define the accesskey in the title only, with ending [p] or [alt-p].
965      *  This fixes the prefix in the title and sets the accesskey.
966      */
967     function fixAccesskey($attrs) {
968         if (!empty($attrs['title']) and preg_match("/\[(alt-)?(.)\]$/", $attrs['title'], $m))
969         {
970             if (empty($attrs['accesskey'])) $attrs['accesskey'] = $m[2];
971             // firefox 'alt-shift', MSIE: 'alt', ... see wikibits.js
972             $attrs['title'] = preg_replace("/\[(alt-)?(.)\]$/", "[".$this->tooltipAccessKeyPrefix()."-\\2]", $attrs['title']);
973         }
974         return $attrs;
975     }
976     
977     /**
978      * Make a "button" which links to a wiki-page.
979      *
980      * These are really just regular WikiLinks, possibly
981      * disguised (e.g. behind an image button) by the theme.
982      *
983      * This method should probably only be used for links
984      * which appear in page navigation bars, or similar places.
985      *
986      * Use linkExistingWikiWord, or LinkWikiWord for normal links.
987      *
988      * @param $page_or_rev mixed The page to link to.  This can be
989      * given as a string (the page name), a WikiDB_Page object, or as
990      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
991      * object, the button will link to a specific version of the
992      * designated page, otherwise the button links to the most recent
993      * version of the page.
994      *
995      * @return object A Button object.
996      */
997     function makeLinkButton ($page_or_rev, $label = false, $action = false) {
998         extract($this->_get_name_and_rev($page_or_rev));
999
1000         $args = $version ? array('version' => $version) : false;
1001         if ($action) $args['action'] = $action;
1002
1003         return $this->makeButton($label ? $label : $pagename, 
1004                                  WikiURL($pagename, $args), 'wiki');
1005     }
1006
1007     function _get_name_and_rev ($page_or_rev) {
1008         $version = false;
1009
1010         if (empty($page_or_rev)) {
1011             global $request;
1012             $pagename = $request->getArg("pagename");
1013             $version = $request->getArg("version");
1014         }
1015         elseif (is_object($page_or_rev)) {
1016             if (isa($page_or_rev, 'WikiDB_PageRevision')) {
1017                 $rev = $page_or_rev;
1018                 $page = $rev->getPage();
1019                 if (!$rev->isCurrent()) $version = $rev->getVersion();
1020             }
1021             else {
1022                 $page = $page_or_rev;
1023             }
1024             $pagename = $page->getName();
1025         }
1026         elseif (is_numeric($page_or_rev)) {
1027             $version = $page_or_rev;
1028         }
1029         else {
1030             $pagename = (string) $page_or_rev;
1031         }
1032         return compact('pagename', 'version');
1033     }
1034
1035     function _labelForAction ($action) {
1036         switch ($action) {
1037             case 'edit':   return _("Edit");
1038             case 'diff':   return _("Diff");
1039             case 'logout': return _("Sign Out");
1040             case 'login':  return _("Sign In");
1041             case 'rename': return _("Rename Page");
1042             case 'lock':   return _("Lock Page");
1043             case 'unlock': return _("Unlock Page");
1044             case 'remove': return _("Remove Page");
1045             case 'purge':  return _("Purge Page");
1046             default:
1047                 // I don't think the rest of these actually get used.
1048                 // 'setprefs'
1049                 // 'upload' 'dumpserial' 'loadfile' 'zip'
1050                 // 'save' 'browse'
1051                 return gettext(ucfirst($action));
1052         }
1053     }
1054
1055     //----------------------------------------------------------------
1056     var $_buttonSeparator = "\n | ";
1057
1058     function setButtonSeparator($separator) {
1059         $this->_buttonSeparator = $separator;
1060     }
1061
1062     function getButtonSeparator() {
1063         return $this->_buttonSeparator;
1064     }
1065
1066
1067     ////////////////////////////////////////////////////////////////
1068     //
1069     // CSS
1070     //
1071     // Notes:
1072     //
1073     // Based on testing with Galeon 1.2.7 (Mozilla 1.2):
1074     // Automatic media-based style selection (via <link> tags) only
1075     // seems to work for the default style, not for alternate styles.
1076     //
1077     // Doing
1078     //
1079     //  <link rel="stylesheet" type="text/css" href="phpwiki.css" />
1080     //  <link rel="stylesheet" type="text/css" href="phpwiki-printer.css" media="print" />
1081     //
1082     // works to make it so that the printer style sheet get used
1083     // automatically when printing (or print-previewing) a page
1084     // (but when only when the default style is selected.)
1085     //
1086     // Attempts like:
1087     //
1088     //  <link rel="alternate stylesheet" title="Modern"
1089     //        type="text/css" href="phpwiki-modern.css" />
1090     //  <link rel="alternate stylesheet" title="Modern"
1091     //        type="text/css" href="phpwiki-printer.css" media="print" />
1092     //
1093     // Result in two "Modern" choices when trying to select alternate style.
1094     // If one selects the first of those choices, one gets phpwiki-modern
1095     // both when browsing and printing.  If one selects the second "Modern",
1096     // one gets no CSS when browsing, and phpwiki-printer when printing.
1097     //
1098     // The Real Fix?
1099     // =============
1100     //
1101     // We should probably move to doing the media based style
1102     // switching in the CSS files themselves using, e.g.:
1103     //
1104     //  @import url(print.css) print;
1105     //
1106     ////////////////////////////////////////////////////////////////
1107
1108     function _CSSlink($title, $css_file, $media, $is_alt = false) {
1109         // Don't set title on default style.  This makes it clear to
1110         // the user which is the default (i.e. most supported) style.
1111         if ($is_alt and isBrowserKonqueror())
1112             return HTML();
1113         $link = HTML::link(array('rel'     => $is_alt ? 'alternate stylesheet' : 'stylesheet',
1114                                  'type'    => 'text/css',
1115                                  'charset' => $GLOBALS['charset'],
1116                                  'href'    => $this->_findData($css_file)));
1117         if ($is_alt)
1118             $link->setAttr('title', $title);
1119
1120         if ($media) 
1121             $link->setAttr('media', $media);
1122         if ($this->DUMP_MODE) {
1123             if (empty($this->dumped_css)) $this->dumped_css = array();
1124             if (!in_array($css_file,$this->dumped_css)) $this->dumped_css[] = $css_file;
1125             $link->setAttr('href', basename($link->getAttr('href')));
1126         }
1127         
1128         return $link;
1129     }
1130
1131     /** Set default CSS source for this theme.
1132      *
1133      * To set styles to be used for different media, pass a
1134      * hash for the second argument, e.g.
1135      *
1136      * $theme->setDefaultCSS('default', array('' => 'normal.css',
1137      *                                        'print' => 'printer.css'));
1138      *
1139      * If you call this more than once, the last one called takes
1140      * precedence as the default style.
1141      *
1142      * @param string $title Name of style (currently ignored, unless
1143      * you call this more than once, in which case, some of the style
1144      * will become alternate (rather than default) styles, and then their
1145      * titles will be used.
1146      *
1147      * @param mixed $css_files Name of CSS file, or hash containing a mapping
1148      * between media types and CSS file names.  Use a key of '' (the empty string)
1149      * to set the default CSS for non-specified media.  (See above for an example.)
1150      */
1151     function setDefaultCSS ($title, $css_files) {
1152         if (!is_array($css_files))
1153             $css_files = array('' => $css_files);
1154         // Add to the front of $this->_css
1155         unset($this->_css[$title]);
1156         $this->_css = array_merge(array($title => $css_files), $this->_css);
1157     }
1158
1159     /** Set alternate CSS source for this theme.
1160      *
1161      * @param string $title Name of style.
1162      * @param string $css_files Name of CSS file.
1163      */
1164     function addAlternateCSS ($title, $css_files) {
1165         if (!is_array($css_files))
1166             $css_files = array('' => $css_files);
1167         $this->_css[$title] = $css_files;
1168     }
1169
1170     /**
1171      * @return string HTML for CSS.
1172      */
1173     function getCSS () {
1174         $css = array();
1175         $is_alt = false;
1176         foreach ($this->_css as $title => $css_files) {
1177             ksort($css_files); // move $css_files[''] to front.
1178             foreach ($css_files as $media => $css_file) {
1179                 if (!empty($this->DUMP_MODE)) {
1180                     if ($media == 'print')
1181                         $css[] = $this->_CSSlink($title, $css_file, '', $is_alt);
1182                 } else {
1183                     $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt);
1184                 }
1185                 if ($is_alt) break;
1186             }
1187             $is_alt = true;
1188         }
1189         return HTML($css);
1190     }
1191
1192     function findTemplate ($name) {
1193         if ($tmp = $this->_findFile("templates/$name.tmpl", 1))
1194             return $this->_path . $tmp;
1195         else {
1196             $f1 = $this->file("templates/$name.tmpl");
1197             foreach ($this->_parents as $parent) {
1198                 if ($tmp = $parent->_findFile("templates/$name.tmpl", 1))
1199                     return $this->_path . $tmp;
1200             }
1201             trigger_error("$f1 not found", E_USER_ERROR);
1202             return false;
1203         }
1204     }
1205
1206     /**
1207      * Add a random header element to head
1208      * TODO: first css, then js. Maybe seperate it into addJSHeaders/addCSSHeaders
1209      * or use an optional type argument, and seperate it within _MoreHeaders[]
1210      */
1211     //$GLOBALS['request']->_MoreHeaders = array();
1212     function addMoreHeaders ($element) {
1213         $GLOBALS['request']->_MoreHeaders[] = $element;
1214         if (!empty($this->_headers_printed) and $this->_headers_printed) {
1215             trigger_error(_("Some action(page) wanted to add more headers, but they were already printed.")
1216                           ."\n". $element->asXML(),
1217                            E_USER_NOTICE);
1218         }
1219     }
1220
1221     /**
1222       * Singleton. Only called once, by the head template. See the warning above.
1223       */
1224     function getMoreHeaders () {
1225         global $request;
1226         // actionpages cannot add headers, because recursive template expansion
1227         // already expanded the head template before.
1228         $this->_headers_printed = 1;
1229         if (empty($request->_MoreHeaders))
1230             return '';
1231         $out = '';
1232         if (false and ($file = $this->_findData('delayed.js'))) {
1233             $request->_MoreHeaders[] = JavaScript('
1234 // Add a script element as a child of the body
1235 function downloadJSAtOnload() {
1236 var element = document.createElement("script");
1237 element.src = "' . $file . '";
1238 document.body.appendChild(element);
1239 }
1240 // Check for browser support of event handling capability
1241 if (window.addEventListener)
1242 window.addEventListener("load", downloadJSAtOnload, false);
1243 else if (window.attachEvent)
1244 window.attachEvent("onload", downloadJSAtOnload);
1245 else window.onload = downloadJSAtOnload;');
1246         }
1247         //$out = "<!-- More Headers -->\n";
1248         foreach ($request->_MoreHeaders as $h) {
1249             if (is_object($h))
1250                 $out .= printXML($h);
1251             else
1252                 $out .= "$h\n";
1253         }
1254         return $out;
1255     }
1256
1257     //$GLOBALS['request']->_MoreAttr = array();
1258     // new arg: named elements to be able to remove them. such as DoubleClickEdit for htmldumps
1259     function addMoreAttr ($tag, $name, $element) {
1260         global $request;
1261         // protect from duplicate attr (body jscript: themes, prefs, ...)
1262         static $_attr_cache = array();
1263         $hash = md5($tag."/".$element);
1264         if (!empty($_attr_cache[$hash])) return;
1265         $_attr_cache[$hash] = 1;
1266
1267         if (empty($request->_MoreAttr) or !is_array($request->_MoreAttr[$tag]))
1268             $request->_MoreAttr[$tag] = array($name => $element);
1269         else
1270             $request->_MoreAttr[$tag][$name] = $element;
1271     }
1272
1273     function getMoreAttr ($tag) {
1274         global $request;
1275         if (empty($request->_MoreAttr[$tag]))
1276             return '';
1277         $out = '';
1278         foreach ($request->_MoreAttr[$tag] as $name => $element) {
1279             if (is_object($element))
1280                 $out .= printXML($element);
1281             else
1282                 $out .= "$element";
1283         }
1284         return $out;
1285     }
1286
1287     /**
1288      * Common Initialisations
1289      */
1290
1291     /**
1292      * The ->load() method replaces the formerly global code in themeinfo.php.
1293      * This is run only once for the selected theme, and not for the parent themes.
1294      * Without this you would not be able to derive from other themes.
1295      */
1296     function load() {
1297
1298         $this->initGlobals();
1299         
1300         // CSS file defines fonts, colors and background images for this
1301         // style.  The companion '*-heavy.css' file isn't defined, it's just
1302         // expected to be in the same directory that the base style is in.
1303
1304         // This should result in phpwiki-printer.css being used when
1305         // printing or print-previewing with style "PhpWiki" or "MacOSX" selected.
1306         $this->setDefaultCSS('PhpWiki',
1307                              array(''      => 'phpwiki.css',
1308                                    'print' => 'phpwiki-printer.css'));
1309
1310         // This allows one to manually select "Printer" style (when browsing page)
1311         // to see what the printer style looks like.
1312         $this->addAlternateCSS(_("Printer"), 'phpwiki-printer.css', 'print, screen');
1313         $this->addAlternateCSS(_("Top & bottom toolbars"), 'phpwiki-topbottombars.css');
1314         $this->addAlternateCSS(_("Modern"), 'phpwiki-modern.css');
1315
1316         if (isBrowserIE()) {
1317             $this->addMoreHeaders($this->_CSSlink(0,
1318                                                   $this->_findFile('IEFixes.css'),'all'));
1319             $this->addMoreHeaders("\n");
1320         }
1321
1322         /**
1323          * The logo image appears on every page and links to the HomePage.
1324          */
1325         $this->addImageAlias('logo', WIKI_NAME . 'Logo.png');
1326         
1327         $this->addImageAlias('search', 'search.png');
1328
1329         /**
1330          * The Signature image is shown after saving an edited page. If this
1331          * is set to false then the "Thank you for editing..." screen will
1332          * be omitted.
1333          */
1334
1335         $this->addImageAlias('signature', WIKI_NAME . "Signature.png");
1336         // Uncomment this next line to disable the signature.
1337         //$this->addImageAlias('signature', false);
1338
1339         /*
1340          * Link icons.
1341          */
1342         $this->setLinkIcon('http');
1343         $this->setLinkIcon('https');
1344         $this->setLinkIcon('ftp');
1345         $this->setLinkIcon('mailto');
1346         $this->setLinkIcon('interwiki');
1347         $this->setLinkIcon('wikiuser');
1348         $this->setLinkIcon('*', 'url');
1349
1350         $this->setButtonSeparator("\n | ");
1351
1352         /**
1353          * WikiWords can automatically be split by inserting spaces between
1354          * the words. The default is to leave WordsSmashedTogetherLikeSo.
1355          */
1356         $this->setAutosplitWikiWords(false);
1357
1358         /**
1359          * Layout improvement with dangling links for mostly closed wiki's:
1360          * If false, only users with edit permissions will be presented the 
1361          * special wikiunknown class with "?" and Tooltip.
1362          * If true (default), any user will see the ?, but will be presented 
1363          * the PrintLoginForm on a click.
1364          */
1365         //$this->setAnonEditUnknownLinks(false);
1366
1367         /*
1368          * You may adjust the formats used for formatting dates and times
1369          * below.  (These examples give the default formats.)
1370          * Formats are given as format strings to PHP strftime() function See
1371          * http://www.php.net/manual/en/function.strftime.php for details.
1372          * Do not include the server's zone (%Z), times are converted to the
1373          * user's time zone.
1374          *
1375          * Suggestion for french: 
1376          *   $this->setDateFormat("%A %e %B %Y");
1377          *   $this->setTimeFormat("%H:%M:%S");
1378          * Suggestion for capable php versions, using the server locale:
1379          *   $this->setDateFormat("%x");
1380          *   $this->setTimeFormat("%X");
1381          */
1382         //$this->setDateFormat("%B %d, %Y");
1383         //$this->setTimeFormat("%I:%M %p");
1384
1385         /*
1386          * To suppress times in the "Last edited on" messages, give a
1387          * give a second argument of false:
1388          */
1389         //$this->setDateFormat("%B %d, %Y", false); 
1390
1391
1392         /**
1393          * Custom UserPreferences:
1394          * A list of name => _UserPreference class pairs.
1395          * Rationale: Certain themes should be able to extend the predefined list 
1396          * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1397          * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1398          * See themes/wikilens/themeinfo.php
1399          */
1400         //$this->customUserPreference(); 
1401
1402         /**
1403          * Register custom PageList type and define custom PageList classes.
1404          * Rationale: Certain themes should be able to extend the predefined list 
1405          * of pagelist types. E.g. certain plugins, like MostPopular might use 
1406          * info=pagename,hits,rating
1407          * which displays the rating column whenever the wikilens theme is active.
1408          * See themes/wikilens/themeinfo.php
1409          */
1410         //$this->addPageListColumn(); 
1411
1412     } // end of load
1413
1414     /**
1415      * Custom UserPreferences:
1416      * A list of name => _UserPreference class pairs.
1417      * Rationale: Certain themes should be able to extend the predefined list 
1418      * of preferences. Display/editing is done in the theme specific userprefs.tmpl
1419      * but storage/sanification/update/... must be extended to the Get/SetPreferences methods.
1420      * These values are just ignored if another theme is used.
1421      */
1422     function customUserPreferences($array) {
1423         global $customUserPreferenceColumns; // FIXME: really a global?
1424         if (empty($customUserPreferenceColumns)) $customUserPreferenceColumns = array();
1425         //array('wikilens' => new _UserPreference_wikilens());
1426         foreach ($array as $field => $prefobj) {
1427             $customUserPreferenceColumns[$field] = $prefobj;
1428         }
1429     }
1430
1431     /** addPageListColumn(array('rating' => new _PageList_Column_rating('rating', _("Rate"))))
1432      *  Register custom PageList types for special themes, like 
1433      *  'rating' for wikilens
1434      */
1435     function addPageListColumn ($array) {
1436         global $customPageListColumns;
1437         if (empty($customPageListColumns)) $customPageListColumns = array();
1438         foreach ($array as $column => $obj) {
1439             $customPageListColumns[$column] = $obj;
1440         }
1441     }
1442
1443     function initGlobals() {
1444         global $request;
1445         static $already = 0;
1446         if (!$already) {
1447             $script_url = deduce_script_name();
1448             if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
1449                 $script_url .= ("?start_debug=".$_GET['start_debug']);
1450             $folderArrowPath = dirname($this->_findData('images/folderArrowLoading.gif'));
1451             $pagename = $request->getArg('pagename');
1452             $js = "var data_path = '". javascript_quote_string(DATA_PATH) ."';\n"
1453                 // XSS warning with pagename
1454                 ."var pagename  = '". javascript_quote_string($pagename) ."';\n"
1455                 ."var script_url= '". javascript_quote_string($script_url) ."';\n"
1456                 ."var stylepath = data_path+'/".javascript_quote_string($this->_theme)."/';\n"
1457                 ."var folderArrowPath = '".javascript_quote_string($folderArrowPath)."';\n"
1458                 ."var use_path_info = " . (USE_PATH_INFO ? "true" : "false") .";\n";
1459             $this->addMoreHeaders(JavaScript($js));
1460             $already = 1;
1461         }
1462     }
1463
1464     // Works only on action=browse. Patch #970004 by pixels
1465     // Usage: call $WikiTheme->initDoubleClickEdit() from theme init or 
1466     // define ENABLE_DOUBLECLICKEDIT
1467     function initDoubleClickEdit() {
1468         if (!$this->HTML_DUMP_SUFFIX)
1469             $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';\""));
1470     }
1471
1472     // Immediate title search results via XMLHTML(HttpRequest)
1473     // by Bitflux GmbH, bitflux.ch. You need to install the livesearch.js seperately.
1474     // Google's or acdropdown is better.
1475     function initLiveSearch() {
1476         //subclasses of Sidebar will init this twice 
1477         static $already = 0;
1478         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1479             $this->addMoreAttr('body', 'LiveSearch', 
1480                                HTML::Raw(" onload=\"liveSearchInit()"));
1481             $this->addMoreHeaders(JavaScript('var liveSearchURI="'
1482                                              .WikiURL(_("TitleSearch"),false,true).'";'));
1483             $this->addMoreHeaders(JavaScript('', array
1484                                              ('src' => $this->_findData('livesearch.js'))));
1485             $already = 1;
1486         }
1487     }
1488
1489     // Immediate title search results via XMLHttpRequest
1490     // using the shipped moacdropdown js-lib
1491     function initMoAcDropDown() {
1492         //subclasses of Sidebar will init this twice 
1493         static $already = 0;
1494         if (!$this->HTML_DUMP_SUFFIX and !$already) {
1495             $dir = $this->_findData('moacdropdown');
1496             if (!DEBUG and ($css = $this->_findFile('moacdropdown/css/dropdown-min.css'))) {
1497                 $this->addMoreHeaders($this->_CSSlink(0, $css, 'all'));
1498             } else {
1499                 $this->addMoreHeaders(HTML::style(array('type' => 'text/css'), "  @import url( $dir/css/dropdown.css );\n"));
1500             }
1501             // if autocomplete_remote is used: (getobject2 also for calc. the showlist width)
1502             if (DEBUG) {
1503                 foreach (array("mobrowser.js","modomevent3.js","modomt.js",
1504                                "modomext.js","getobject2.js","xmlextras.js") as $js) 
1505                 {
1506                     $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/$js")));
1507                 }
1508                 $this->addMoreHeaders(JavaScript('', array('src' => "$dir/js/acdropdown.js")));
1509             } else {
1510                 // already in wikicommon-min.js
1511                 ; //$this->addMoreHeaders(JavaScript('', array('src' => DATA_PATH . "/themes/default/moacdropdown.js")));
1512             }
1513             /*
1514             // for local xmlrpc requests
1515             $xmlrpc_url = deduce_script_name();
1516             //if (1 or DATABASE_TYPE == 'dba')
1517             $xmlrpc_url = DATA_PATH . "/RPC2.php";
1518             if ((DEBUG & _DEBUG_REMOTE) and isset($_GET['start_debug']))
1519                 $xmlrpc_url .= ("?start_debug=".$_GET['start_debug']);
1520             $this->addMoreHeaders(JavaScript("var xmlrpc_url = '$xmlrpc_url'"));
1521             */
1522             $already = 1;
1523         }
1524     }
1525
1526     function calendarLink($date = false) {
1527         return $this->calendarBase() . SUBPAGE_SEPARATOR . 
1528                strftime("%Y-%m-%d", $date ? $date : time());
1529     }
1530
1531     function calendarBase() {
1532         static $UserCalPageTitle = false;
1533         global $request;
1534
1535         if (!$UserCalPageTitle) 
1536             $UserCalPageTitle = $request->_user->getId() . 
1537                                 SUBPAGE_SEPARATOR . _("Calendar");
1538         if (!$UserCalPageTitle)
1539             $UserCalPageTitle = (BLOG_EMPTY_DEFAULT_PREFIX ? '' 
1540                                  : ($request->_user->getId() . SUBPAGE_SEPARATOR)) . "Blog";
1541         return $UserCalPageTitle;
1542     }
1543
1544     function calendarInit($force = false) {
1545         $dbi = $GLOBALS['request']->getDbh();
1546         // display flat calender dhtml in the sidebar
1547         if ($force or $dbi->isWikiPage($this->calendarBase())) {
1548             $jslang = @$GLOBALS['LANG'];
1549             $this->addMoreHeaders
1550                 (
1551                  $this->_CSSlink(0, 
1552                                  $this->_findFile('jscalendar/calendar-phpwiki.css'), 'all'));
1553             $this->addMoreHeaders
1554                 (JavaScript('',
1555                             array('src' => $this->_findData('jscalendar/calendar'.(DEBUG?'':'_stripped').'.js'))));
1556             if (!($langfile = $this->_findData("jscalendar/lang/calendar-$jslang.js")))
1557                 $langfile = $this->_findData("jscalendar/lang/calendar-en.js");
1558             $this->addMoreHeaders(JavaScript('',array('src' => $langfile)));
1559             $this->addMoreHeaders
1560                 (JavaScript('',
1561                             array('src' => 
1562                                   $this->_findData('jscalendar/calendar-setup'.(DEBUG?'':'_stripped').'.js'))));
1563
1564             // Get existing date entries for the current user
1565             require_once("lib/TextSearchQuery.php");
1566             $iter = $dbi->titleSearch(new TextSearchQuery("^".$this->calendarBase().SUBPAGE_SEPARATOR, true, "auto"));
1567             $existing = array();
1568             while ($page = $iter->next()) {
1569                 if ($page->exists())
1570                     $existing[] = basename($page->_pagename);
1571             }
1572             if (!empty($existing)) {
1573                 $js_exist = '{"'.join('":1,"',$existing).'":1}';
1574                 //var SPECIAL_DAYS = {"2004-05-11":1,"2004-05-12":1,"2004-06-01":1}
1575                 $this->addMoreHeaders(JavaScript('
1576 /* This table holds the existing calender entries for the current user
1577  *  calculated from the database 
1578  */
1579
1580 var SPECIAL_DAYS = '.javascript_quote_string($js_exist).';
1581
1582 /* This function returns true if the date exists in SPECIAL_DAYS */
1583 function dateExists(date, y, m, d) {
1584     var year = date.getFullYear();
1585     m = m + 1;
1586     m = m < 10 ? "0" + m : m;  // integer, 0..11
1587     d = d < 10 ? "0" + d : d;  // integer, 1..31
1588     var date = year+"-"+m+"-"+d;
1589     var exists = SPECIAL_DAYS[date];
1590     if (!exists) return false;
1591     else return true;
1592 }
1593 // This is the actual date status handler. 
1594 // Note that it receives the date object as well as separate 
1595 // values of year, month and date.
1596 function dateStatusFunc(date, y, m, d) {
1597     if (dateExists(date, y, m, d)) return "existing";
1598     else return false;
1599 }
1600 '));
1601             }
1602             else {
1603                 $this->addMoreHeaders(JavaScript('
1604 function dateStatusFunc(date, y, m, d) { return false;}'));
1605             }
1606         }
1607     }
1608
1609     ////////////////////////////////////////////////////////////////
1610     //
1611     // Events
1612     //
1613     ////////////////////////////////////////////////////////////////
1614
1615     /**  CbUserLogin (&$request, $userid)
1616      * Callback when a user logs in
1617     */
1618     function CbUserLogin (&$request, $userid) {
1619         ; // do nothing
1620     }
1621
1622     /** CbNewUserEdit (&$request, $userid)
1623      * Callback when a new user creates or edits a page 
1624      */
1625     function CbNewUserEdit (&$request, $userid) {
1626         ; // i.e. create homepage with Template/UserPage
1627     }
1628
1629     /** CbNewUserLogin (&$request, $userid)
1630      * Callback when a "new user" logs in. 
1631      *  What is new? We only record changes, not logins.
1632      *  Should we track user actions?
1633      *  Let's say a new user is a user without homepage.
1634      */
1635     function CbNewUserLogin (&$request, $userid) {
1636         ; // do nothing
1637     }
1638
1639     /** CbUserLogout (&$request, $userid) 
1640      * Callback when a user logs out
1641      */
1642     function CbUserLogout (&$request, $userid) {
1643         ; // do nothing
1644     }
1645
1646 };
1647
1648
1649 /**
1650  * A class representing a clickable "button".
1651  *
1652  * In it's simplest (default) form, a "button" is just a link associated
1653  * with some sort of wiki-action.
1654  */
1655 class Button extends HtmlElement {
1656     /** Constructor
1657      *
1658      * @param $text string The text for the button.
1659      * @param $url string The url (href) for the button.
1660      * @param $class string The CSS class for the button.
1661      * @param $options array Additional attributes for the &lt;input&gt; tag.
1662      */
1663     function Button ($text, $url, $class=false, $options=false) {
1664         global $request;
1665         //php5 workaround
1666         if (check_php_version(5)) {
1667             $this->_init('a', array('href' => $url));
1668         } else {
1669             $this->__construct('a', array('href' => $url));
1670         }
1671         if ($class)
1672             $this->setAttr('class', $class);
1673         if ($request->getArg('frame'))
1674             $this->setAttr('target', '_top');
1675         if (!empty($options) and is_array($options)) {
1676             foreach ($options as $key => $val)
1677                 $this->setAttr($key, $val);
1678         }
1679         // Google honors this
1680         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1681             and !$request->_user->isAuthenticated())
1682             $this->setAttr('rel', 'nofollow');
1683         $this->pushContent($GLOBALS['WikiTheme']->maybeSplitWikiWord($text));
1684     }
1685
1686 };
1687
1688
1689 /**
1690  * A clickable image button.
1691  */
1692 class ImageButton extends Button {
1693     /** Constructor
1694      *
1695      * @param $text string The text for the button.
1696      * @param $url string The url (href) for the button.
1697      * @param $class string The CSS class for the button.
1698      * @param $img_url string URL for button's image.
1699      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1700      */
1701     function ImageButton ($text, $url, $class, $img_url, $img_attr=false) {
1702         $this->__construct('a', array('href' => $url));
1703         if ($class)
1704             $this->setAttr('class', $class);
1705         // Google honors this
1706         if (in_array(strtolower($text), array('edit','create','diff','pdf'))
1707             and !$GLOBALS['request']->_user->isAuthenticated())
1708             $this->setAttr('rel', 'nofollow');
1709
1710         if (!is_array($img_attr))
1711             $img_attr = array();
1712         $img_attr['src'] = $img_url;
1713         $img_attr['alt'] = $text;
1714         $img_attr['class'] = 'wiki-button';
1715         $img_attr['border'] = 0;
1716         $this->pushContent(HTML::img($img_attr));
1717     }
1718 };
1719
1720 /**
1721  * A class representing a form <samp>submit</samp> button.
1722  */
1723 class SubmitButton extends HtmlElement {
1724     /** Constructor
1725      *
1726      * @param $text string The text for the button.
1727      * @param $name string The name of the form field.
1728      * @param $class string The CSS class for the button.
1729      * @param $options array Additional attributes for the &lt;input&gt; tag.
1730      */
1731     function SubmitButton ($text, $name=false, $class=false, $options=false) {
1732         $this->__construct('input', array('type' => 'submit',
1733                                           'value' => $text));
1734         if ($name)
1735             $this->setAttr('name', $name);
1736         if ($class)
1737             $this->setAttr('class', $class);
1738         if (!empty($options)) {
1739             foreach ($options as $key => $val)
1740                 $this->setAttr($key, $val);
1741         }
1742     }
1743
1744 };
1745
1746
1747 /**
1748  * A class representing an image form <samp>submit</samp> button.
1749  */
1750 class SubmitImageButton extends SubmitButton {
1751     /** Constructor
1752      *
1753      * @param $text string The text for the button.
1754      * @param $name string The name of the form field.
1755      * @param $class string The CSS class for the button.
1756      * @param $img_url string URL for button's image.
1757      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1758      */
1759     function SubmitImageButton ($text, $name=false, $class=false, $img_url, $img_attr=false) {
1760         $this->__construct('input', array('type'  => 'image',
1761                                           'src'   => $img_url,
1762                                           'value' => $text,
1763                                           'alt'   => $text));
1764         if ($name)
1765             $this->setAttr('name', $name);
1766         if ($class)
1767             $this->setAttr('class', $class);
1768         if (!empty($img_attr)) {
1769             foreach ($img_attr as $key => $val)
1770                 $this->setAttr($key, $val);
1771         }
1772     }
1773
1774 };
1775
1776 /** 
1777  * A sidebar box with title and body, narrow fixed-width.
1778  * To represent abbrevated content of plugins, links or forms,
1779  * like "Getting Started", "Search", "Sarch Pagename", 
1780  * "Login", "Menu", "Recent Changes", "Last comments", "Last Blogs"
1781  * "Calendar"
1782  * ... See http://tikiwiki.org/
1783  *
1784  * Usage:
1785  * sidebar.tmpl:
1786  *   $menu = SidebarBox("Menu",HTML::dl(HTML::dt(...))); $menu->format();
1787  *   $menu = PluginSidebarBox("RecentChanges",array('limit'=>10)); $menu->format();
1788  */
1789 class SidebarBox {
1790
1791     function SidebarBox($title, $body) {
1792         require_once('lib/WikiPlugin.php');
1793         $this->title = $title;
1794         $this->body = $body;
1795     }
1796     function format() {
1797         return WikiPlugin::makeBox($this->title, $this->body);
1798     }
1799 }
1800
1801 /** 
1802  * A sidebar box for plugins.
1803  * Any plugin may provide a box($args=false, $request=false, $basepage=false)
1804  * method, with the help of WikiPlugin::makeBox()
1805  */
1806 class PluginSidebarBox extends SidebarBox {
1807
1808     var $_plugin, $_args = false, $_basepage = false;
1809
1810     function PluginSidebarBox($name, $args = false, $basepage = false) {
1811         require_once("lib/WikiPlugin.php");
1812
1813         $loader = new WikiPluginLoader();
1814         $plugin = $loader->getPlugin($name);
1815         if (!$plugin) {
1816             return $loader->_error(sprintf(_("Plugin %s: undefined"),
1817                                           $name));
1818         }/*
1819         if (!method_exists($plugin, 'box')) {
1820             return $loader->_error(sprintf(_("%s: has no box method"),
1821                                            get_class($plugin)));
1822         }*/
1823         $this->_plugin   =& $plugin;
1824         $this->_args     = $args ? $args : array();
1825         $this->_basepage = $basepage;
1826     }
1827
1828     function format($args = false) {
1829         return $this->_plugin->box($args ? array_merge($this->_args, $args) : $this->_args,
1830                                    $GLOBALS['request'], 
1831                                    $this->_basepage);
1832     }
1833 }
1834
1835 // Various boxes which are no plugins
1836 class RelatedLinksBox extends SidebarBox {
1837     function RelatedLinksBox($title = false, $body = '', $limit = 20) {
1838         global $request;
1839         $this->title = $title ? $title : _("Related Links");
1840         $this->body = HTML($body);
1841         $page = $request->getPage($request->getArg('pagename'));
1842         $revision = $page->getCurrentRevision();
1843         $page_content = $revision->getTransformedContent();
1844         //$cache = &$page->_wikidb->_cache;
1845         $counter = 0;
1846         $sp = HTML::Raw('&middot; ');
1847         foreach ($page_content->getWikiPageLinks() as $link) {
1848             $linkto = $link['linkto'];
1849             if (!$request->_dbi->isWikiPage($linkto)) continue;
1850             $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1851             $counter++;
1852             if ($limit and $counter > $limit) continue;
1853         }
1854     }
1855 }
1856
1857 class RelatedExternalLinksBox extends SidebarBox {
1858     function RelatedExternalLinksBox($title = false, $body = '', $limit = 20) {
1859         global $request;
1860         $this->title = $title ? $title : _("External Links");
1861         $this->body = HTML($body);
1862         $page = $request->getPage($request->getArg('pagename'));
1863         $cache = &$page->_wikidb->_cache;
1864         $counter = 0;
1865         $sp = HTML::Raw('&middot; ');
1866         foreach ($cache->getWikiPageLinks() as $link) {
1867             $linkto = $link['linkto'];
1868             if ($linkto) {
1869                 $this->body->pushContent($sp, WikiLink($linkto), HTML::br());
1870                 $counter++;
1871                 if ($limit and $counter > $limit) continue;
1872             }
1873         }
1874     }
1875 }
1876
1877 function listAvailableThemes() {
1878     $available_themes = array(); 
1879     $dir_root = 'themes';
1880     if (defined('PHPWIKI_DIR'))
1881         $dir_root = PHPWIKI_DIR . "/$dir_root";
1882     $dir = dir($dir_root);
1883     if ($dir) {
1884         while($entry = $dir->read()) {
1885             if (is_dir($dir_root.'/'.$entry) 
1886                 and file_exists($dir_root.'/'.$entry.'/themeinfo.php')) 
1887             {
1888                 array_push($available_themes, $entry);
1889             }
1890         }
1891         $dir->close();
1892     }
1893     return $available_themes;
1894 }
1895
1896 function listAvailableLanguages() {
1897     $available_languages = array('en');
1898     $dir_root = 'locale';
1899     if (defined('PHPWIKI_DIR'))
1900         $dir_root = PHPWIKI_DIR . "/$dir_root";
1901     if ($dir = dir($dir_root)) {
1902         while($entry = $dir->read()) {
1903             if (is_dir($dir_root."/".$entry) and is_dir($dir_root.'/'.$entry.'/LC_MESSAGES'))
1904             {
1905                 array_push($available_languages, $entry);
1906             }
1907         }
1908         $dir->close();
1909     }
1910     return $available_languages;
1911 }
1912
1913 // (c-file-style: "gnu")
1914 // Local Variables:
1915 // mode: php
1916 // tab-width: 8
1917 // c-basic-offset: 4
1918 // c-hanging-comment-ender-p: nil
1919 // indent-tabs-mode: nil
1920 // End:
1921 ?>