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