]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/EditToolbar.php
Add () for new WikiPluginLoader
[SourceForge/phpwiki.git] / lib / EditToolbar.php
1 <?php
2
3 /* Copyright 2004-2010 $ThePhpWikiProgrammingTeam
4  * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * EDIT Toolbar Initialization.
25  * The default/themes/toolbar.js is from Mediawiki, this PHP is written from scratch.
26  *
27  * Features:
28  * - save-preview and formatting buttons from mediawiki
29  * - Search&Replace from walterzorn.de
30  * - pageinsert popup by Reini Urban (TODO: should be a pulldown, use acdropdown)
31  */
32
33 class EditToolbar
34 {
35
36     function EditToolbar()
37     {
38         global $WikiTheme;
39
40         $this->tokens = array();
41
42         //FIXME: enable Undo button for all other buttons also, not only the search/replace button
43         if (JS_SEARCHREPLACE) {
44             $this->tokens['JS_SEARCHREPLACE'] = 1;
45             $undo_btn = $WikiTheme->getImageURL("ed_undo.png");
46             $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png");
47             // JS_SEARCHREPLACE from walterzorn.de
48             $js = Javascript("
49 uri_undo_btn   = '" . $undo_btn . "'
50 msg_undo_alt   = '" . _("Undo") . "'
51 uri_undo_d_btn = '" . $undo_d_btn . "'
52 msg_undo_d_alt = '" . _("Undo disabled") . "'
53 msg_do_undo    = '" . _("Operation undone") . "'
54 msg_replfound  = '" . _("Substring \"\\1\" found \\2 times. Replace with \"\\3\"?") . "'
55 msg_replnot    = '" . _("String \"%s\" not found.") . "'
56 msg_repl_title     = '" . _("Search & Replace") . "'
57 msg_repl_search    = '" . _("Search for") . "'
58 msg_repl_replace_with = '" . _("Replace with") . "'
59 msg_repl_ok        = '" . _("OK") . "'
60 msg_repl_close     = '" . _("Close") . "'
61 ");
62             if (empty($WikiTheme->_headers_printed)) {
63                 $WikiTheme->addMoreHeaders($js);
64                 $WikiTheme->addMoreAttr('body', "SearchReplace", " onload='define_f()'");
65             } else { // from an actionpage: WikiBlog, AddComment, WikiForum
66                 printXML($js);
67             }
68         } else {
69             $WikiTheme->addMoreAttr('body', "editfocus", "document.getElementById('edit-content]').editarea.focus()");
70         }
71
72         if (ENABLE_EDIT_TOOLBAR) {
73             $js = JavaScript('', array('src' => $WikiTheme->_findData("toolbar.js")));
74             if (empty($WikiTheme->_headers_printed)) {
75                 $WikiTheme->addMoreHeaders($js);
76             } else { // from an actionpage: WikiBlog, AddComment, WikiForum
77                 printXML($js);
78                 printXML(JavaScript('define_f()'));
79             }
80         }
81
82         require_once 'lib/WikiPluginCached.php';
83         $cache = WikiPluginCached::newCache();
84         $dbi = $GLOBALS['request']->getDbh();
85         // regenerate if number of pages changes (categories, pages, templates)
86         $key = $dbi->numPages();
87         $key .= '+categories+plugin' . (isBrowserSafari() ? '+safari' : '');
88         if (TOOLBAR_PAGELINK_PULLDOWN) {
89             $key .= "+pages";
90         }
91         if (TOOLBAR_TEMPLATE_PULLDOWN) {
92             $key .= "+templates_" . $dbi->getTimestamp();
93         }
94         $id = $cache->generateId($key);
95         $content = $cache->get($id, 'toolbarcache');
96
97         if (!empty($content)) {
98             $this->tokens['EDIT_TOOLBAR'] =& $content;
99         } else {
100             $content = $this->_generate();
101             // regenerate buttons every 1 hr/6 hrs
102             $cache->save($id, $content, DEBUG ? '+3600' : '+21600', 'toolbarcache');
103             $this->tokens['EDIT_TOOLBAR'] =& $content;
104         }
105     }
106
107     function getTokens()
108     {
109         return $this->tokens;
110     }
111
112     function _generate()
113     {
114         global $WikiTheme, $request;
115
116         $toolbar = "document.writeln(\"<div class=\\\"edit-toolbar\\\" id=\\\"toolbar\\\">\");\n";
117
118         if (ENABLE_EDIT_TOOLBAR) {
119             $username = $request->_user->UserName();
120             if ((defined('FUSIONFORGE') and FUSIONFORGE) or DISABLE_MARKUP_WIKIWORD or (!isWikiWord($username))) {
121                 $username = '[[' . $username . ']]';
122             }
123             $signature = " ––" . $username . " " . CTime();
124             $toolarray = array(
125                 array(
126                     "image" => "ed_format_bold.png",
127                     "open" => "**",
128                     "close" => "**",
129                     "sample" => _("Bold text"),
130                     "title" => _("Bold text [alt-b]")),
131                 array("image" => "ed_format_italic.png",
132                     "open" => "//",
133                     "close" => "//",
134                     "sample" => _("Italic text"),
135                     "title" => _("Italic text [alt-i]")),
136                 array("image" => "ed_format_strike.png",
137                     "open" => "<s>",
138                     "close" => "</s>",
139                     "sample" => _("Strike-through text"),
140                     "title" => _("Strike")),
141                 array("image" => "ed_format_color.png",
142                     "open" => "%color=green% ",
143                     "close" => " %%",
144                     "sample" => _("Color text"),
145                     "title" => _("Color")),
146                 array("image" => "ed_pagelink.png",
147                     "open" => "[[",
148                     "close" => "]]",
149                     "sample" => _("PageName|optional label"),
150                     "title" => _("Link to page")),
151                 array("image" => "ed_link.png",
152                     "open" => "[[",
153                     "close" => "]]",
154                     "sample" => _("http://www.example.com|optional label"),
155                     "title" => _("External link (remember http:// prefix)")),
156                 array("image" => "ed_headline.png",
157                     "open" => "\\n== ",
158                     "close" => " ==\\n",
159                     "sample" => _("Headline text"),
160                     "title" => _("Level 1 headline")),
161                 array("image" => "ed_nowiki.png",
162                     "open" => "\\<verbatim\\>\\n",
163                     "close" => "\\n\\</verbatim\\>",
164                     "sample" => _("Insert non-formatted text here"),
165                     "title" => _("Ignore wiki formatting")),
166                 array("image" => "ed_sig.png",
167                     "open" => $signature,
168                     "close" => "",
169                     "sample" => "",
170                     "title" => _("Your signature")),
171                 array("image" => "ed_hr.png",
172                     "open" => "\\n----\\n",
173                     "close" => "",
174                     "sample" => "",
175                     "title" => _("Horizontal line")),
176                 array("image" => "ed_table.png",
177                     "open" => "\\n{| class=\"bordered\"\\n|+ This is the table caption\\n|= This is the table summary\\n|-\\n! Header A !! Header B !! Header C\\n|-\\n| Cell A1 || Cell B1 || Cell C1\\n|-\\n| Cell A2 || Cell B2 || Cell C2\\n|-\\n| Cell A3 || Cell B3 || Cell C3\\n|}\\n",
178                     "close" => "",
179                     "sample" => "",
180                     "title" => _("Sample table")),
181                 array("image" => "ed_enumlist.png",
182                     "open" => "\\n# Item 1\\n# Item 2\\n# Item 3\\n",
183                     "close" => "",
184                     "sample" => "",
185                     "title" => _("Enumeration")),
186                 array("image" => "ed_list.png",
187                     "open" => "\\n* Item 1\\n* Item 2\\n* Item 3\\n",
188                     "close" => "",
189                     "sample" => "",
190                     "title" => _("List")),
191                 array("image" => "ed_toc.png",
192                     "open" => "<<CreateToc with_toclink||=1>>\\n",
193                     "close" => "",
194                     "sample" => "",
195                     "title" => _("Table of Contents")),
196                 array("image" => "ed_redirect.png",
197                     "open" => "<<RedirectTo page=\"",
198                     "close" => "\">>",
199                     "sample" => _("Page Name"),
200                     "title" => _("Redirect")),
201                 array("image" => "ed_templateplugin.png",
202                     "open" => "{{",
203                     "close" => "}}",
204                     "sample" => _("Template Name"),
205                     "title" => _("Template"))
206             );
207             $btn = new SubmitImageButton(_("Save"), "edit[save]", 'toolbar',
208                 $WikiTheme->getImageURL("ed_save.png"));
209             $btn->addTooltip(_("Save"));
210             $btn->setAccesskey("s");
211             $toolbar .= ('document.writeln("' . addslashes($btn->asXml()) . '");' . "\n");
212             // preview not supported yet on Wikiblog
213             if (empty($WikiTheme->_headers_printed)) {
214                 $btn = new SubmitImageButton(_("Preview"), "edit[preview]", 'toolbar',
215                     $WikiTheme->getImageURL("ed_preview.png"));
216                 $btn->addTooltip(_("Preview"));
217                 $btn->setAccesskey("p");
218                 $toolbar .= ('document.writeln("' . addslashes($btn->asXml()) . '");' . "\n");
219             }
220
221             foreach ($toolarray as $tool) {
222                 $image = $WikiTheme->getImageURL($tool["image"]);
223                 $open = $tool["open"];
224                 $close = $tool["close"];
225                 $sample = addslashes($tool["sample"]);
226                 // Note that we use the title both for the ALT tag and the TITLE tag of the image.
227                 // Older browsers show a "speedtip" type message only for ALT.
228                 // Ideally these should be different, realistically they
229                 // probably don't need to be.
230                 $tool = $WikiTheme->fixAccesskey($tool);
231                 $title = addslashes($tool["title"]);
232                 $toolbar .= ("addTagButton('$image','$title','$open','$close','$sample');\n");
233             }
234             /* Fails with Chrome */
235             if (!isBrowserSafari()) {
236                 $toolbar .= ("addInfobox('"
237                     . addslashes(_("Click a button to get an example text"))
238                     . "');\n");
239             }
240         }
241
242         if (JS_SEARCHREPLACE) {
243             $undo_d_btn = $WikiTheme->getImageURL("ed_undo_d.png");
244             //$redo_btn = $WikiTheme->getImageURL("ed_redo.png");
245             $sr_btn = $WikiTheme->getImageURL("ed_replace.png");
246             //TODO: generalize the UNDO button and fix it for Search & Replace
247             $sr_html = HTML(HTML::img
248                 (array('class' => "toolbar",
249                     'id' => "sr_undo",
250                     'src' => $undo_d_btn,
251                     'title' => _("Undo Search & Replace"),
252                     'alt' => _("Undo Search & Replace"),
253                     //'disabled'=>"disabled",   //non-XHTML conform
254                     //'onfocus' =>"if(this.blur && undo_buffer_index==0) this.blur()",
255                     'onclick' => "do_undo()")),
256                 HTML::img
257                 (array('class' => "toolbar",
258                     'src' => $sr_btn,
259                     'alt' => _("Search & Replace"),
260                     'title' => _("Search & Replace"),
261                     'onclick' => "replace()")));
262         } else {
263             $sr_html = '';
264         }
265
266         //TODO: Delegate this to run-time with showing an hidden input at the right, and do
267         // a separate moacdropdown and xmlrpc:titleSearch.
268
269         // Button to generate categories, display in extra window as popup and insert
270         $sr_html = HTML($sr_html, $this->categoriesPulldown());
271         // Button to generate plugins, display in extra window as popup and insert
272         $sr_html = HTML($sr_html, $this->pluginPulldown());
273
274         // Button to generate pagenames, display in extra window as popup and insert
275         if (TOOLBAR_PAGELINK_PULLDOWN)
276             $sr_html = HTML($sr_html, $this->pagesPulldown(TOOLBAR_PAGELINK_PULLDOWN));
277         // Button to insert from an template, display pagename in extra window as popup and insert
278         if (TOOLBAR_TEMPLATE_PULLDOWN)
279             $sr_html = HTML($sr_html, $this->templatePulldown(TOOLBAR_TEMPLATE_PULLDOWN));
280
281         // Button to add images, display in extra window as popup and insert
282         if (TOOLBAR_IMAGE_PULLDOWN)
283             $sr_html = HTML($sr_html, $this->imagePulldown(TOOLBAR_IMAGE_PULLDOWN));
284
285         // don't use document.write for replace, otherwise self.opener is not defined.
286         $toolbar_end = "document.writeln(\"</div>\");";
287         if ($sr_html)
288             return HTML(Javascript($toolbar),
289                 "\n", $sr_html, "\n",
290                 Javascript($toolbar_end));
291         else
292             return HTML(Javascript($toolbar . $toolbar_end));
293     }
294
295     //result is cached
296     function categoriesPulldown()
297     {
298         global $WikiTheme;
299
300         require_once 'lib/TextSearchQuery.php';
301         $dbi =& $GLOBALS['request']->_dbi;
302         // KEYWORDS formerly known as $KeywordLinkRegexp
303         $pages = $dbi->titleSearch(new TextSearchQuery(KEYWORDS, true));
304         if ($pages) {
305             $categories = array();
306             while ($p = $pages->next()) {
307                 $page = $p->getName();
308                 if ((defined('FUSIONFORGE') and FUSIONFORGE)) {
309                     $categories[] = "['$page', '%0A----%0A%5B%5B" . $page . "%5D%5D']";
310                 } elseif (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page))) {
311                     $categories[] = "['$page', '%0A%5B" . $page . "%5D']";
312                 } else {
313                     $categories[] = "['$page', '%0A" . $page . "']";
314                 }
315             }
316             if (!$categories) return '';
317             // Ensure this to be inserted at the very end. Hence we added the id to the function.
318             $more_buttons = HTML::img(array('class' => "toolbar",
319                 'id' => 'tb-categories',
320                 'src' => $WikiTheme->getImageURL("ed_category.png"),
321                 'title' => _("Insert Categories"),
322                 'alt' => "Insert Categories", // to detect this at js
323                 'onclick' => "showPulldown('" .
324                     _("Insert Categories")
325                     . "',[" . join(",", $categories) . "],'"
326                     . _("Insert") . "','"
327                     . _("Close") . "','tb-categories')"));
328             return HTML("\n", $more_buttons);
329         }
330         return '';
331     }
332
333     // result is cached. Esp. the args are expensive
334     function pluginPulldown()
335     {
336         global $WikiTheme;
337         global $AllAllowedPlugins;
338
339         $plugin_dir = 'lib/plugin';
340         if (defined('PHPWIKI_DIR'))
341             $plugin_dir = PHPWIKI_DIR . "/$plugin_dir";
342         $pd = new fileSet($plugin_dir, '*.php');
343         $plugins = $pd->getFiles();
344         unset($pd);
345         sort($plugins);
346         if (!empty($plugins)) {
347             $plugin_js = '';
348             require_once 'lib/WikiPlugin.php';
349             $w = new WikiPluginLoader();
350             foreach ($plugins as $plugin) {
351                 $pluginName = str_replace(".php", "", $plugin);
352                 if (in_array($pluginName, $AllAllowedPlugins)) {
353                     $p = $w->getPlugin($pluginName, false); // second arg?
354                     // trap php files which aren't WikiPlugin~s
355                     if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
356                         $plugin_args = '';
357                         $desc = $p->getArgumentsDescription();
358                         $src = array("\n", '"', "'", '|', '[', ']', '\\');
359                         $replace = array('%0A', '%22', '%27', '%7C', '%5B', '%5D', '%5C');
360                         $desc = str_replace("<br />", ' ', $desc->asXML());
361                         if ($desc)
362                             $plugin_args = ' ' . str_replace($src, $replace, $desc);
363                         $toinsert = "%0A<<" . $pluginName . $plugin_args . ">>"; // args?
364                         $plugin_js .= ",['$pluginName','$toinsert']";
365                     }
366                 }
367             }
368             $plugin_js = substr($plugin_js, 1);
369             $more_buttons = HTML::img(array('class' => "toolbar",
370                 'id' => 'tb-plugins',
371                 'src' => $WikiTheme->getImageURL("ed_plugins.png"),
372                 'title' => _("Insert Plugin"),
373                 'alt' => _("Insert Plugin"),
374                 'onclick' => "showPulldown('" .
375                     _("Insert Plugin")
376                     . "',[" . $plugin_js . "],'"
377                     . _("Insert") . "','"
378                     . _("Close") . "','tb-plugins')"));
379             return HTML("\n", $more_buttons);
380         }
381         return '';
382     }
383
384     // result is cached. Esp. the args are expensive
385     function pagesPulldown($query, $case_exact = false, $regex = 'auto')
386     {
387         require_once 'lib/TextSearchQuery.php';
388         $dbi =& $GLOBALS['request']->_dbi;
389         $page_iter = $dbi->titleSearch(new TextSearchQuery($query, $case_exact, $regex));
390         if ($page_iter->count() > 0) {
391             global $WikiTheme;
392             $pages = array();
393             while ($p = $page_iter->next()) {
394                 $page = $p->getName();
395                 if (DISABLE_MARKUP_WIKIWORD or (!isWikiWord($page)))
396                     $pages[] = "['$page', '%5B" . $page . "%5D']";
397                 else
398                     $pages[] = "['$page', '$page']";
399             }
400             return HTML("\n", HTML::img(array('class' => "toolbar",
401                 'id' => 'tb-pages',
402                 'src' => $WikiTheme->getImageURL("ed_pages.png"),
403                 'title' => _("Insert PageLink"),
404                 'alt' => _("Insert PageLink"),
405                 'onclick' => "showPulldown('" .
406                     _("Insert PageLink")
407                     . "',[" . join(",", $pages) . "],'"
408                     . _("Insert") . "','"
409                     . _("Close") . "','tb-pages')")));
410         }
411         return '';
412     }
413
414     // result is cached. Esp. the args are expensive
415     function imagePulldown($query, $case_exact = false, $regex = 'auto')
416     {
417         global $WikiTheme;
418
419         $image_dir = getUploadFilePath();
420         $pd = new fileSet($image_dir, '*');
421         $images = $pd->getFiles();
422         unset($pd);
423         if (UPLOAD_USERDIR) {
424             $image_dir .= "/" . $request->_user->_userid;
425             $pd = new fileSet($image_dir, '*');
426             $images = array_merge($images, $pd->getFiles());
427             unset($pd);
428         }
429         sort($images);
430         if (!empty($images)) {
431             $image_js = '';
432             foreach ($images as $image) {
433                 // Select only image and video files
434                 if (is_image($image) or is_video($image)) {
435                     $image_js .= ",['$image','{{" . $image . "}}']";
436                 }
437             }
438             $image_js = substr($image_js, 1);
439             $more_buttons = HTML::img(array('class' => "toolbar",
440                 'id' => 'tb-images',
441                 'src' => $WikiTheme->getImageURL("ed_image.png"),
442                 'title' => _("Insert Image or Video"),
443                 'alt' => _("Insert Image or Video"),
444                 'onclick' => "showPulldown('" .
445                     _("Insert Image or Video")
446                     . "',[" . $image_js . "],'"
447                     . _("Insert") . "','"
448                     . _("Close") . "','tb-images')"));
449             return HTML("\n", $more_buttons);
450         }
451         return '';
452     }
453
454     // result is cached. Esp. the args are expensive
455     // FIXME!
456     function templatePulldown($query, $case_exact = false, $regex = 'auto')
457     {
458         global $request;
459         require_once 'lib/TextSearchQuery.php';
460         $dbi =& $request->_dbi;
461         $page_iter = $dbi->titleSearch(new TextSearchQuery($query, $case_exact, $regex));
462         $count = 0;
463         if ($page_iter->count()) {
464             global $WikiTheme;
465             $pages_js = '';
466             while ($p = $page_iter->next()) {
467                 $rev = $p->getCurrentRevision();
468                 $toinsert = str_replace(array("\n", '"'), array('_nl', '_quot'), $rev->_get_content());
469                 //$toinsert = str_replace("\n",'\n',addslashes($rev->_get_content()));
470                 $pages_js .= ",['" . $p->getName() . "','_nl$toinsert']";
471             }
472             $pages_js = substr($pages_js, 1);
473             if (!empty($pages_js))
474                 return HTML("\n", HTML::img
475                 (array('class' => "toolbar",
476                     'id' => 'tb-templates',
477                     'src' => $WikiTheme->getImageURL("ed_template.png"),
478                     'title' => _("Insert Template"),
479                     'alt' => _("Insert Template"),
480                     'onclick' => "showPulldown('" .
481                         _("Insert Template")
482                         . "',[" . $pages_js . "],'"
483                         . _("Insert") . "','"
484                         . _("Close") . "','tb-templates')")));
485         }
486         return '';
487     }
488
489 }
490
491 // Local Variables:
492 // mode: php
493 // tab-width: 8
494 // c-basic-offset: 4
495 // c-hanging-comment-ender-p: nil
496 // indent-tabs-mode: nil
497 // End: