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