]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPlugin.php
fix PageList with multiple lists: added id, fixed sortby REQUEST logic
[SourceForge/phpwiki.git] / lib / WikiPlugin.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiPlugin.php,v 1.65 2007-07-01 09:09:19 rurban Exp $');
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.65 $");
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             $argstr = substr($argstr, strlen($m[0]));
190
191             // Remove quotes from string values.
192             if ($qq_val)
193                 $val = stripslashes($qq_val);
194             elseif ($q_val)
195                 $val = stripslashes($q_val);
196             elseif ($gt_val)
197                 $val = _(stripslashes($gt_val));
198             else
199                 $val = $word_val;
200
201             if ($op == '=') {
202                 $args[$arg] = $val;
203             }
204             else {
205                 // NOTE: This does work for multiple args. Use the
206                 // separator character defined in your webserver
207                 // configuration, usually & or &amp; (See
208                 // http://www.htmlhelp.com/faq/cgifaq.4.html)
209                 // e.g. <plugin RecentChanges days||=1 show_all||=0 show_minor||=0>
210                 // url: RecentChanges?days=1&show_all=1&show_minor=0
211                 assert($op == '||=');
212                 $defaults[$arg] = $val;
213             }
214         }
215
216         if ($argstr) {
217            $this->handle_plugin_args_cruft($argstr, $args);
218         }
219
220         return array($args, $defaults);
221     }
222
223     /* A plugin can override this function to define how any remaining text is handled */
224     function handle_plugin_args_cruft($argstr, $args) {
225         trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"),
226                               $argstr), E_USER_NOTICE);
227     }
228     
229     /* A plugin can override this to allow undeclared arguments.
230        Or to silence the warning.
231      */
232     function allow_undeclared_arg($name, $value) {
233         trigger_error(sprintf(_("Argument '%s' not declared by plugin."),
234                               $name), E_USER_NOTICE);
235         return false;
236     }
237
238     /* handle plugin-list argument: use run(). */
239     function makeList($plugin_args, $request, $basepage) {
240         $dbi = $request->getDbh();
241         $pagelist = $this->run($dbi, $plugin_args, $request, $basepage);
242         $list = array();
243         if (is_object($pagelist) and isa($pagelist, 'PageList'))
244             return $pagelist->pageNames();
245         elseif (is_array($pagelist))
246             return $pagelist;
247         else    
248             return $list;
249     }
250
251     function getDefaultLinkArguments() {
252         return array('targetpage'  => $this->getName(),
253                      'linktext'    => $this->getName(),
254                      'description' => $this->getDescription(),
255                      'class'       => 'wikiaction');
256     }
257
258     function makeLink($argstr, $request) {
259         $defaults = $this->getDefaultArguments();
260         $link_defaults = $this->getDefaultLinkArguments();
261         $defaults = array_merge($defaults, $link_defaults);
262     
263         $args = $this->getArgs($argstr, $request, $defaults);
264         $plugin = $this->getName();
265     
266         $query_args = array();
267         foreach ($args as $arg => $val) {
268             if (isset($link_defaults[$arg]))
269                 continue;
270             if ($val != $defaults[$arg])
271                 $query_args[$arg] = $val;
272         }
273     
274         $link = Button($query_args, $args['linktext'], $args['targetpage']);
275         if (!empty($args['description']))
276             $link->addTooltip($args['description']);
277     
278         return $link;
279     }
280     
281     function getDefaultFormArguments() {
282         return array('targetpage' => $this->getName(),
283                      'buttontext' => $this->getName(),
284                      'class'      => 'wikiaction',
285                      'method'     => 'get',
286                      'textinput'  => 's',
287                      'description'=> $this->getDescription(),
288                      'formsize'   => 30);
289     }
290     
291     function makeForm($argstr, $request) {
292         $form_defaults = $this->getDefaultFormArguments();
293         $defaults = array_merge($form_defaults, 
294                                 array('start_debug' => $request->getArg('start_debug')),
295                                 $this->getDefaultArguments());
296     
297         $args = $this->getArgs($argstr, $request, $defaults);
298         $plugin = $this->getName();
299         $textinput = $args['textinput'];
300         assert(!empty($textinput) && isset($args['textinput']));
301     
302         $form = HTML::form(array('action' => WikiURL($args['targetpage']),
303                                  'method' => $args['method'],
304                                  'class'  => $args['class'],
305                                  'accept-charset' => $GLOBALS['charset']));
306         if (! USE_PATH_INFO ) {
307             $pagename = $request->get('pagename');
308             $form->pushContent(HTML::input(array('type' => 'hidden', 
309                                                  'name' => 'pagename', 
310                                                  'value' => $args['targetpage'])));
311         }
312         if ($args['targetpage'] != $this->getName()) {
313             $form->pushContent(HTML::input(array('type' => 'hidden', 
314                                                  'name' => 'action', 
315                                                  'value' => $this->getName())));
316         }
317         $contents = HTML::div();
318         $contents->setAttr('class', $args['class']);
319     
320         foreach ($args as $arg => $val) {
321             if (isset($form_defaults[$arg]))
322                 continue;
323             if ($arg != $textinput && $val == $defaults[$arg])
324                 continue;
325     
326             $i = HTML::input(array('name' => $arg, 'value' => $val));
327     
328             if ($arg == $textinput) {
329                 //if ($inputs[$arg] == 'file')
330                 //    $attr['type'] = 'file';
331                 //else
332                 $i->setAttr('type', 'text');
333                 $i->setAttr('size', $args['formsize']);
334                 if ($args['description'])
335                     $i->addTooltip($args['description']);
336             }
337             else {
338                 $i->setAttr('type', 'hidden');
339             }
340             $contents->pushContent($i);
341     
342             // FIXME: hackage
343             if ($i->getAttr('type') == 'file') {
344                 $form->setAttr('enctype', 'multipart/form-data');
345                 $form->setAttr('method', 'post');
346                 $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
347                                                          'value' => MAX_UPLOAD_SIZE,
348                                                          'type' => 'hidden')));
349             }
350         }
351     
352         if (!empty($args['buttontext']))
353             $contents->pushContent(HTML::input(array('type' => 'submit',
354                                                      'class' => 'button',
355                                                      'value' => $args['buttontext'])));
356         $form->pushContent($contents);
357         return $form;
358     }
359
360     // box is used to display a fixed-width, narrow version with common header
361     function box($args=false, $request=false, $basepage=false) {
362         if (!$request) $request =& $GLOBALS['request'];
363         $dbi = $request->getDbh();
364         return $this->makeBox('', $this->run($dbi, $args, $request, $basepage));
365     }
366
367     function makeBox($title, $body) {
368         if (!$title) $title = $this->getName();
369         return HTML::div(array('class'=>'box'),
370                          HTML::div(array('class'=>'box-title'), $title),
371                          HTML::div(array('class'=>'box-data'), $body));
372     }
373     
374     function error ($message) {
375         return HTML::div(array('class' => 'errors'),
376                         HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ',
377                         $message);
378     }
379
380     function disabled ($message='') {
381         $html[] = HTML::div(array('class' => 'title'),
382                             fmt("Plugin %s disabled.", $this->getName()),
383                             ' ', $message);
384         $html[] = HTML::pre($this->_pi);
385         return HTML::div(array('class' => 'disabled-plugin'), $html);
386     }
387
388     // TODO: Not really needed, since our plugins generally initialize their own 
389     // PageList object, which accepts options['types'].
390     // Register custom PageList types for special plugins, like 
391     // 'hi_content' for WikiAdminSearcheplace, 'renamed_pagename' for WikiAdminRename, ...
392     function addPageListColumn ($array) {
393         global $customPageListColumns;
394         if (empty($customPageListColumns)) $customPageListColumns = array();
395         foreach ($array as $column => $obj) {
396             $customPageListColumns[$column] = $obj;
397         }
398     }
399     
400     // provide a sample usage text for automatic edit-toolbar insertion
401     function getUsage() {
402         $args = $this->getDefaultArguments();
403         $string = '<'.'?plugin '.$this->getName().' ';
404         if ($args) {
405             foreach ($args as $key => $value) {
406                 $string .= ($key."||=".(string)$value." ");
407             }
408         }
409         return $string . '?'.'>';
410     }
411
412     function getArgumentsDescription() {
413         $arguments = HTML();
414         foreach ($this->getDefaultArguments() as $arg => $default) {
415             // Work around UserPreferences plugin to avoid error
416             if ((is_array($default))) {
417                 $default = '(array)';
418                 // This is a bit flawed with UserPreferences object
419                 //$default = sprintf("array('%s')",
420                 //                   implode("', '", array_keys($default)));
421             }
422             else
423                 if (stristr($default, ' '))
424                     $default = "'$default'";
425             $arguments->pushcontent("$arg=$default", HTML::br());
426         }
427         return $arguments;
428     }
429
430 }
431
432 class WikiPluginLoader {
433     var $_errors;
434
435     function expandPI($pi, &$request, &$markup, $basepage=false) {
436         if (!($ppi = $this->parsePi($pi)))
437             return false;
438         list($pi_name, $plugin, $plugin_args) = $ppi;
439
440         if (!is_object($plugin)) {
441             return new HtmlElement($pi_name == 'plugin-link' ? 'span' : 'p',
442                                    array('class' => 'plugin-error'),
443                                    $this->getErrorDetail());
444         }
445         switch ($pi_name) {
446             case 'plugin':
447                 // FIXME: change API for run() (no $dbi needed).
448                 $dbi = $request->getDbh();
449                 // pass the parsed CachedMarkup context in dbi to the plugin 
450                 // to be able to know about itself, or even to change the markup XmlTree (CreateToc)
451                 $dbi->_markup = &$markup; 
452                 // FIXME: could do better here...
453                 if (! $plugin->managesValidators()) {
454                     // Output of plugin (potentially) depends on
455                     // the state of the WikiDB (other than the current
456                     // page.)
457                     
458                     // Lacking other information, we'll assume things
459                     // changed last time the wikidb was touched.
460                     
461                     // As an additional hack, mark the ETag weak, since,
462                     // for all we know, the page might depend
463                     // on things other than the WikiDB (e.g. PhpWeather,
464                     // Calendar...)
465                     
466                     $timestamp = $dbi->getTimestamp();
467                     $request->appendValidators(array('dbi_timestamp' => $timestamp,
468                                                      '%mtime' => (int)$timestamp,
469                                                      '%weak' => true));
470                 }
471                 return $plugin->run($dbi, $plugin_args, $request, $basepage);
472             case 'plugin-list':
473                 return $plugin->makeList($plugin_args, $request, $basepage);
474             case 'plugin-link':
475                 return $plugin->makeLink($plugin_args, $request);
476             case 'plugin-form':
477                 return $plugin->makeForm($plugin_args, $request);
478         }
479     }
480
481     function getWikiPageLinks($pi, $basepage) {
482         if (!($ppi = $this->parsePi($pi)))
483             return false;
484         list($pi_name, $plugin, $plugin_args) = $ppi;
485         if (!is_object($plugin))
486             return false;
487         if ($pi_name != 'plugin')
488             return false;
489         return $plugin->getWikiPageLinks($plugin_args, $basepage);
490     }
491     
492     function parsePI($pi) {
493         if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m))
494             return $this->_error(sprintf("Bad %s", 'PI'));
495
496         list(, $pi_name, $plugin_name, $plugin_args) = $m;
497         $plugin = $this->getPlugin($plugin_name, $pi);
498
499         return array($pi_name, $plugin, $plugin_args);
500     }
501     
502     function getPlugin($plugin_name, $pi=false) {
503         global $ErrorManager;
504
505         // Note that there seems to be no way to trap parse errors
506         // from this include.  (At least not via set_error_handler().)
507         $plugin_source = "lib/plugin/$plugin_name.php";
508
509         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_plugin_error_filter'));
510         $plugin_class = "WikiPlugin_$plugin_name";
511         if (!class_exists($plugin_class)) {
512             // $include_failed = !@include_once("lib/plugin/$plugin_name.php");
513             $include_failed = !include_once("lib/plugin/$plugin_name.php");
514             $ErrorManager->popErrorHandler();
515             
516             if (!class_exists($plugin_class)) {
517                 if ($include_failed)
518                     return $this->_error(sprintf(_("Include of '%s' failed."),
519                                                  $plugin_source));
520                 return $this->_error(sprintf(_("%s: no such class"), $plugin_class));
521             }
522         }
523         $ErrorManager->popErrorHandler();
524         $plugin = new $plugin_class;
525         if (!is_subclass_of($plugin, "WikiPlugin"))
526             return $this->_error(sprintf(_("%s: not a subclass of WikiPlugin."),
527                                          $plugin_class));
528
529         $plugin->_pi = $pi;
530         return $plugin;
531     }
532
533     function _plugin_error_filter ($err) {
534         if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr))
535             return true;        // Ignore this error --- it's expected.
536         return false;
537     }
538
539     function getErrorDetail() {
540         return $this->_errors;
541     }
542
543     function _error($message) {
544         $this->_errors = $message;
545         return false;
546     }
547 };
548
549 // (c-file-style: "gnu")
550 // Local Variables:
551 // mode: php
552 // tab-width: 8
553 // c-basic-offset: 4
554 // c-hanging-comment-ender-p: nil
555 // indent-tabs-mode: nil
556 // End:
557 ?>