]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/WikiPlugin.php
Activated Id substitution for Subversion
[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 makeLink($argstr, $request) {
270         $defaults = $this->getDefaultArguments();
271         $link_defaults = $this->getDefaultLinkArguments();
272         $defaults = array_merge($defaults, $link_defaults);
273     
274         $args = $this->getArgs($argstr, $request, $defaults);
275         $plugin = $this->getName();
276     
277         $query_args = array();
278         foreach ($args as $arg => $val) {
279             if (isset($link_defaults[$arg]))
280                 continue;
281             if ($val != $defaults[$arg])
282                 $query_args[$arg] = $val;
283         }
284     
285         $link = Button($query_args, $args['linktext'], $args['targetpage']);
286         if (!empty($args['description']))
287             $link->addTooltip($args['description']);
288     
289         return $link;
290     }
291     
292     function getDefaultFormArguments() {
293         return array('targetpage' => $this->getName(),
294                      'buttontext' => $this->getName(),
295                      'class'      => 'wikiaction',
296                      'method'     => 'get',
297                      'textinput'  => 's',
298                      'description'=> $this->getDescription(),
299                      'formsize'   => 30);
300     }
301     
302     function makeForm($argstr, $request) {
303         $form_defaults = $this->getDefaultFormArguments();
304         $defaults = array_merge($form_defaults, 
305                                 array('start_debug' => $request->getArg('start_debug')),
306                                 $this->getDefaultArguments());
307     
308         $args = $this->getArgs($argstr, $request, $defaults);
309         $plugin = $this->getName();
310         $textinput = $args['textinput'];
311         assert(!empty($textinput) && isset($args['textinput']));
312     
313         $form = HTML::form(array('action' => WikiURL($args['targetpage']),
314                                  'method' => $args['method'],
315                                  'class'  => $args['class'],
316                                  'accept-charset' => $GLOBALS['charset']));
317         if (! USE_PATH_INFO ) {
318             $pagename = $request->get('pagename');
319             $form->pushContent(HTML::input(array('type' => 'hidden', 
320                                                  'name' => 'pagename', 
321                                                  'value' => $args['targetpage'])));
322         }
323         if ($args['targetpage'] != $this->getName()) {
324             $form->pushContent(HTML::input(array('type' => 'hidden', 
325                                                  'name' => 'action', 
326                                                  'value' => $this->getName())));
327         }
328         $contents = HTML::div();
329         $contents->setAttr('class', $args['class']);
330     
331         foreach ($args as $arg => $val) {
332             if (isset($form_defaults[$arg]))
333                 continue;
334             if ($arg != $textinput && $val == $defaults[$arg])
335                 continue;
336     
337             $i = HTML::input(array('name' => $arg, 'value' => $val));
338     
339             if ($arg == $textinput) {
340                 //if ($inputs[$arg] == 'file')
341                 //    $attr['type'] = 'file';
342                 //else
343                 $i->setAttr('type', 'text');
344                 $i->setAttr('size', $args['formsize']);
345                 if ($args['description'])
346                     $i->addTooltip($args['description']);
347             }
348             else {
349                 $i->setAttr('type', 'hidden');
350             }
351             $contents->pushContent($i);
352     
353             // FIXME: hackage
354             if ($i->getAttr('type') == 'file') {
355                 $form->setAttr('enctype', 'multipart/form-data');
356                 $form->setAttr('method', 'post');
357                 $contents->pushContent(HTML::input(array('name' => 'MAX_FILE_SIZE',
358                                                          'value' => MAX_UPLOAD_SIZE,
359                                                          'type' => 'hidden')));
360             }
361         }
362     
363         if (!empty($args['buttontext']))
364             $contents->pushContent(HTML::input(array('type' => 'submit',
365                                                      'class' => 'button',
366                                                      'value' => $args['buttontext'])));
367         $form->pushContent($contents);
368         return $form;
369     }
370
371     // box is used to display a fixed-width, narrow version with common header
372     function box($args=false, $request=false, $basepage=false) {
373         if (!$request) $request =& $GLOBALS['request'];
374         $dbi = $request->getDbh();
375         return $this->makeBox('', $this->run($dbi, $args, $request, $basepage));
376     }
377
378     function makeBox($title, $body) {
379         if (!$title) $title = $this->getName();
380         return HTML::div(array('class'=>'box'),
381                          HTML::div(array('class'=>'box-title'), $title),
382                          HTML::div(array('class'=>'box-data'), $body));
383     }
384     
385     function error ($message) {
386         return HTML::div(array('class' => 'errors'),
387                         HTML::strong(fmt("Plugin %s failed.", $this->getName())), ' ',
388                         $message);
389     }
390
391     function disabled ($message='') {
392         $html[] = HTML::div(array('class' => 'title'),
393                             fmt("Plugin %s disabled.", $this->getName()),
394                             ' ', $message);
395         $html[] = HTML::pre($this->_pi);
396         return HTML::div(array('class' => 'disabled-plugin'), $html);
397     }
398
399     // TODO: Not really needed, since our plugins generally initialize their own 
400     // PageList object, which accepts options['types'].
401     // Register custom PageList types for special plugins, like 
402     // 'hi_content' for WikiAdminSearcheplace, 'renamed_pagename' for WikiAdminRename, ...
403     function addPageListColumn ($array) {
404         global $customPageListColumns;
405         if (empty($customPageListColumns)) $customPageListColumns = array();
406         foreach ($array as $column => $obj) {
407             $customPageListColumns[$column] = $obj;
408         }
409     }
410     
411     // provide a sample usage text for automatic edit-toolbar insertion
412     function getUsage() {
413         $args = $this->getDefaultArguments();
414         $string = '<'.'?plugin '.$this->getName().' ';
415         if ($args) {
416             foreach ($args as $key => $value) {
417                 $string .= ($key."||=".(string)$value." ");
418             }
419         }
420         return $string . '?'.'>';
421     }
422
423     function getArgumentsDescription() {
424         $arguments = HTML();
425         foreach ($this->getDefaultArguments() as $arg => $default) {
426             // Work around UserPreferences plugin to avoid error
427             if ((is_array($default))) {
428                 $default = '(array)';
429                 // This is a bit flawed with UserPreferences object
430                 //$default = sprintf("array('%s')",
431                 //                   implode("', '", array_keys($default)));
432             }
433             else
434                 if (stristr($default, ' '))
435                     $default = "'$default'";
436             $arguments->pushcontent("$arg=$default", HTML::br());
437         }
438         return $arguments;
439     }
440
441 }
442
443 class WikiPluginLoader {
444     var $_errors;
445
446     function expandPI($pi, &$request, &$markup, $basepage=false) {
447         if (!($ppi = $this->parsePi($pi)))
448             return false;
449         list($pi_name, $plugin, $plugin_args) = $ppi;
450
451         if (!is_object($plugin)) {
452             return new HtmlElement($pi_name == 'plugin-link' ? 'span' : 'p',
453                                    array('class' => 'plugin-error'),
454                                    $this->getErrorDetail());
455         }
456         switch ($pi_name) {
457             case 'plugin':
458                 // FIXME: change API for run() (no $dbi needed).
459                 $dbi = $request->getDbh();
460                 // pass the parsed CachedMarkup context in dbi to the plugin 
461                 // to be able to know about itself, or even to change the markup XmlTree (CreateToc)
462                 $dbi->_markup = &$markup; 
463                 // FIXME: could do better here...
464                 if (! $plugin->managesValidators()) {
465                     // Output of plugin (potentially) depends on
466                     // the state of the WikiDB (other than the current
467                     // page.)
468                     
469                     // Lacking other information, we'll assume things
470                     // changed last time the wikidb was touched.
471                     
472                     // As an additional hack, mark the ETag weak, since,
473                     // for all we know, the page might depend
474                     // on things other than the WikiDB (e.g. PhpWeather,
475                     // Calendar...)
476                     
477                     $timestamp = $dbi->getTimestamp();
478                     $request->appendValidators(array('dbi_timestamp' => $timestamp,
479                                                      '%mtime' => (int)$timestamp,
480                                                      '%weak' => true));
481                 }
482                 return $plugin->run($dbi, $plugin_args, $request, $basepage);
483             case 'plugin-list':
484                 return $plugin->makeList($plugin_args, $request, $basepage);
485             case 'plugin-link':
486                 return $plugin->makeLink($plugin_args, $request);
487             case 'plugin-form':
488                 return $plugin->makeForm($plugin_args, $request);
489         }
490     }
491
492     function getWikiPageLinks($pi, $basepage) {
493         if (!($ppi = $this->parsePi($pi)))
494             return false;
495         list($pi_name, $plugin, $plugin_args) = $ppi;
496         if (!is_object($plugin))
497             return false;
498         if ($pi_name != 'plugin')
499             return false;
500         return $plugin->getWikiPageLinks($plugin_args, $basepage);
501     }
502     
503     function parsePI($pi) {
504         if (!preg_match('/^\s*<\?(plugin(?:-form|-link|-list)?)\s+(\w+)\s*(.*?)\s*\?>\s*$/s', $pi, $m))
505             return $this->_error(sprintf("Bad %s", 'PI'));
506
507         list(, $pi_name, $plugin_name, $plugin_args) = $m;
508         $plugin = $this->getPlugin($plugin_name, $pi);
509
510         return array($pi_name, $plugin, $plugin_args);
511     }
512     
513     function getPlugin($plugin_name, $pi=false) {
514         global $ErrorManager;
515
516         // Note that there seems to be no way to trap parse errors
517         // from this include.  (At least not via set_error_handler().)
518         $plugin_source = "lib/plugin/$plugin_name.php";
519
520         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_plugin_error_filter'));
521         $plugin_class = "WikiPlugin_$plugin_name";
522         if (!class_exists($plugin_class)) {
523             // $include_failed = !@include_once("lib/plugin/$plugin_name.php");
524             $include_failed = !include_once("lib/plugin/$plugin_name.php");
525             $ErrorManager->popErrorHandler();
526             
527             if (!class_exists($plugin_class)) {
528                 if ($include_failed)
529                     return $this->_error(sprintf(_("Include of '%s' failed."),
530                                                  $plugin_source));
531                 return $this->_error(sprintf(_("%s: no such class"), $plugin_class));
532             }
533         }
534         $ErrorManager->popErrorHandler();
535         $plugin = new $plugin_class;
536         if (!is_subclass_of($plugin, "WikiPlugin"))
537             return $this->_error(sprintf(_("%s: not a subclass of WikiPlugin."),
538                                          $plugin_class));
539
540         $plugin->_pi = $pi;
541         return $plugin;
542     }
543
544     function _plugin_error_filter ($err) {
545         if (preg_match("/Failed opening '.*' for inclusion/", $err->errstr))
546             return true;        // Ignore this error --- it's expected.
547         return false;
548     }
549
550     function getErrorDetail() {
551         return $this->_errors;
552     }
553
554     function _error($message) {
555         $this->_errors = $message;
556         return false;
557     }
558 };
559
560 // (c-file-style: "gnu")
561 // Local Variables:
562 // mode: php
563 // tab-width: 8
564 // c-basic-offset: 4
565 // c-hanging-comment-ender-p: nil
566 // indent-tabs-mode: nil
567 // End:
568 ?>