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