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