]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/Theme.php
New feature: Easier to run multiple wiks off of one set of code. Name
[SourceForge/phpwiki.git] / lib / Theme.php
1 <?php rcs_id('$Id: Theme.php,v 1.69 2003-12-05 01:32:28 carstenklapp Exp $');
2
3 require_once('lib/HtmlElement.php');
4
5
6 /**
7  * Make a link to a wiki page (in this wiki).
8  *
9  * This is a convenience function.
10  *
11  * @param mixed $page_or_rev
12  * Can be:<dl>
13  * <dt>A string</dt><dd>The page to link to.</dd>
14  * <dt>A WikiDB_Page object</dt><dd>The page to link to.</dd>
15  * <dt>A WikiDB_PageRevision object</dt><dd>A specific version of the page to link to.</dd>
16  * </dl>
17  *
18  * @param string $type
19  * One of:<dl>
20  * <dt>'unknown'</dt><dd>Make link appropriate for a non-existant page.</dd>
21  * <dt>'known'</dt><dd>Make link appropriate for an existing page.</dd>
22  * <dt>'auto'</dt><dd>Either 'unknown' or 'known' as appropriate.</dd>
23  * <dt>'button'</dt><dd>Make a button-style link.</dd>
24  * <dt>'if_known'</dt><dd>Only linkify if page exists.</dd>
25  * </dl>
26  * Unless $type of of the latter form, the link will be of class 'wiki', 'wikiunknown',
27  * 'named-wiki', or 'named-wikiunknown', as appropriate.
28  *
29  * @param mixed $label (string or XmlContent object)
30  * Label for the link.  If not given, defaults to the page name.
31  *
32  * @return XmlContent The link
33  */
34 function WikiLink ($page_or_rev, $type = 'known', $label = false) {
35     global $Theme, $request;
36
37     if ($type == 'button') {
38         return $Theme->makeLinkButton($page_or_rev, $label);
39     }
40
41     $version = false;
42     
43     if (isa($page_or_rev, 'WikiDB_PageRevision')) {
44         $version = $page_or_rev->getVersion();
45         $page = $page_or_rev->getPage();
46         $pagename = $page->getName();
47         $wikipage = $pagename;
48         $exists = true;
49     }
50     elseif (isa($page_or_rev, 'WikiDB_Page')) {
51         $page = $page_or_rev;
52         $pagename = $page->getName();
53         $wikipage = $pagename;
54     }
55     elseif (isa($page_or_rev, 'WikiPageName')) {
56         $wikipage = $page_or_rev;
57         $pagename = $wikipage->name;
58     }
59     else {
60         $wikipage = new WikiPageName($page_or_rev, $request->getPage());
61         $pagename = $wikipage->name;
62     }
63     
64     if (!is_string($wikipage) and !$wikipage->isValid('strict'))
65         return $Theme->linkBadWikiWord($wikipage, $label);
66     
67     if ($type == 'auto' or $type == 'if_known') {
68         if (isset($page)) {
69             $current = $page->getCurrentRevision();
70             $exists = ! $current->hasDefaultContents();
71         }
72         else {
73             $dbi = $request->getDbh();
74             $exists = $dbi->isWikiPage($wikipage->name);
75         }
76     }
77     elseif ($type == 'unknown') {
78         $exists = false;
79     }
80     else {
81         $exists = true;
82     }
83
84     // FIXME: this should be somewhere else, if really needed.
85     // WikiLink makes A link, not a string of fancy ones.
86     // (I think that the fancy split links are just confusing.)
87     // Todo: test external ImageLinks http://some/images/next.gif
88     if (isa($wikipage, 'WikiPageName') and !$label 
89         and strchr(substr($wikipage->shortName,1), SUBPAGE_SEPARATOR)) {
90         $parts = explode(SUBPAGE_SEPARATOR, $wikipage->shortName);
91         $last_part = array_pop($parts);
92         $sep = '';
93         $link = HTML::span();
94         foreach ($parts as $part) {
95             $path[] = $part;
96             $parent = join(SUBPAGE_SEPARATOR, $path);
97             if ($part)
98                 $link->pushContent($Theme->linkExistingWikiWord($parent, $sep . $part));
99             $sep = SUBPAGE_SEPARATOR;
100         }
101         if ($exists)
102             $link->pushContent($Theme->linkExistingWikiWord($wikipage, $sep . $last_part, $version));
103         else
104             $link->pushContent($Theme->linkUnknownWikiWord($wikipage, $last_part));
105         return $link;
106     }
107
108     if ($exists) {
109         return $Theme->linkExistingWikiWord($wikipage, $label, $version);
110     }
111     elseif ($type == 'if_known') {
112         if (!$label && isa($wikipage, 'WikiPageName'))
113             $label = $wikipage->shortName;
114         return HTML($label ? $label : $pagename);
115     }
116     else {
117         return $Theme->linkUnknownWikiWord($wikipage, $label);
118     }
119 }
120
121
122
123 /**
124  * Make a button.
125  *
126  * This is a convenience function.
127  *
128  * @param $action string
129  * One of <dl>
130  * <dt>[action]</dt><dd>Perform action (e.g. 'edit') on the selected page.</dd>
131  * <dt>[ActionPage]</dt><dd>Run the actionpage (e.g. 'BackLinks') on the selected page.</dd>
132  * <dt>'submit:'[name]</dt><dd>Make a form submission button with the given name.
133  *      ([name] can be blank for a nameless submit button.)</dd>
134  * <dt>a hash</dt><dd>Query args for the action. E.g.<pre>
135  *      array('action' => 'diff', 'previous' => 'author')
136  * </pre></dd>
137  * </dl>
138  *
139  * @param $label string
140  * A label for the button.  If ommited, a suitable default (based on the valued of $action)
141  * will be picked.
142  *
143  * @param $page_or_rev mixed
144  * Which page (& version) to perform the action on.
145  * Can be one of:<dl>
146  * <dt>A string</dt><dd>The pagename.</dd>
147  * <dt>A WikiDB_Page object</dt><dd>The page.</dd>
148  * <dt>A WikiDB_PageRevision object</dt><dd>A specific version of the page.</dd>
149  * </dl>
150  * ($Page_or_rev is ignored for submit buttons.)
151  */
152 function Button ($action, $label = false, $page_or_rev = false) {
153     global $Theme;
154
155     if (!is_array($action) && preg_match('/submit:(.*)/A', $action, $m))
156         return $Theme->makeSubmitButton($label, $m[1], $class = $page_or_rev);
157     else
158         return $Theme->makeActionButton($action, $label, $page_or_rev);
159 }
160
161
162 class Theme {
163     var $HTML_DUMP_SUFFIX = '';
164     function Theme ($theme_name = 'default') {
165         $this->_name = $theme_name;
166         $themes_dir = defined('PHPWIKI_DIR') ? PHPWIKI_DIR . "/themes" : "themes";
167
168         $this->_path  = defined('PHPWIKI_DIR') ? PHPWIKI_DIR . "/" : "";
169         $this->_theme = "themes/$theme_name";
170
171         if ($theme_name != 'default')
172             $this->_default_theme = new Theme;
173
174         $this->_css = array();
175     }
176
177     function file ($file) {
178         return $this->_path . "$this->_theme/$file";
179     }
180
181     function _findFile ($file, $missing_okay = false) {
182         if (file_exists($this->_path . "$this->_theme/$file"))
183             return "$this->_theme/$file";
184
185         // FIXME: this is a short-term hack.  Delete this after all files
186         // get moved into themes/...
187         if (file_exists($this->_path . $file))
188             return $file;
189
190
191         if (isset($this->_default_theme)) {
192             return $this->_default_theme->_findFile($file, $missing_okay);
193         }
194         else if (!$missing_okay) {
195             trigger_error("$file: not found", E_USER_NOTICE);
196         }
197         return false;
198     }
199
200     function _findData ($file, $missing_okay = false) {
201         $path = $this->_findFile($file, $missing_okay);
202         if (!$path)
203             return false;
204
205         if (defined('DATA_PATH'))
206             return DATA_PATH . "/$path";
207         return $path;
208     }
209
210     ////////////////////////////////////////////////////////////////
211     //
212     // Date and Time formatting
213     //
214     ////////////////////////////////////////////////////////////////
215
216     // Note:  Windows' implemetation of strftime does not include certain
217         // format specifiers, such as %e (for date without leading zeros).  In
218         // general, see:
219         // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_strftime.2c_.wcsftime.asp
220         // As a result, we have to use %d, and strip out leading zeros ourselves.
221
222     var $_dateFormat = "%B %d, %Y";
223     var $_timeFormat = "%I:%M %p";
224
225     var $_showModTime = true;
226
227     /**
228      * Set format string used for dates.
229      *
230      * @param $fs string Format string for dates.
231      *
232      * @param $show_mod_time bool If true (default) then times
233      * are included in the messages generated by getLastModifiedMessage(),
234      * otherwise, only the date of last modification will be shown.
235      */
236     function setDateFormat ($fs, $show_mod_time = true) {
237         $this->_dateFormat = $fs;
238         $this->_showModTime = $show_mod_time;
239     }
240
241     /**
242      * Set format string used for times.
243      *
244      * @param $fs string Format string for times.
245      */
246     function setTimeFormat ($fs) {
247         $this->_timeFormat = $fs;
248     }
249
250     /**
251      * Format a date.
252      *
253      * Any time zone offset specified in the users preferences is
254      * taken into account by this method.
255      *
256      * @param $time_t integer Unix-style time.
257      *
258      * @return string The date.
259      */
260     function formatDate ($time_t) {
261         global $request;
262         
263         $offset_time = $time_t + 3600 * $request->getPref('timeOffset');
264         // strip leading zeros from date elements (ie space followed by zero)
265         return preg_replace('/ 0/', ' ', 
266                             strftime($this->_dateFormat, $offset_time));
267     }
268
269     /**
270      * Format a date.
271      *
272      * Any time zone offset specified in the users preferences is
273      * taken into account by this method.
274      *
275      * @param $time_t integer Unix-style time.
276      *
277      * @return string The time.
278      */
279     function formatTime ($time_t) {
280         //FIXME: make 24-hour mode configurable?
281         global $request;
282         $offset_time = $time_t + 3600 * $request->getPref('timeOffset');
283         return preg_replace('/^0/', ' ',
284                             strtolower(strftime($this->_timeFormat, $offset_time)));
285     }
286
287     /**
288      * Format a date and time.
289      *
290      * Any time zone offset specified in the users preferences is
291      * taken into account by this method.
292      *
293      * @param $time_t integer Unix-style time.
294      *
295      * @return string The date and time.
296      */
297     function formatDateTime ($time_t) {
298         return $this->formatDate($time_t) . ' ' . $this->formatTime($time_t);
299     }
300
301     /**
302      * Format a (possibly relative) date.
303      *
304      * If enabled in the users preferences, this method might
305      * return a relative day (e.g. 'Today', 'Yesterday').
306      *
307      * Any time zone offset specified in the users preferences is
308      * taken into account by this method.
309      *
310      * @param $time_t integer Unix-style time.
311      *
312      * @return string The day.
313      */
314     function getDay ($time_t) {
315         global $request;
316         
317         if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($time_t))) {
318             return ucfirst($date);
319         }
320         return $this->formatDate($time_t);
321     }
322     
323     /**
324      * Format the "last modified" message for a page revision.
325      *
326      * @param $revision object A WikiDB_PageRevision object.
327      *
328      * @param $show_version bool Should the page version number
329      * be included in the message.  (If this argument is omitted,
330      * then the version number will be shown only iff the revision
331      * is not the current one.
332      *
333      * @return string The "last modified" message.
334      */
335     function getLastModifiedMessage ($revision, $show_version = 'auto') {
336         global $request;
337
338         // dates >= this are considered invalid.
339         if (! defined('EPOCH'))
340             define('EPOCH', 0); // seconds since ~ January 1 1970
341
342         $mtime = $revision->get('mtime');
343         if ($mtime <= EPOCH)
344             return fmt("Never edited.");
345
346         if ($show_version == 'auto')
347             $show_version = !$revision->isCurrent();
348
349         if ($request->getPref('relativeDates') && ($date = $this->_relativeDay($mtime))) {
350             if ($this->_showModTime)
351                 $date =  sprintf(_("%s at %s"),
352                                  $date, $this->formatTime($mtime));
353             
354             if ($show_version)
355                 return fmt("Version %s, saved %s.", $revision->getVersion(), $date);
356             else
357                 return fmt("Last edited %s.", $date);
358         }
359
360         if ($this->_showModTime)
361             $date = $this->formatDateTime($mtime);
362         else
363             $date = $this->formatDate($mtime);
364         
365         if ($show_version)
366             return fmt("Version %s, saved on %s.", $revision->getVersion(), $date);
367         else
368             return fmt("Last edited on %s.", $date);
369     }
370     
371     function _relativeDay ($time_t) {
372         global $request;
373         $offset = 3600 * $request->getPref('timeOffset');
374
375         $now = time() + $offset;
376         $today = localtime($now, true);
377         $time = localtime($time_t + $offset, true);
378
379         if ($time['tm_yday'] == $today['tm_yday'] && $time['tm_year'] == $today['tm_year'])
380             return _("today");
381         
382         // Note that due to daylight savings chages (and leap seconds), $now minus
383         // 24 hours is not guaranteed to be yesterday.
384         $yesterday = localtime($now - (12 + $today['tm_hour']) * 3600, true);
385         if ($time['tm_yday'] == $yesterday['tm_yday'] && $time['tm_year'] == $yesterday['tm_year'])
386             return _("yesterday");
387
388         return false;
389     }
390
391     ////////////////////////////////////////////////////////////////
392     //
393     // Hooks for other formatting
394     //
395     ////////////////////////////////////////////////////////////////
396
397     //FIXME: PHP 4.1 Warnings
398     //lib/Theme.php:84: Notice[8]: The call_user_method() function is deprecated,
399     //use the call_user_func variety with the array(&$obj, "method") syntax instead
400
401     function getFormatter ($type, $format) {
402         $method = strtolower("get${type}Formatter");
403         if (method_exists($this, $method))
404             return $this->{$method}($format);
405         return false;
406     }
407
408     ////////////////////////////////////////////////////////////////
409     //
410     // Links
411     //
412     ////////////////////////////////////////////////////////////////
413
414     var $_autosplitWikiWords = false;
415
416     function setAutosplitWikiWords($autosplit=false) {
417         $this->_autosplitWikiWords = $autosplit ? true : false;
418     }
419
420     function maybeSplitWikiWord ($wikiword) {
421         if ($this->_autosplitWikiWords)
422             return split_pagename($wikiword);
423         else
424             return $wikiword;
425     }
426
427     function linkExistingWikiWord($wikiword, $linktext = '', $version = false) {
428         global $request;
429
430         if ($version !== false)
431             $url = WikiURL($wikiword, array('version' => $version));
432         else
433             $url = WikiURL($wikiword);
434
435         // Extra steps for dumping page to an html file.
436         // FIXME: shouldn't this be in WikiURL?
437         if ($this->HTML_DUMP_SUFFIX) {
438             // urlencode for pagenames with accented letters
439             $url = rawurlencode($url);
440             $url = preg_replace('/^\./', '%2e', $url);
441             $url .= $this->HTML_DUMP_SUFFIX;
442         }
443
444         $link = HTML::a(array('href' => $url));
445
446         if (isa($wikiword, 'WikiPageName'))
447             $default_text = $wikiword->shortName;
448         else
449             $default_text = $wikiword;
450         
451         if (!empty($linktext)) {
452             $link->pushContent($linktext);
453             $link->setAttr('class', 'named-wiki');
454             $link->setAttr('title', $this->maybeSplitWikiWord($default_text));
455         }
456         else {
457             $link->pushContent($this->maybeSplitWikiWord($default_text));
458             $link->setAttr('class', 'wiki');
459         }
460         if ($request->getArg('frame'))
461             $link->setAttr('target', '_top');
462         return $link;
463     }
464
465     function linkUnknownWikiWord($wikiword, $linktext = '') {
466         global $request;
467
468         // Get rid of anchors on unknown wikiwords
469         if (isa($wikiword, 'WikiPageName')) {
470             $default_text = $wikiword->shortName;
471             $wikiword = $wikiword->name;
472         }
473         else {
474             $default_text = $wikiword;
475         }
476         
477         $url = WikiURL($wikiword, array('action' => 'create'));
478
479         $button = $this->makeButton('?', $url);
480         $button->addTooltip(sprintf(_("Create: %s"), $wikiword));
481         $link = HTML::span($button);
482
483
484         if (!empty($linktext)) {
485             $link->pushContent(HTML::u($linktext));
486             $link->setAttr('class', 'named-wikiunknown');
487         }
488         else {
489             $link->pushContent(HTML::u($this->maybeSplitWikiWord($default_text)));
490             $link->setAttr('class', 'wikiunknown');
491         }
492         if ($request->getArg('frame'))
493             $link->setAttr('target', '_top');
494
495         return $link;
496     }
497
498     function linkBadWikiWord($wikiword, $linktext = '') {
499         global $ErrorManager;
500         
501         if ($linktext) {
502             $text = $linktext;
503         }
504         elseif (isa($wikiword, 'WikiPageName')) {
505             $text = $wikiword->shortName;
506         }
507         else {
508             $text = $wikiword;
509         }
510
511         if (isa($wikiword, 'WikiPageName'))
512             $message = $wikiword->getWarnings();
513         else
514             $message = sprintf(_("'%s': Bad page name"), $wikiword);
515         $ErrorManager->warning($message);
516         
517         return HTML::span(array('class' => 'badwikiword'), $text);
518     }
519     
520     ////////////////////////////////////////////////////////////////
521     //
522     // Images and Icons
523     //
524     ////////////////////////////////////////////////////////////////
525     var $_imageAliases = array();
526     var $_imageAlt = array();
527
528     /**
529      *
530      * (To disable an image, alias the image to <code>false</code>.
531      */
532     function addImageAlias ($alias, $image_name) {
533         // fall back to the PhpWiki-supplied image if not found
534         if ($this->_findFile("images/$image_name", true))
535             $this->_imageAliases[$alias] = $image_name;
536     }
537
538     function addImageAlt ($alias, $alt_text) {
539         $this->_imageAlt[$alias] = $alt_text;
540     }
541     function getImageAlt ($alias) {
542         return $this->_imageAlt[$alias];
543     }
544
545     function getImageURL ($image) {
546         $aliases = &$this->_imageAliases;
547
548         if (isset($aliases[$image])) {
549             $image = $aliases[$image];
550             if (!$image)
551                 return false;
552         }
553
554         // If not extension, default to .png.
555         if (!preg_match('/\.\w+$/', $image))
556             $image .= '.png';
557
558         // FIXME: this should probably be made to fall back
559         //        automatically to .gif, .jpg.
560         //        Also try .gif before .png if browser doesn't like png.
561
562         $path = $this->_findData("images/$image", 'missing okay');
563         if (!$path) // search explicit images/ or button/ links also
564             return $this->_findData("$image", 'missing okay');
565         else 
566             return $path;       
567     }
568
569     function setLinkIcon($proto, $image = false) {
570         if (!$image)
571             $image = $proto;
572
573         $this->_linkIcons[$proto] = $image;
574     }
575
576     function getLinkIconURL ($proto) {
577         $icons = &$this->_linkIcons;
578         if (!empty($icons[$proto]))
579             return $this->getImageURL($icons[$proto]);
580         elseif (!empty($icons['*']))
581             return $this->getImageURL($icons['*']);
582         return false;
583     }
584
585     function addButtonAlias ($text, $alias = false) {
586         $aliases = &$this->_buttonAliases;
587
588         if (is_array($text))
589             $aliases = array_merge($aliases, $text);
590         elseif ($alias === false)
591             unset($aliases[$text]);
592         else
593             $aliases[$text] = $alias;
594     }
595
596     function getButtonURL ($text) {
597         $aliases = &$this->_buttonAliases;
598         if (isset($aliases[$text]))
599             $text = $aliases[$text];
600
601         $qtext = urlencode($text);
602         $url = $this->_findButton("$qtext.png");
603         if ($url && strstr($url, '%')) {
604             $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
605         }
606         if (!$url) {// Jeff complained about png not supported everywhere. This is not PC
607             $url = $this->_findButton("$qtext.gif");
608             if ($url && strstr($url, '%')) {
609                 $url = preg_replace('|([^/]+)$|e', 'urlencode("\\1")', $url);
610             }
611         }
612         return $url;
613     }
614
615     function _findButton ($button_file) {
616         if (!isset($this->_button_path))
617             $this->_button_path = $this->_getButtonPath();
618
619         foreach ($this->_button_path as $dir) {
620             $path = "$this->_theme/$dir/$button_file";
621             if (file_exists($this->_path . $path))
622                 return defined('DATA_PATH') ? DATA_PATH . "/$path" : $path;
623         }
624         return false;
625     }
626
627     function _getButtonPath () {
628         $button_dir = $this->file("buttons");
629         if (!file_exists($button_dir) || !is_dir($button_dir))
630             return array();
631
632         $path = array('buttons');
633
634         $dir = dir($button_dir);
635         while (($subdir = $dir->read()) !== false) {
636             if ($subdir[0] == '.')
637                 continue;
638             if (is_dir("$button_dir/$subdir"))
639                 $path[] = "buttons/$subdir";
640         }
641         $dir->close();
642
643         return $path;
644     }
645
646     ////////////////////////////////////////////////////////////////
647     //
648     // Button style
649     //
650     ////////////////////////////////////////////////////////////////
651
652     function makeButton ($text, $url, $class = false) {
653         // FIXME: don't always try for image button?
654
655         // Special case: URLs like 'submit:preview' generate form
656         // submission buttons.
657         if (preg_match('/^submit:(.*)$/', $url, $m))
658             return $this->makeSubmitButton($text, $m[1], $class);
659
660         $imgurl = $this->getButtonURL($text);
661         if ($imgurl)
662             return new ImageButton($text, $url, $class, $imgurl);
663         else
664             return new Button($text, $url, $class);
665     }
666
667     function makeSubmitButton ($text, $name, $class = false) {
668         $imgurl = $this->getButtonURL($text);
669
670         if ($imgurl)
671             return new SubmitImageButton($text, $name, $class, $imgurl);
672         else
673             return new SubmitButton($text, $name, $class);
674     }
675
676     /**
677      * Make button to perform action.
678      *
679      * This constructs a button which performs an action on the
680      * currently selected version of the current page.
681      * (Or anotherpage or version, if you want...)
682      *
683      * @param $action string The action to perform (e.g. 'edit', 'lock').
684      * This can also be the name of an "action page" like 'LikePages'.
685      * Alternatively you can give a hash of query args to be applied
686      * to the page.
687      *
688      * @param $label string Textual label for the button.  If left empty,
689      * a suitable name will be guessed.
690      *
691      * @param $page_or_rev mixed  The page to link to.  This can be
692      * given as a string (the page name), a WikiDB_Page object, or as
693      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
694      * object, the button will link to a specific version of the
695      * designated page, otherwise the button links to the most recent
696      * version of the page.
697      *
698      * @return object A Button object.
699      */
700     function makeActionButton ($action, $label = false, $page_or_rev = false) {
701         extract($this->_get_name_and_rev($page_or_rev));
702
703         if (is_array($action)) {
704             $attr = $action;
705             $action = isset($attr['action']) ? $attr['action'] : 'browse';
706         }
707         else
708             $attr['action'] = $action;
709
710         $class = is_safe_action($action) ? 'wikiaction' : 'wikiadmin';
711         if (!$label)
712             $label = $this->_labelForAction($action);
713
714         if ($version)
715             $attr['version'] = $version;
716
717         if ($action == 'browse')
718             unset($attr['action']);
719
720         return $this->makeButton($label, WikiURL($pagename, $attr), $class);
721     }
722
723     /**
724      * Make a "button" which links to a wiki-page.
725      *
726      * These are really just regular WikiLinks, possibly
727      * disguised (e.g. behind an image button) by the theme.
728      *
729      * This method should probably only be used for links
730      * which appear in page navigation bars, or similar places.
731      *
732      * Use linkExistingWikiWord, or LinkWikiWord for normal links.
733      *
734      * @param $page_or_rev mixed The page to link to.  This can be
735      * given as a string (the page name), a WikiDB_Page object, or as
736      * WikiDB_PageRevision object.  If given as a WikiDB_PageRevision
737      * object, the button will link to a specific version of the
738      * designated page, otherwise the button links to the most recent
739      * version of the page.
740      *
741      * @return object A Button object.
742      */
743     function makeLinkButton ($page_or_rev, $label = false) {
744         extract($this->_get_name_and_rev($page_or_rev));
745
746         $args = $version ? array('version' => $version) : false;
747
748         return $this->makeButton($label ? $label : $this->maybeSplitWikiWord($pagename), 
749                                  WikiURL($pagename, $args), 'wiki');
750     }
751
752     function _get_name_and_rev ($page_or_rev) {
753         $version = false;
754
755         if (empty($page_or_rev)) {
756             global $request;
757             $pagename = $request->getArg("pagename");
758             $version = $request->getArg("version");
759         }
760         elseif (is_object($page_or_rev)) {
761             if (isa($page_or_rev, 'WikiDB_PageRevision')) {
762                 $rev = $page_or_rev;
763                 $page = $rev->getPage();
764                 $version = $rev->getVersion();
765             }
766             else {
767                 $page = $page_or_rev;
768             }
769             $pagename = $page->getName();
770         }
771         else {
772             $pagename = (string) $page_or_rev;
773         }
774         return compact('pagename', 'version');
775     }
776
777     function _labelForAction ($action) {
778         switch ($action) {
779             case 'edit':   return _("Edit");
780             case 'diff':   return _("Diff");
781             case 'logout': return _("Sign Out");
782             case 'login':  return _("Sign In");
783             case 'lock':   return _("Lock Page");
784             case 'unlock': return _("Unlock Page");
785             case 'remove': return _("Remove Page");
786             default:
787                 // I don't think the rest of these actually get used.
788                 // 'setprefs'
789                 // 'upload' 'dumpserial' 'loadfile' 'zip'
790                 // 'save' 'browse'
791                 return gettext(ucfirst($action));
792         }
793     }
794
795     //----------------------------------------------------------------
796     var $_buttonSeparator = "\n | ";
797
798     function setButtonSeparator($separator) {
799         $this->_buttonSeparator = $separator;
800     }
801
802     function getButtonSeparator() {
803         return $this->_buttonSeparator;
804     }
805
806
807     ////////////////////////////////////////////////////////////////
808     //
809     // CSS
810     //
811     // Notes:
812     //
813     // Based on testing with Galeon 1.2.7 (Mozilla 1.2):
814     // Automatic media-based style selection (via <link> tags) only
815     // seems to work for the default style, not for alternate styles.
816     //
817     // Doing
818     //
819     //  <link rel="stylesheet" type="text/css" href="phpwiki.css" />
820     //  <link rel="stylesheet" type="text/css" href="phpwiki-printer.css" media="print" />
821     //
822     // works to make it so that the printer style sheet get used
823     // automatically when printing (or print-previewing) a page
824     // (but when only when the default style is selected.)
825     //
826     // Attempts like:
827     //
828     //  <link rel="alternate stylesheet" title="Modern"
829     //        type="text/css" href="phpwiki-modern.css" />
830     //  <link rel="alternate stylesheet" title="Modern"
831     //        type="text/css" href="phpwiki-printer.css" media="print" />
832     //
833     // Result in two "Modern" choices when trying to select alternate style.
834     // If one selects the first of those choices, one gets phpwiki-modern
835     // both when browsing and printing.  If one selects the second "Modern",
836     // one gets no CSS when browsing, and phpwiki-printer when printing.
837     //
838     // The Real Fix?
839     // =============
840     //
841     // We should probably move to doing the media based style
842     // switching in the CSS files themselves using, e.g.:
843     //
844     //  @import url(print.css) print;
845     //
846     ////////////////////////////////////////////////////////////////
847
848     function _CSSlink($title, $css_file, $media, $is_alt = false) {
849         // Don't set title on default style.  This makes it clear to
850         // the user which is the default (i.e. most supported) style.
851         $link = HTML::link(array('rel'     => $is_alt ? 'alternate stylesheet' : 'stylesheet',
852                                  'type'    => 'text/css',
853                                  'charset' => CHARSET,
854                                  'href'    => $this->_findData($css_file)));
855         if ($is_alt)
856             $link->setAttr('title', $title);
857
858         if ($media) 
859             $link->setAttr('media', $media);
860         
861         return $link;
862     }
863
864     /** Set default CSS source for this theme.
865      *
866      * To set styles to be used for different media, pass a
867      * hash for the second argument, e.g.
868      *
869      * $theme->setDefaultCSS('default', array('' => 'normal.css',
870      *                                        'print' => 'printer.css'));
871      *
872      * If you call this more than once, the last one called takes
873      * precedence as the default style.
874      *
875      * @param string $title Name of style (currently ignored, unless
876      * you call this more than once, in which case, some of the style
877      * will become alternate (rather than default) styles, and then their
878      * titles will be used.
879      *
880      * @param mixed $css_files Name of CSS file, or hash containing a mapping
881      * between media types and CSS file names.  Use a key of '' (the empty string)
882      * to set the default CSS for non-specified media.  (See above for an example.)
883      */
884     function setDefaultCSS ($title, $css_files) {
885         if (!is_array($css_files))
886             $css_files = array('' => $css_files);
887         // Add to the front of $this->_css
888         unset($this->_css[$title]);
889         $this->_css = array_merge(array($title => $css_files), $this->_css);
890     }
891
892     /** Set alternate CSS source for this theme.
893      *
894      * @param string $title Name of style.
895      * @param string $css_files Name of CSS file.
896      */
897     function addAlternateCSS ($title, $css_files) {
898         if (!is_array($css_files))
899             $css_files = array('' => $css_files);
900         $this->_css[$title] = $css_files;
901     }
902
903     /**
904         * @return string HTML for CSS.
905      */
906     function getCSS () {
907         $css = array();
908         $is_alt = false;
909         foreach ($this->_css as $title => $css_files) {
910             ksort($css_files); // move $css_files[''] to front.
911             foreach ($css_files as $media => $css_file) {
912                 $css[] = $this->_CSSlink($title, $css_file, $media, $is_alt);
913                 if ($is_alt) break;
914                 
915             }
916             $is_alt = true;
917         }
918         return HTML($css);
919     }
920     
921
922     function findTemplate ($name) {
923         return $this->_path . $this->_findFile("templates/$name.tmpl");
924     }
925 };
926
927
928 /**
929  * A class representing a clickable "button".
930  *
931  * In it's simplest (default) form, a "button" is just a link associated
932  * with some sort of wiki-action.
933  */
934 class Button extends HtmlElement {
935     /** Constructor
936      *
937      * @param $text string The text for the button.
938      * @param $url string The url (href) for the button.
939      * @param $class string The CSS class for the button.
940      */
941     function Button ($text, $url, $class = false) {
942         global $request;
943         $this->HtmlElement('a', array('href' => $url));
944         if ($class)
945             $this->setAttr('class', $class);
946         if ($request->getArg('frame'))
947             $this->setAttr('target', '_top');
948         $this->pushContent($GLOBALS['Theme']->maybeSplitWikiWord($text));
949     }
950
951 };
952
953
954 /**
955  * A clickable image button.
956  */
957 class ImageButton extends Button {
958     /** Constructor
959      *
960      * @param $text string The text for the button.
961      * @param $url string The url (href) for the button.
962      * @param $class string The CSS class for the button.
963      * @param $img_url string URL for button's image.
964      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
965      */
966     function ImageButton ($text, $url, $class, $img_url, $img_attr = false) {
967         $this->HtmlElement('a', array('href' => $url));
968         if ($class)
969             $this->setAttr('class', $class);
970
971         if (!is_array($img_attr))
972             $img_attr = array();
973         $img_attr['src'] = $img_url;
974         $img_attr['alt'] = $text;
975         $img_attr['class'] = 'wiki-button';
976         $img_attr['border'] = 0;
977         $this->pushContent(HTML::img($img_attr));
978     }
979 };
980
981 /**
982  * A class representing a form <samp>submit</samp> button.
983  */
984 class SubmitButton extends HtmlElement {
985     /** Constructor
986      *
987      * @param $text string The text for the button.
988      * @param $name string The name of the form field.
989      * @param $class string The CSS class for the button.
990      */
991     function SubmitButton ($text, $name = false, $class = false) {
992         $this->HtmlElement('input', array('type' => 'submit',
993                                           'value' => $text));
994         if ($name)
995             $this->setAttr('name', $name);
996         if ($class)
997             $this->setAttr('class', $class);
998     }
999
1000 };
1001
1002
1003 /**
1004  * A class representing an image form <samp>submit</samp> button.
1005  */
1006 class SubmitImageButton extends SubmitButton {
1007     /** Constructor
1008      *
1009      * @param $text string The text for the button.
1010      * @param $name string The name of the form field.
1011      * @param $class string The CSS class for the button.
1012      * @param $img_url string URL for button's image.
1013      * @param $img_attr array Additional attributes for the &lt;img&gt; tag.
1014      */
1015     function SubmitImageButton ($text, $name = false, $class = false, $img_url) {
1016         $this->HtmlElement('input', array('type'  => 'image',
1017                                           'src'   => $img_url,
1018                                           'value' => $text,
1019                                           'alt'   => $text));
1020         if ($name)
1021             $this->setAttr('name', $name);
1022         if ($class)
1023             $this->setAttr('class', $class);
1024     }
1025
1026 };
1027
1028 // $Log: not supported by cvs2svn $
1029 // Revision 1.68  2003/03/04 01:53:30  dairiki
1030 // Inconsequential decrufting.
1031 //
1032 // Revision 1.67  2003/02/26 03:40:22  dairiki
1033 // New action=create.  Essentially the same as action=edit, except that if the
1034 // page already exists, it falls back to action=browse.
1035 //
1036 // This is for use in the "question mark" links for unknown wiki words
1037 // to avoid problems and confusion when following links from stale pages.
1038 // (If the "unknown page" has been created in the interim, the user probably
1039 // wants to view the page before editing it.)
1040 //
1041 // Revision 1.66  2003/02/26 00:10:26  dairiki
1042 // More/better/different checks for bad page names.
1043 //
1044 // Revision 1.65  2003/02/24 22:41:57  dairiki
1045 // Fix stupid typo.
1046 //
1047 // Revision 1.64  2003/02/24 22:06:14  dairiki
1048 // Attempts to fix auto-selection of printer CSS when printing.
1049 // See new comments lib/Theme.php for more details.
1050 // Also see SF patch #669563.
1051 //
1052 // Revision 1.63  2003/02/23 03:37:05  dairiki
1053 // Stupid typo/bug fix.
1054 //
1055 // Revision 1.62  2003/02/21 04:14:52  dairiki
1056 // New WikiLink type 'if_known'.  This gives linkified name if page
1057 // exists, otherwise, just plain text.
1058 //
1059 // Revision 1.61  2003/02/18 21:52:05  dairiki
1060 // Fix so that one can still link to wiki pages with # in their names.
1061 // (This was made difficult by the introduction of named tags, since
1062 // '[Page #1]' is now a link to anchor '1' in page 'Page'.
1063 //
1064 // Now the ~ escape for page names should work: [Page ~#1].
1065 //
1066 // Revision 1.60  2003/02/15 01:59:47  dairiki
1067 // Theme::getCSS():  Add Default-Style HTTP(-eqiv) header in attempt
1068 // to fix default stylesheet selection on some browsers.
1069 // For details on the Default-Style header, see:
1070 //  http://home.dairiki.org/docs/html4/present/styles.html#h-14.3.2
1071 //
1072 // Revision 1.59  2003/01/04 22:30:16  carstenklapp
1073 // New: display a "Never edited." message instead of an invalid epoch date.
1074 //
1075
1076 // (c-file-style: "gnu")
1077 // Local Variables:
1078 // mode: php
1079 // tab-width: 8
1080 // c-basic-offset: 4
1081 // c-hanging-comment-ender-p: nil
1082 // indent-tabs-mode: nil
1083 // End:
1084 ?>