]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPlugin.php
fix plugin-list array
[SourceForge/phpwiki.git] / lib / WikiPlugin.php
1 <?php //-*-php-*-
2 rcs_id('$Id: WikiPlugin.php,v 1.55 2004-11-25 08:26:49 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.55 $");
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             if ($request and $request->getArg('pagename') == _("PhpWikiAdministration") 
122                 and $arg == 'overwrite') // silence this warning
123                 ;
124             else
125                 trigger_error(sprintf(_("argument '%s' not declared by plugin"),
126                                       $arg), E_USER_NOTICE);
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         // always override sortby,limit from the REQUEST. ignore defaults if defined as such.
140         foreach (array('sortby', 'limit') as $key) {
141             if (array_key_exists($key, $defaults)) {
142                 if ($val = $request->getArg($key))
143                     $args[$key] = $val;
144                 elseif (!empty($args[$key]))
145                     $GLOBALS['request']->setArg($val, $args[$val]);
146             }
147         }
148         return $args;
149     }
150
151     // Patch by Dan F:
152     // Expand [arg] to $request->getArg("arg") unless preceded by ~
153     function expandArg($argval, &$request) {
154         // return preg_replace('/\[(\w[\w\d]*)\]/e', '$request->getArg("$1")',
155         // Replace the arg unless it is preceded by a ~
156         $ret = preg_replace('/([^~]|^)\[(\w[\w\d]*)\]/e',
157                             '"$1" . $request->getArg("$2")',
158                            $argval);
159         // Ditch the ~ so later versions can be expanded if desired
160         return preg_replace('/~(\[\w[\w\d]*\])/', '$1', $ret);
161     }
162
163     function parseArgStr($argstr) {
164         $args = array();
165         $defaults = array();
166         if (empty($argstr))
167             return array($args,$defaults);
168             
169         $arg_p = '\w+';
170         $op_p = '(?:\|\|)?=';
171         $word_p = '\S+';
172         $opt_ws = '\s*';
173         $qq_p = '" ( (?:[^"\\\\]|\\\\.)* ) "';
174         //"<--kludge for brain-dead syntax coloring
175         $q_p  = "' ( (?:[^'\\\\]|\\\\.)* ) '";
176         $gt_p = "_\\( $opt_ws $qq_p $opt_ws \\)";
177         $argspec_p = "($arg_p) $opt_ws ($op_p) $opt_ws (?: $qq_p|$q_p|$gt_p|($word_p))";
178
179         // handle plugin-list arguments seperately
180         $plugin_p = '<!plugin-list\s+\w+.*?!>';
181         while (preg_match("/^($arg_p) $opt_ws ($op_p) $opt_ws ($plugin_p) $opt_ws/x", $argstr, $m)) {
182             @ list(,$arg, $op, $plugin_val) = $m;
183             $argstr = substr($argstr, strlen($m[0]));
184             $loader = new WikiPluginLoader();
185             $markup = null;
186             $basepage = null;
187             $plugin_val = preg_replace(array("/^<!/","/!>$/"),array("<?","?>"),$plugin_val);
188             $val = $loader->expandPI($plugin_val, $GLOBALS['request'], $markup, $basepage);
189             if ($op == '=') {
190                 $args[$arg] = $val; // comma delimited pagenames or array()?
191             } else {
192                 assert($op == '||=');
193                 $defaults[$arg] = $val;
194             }
195         }
196         while (preg_match("/^$opt_ws $argspec_p $opt_ws/x", $argstr, $m)) {
197             @ list(,$arg,$op,$qq_val,$q_val,$gt_val,$word_val) = $m;
198             $argstr = substr($argstr, strlen($m[0]));
199
200             // Remove quotes from string values.
201             if ($qq_val)
202                 $val = stripslashes($qq_val);
203             elseif ($q_val)
204                 $val = stripslashes($q_val);
205             elseif ($gt_val)
206                 $val = _(stripslashes($gt_val));
207             else
208                 $val = $word_val;
209
210             if ($op == '=') {
211                 $args[$arg] = $val;
212             }
213             else {
214                 // NOTE: This does work for multiple args. Use the
215                 // separator character defined in your webserver
216                 // configuration, usually & or &amp; (See
217                 // http://www.htmlhelp.com/faq/cgifaq.4.html)
218                 // e.g. <plugin RecentChanges days||=1 show_all||=0 show_minor||=0>
219                 // url: RecentChanges?days=1&show_all=1&show_minor=0
220                 assert($op == '||=');
221                 $defaults[$arg] = $val;
222             }
223         }
224
225         if ($argstr) {
226            $this->handle_plugin_args_cruft($argstr, $args);
227         }
228
229         return array($args, $defaults);
230     }
231
232     /* A plugin can override this function to define how any remaining text is handled */
233     function handle_plugin_args_cruft($argstr, $args) {
234         trigger_error(sprintf(_("trailing cruft in plugin args: '%s'"),
235                               $argstr), E_USER_NOTICE);
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             // table or list?
245             foreach ($pagelist->_pages as $page) {
246                 $list[] = $page->getName();
247             }
248         }
249         return $list;
250     }
251
252     function getDefaultLinkArguments() {
253         return array('targetpage'  => $this->getName(),
254                      'linktext'    => $this->getName(),
255                      'description' => $this->getDescription(),
256                      'class'       => 'wikiaction');
257     }
258
259     function makeLink($argstr, $request) {
260         $defaults = $this->getDefaultArguments();
261         $link_defaults = $this->getDefaultLinkArguments();
262         $defaults = array_merge($defaults, $link_defaults);
263     
264         $args = $this->getArgs($argstr, $request, $defaults);
265         $plugin = $this->getName();
266     
267         $query_args = array();
268         foreach ($args as $arg => $val) {
269             if (isset($link_defaults[$arg]))
270                 continue;
271             if ($val != $defaults[$arg])
272                 $query_args[$arg] = $val;
273         }
274     
275         $link = Button($query_args, $args['linktext'], $args['targetpage']);
276         if (!empty($args['description']))
277             $link->addTooltip($args['description']);
278     
279         return $link;
280     }
281     
282     function getDefaultFormArguments() {
283         return array('targetpage' => $this->getName(),
284                      'buttontext' => $this->getName(),
285                      'class'      => 'wikiaction',
286                      'method'     => 'get',
287                      'textinput'  => 's',
288                      'description'=> $this->getDescription(),
289                      'formsize'   => 30);
290     }
291     
292     function makeForm($argstr, $request) {
293         $form_defaults = $this->getDefaultFormArguments();
294         $defaults = array_merge($form_defaults, 
295                                 array('start_debug' => $request->getArg('start_debug')),
296                                 $this->getDefaultArguments());
297     
298         $args = $this->getArgs($argstr, $request, $defaults);
299         $plugin = $this->getName();
300         $textinput = $args['textinput'];
301         assert(!empty($textinput) && isset($args['textinput']));
302     
303         $form = HTML::form(array('action' => WikiURL($args['targetpage']),
304                                  'method' => $args['method'],
305                                  'class'  => $args['class'],
306                                  'accept-charset' => $GLOBALS['charset']));
307         if (! USE_PATH_INFO ) {
308             $pagename = $request->get('pagename');
309             $form->pushContent(HTML::input(array('type' => 'hidden', 
310                                                  'name' => 'pagename', 
311                                                  'value' => $args['targetpage'])));
312         }
313         if ($args['targetpage'] != $this->getName()) {
314             $form->pushContent(HTML::input(array('type' => 'hidden', 
315                                                  'name' => 'action', 
316                                                  'value' => $this->getName())));
317         }
318         $contents = HTML::div();
319         $contents->setAttr('class', $args['class']);
320     
321         foreach ($args as $arg => $val) {
322             if (isset($form_defaults[$arg]))
323                 continue;
324             if ($arg != $textinput && $val == $defaults[$arg])
325                 continue;
326     
327             $i = HTML::input(array('name' => $arg, 'value' => $val));
328     
329             if ($arg == $textinput) {
330                 //if ($inputs[$arg] == 'file')
331                 //    $attr['type'] = 'file';
332                 //else
333                 $i->setAttr('type', 'text');
334                 $i->setAttr('size', $args['formsize']);
335                 if ($args['description'])
336                     $i->addTooltip($args['description']);
337             }
338             else {
339                 $i->setAttr('type', 'hidden');
340             }
341             $contents->pushContent($i);
342     
343             // FIXME: hackage
344             if ($i->getAttr('type') == 'file') {
345                 $form->setAttr('enctype', 'multipart/form-data');
346                 $form->setAttr('method', 'post');
347                 $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
348                                                          'value' => MAX_UPLOAD_SIZE,
349                                                          'type' => 'hidden')));
350             }
351         }
352     
353         if (!empty($args['buttontext']))
354             $contents->pushContent(HTML::input(array('type' => 'submit',
355                                                      'class' => 'button',
356                                                      'value' => $args['buttontext'])));
357         $form->pushContent($contents);
358         return $form;
359     }
360
361     function makeBox($title,$body) {
362         if (!$title) $title = $this->_getName();
363         return HTML::div(array('class'=>'box'),
364                          HTML::div(array('class'=>'box-title'),$title),
365                          HTML::div(array('class'=>'box-data'),$body));
366     }
367     
368     function error ($message) {
369         return HTML::div(array('class' => 'errors'),
370                         HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ',
371                         $message);
372     }
373
374     function disabled ($message='') {
375         $html[] = HTML::div(array('class' => 'title'),
376                             fmt("Plugin %s disabled.", $this->getName()),
377                             ' ', $message);
378         $html[] = HTML::pre($this->_pi);
379         return HTML::div(array('class' => 'disabled-plugin'), $html);
380     }
381
382     // TODO: Not really needed, since our plugins generally initialize their own 
383     // PageList object, which accepts options['types'].
384     // Register custom PageList types for special plugins, like 
385     // 'hi_content' for WikiAdminSearcheplace, 'renamed_pagename' for WikiAdminRename, ...
386     function addPageListColumn ($array) {
387         global $customPageListColumns;
388         if (empty($customPageListColumns)) $customPageListColumns = array();
389         foreach ($array as $column => $obj) {
390             $customPageListColumns[$column] = $obj;
391         }
392     }
393     
394     // provide a sample usage text for automatic edit-toolbar insertion
395     function getUsage() {
396         $args = $this->getDefaultArguments();
397         $string = '<'.'?plugin '.$this->getName().' ';
398         if ($args) {
399             foreach ($args as $key => $value) {
400                 $string .= ($key."||=".(string)$value." ");
401             }
402         }
403         return $string . '?'.'>';
404     }
405 }
406
407 class WikiPluginLoader {
408     var $_errors;
409
410     function expandPI($pi, &$request, &$markup, $basepage=false) {
411         if (!($ppi = $this->parsePi($pi)))
412             return false;
413         list($pi_name, $plugin, $plugin_args) = $ppi;
414
415         if (!is_object($plugin)) {
416             return new HtmlElement($pi_name == 'plugin-link' ? 'span' : 'p',
417                                    array('class' => 'plugin-error'),
418                                    $this->getErrorDetail());
419         }
420         switch ($pi_name) {
421             case 'plugin':
422                 // FIXME: change API for run() (no $dbi needed).
423                 $dbi = $request->getDbh();
424                 // pass the parsed CachedMarkup context in dbi to the plugin 
425                 // to be able to know about itself, or even to change the markup XmlTree (CreateToc)
426                 $dbi->_markup = &$markup; 
427                 // FIXME: could do better here...
428                 if (! $plugin->managesValidators()) {
429                     // Output of plugin (potentially) depends on
430                     // the state of the WikiDB (other than the current
431                     // page.)
432                     
433                     // Lacking other information, we'll assume things
434                     // changed last time the wikidb was touched.
435                     
436                     // As an additional hack, mark the ETag weak, since,
437                     // for all we know, the page might depend
438                     // on things other than the WikiDB (e.g. PhpWeather,
439                     // Calendar...)
440                     
441                     $timestamp = $dbi->getTimestamp();
442                     $request->appendValidators(array('dbi_timestamp' => $timestamp,
443                                                      '%mtime' => (int)$timestamp,
444                                                      '%weak' => true));
445                 }
446                 return $plugin->run($dbi, $plugin_args, $request, $basepage);
447             case 'plugin-list':
448                 return $plugin->makeList($plugin_args, $request, $basepage);
449             case 'plugin-link':
450                 return $plugin->makeLink($plugin_args, $request);
451             case 'plugin-form':
452                 return $plugin->makeForm($plugin_args, $request);
453         }
454     }
455
456     function getWikiPageLinks($pi, $basepage) {
457         if (!($ppi = $this->parsePi($pi)))
458             return false;
459         list($pi_name, $plugin, $plugin_args) = $ppi;
460         if (!is_object($plugin))
461             return false;
462         if ($pi_name != 'plugin')
463             return false;
464         return $plugin->getWikiPageLinks($plugin_args, $basepage);
465     }
466     
467     function parsePI($pi) {
468         if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m))
469             return $this->_error(sprintf("Bad %s", 'PI'));
470
471         list(, $pi_name, $plugin_name, $plugin_args) = $m;
472         $plugin = $this->getPlugin($plugin_name, $pi);
473
474         return array($pi_name, $plugin, $plugin_args);
475     }
476     
477     function getPlugin($plugin_name, $pi=false) {
478         global $ErrorManager;
479
480         // Note that there seems to be no way to trap parse errors
481         // from this include.  (At least not via set_error_handler().)
482         $plugin_source = "lib/plugin/$plugin_name.php";
483
484         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_plugin_error_filter'));
485         $plugin_class = "WikiPlugin_$plugin_name";
486         if (!class_exists($plugin_class)) {
487             // $include_failed = !@include_once("lib/plugin/$plugin_name.php");
488             $include_failed = !include_once("lib/plugin/$plugin_name.php");
489             $ErrorManager->popErrorHandler();
490             
491             if (!class_exists($plugin_class)) {
492                 if ($include_failed)
493                     return $this->_error(sprintf(_("Include of '%s' failed"),
494                                                  $plugin_source));
495                 return $this->_error(sprintf(_("%s: no such class"), $plugin_class));
496             }
497         }
498         $ErrorManager->popErrorHandler();
499         $plugin = new $plugin_class;
500         if (!is_subclass_of($plugin, "WikiPlugin"))
501             return $this->_error(sprintf(_("%s: not a subclass of WikiPlugin"),
502                                          $plugin_class));
503
504         $plugin->_pi = $pi;
505         return $plugin;
506     }
507
508     function _plugin_error_filter ($err) {
509         if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr))
510             return true;        // Ignore this error --- it's expected.
511         return false;
512     }
513
514     function getErrorDetail() {
515         return $this->_errors;
516     }
517
518     function _error($message) {
519         $this->_errors = $message;
520         return false;
521     }
522 };
523
524 // (c-file-style: "gnu")
525 // Local Variables:
526 // mode: php
527 // tab-width: 8
528 // c-basic-offset: 4
529 // c-hanging-comment-ender-p: nil
530 // indent-tabs-mode: nil
531 // End:
532 ?>