]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPlugin.php
Use global $AllAllowedPlugins
[SourceForge/phpwiki.git] / lib / WikiPlugin.php
1 <?php //-*-php-*-
2 rcs_id('$Id$');
3
4 class WikiPlugin
5 {
6     function getDefaultArguments() {
7         return array('description' => $this->getDescription());
8     }
9
10     /** Does the plugin manage its own HTTP validators?
11      *
12      * This should be overwritten by (some) individual plugins.
13      *
14      * If the output of the plugin is static, depending only
15      * on the plugin arguments, query arguments and contents
16      * of the current page, this can (and should) return true.
17      *
18      * If the plugin can deduce a modification time, or equivalent
19      * sort of tag for it's content, then the plugin should
20      * call $request->appendValidators() with appropriate arguments,
21      * and should override this method to return true.
22      *
23      * When in doubt, the safe answer here is false.
24      * Unfortunately, returning false here will most likely make
25      * any page which invokes the plugin uncacheable (by HTTP proxies
26      * or browsers).
27      */
28     function managesValidators() {
29         return false;
30     }
31     
32     // FIXME: args?
33     function run ($dbi, $argstr, &$request, $basepage) {
34         trigger_error("WikiPlugin::run: pure virtual function",
35                       E_USER_ERROR);
36     }
37
38     /** Get wiki-pages linked to by plugin invocation.
39      *
40      * A plugin may override this method to add pages to the
41      * link database for the invoking page.
42      *
43      * For example, the IncludePage plugin should override this so
44      * that the including page shows up in the backlinks list for the
45      * included page.
46      *
47      * Not all plugins which generate links to wiki-pages need list
48      * those pages here.
49      *
50      * Note also that currently the links are calculated at page save
51      * time, so only static page links (e.g. those dependent on the PI
52      * args, not the rest of the wikidb state or any request query args)
53      * will work correctly here.
54      *
55      * @param string $argstr The plugin argument string.
56      * @param string $basepage The pagename the plugin is invoked from.
57      * @return array List of pagenames linked to (or false).
58      */
59     function getWikiPageLinks ($argstr, $basepage) {
60         return false;
61     }
62     
63     /**
64      * Get name of plugin.
65      *
66      * This is used (by default) by getDefaultLinkArguments and
67      * getDefaultFormArguments to compute the default link/form
68      * targets.
69      *
70      * If you want to gettextify the name (probably a good idea),
71      * override this method in your plugin class, like:
72      * <pre>
73      *   function getName() { return _("MyPlugin"); }
74      * </pre>
75      *
76      * @return string plugin name/target.
77      */
78     function getName() {
79         return preg_replace('/^.*_/', '',  get_class($this));
80     }
81
82     function getDescription() {
83         return $this->getName();
84     }
85     
86     // plugins should override this with the commented-out code
87     function getVersion() {
88         return _("n/a");
89         //return preg_replace("/[Revision: $]/", '',
90         //                    "\$Revision: 1.67 $");
91     }
92
93     function getArgs($argstr, $request=false, $defaults=false) {
94         if ($defaults === false) {
95             $defaults = $this->getDefaultArguments();
96         }
97         //Fixme: on POST argstr is empty
98         list ($argstr_args, $argstr_defaults) = $this->parseArgStr($argstr);
99         $args = array();
100         if (!empty($defaults))
101           foreach ($defaults as $arg => $default_val) {
102             if (isset($argstr_args[$arg])) {
103                 $args[$arg] = $argstr_args[$arg];
104             } elseif ( $request and ($argval = $request->getArg($arg)) !== false ) {
105                 $args[$arg] = $argval;
106             } elseif (isset($argstr_defaults[$arg])) {
107                 $args[$arg] = (string) $argstr_defaults[$arg];
108             } else {
109                 $args[$arg] = $default_val;
110             }
111             // expand [arg]
112             if ($request and is_string($args[$arg]) and strstr($args[$arg], "[")) {
113                 $args[$arg] = $this->expandArg($args[$arg], $request);
114             }
115
116             unset($argstr_args[$arg]);
117             unset($argstr_defaults[$arg]);
118         }
119         
120         foreach (array_merge($argstr_args, $argstr_defaults) as $arg => $val) {
121             // TODO: where the heck comes this from? Put the new method over there and peace.
122             /*if ($request and $request->getArg('pagename') == _("PhpWikiAdministration") 
123                 and $arg == 'overwrite') // silence this warning
124                 ;*/
125             if ($this->allow_undeclared_arg($arg, $val))
126                 $args[$arg] = $val;
127         }
128
129         // Add special handling of pages and exclude args to accept <! plugin-list !>
130         // and split explodePageList($args['exclude']) => array()
131         // TODO : handle p[] pagehash
132         foreach (array('pages', 'exclude') as $key) {
133             if (!empty($args[$key]) and array_key_exists($key, $defaults))
134                 $args[$key] = is_string($args[$key])
135                     ? explodePageList($args[$key])
136                     : $args[$key]; // <! plugin-list !>
137         }
138
139         return $args;
140     }
141
142     // Patch by Dan F:
143     // Expand [arg] to $request->getArg("arg") unless preceded by ~
144     function expandArg($argval, &$request) {
145         // return preg_replace('/\[(\w[\w\d]*)\]/e', '$request->getArg("$1")',
146         // Replace the arg unless it is preceded by a ~
147         $ret = preg_replace('/([^~]|^)\[(\w[\w\d]*)\]/e',
148                             '"$1" . $request->getArg("$2")',
149                            $argval);
150         // Ditch the ~ so later versions can be expanded if desired
151         return preg_replace('/~(\[\w[\w\d]*\])/', '$1', $ret);
152     }
153
154     function parseArgStr($argstr) {
155         $args = array();
156         $defaults = array();
157         if (empty($argstr))
158             return array($args, $defaults);
159             
160         $arg_p = '\w+';
161         $op_p = '(?:\|\|)?=';
162         $word_p = '\S+';
163         $opt_ws = '\s*';
164         $qq_p = '" ( (?:[^"\\\\]|\\\\.)* ) "';
165         //"<--kludge for brain-dead syntax coloring
166         $q_p  = "' ( (?:[^'\\\\]|\\\\.)* ) '";
167         $gt_p = "_\\( $opt_ws $qq_p $opt_ws \\)";
168         $argspec_p = "($arg_p) $opt_ws ($op_p) $opt_ws (?: $qq_p|$q_p|$gt_p|($word_p))";
169
170         // handle plugin-list arguments seperately
171         $plugin_p = '<!plugin-list\s+\w+.*?!>';
172         while (preg_match("/^($arg_p) $opt_ws ($op_p) $opt_ws ($plugin_p) $opt_ws/x", $argstr, $m)) {
173             @ list(,$arg, $op, $plugin_val) = $m;
174             $argstr = substr($argstr, strlen($m[0]));
175             $loader = new WikiPluginLoader();
176             $markup = null;
177             $basepage = null;
178             $plugin_val = preg_replace(array("/^<!/","/!>$/"),array("<?","?>"),$plugin_val);
179             $val = $loader->expandPI($plugin_val, $GLOBALS['request'], $markup, $basepage);
180             if ($op == '=') {
181                 $args[$arg] = $val; // comma delimited pagenames or array()?
182             } else {
183                 assert($op == '||=');
184                 $defaults[$arg] = $val;
185             }
186         }
187         while (preg_match("/^$opt_ws $argspec_p $opt_ws/x", $argstr, $m)) {
188             //@ list(,$arg,$op,$qq_val,$q_val,$gt_val,$word_val) = $m;
189             $count = count($m);
190             if ($count >= 7) {
191                 list(, $arg, $op, $qq_val, $q_val, $gt_val, $word_val) = $m;
192             } elseif ($count == 6) {
193                 list(, $arg, $op, $qq_val, $q_val, $gt_val) = $m;
194             } elseif ($count == 5) {
195                 list(, $arg, $op, $qq_val, $q_val) = $m;
196             } elseif ($count == 4) {
197                 list(, $arg, $op, $qq_val) = $m;
198             }
199             $argstr = substr($argstr, strlen($m[0]));
200             // Remove quotes from string values.
201             if ($qq_val)
202                 $val = stripslashes($qq_val);
203             elseif ($count > 4 and $q_val)
204                 $val = stripslashes($q_val);
205             elseif ($count >= 6 and $gt_val)
206                 $val = _(stripslashes($gt_val));
207             elseif ($count >= 7)
208                 $val = $word_val;
209             else 
210                 $val = '';    
211
212             if ($op == '=') {
213                 $args[$arg] = $val;
214             }
215             else {
216                 // NOTE: This does work for multiple args. Use the
217                 // separator character defined in your webserver
218                 // configuration, usually & or &amp; (See
219                 // http://www.htmlhelp.com/faq/cgifaq.4.html)
220                 // e.g. <plugin RecentChanges days||=1 show_all||=0 show_minor||=0>
221                 // url: RecentChanges?days=1&show_all=1&show_minor=0
222                 assert($op == '||=');
223                 $defaults[$arg] = $val;
224             }
225         }
226
227         if ($argstr) {
228            $this->handle_plugin_args_cruft($argstr, $args);
229         }
230
231         return array($args, $defaults);
232     }
233
234     /* A plugin can override this function to define how any remaining text is handled */
235     function handle_plugin_args_cruft($argstr, $args) {
236         trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"),
237                               $argstr), E_USER_NOTICE);
238     }
239     
240     /* A plugin can override this to allow undeclared arguments.
241        Or to silence the warning.
242      */
243     function allow_undeclared_arg($name, $value) {
244         trigger_error(sprintf(_("Argument '%s' not declared by plugin."),
245                               $name), E_USER_NOTICE);
246         return false;
247     }
248
249     /* handle plugin-list argument: use run(). */
250     function makeList($plugin_args, $request, $basepage) {
251         $dbi = $request->getDbh();
252         $pagelist = $this->run($dbi, $plugin_args, $request, $basepage);
253         $list = array();
254         if (is_object($pagelist) and isa($pagelist, 'PageList'))
255             return $pagelist->pageNames();
256         elseif (is_array($pagelist))
257             return $pagelist;
258         else    
259             return $list;
260     }
261
262     function getDefaultLinkArguments() {
263         return array('targetpage'  => $this->getName(),
264                      'linktext'    => $this->getName(),
265                      'description' => $this->getDescription(),
266                      'class'       => 'wikiaction');
267     }
268
269     function getDefaultFormArguments() {
270         return array('targetpage' => $this->getName(),
271                      'buttontext' => $this->getName(),
272                      'class'      => 'wikiaction',
273                      'method'     => 'get',
274                      'textinput'  => 's',
275                      'description'=> $this->getDescription(),
276                      'formsize'   => 30);
277     }
278     
279     function makeForm($argstr, $request) {
280         $form_defaults = $this->getDefaultFormArguments();
281         $defaults = array_merge($form_defaults, 
282                                 array('start_debug' => $request->getArg('start_debug')),
283                                 $this->getDefaultArguments());
284     
285         $args = $this->getArgs($argstr, $request, $defaults);
286         $plugin = $this->getName();
287         $textinput = $args['textinput'];
288         assert(!empty($textinput) && isset($args['textinput']));
289     
290         $form = HTML::form(array('action' => WikiURL($args['targetpage']),
291                                  'method' => $args['method'],
292                                  'class'  => $args['class'],
293                                  'accept-charset' => $GLOBALS['charset']));
294         if (! USE_PATH_INFO ) {
295             $pagename = $request->get('pagename');
296             $form->pushContent(HTML::input(array('type' => 'hidden', 
297                                                  'name' => 'pagename', 
298                                                  'value' => $args['targetpage'])));
299         }
300         if ($args['targetpage'] != $this->getName()) {
301             $form->pushContent(HTML::input(array('type' => 'hidden', 
302                                                  'name' => 'action', 
303                                                  'value' => $this->getName())));
304         }
305         $contents = HTML::div();
306         $contents->setAttr('class', $args['class']);
307     
308         foreach ($args as $arg => $val) {
309             if (isset($form_defaults[$arg]))
310                 continue;
311             if ($arg != $textinput && $val == $defaults[$arg])
312                 continue;
313     
314             $i = HTML::input(array('name' => $arg, 'value' => $val));
315     
316             if ($arg == $textinput) {
317                 //if ($inputs[$arg] == 'file')
318                 //    $attr['type'] = 'file';
319                 //else
320                 $i->setAttr('type', 'text');
321                 $i->setAttr('size', $args['formsize']);
322                 if ($args['description'])
323                     $i->addTooltip($args['description']);
324             }
325             else {
326                 $i->setAttr('type', 'hidden');
327             }
328             $contents->pushContent($i);
329     
330             // FIXME: hackage
331             if ($i->getAttr('type') == 'file') {
332                 $form->setAttr('enctype', 'multipart/form-data');
333                 $form->setAttr('method', 'post');
334                 $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
335                                                          'value' => MAX_UPLOAD_SIZE,
336                                                          'type' => 'hidden')));
337             }
338         }
339     
340         if (!empty($args['buttontext']))
341             $contents->pushContent(HTML::input(array('type' => 'submit',
342                                                      'class' => 'button',
343                                                      'value' => $args['buttontext'])));
344         $form->pushContent($contents);
345         return $form;
346     }
347
348     // box is used to display a fixed-width, narrow version with common header
349     function box($args=false, $request=false, $basepage=false) {
350         if (!$request) $request =& $GLOBALS['request'];
351         $dbi = $request->getDbh();
352         return $this->makeBox('', $this->run($dbi, $args, $request, $basepage));
353     }
354
355     function makeBox($title, $body) {
356         if (!$title) $title = $this->getName();
357         return HTML::div(array('class'=>'box'),
358                          HTML::div(array('class'=>'box-title'), $title),
359                          HTML::div(array('class'=>'box-data'), $body));
360     }
361     
362     function error ($message) {
363         return HTML::div(array('class' => 'errors'),
364                         HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ',
365                         $message);
366     }
367
368     function disabled ($message='') {
369         $html[] = HTML::div(array('class' => 'title'),
370                             fmt("Plugin %s disabled.", $this->getName()),
371                             ' ', $message);
372         $html[] = HTML::pre($this->_pi);
373         return HTML::div(array('class' => 'disabled-plugin'), $html);
374     }
375
376     // TODO: Not really needed, since our plugins generally initialize their own 
377     // PageList object, which accepts options['types'].
378     // Register custom PageList types for special plugins, like 
379     // 'hi_content' for WikiAdminSearcheplace, 'renamed_pagename' for WikiAdminRename, ...
380     function addPageListColumn ($array) {
381         global $customPageListColumns;
382         if (empty($customPageListColumns)) $customPageListColumns = array();
383         foreach ($array as $column => $obj) {
384             $customPageListColumns[$column] = $obj;
385         }
386     }
387     
388     // provide a sample usage text for automatic edit-toolbar insertion
389     function getUsage() {
390         $args = $this->getDefaultArguments();
391         $string = '<<'.$this->getName().' ';
392         if ($args) {
393             foreach ($args as $key => $value) {
394                 $string .= ($key."||=".(string)$value." ");
395             }
396         }
397         return $string . '>>';
398     }
399
400     function getArgumentsDescription() {
401         $arguments = HTML();
402         foreach ($this->getDefaultArguments() as $arg => $default) {
403             // Work around UserPreferences plugin to avoid error
404             if ((is_array($default))) {
405                 $default = '(array)';
406                 // This is a bit flawed with UserPreferences object
407                 //$default = sprintf("array('%s')",
408                 //                   implode("', '", array_keys($default)));
409             }
410             else
411                 if (stristr($default, ' '))
412                     $default = "'$default'";
413             $arguments->pushcontent("$arg=$default", HTML::br());
414         }
415         return $arguments;
416     }
417
418 }
419
420 class WikiPluginLoader {
421     var $_errors;
422
423     function expandPI($pi, &$request, &$markup, $basepage=false) {
424         if (!($ppi = $this->parsePi($pi)))
425             return false;
426         list($pi_name, $plugin, $plugin_args) = $ppi;
427
428         if (!is_object($plugin)) {
429             return new HtmlElement('div',
430                                    array('class' => 'error'),
431                                    $this->getErrorDetail());
432         }
433         switch ($pi_name) {
434             case 'plugin':
435                 // FIXME: change API for run() (no $dbi needed).
436                 $dbi = $request->getDbh();
437                 // pass the parsed CachedMarkup context in dbi to the plugin 
438                 // to be able to know about itself, or even to change the markup XmlTree (CreateToc)
439                 $dbi->_markup = &$markup; 
440                 // FIXME: could do better here...
441                 if (! $plugin->managesValidators()) {
442                     // Output of plugin (potentially) depends on
443                     // the state of the WikiDB (other than the current
444                     // page.)
445                     
446                     // Lacking other information, we'll assume things
447                     // changed last time the wikidb was touched.
448                     
449                     // As an additional hack, mark the ETag weak, since,
450                     // for all we know, the page might depend
451                     // on things other than the WikiDB (e.g. PhpWeather,
452                     // Calendar...)
453                     
454                     $timestamp = $dbi->getTimestamp();
455                     $request->appendValidators(array('dbi_timestamp' => $timestamp,
456                                                      '%mtime' => (int)$timestamp,
457                                                      '%weak' => true));
458                 }
459                 return $plugin->run($dbi, $plugin_args, $request, $basepage);
460             case 'plugin-list':
461                 return $plugin->makeList($plugin_args, $request, $basepage);
462             case 'plugin-form':
463                 return $plugin->makeForm($plugin_args, $request);
464         }
465     }
466
467     function getWikiPageLinks($pi, $basepage) {
468         if (!($ppi = $this->parsePi($pi)))
469             return false;
470         list($pi_name, $plugin, $plugin_args) = $ppi;
471         if (!is_object($plugin))
472             return false;
473         if ($pi_name != 'plugin')
474             return false;
475         return $plugin->getWikiPageLinks($plugin_args, $basepage);
476     }
477     
478     function parsePI($pi) {
479         if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m))
480             return $this->_error(sprintf("Bad %s", 'PI'));
481
482         list(, $pi_name, $plugin_name, $plugin_args) = $m;
483         $plugin = $this->getPlugin($plugin_name, $pi);
484
485         return array($pi_name, $plugin, $plugin_args);
486     }
487     
488     function getPlugin($plugin_name, $pi=false) {
489         global $ErrorManager;
490         global $AllAllowedPlugins;
491
492         if (in_array($plugin_name, $AllAllowedPlugins) === false) {
493             return $this->_error(sprintf(_("Plugin '%s' does not exist."),
494                                          $plugin_name));
495         }
496
497         // Note that there seems to be no way to trap parse errors
498         // from this include.  (At least not via set_error_handler().)
499         $plugin_source = "lib/plugin/$plugin_name.php";
500
501         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_plugin_error_filter'));
502         $plugin_class = "WikiPlugin_$plugin_name";
503         if (!class_exists($plugin_class)) {
504             // $include_failed = !@include_once("lib/plugin/$plugin_name.php");
505             $include_failed = !include_once("lib/plugin/$plugin_name.php");
506             $ErrorManager->popErrorHandler();
507
508             if (!class_exists($plugin_class)) {
509                 if ($include_failed) {
510                     return $this->_error(sprintf(_("Plugin '%s' does not exist."),
511                                                  $plugin_name));
512                 }
513                 return $this->_error(sprintf(_("%s: no such class"), $plugin_class));
514             }
515         }
516         $ErrorManager->popErrorHandler();
517         $plugin = new $plugin_class;
518         if (!is_subclass_of($plugin, "WikiPlugin"))
519             return $this->_error(sprintf(_("%s: not a subclass of WikiPlugin."),
520                                          $plugin_class));
521
522         $plugin->_pi = $pi;
523         return $plugin;
524     }
525
526     function _plugin_error_filter ($err) {
527         if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr))
528             return true;        // Ignore this error --- it's expected.
529         return false;
530     }
531
532     function getErrorDetail() {
533         return $this->_errors;
534     }
535
536     function _error($message) {
537         $this->_errors = $message;
538         return false;
539     }
540 };
541
542 // (c-file-style: "gnu")
543 // Local Variables:
544 // mode: php
545 // tab-width: 8
546 // c-basic-offset: 4
547 // c-hanging-comment-ender-p: nil
548 // indent-tabs-mode: nil
549 // End:
550 ?>