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