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