source: subversion/trunk/roundcubemail/program/include/rcube_plugin_api.php @ 5672

Last change on this file since 5672 was 5672, checked in by thomasb, 17 months ago

Always load jquery UI; minor phpdoc fix

  • Property svn:keywords set to Id
File size: 13.7 KB
Line 
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-2011, The Roundcube Dev Team                       |
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$
19
20*/
21
22/**
23 * The plugin loader and global API
24 *
25 * @package PluginAPI
26 */
27class 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', 'jqueryui');
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_enabled = (array)$rcmail->config->get('plugins', array());
113    foreach ($plugins_enabled as $plugin_name) {
114      $this->load_plugin($plugin_name);
115    }
116
117    // check existance of all required core plugins
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      }
126
127      // load required core plugin if no derivate was found
128      if (!$loaded)
129        $loaded = $this->load_plugin($plugin_name);
130
131      // trigger fatal error if still not loaded
132      if (!$loaded) {
133        raise_error(array('code' => 520, 'type' => 'php',
134          'file' => __FILE__, 'line' => __LINE__,
135          'message' => "Requried plugin $plugin_name was not loaded"), true, true);
136      }
137    }
138
139    // register an internal hook
140    $this->register_hook('template_container', array($this, 'template_container_hook'));
141
142    // maybe also register a shudown function which triggers shutdown functions of all plugin objects
143  }
144
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;
155
156    $rcmail = rcmail::get_instance();
157
158    if (!$plugins_dir) {
159      $dir = dir($this->dir);
160      $plugins_dir = unslashify($dir->path);
161    }
162
163    // plugin already loaded
164    if ($this->plugins[$plugin_name] || class_exists($plugin_name, false))
165      return true;
166
167    $fn = $plugins_dir . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . $plugin_name . '.php';
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
178          if ((!$plugin->task || preg_match('/^('.$plugin->task.')$/i', $rcmail->task))
179              && (!$plugin->noajax || (is_object($rcmail->output) && is_a($rcmail->output, 'rcube_template')))
180              && (!$plugin->noframe || empty($_REQUEST['_framed']))
181          ) {
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    }
199
200    return false;
201  }
202
203
204  /**
205   * Allows a plugin object to register a callback for a certain hook
206   *
207   * @param string $hook Hook name
208   * @param mixed  $callback String with global function name or array($obj, 'methodname')
209   */
210  public function register_hook($hook, $callback)
211  {
212    if (is_callable($callback)) {
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      }
219      $this->handlers[$hook][] = $callback;
220    }
221    else
222      raise_error(array('code' => 521, 'type' => 'php',
223        'file' => __FILE__, 'line' => __LINE__,
224        'message' => "Invalid callback function for $hook"), true, false);
225  }
226
227
228  /**
229   * Triggers a plugin hook.
230   * This is called from the application and executes all registered handlers
231   *
232   * @param string $hook Hook name
233   * @param array $args Named arguments (key->value pairs)
234   * @return array The (probably) altered hook arguments
235   */
236  public function exec_hook($hook, $args = array())
237  {
238    if (!is_array($args))
239      $args = array('arg' => $args);
240
241    $args += array('abort' => false);
242    $this->active_hook = $hook;
243
244    foreach ((array)$this->handlers[$hook] as $callback) {
245      $ret = call_user_func($callback, $args);
246      if ($ret && is_array($ret))
247        $args = $ret + $args;
248
249      if ($args['abort'])
250        break;
251    }
252
253    $this->active_hook = false;
254    return $args;
255  }
256
257
258  /**
259   * Let a plugin register a handler for a specific request
260   *
261   * @param string $action Action name (_task=mail&_action=plugin.foo)
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
265   */
266  public function register_action($action, $owner, $callback, $task = null)
267  {
268    // check action name
269    if ($task)
270      $action = $task.'.'.$action;
271    else if (strpos($action, 'plugin.') !== 0)
272      $action = 'plugin.'.$action;
273
274    // can register action only if it's not taken or registered by myself
275    if (!isset($this->actionmap[$action]) || $this->actionmap[$action] == $owner) {
276      $this->actions[$action] = $callback;
277      $this->actionmap[$action] = $owner;
278    }
279    else {
280      raise_error(array('code' => 523, 'type' => 'php',
281        'file' => __FILE__, 'line' => __LINE__,
282        'message' => "Cannot register action $action; already taken by another plugin"), true, false);
283    }
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   *
291   * @param string $action Action name
292   */
293  public function exec_action($action)
294  {
295    if (isset($this->actions[$action])) {
296      call_user_func($this->actions[$action]);
297    }
298    else {
299      raise_error(array('code' => 524, 'type' => 'php',
300        'file' => __FILE__, 'line' => __LINE__,
301        'message' => "No handler found for action $action"), true, true);
302    }
303  }
304
305
306  /**
307   * Register a handler function for template objects
308   *
309   * @param string $name Object name
310   * @param string $owner Plugin name that registers this action
311   * @param mixed  $callback Callback: string with global function name or array($obj, 'methodname')
312   */
313  public function register_handler($name, $owner, $callback)
314  {
315    // check name
316    if (strpos($name, 'plugin.') !== 0)
317      $name = 'plugin.'.$name;
318
319    // can register handler only if it's not taken or registered by myself
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 {
325      raise_error(array('code' => 525, 'type' => 'php',
326        'file' => __FILE__, 'line' => __LINE__,
327        'message' => "Cannot register template handler $name; already taken by another plugin"), true, false);
328    }
329  }
330
331
332  /**
333   * Register this plugin to be responsible for a specific task
334   *
335   * @param string $task Task name (only characters [a-z0-9_.-] are allowed)
336   * @param string $owner Plugin name that registers this action
337   */
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    }
355
356    return false;
357  }
358
359
360  /**
361   * Checks whether the given task is registered by a plugin
362   *
363   * @param string $task Task name
364   * @return boolean True if registered, otherwise false
365   */
366  public function is_plugin_task($task)
367  {
368    return $this->tasks[$task] ? true : false;
369  }
370
371
372  /**
373   * Check if a plugin hook is currently processing.
374   * Mainly used to prevent loops and recursion.
375   *
376   * @param string $hook Hook to check (optional)
377   * @return boolean True if any/the given hook is currently processed, otherwise false
378   */
379  public function is_processing($hook = null)
380  {
381    return $this->active_hook && (!$hook || $this->active_hook == $hook);
382  }
383
384  /**
385   * Include a plugin script file in the current HTML page
386   *
387   * @param string $fn Path to script
388   */
389  public function include_script($fn)
390  {
391    if ($this->output->type == 'html') {
392      $src = $this->resource_url($fn);
393      $this->output->add_header(html::tag('script', array('type' => "text/javascript", 'src' => $src)));
394    }
395  }
396
397
398  /**
399   * Include a plugin stylesheet in the current HTML page
400   *
401   * @param string $fn Path to stylesheet
402   */
403  public function include_stylesheet($fn)
404  {
405    if ($this->output->type == 'html') {
406      $src = $this->resource_url($fn);
407      $this->output->include_css($src);
408    }
409  }
410
411
412  /**
413   * Save the given HTML content to be added to a template container
414   *
415   * @param string $html HTML content
416   * @param string $container Template container identifier
417   */
418  public function add_content($html, $container)
419  {
420    $this->template_contents[$container] .= $html . "\n";
421  }
422
423
424  /**
425   * Returns list of loaded plugins names
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  /**
436   * Callback for template_container hooks
437   *
438   * @param array $attrib
439   * @return array
440   */
441  private function template_container_hook($attrib)
442  {
443    $container = $attrib['name'];
444    return array('content' => $attrib['content'] . $this->template_contents[$container]);
445  }
446
447
448  /**
449   * Make the given file name link into the plugins directory
450   *
451   * @param string $fn Filename
452   * @return string
453   */
454  private function resource_url($fn)
455  {
456    if ($fn[0] != '/' && !preg_match('|^https?://|i', $fn))
457      return $this->url . $fn;
458    else
459      return $fn;
460  }
461
462}
Note: See TracBrowser for help on using the repository browser.