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