source: github/program/include/rcube_plugin_api.php @ 041c93c

HEADdev-browser-capabilitiespdo
Last change on this file since 041c93c was 041c93c, checked in by Aleksander Machniak <alec@…>, 12 months ago

Removed $Id$

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