Aleksander Machniak
2013-10-17 197203727417a03d87053a47e5aa5175a76e3e0b
commit | author | age
cc97ea 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_plugin_api.php                                  |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
f5e7b3 8  | Copyright (C) 2008-2009, The Roundcube Dev Team                       |
cc97ea 9  | Licensed under the GNU GPL                                            |
T 10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Plugins repository                                                  |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
1d786c 18  $Id$
cc97ea 19
T 20 */
21
22 /**
23  * The plugin loader and global API
24  *
d062db 25  * @package PluginAPI
cc97ea 26  */
T 27 class rcube_plugin_api
28 {
29   static private $instance;
197203 30
cc97ea 31   public $dir;
T 32   public $url = 'plugins/';
33   public $output;
1ac543 34   public $config;
197203 35   public $allowed_prefs         = array();
AM 36   public $allowed_session_prefs = array();
37
cc97ea 38   public $handlers = array();
T 39   private $plugins = array();
05a631 40   private $tasks = array();
cc97ea 41   private $actions = array();
T 42   private $actionmap = array();
43   private $objectsmap = array();
44   private $template_contents = array();
a366a3 45   private $required_plugins = array('filesystem_attachments');
T 46   private $active_hook = false;
cc97ea 47
e6ce00 48   // Deprecated names of hooks, will be removed after 0.5-stable release
A 49   private $deprecated_hooks = array(
50     'create_user'       => 'user_create',
51     'kill_session'      => 'session_destroy',
52     'upload_attachment' => 'attachment_upload',
53     'save_attachment'   => 'attachment_save',
54     'get_attachment'    => 'attachment_get',
55     'cleanup_attachments' => 'attachments_cleanup',
56     'display_attachment' => 'attachment_display',
57     'remove_attachment' => 'attachment_delete',
58     'outgoing_message_headers' => 'message_outgoing_headers',
59     'outgoing_message_body' => 'message_outgoing_body',
60     'address_sources'   => 'addressbooks_list',
61     'get_address_book'  => 'addressbook_get',
62     'create_contact'    => 'contact_create',
119ad1 63     'save_contact'      => 'contact_update',
A 64     'contact_save'      => 'contact_update',
e6ce00 65     'delete_contact'    => 'contact_delete',
A 66     'manage_folders'    => 'folders_list',
67     'list_mailboxes'    => 'mailboxes_list',
68     'save_preferences'  => 'preferences_save',
69     'user_preferences'  => 'preferences_list',
70     'list_prefs_sections' => 'preferences_sections_list',
71     'list_identities'   => 'identities_list',
72     'create_identity'   => 'identity_create',
119ad1 73     'delete_identity'   => 'identity_delete',
A 74     'save_identity'     => 'identity_update',
75     'identity_save'     => 'identity_update',
e6ce00 76   );
A 77
cc97ea 78   /**
T 79    * This implements the 'singleton' design pattern
80    *
5c461b 81    * @return rcube_plugin_api The one and only instance if this class
cc97ea 82    */
T 83   static function get_instance()
84   {
85     if (!self::$instance) {
86       self::$instance = new rcube_plugin_api();
87     }
88
89     return self::$instance;
90   }
8ec1b9 91
A 92
cc97ea 93   /**
T 94    * Private constructor
95    */
96   private function __construct()
97   {
7dbe2f 98     $this->dir = INSTALL_PATH . $this->url;
cc97ea 99   }
8ec1b9 100
A 101
cc97ea 102   /**
T 103    * Load and init all enabled plugins
104    *
929a50 105    * This has to be done after rcmail::load_gui() or rcmail::json_init()
cc97ea 106    * was called because plugins need to have access to rcmail->output
T 107    */
108   public function init()
109   {
110     $rcmail = rcmail::get_instance();
111     $this->output = $rcmail->output;
1ac543 112     $this->config = $rcmail->config;
d5d968 113
cc97ea 114     $plugins_enabled = (array)$rcmail->config->get('plugins', array());
T 115     foreach ($plugins_enabled as $plugin_name) {
0501b6 116       $this->load_plugin($plugin_name);
cc97ea 117     }
8ec1b9 118
cc97ea 119     // check existance of all required core plugins
T 120     foreach ($this->required_plugins as $plugin_name) {
121       $loaded = false;
122       foreach ($this->plugins as $plugin) {
123         if ($plugin instanceof $plugin_name) {
124           $loaded = true;
125           break;
126         }
127       }
8ec1b9 128
cc97ea 129       // load required core plugin if no derivate was found
0501b6 130       if (!$loaded)
T 131         $loaded = $this->load_plugin($plugin_name);
d5d968 132
cc97ea 133       // trigger fatal error if still not loaded
T 134       if (!$loaded) {
10eedb 135         raise_error(array('code' => 520, 'type' => 'php',
0501b6 136           'file' => __FILE__, 'line' => __LINE__,
T 137           'message' => "Requried plugin $plugin_name was not loaded"), true, true);
cc97ea 138       }
T 139     }
140
141     // register an internal hook
142     $this->register_hook('template_container', array($this, 'template_container_hook'));
8ec1b9 143
cc97ea 144     // maybe also register a shudown function which triggers shutdown functions of all plugin objects
T 145   }
0501b6 146
T 147
148   /**
149    * Load the specified plugin
150    *
151    * @param string Plugin name
152    * @return boolean True on success, false if not loaded or failure
153    */
154   public function load_plugin($plugin_name)
155   {
156     static $plugins_dir;
8ec1b9 157
0501b6 158     $rcmail = rcmail::get_instance();
8ec1b9 159
0501b6 160     if (!$plugins_dir) {
T 161       $dir = dir($this->dir);
162       $plugins_dir = unslashify($dir->path);
163     }
8ec1b9 164
0501b6 165     // plugin already loaded
T 166     if ($this->plugins[$plugin_name] || class_exists($plugin_name, false))
167       return true;
8ec1b9 168
0501b6 169     $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
T 170
171     if (file_exists($fn)) {
172       include($fn);
173
174       // instantiate class if exists
175       if (class_exists($plugin_name, false)) {
176         $plugin = new $plugin_name($this);
177         // check inheritance...
178         if (is_subclass_of($plugin, 'rcube_plugin')) {
179           // ... task, request type and framed mode
8ec1b9 180           if ((!$plugin->task || preg_match('/^('.$plugin->task.')$/i', $rcmail->task))
9a835c 181               && (!$plugin->noajax || (is_object($rcmail->output) && is_a($rcmail->output, 'rcube_template')))
8ec1b9 182               && (!$plugin->noframe || empty($_REQUEST['_framed']))
0501b6 183           ) {
T 184             $plugin->init();
185             $this->plugins[$plugin_name] = $plugin;
186           }
395b74 187           if (!empty($plugin->allowed_prefs)) {
AM 188             $this->allowed_prefs = array_merge($this->allowed_prefs, $plugin->allowed_prefs);
189           }
0501b6 190           return true;
T 191         }
192       }
193       else {
194         raise_error(array('code' => 520, 'type' => 'php',
195           'file' => __FILE__, 'line' => __LINE__,
196           'message' => "No plugin class $plugin_name found in $fn"), true, false);
197       }
198     }
199     else {
200       raise_error(array('code' => 520, 'type' => 'php',
201         'file' => __FILE__, 'line' => __LINE__,
202         'message' => "Failed to load plugin file $fn"), true, false);
203     }
8ec1b9 204
0501b6 205     return false;
T 206   }
8ec1b9 207
A 208
cc97ea 209   /**
T 210    * Allows a plugin object to register a callback for a certain hook
211    *
5c461b 212    * @param string $hook Hook name
A 213    * @param mixed  $callback String with global function name or array($obj, 'methodname')
cc97ea 214    */
T 215   public function register_hook($hook, $callback)
216   {
e6ce00 217     if (is_callable($callback)) {
A 218       if (isset($this->deprecated_hooks[$hook])) {
219         raise_error(array('code' => 522, 'type' => 'php',
220           'file' => __FILE__, 'line' => __LINE__,
221           'message' => "Deprecated hook name. ".$hook.' -> '.$this->deprecated_hooks[$hook]), true, false);
222         $hook = $this->deprecated_hooks[$hook];
223       }
cc97ea 224       $this->handlers[$hook][] = $callback;
e6ce00 225     }
cc97ea 226     else
10eedb 227       raise_error(array('code' => 521, 'type' => 'php',
A 228         'file' => __FILE__, 'line' => __LINE__,
229         'message' => "Invalid callback function for $hook"), true, false);
cc97ea 230   }
8ec1b9 231
A 232
cc97ea 233   /**
T 234    * Triggers a plugin hook.
235    * This is called from the application and executes all registered handlers
236    *
5c461b 237    * @param string $hook Hook name
A 238    * @param array $args Named arguments (key->value pairs)
cc97ea 239    * @return array The (probably) altered hook arguments
T 240    */
241   public function exec_hook($hook, $args = array())
242   {
463a03 243     if (!is_array($args))
A 244       $args = array('arg' => $args);
245
cc97ea 246     $args += array('abort' => false);
a366a3 247     $this->active_hook = $hook;
8ec1b9 248
cc97ea 249     foreach ((array)$this->handlers[$hook] as $callback) {
T 250       $ret = call_user_func($callback, $args);
251       if ($ret && is_array($ret))
252         $args = $ret + $args;
8ec1b9 253
cc97ea 254       if ($args['abort'])
T 255         break;
256     }
8ec1b9 257
a366a3 258     $this->active_hook = false;
cc97ea 259     return $args;
T 260   }
261
262
263   /**
264    * Let a plugin register a handler for a specific request
265    *
5c461b 266    * @param string $action Action name (_task=mail&_action=plugin.foo)
A 267    * @param string $owner Plugin name that registers this action
268    * @param mixed  $callback Callback: string with global function name or array($obj, 'methodname')
269    * @param string $task Task name registered by this plugin
cc97ea 270    */
05a631 271   public function register_action($action, $owner, $callback, $task = null)
cc97ea 272   {
T 273     // check action name
05a631 274     if ($task)
T 275       $action = $task.'.'.$action;
276     else if (strpos($action, 'plugin.') !== 0)
cc97ea 277       $action = 'plugin.'.$action;
2cd443 278
cc97ea 279     // can register action only if it's not taken or registered by myself
T 280     if (!isset($this->actionmap[$action]) || $this->actionmap[$action] == $owner) {
281       $this->actions[$action] = $callback;
282       $this->actionmap[$action] = $owner;
283     }
284     else {
10eedb 285       raise_error(array('code' => 523, 'type' => 'php',
A 286         'file' => __FILE__, 'line' => __LINE__,
287         'message' => "Cannot register action $action; already taken by another plugin"), true, false);
cc97ea 288     }
T 289   }
290
291
292   /**
293    * This method handles requests like _task=mail&_action=plugin.foo
294    * It executes the callback function that was registered with the given action.
295    *
5c461b 296    * @param string $action Action name
cc97ea 297    */
T 298   public function exec_action($action)
299   {
300     if (isset($this->actions[$action])) {
301       call_user_func($this->actions[$action]);
302     }
303     else {
10eedb 304       raise_error(array('code' => 524, 'type' => 'php',
A 305         'file' => __FILE__, 'line' => __LINE__,
306         'message' => "No handler found for action $action"), true, true);
cc97ea 307     }
T 308   }
309
310
311   /**
312    * Register a handler function for template objects
313    *
5c461b 314    * @param string $name Object name
A 315    * @param string $owner Plugin name that registers this action
316    * @param mixed  $callback Callback: string with global function name or array($obj, 'methodname')
cc97ea 317    */
T 318   public function register_handler($name, $owner, $callback)
319   {
320     // check name
321     if (strpos($name, 'plugin.') !== 0)
322       $name = 'plugin.'.$name;
8ec1b9 323
cc97ea 324     // can register handler only if it's not taken or registered by myself
T 325     if (!isset($this->objectsmap[$name]) || $this->objectsmap[$name] == $owner) {
326       $this->output->add_handler($name, $callback);
327       $this->objectsmap[$name] = $owner;
328     }
329     else {
10eedb 330       raise_error(array('code' => 525, 'type' => 'php',
A 331         'file' => __FILE__, 'line' => __LINE__,
332         'message' => "Cannot register template handler $name; already taken by another plugin"), true, false);
cc97ea 333     }
T 334   }
8ec1b9 335
A 336
a366a3 337   /**
05a631 338    * Register this plugin to be responsible for a specific task
T 339    *
5c461b 340    * @param string $task Task name (only characters [a-z0-9_.-] are allowed)
A 341    * @param string $owner Plugin name that registers this action
05a631 342    */
T 343   public function register_task($task, $owner)
344   {
345     if ($task != asciiwords($task)) {
346       raise_error(array('code' => 526, 'type' => 'php',
347         'file' => __FILE__, 'line' => __LINE__,
348         'message' => "Invalid task name: $task. Only characters [a-z0-9_.-] are allowed"), true, false);
349     }
350     else if (in_array($task, rcmail::$main_tasks)) {
351       raise_error(array('code' => 526, 'type' => 'php',
352         'file' => __FILE__, 'line' => __LINE__,
353         'message' => "Cannot register taks $task; already taken by another plugin or the application itself"), true, false);
354     }
355     else {
356       $this->tasks[$task] = $owner;
357       rcmail::$main_tasks[] = $task;
358       return true;
359     }
8ec1b9 360
05a631 361     return false;
T 362   }
363
364
365   /**
366    * Checks whether the given task is registered by a plugin
367    *
5c461b 368    * @param string $task Task name
05a631 369    * @return boolean True if registered, otherwise false
T 370    */
371   public function is_plugin_task($task)
372   {
373     return $this->tasks[$task] ? true : false;
374   }
375
376
377   /**
a366a3 378    * Check if a plugin hook is currently processing.
T 379    * Mainly used to prevent loops and recursion.
380    *
5c461b 381    * @param string $hook Hook to check (optional)
a366a3 382    * @return boolean True if any/the given hook is currently processed, otherwise false
T 383    */
384   public function is_processing($hook = null)
385   {
386     return $this->active_hook && (!$hook || $this->active_hook == $hook);
387   }
8ec1b9 388
cc97ea 389   /**
T 390    * Include a plugin script file in the current HTML page
5c461b 391    *
A 392    * @param string $fn Path to script
cc97ea 393    */
T 394   public function include_script($fn)
395   {
396     if ($this->output->type == 'html') {
eb6f19 397       $src = $this->resource_url($fn);
cc97ea 398       $this->output->add_header(html::tag('script', array('type' => "text/javascript", 'src' => $src)));
T 399     }
400   }
401
8ec1b9 402
cc97ea 403   /**
T 404    * Include a plugin stylesheet in the current HTML page
5c461b 405    *
A 406    * @param string $fn Path to stylesheet
cc97ea 407    */
T 408   public function include_stylesheet($fn)
409   {
410     if ($this->output->type == 'html') {
eb6f19 411       $src = $this->resource_url($fn);
ba3377 412       $this->output->include_css($src);
cc97ea 413     }
T 414   }
8ec1b9 415
A 416
cc97ea 417   /**
T 418    * Save the given HTML content to be added to a template container
5c461b 419    *
A 420    * @param string $html HTML content
421    * @param string $container Template container identifier
cc97ea 422    */
T 423   public function add_content($html, $container)
424   {
425     $this->template_contents[$container] .= $html . "\n";
426   }
8ec1b9 427
A 428
cc97ea 429   /**
8703b0 430    * Returns list of loaded plugins names
A 431    *
432    * @return array List of plugin names
433    */
434   public function loaded_plugins()
435   {
436     return array_keys($this->plugins);
437   }
438
439
440   /**
cc97ea 441    * Callback for template_container hooks
5c461b 442    *
A 443    * @param array $attrib
444    * @return array
cc97ea 445    */
T 446   private function template_container_hook($attrib)
447   {
448     $container = $attrib['name'];
8448fc 449     return array('content' => $attrib['content'] . $this->template_contents[$container]);
cc97ea 450   }
8ec1b9 451
A 452
cc97ea 453   /**
T 454    * Make the given file name link into the plugins directory
5c461b 455    *
A 456    * @param string $fn Filename
457    * @return string 
cc97ea 458    */
eb6f19 459   private function resource_url($fn)
cc97ea 460   {
23a2ee 461     if ($fn[0] != '/' && !preg_match('|^https?://|i', $fn))
cc97ea 462       return $this->url . $fn;
T 463     else
464       return $fn;
465   }
466
467 }