Page MenuHomePhorge

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/plugins/acl/acl.php b/plugins/acl/acl.php
index 1952dad49..5ae9e4e0a 100644
--- a/plugins/acl/acl.php
+++ b/plugins/acl/acl.php
@@ -1,706 +1,706 @@
<?php
/**
* Folders Access Control Lists Management (RFC4314, RFC2086)
*
* @version @package_version@
* @author Aleksander Machniak <alec@alec.pl>
*
*
* Copyright (C) 2011-2012, Kolab Systems AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
class acl extends rcube_plugin
{
public $task = 'settings|addressbook|calendar';
private $rc;
private $supported = null;
private $mbox;
private $ldap;
private $specials = array('anyone', 'anonymous');
/**
* Plugin initialization
*/
function init()
{
$this->rc = rcmail::get_instance();
// Register hooks
$this->add_hook('folder_form', array($this, 'folder_form'));
// kolab_addressbook plugin
$this->add_hook('addressbook_form', array($this, 'folder_form'));
$this->add_hook('calendar_form_kolab', array($this, 'folder_form'));
// Plugin actions
$this->register_action('plugin.acl', array($this, 'acl_actions'));
$this->register_action('plugin.acl-autocomplete', array($this, 'acl_autocomplete'));
}
/**
* Handler for plugin actions (AJAX)
*/
function acl_actions()
{
- $action = trim(get_input_value('_act', RCUBE_INPUT_GPC));
+ $action = trim(rcube_utils::get_input_value('_act', rcube_utils::INPUT_GPC));
// Connect to IMAP
$this->rc->storage_init();
// Load localization and configuration
$this->add_texts('localization/');
$this->load_config();
if ($action == 'save') {
$this->action_save();
}
else if ($action == 'delete') {
$this->action_delete();
}
else if ($action == 'list') {
$this->action_list();
}
// Only AJAX actions
$this->rc->output->send();
}
/**
* Handler for user login autocomplete request
*/
function acl_autocomplete()
{
$this->load_config();
- $search = get_input_value('_search', RCUBE_INPUT_GPC, true);
- $sid = get_input_value('_id', RCUBE_INPUT_GPC);
+ $search = rcube_utils::get_input_value('_search', rcube_utils::INPUT_GPC, true);
+ $sid = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GPC);
$users = array();
if ($this->init_ldap()) {
$max = (int) $this->rc->config->get('autocomplete_max', 15);
$mode = (int) $this->rc->config->get('addressbook_search_mode');
$this->ldap->set_pagesize($max);
$result = $this->ldap->search('*', $search, $mode);
foreach ($result->records as $record) {
$user = $record['uid'];
if (is_array($user)) {
$user = array_filter($user);
$user = $user[0];
}
if ($user) {
if ($record['name'])
$user = $record['name'] . ' (' . $user . ')';
$users[] = $user;
}
}
}
sort($users, SORT_LOCALE_STRING);
$this->rc->output->command('ksearch_query_results', $users, $search, $sid);
$this->rc->output->send();
}
/**
* Handler for 'folder_form' hook
*
* @param array $args Hook arguments array (form data)
*
* @return array Hook arguments array
*/
function folder_form($args)
{
$mbox_imap = $args['options']['name'];
$myrights = $args['options']['rights'];
// Edited folder name (empty in create-folder mode)
if (!strlen($mbox_imap)) {
return $args;
}
/*
// Do nothing on protected folders (?)
if ($args['options']['protected']) {
return $args;
}
*/
// Get MYRIGHTS
if (empty($myrights)) {
return $args;
}
// Load localization and include scripts
$this->load_config();
$this->add_texts('localization/', array('deleteconfirm', 'norights',
'nouser', 'deleting', 'saving'));
$this->include_script('acl.js');
$this->rc->output->include_script('list.js');
$this->include_stylesheet($this->local_skin_path().'/acl.css');
// add Info fieldset if it doesn't exist
if (!isset($args['form']['props']['fieldsets']['info']))
$args['form']['props']['fieldsets']['info'] = array(
- 'name' => rcube_label('info'),
+ 'name' => $this->rc->gettext('info'),
'content' => array());
// Display folder rights to 'Info' fieldset
$args['form']['props']['fieldsets']['info']['content']['myrights'] = array(
- 'label' => Q($this->gettext('myrights')),
+ 'label' => rcube::Q($this->gettext('myrights')),
'value' => $this->acl2text($myrights)
);
// Return if not folder admin
if (!in_array('a', $myrights)) {
return $args;
}
// The 'Sharing' tab
$this->mbox = $mbox_imap;
$this->rc->output->set_env('acl_users_source', (bool) $this->rc->config->get('acl_users_source'));
$this->rc->output->set_env('mailbox', $mbox_imap);
$this->rc->output->add_handlers(array(
'acltable' => array($this, 'templ_table'),
'acluser' => array($this, 'templ_user'),
'aclrights' => array($this, 'templ_rights'),
));
$this->rc->output->set_env('autocomplete_max', (int)$this->rc->config->get('autocomplete_max', 15));
$this->rc->output->set_env('autocomplete_min_length', $this->rc->config->get('autocomplete_min_length'));
$this->rc->output->add_label('autocompletechars', 'autocompletemore');
$args['form']['sharing'] = array(
- 'name' => Q($this->gettext('sharing')),
+ 'name' => rcube::Q($this->gettext('sharing')),
'content' => $this->rc->output->parse('acl.table', false, false),
);
return $args;
}
/**
* Creates ACL rights table
*
* @param array $attrib Template object attributes
*
* @return string HTML Content
*/
function templ_table($attrib)
{
if (empty($attrib['id']))
$attrib['id'] = 'acl-table';
$out = $this->list_rights($attrib);
$this->rc->output->add_gui_object('acltable', $attrib['id']);
return $out;
}
/**
* Creates ACL rights form (rights list part)
*
* @param array $attrib Template object attributes
*
* @return string HTML Content
*/
function templ_rights($attrib)
{
// Get supported rights
$supported = $this->rights_supported();
// depending on server capability either use 'te' or 'd' for deleting msgs
$deleteright = implode(array_intersect(str_split('ted'), $supported));
$out = '';
$ul = '';
$input = new html_checkbox();
// Advanced rights
$attrib['id'] = 'advancedrights';
foreach ($supported as $idx => $val) {
$ul .= html::tag('li', null,
$input->show('', array(
'name' => "acl[$val]", 'value' => $val, 'id' => $id))
. html::label(array('for' => $id, 'title' => $this->gettext('longacl'.$val)),
$this->gettext('acl'.$val)));
}
$out = html::tag('ul', $attrib, $ul, html::$common_attrib);
// Simple rights
$ul = '';
$attrib['id'] = 'simplerights';
$items = array(
'read' => 'lrs',
'write' => 'wi',
'delete' => $deleteright,
'other' => preg_replace('/[lrswi'.$deleteright.']/', '', implode($supported)),
);
foreach ($items as $key => $val) {
$id = "acl$key";
$ul .= html::tag('li', null,
$input->show('', array(
'name' => "acl[$val]", 'value' => $val, 'id' => $id))
. html::label(array('for' => $id, 'title' => $this->gettext('longacl'.$key)),
$this->gettext('acl'.$key)));
}
$out .= "\n" . html::tag('ul', $attrib, $ul, html::$common_attrib);
$this->rc->output->set_env('acl_items', $items);
return $out;
}
/**
* Creates ACL rights form (user part)
*
* @param array $attrib Template object attributes
*
* @return string HTML Content
*/
function templ_user($attrib)
{
// Create username input
$attrib['name'] = 'acluser';
$textfield = new html_inputfield($attrib);
$fields['user'] = html::label(array('for' => 'iduser'), $this->gettext('username'))
. ' ' . $textfield->show();
// Add special entries
if (!empty($this->specials)) {
foreach ($this->specials as $key) {
$fields[$key] = html::label(array('for' => 'id'.$key), $this->gettext($key));
}
}
$this->rc->output->set_env('acl_specials', $this->specials);
// Create list with radio buttons
if (count($fields) > 1) {
$ul = '';
$radio = new html_radiobutton(array('name' => 'usertype'));
foreach ($fields as $key => $val) {
$ul .= html::tag('li', null, $radio->show($key == 'user' ? 'user' : '',
array('value' => $key, 'id' => 'id'.$key))
. $val);
}
$out = html::tag('ul', array('id' => 'usertype'), $ul, html::$common_attrib);
}
// Display text input alone
else {
$out = $fields['user'];
}
return $out;
}
/**
* Creates ACL rights table
*
* @param array $attrib Template object attributes
*
* @return string HTML Content
*/
private function list_rights($attrib=array())
{
// Get ACL for the folder
$acl = $this->rc->storage->get_acl($this->mbox);
if (!is_array($acl)) {
$acl = array();
}
// Keep special entries (anyone/anonymous) on top of the list
if (!empty($this->specials) && !empty($acl)) {
foreach ($this->specials as $key) {
if (isset($acl[$key])) {
$acl_special[$key] = $acl[$key];
unset($acl[$key]);
}
}
}
// Sort the list by username
uksort($acl, 'strnatcasecmp');
if (!empty($acl_special)) {
$acl = array_merge($acl_special, $acl);
}
// Get supported rights and build column names
$supported = $this->rights_supported();
// depending on server capability either use 'te' or 'd' for deleting msgs
$deleteright = implode(array_intersect(str_split('ted'), $supported));
// Use advanced or simple (grouped) rights
$advanced = $this->rc->config->get('acl_advanced_mode');
if ($advanced) {
$items = array();
foreach ($supported as $sup) {
$items[$sup] = $sup;
}
}
else {
$items = array(
'read' => 'lrs',
'write' => 'wi',
'delete' => $deleteright,
'other' => preg_replace('/[lrswi'.$deleteright.']/', '', implode($supported)),
);
}
// Create the table
$attrib['noheader'] = true;
$table = new html_table($attrib);
// Create table header
$table->add_header('user', $this->gettext('identifier'));
foreach (array_keys($items) as $key) {
$label = $this->gettext('shortacl'.$key);
$table->add_header(array('class' => 'acl'.$key, 'title' => $label), $label);
}
$i = 1;
$js_table = array();
foreach ($acl as $user => $rights) {
if ($this->rc->storage->conn->user == $user) {
continue;
}
// filter out virtual rights (c or d) the server may return
$userrights = array_intersect($rights, $supported);
- $userid = html_identifier($user);
+ $userid = rcube_utils::html_identifier($user);
if (!empty($this->specials) && in_array($user, $this->specials)) {
$user = $this->gettext($user);
}
$table->add_row(array('id' => 'rcmrow'.$userid));
- $table->add('user', Q($user));
+ $table->add('user', rcube::Q($user));
foreach ($items as $key => $right) {
$in = $this->acl_compare($userrights, $right);
switch ($in) {
case 2: $class = 'enabled'; break;
case 1: $class = 'partial'; break;
default: $class = 'disabled'; break;
}
$table->add('acl' . $key . ' ' . $class, '');
}
$js_table[$userid] = implode($userrights);
}
$this->rc->output->set_env('acl', $js_table);
$this->rc->output->set_env('acl_advanced', $advanced);
$out = $table->show();
return $out;
}
/**
* Handler for ACL update/create action
*/
private function action_save()
{
- $mbox = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true)); // UTF7-IMAP
- $user = trim(get_input_value('_user', RCUBE_INPUT_GPC));
- $acl = trim(get_input_value('_acl', RCUBE_INPUT_GPC));
- $oldid = trim(get_input_value('_old', RCUBE_INPUT_GPC));
+ $mbox = trim(rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GPC, true)); // UTF7-IMAP
+ $user = trim(rcube_utils::get_input_value('_user', rcube_utils::INPUT_GPC));
+ $acl = trim(rcube_utils::get_input_value('_acl', rcube_utils::INPUT_GPC));
+ $oldid = trim(rcube_utils::get_input_value('_old', rcube_utils::INPUT_GPC));
$acl = array_intersect(str_split($acl), $this->rights_supported());
$users = $oldid ? array($user) : explode(',', $user);
foreach ($users as $user) {
$user = trim($user);
if (!empty($this->specials) && in_array($user, $this->specials)) {
$username = $this->gettext($user);
}
else {
if (!strpos($user, '@') && ($realm = $this->get_realm())) {
- $user .= '@' . rcube_idn_to_ascii(preg_replace('/^@/', '', $realm));
+ $user .= '@' . rcube_utils::idn_to_ascii(preg_replace('/^@/', '', $realm));
}
$username = $user;
}
if (!$acl || !$user || !strlen($mbox)) {
continue;
}
if ($user != $_SESSION['username'] && $username != $_SESSION['username']) {
if ($this->rc->storage->set_acl($mbox, $user, $acl)) {
- $ret = array('id' => html_identifier($user),
+ $ret = array('id' => rcube_utils::html_identifier($user),
'username' => $username, 'acl' => implode($acl), 'old' => $oldid);
$this->rc->output->command('acl_update', $ret);
$result++;
}
}
}
if ($result) {
$this->rc->output->show_message($oldid ? 'acl.updatesuccess' : 'acl.createsuccess', 'confirmation');
}
else {
$this->rc->output->show_message($oldid ? 'acl.updateerror' : 'acl.createerror', 'error');
}
}
/**
* Handler for ACL delete action
*/
private function action_delete()
{
- $mbox = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true)); //UTF7-IMAP
- $user = trim(get_input_value('_user', RCUBE_INPUT_GPC));
+ $mbox = trim(rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GPC, true)); //UTF7-IMAP
+ $user = trim(rcube_utils::get_input_value('_user', rcube_utils::INPUT_GPC));
$user = explode(',', $user);
foreach ($user as $u) {
$u = trim($u);
if ($this->rc->storage->delete_acl($mbox, $u)) {
- $this->rc->output->command('acl_remove_row', html_identifier($u));
+ $this->rc->output->command('acl_remove_row', rcube_utils::html_identifier($u));
}
else {
$error = true;
}
}
if (!$error) {
$this->rc->output->show_message('acl.deletesuccess', 'confirmation');
}
else {
$this->rc->output->show_message('acl.deleteerror', 'error');
}
}
/**
* Handler for ACL list update action (with display mode change)
*/
private function action_list()
{
if (in_array('acl_advanced_mode', (array)$this->rc->config->get('dont_override'))) {
return;
}
- $this->mbox = trim(get_input_value('_mbox', RCUBE_INPUT_GPC, true)); // UTF7-IMAP
- $advanced = trim(get_input_value('_mode', RCUBE_INPUT_GPC));
+ $this->mbox = trim(rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GPC, true)); // UTF7-IMAP
+ $advanced = trim(rcube_utils::get_input_value('_mode', rcube_utils::INPUT_GPC));
$advanced = $advanced == 'advanced' ? true : false;
// Save state in user preferences
$this->rc->user->save_prefs(array('acl_advanced_mode' => $advanced));
$out = $this->list_rights();
$out = preg_replace(array('/^<table[^>]+>/', '/<\/table>$/'), '', $out);
$this->rc->output->command('acl_list_update', $out);
}
/**
* Creates <UL> list with descriptive access rights
*
* @param array $rights MYRIGHTS result
*
* @return string HTML content
*/
function acl2text($rights)
{
if (empty($rights)) {
return '';
}
$supported = $this->rights_supported();
$list = array();
$attrib = array(
'name' => 'rcmyrights',
'style' => 'margin:0; padding:0 15px;',
);
foreach ($supported as $right) {
if (in_array($right, $rights)) {
- $list[] = html::tag('li', null, Q($this->gettext('acl' . $right)));
+ $list[] = html::tag('li', null, rcube::Q($this->gettext('acl' . $right)));
}
}
if (count($list) == count($supported))
- return Q($this->gettext('aclfull'));
+ return rcube::Q($this->gettext('aclfull'));
return html::tag('ul', $attrib, implode("\n", $list));
}
/**
* Compares two ACLs (according to supported rights)
*
* @param array $acl1 ACL rights array (or string)
* @param array $acl2 ACL rights array (or string)
*
* @param int Comparision result, 2 - full match, 1 - partial match, 0 - no match
*/
function acl_compare($acl1, $acl2)
{
if (!is_array($acl1)) $acl1 = str_split($acl1);
if (!is_array($acl2)) $acl2 = str_split($acl2);
$rights = $this->rights_supported();
$acl1 = array_intersect($acl1, $rights);
$acl2 = array_intersect($acl2, $rights);
$res = array_intersect($acl1, $acl2);
$cnt1 = count($res);
$cnt2 = count($acl2);
if ($cnt1 == $cnt2)
return 2;
else if ($cnt1)
return 1;
else
return 0;
}
/**
* Get list of supported access rights (according to RIGHTS capability)
*
* @return array List of supported access rights abbreviations
*/
function rights_supported()
{
if ($this->supported !== null) {
return $this->supported;
}
$capa = $this->rc->storage->get_capability('RIGHTS');
if (is_array($capa)) {
$rights = strtolower($capa[0]);
}
else {
$rights = 'cd';
}
return $this->supported = str_split('lrswi' . $rights . 'pa');
}
/**
* Username realm detection.
*
* @return string Username realm (domain)
*/
private function get_realm()
{
// When user enters a username without domain part, realm
// allows to add it to the username (and display correct username in the table)
if (isset($_SESSION['acl_username_realm'])) {
return $_SESSION['acl_username_realm'];
}
// find realm in username of logged user (?)
list($name, $domain) = explode('@', $_SESSION['username']);
// Use (always existent) ACL entry on the INBOX for the user to determine
// whether or not the user ID in ACL entries need to be qualified and how
// they would need to be qualified.
if (empty($domain)) {
$acl = $this->rc->storage->get_acl('INBOX');
if (is_array($acl)) {
$regexp = '/^' . preg_quote($_SESSION['username'], '/') . '@(.*)$/';
foreach (array_keys($acl) as $name) {
if (preg_match($regexp, $name, $matches)) {
$domain = $matches[1];
break;
}
}
}
}
return $_SESSION['acl_username_realm'] = $domain;
}
/**
* Initializes autocomplete LDAP backend
*/
private function init_ldap()
{
if ($this->ldap)
return $this->ldap->ready;
// get LDAP config
$config = $this->rc->config->get('acl_users_source');
if (empty($config)) {
return false;
}
// not an array, use configured ldap_public source
if (!is_array($config)) {
$ldap_config = (array) $this->rc->config->get('ldap_public');
$config = $ldap_config[$config];
}
$uid_field = $this->rc->config->get('acl_users_field', 'mail');
$filter = $this->rc->config->get('acl_users_filter');
if (empty($uid_field) || empty($config)) {
return false;
}
// get name attribute
if (!empty($config['fieldmap'])) {
$name_field = $config['fieldmap']['name'];
}
// ... no fieldmap, use the old method
if (empty($name_field)) {
$name_field = $config['name_field'];
}
// add UID field to fieldmap, so it will be returned in a record with name
$config['fieldmap'] = array(
'name' => $name_field,
'uid' => $uid_field,
);
// search in UID and name fields
$config['search_fields'] = array_values($config['fieldmap']);
$config['required_fields'] = array($uid_field);
// set search filter
if ($filter)
$config['filter'] = $filter;
// disable vlv
$config['vlv'] = false;
// Initialize LDAP connection
$this->ldap = new rcube_ldap($config,
$this->rc->config->get('ldap_debug'),
$this->rc->config->mail_domain($_SESSION['imap_host']));
return $this->ldap->ready;
}
}
diff --git a/plugins/archive/archive.php b/plugins/archive/archive.php
index 0a298cbe3..9b03cb186 100644
--- a/plugins/archive/archive.php
+++ b/plugins/archive/archive.php
@@ -1,129 +1,129 @@
<?php
/**
* Archive
*
* Plugin that adds a new button to the mailbox toolbar
* to move messages to a (user selectable) archive folder.
*
* @version @package_version@
* @license GNU GPLv3+
* @author Andre Rodier, Thomas Bruederli
*/
class archive extends rcube_plugin
{
public $task = 'mail|settings';
function init()
{
$rcmail = rcmail::get_instance();
// There is no "Archived flags"
// $GLOBALS['IMAP_FLAGS']['ARCHIVED'] = 'Archive';
if ($rcmail->task == 'mail' && ($rcmail->action == '' || $rcmail->action == 'show')
&& ($archive_folder = $rcmail->config->get('archive_mbox'))) {
$skin_path = $this->local_skin_path();
if (is_file($this->home . "/$skin_path/archive.css"))
$this->include_stylesheet("$skin_path/archive.css");
$this->include_script('archive.js');
$this->add_texts('localization', true);
$this->add_button(
array(
'type' => 'link',
'label' => 'buttontext',
'command' => 'plugin.archive',
'class' => 'button buttonPas archive disabled',
'classact' => 'button archive',
'width' => 32,
'height' => 32,
'title' => 'buttontitle',
'domain' => $this->ID,
),
'toolbar');
// register hook to localize the archive folder
$this->add_hook('render_mailboxlist', array($this, 'render_mailboxlist'));
// set env variable for client
$rcmail->output->set_env('archive_folder', $archive_folder);
// add archive folder to the list of default mailboxes
if (($default_folders = $rcmail->config->get('default_folders')) && !in_array($archive_folder, $default_folders)) {
$default_folders[] = $archive_folder;
$rcmail->config->set('default_folders', $default_folders);
}
}
else if ($rcmail->task == 'settings') {
$dont_override = $rcmail->config->get('dont_override', array());
if (!in_array('archive_mbox', $dont_override)) {
$this->add_hook('preferences_list', array($this, 'prefs_table'));
$this->add_hook('preferences_save', array($this, 'save_prefs'));
}
}
}
function render_mailboxlist($p)
{
$rcmail = rcmail::get_instance();
$archive_folder = $rcmail->config->get('archive_mbox');
$localize_name = $rcmail->config->get('archive_localize_name', true);
// set localized name for the configured archive folder
if ($archive_folder && $localize_name) {
if (isset($p['list'][$archive_folder]))
$p['list'][$archive_folder]['name'] = $this->gettext('archivefolder');
else // search in subfolders
$this->_mod_folder_name($p['list'], $archive_folder, $this->gettext('archivefolder'));
}
return $p;
}
function _mod_folder_name(&$list, $folder, $new_name)
{
foreach ($list as $idx => $item) {
if ($item['id'] == $folder) {
$list[$idx]['name'] = $new_name;
return true;
} else if (!empty($item['folders']))
if ($this->_mod_folder_name($list[$idx]['folders'], $folder, $new_name))
return true;
}
return false;
}
function prefs_table($args)
{
global $CURR_SECTION;
if ($args['section'] == 'folders') {
$this->add_texts('localization');
$rcmail = rcmail::get_instance();
// load folders list when needed
if ($CURR_SECTION)
- $select = rcmail_mailbox_select(array('noselection' => '---', 'realnames' => true,
+ $select = $rcmail->folder_selector(array('noselection' => '---', 'realnames' => true,
'maxlength' => 30, 'exceptions' => array('INBOX'), 'folder_filter' => 'mail', 'folder_rights' => 'w'));
else
$select = new html_select();
$args['blocks']['main']['options']['archive_mbox'] = array(
'title' => $this->gettext('archivefolder'),
'content' => $select->show($rcmail->config->get('archive_mbox'), array('name' => "_archive_mbox"))
);
}
return $args;
}
function save_prefs($args)
{
if ($args['section'] == 'folders') {
- $args['prefs']['archive_mbox'] = get_input_value('_archive_mbox', RCUBE_INPUT_POST);
+ $args['prefs']['archive_mbox'] = rcube_utils::get_input_value('_archive_mbox', rcube_utils::INPUT_POST);
return $args;
}
}
}
diff --git a/plugins/database_attachments/database_attachments.php b/plugins/database_attachments/database_attachments.php
index 079f4e567..2511dbbb2 100644
--- a/plugins/database_attachments/database_attachments.php
+++ b/plugins/database_attachments/database_attachments.php
@@ -1,169 +1,169 @@
<?php
/**
* Filesystem Attachments
*
* This plugin which provides database backed storage for temporary
* attachment file handling. The primary advantage of this plugin
* is its compatibility with round-robin dns multi-server roundcube
* installations.
*
* This plugin relies on the core filesystem_attachments plugin
*
* @author Ziba Scott <ziba@umich.edu>
* @author Aleksander Machniak <alec@alec.pl>
* @version @package_version@
*/
require_once('plugins/filesystem_attachments/filesystem_attachments.php');
class database_attachments extends filesystem_attachments
{
// A prefix for the cache key used in the session and in the key field of the cache table
private $cache_prefix = "db_attach";
/**
* Helper method to generate a unique key for the given attachment file
*/
private function _key($args)
{
$uname = $args['path'] ? $args['path'] : $args['name'];
return $this->cache_prefix . $args['group'] . md5(mktime() . $uname . $_SESSION['user_id']);
}
/**
* Save a newly uploaded attachment
*/
function upload($args)
{
$args['status'] = false;
$rcmail = rcmail::get_instance();
$key = $this->_key($args);
$data = file_get_contents($args['path']);
if ($data === false)
return $args;
$data = base64_encode($data);
$status = $rcmail->db->query(
- "INSERT INTO ".get_table_name('cache')
+ "INSERT INTO ".$rcmail->db->table_name('cache')
." (created, user_id, cache_key, data)"
." VALUES (".$rcmail->db->now().", ?, ?, ?)",
$_SESSION['user_id'],
$key,
$data);
if ($status) {
$args['id'] = $key;
$args['status'] = true;
unset($args['path']);
}
return $args;
}
/**
* Save an attachment from a non-upload source (draft or forward)
*/
function save($args)
{
$args['status'] = false;
$rcmail = rcmail::get_instance();
$key = $this->_key($args);
if ($args['path']) {
$args['data'] = file_get_contents($args['path']);
if ($args['data'] === false)
return $args;
}
$data = base64_encode($args['data']);
$status = $rcmail->db->query(
- "INSERT INTO ".get_table_name('cache')
+ "INSERT INTO ".$rcmail->db->table_name('cache')
." (created, user_id, cache_key, data)"
." VALUES (".$rcmail->db->now().", ?, ?, ?)",
$_SESSION['user_id'],
$key,
$data);
if ($status) {
$args['id'] = $key;
$args['status'] = true;
}
return $args;
}
/**
* Remove an attachment from storage
* This is triggered by the remove attachment button on the compose screen
*/
function remove($args)
{
$args['status'] = false;
$rcmail = rcmail::get_instance();
$status = $rcmail->db->query(
- "DELETE FROM ".get_table_name('cache')
+ "DELETE FROM ".$rcmail->db->table_name('cache')
." WHERE user_id = ?"
." AND cache_key = ?",
$_SESSION['user_id'],
$args['id']);
if ($status) {
$args['status'] = true;
}
return $args;
}
/**
* When composing an html message, image attachments may be shown
* For this plugin, $this->get() will check the file and
* return it's contents
*/
function display($args)
{
return $this->get($args);
}
/**
* When displaying or sending the attachment the file contents are fetched
* using this method. This is also called by the attachment_display hook.
*/
function get($args)
{
$rcmail = rcmail::get_instance();
$sql_result = $rcmail->db->query(
"SELECT data"
- ." FROM ".get_table_name('cache')
+ ." FROM ".$rcmail->db->table_name('cache')
." WHERE user_id=?"
." AND cache_key=?",
$_SESSION['user_id'],
$args['id']);
if ($sql_arr = $rcmail->db->fetch_assoc($sql_result)) {
$args['data'] = base64_decode($sql_arr['data']);
$args['status'] = true;
}
return $args;
}
/**
* Delete all temp files associated with this user
*/
function cleanup($args)
{
$prefix = $this->cache_prefix . $args['group'];
$rcmail = rcmail::get_instance();
$rcmail->db->query(
- "DELETE FROM ".get_table_name('cache')
+ "DELETE FROM ".$rcmail->db->table_name('cache')
." WHERE user_id = ?"
." AND cache_key LIKE '{$prefix}%'",
$_SESSION['user_id']);
}
}
diff --git a/plugins/enigma/enigma.php b/plugins/enigma/enigma.php
index a4009ce26..c96b94620 100644
--- a/plugins/enigma/enigma.php
+++ b/plugins/enigma/enigma.php
@@ -1,475 +1,475 @@
<?php
/*
+-------------------------------------------------------------------------+
| Enigma Plugin for Roundcube |
| Version 0.1 |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License version 2 |
| as published by the Free Software Foundation. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with this program; if not, write to the Free Software Foundation, Inc., |
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| |
+-------------------------------------------------------------------------+
| Author: Aleksander Machniak <alec@alec.pl> |
+-------------------------------------------------------------------------+
*/
/*
This class contains only hooks and action handlers.
Most plugin logic is placed in enigma_engine and enigma_ui classes.
*/
class enigma extends rcube_plugin
{
public $task = 'mail|settings';
public $rc;
public $engine;
private $env_loaded;
private $message;
private $keys_parts = array();
private $keys_bodies = array();
/**
* Plugin initialization.
*/
function init()
{
$rcmail = rcmail::get_instance();
$this->rc = $rcmail;
if ($this->rc->task == 'mail') {
// message parse/display hooks
$this->add_hook('message_part_structure', array($this, 'parse_structure'));
$this->add_hook('message_body_prefix', array($this, 'status_message'));
// message displaying
if ($rcmail->action == 'show' || $rcmail->action == 'preview') {
$this->add_hook('message_load', array($this, 'message_load'));
$this->add_hook('template_object_messagebody', array($this, 'message_output'));
$this->register_action('plugin.enigmaimport', array($this, 'import_file'));
}
// message composing
else if ($rcmail->action == 'compose') {
$this->load_ui();
$this->ui->init($section);
}
// message sending (and draft storing)
else if ($rcmail->action == 'sendmail') {
//$this->add_hook('outgoing_message_body', array($this, 'msg_encode'));
//$this->add_hook('outgoing_message_body', array($this, 'msg_sign'));
}
}
else if ($this->rc->task == 'settings') {
// add hooks for Enigma settings
$this->add_hook('preferences_sections_list', array($this, 'preferences_section'));
$this->add_hook('preferences_list', array($this, 'preferences_list'));
$this->add_hook('preferences_save', array($this, 'preferences_save'));
// register handler for keys/certs management
$this->register_action('plugin.enigma', array($this, 'preferences_ui'));
// grab keys/certs management iframe requests
- $section = get_input_value('_section', RCUBE_INPUT_GET);
+ $section = rcube_utils::get_input_value('_section', rcube_utils::INPUT_GET);
if ($this->rc->action == 'edit-prefs' && preg_match('/^enigma(certs|keys)/', $section)) {
$this->load_ui();
$this->ui->init($section);
}
}
}
/**
* Plugin environment initialization.
*/
function load_env()
{
if ($this->env_loaded)
return;
$this->env_loaded = true;
// Add include path for Enigma classes and drivers
$include_path = $this->home . '/lib' . PATH_SEPARATOR;
$include_path .= ini_get('include_path');
set_include_path($include_path);
// load the Enigma plugin configuration
$this->load_config();
// include localization (if wasn't included before)
$this->add_texts('localization/');
}
/**
* Plugin UI initialization.
*/
function load_ui()
{
if ($this->ui)
return;
// load config/localization
$this->load_env();
// Load UI
$this->ui = new enigma_ui($this, $this->home);
}
/**
* Plugin engine initialization.
*/
function load_engine()
{
if ($this->engine)
return;
// load config/localization
$this->load_env();
$this->engine = new enigma_engine($this);
}
/**
* Handler for message_part_structure hook.
* Called for every part of the message.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function parse_structure($p)
{
$struct = $p['structure'];
if ($p['mimetype'] == 'text/plain' || $p['mimetype'] == 'application/pgp') {
$this->parse_plain($p);
}
else if ($p['mimetype'] == 'multipart/signed') {
$this->parse_signed($p);
}
else if ($p['mimetype'] == 'multipart/encrypted') {
$this->parse_encrypted($p);
}
else if ($p['mimetype'] == 'application/pkcs7-mime') {
$this->parse_encrypted($p);
}
return $p;
}
/**
* Handler for preferences_sections_list hook.
* Adds Enigma settings sections into preferences sections list.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function preferences_section($p)
{
// add labels
$this->add_texts('localization/');
$p['list']['enigmasettings'] = array(
'id' => 'enigmasettings', 'section' => $this->gettext('enigmasettings'),
);
$p['list']['enigmacerts'] = array(
'id' => 'enigmacerts', 'section' => $this->gettext('enigmacerts'),
);
$p['list']['enigmakeys'] = array(
'id' => 'enigmakeys', 'section' => $this->gettext('enigmakeys'),
);
return $p;
}
/**
* Handler for preferences_list hook.
* Adds options blocks into Enigma settings sections in Preferences.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function preferences_list($p)
{
if ($p['section'] == 'enigmasettings') {
// This makes that section is not removed from the list
$p['blocks']['dummy']['options']['dummy'] = array();
}
else if ($p['section'] == 'enigmacerts') {
// This makes that section is not removed from the list
$p['blocks']['dummy']['options']['dummy'] = array();
}
else if ($p['section'] == 'enigmakeys') {
// This makes that section is not removed from the list
$p['blocks']['dummy']['options']['dummy'] = array();
}
return $p;
}
/**
* Handler for preferences_save hook.
* Executed on Enigma settings form submit.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function preferences_save($p)
{
if ($p['section'] == 'enigmasettings') {
$a['prefs'] = array(
-// 'dummy' => get_input_value('_dummy', RCUBE_INPUT_POST),
+// 'dummy' => rcube_utils::get_input_value('_dummy', rcube_utils::INPUT_POST),
);
}
return $p;
}
/**
* Handler for keys/certs management UI template.
*/
function preferences_ui()
{
$this->load_ui();
$this->ui->init();
}
/**
* Handler for message_body_prefix hook.
* Called for every displayed (content) part of the message.
* Adds infobox about signature verification and/or decryption
* status above the body.
*
* @param array Original parameters
*
* @return array Modified parameters
*/
function status_message($p)
{
$part_id = $p['part']->mime_id;
// skip: not a message part
if ($p['part'] instanceof rcube_message)
return $p;
// skip: message has no signed/encoded content
if (!$this->engine)
return $p;
// Decryption status
if (isset($this->engine->decryptions[$part_id])) {
// get decryption status
$status = $this->engine->decryptions[$part_id];
// Load UI and add css script
$this->load_ui();
$this->ui->add_css();
// display status info
$attrib['id'] = 'enigma-message';
if ($status instanceof enigma_error) {
$attrib['class'] = 'enigmaerror';
$code = $status->getCode();
if ($code == enigma_error::E_KEYNOTFOUND)
- $msg = Q(str_replace('$keyid', enigma_key::format_id($status->getData('id')),
+ $msg = rcube::Q(str_replace('$keyid', enigma_key::format_id($status->getData('id')),
$this->gettext('decryptnokey')));
else if ($code == enigma_error::E_BADPASS)
- $msg = Q($this->gettext('decryptbadpass'));
+ $msg = rcube::Q($this->gettext('decryptbadpass'));
else
- $msg = Q($this->gettext('decrypterror'));
+ $msg = rcube::Q($this->gettext('decrypterror'));
}
else {
$attrib['class'] = 'enigmanotice';
- $msg = Q($this->gettext('decryptok'));
+ $msg = rcube::Q($this->gettext('decryptok'));
}
$p['prefix'] .= html::div($attrib, $msg);
}
// Signature verification status
if (isset($this->engine->signed_parts[$part_id])
&& ($sig = $this->engine->signatures[$this->engine->signed_parts[$part_id]])
) {
// add css script
$this->load_ui();
$this->ui->add_css();
// display status info
$attrib['id'] = 'enigma-message';
if ($sig instanceof enigma_signature) {
if ($sig->valid) {
$attrib['class'] = 'enigmanotice';
$sender = ($sig->name ? $sig->name . ' ' : '') . '<' . $sig->email . '>';
- $msg = Q(str_replace('$sender', $sender, $this->gettext('sigvalid')));
+ $msg = rcube::Q(str_replace('$sender', $sender, $this->gettext('sigvalid')));
}
else {
$attrib['class'] = 'enigmawarning';
$sender = ($sig->name ? $sig->name . ' ' : '') . '<' . $sig->email . '>';
- $msg = Q(str_replace('$sender', $sender, $this->gettext('siginvalid')));
+ $msg = rcube::Q(str_replace('$sender', $sender, $this->gettext('siginvalid')));
}
}
else if ($sig->getCode() == enigma_error::E_KEYNOTFOUND) {
$attrib['class'] = 'enigmawarning';
- $msg = Q(str_replace('$keyid', enigma_key::format_id($sig->getData('id')),
+ $msg = rcube::Q(str_replace('$keyid', enigma_key::format_id($sig->getData('id')),
$this->gettext('signokey')));
}
else {
$attrib['class'] = 'enigmaerror';
- $msg = Q($this->gettext('sigerror'));
+ $msg = rcube::Q($this->gettext('sigerror'));
}
/*
$msg .= '&nbsp;' . html::a(array('href' => "#sigdetails",
- 'onclick' => JS_OBJECT_NAME.".command('enigma-sig-details')"),
- Q($this->gettext('showdetails')));
+ 'onclick' => rcmail_output::JS_OBJECT_NAME.".command('enigma-sig-details')"),
+ rcube::Q($this->gettext('showdetails')));
*/
// test
// $msg .= '<br /><pre>'.$sig->body.'</pre>';
$p['prefix'] .= html::div($attrib, $msg);
// Display each signature message only once
unset($this->engine->signatures[$this->engine->signed_parts[$part_id]]);
}
return $p;
}
/**
* Handler for plain/text message.
*
* @param array Reference to hook's parameters (see enigma::parse_structure())
*/
private function parse_plain(&$p)
{
$this->load_engine();
$this->engine->parse_plain($p);
}
/**
* Handler for multipart/signed message.
* Verifies signature.
*
* @param array Reference to hook's parameters (see enigma::parse_structure())
*/
private function parse_signed(&$p)
{
$this->load_engine();
$this->engine->parse_signed($p);
}
/**
* Handler for multipart/encrypted and application/pkcs7-mime message.
*
* @param array Reference to hook's parameters (see enigma::parse_structure())
*/
private function parse_encrypted(&$p)
{
$this->load_engine();
$this->engine->parse_encrypted($p);
}
/**
* Handler for message_load hook.
* Check message bodies and attachments for keys/certs.
*/
function message_load($p)
{
$this->message = $p['object'];
// handle attachments vcard attachments
foreach ((array)$this->message->attachments as $attachment) {
if ($this->is_keys_part($attachment)) {
$this->keys_parts[] = $attachment->mime_id;
}
}
// the same with message bodies
foreach ((array)$this->message->parts as $idx => $part) {
if ($this->is_keys_part($part)) {
$this->keys_parts[] = $part->mime_id;
$this->keys_bodies[] = $part->mime_id;
}
}
// @TODO: inline PGP keys
if ($this->keys_parts) {
$this->add_texts('localization');
}
}
/**
* Handler for template_object_messagebody hook.
* This callback function adds a box below the message content
* if there is a key/cert attachment available
*/
function message_output($p)
{
$attach_script = false;
foreach ($this->keys_parts as $part) {
// remove part's body
if (in_array($part, $this->keys_bodies))
$p['content'] = '';
$style = "margin:0 1em; padding:0.2em 0.5em; border:1px solid #999; width: auto"
." border-radius:4px; -moz-border-radius:4px; -webkit-border-radius:4px";
// add box below message body
$p['content'] .= html::p(array('style' => $style),
html::a(array(
'href' => "#",
- 'onclick' => "return ".JS_OBJECT_NAME.".enigma_import_attachment('".JQ($part)."')",
+ 'onclick' => "return ".rcmail_output::JS_OBJECT_NAME.".enigma_import_attachment('".rcube::JQ($part)."')",
'title' => $this->gettext('keyattimport')),
html::img(array('src' => $this->url('skins/classic/key_add.png'), 'style' => "vertical-align:middle")))
. ' ' . html::span(null, $this->gettext('keyattfound')));
$attach_script = true;
}
if ($attach_script) {
$this->include_script('enigma.js');
}
return $p;
}
/**
* Handler for attached keys/certs import
*/
function import_file()
{
$this->load_engine();
$this->engine->import_file();
}
/**
* Checks if specified message part is a PGP-key or S/MIME cert data
*
* @param rcube_message_part Part object
*
* @return boolean True if part is a key/cert
*/
private function is_keys_part($part)
{
// @TODO: S/MIME
return (
// Content-Type: application/pgp-keys
$part->mimetype == 'application/pgp-keys'
);
}
}
diff --git a/plugins/enigma/lib/enigma_engine.php b/plugins/enigma/lib/enigma_engine.php
index 89cb4b796..220d6c0b3 100644
--- a/plugins/enigma/lib/enigma_engine.php
+++ b/plugins/enigma/lib/enigma_engine.php
@@ -1,547 +1,547 @@
<?php
/*
+-------------------------------------------------------------------------+
| Engine of the Enigma Plugin |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License version 2 |
| as published by the Free Software Foundation. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with this program; if not, write to the Free Software Foundation, Inc., |
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| |
+-------------------------------------------------------------------------+
| Author: Aleksander Machniak <alec@alec.pl> |
+-------------------------------------------------------------------------+
*/
/*
RFC2440: OpenPGP Message Format
RFC3156: MIME Security with OpenPGP
RFC3851: S/MIME
*/
class enigma_engine
{
private $rc;
private $enigma;
private $pgp_driver;
private $smime_driver;
public $decryptions = array();
public $signatures = array();
public $signed_parts = array();
/**
* Plugin initialization.
*/
function __construct($enigma)
{
$rcmail = rcmail::get_instance();
$this->rc = $rcmail;
$this->enigma = $enigma;
}
/**
* PGP driver initialization.
*/
function load_pgp_driver()
{
if ($this->pgp_driver)
return;
$driver = 'enigma_driver_' . $this->rc->config->get('enigma_pgp_driver', 'gnupg');
$username = $this->rc->user->get_username();
// Load driver
$this->pgp_driver = new $driver($username);
if (!$this->pgp_driver) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: Unable to load PGP driver: $driver"
), true, true);
}
// Initialise driver
$result = $this->pgp_driver->init();
if ($result instanceof enigma_error) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: ".$result->getMessage()
), true, true);
}
}
/**
* S/MIME driver initialization.
*/
function load_smime_driver()
{
if ($this->smime_driver)
return;
// NOT IMPLEMENTED!
return;
$driver = 'enigma_driver_' . $this->rc->config->get('enigma_smime_driver', 'phpssl');
$username = $this->rc->user->get_username();
// Load driver
$this->smime_driver = new $driver($username);
if (!$this->smime_driver) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: Unable to load S/MIME driver: $driver"
), true, true);
}
// Initialise driver
$result = $this->smime_driver->init();
if ($result instanceof enigma_error) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: ".$result->getMessage()
), true, true);
}
}
/**
* Handler for plain/text message.
*
* @param array Reference to hook's parameters
*/
function parse_plain(&$p)
{
$part = $p['structure'];
// Get message body from IMAP server
$this->set_part_body($part, $p['object']->uid);
// @TODO: big message body can be a file resource
// PGP signed message
if (preg_match('/^-----BEGIN PGP SIGNED MESSAGE-----/', $part->body)) {
$this->parse_plain_signed($p);
}
// PGP encrypted message
else if (preg_match('/^-----BEGIN PGP MESSAGE-----/', $part->body)) {
$this->parse_plain_encrypted($p);
}
}
/**
* Handler for multipart/signed message.
*
* @param array Reference to hook's parameters
*/
function parse_signed(&$p)
{
$struct = $p['structure'];
// S/MIME
if ($struct->parts[1] && $struct->parts[1]->mimetype == 'application/pkcs7-signature') {
$this->parse_smime_signed($p);
}
// PGP/MIME:
// The multipart/signed body MUST consist of exactly two parts.
// The first part contains the signed data in MIME canonical format,
// including a set of appropriate content headers describing the data.
// The second body MUST contain the PGP digital signature. It MUST be
// labeled with a content type of "application/pgp-signature".
else if ($struct->parts[1] && $struct->parts[1]->mimetype == 'application/pgp-signature') {
$this->parse_pgp_signed($p);
}
}
/**
* Handler for multipart/encrypted message.
*
* @param array Reference to hook's parameters
*/
function parse_encrypted(&$p)
{
$struct = $p['structure'];
// S/MIME
if ($struct->mimetype == 'application/pkcs7-mime') {
$this->parse_smime_encrypted($p);
}
// PGP/MIME:
// The multipart/encrypted MUST consist of exactly two parts. The first
// MIME body part must have a content type of "application/pgp-encrypted".
// This body contains the control information.
// The second MIME body part MUST contain the actual encrypted data. It
// must be labeled with a content type of "application/octet-stream".
else if ($struct->parts[0] && $struct->parts[0]->mimetype == 'application/pgp-encrypted' &&
$struct->parts[1] && $struct->parts[1]->mimetype == 'application/octet-stream'
) {
$this->parse_pgp_encrypted($p);
}
}
/**
* Handler for plain signed message.
* Excludes message and signature bodies and verifies signature.
*
* @param array Reference to hook's parameters
*/
private function parse_plain_signed(&$p)
{
$this->load_pgp_driver();
$part = $p['structure'];
// Verify signature
if ($this->rc->action == 'show' || $this->rc->action == 'preview') {
$sig = $this->pgp_verify($part->body);
}
// @TODO: Handle big bodies using (temp) files
// In this way we can use fgets on string as on file handle
$fh = fopen('php://memory', 'br+');
// @TODO: fopen/fwrite errors handling
if ($fh) {
fwrite($fh, $part->body);
rewind($fh);
}
$part->body = null;
// Extract body (and signature?)
while (!feof($fh)) {
$line = fgets($fh, 1024);
if ($part->body === null)
$part->body = '';
else if (preg_match('/^-----BEGIN PGP SIGNATURE-----/', $line))
break;
else
$part->body .= $line;
}
// Remove "Hash" Armor Headers
$part->body = preg_replace('/^.*\r*\n\r*\n/', '', $part->body);
// de-Dash-Escape (RFC2440)
$part->body = preg_replace('/(^|\n)- -/', '\\1-', $part->body);
// Store signature data for display
if (!empty($sig)) {
$this->signed_parts[$part->mime_id] = $part->mime_id;
$this->signatures[$part->mime_id] = $sig;
}
fclose($fh);
}
/**
* Handler for PGP/MIME signed message.
* Verifies signature.
*
* @param array Reference to hook's parameters
*/
private function parse_pgp_signed(&$p)
{
$this->load_pgp_driver();
$struct = $p['structure'];
// Verify signature
if ($this->rc->action == 'show' || $this->rc->action == 'preview') {
$msg_part = $struct->parts[0];
$sig_part = $struct->parts[1];
// Get bodies
$this->set_part_body($msg_part, $p['object']->uid);
$this->set_part_body($sig_part, $p['object']->uid);
// Verify
$sig = $this->pgp_verify($msg_part->body, $sig_part->body);
// Store signature data for display
$this->signatures[$struct->mime_id] = $sig;
// Message can be multipart (assign signature to each subpart)
if (!empty($msg_part->parts)) {
foreach ($msg_part->parts as $part)
$this->signed_parts[$part->mime_id] = $struct->mime_id;
}
else
$this->signed_parts[$msg_part->mime_id] = $struct->mime_id;
// Remove signature file from attachments list
unset($struct->parts[1]);
}
}
/**
* Handler for S/MIME signed message.
* Verifies signature.
*
* @param array Reference to hook's parameters
*/
private function parse_smime_signed(&$p)
{
$this->load_smime_driver();
}
/**
* Handler for plain encrypted message.
*
* @param array Reference to hook's parameters
*/
private function parse_plain_encrypted(&$p)
{
$this->load_pgp_driver();
$part = $p['structure'];
// Get body
$this->set_part_body($part, $p['object']->uid);
// Decrypt
$result = $this->pgp_decrypt($part->body);
// Store decryption status
$this->decryptions[$part->mime_id] = $result;
// Parse decrypted message
if ($result === true) {
// @TODO
}
}
/**
* Handler for PGP/MIME encrypted message.
*
* @param array Reference to hook's parameters
*/
private function parse_pgp_encrypted(&$p)
{
$this->load_pgp_driver();
$struct = $p['structure'];
$part = $struct->parts[1];
// Get body
$this->set_part_body($part, $p['object']->uid);
// Decrypt
$result = $this->pgp_decrypt($part->body);
$this->decryptions[$part->mime_id] = $result;
//print_r($part);
// Parse decrypted message
if ($result === true) {
// @TODO
}
else {
// Make sure decryption status message will be displayed
$part->type = 'content';
$p['object']->parts[] = $part;
}
}
/**
* Handler for S/MIME encrypted message.
*
* @param array Reference to hook's parameters
*/
private function parse_smime_encrypted(&$p)
{
$this->load_smime_driver();
}
/**
* PGP signature verification.
*
* @param mixed Message body
* @param mixed Signature body (for MIME messages)
*
* @return mixed enigma_signature or enigma_error
*/
private function pgp_verify(&$msg_body, $sig_body=null)
{
// @TODO: Handle big bodies using (temp) files
// @TODO: caching of verification result
$sig = $this->pgp_driver->verify($msg_body, $sig_body);
if (($sig instanceof enigma_error) && $sig->getCode() != enigma_error::E_KEYNOTFOUND)
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: " . $error->getMessage()
), true, false);
//print_r($sig);
return $sig;
}
/**
* PGP message decryption.
*
* @param mixed Message body
*
* @return mixed True or enigma_error
*/
private function pgp_decrypt(&$msg_body)
{
// @TODO: Handle big bodies using (temp) files
// @TODO: caching of verification result
$result = $this->pgp_driver->decrypt($msg_body, $key, $pass);
//print_r($result);
if ($result instanceof enigma_error) {
$err_code = $result->getCode();
if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS)))
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: " . $result->getMessage()
), true, false);
return $result;
}
// $msg_body = $result;
return true;
}
/**
* PGP keys listing.
*
* @param mixed Key ID/Name pattern
*
* @return mixed Array of keys or enigma_error
*/
function list_keys($pattern='')
{
$this->load_pgp_driver();
$result = $this->pgp_driver->list_keys($pattern);
if ($result instanceof enigma_error) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: " . $result->getMessage()
), true, false);
}
return $result;
}
/**
* PGP key details.
*
* @param mixed Key ID
*
* @return mixed enigma_key or enigma_error
*/
function get_key($keyid)
{
$this->load_pgp_driver();
$result = $this->pgp_driver->get_key($keyid);
if ($result instanceof enigma_error) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: " . $result->getMessage()
), true, false);
}
return $result;
}
/**
* PGP keys/certs importing.
*
* @param mixed Import file name or content
* @param boolean True if first argument is a filename
*
* @return mixed Import status data array or enigma_error
*/
function import_key($content, $isfile=false)
{
$this->load_pgp_driver();
$result = $this->pgp_driver->import($content, $isfile);
if ($result instanceof enigma_error) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: " . $result->getMessage()
), true, false);
}
else {
$result['imported'] = $result['public_imported'] + $result['private_imported'];
$result['unchanged'] = $result['public_unchanged'] + $result['private_unchanged'];
}
return $result;
}
/**
* Handler for keys/certs import request action
*/
function import_file()
{
- $uid = get_input_value('_uid', RCUBE_INPUT_POST);
- $mbox = get_input_value('_mbox', RCUBE_INPUT_POST);
- $mime_id = get_input_value('_part', RCUBE_INPUT_POST);
+ $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
+ $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
+ $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
if ($uid && $mime_id) {
$part = $this->rc->storage->get_message_part($uid, $mime_id);
}
if ($part && is_array($result = $this->import_key($part))) {
$this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation',
array('new' => $result['imported'], 'old' => $result['unchanged']));
}
else
$this->rc->output->show_message('enigma.keysimportfailed', 'error');
$this->rc->output->send();
}
/**
* Checks if specified message part contains body data.
* If body is not set it will be fetched from IMAP server.
*
* @param rcube_message_part Message part object
* @param integer Message UID
*/
private function set_part_body($part, $uid)
{
// @TODO: Create such function in core
// @TODO: Handle big bodies using file handles
if (!isset($part->body)) {
$part->body = $this->rc->storage->get_message_part(
$uid, $part->mime_id, $part);
}
}
/**
* Adds CSS style file to the page header.
*/
private function add_css()
{
$skin = $this->rc->config->get('skin');
if (!file_exists($this->home . "/skins/$skin/enigma.css"))
$skin = 'default';
$this->include_stylesheet("skins/$skin/enigma.css");
}
}
diff --git a/plugins/enigma/lib/enigma_ui.php b/plugins/enigma/lib/enigma_ui.php
index dc3580872..47366b7e8 100644
--- a/plugins/enigma/lib/enigma_ui.php
+++ b/plugins/enigma/lib/enigma_ui.php
@@ -1,456 +1,456 @@
<?php
/*
+-------------------------------------------------------------------------+
| User Interface for the Enigma Plugin |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License version 2 |
| as published by the Free Software Foundation. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with this program; if not, write to the Free Software Foundation, Inc., |
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| |
+-------------------------------------------------------------------------+
| Author: Aleksander Machniak <alec@alec.pl> |
+-------------------------------------------------------------------------+
*/
class enigma_ui
{
private $rc;
private $enigma;
private $home;
private $css_added;
private $data;
function __construct($enigma_plugin, $home='')
{
$this->enigma = $enigma_plugin;
$this->rc = $enigma_plugin->rc;
// we cannot use $enigma_plugin->home here
$this->home = $home;
}
/**
* UI initialization and requests handlers.
*
* @param string Preferences section
*/
function init($section='')
{
$this->enigma->include_script('enigma.js');
// Enigma actions
if ($this->rc->action == 'plugin.enigma') {
- $action = get_input_value('_a', RCUBE_INPUT_GPC);
+ $action = rcube_utils::get_input_value('_a', rcube_utils::INPUT_GPC);
switch ($action) {
case 'keyedit':
$this->key_edit();
break;
case 'keyimport':
$this->key_import();
break;
case 'keysearch':
case 'keylist':
$this->key_list();
break;
case 'keyinfo':
default:
$this->key_info();
}
}
// Message composing UI
else if ($this->rc->action == 'compose') {
$this->compose_ui();
}
// Preferences UI
else { // if ($this->rc->action == 'edit-prefs') {
if ($section == 'enigmacerts') {
$this->rc->output->add_handlers(array(
'keyslist' => array($this, 'tpl_certs_list'),
'keyframe' => array($this, 'tpl_cert_frame'),
'countdisplay' => array($this, 'tpl_certs_rowcount'),
'searchform' => array($this->rc->output, 'search_form'),
));
$this->rc->output->set_pagetitle($this->enigma->gettext('enigmacerts'));
$this->rc->output->send('enigma.certs');
}
else {
$this->rc->output->add_handlers(array(
'keyslist' => array($this, 'tpl_keys_list'),
'keyframe' => array($this, 'tpl_key_frame'),
'countdisplay' => array($this, 'tpl_keys_rowcount'),
'searchform' => array($this->rc->output, 'search_form'),
));
$this->rc->output->set_pagetitle($this->enigma->gettext('enigmakeys'));
$this->rc->output->send('enigma.keys');
}
}
}
/**
* Adds CSS style file to the page header.
*/
function add_css()
{
if ($this->css_loaded)
return;
$skin = $this->rc->config->get('skin');
if (!file_exists($this->home . "/skins/$skin/enigma.css"))
$skin = 'default';
$this->enigma->include_stylesheet("skins/$skin/enigma.css");
$this->css_added = true;
}
/**
* Template object for key info/edit frame.
*
* @param array Object attributes
*
* @return string HTML output
*/
function tpl_key_frame($attrib)
{
if (!$attrib['id']) {
$attrib['id'] = 'rcmkeysframe';
}
$attrib['name'] = $attrib['id'];
$this->rc->output->set_env('contentframe', $attrib['name']);
$this->rc->output->set_env('blankpage', $attrib['src'] ?
$this->rc->output->abs_url($attrib['src']) : 'program/resources/blank.gif');
return $this->rc->output->frame($attrib);
}
/**
* Template object for list of keys.
*
* @param array Object attributes
*
* @return string HTML content
*/
function tpl_keys_list($attrib)
{
// add id to message list table if not specified
if (!strlen($attrib['id'])) {
$attrib['id'] = 'rcmenigmakeyslist';
}
// define list of cols to be displayed
$a_show_cols = array('name');
// create XHTML table
- $out = rcube_table_output($attrib, array(), $a_show_cols, 'id');
+ $out = $this->rc->table_output($attrib, array(), $a_show_cols, 'id');
// set client env
$this->rc->output->add_gui_object('keyslist', $attrib['id']);
$this->rc->output->include_script('list.js');
// add some labels to client
$this->rc->output->add_label('enigma.keyconfirmdelete');
return $out;
}
/**
* Key listing (and searching) request handler
*/
private function key_list()
{
$this->enigma->load_engine();
$pagesize = $this->rc->config->get('pagesize', 100);
- $page = max(intval(get_input_value('_p', RCUBE_INPUT_GPC)), 1);
- $search = get_input_value('_q', RCUBE_INPUT_GPC);
+ $page = max(intval(rcube_utils::get_input_value('_p', rcube_utils::INPUT_GPC)), 1);
+ $search = rcube_utils::get_input_value('_q', rcube_utils::INPUT_GPC);
// define list of cols to be displayed
$a_show_cols = array('name');
$result = array();
// Get the list
$list = $this->enigma->engine->list_keys($search);
if ($list && ($list instanceof enigma_error))
$this->rc->output->show_message('enigma.keylisterror', 'error');
else if (empty($list))
$this->rc->output->show_message('enigma.nokeysfound', 'notice');
else {
if (is_array($list)) {
// Save the size
$listsize = count($list);
// Sort the list by key (user) name
usort($list, array('enigma_key', 'cmp'));
// Slice current page
$list = array_slice($list, ($page - 1) * $pagesize, $pagesize);
$size = count($list);
// Add rows
foreach($list as $idx => $key) {
$this->rc->output->command('enigma_add_list_row',
- array('name' => Q($key->name), 'id' => $key->id));
+ array('name' => rcube::Q($key->name), 'id' => $key->id));
}
}
}
$this->rc->output->set_env('search_request', $search);
$this->rc->output->set_env('pagecount', ceil($listsize/$pagesize));
$this->rc->output->set_env('current_page', $page);
$this->rc->output->command('set_rowcount',
$this->get_rowcount_text($listsize, $size, $page));
$this->rc->output->send();
}
/**
* Template object for list records counter.
*
* @param array Object attributes
*
* @return string HTML output
*/
function tpl_keys_rowcount($attrib)
{
if (!$attrib['id'])
$attrib['id'] = 'rcmcountdisplay';
$this->rc->output->add_gui_object('countdisplay', $attrib['id']);
return html::span($attrib, $this->get_rowcount_text());
}
/**
* Returns text representation of list records counter
*/
private function get_rowcount_text($all=0, $curr_count=0, $page=1)
{
if (!$curr_count)
$out = $this->enigma->gettext('nokeysfound');
else {
$pagesize = $this->rc->config->get('pagesize', 100);
$first = ($page - 1) * $pagesize;
$out = $this->enigma->gettext(array(
'name' => 'keysfromto',
'vars' => array(
'from' => $first + 1,
'to' => $first + $curr_count,
'count' => $all)
));
}
return $out;
}
/**
* Key information page handler
*/
private function key_info()
{
- $id = get_input_value('_id', RCUBE_INPUT_GET);
+ $id = rcube_utils::get_input_value('_id', rcube_utils::INPUT_GET);
$this->enigma->load_engine();
$res = $this->enigma->engine->get_key($id);
if ($res instanceof enigma_key)
$this->data = $res;
else { // error
$this->rc->output->show_message('enigma.keyopenerror', 'error');
$this->rc->output->command('parent.enigma_loadframe');
$this->rc->output->send('iframe');
}
$this->rc->output->add_handlers(array(
'keyname' => array($this, 'tpl_key_name'),
'keydata' => array($this, 'tpl_key_data'),
));
$this->rc->output->set_pagetitle($this->enigma->gettext('keyinfo'));
$this->rc->output->send('enigma.keyinfo');
}
/**
* Template object for key name
*/
function tpl_key_name($attrib)
{
- return Q($this->data->name);
+ return rcube::Q($this->data->name);
}
/**
* Template object for key information page content
*/
function tpl_key_data($attrib)
{
$out = '';
$table = new html_table(array('cols' => 2));
// Key user ID
$table->add('title', $this->enigma->gettext('keyuserid'));
- $table->add(null, Q($this->data->name));
+ $table->add(null, rcube::Q($this->data->name));
// Key ID
$table->add('title', $this->enigma->gettext('keyid'));
$table->add(null, $this->data->subkeys[0]->get_short_id());
// Key type
$keytype = $this->data->get_type();
if ($keytype == enigma_key::TYPE_KEYPAIR)
$type = $this->enigma->gettext('typekeypair');
else if ($keytype == enigma_key::TYPE_PUBLIC)
$type = $this->enigma->gettext('typepublickey');
$table->add('title', $this->enigma->gettext('keytype'));
$table->add(null, $type);
// Key fingerprint
$table->add('title', $this->enigma->gettext('fingerprint'));
$table->add(null, $this->data->subkeys[0]->get_fingerprint());
$out .= html::tag('fieldset', null,
html::tag('legend', null,
$this->enigma->gettext('basicinfo')) . $table->show($attrib));
// Subkeys
$table = new html_table(array('cols' => 6));
// Columns: Type, ID, Algorithm, Size, Created, Expires
$out .= html::tag('fieldset', null,
html::tag('legend', null,
$this->enigma->gettext('subkeys')) . $table->show($attrib));
// Additional user IDs
$table = new html_table(array('cols' => 2));
// Columns: User ID, Validity
$out .= html::tag('fieldset', null,
html::tag('legend', null,
$this->enigma->gettext('userids')) . $table->show($attrib));
return $out;
}
/**
* Key import page handler
*/
private function key_import()
{
// Import process
if ($_FILES['_file']['tmp_name'] && is_uploaded_file($_FILES['_file']['tmp_name'])) {
$this->enigma->load_engine();
$result = $this->enigma->engine->import_key($_FILES['_file']['tmp_name'], true);
if (is_array($result)) {
// reload list if any keys has been added
if ($result['imported']) {
$this->rc->output->command('parent.enigma_list', 1);
}
else
$this->rc->output->command('parent.enigma_loadframe');
$this->rc->output->show_message('enigma.keysimportsuccess', 'confirmation',
array('new' => $result['imported'], 'old' => $result['unchanged']));
$this->rc->output->send('iframe');
}
else
$this->rc->output->show_message('enigma.keysimportfailed', 'error');
}
else if ($err = $_FILES['_file']['error']) {
if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
$this->rc->output->show_message('filesizeerror', 'error',
- array('size' => show_bytes(parse_bytes(ini_get('upload_max_filesize')))));
+ array('size' => $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize')))));
} else {
$this->rc->output->show_message('fileuploaderror', 'error');
}
}
$this->rc->output->add_handlers(array(
'importform' => array($this, 'tpl_key_import_form'),
));
$this->rc->output->set_pagetitle($this->enigma->gettext('keyimport'));
$this->rc->output->send('enigma.keyimport');
}
/**
* Template object for key import (upload) form
*/
function tpl_key_import_form($attrib)
{
$attrib += array('id' => 'rcmKeyImportForm');
$upload = new html_inputfield(array('type' => 'file', 'name' => '_file',
'id' => 'rcmimportfile', 'size' => 30));
$form = html::p(null,
- Q($this->enigma->gettext('keyimporttext'), 'show')
+ rcube::Q($this->enigma->gettext('keyimporttext'), 'show')
. html::br() . html::br() . $upload->show()
);
$this->rc->output->add_label('selectimportfile', 'importwait');
$this->rc->output->add_gui_object('importform', $attrib['id']);
$out = $this->rc->output->form_tag(array(
'action' => $this->rc->url(array('action' => 'plugin.enigma', 'a' => 'keyimport')),
'method' => 'post',
'enctype' => 'multipart/form-data') + $attrib,
$form);
return $out;
}
private function compose_ui()
{
// Options menu button
// @TODO: make this work with non-default skins
$this->enigma->add_button(array(
'name' => 'enigmamenu',
'imagepas' => 'skins/default/enigma.png',
'imageact' => 'skins/default/enigma.png',
'onclick' => "rcmail_ui.show_popup('enigmamenu', true); return false",
'title' => 'securityoptions',
'domain' => 'enigma',
), 'toolbar');
// Options menu contents
$this->enigma->add_hook('render_page', array($this, 'compose_menu'));
}
function compose_menu($p)
{
$menu = new html_table(array('cols' => 2));
$chbox = new html_checkbox(array('value' => 1));
$menu->add(null, html::label(array('for' => 'enigmadefaultopt'),
- Q($this->enigma->gettext('identdefault'))));
+ rcube::Q($this->enigma->gettext('identdefault'))));
$menu->add(null, $chbox->show(1, array('name' => '_enigma_default', 'id' => 'enigmadefaultopt')));
$menu->add(null, html::label(array('for' => 'enigmasignopt'),
- Q($this->enigma->gettext('signmsg'))));
+ rcube::Q($this->enigma->gettext('signmsg'))));
$menu->add(null, $chbox->show(1, array('name' => '_enigma_sign', 'id' => 'enigmasignopt')));
$menu->add(null, html::label(array('for' => 'enigmacryptopt'),
- Q($this->enigma->gettext('encryptmsg'))));
+ rcube::Q($this->enigma->gettext('encryptmsg'))));
$menu->add(null, $chbox->show(1, array('name' => '_enigma_crypt', 'id' => 'enigmacryptopt')));
$menu = html::div(array('id' => 'enigmamenu', 'class' => 'popupmenu'),
$menu->show());
$p['content'] = preg_replace('/(<form name="form"[^>]+>)/i', '\\1'."\n$menu", $p['content']);
return $p;
}
}
diff --git a/plugins/hide_blockquote/hide_blockquote.php b/plugins/hide_blockquote/hide_blockquote.php
index 7af163dcd..1168656fd 100644
--- a/plugins/hide_blockquote/hide_blockquote.php
+++ b/plugins/hide_blockquote/hide_blockquote.php
@@ -1,78 +1,78 @@
<?php
/**
* Quotation block hidding
*
* Plugin that adds a possibility to hide long blocks of cited text in messages.
*
* Configuration:
* // Minimum number of citation lines. Longer citation blocks will be hidden.
* // 0 - no limit (no hidding).
* $rcmail_config['hide_blockquote_limit'] = 0;
*
* @version @package_version@
* @license GNU GPLv3+
* @author Aleksander Machniak <alec@alec.pl>
*/
class hide_blockquote extends rcube_plugin
{
public $task = 'mail|settings';
function init()
{
$rcmail = rcmail::get_instance();
if ($rcmail->task == 'mail'
&& ($rcmail->action == 'preview' || $rcmail->action == 'show')
&& ($limit = $rcmail->config->get('hide_blockquote_limit'))
) {
// include styles
$this->include_stylesheet($this->local_skin_path() . "/style.css");
// Script and localization
$this->include_script('hide_blockquote.js');
$this->add_texts('localization', true);
// set env variable for client
$rcmail->output->set_env('blockquote_limit', $limit);
}
else if ($rcmail->task == 'settings') {
$dont_override = $rcmail->config->get('dont_override', array());
if (!in_array('hide_blockquote_limit', $dont_override)) {
$this->add_hook('preferences_list', array($this, 'prefs_table'));
$this->add_hook('preferences_save', array($this, 'save_prefs'));
}
}
}
function prefs_table($args)
{
if ($args['section'] != 'mailview') {
return $args;
}
$this->add_texts('localization');
$rcmail = rcmail::get_instance();
$limit = (int) $rcmail->config->get('hide_blockquote_limit');
$field_id = 'hide_blockquote_limit';
$input = new html_inputfield(array('name' => '_'.$field_id, 'id' => $field_id, 'size' => 5));
$args['blocks']['main']['options']['hide_blockquote_limit'] = array(
'title' => $this->gettext('quotelimit'),
'content' => $input->show($limit ? $limit : '')
);
return $args;
}
function save_prefs($args)
{
if ($args['section'] == 'mailview') {
- $args['prefs']['hide_blockquote_limit'] = (int) get_input_value('_hide_blockquote_limit', RCUBE_INPUT_POST);
+ $args['prefs']['hide_blockquote_limit'] = (int) rcube_utils::get_input_value('_hide_blockquote_limit', rcube_utils::INPUT_POST);
}
return $args;
}
}
diff --git a/plugins/http_authentication/http_authentication.php b/plugins/http_authentication/http_authentication.php
index a94b6121a..57227cb03 100644
--- a/plugins/http_authentication/http_authentication.php
+++ b/plugins/http_authentication/http_authentication.php
@@ -1,92 +1,92 @@
<?php
/**
* HTTP Basic Authentication
*
* Make use of an existing HTTP authentication and perform login with the existing user credentials
*
* Configuration:
* // redirect the client to this URL after logout. This page is then responsible to clear HTTP auth
* $rcmail_config['logout_url'] = 'http://server.tld/logout.html';
*
* See logout.html (in this directory) for an example how HTTP auth can be cleared.
*
* For other configuration options, see config.inc.php.dist!
*
* @version @package_version@
* @license GNU GPLv3+
* @author Thomas Bruederli
*/
class http_authentication extends rcube_plugin
{
function init()
{
$this->add_hook('startup', array($this, 'startup'));
$this->add_hook('authenticate', array($this, 'authenticate'));
$this->add_hook('logout_after', array($this, 'logout'));
}
function startup($args)
{
if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
$rcmail = rcmail::get_instance();
$rcmail->add_shutdown_function(array('http_authentication', 'shutdown'));
// handle login action
if (empty($args['action']) && empty($_SESSION['user_id'])) {
$args['action'] = 'login';
}
// Set user password in session (see shutdown() method for more info)
else if (!empty($_SESSION['user_id']) && empty($_SESSION['password'])) {
$_SESSION['password'] = $rcmail->encrypt($_SERVER['PHP_AUTH_PW']);
}
}
return $args;
}
function authenticate($args)
{
// Load plugin's config file
$this->load_config();
$host = rcmail::get_instance()->config->get('http_authentication_host');
if (is_string($host) && trim($host) !== '')
- $args['host'] = rcube_idn_to_ascii(rcube_parse_host($host));
+ $args['host'] = rcube_utils::idn_to_ascii(rcube_utils::parse_host($host));
// Allow entering other user data in login form,
// e.g. after log out (#1487953)
if (!empty($args['user'])) {
return $args;
}
if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
$args['user'] = $_SERVER['PHP_AUTH_USER'];
$args['pass'] = $_SERVER['PHP_AUTH_PW'];
}
$args['cookiecheck'] = false;
$args['valid'] = true;
return $args;
}
function logout($args)
{
// redirect to configured URL in order to clear HTTP auth credentials
if (!empty($_SERVER['PHP_AUTH_USER']) && $args['user'] == $_SERVER['PHP_AUTH_USER']) {
if ($url = rcmail::get_instance()->config->get('logout_url')) {
header("Location: $url", true, 307);
}
}
}
function shutdown()
{
// There's no need to store password (even if encrypted) in session
// We'll set it back on startup (#1486553)
rcmail::get_instance()->session->remove('password');
}
}
diff --git a/plugins/managesieve/Changelog b/plugins/managesieve/Changelog
index 19799a302..d8baf63ef 100644
--- a/plugins/managesieve/Changelog
+++ b/plugins/managesieve/Changelog
@@ -1,265 +1,266 @@
- Support tls:// prefix in managesieve_host option
+- Removed depracated functions usage
* version 6.1 [2012-12-21]
-----------------------------------------------------------
- Fixed filter activation/deactivation confirmation message (#1488765)
- Moved rcube_* classes to <plugin>/lib/Roundcube for compat. with Roundcube Framework autoloader
- Fixed filter selection after filter deletion (#1488832)
- Fixed compatibility with jQueryUI-1.9
- Don't force 'stop' action on last rule in a script
* version 6.0 [2012-10-03]
-----------------------------------------------------------
- Fixed issue with DBMail bug [http://pear.php.net/bugs/bug.php?id=19077] (#1488594)
- Added support for enotify/notify (RFC5435, RFC5436, draft-ietf-sieve-notify-00)
- Change default port to 4190 (IANA-allocated), add port auto-detection (#1488713)
- Added request size limits detection and script corruption prevention (#1488648)
- Fix so scripts listed in managesieve_filename_exceptions aren't displayed on the list (#1488724)
* version 5.2 [2012-07-24]
-----------------------------------------------------------
- Added GUI for variables setting - RFC5229 (patch from Paweł Słowik)
- Fixed scrollbars in Larry's iframes
- Fix performance issue in message_headers_output hook handling
* version 5.1 [2012-06-21]
-----------------------------------------------------------
- Fixed filter popup width (for non-english localizations)
- Fixed tokenizer infinite loop on invalid script content
- Larry skin support
- Fixed custom header name validity check, made RFC2822-compliant
* version 5.0 [2012-01-05]
-----------------------------------------------------------
- Fixed setting test type to :is when none is specified
- Fixed javascript error in IE8
- Fixed possible ID duplication when adding filter rules very fast (#1488288)
- Fixed bug where drag layer wasn't removed when dragging was ended over sets list
* version 5.0-rc1 [2011-11-17]
-----------------------------------------------------------
- Fixed sorting of scripts, scripts including aware of the sort order
- Fixed import of rules with unsupported tests
- Added 'address' and 'envelope' tests support
- Added 'body' extension support (RFC5173)
- Added 'subaddress' extension support (RFC5233)
- Added comparators support
- Changed Sender/Recipient labels to From/To
- Fixed importing rule names from Ingo
- Fixed handling of extensions disabled in config
* version 5.0-beta [2011-10-17]
-----------------------------------------------------------
- Added possibility to create a filter based on selected message "in-place"
- Fixed import from Horde-INGO (#1488064)
- Add managesieve_script_name option for default name of the script (#1487956)
- Fixed handling of enabled magic_quotes_gpc setting
- Fixed PHP warning on connection error when submitting filter form
- Fixed bug where new action row with flags wasn't handled properly
- Added managesieve_connect hook for plugins
- Fixed doubled Filter tab on page refresh
- Added filters set selector in filter form when invoked in mail task
- Improved script parser, added support for include and variables extensions
- Added Kolab's KEP:14 support (http://wiki.kolab.org/User:Greve/Drafts/KEP:14)
- Use smaller action/rule buttons
- UI redesign: added possibility to move filter to any place using drag&drop
(instead of up/down buttons), added filter sets list object, added more
'loading' messages
- Added option to hide some scripts (managesieve_filename_exceptions)
* version 4.3 [2011-07-28]
-----------------------------------------------------------
- Fixed handling of error in Net_Sieve::listScripts()
- Fixed handling of REFERRAL responses (http://pear.php.net/bugs/bug.php?id=17107)
- Fixed bug where wrong folders hierarchy was displayed on folders listing
* version 4.2 [2011-05-24]
-----------------------------------------------------------
- Moved elsif replacement code to handle only imports from other formats
- Fixed mod_mailbox() usage for newer Roundcube versions
- Fixed regex extension (error: regex require missing)
* version 4.1 [2011-03-07]
-----------------------------------------------------------
- Fix fileinto target is always INBOX (#1487776)
- Fix escaping of backslash character in quoted strings (#1487780)
- Fix handling of non-safe characters (double-quote, backslash)
or UTF-8 characters (dovecot's implementation bug workaround)
in script names
- Fix saving of a script using flags extension on servers with imap4flags support (#1487825)
* version 4.0 [2011-02-10]
-----------------------------------------------------------
- Fix STARTTLS for timsieved < 2.3.10
- Added :regex and :matches support (#1487746)
- Added setflag/addflag/removeflag support (#1487449)
- Added support for vacation :subject field (#1487120)
- rcube_sieve_script class moved to separate file
- Moved javascript code from skin templates into managesieve.js file
* version 3.0 [2011-02-01]
-----------------------------------------------------------
- Added support for SASL proxy authentication (#1486691)
- Fixed parsing of scripts with \r\n line separator
- Apply forgotten changes for form errors handling
- Fix multi-line strings parsing (#1487685)
- Added tests for script parser
- Rewritten script parser
- Fix double request when clicking on Filters tab using Firefox
* version 2.10 [2010-10-10]
-----------------------------------------------------------
- Fixed import from Avelsieve
- Use localized size units (#1486976)
- Added support for relational operators and i;ascii-numeric comparator
- Added popups with form errors
* version 2.9 [2010-08-02]
-----------------------------------------------------------
- Fixed vacation parameters parsing (#1486883)
* version 2.8 [2010-07-08]
-----------------------------------------------------------
- Added managesieve_auth_type option (#1486731)
* version 2.7 [2010-07-06]
-----------------------------------------------------------
- Update Net_Sieve to version 1.3.0 (fixes LOGIN athentication)
- Added support for copying and copy sending of messages (COPY extension)
* version 2.6 [2010-06-03]
-----------------------------------------------------------
- Support %n and %d variables in managesieve_host option
* version 2.5 [2010-05-04]
-----------------------------------------------------------
- Fix filters set label after activation
- Fix filters set activation, add possibility to deactivate sets (#1486699)
- Fix download button state when sets list is empty
- Fix errors when sets list is empty
* version 2.4 [2010-04-01]
-----------------------------------------------------------
- Fixed bug in DIGEST-MD5 authentication (http://pear.php.net/bugs/bug.php?id=17285)
- Fixed disabling rules with many tests
- Small css unification with core
- Scripts import/export
* version 2.3 [2010-03-18]
-----------------------------------------------------------
- Added import from Horde-INGO
- Support for more than one match using if+stop instead of if+elsif structures (#1486078)
- Support for selectively disabling rules within a single sieve script (#1485882)
- Added vertical splitter
* version 2.2 [2010-02-06]
-----------------------------------------------------------
- Fix handling of "<>" characters in filter names (#1486477)
* version 2.1 [2010-01-12]
-----------------------------------------------------------
- Fix "require" structure generation when many modules are used
- Fix problem with '<' and '>' characters in header tests
* version 2.0 [2009-11-02]
-----------------------------------------------------------
- Added 'managesieve_debug' option
- Added multi-script support
- Small css improvements + sprite image buttons
- PEAR::NetSieve 1.2.0b1
* version 1.7 [2009-09-20]
-----------------------------------------------------------
- Support multiple managesieve hosts using %h variable
in managesieve_host option
- Fix first rule deleting (#1486140)
* version 1.6 [2009-09-08]
-----------------------------------------------------------
- Fix warning when importing squirrelmail rules
- Fix handling of "true" as "anyof (true)" test
* version 1.5 [2009-09-04]
-----------------------------------------------------------
- Added es_ES, ua_UA localizations
- Added 'managesieve_mbox_encoding' option
* version 1.4 [2009-07-29]
-----------------------------------------------------------
- Updated PEAR::Net_Sieve to 1.1.7
* version 1.3 [2009-07-24]
-----------------------------------------------------------
- support more languages
- support config.inc.php file
* version 1.2 [2009-06-28]
-----------------------------------------------------------
- Support IMAP namespaces in fileinto (#1485943)
- Added it_IT localization
* version 1.1 [2009-05-27]
-----------------------------------------------------------
- Added new icons
- Added support for headers lists (coma-separated) in rules
- Added de_CH localization
* version 1.0 [2009-05-21]
-----------------------------------------------------------
- Rewritten using plugin API
- Added hu_HU localization (Tamas Tevesz)
* version beta7 (svn-r2300) [2009-03-01]
-----------------------------------------------------------
- Added SquirrelMail script auto-import (Jonathan Ernst)
- Added 'vacation' support (Jonathan Ernst & alec)
- Added 'stop' support (Jonathan Ernst)
- Added option for extensions disabling (Jonathan Ernst & alec)
- Added fi_FI, nl_NL, bg_BG localization
- Small style fixes
* version 0.2-stable1 (svn-r2205) [2009-01-03]
-----------------------------------------------------------
- Fix moving down filter row
- Fixes for compressed js files in stable release package
- Created patch for svn version r2205
* version 0.2-stable [2008-12-31]
-----------------------------------------------------------
- Added ru_RU, fr_FR, zh_CN translation
- Fixes for Roundcube 0.2-stable
* version rc0.2beta [2008-09-21]
-----------------------------------------------------------
- Small css fixes for IE
- Fixes for Roundcube 0.2-beta
* version beta6 [2008-08-08]
-----------------------------------------------------------
- Added de_DE translation
- Fix for Roundcube r1634
* version beta5 [2008-06-10]
-----------------------------------------------------------
- Fixed 'exists' operators
- Fixed 'not*' operators for custom headers
- Fixed filters deleting
* version beta4 [2008-06-09]
-----------------------------------------------------------
- Fix for Roundcube r1490
* version beta3 [2008-05-22]
-----------------------------------------------------------
- Fixed textarea error class setting
- Added pagetitle setting
- Added option 'managesieve_replace_delimiter'
- Fixed errors on IE (still need some css fixes)
* version beta2 [2008-05-20]
-----------------------------------------------------------
- Use 'if' only for first filter and 'elsif' for the rest
* version beta1 [2008-05-15]
-----------------------------------------------------------
- Initial version for Roundcube r1388.
diff --git a/plugins/managesieve/lib/Roundcube/rcube_sieve.php b/plugins/managesieve/lib/Roundcube/rcube_sieve.php
index 4f66bf029..736f73146 100644
--- a/plugins/managesieve/lib/Roundcube/rcube_sieve.php
+++ b/plugins/managesieve/lib/Roundcube/rcube_sieve.php
@@ -1,384 +1,384 @@
<?php
/**
* Classes for managesieve operations (using PEAR::Net_Sieve)
*
* Copyright (C) 2008-2011, The Roundcube Dev Team
* Copyright (C) 2011, Kolab Systems AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// Managesieve Protocol: RFC5804
define('SIEVE_ERROR_CONNECTION', 1);
define('SIEVE_ERROR_LOGIN', 2);
define('SIEVE_ERROR_NOT_EXISTS', 3); // script not exists
define('SIEVE_ERROR_INSTALL', 4); // script installation
define('SIEVE_ERROR_ACTIVATE', 5); // script activation
define('SIEVE_ERROR_DELETE', 6); // script deletion
define('SIEVE_ERROR_INTERNAL', 7); // internal error
define('SIEVE_ERROR_DEACTIVATE', 8); // script activation
define('SIEVE_ERROR_OTHER', 255); // other/unknown error
class rcube_sieve
{
private $sieve; // Net_Sieve object
private $error = false; // error flag
private $list = array(); // scripts list
public $script; // rcube_sieve_script object
public $current; // name of currently loaded script
private $exts; // array of supported extensions
/**
* Object constructor
*
* @param string Username (for managesieve login)
* @param string Password (for managesieve login)
* @param string Managesieve server hostname/address
* @param string Managesieve server port number
* @param string Managesieve authentication method
* @param boolean Enable/disable TLS use
* @param array Disabled extensions
* @param boolean Enable/disable debugging
* @param string Proxy authentication identifier
* @param string Proxy authentication password
*/
public function __construct($username, $password='', $host='localhost', $port=2000,
$auth_type=null, $usetls=true, $disabled=array(), $debug=false,
$auth_cid=null, $auth_pw=null)
{
$this->sieve = new Net_Sieve();
if ($debug) {
$this->sieve->setDebug(true, array($this, 'debug_handler'));
}
if (PEAR::isError($this->sieve->connect($host, $port, null, $usetls))) {
return $this->_set_error(SIEVE_ERROR_CONNECTION);
}
if (!empty($auth_cid)) {
$authz = $username;
$username = $auth_cid;
$password = $auth_pw;
}
if (PEAR::isError($this->sieve->login($username, $password,
$auth_type ? strtoupper($auth_type) : null, $authz))
) {
return $this->_set_error(SIEVE_ERROR_LOGIN);
}
$this->exts = $this->get_extensions();
// disable features by config
if (!empty($disabled)) {
// we're working on lower-cased names
$disabled = array_map('strtolower', (array) $disabled);
foreach ($disabled as $ext) {
if (($idx = array_search($ext, $this->exts)) !== false) {
unset($this->exts[$idx]);
}
}
}
}
public function __destruct() {
$this->sieve->disconnect();
}
/**
* Getter for error code
*/
public function error()
{
return $this->error ? $this->error : false;
}
/**
* Saves current script into server
*/
public function save($name = null)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if (!$this->script)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if (!$name)
$name = $this->current;
$script = $this->script->as_text();
if (!$script)
$script = '/* empty script */';
if (PEAR::isError($this->sieve->installScript($name, $script)))
return $this->_set_error(SIEVE_ERROR_INSTALL);
return true;
}
/**
* Saves text script into server
*/
public function save_script($name, $content = null)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if (!$content)
$content = '/* empty script */';
if (PEAR::isError($this->sieve->installScript($name, $content)))
return $this->_set_error(SIEVE_ERROR_INSTALL);
return true;
}
/**
* Activates specified script
*/
public function activate($name = null)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if (!$name)
$name = $this->current;
if (PEAR::isError($this->sieve->setActive($name)))
return $this->_set_error(SIEVE_ERROR_ACTIVATE);
return true;
}
/**
* De-activates specified script
*/
public function deactivate()
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if (PEAR::isError($this->sieve->setActive('')))
return $this->_set_error(SIEVE_ERROR_DEACTIVATE);
return true;
}
/**
* Removes specified script
*/
public function remove($name = null)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if (!$name)
$name = $this->current;
// script must be deactivated first
if ($name == $this->sieve->getActive())
if (PEAR::isError($this->sieve->setActive('')))
return $this->_set_error(SIEVE_ERROR_DELETE);
if (PEAR::isError($this->sieve->removeScript($name)))
return $this->_set_error(SIEVE_ERROR_DELETE);
if ($name == $this->current)
$this->current = null;
return true;
}
/**
* Gets list of supported by server Sieve extensions
*/
public function get_extensions()
{
if ($this->exts)
return $this->exts;
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
$ext = $this->sieve->getExtensions();
// we're working on lower-cased names
$ext = array_map('strtolower', (array) $ext);
if ($this->script) {
$supported = $this->script->get_extensions();
foreach ($ext as $idx => $ext_name)
if (!in_array($ext_name, $supported))
unset($ext[$idx]);
}
return array_values($ext);
}
/**
* Gets list of scripts from server
*/
public function get_scripts()
{
if (!$this->list) {
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
$list = $this->sieve->listScripts();
if (PEAR::isError($list))
return $this->_set_error(SIEVE_ERROR_OTHER);
$this->list = $list;
}
return $this->list;
}
/**
* Returns active script name
*/
public function get_active()
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
return $this->sieve->getActive();
}
/**
* Loads script by name
*/
public function load($name)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if ($this->current == $name)
return true;
$script = $this->sieve->getScript($name);
if (PEAR::isError($script))
return $this->_set_error(SIEVE_ERROR_OTHER);
// try to parse from Roundcube format
$this->script = $this->_parse($script);
$this->current = $name;
return true;
}
/**
* Loads script from text content
*/
public function load_script($script)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
// try to parse from Roundcube format
$this->script = $this->_parse($script);
}
/**
* Creates rcube_sieve_script object from text script
*/
private function _parse($txt)
{
// parse
$script = new rcube_sieve_script($txt, $this->exts);
// fix/convert to Roundcube format
if (!empty($script->content)) {
// replace all elsif with if+stop, we support only ifs
foreach ($script->content as $idx => $rule) {
if (empty($rule['type']) || !preg_match('/^(if|elsif|else)$/', $rule['type'])) {
continue;
}
$script->content[$idx]['type'] = 'if';
// 'stop' not found?
foreach ($rule['actions'] as $action) {
if (preg_match('/^(stop|vacation)$/', $action['type'])) {
continue 2;
}
}
if (!empty($script->content[$idx+1]) && $script->content[$idx+1]['type'] != 'if') {
$script->content[$idx]['actions'][] = array('type' => 'stop');
}
}
}
return $script;
}
/**
* Gets specified script as text
*/
public function get_script($name)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
$content = $this->sieve->getScript($name);
if (PEAR::isError($content))
return $this->_set_error(SIEVE_ERROR_OTHER);
return $content;
}
/**
* Creates empty script or copy of other script
*/
public function copy($name, $copy)
{
if (!$this->sieve)
return $this->_set_error(SIEVE_ERROR_INTERNAL);
if ($copy) {
$content = $this->sieve->getScript($copy);
if (PEAR::isError($content))
return $this->_set_error(SIEVE_ERROR_OTHER);
}
return $this->save_script($name, $content);
}
private function _set_error($error)
{
$this->error = $error;
return false;
}
/**
* This is our own debug handler for connection
*/
public function debug_handler(&$sieve, $message)
{
- write_log('sieve', preg_replace('/\r\n$/', '', $message));
+ rcube::write_log('sieve', preg_replace('/\r\n$/', '', $message));
}
}
diff --git a/plugins/managesieve/managesieve.php b/plugins/managesieve/managesieve.php
index d30404ac7..8f50cd5a2 100644
--- a/plugins/managesieve/managesieve.php
+++ b/plugins/managesieve/managesieve.php
@@ -1,2050 +1,2050 @@
<?php
/**
* Managesieve (Sieve Filters)
*
* Plugin that adds a possibility to manage Sieve filters in Thunderbird's style.
* It's clickable interface which operates on text scripts and communicates
* with server using managesieve protocol. Adds Filters tab in Settings.
*
* @version @package_version@
* @author Aleksander Machniak <alec@alec.pl>
*
* Configuration (see config.inc.php.dist)
*
* Copyright (C) 2008-2012, The Roundcube Dev Team
* Copyright (C) 2011-2012, Kolab Systems AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
class managesieve extends rcube_plugin
{
public $task = 'mail|settings';
private $rc;
private $sieve;
private $errors;
private $form;
private $tips = array();
private $script = array();
private $exts = array();
private $list;
private $active = array();
private $headers = array(
'subject' => 'Subject',
'from' => 'From',
'to' => 'To',
);
private $addr_headers = array(
// Required
"from", "to", "cc", "bcc", "sender", "resent-from", "resent-to",
// Additional (RFC 822 / RFC 2822)
"reply-to", "resent-reply-to", "resent-sender", "resent-cc", "resent-bcc",
// Non-standard (RFC 2076, draft-palme-mailext-headers-08.txt)
"for-approval", "for-handling", "for-comment", "apparently-to", "errors-to",
"delivered-to", "return-receipt-to", "x-admin", "read-receipt-to",
"x-confirm-reading-to", "return-receipt-requested",
"registered-mail-reply-requested-by", "mail-followup-to", "mail-reply-to",
"abuse-reports-to", "x-complaints-to", "x-report-abuse-to",
// Undocumented
"x-beenthere",
);
const VERSION = '6.1';
const PROGNAME = 'Roundcube (Managesieve)';
const PORT = 4190;
function init()
{
$this->rc = rcmail::get_instance();
// register actions
$this->register_action('plugin.managesieve', array($this, 'managesieve_actions'));
$this->register_action('plugin.managesieve-save', array($this, 'managesieve_save'));
if ($this->rc->task == 'settings') {
$this->init_ui();
}
else if ($this->rc->task == 'mail') {
// register message hook
$this->add_hook('message_headers_output', array($this, 'mail_headers'));
// inject Create Filter popup stuff
if (empty($this->rc->action) || $this->rc->action == 'show') {
$this->mail_task_handler();
}
}
}
/**
* Initializes plugin's UI (localization, js script)
*/
private function init_ui()
{
if ($this->ui_initialized)
return;
// load localization
$this->add_texts('localization/', array('filters','managefilters'));
$this->include_script('managesieve.js');
$this->ui_initialized = true;
}
/**
* Add UI elements to the 'mailbox view' and 'show message' UI.
*/
function mail_task_handler()
{
// use jQuery for popup window
$this->require_plugin('jqueryui');
// include js script and localization
$this->init_ui();
// include styles
$skin_path = $this->local_skin_path();
if (is_file($this->home . "/$skin_path/managesieve_mail.css")) {
$this->include_stylesheet("$skin_path/managesieve_mail.css");
}
// add 'Create filter' item to message menu
$this->api->add_content(html::tag('li', null,
$this->api->output->button(array(
'command' => 'managesieve-create',
'label' => 'managesieve.filtercreate',
'type' => 'link',
'classact' => 'icon filterlink active',
'class' => 'icon filterlink',
'innerclass' => 'icon filterlink',
))), 'messagemenu');
// register some labels/messages
$this->rc->output->add_label('managesieve.newfilter', 'managesieve.usedata',
'managesieve.nodata', 'managesieve.nextstep', 'save');
$this->rc->session->remove('managesieve_current');
}
/**
* Get message headers for popup window
*/
function mail_headers($args)
{
// this hook can be executed many times
if ($this->mail_headers_done) {
return $args;
}
$this->mail_headers_done = true;
$headers = $args['headers'];
$ret = array();
if ($headers->subject)
$ret[] = array('Subject', rcube_mime::decode_header($headers->subject));
// @TODO: List-Id, others?
foreach (array('From', 'To') as $h) {
$hl = strtolower($h);
if ($headers->$hl) {
$list = rcube_mime::decode_address_list($headers->$hl);
foreach ($list as $item) {
if ($item['mailto']) {
$ret[] = array($h, $item['mailto']);
}
}
}
}
if ($this->rc->action == 'preview')
$this->rc->output->command('parent.set_env', array('sieve_headers' => $ret));
else
$this->rc->output->set_env('sieve_headers', $ret);
return $args;
}
/**
* Loads configuration, initializes plugin (including sieve connection)
*/
function managesieve_start()
{
$this->load_config();
// register UI objects
$this->rc->output->add_handlers(array(
'filterslist' => array($this, 'filters_list'),
'filtersetslist' => array($this, 'filtersets_list'),
'filterframe' => array($this, 'filter_frame'),
'filterform' => array($this, 'filter_form'),
'filtersetform' => array($this, 'filterset_form'),
));
// Add include path for internal classes
$include_path = $this->home . '/lib' . PATH_SEPARATOR;
$include_path .= ini_get('include_path');
set_include_path($include_path);
// Get connection parameters
$host = $this->rc->config->get('managesieve_host', 'localhost');
$port = $this->rc->config->get('managesieve_port');
$tls = $this->rc->config->get('managesieve_usetls', false);
- $host = rcube_parse_host($host);
- $host = rcube_idn_to_ascii($host);
+ $host = rcube_utils::parse_host($host);
+ $host = rcube_utils::idn_to_ascii($host);
// remove tls:// prefix, set TLS flag
if (($host = preg_replace('|^tls://|i', '', $host, 1, $cnt)) && $cnt) {
$tls = true;
}
if (empty($port)) {
$port = getservbyname('sieve', 'tcp');
if (empty($port)) {
$port = self::PORT;
}
}
$plugin = $this->rc->plugins->exec_hook('managesieve_connect', array(
'user' => $_SESSION['username'],
'password' => $this->rc->decrypt($_SESSION['password']),
'host' => $host,
'port' => $port,
'usetls' => $tls,
'auth_type' => $this->rc->config->get('managesieve_auth_type'),
'disabled' => $this->rc->config->get('managesieve_disabled_extensions'),
'debug' => $this->rc->config->get('managesieve_debug', false),
'auth_cid' => $this->rc->config->get('managesieve_auth_cid'),
'auth_pw' => $this->rc->config->get('managesieve_auth_pw'),
));
// try to connect to managesieve server and to fetch the script
$this->sieve = new rcube_sieve(
$plugin['user'],
$plugin['password'],
$plugin['host'],
$plugin['port'],
$plugin['auth_type'],
$plugin['usetls'],
$plugin['disabled'],
$plugin['debug'],
$plugin['auth_cid'],
$plugin['auth_pw']
);
if (!($error = $this->sieve->error())) {
// Get list of scripts
$list = $this->list_scripts();
if (!empty($_GET['_set']) || !empty($_POST['_set'])) {
- $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
+ $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true);
}
else if (!empty($_SESSION['managesieve_current'])) {
$script_name = $_SESSION['managesieve_current'];
}
else {
// get (first) active script
if (!empty($this->active[0])) {
$script_name = $this->active[0];
}
else if ($list) {
$script_name = $list[0];
}
// create a new (initial) script
else {
// if script not exists build default script contents
$script_file = $this->rc->config->get('managesieve_default');
$script_name = $this->rc->config->get('managesieve_script_name');
if (empty($script_name))
$script_name = 'roundcube';
if ($script_file && is_readable($script_file))
$content = file_get_contents($script_file);
// add script and set it active
if ($this->sieve->save_script($script_name, $content)) {
$this->activate_script($script_name);
$this->list[] = $script_name;
}
}
}
if ($script_name) {
$this->sieve->load($script_name);
}
$error = $this->sieve->error();
}
// finally set script objects
if ($error) {
switch ($error) {
case SIEVE_ERROR_CONNECTION:
case SIEVE_ERROR_LOGIN:
$this->rc->output->show_message('managesieve.filterconnerror', 'error');
break;
default:
$this->rc->output->show_message('managesieve.filterunknownerror', 'error');
break;
}
- raise_error(array('code' => 403, 'type' => 'php',
+ rcube::raise_error(array('code' => 403, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Unable to connect to managesieve on $host:$port"), true, false);
// to disable 'Add filter' button set env variable
$this->rc->output->set_env('filterconnerror', true);
$this->script = array();
}
else {
$this->exts = $this->sieve->get_extensions();
$this->script = $this->sieve->script->as_array();
$this->rc->output->set_env('currentset', $this->sieve->current);
$_SESSION['managesieve_current'] = $this->sieve->current;
}
return $error;
}
function managesieve_actions()
{
$this->init_ui();
$error = $this->managesieve_start();
// Handle user requests
- if ($action = get_input_value('_act', RCUBE_INPUT_GPC)) {
- $fid = (int) get_input_value('_fid', RCUBE_INPUT_POST);
+ if ($action = rcube_utils::get_input_value('_act', rcube_utils::INPUT_GPC)) {
+ $fid = (int) rcube_utils::get_input_value('_fid', rcube_utils::INPUT_POST);
if ($action == 'delete' && !$error) {
if (isset($this->script[$fid])) {
if ($this->sieve->script->delete_rule($fid))
$result = $this->save_script();
if ($result === true) {
$this->rc->output->show_message('managesieve.filterdeleted', 'confirmation');
$this->rc->output->command('managesieve_updatelist', 'del', array('id' => $fid));
} else {
$this->rc->output->show_message('managesieve.filterdeleteerror', 'error');
}
}
}
else if ($action == 'move' && !$error) {
if (isset($this->script[$fid])) {
- $to = (int) get_input_value('_to', RCUBE_INPUT_POST);
+ $to = (int) rcube_utils::get_input_value('_to', rcube_utils::INPUT_POST);
$rule = $this->script[$fid];
// remove rule
unset($this->script[$fid]);
$this->script = array_values($this->script);
// add at target position
if ($to >= count($this->script)) {
$this->script[] = $rule;
}
else {
$script = array();
foreach ($this->script as $idx => $r) {
if ($idx == $to)
$script[] = $rule;
$script[] = $r;
}
$this->script = $script;
}
$this->sieve->script->content = $this->script;
$result = $this->save_script();
if ($result === true) {
$result = $this->list_rules();
$this->rc->output->show_message('managesieve.moved', 'confirmation');
$this->rc->output->command('managesieve_updatelist', 'list',
array('list' => $result, 'clear' => true, 'set' => $to));
} else {
$this->rc->output->show_message('managesieve.moveerror', 'error');
}
}
}
else if ($action == 'act' && !$error) {
if (isset($this->script[$fid])) {
$rule = $this->script[$fid];
$disabled = $rule['disabled'] ? true : false;
$rule['disabled'] = !$disabled;
$result = $this->sieve->script->update_rule($fid, $rule);
if ($result !== false)
$result = $this->save_script();
if ($result === true) {
if ($rule['disabled'])
$this->rc->output->show_message('managesieve.deactivated', 'confirmation');
else
$this->rc->output->show_message('managesieve.activated', 'confirmation');
$this->rc->output->command('managesieve_updatelist', 'update',
array('id' => $fid, 'disabled' => $rule['disabled']));
} else {
if ($rule['disabled'])
$this->rc->output->show_message('managesieve.deactivateerror', 'error');
else
$this->rc->output->show_message('managesieve.activateerror', 'error');
}
}
}
else if ($action == 'setact' && !$error) {
- $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
+ $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true);
$result = $this->activate_script($script_name);
$kep14 = $this->rc->config->get('managesieve_kolab_master');
if ($result === true) {
$this->rc->output->set_env('active_sets', $this->active);
$this->rc->output->show_message('managesieve.setactivated', 'confirmation');
$this->rc->output->command('managesieve_updatelist', 'setact',
array('name' => $script_name, 'active' => true, 'all' => !$kep14));
} else {
$this->rc->output->show_message('managesieve.setactivateerror', 'error');
}
}
else if ($action == 'deact' && !$error) {
- $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
+ $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true);
$result = $this->deactivate_script($script_name);
if ($result === true) {
$this->rc->output->set_env('active_sets', $this->active);
$this->rc->output->show_message('managesieve.setdeactivated', 'confirmation');
$this->rc->output->command('managesieve_updatelist', 'setact',
array('name' => $script_name, 'active' => false));
} else {
$this->rc->output->show_message('managesieve.setdeactivateerror', 'error');
}
}
else if ($action == 'setdel' && !$error) {
- $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
+ $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true);
$result = $this->remove_script($script_name);
if ($result === true) {
$this->rc->output->show_message('managesieve.setdeleted', 'confirmation');
$this->rc->output->command('managesieve_updatelist', 'setdel',
array('name' => $script_name));
$this->rc->session->remove('managesieve_current');
} else {
$this->rc->output->show_message('managesieve.setdeleteerror', 'error');
}
}
else if ($action == 'setget') {
- $script_name = get_input_value('_set', RCUBE_INPUT_GPC, true);
+ $script_name = rcube_utils::get_input_value('_set', rcube_utils::INPUT_GPC, true);
$script = $this->sieve->get_script($script_name);
if (PEAR::isError($script))
exit;
$browser = new rcube_browser;
// send download headers
header("Content-Type: application/octet-stream");
header("Content-Length: ".strlen($script));
if ($browser->ie)
header("Content-Type: application/force-download");
if ($browser->ie && $browser->ver < 7)
$filename = rawurlencode(abbreviate_string($script_name, 55));
else if ($browser->ie)
$filename = rawurlencode($script_name);
else
$filename = addcslashes($script_name, '\\"');
header("Content-Disposition: attachment; filename=\"$filename.txt\"");
echo $script;
exit;
}
else if ($action == 'list') {
$result = $this->list_rules();
$this->rc->output->command('managesieve_updatelist', 'list', array('list' => $result));
}
else if ($action == 'ruleadd') {
- $rid = get_input_value('_rid', RCUBE_INPUT_GPC);
+ $rid = rcube_utils::get_input_value('_rid', rcube_utils::INPUT_GPC);
$id = $this->genid();
$content = $this->rule_div($fid, $id, false);
$this->rc->output->command('managesieve_rulefill', $content, $id, $rid);
}
else if ($action == 'actionadd') {
- $aid = get_input_value('_aid', RCUBE_INPUT_GPC);
+ $aid = rcube_utils::get_input_value('_aid', rcube_utils::INPUT_GPC);
$id = $this->genid();
$content = $this->action_div($fid, $id, false);
$this->rc->output->command('managesieve_actionfill', $content, $id, $aid);
}
$this->rc->output->send();
}
else if ($this->rc->task == 'mail') {
// Initialize the form
- $rules = get_input_value('r', RCUBE_INPUT_GET);
+ $rules = rcube_utils::get_input_value('r', rcube_utils::INPUT_GET);
if (!empty($rules)) {
$i = 0;
foreach ($rules as $rule) {
list($header, $value) = explode(':', $rule, 2);
$tests[$i] = array(
'type' => 'contains',
'test' => 'header',
'arg1' => $header,
'arg2' => $value,
);
$i++;
}
$this->form = array(
'join' => count($tests) > 1 ? 'allof' : 'anyof',
'name' => '',
'tests' => $tests,
'actions' => array(
0 => array('type' => 'fileinto'),
1 => array('type' => 'stop'),
),
);
}
}
$this->managesieve_send();
}
function managesieve_save()
{
// load localization
$this->add_texts('localization/', array('filters','managefilters'));
// include main js script
if ($this->api->output->type == 'html') {
$this->include_script('managesieve.js');
}
// Init plugin and handle managesieve connection
$error = $this->managesieve_start();
// get request size limits (#1488648)
$max_post = max(array(
ini_get('max_input_vars'),
ini_get('suhosin.request.max_vars'),
ini_get('suhosin.post.max_vars'),
));
$max_depth = max(array(
ini_get('suhosin.request.max_array_depth'),
ini_get('suhosin.post.max_array_depth'),
));
// check request size limit
if ($max_post && count($_POST, COUNT_RECURSIVE) >= $max_post) {
rcube::raise_error(array(
'code' => 500, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Request size limit exceeded (one of max_input_vars/suhosin.request.max_vars/suhosin.post.max_vars)"
), true, false);
$this->rc->output->show_message('managesieve.filtersaveerror', 'error');
}
// check request depth limits
else if ($max_depth && count($_POST['_header']) > $max_depth) {
rcube::raise_error(array(
'code' => 500, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Request size limit exceeded (one of suhosin.request.max_array_depth/suhosin.post.max_array_depth)"
), true, false);
$this->rc->output->show_message('managesieve.filtersaveerror', 'error');
}
// filters set add action
else if (!empty($_POST['_newset'])) {
- $name = get_input_value('_name', RCUBE_INPUT_POST, true);
- $copy = get_input_value('_copy', RCUBE_INPUT_POST, true);
- $from = get_input_value('_from', RCUBE_INPUT_POST);
+ $name = rcube_utils::get_input_value('_name', rcube_utils::INPUT_POST, true);
+ $copy = rcube_utils::get_input_value('_copy', rcube_utils::INPUT_POST, true);
+ $from = rcube_utils::get_input_value('_from', rcube_utils::INPUT_POST);
$exceptions = $this->rc->config->get('managesieve_filename_exceptions');
$kolab = $this->rc->config->get('managesieve_kolab_master');
$name_uc = mb_strtolower($name);
$list = $this->list_scripts();
if (!$name) {
$this->errors['name'] = $this->gettext('cannotbeempty');
}
else if (mb_strlen($name) > 128) {
$this->errors['name'] = $this->gettext('nametoolong');
}
else if (!empty($exceptions) && in_array($name, (array)$exceptions)) {
$this->errors['name'] = $this->gettext('namereserved');
}
else if (!empty($kolab) && in_array($name_uc, array('MASTER', 'USER', 'MANAGEMENT'))) {
$this->errors['name'] = $this->gettext('namereserved');
}
else if (in_array($name, $list)) {
$this->errors['name'] = $this->gettext('setexist');
}
else if ($from == 'file') {
// from file
if (is_uploaded_file($_FILES['_file']['tmp_name'])) {
$file = file_get_contents($_FILES['_file']['tmp_name']);
$file = preg_replace('/\r/', '', $file);
// for security don't save script directly
// check syntax before, like this...
$this->sieve->load_script($file);
if (!$this->save_script($name)) {
$this->errors['file'] = $this->gettext('setcreateerror');
}
}
else { // upload failed
$err = $_FILES['_file']['error'];
if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE) {
- $msg = rcube_label(array('name' => 'filesizeerror',
+ $msg = $this->rc->gettext(array('name' => 'filesizeerror',
'vars' => array('size' =>
- show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
+ $this->rc->show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
}
else {
$this->errors['file'] = $this->gettext('fileuploaderror');
}
}
}
else if (!$this->sieve->copy($name, $from == 'set' ? $copy : '')) {
$error = 'managesieve.setcreateerror';
}
if (!$error && empty($this->errors)) {
// Find position of the new script on the list
$list[] = $name;
asort($list, SORT_LOCALE_STRING);
$list = array_values($list);
$index = array_search($name, $list);
$this->rc->output->show_message('managesieve.setcreated', 'confirmation');
$this->rc->output->command('parent.managesieve_updatelist', 'setadd',
array('name' => $name, 'index' => $index));
} else if ($msg) {
$this->rc->output->command('display_message', $msg, 'error');
} else if ($error) {
$this->rc->output->show_message($error, 'error');
}
}
// filter add/edit action
else if (isset($_POST['_name'])) {
- $name = trim(get_input_value('_name', RCUBE_INPUT_POST, true));
- $fid = trim(get_input_value('_fid', RCUBE_INPUT_POST));
- $join = trim(get_input_value('_join', RCUBE_INPUT_POST));
+ $name = trim(rcube_utils::get_input_value('_name', rcube_utils::INPUT_POST, true));
+ $fid = trim(rcube_utils::get_input_value('_fid', rcube_utils::INPUT_POST));
+ $join = trim(rcube_utils::get_input_value('_join', rcube_utils::INPUT_POST));
// and arrays
- $headers = get_input_value('_header', RCUBE_INPUT_POST);
- $cust_headers = get_input_value('_custom_header', RCUBE_INPUT_POST);
- $ops = get_input_value('_rule_op', RCUBE_INPUT_POST);
- $sizeops = get_input_value('_rule_size_op', RCUBE_INPUT_POST);
- $sizeitems = get_input_value('_rule_size_item', RCUBE_INPUT_POST);
- $sizetargets = get_input_value('_rule_size_target', RCUBE_INPUT_POST);
- $targets = get_input_value('_rule_target', RCUBE_INPUT_POST, true);
- $mods = get_input_value('_rule_mod', RCUBE_INPUT_POST);
- $mod_types = get_input_value('_rule_mod_type', RCUBE_INPUT_POST);
- $body_trans = get_input_value('_rule_trans', RCUBE_INPUT_POST);
- $body_types = get_input_value('_rule_trans_type', RCUBE_INPUT_POST, true);
- $comparators = get_input_value('_rule_comp', RCUBE_INPUT_POST);
- $act_types = get_input_value('_action_type', RCUBE_INPUT_POST, true);
- $mailboxes = get_input_value('_action_mailbox', RCUBE_INPUT_POST, true);
- $act_targets = get_input_value('_action_target', RCUBE_INPUT_POST, true);
- $area_targets = get_input_value('_action_target_area', RCUBE_INPUT_POST, true);
- $reasons = get_input_value('_action_reason', RCUBE_INPUT_POST, true);
- $addresses = get_input_value('_action_addresses', RCUBE_INPUT_POST, true);
- $days = get_input_value('_action_days', RCUBE_INPUT_POST);
- $subject = get_input_value('_action_subject', RCUBE_INPUT_POST, true);
- $flags = get_input_value('_action_flags', RCUBE_INPUT_POST);
- $varnames = get_input_value('_action_varname', RCUBE_INPUT_POST);
- $varvalues = get_input_value('_action_varvalue', RCUBE_INPUT_POST);
- $varmods = get_input_value('_action_varmods', RCUBE_INPUT_POST);
- $notifyaddrs = get_input_value('_action_notifyaddress', RCUBE_INPUT_POST);
- $notifybodies = get_input_value('_action_notifybody', RCUBE_INPUT_POST);
- $notifymessages = get_input_value('_action_notifymessage', RCUBE_INPUT_POST);
- $notifyfrom = get_input_value('_action_notifyfrom', RCUBE_INPUT_POST);
- $notifyimp = get_input_value('_action_notifyimportance', RCUBE_INPUT_POST);
+ $headers = rcube_utils::get_input_value('_header', rcube_utils::INPUT_POST);
+ $cust_headers = rcube_utils::get_input_value('_custom_header', rcube_utils::INPUT_POST);
+ $ops = rcube_utils::get_input_value('_rule_op', rcube_utils::INPUT_POST);
+ $sizeops = rcube_utils::get_input_value('_rule_size_op', rcube_utils::INPUT_POST);
+ $sizeitems = rcube_utils::get_input_value('_rule_size_item', rcube_utils::INPUT_POST);
+ $sizetargets = rcube_utils::get_input_value('_rule_size_target', rcube_utils::INPUT_POST);
+ $targets = rcube_utils::get_input_value('_rule_target', rcube_utils::INPUT_POST, true);
+ $mods = rcube_utils::get_input_value('_rule_mod', rcube_utils::INPUT_POST);
+ $mod_types = rcube_utils::get_input_value('_rule_mod_type', rcube_utils::INPUT_POST);
+ $body_trans = rcube_utils::get_input_value('_rule_trans', rcube_utils::INPUT_POST);
+ $body_types = rcube_utils::get_input_value('_rule_trans_type', rcube_utils::INPUT_POST, true);
+ $comparators = rcube_utils::get_input_value('_rule_comp', rcube_utils::INPUT_POST);
+ $act_types = rcube_utils::get_input_value('_action_type', rcube_utils::INPUT_POST, true);
+ $mailboxes = rcube_utils::get_input_value('_action_mailbox', rcube_utils::INPUT_POST, true);
+ $act_targets = rcube_utils::get_input_value('_action_target', rcube_utils::INPUT_POST, true);
+ $area_targets = rcube_utils::get_input_value('_action_target_area', rcube_utils::INPUT_POST, true);
+ $reasons = rcube_utils::get_input_value('_action_reason', rcube_utils::INPUT_POST, true);
+ $addresses = rcube_utils::get_input_value('_action_addresses', rcube_utils::INPUT_POST, true);
+ $days = rcube_utils::get_input_value('_action_days', rcube_utils::INPUT_POST);
+ $subject = rcube_utils::get_input_value('_action_subject', rcube_utils::INPUT_POST, true);
+ $flags = rcube_utils::get_input_value('_action_flags', rcube_utils::INPUT_POST);
+ $varnames = rcube_utils::get_input_value('_action_varname', rcube_utils::INPUT_POST);
+ $varvalues = rcube_utils::get_input_value('_action_varvalue', rcube_utils::INPUT_POST);
+ $varmods = rcube_utils::get_input_value('_action_varmods', rcube_utils::INPUT_POST);
+ $notifyaddrs = rcube_utils::get_input_value('_action_notifyaddress', rcube_utils::INPUT_POST);
+ $notifybodies = rcube_utils::get_input_value('_action_notifybody', rcube_utils::INPUT_POST);
+ $notifymessages = rcube_utils::get_input_value('_action_notifymessage', rcube_utils::INPUT_POST);
+ $notifyfrom = rcube_utils::get_input_value('_action_notifyfrom', rcube_utils::INPUT_POST);
+ $notifyimp = rcube_utils::get_input_value('_action_notifyimportance', rcube_utils::INPUT_POST);
// we need a "hack" for radiobuttons
foreach ($sizeitems as $item)
$items[] = $item;
$this->form['disabled'] = $_POST['_disabled'] ? true : false;
$this->form['join'] = $join=='allof' ? true : false;
$this->form['name'] = $name;
$this->form['tests'] = array();
$this->form['actions'] = array();
if ($name == '')
$this->errors['name'] = $this->gettext('cannotbeempty');
else {
foreach($this->script as $idx => $rule)
if($rule['name'] == $name && $idx != $fid) {
$this->errors['name'] = $this->gettext('ruleexist');
break;
}
}
$i = 0;
// rules
if ($join == 'any') {
$this->form['tests'][0]['test'] = 'true';
}
else {
foreach ($headers as $idx => $header) {
$header = $this->strip_value($header);
$target = $this->strip_value($targets[$idx], true);
$operator = $this->strip_value($ops[$idx]);
$comparator = $this->strip_value($comparators[$idx]);
if ($header == 'size') {
$sizeop = $this->strip_value($sizeops[$idx]);
$sizeitem = $this->strip_value($items[$idx]);
$sizetarget = $this->strip_value($sizetargets[$idx]);
$this->form['tests'][$i]['test'] = 'size';
$this->form['tests'][$i]['type'] = $sizeop;
$this->form['tests'][$i]['arg'] = $sizetarget;
if ($sizetarget == '')
$this->errors['tests'][$i]['sizetarget'] = $this->gettext('cannotbeempty');
else if (!preg_match('/^[0-9]+(K|M|G)?$/i', $sizetarget.$sizeitem, $m)) {
$this->errors['tests'][$i]['sizetarget'] = $this->gettext('forbiddenchars');
$this->form['tests'][$i]['item'] = $sizeitem;
}
else
$this->form['tests'][$i]['arg'] .= $m[1];
}
else if ($header == 'body') {
$trans = $this->strip_value($body_trans[$idx]);
$trans_type = $this->strip_value($body_types[$idx], true);
if (preg_match('/^not/', $operator))
$this->form['tests'][$i]['not'] = true;
$type = preg_replace('/^not/', '', $operator);
if ($type == 'exists') {
$this->errors['tests'][$i]['op'] = true;
}
$this->form['tests'][$i]['test'] = 'body';
$this->form['tests'][$i]['type'] = $type;
$this->form['tests'][$i]['arg'] = $target;
if ($target == '' && $type != 'exists')
$this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
$this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
$this->form['tests'][$i]['part'] = $trans;
if ($trans == 'content') {
$this->form['tests'][$i]['content'] = $trans_type;
}
}
else {
$cust_header = $headers = $this->strip_value($cust_headers[$idx]);
$mod = $this->strip_value($mods[$idx]);
$mod_type = $this->strip_value($mod_types[$idx]);
if (preg_match('/^not/', $operator))
$this->form['tests'][$i]['not'] = true;
$type = preg_replace('/^not/', '', $operator);
if ($header == '...') {
$headers = preg_split('/[\s,]+/', $cust_header, -1, PREG_SPLIT_NO_EMPTY);
if (!count($headers))
$this->errors['tests'][$i]['header'] = $this->gettext('cannotbeempty');
else {
foreach ($headers as $hr) {
// RFC2822: printable ASCII except colon
if (!preg_match('/^[\x21-\x39\x41-\x7E]+$/i', $hr)) {
$this->errors['tests'][$i]['header'] = $this->gettext('forbiddenchars');
}
}
}
if (empty($this->errors['tests'][$i]['header']))
$cust_header = (is_array($headers) && count($headers) == 1) ? $headers[0] : $headers;
}
if ($type == 'exists') {
$this->form['tests'][$i]['test'] = 'exists';
$this->form['tests'][$i]['arg'] = $header == '...' ? $cust_header : $header;
}
else {
$test = 'header';
$header = $header == '...' ? $cust_header : $header;
if ($mod == 'address' || $mod == 'envelope') {
$found = false;
if (empty($this->errors['tests'][$i]['header'])) {
foreach ((array)$header as $hdr) {
if (!in_array(strtolower(trim($hdr)), $this->addr_headers))
$found = true;
}
}
if (!$found)
$test = $mod;
}
$this->form['tests'][$i]['type'] = $type;
$this->form['tests'][$i]['test'] = $test;
$this->form['tests'][$i]['arg1'] = $header;
$this->form['tests'][$i]['arg2'] = $target;
if ($target == '')
$this->errors['tests'][$i]['target'] = $this->gettext('cannotbeempty');
else if (preg_match('/^(value|count)-/', $type) && !preg_match('/[0-9]+/', $target))
$this->errors['tests'][$i]['target'] = $this->gettext('forbiddenchars');
if ($mod) {
$this->form['tests'][$i]['part'] = $mod_type;
}
}
}
if ($header != 'size' && $comparator) {
if (preg_match('/^(value|count)/', $this->form['tests'][$i]['type']))
$comparator = 'i;ascii-numeric';
$this->form['tests'][$i]['comparator'] = $comparator;
}
$i++;
}
}
$i = 0;
// actions
foreach($act_types as $idx => $type) {
$type = $this->strip_value($type);
$target = $this->strip_value($act_targets[$idx]);
switch ($type) {
case 'fileinto':
case 'fileinto_copy':
$mailbox = $this->strip_value($mailboxes[$idx]);
$this->form['actions'][$i]['target'] = $this->mod_mailbox($mailbox, 'in');
if ($type == 'fileinto_copy') {
$type = 'fileinto';
$this->form['actions'][$i]['copy'] = true;
}
break;
case 'reject':
case 'ereject':
$target = $this->strip_value($area_targets[$idx]);
$this->form['actions'][$i]['target'] = str_replace("\r\n", "\n", $target);
// if ($target == '')
// $this->errors['actions'][$i]['targetarea'] = $this->gettext('cannotbeempty');
break;
case 'redirect':
case 'redirect_copy':
$this->form['actions'][$i]['target'] = $target;
if ($this->form['actions'][$i]['target'] == '')
$this->errors['actions'][$i]['target'] = $this->gettext('cannotbeempty');
- else if (!check_email($this->form['actions'][$i]['target']))
+ else if (!rcube_utils::check_email($this->form['actions'][$i]['target']))
$this->errors['actions'][$i]['target'] = $this->gettext('noemailwarning');
if ($type == 'redirect_copy') {
$type = 'redirect';
$this->form['actions'][$i]['copy'] = true;
}
break;
case 'addflag':
case 'setflag':
case 'removeflag':
$_target = array();
if (empty($flags[$idx])) {
$this->errors['actions'][$i]['target'] = $this->gettext('noflagset');
}
else {
foreach ($flags[$idx] as $flag) {
$_target[] = $this->strip_value($flag);
}
}
$this->form['actions'][$i]['target'] = $_target;
break;
case 'vacation':
$reason = $this->strip_value($reasons[$idx]);
$this->form['actions'][$i]['reason'] = str_replace("\r\n", "\n", $reason);
$this->form['actions'][$i]['days'] = $days[$idx];
$this->form['actions'][$i]['subject'] = $subject[$idx];
$this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
// @TODO: vacation :mime, :from, :handle
if ($this->form['actions'][$i]['addresses']) {
foreach($this->form['actions'][$i]['addresses'] as $aidx => $address) {
$address = trim($address);
if (!$address)
unset($this->form['actions'][$i]['addresses'][$aidx]);
- else if(!check_email($address)) {
+ else if(!rcube_utils::check_email($address)) {
$this->errors['actions'][$i]['addresses'] = $this->gettext('noemailwarning');
break;
} else
$this->form['actions'][$i]['addresses'][$aidx] = $address;
}
}
if ($this->form['actions'][$i]['reason'] == '')
$this->errors['actions'][$i]['reason'] = $this->gettext('cannotbeempty');
if ($this->form['actions'][$i]['days'] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i]['days']))
$this->errors['actions'][$i]['days'] = $this->gettext('forbiddenchars');
break;
case 'set':
$this->form['actions'][$i]['name'] = $varnames[$idx];
$this->form['actions'][$i]['value'] = $varvalues[$idx];
foreach ((array)$varmods[$idx] as $v_m) {
$this->form['actions'][$i][$v_m] = true;
}
if (empty($varnames[$idx])) {
$this->errors['actions'][$i]['name'] = $this->gettext('cannotbeempty');
}
else if (!preg_match('/^[0-9a-z_]+$/i', $varnames[$idx])) {
$this->errors['actions'][$i]['name'] = $this->gettext('forbiddenchars');
}
if (!isset($varvalues[$idx]) || $varvalues[$idx] === '') {
$this->errors['actions'][$i]['value'] = $this->gettext('cannotbeempty');
}
break;
case 'notify':
if (empty($notifyaddrs[$idx])) {
$this->errors['actions'][$i]['address'] = $this->gettext('cannotbeempty');
}
- else if (!check_email($notifyaddrs[$idx])) {
+ else if (!rcube_utils::check_email($notifyaddrs[$idx])) {
$this->errors['actions'][$i]['address'] = $this->gettext('noemailwarning');
}
- if (!empty($notifyfrom[$idx]) && !check_email($notifyfrom[$idx])) {
+ if (!empty($notifyfrom[$idx]) && !rcube_utils::check_email($notifyfrom[$idx])) {
$this->errors['actions'][$i]['from'] = $this->gettext('noemailwarning');
}
$this->form['actions'][$i]['address'] = $notifyaddrs[$idx];
$this->form['actions'][$i]['body'] = $notifybodies[$idx];
$this->form['actions'][$i]['message'] = $notifymessages[$idx];
$this->form['actions'][$i]['from'] = $notifyfrom[$idx];
$this->form['actions'][$i]['importance'] = $notifyimp[$idx];
break;
}
$this->form['actions'][$i]['type'] = $type;
$i++;
}
if (!$this->errors && !$error) {
// zapis skryptu
if (!isset($this->script[$fid])) {
$fid = $this->sieve->script->add_rule($this->form);
$new = true;
} else
$fid = $this->sieve->script->update_rule($fid, $this->form);
if ($fid !== false)
$save = $this->save_script();
if ($save && $fid !== false) {
$this->rc->output->show_message('managesieve.filtersaved', 'confirmation');
if ($this->rc->task != 'mail') {
$this->rc->output->command('parent.managesieve_updatelist',
isset($new) ? 'add' : 'update',
array(
- 'name' => Q($this->form['name']),
+ 'name' => rcube::Q($this->form['name']),
'id' => $fid,
'disabled' => $this->form['disabled']
));
}
else {
$this->rc->output->command('managesieve_dialog_close');
$this->rc->output->send('iframe');
}
}
else {
$this->rc->output->show_message('managesieve.filtersaveerror', 'error');
// $this->rc->output->send();
}
}
}
$this->managesieve_send();
}
private function managesieve_send()
{
// Handle form action
if (isset($_GET['_framed']) || isset($_POST['_framed'])) {
if (isset($_GET['_newset']) || isset($_POST['_newset'])) {
$this->rc->output->send('managesieve.setedit');
}
else {
$this->rc->output->send('managesieve.filteredit');
}
} else {
$this->rc->output->set_pagetitle($this->gettext('filters'));
$this->rc->output->send('managesieve.managesieve');
}
}
// return the filters list as HTML table
function filters_list($attrib)
{
// add id to message list table if not specified
if (!strlen($attrib['id']))
$attrib['id'] = 'rcmfilterslist';
// define list of cols to be displayed
$a_show_cols = array('name');
$result = $this->list_rules();
// create XHTML table
- $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
+ $out = $this->rc->table_output($attrib, $result, $a_show_cols, 'id');
// set client env
$this->rc->output->add_gui_object('filterslist', $attrib['id']);
$this->rc->output->include_script('list.js');
// add some labels to client
$this->rc->output->add_label('managesieve.filterdeleteconfirm');
return $out;
}
// return the filters list as <SELECT>
function filtersets_list($attrib, $no_env = false)
{
// add id to message list table if not specified
if (!strlen($attrib['id']))
$attrib['id'] = 'rcmfiltersetslist';
$list = $this->list_scripts();
if ($list) {
asort($list, SORT_LOCALE_STRING);
}
if (!empty($attrib['type']) && $attrib['type'] == 'list') {
// define list of cols to be displayed
$a_show_cols = array('name');
if ($list) {
foreach ($list as $idx => $set) {
$scripts['S'.$idx] = $set;
$result[] = array(
- 'name' => Q($set),
+ 'name' => rcube::Q($set),
'id' => 'S'.$idx,
'class' => !in_array($set, $this->active) ? 'disabled' : '',
);
}
}
// create XHTML table
- $out = rcube_table_output($attrib, $result, $a_show_cols, 'id');
+ $out = $this->rc->table_output($attrib, $result, $a_show_cols, 'id');
$this->rc->output->set_env('filtersets', $scripts);
$this->rc->output->include_script('list.js');
}
else {
$select = new html_select(array('name' => '_set', 'id' => $attrib['id'],
'onchange' => $this->rc->task != 'mail' ? 'rcmail.managesieve_set()' : ''));
if ($list) {
foreach ($list as $set)
$select->add($set, $set);
}
$out = $select->show($this->sieve->current);
}
// set client env
if (!$no_env) {
$this->rc->output->add_gui_object('filtersetslist', $attrib['id']);
$this->rc->output->add_label('managesieve.setdeleteconfirm');
}
return $out;
}
function filter_frame($attrib)
{
if (!$attrib['id'])
$attrib['id'] = 'rcmfilterframe';
$attrib['name'] = $attrib['id'];
$this->rc->output->set_env('contentframe', $attrib['name']);
$this->rc->output->set_env('blankpage', $attrib['src'] ?
$this->rc->output->abs_url($attrib['src']) : 'program/resources/blank.gif');
return $this->rc->output->frame($attrib);
}
function filterset_form($attrib)
{
if (!$attrib['id'])
$attrib['id'] = 'rcmfiltersetform';
$out = '<form name="filtersetform" action="./" method="post" enctype="multipart/form-data">'."\n";
$hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
$hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
$hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
$hiddenfields->add(array('name' => '_newset', 'value' => 1));
$out .= $hiddenfields->show();
- $name = get_input_value('_name', RCUBE_INPUT_POST);
- $copy = get_input_value('_copy', RCUBE_INPUT_POST);
- $selected = get_input_value('_from', RCUBE_INPUT_POST);
+ $name = rcube_utils::get_input_value('_name', rcube_utils::INPUT_POST);
+ $copy = rcube_utils::get_input_value('_copy', rcube_utils::INPUT_POST);
+ $selected = rcube_utils::get_input_value('_from', rcube_utils::INPUT_POST);
// filter set name input
$input_name = new html_inputfield(array('name' => '_name', 'id' => '_name', 'size' => 30,
'class' => ($this->errors['name'] ? 'error' : '')));
$out .= sprintf('<label for="%s"><b>%s:</b></label> %s<br /><br />',
- '_name', Q($this->gettext('filtersetname')), $input_name->show($name));
+ '_name', rcube::Q($this->gettext('filtersetname')), $input_name->show($name));
$out .="\n<fieldset class=\"itemlist\"><legend>" . $this->gettext('filters') . ":</legend>\n";
$out .= '<input type="radio" id="from_none" name="_from" value="none"'
.(!$selected || $selected=='none' ? ' checked="checked"' : '').'></input>';
- $out .= sprintf('<label for="%s">%s</label> ', 'from_none', Q($this->gettext('none')));
+ $out .= sprintf('<label for="%s">%s</label> ', 'from_none', rcube::Q($this->gettext('none')));
// filters set list
$list = $this->list_scripts();
$select = new html_select(array('name' => '_copy', 'id' => '_copy'));
if (is_array($list)) {
asort($list, SORT_LOCALE_STRING);
if (!$copy)
$copy = $_SESSION['managesieve_current'];
foreach ($list as $set) {
$select->add($set, $set);
}
$out .= '<br /><input type="radio" id="from_set" name="_from" value="set"'
.($selected=='set' ? ' checked="checked"' : '').'></input>';
- $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', Q($this->gettext('fromset')));
+ $out .= sprintf('<label for="%s">%s:</label> ', 'from_set', rcube::Q($this->gettext('fromset')));
$out .= $select->show($copy);
}
// script upload box
$upload = new html_inputfield(array('name' => '_file', 'id' => '_file', 'size' => 30,
'type' => 'file', 'class' => ($this->errors['file'] ? 'error' : '')));
$out .= '<br /><input type="radio" id="from_file" name="_from" value="file"'
.($selected=='file' ? ' checked="checked"' : '').'></input>';
- $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', Q($this->gettext('fromfile')));
+ $out .= sprintf('<label for="%s">%s:</label> ', 'from_file', rcube::Q($this->gettext('fromfile')));
$out .= $upload->show();
$out .= '</fieldset>';
$this->rc->output->add_gui_object('sieveform', 'filtersetform');
if ($this->errors['name'])
$this->add_tip('_name', $this->errors['name'], true);
if ($this->errors['file'])
$this->add_tip('_file', $this->errors['file'], true);
$this->print_tips();
return $out;
}
function filter_form($attrib)
{
if (!$attrib['id'])
$attrib['id'] = 'rcmfilterform';
- $fid = get_input_value('_fid', RCUBE_INPUT_GPC);
+ $fid = rcube_utils::get_input_value('_fid', rcube_utils::INPUT_GPC);
$scr = isset($this->form) ? $this->form : $this->script[$fid];
$hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $this->rc->task));
$hiddenfields->add(array('name' => '_action', 'value' => 'plugin.managesieve-save'));
$hiddenfields->add(array('name' => '_framed', 'value' => ($_POST['_framed'] || $_GET['_framed'] ? 1 : 0)));
$hiddenfields->add(array('name' => '_fid', 'value' => $fid));
$out = '<form name="filterform" action="./" method="post">'."\n";
$out .= $hiddenfields->show();
// 'any' flag
if (sizeof($scr['tests']) == 1 && $scr['tests'][0]['test'] == 'true' && !$scr['tests'][0]['not'])
$any = true;
// filter name input
$field_id = '_name';
$input_name = new html_inputfield(array('name' => '_name', 'id' => $field_id, 'size' => 30,
'class' => ($this->errors['name'] ? 'error' : '')));
if ($this->errors['name'])
$this->add_tip($field_id, $this->errors['name'], true);
if (isset($scr))
$input_name = $input_name->show($scr['name']);
else
$input_name = $input_name->show();
$out .= sprintf("\n<label for=\"%s\"><b>%s:</b></label> %s\n",
- $field_id, Q($this->gettext('filtername')), $input_name);
+ $field_id, rcube::Q($this->gettext('filtername')), $input_name);
// filter set selector
if ($this->rc->task == 'mail') {
$out .= sprintf("\n&nbsp;<label for=\"%s\"><b>%s:</b></label> %s\n",
- $field_id, Q($this->gettext('filterset')),
+ $field_id, rcube::Q($this->gettext('filterset')),
$this->filtersets_list(array('id' => 'sievescriptname'), true));
}
- $out .= '<br /><br /><fieldset><legend>' . Q($this->gettext('messagesrules')) . "</legend>\n";
+ $out .= '<br /><br /><fieldset><legend>' . rcube::Q($this->gettext('messagesrules')) . "</legend>\n";
// any, allof, anyof radio buttons
$field_id = '_allof';
$input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'allof',
'onclick' => 'rule_join_radio(\'allof\')', 'class' => 'radio'));
if (isset($scr) && !$any)
$input_join = $input_join->show($scr['join'] ? 'allof' : '');
else
$input_join = $input_join->show();
$out .= sprintf("%s<label for=\"%s\">%s</label>&nbsp;\n",
- $input_join, $field_id, Q($this->gettext('filterallof')));
+ $input_join, $field_id, rcube::Q($this->gettext('filterallof')));
$field_id = '_anyof';
$input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'anyof',
'onclick' => 'rule_join_radio(\'anyof\')', 'class' => 'radio'));
if (isset($scr) && !$any)
$input_join = $input_join->show($scr['join'] ? '' : 'anyof');
else
$input_join = $input_join->show('anyof'); // default
$out .= sprintf("%s<label for=\"%s\">%s</label>\n",
- $input_join, $field_id, Q($this->gettext('filteranyof')));
+ $input_join, $field_id, rcube::Q($this->gettext('filteranyof')));
$field_id = '_any';
$input_join = new html_radiobutton(array('name' => '_join', 'id' => $field_id, 'value' => 'any',
'onclick' => 'rule_join_radio(\'any\')', 'class' => 'radio'));
$input_join = $input_join->show($any ? 'any' : '');
$out .= sprintf("%s<label for=\"%s\">%s</label>\n",
- $input_join, $field_id, Q($this->gettext('filterany')));
+ $input_join, $field_id, rcube::Q($this->gettext('filterany')));
$rows_num = isset($scr) ? sizeof($scr['tests']) : 1;
$out .= '<div id="rules"'.($any ? ' style="display: none"' : '').'>';
for ($x=0; $x<$rows_num; $x++)
$out .= $this->rule_div($fid, $x);
$out .= "</div>\n";
$out .= "</fieldset>\n";
// actions
- $out .= '<fieldset><legend>' . Q($this->gettext('messagesactions')) . "</legend>\n";
+ $out .= '<fieldset><legend>' . rcube::Q($this->gettext('messagesactions')) . "</legend>\n";
$rows_num = isset($scr) ? sizeof($scr['actions']) : 1;
$out .= '<div id="actions">';
for ($x=0; $x<$rows_num; $x++)
$out .= $this->action_div($fid, $x);
$out .= "</div>\n";
$out .= "</fieldset>\n";
$this->print_tips();
if ($scr['disabled']) {
$this->rc->output->set_env('rule_disabled', true);
}
$this->rc->output->add_label(
'managesieve.ruledeleteconfirm',
'managesieve.actiondeleteconfirm'
);
$this->rc->output->add_gui_object('sieveform', 'filterform');
return $out;
}
function rule_div($fid, $id, $div=true)
{
$rule = isset($this->form) ? $this->form['tests'][$id] : $this->script[$fid]['tests'][$id];
$rows_num = isset($this->form) ? sizeof($this->form['tests']) : sizeof($this->script[$fid]['tests']);
// headers select
$select_header = new html_select(array('name' => "_header[]", 'id' => 'header'.$id,
'onchange' => 'rule_header_select(' .$id .')'));
foreach($this->headers as $name => $val)
- $select_header->add(Q($this->gettext($name)), Q($val));
+ $select_header->add(rcube::Q($this->gettext($name)), Q($val));
if (in_array('body', $this->exts))
- $select_header->add(Q($this->gettext('body')), 'body');
- $select_header->add(Q($this->gettext('size')), 'size');
- $select_header->add(Q($this->gettext('...')), '...');
+ $select_header->add(rcube::Q($this->gettext('body')), 'body');
+ $select_header->add(rcube::Q($this->gettext('size')), 'size');
+ $select_header->add(rcube::Q($this->gettext('...')), '...');
// TODO: list arguments
$aout = '';
if ((isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope')))
&& !is_array($rule['arg1']) && in_array($rule['arg1'], $this->headers)
) {
$aout .= $select_header->show($rule['arg1']);
}
else if ((isset($rule['test']) && $rule['test'] == 'exists')
&& !is_array($rule['arg']) && in_array($rule['arg'], $this->headers)
) {
$aout .= $select_header->show($rule['arg']);
}
else if (isset($rule['test']) && $rule['test'] == 'size')
$aout .= $select_header->show('size');
else if (isset($rule['test']) && $rule['test'] == 'body')
$aout .= $select_header->show('body');
else if (isset($rule['test']) && $rule['test'] != 'true')
$aout .= $select_header->show('...');
else
$aout .= $select_header->show();
if (isset($rule['test']) && in_array($rule['test'], array('header', 'address', 'envelope'))) {
if (is_array($rule['arg1']))
$custom = implode(', ', $rule['arg1']);
else if (!in_array($rule['arg1'], $this->headers))
$custom = $rule['arg1'];
}
else if (isset($rule['test']) && $rule['test'] == 'exists') {
if (is_array($rule['arg']))
$custom = implode(', ', $rule['arg']);
else if (!in_array($rule['arg'], $this->headers))
$custom = $rule['arg'];
}
$tout = '<div id="custom_header' .$id. '" style="display:' .(isset($custom) ? 'inline' : 'none'). '">
<input type="text" name="_custom_header[]" id="custom_header_i'.$id.'" '
. $this->error_class($id, 'test', 'header', 'custom_header_i')
- .' value="' .Q($custom). '" size="15" />&nbsp;</div>' . "\n";
+ .' value="' .rcube::Q($custom). '" size="15" />&nbsp;</div>' . "\n";
// matching type select (operator)
$select_op = new html_select(array('name' => "_rule_op[]", 'id' => 'rule_op'.$id,
'style' => 'display:' .($rule['test']!='size' ? 'inline' : 'none'),
'class' => 'operator_selector',
'onchange' => 'rule_op_select('.$id.')'));
- $select_op->add(Q($this->gettext('filtercontains')), 'contains');
- $select_op->add(Q($this->gettext('filternotcontains')), 'notcontains');
- $select_op->add(Q($this->gettext('filteris')), 'is');
- $select_op->add(Q($this->gettext('filterisnot')), 'notis');
- $select_op->add(Q($this->gettext('filterexists')), 'exists');
- $select_op->add(Q($this->gettext('filternotexists')), 'notexists');
- $select_op->add(Q($this->gettext('filtermatches')), 'matches');
- $select_op->add(Q($this->gettext('filternotmatches')), 'notmatches');
+ $select_op->add(rcube::Q($this->gettext('filtercontains')), 'contains');
+ $select_op->add(rcube::Q($this->gettext('filternotcontains')), 'notcontains');
+ $select_op->add(rcube::Q($this->gettext('filteris')), 'is');
+ $select_op->add(rcube::Q($this->gettext('filterisnot')), 'notis');
+ $select_op->add(rcube::Q($this->gettext('filterexists')), 'exists');
+ $select_op->add(rcube::Q($this->gettext('filternotexists')), 'notexists');
+ $select_op->add(rcube::Q($this->gettext('filtermatches')), 'matches');
+ $select_op->add(rcube::Q($this->gettext('filternotmatches')), 'notmatches');
if (in_array('regex', $this->exts)) {
- $select_op->add(Q($this->gettext('filterregex')), 'regex');
- $select_op->add(Q($this->gettext('filternotregex')), 'notregex');
+ $select_op->add(rcube::Q($this->gettext('filterregex')), 'regex');
+ $select_op->add(rcube::Q($this->gettext('filternotregex')), 'notregex');
}
if (in_array('relational', $this->exts)) {
- $select_op->add(Q($this->gettext('countisgreaterthan')), 'count-gt');
- $select_op->add(Q($this->gettext('countisgreaterthanequal')), 'count-ge');
- $select_op->add(Q($this->gettext('countislessthan')), 'count-lt');
- $select_op->add(Q($this->gettext('countislessthanequal')), 'count-le');
- $select_op->add(Q($this->gettext('countequals')), 'count-eq');
- $select_op->add(Q($this->gettext('countnotequals')), 'count-ne');
- $select_op->add(Q($this->gettext('valueisgreaterthan')), 'value-gt');
- $select_op->add(Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
- $select_op->add(Q($this->gettext('valueislessthan')), 'value-lt');
- $select_op->add(Q($this->gettext('valueislessthanequal')), 'value-le');
- $select_op->add(Q($this->gettext('valueequals')), 'value-eq');
- $select_op->add(Q($this->gettext('valuenotequals')), 'value-ne');
+ $select_op->add(rcube::Q($this->gettext('countisgreaterthan')), 'count-gt');
+ $select_op->add(rcube::Q($this->gettext('countisgreaterthanequal')), 'count-ge');
+ $select_op->add(rcube::Q($this->gettext('countislessthan')), 'count-lt');
+ $select_op->add(rcube::Q($this->gettext('countislessthanequal')), 'count-le');
+ $select_op->add(rcube::Q($this->gettext('countequals')), 'count-eq');
+ $select_op->add(rcube::Q($this->gettext('countnotequals')), 'count-ne');
+ $select_op->add(rcube::Q($this->gettext('valueisgreaterthan')), 'value-gt');
+ $select_op->add(rcube::Q($this->gettext('valueisgreaterthanequal')), 'value-ge');
+ $select_op->add(rcube::Q($this->gettext('valueislessthan')), 'value-lt');
+ $select_op->add(rcube::Q($this->gettext('valueislessthanequal')), 'value-le');
+ $select_op->add(rcube::Q($this->gettext('valueequals')), 'value-eq');
+ $select_op->add(rcube::Q($this->gettext('valuenotequals')), 'value-ne');
}
// target input (TODO: lists)
if (in_array($rule['test'], array('header', 'address', 'envelope'))) {
$test = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
$target = $rule['arg2'];
}
else if ($rule['test'] == 'body') {
$test = ($rule['not'] ? 'not' : '').($rule['type'] ? $rule['type'] : 'is');
$target = $rule['arg'];
}
else if ($rule['test'] == 'size') {
$test = '';
$target = '';
if (preg_match('/^([0-9]+)(K|M|G)?$/', $rule['arg'], $matches)) {
$sizetarget = $matches[1];
$sizeitem = $matches[2];
}
else {
$sizetarget = $rule['arg'];
$sizeitem = $rule['item'];
}
}
else {
$test = ($rule['not'] ? 'not' : '').$rule['test'];
$target = '';
}
$tout .= $select_op->show($test);
$tout .= '<input type="text" name="_rule_target[]" id="rule_target' .$id. '"
- value="' .Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
+ value="' .rcube::Q($target). '" size="20" ' . $this->error_class($id, 'test', 'target', 'rule_target')
. ' style="display:' . ($rule['test']!='size' && $rule['test'] != 'exists' ? 'inline' : 'none') . '" />'."\n";
$select_size_op = new html_select(array('name' => "_rule_size_op[]", 'id' => 'rule_size_op'.$id));
- $select_size_op->add(Q($this->gettext('filterover')), 'over');
- $select_size_op->add(Q($this->gettext('filterunder')), 'under');
+ $select_size_op->add(rcube::Q($this->gettext('filterover')), 'over');
+ $select_size_op->add(rcube::Q($this->gettext('filterunder')), 'under');
$tout .= '<div id="rule_size' .$id. '" style="display:' . ($rule['test']=='size' ? 'inline' : 'none') .'">';
$tout .= $select_size_op->show($rule['test']=='size' ? $rule['type'] : '');
$tout .= '<input type="text" name="_rule_size_target[]" id="rule_size_i'.$id.'" value="'.$sizetarget.'" size="10" '
. $this->error_class($id, 'test', 'sizetarget', 'rule_size_i') .' />
<input type="radio" name="_rule_size_item['.$id.']" value=""'
- . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('B').'
+ . (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('B').'
<input type="radio" name="_rule_size_item['.$id.']" value="K"'
- . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('KB').'
+ . ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('KB').'
<input type="radio" name="_rule_size_item['.$id.']" value="M"'
- . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('MB').'
+ . ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('MB').'
<input type="radio" name="_rule_size_item['.$id.']" value="G"'
- . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.rcube_label('GB');
+ . ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('GB');
$tout .= '</div>';
// Advanced modifiers (address, envelope)
$select_mod = new html_select(array('name' => "_rule_mod[]", 'id' => 'rule_mod_op'.$id,
'onchange' => 'rule_mod_select(' .$id .')'));
- $select_mod->add(Q($this->gettext('none')), '');
- $select_mod->add(Q($this->gettext('address')), 'address');
+ $select_mod->add(rcube::Q($this->gettext('none')), '');
+ $select_mod->add(rcube::Q($this->gettext('address')), 'address');
if (in_array('envelope', $this->exts))
- $select_mod->add(Q($this->gettext('envelope')), 'envelope');
+ $select_mod->add(rcube::Q($this->gettext('envelope')), 'envelope');
$select_type = new html_select(array('name' => "_rule_mod_type[]", 'id' => 'rule_mod_type'.$id));
- $select_type->add(Q($this->gettext('allparts')), 'all');
- $select_type->add(Q($this->gettext('domain')), 'domain');
- $select_type->add(Q($this->gettext('localpart')), 'localpart');
+ $select_type->add(rcube::Q($this->gettext('allparts')), 'all');
+ $select_type->add(rcube::Q($this->gettext('domain')), 'domain');
+ $select_type->add(rcube::Q($this->gettext('localpart')), 'localpart');
if (in_array('subaddress', $this->exts)) {
- $select_type->add(Q($this->gettext('user')), 'user');
- $select_type->add(Q($this->gettext('detail')), 'detail');
+ $select_type->add(rcube::Q($this->gettext('user')), 'user');
+ $select_type->add(rcube::Q($this->gettext('detail')), 'detail');
}
$need_mod = $rule['test'] != 'size' && $rule['test'] != 'body';
$mout = '<div id="rule_mod' .$id. '" class="adv" style="display:' . ($need_mod ? 'block' : 'none') .'">';
$mout .= ' <span>';
- $mout .= Q($this->gettext('modifier')) . ' ';
+ $mout .= rcube::Q($this->gettext('modifier')) . ' ';
$mout .= $select_mod->show($rule['test']);
$mout .= '</span>';
$mout .= ' <span id="rule_mod_type' . $id . '"';
$mout .= ' style="display:' . (in_array($rule['test'], array('address', 'envelope')) ? 'inline' : 'none') .'">';
- $mout .= Q($this->gettext('modtype')) . ' ';
+ $mout .= rcube::Q($this->gettext('modtype')) . ' ';
$mout .= $select_type->show($rule['part']);
$mout .= '</span>';
$mout .= '</div>';
// Advanced modifiers (body transformations)
$select_mod = new html_select(array('name' => "_rule_trans[]", 'id' => 'rule_trans_op'.$id,
'onchange' => 'rule_trans_select(' .$id .')'));
- $select_mod->add(Q($this->gettext('text')), 'text');
- $select_mod->add(Q($this->gettext('undecoded')), 'raw');
- $select_mod->add(Q($this->gettext('contenttype')), 'content');
+ $select_mod->add(rcube::Q($this->gettext('text')), 'text');
+ $select_mod->add(rcube::Q($this->gettext('undecoded')), 'raw');
+ $select_mod->add(rcube::Q($this->gettext('contenttype')), 'content');
$mout .= '<div id="rule_trans' .$id. '" class="adv" style="display:' . ($rule['test'] == 'body' ? 'block' : 'none') .'">';
$mout .= ' <span>';
- $mout .= Q($this->gettext('modifier')) . ' ';
+ $mout .= rcube::Q($this->gettext('modifier')) . ' ';
$mout .= $select_mod->show($rule['part']);
$mout .= '<input type="text" name="_rule_trans_type[]" id="rule_trans_type'.$id
. '" value="'.(is_array($rule['content']) ? implode(',', $rule['content']) : $rule['content'])
.'" size="20" style="display:' . ($rule['part'] == 'content' ? 'inline' : 'none') .'"'
. $this->error_class($id, 'test', 'part', 'rule_trans_type') .' />';
$mout .= '</span>';
$mout .= '</div>';
// Advanced modifiers (body transformations)
$select_comp = new html_select(array('name' => "_rule_comp[]", 'id' => 'rule_comp_op'.$id));
- $select_comp->add(Q($this->gettext('default')), '');
- $select_comp->add(Q($this->gettext('octet')), 'i;octet');
- $select_comp->add(Q($this->gettext('asciicasemap')), 'i;ascii-casemap');
+ $select_comp->add(rcube::Q($this->gettext('default')), '');
+ $select_comp->add(rcube::Q($this->gettext('octet')), 'i;octet');
+ $select_comp->add(rcube::Q($this->gettext('asciicasemap')), 'i;ascii-casemap');
if (in_array('comparator-i;ascii-numeric', $this->exts)) {
- $select_comp->add(Q($this->gettext('asciinumeric')), 'i;ascii-numeric');
+ $select_comp->add(rcube::Q($this->gettext('asciinumeric')), 'i;ascii-numeric');
}
$mout .= '<div id="rule_comp' .$id. '" class="adv" style="display:' . ($rule['test'] != 'size' ? 'block' : 'none') .'">';
$mout .= ' <span>';
- $mout .= Q($this->gettext('comparator')) . ' ';
+ $mout .= rcube::Q($this->gettext('comparator')) . ' ';
$mout .= $select_comp->show($rule['comparator']);
$mout .= '</span>';
$mout .= '</div>';
// Build output table
$out = $div ? '<div class="rulerow" id="rulerow' .$id .'">'."\n" : '';
$out .= '<table><tr>';
$out .= '<td class="advbutton">';
- $out .= '<a href="#" id="ruleadv' . $id .'" title="'. Q($this->gettext('advancedopts')). '"
+ $out .= '<a href="#" id="ruleadv' . $id .'" title="'. rcube::Q($this->gettext('advancedopts')). '"
onclick="rule_adv_switch(' . $id .', this)" class="show">&nbsp;&nbsp;</a>';
$out .= '</td>';
$out .= '<td class="rowactions">' . $aout . '</td>';
$out .= '<td class="rowtargets">' . $tout . "\n";
$out .= '<div id="rule_advanced' .$id. '" style="display:none">' . $mout . '</div>';
$out .= '</td>';
// add/del buttons
$out .= '<td class="rowbuttons">';
- $out .= '<a href="#" id="ruleadd' . $id .'" title="'. Q($this->gettext('add')). '"
+ $out .= '<a href="#" id="ruleadd' . $id .'" title="'. rcube::Q($this->gettext('add')). '"
onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button add"></a>';
- $out .= '<a href="#" id="ruledel' . $id .'" title="'. Q($this->gettext('del')). '"
+ $out .= '<a href="#" id="ruledel' . $id .'" title="'. rcube::Q($this->gettext('del')). '"
onclick="rcmail.managesieve_ruledel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
$out .= '</td>';
$out .= '</tr></table>';
$out .= $div ? "</div>\n" : '';
return $out;
}
function action_div($fid, $id, $div=true)
{
$action = isset($this->form) ? $this->form['actions'][$id] : $this->script[$fid]['actions'][$id];
$rows_num = isset($this->form) ? sizeof($this->form['actions']) : sizeof($this->script[$fid]['actions']);
$out = $div ? '<div class="actionrow" id="actionrow' .$id .'">'."\n" : '';
$out .= '<table><tr><td class="rowactions">';
// action select
$select_action = new html_select(array('name' => "_action_type[$id]", 'id' => 'action_type'.$id,
'onchange' => 'action_type_select(' .$id .')'));
if (in_array('fileinto', $this->exts))
- $select_action->add(Q($this->gettext('messagemoveto')), 'fileinto');
+ $select_action->add(rcube::Q($this->gettext('messagemoveto')), 'fileinto');
if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
- $select_action->add(Q($this->gettext('messagecopyto')), 'fileinto_copy');
- $select_action->add(Q($this->gettext('messageredirect')), 'redirect');
+ $select_action->add(rcube::Q($this->gettext('messagecopyto')), 'fileinto_copy');
+ $select_action->add(rcube::Q($this->gettext('messageredirect')), 'redirect');
if (in_array('copy', $this->exts))
- $select_action->add(Q($this->gettext('messagesendcopy')), 'redirect_copy');
+ $select_action->add(rcube::Q($this->gettext('messagesendcopy')), 'redirect_copy');
if (in_array('reject', $this->exts))
- $select_action->add(Q($this->gettext('messagediscard')), 'reject');
+ $select_action->add(rcube::Q($this->gettext('messagediscard')), 'reject');
else if (in_array('ereject', $this->exts))
- $select_action->add(Q($this->gettext('messagediscard')), 'ereject');
+ $select_action->add(rcube::Q($this->gettext('messagediscard')), 'ereject');
if (in_array('vacation', $this->exts))
- $select_action->add(Q($this->gettext('messagereply')), 'vacation');
- $select_action->add(Q($this->gettext('messagedelete')), 'discard');
+ $select_action->add(rcube::Q($this->gettext('messagereply')), 'vacation');
+ $select_action->add(rcube::Q($this->gettext('messagedelete')), 'discard');
if (in_array('imapflags', $this->exts) || in_array('imap4flags', $this->exts)) {
- $select_action->add(Q($this->gettext('setflags')), 'setflag');
- $select_action->add(Q($this->gettext('addflags')), 'addflag');
- $select_action->add(Q($this->gettext('removeflags')), 'removeflag');
+ $select_action->add(rcube::Q($this->gettext('setflags')), 'setflag');
+ $select_action->add(rcube::Q($this->gettext('addflags')), 'addflag');
+ $select_action->add(rcube::Q($this->gettext('removeflags')), 'removeflag');
}
if (in_array('variables', $this->exts)) {
- $select_action->add(Q($this->gettext('setvariable')), 'set');
+ $select_action->add(rcube::Q($this->gettext('setvariable')), 'set');
}
if (in_array('enotify', $this->exts) || in_array('notify', $this->exts)) {
- $select_action->add(Q($this->gettext('notify')), 'notify');
+ $select_action->add(rcube::Q($this->gettext('notify')), 'notify');
}
- $select_action->add(Q($this->gettext('rulestop')), 'stop');
+ $select_action->add(rcube::Q($this->gettext('rulestop')), 'stop');
$select_type = $action['type'];
if (in_array($action['type'], array('fileinto', 'redirect')) && $action['copy']) {
$select_type .= '_copy';
}
$out .= $select_action->show($select_type);
$out .= '</td>';
// actions target inputs
$out .= '<td class="rowtargets">';
// shared targets
$out .= '<input type="text" name="_action_target['.$id.']" id="action_target' .$id. '" '
- .'value="' .($action['type']=='redirect' ? Q($action['target'], 'strict', false) : ''). '" size="35" '
+ .'value="' .($action['type']=='redirect' ? rcube::Q($action['target'], 'strict', false) : ''). '" size="35" '
.'style="display:' .($action['type']=='redirect' ? 'inline' : 'none') .'" '
. $this->error_class($id, 'action', 'target', 'action_target') .' />';
$out .= '<textarea name="_action_target_area['.$id.']" id="action_target_area' .$id. '" '
.'rows="3" cols="35" '. $this->error_class($id, 'action', 'targetarea', 'action_target_area')
.'style="display:' .(in_array($action['type'], array('reject', 'ereject')) ? 'inline' : 'none') .'">'
- . (in_array($action['type'], array('reject', 'ereject')) ? Q($action['target'], 'strict', false) : '')
+ . (in_array($action['type'], array('reject', 'ereject')) ? rcube::Q($action['target'], 'strict', false) : '')
. "</textarea>\n";
// vacation
$out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
- $out .= '<span class="label">'. Q($this->gettext('vacationreason')) .'</span><br />'
+ $out .= '<span class="label">'. rcube::Q($this->gettext('vacationreason')) .'</span><br />'
.'<textarea name="_action_reason['.$id.']" id="action_reason' .$id. '" '
.'rows="3" cols="35" '. $this->error_class($id, 'action', 'reason', 'action_reason') . '>'
. Q($action['reason'], 'strict', false) . "</textarea>\n";
- $out .= '<br /><span class="label">' .Q($this->gettext('vacationsubject')) . '</span><br />'
+ $out .= '<br /><span class="label">' .rcube::Q($this->gettext('vacationsubject')) . '</span><br />'
.'<input type="text" name="_action_subject['.$id.']" id="action_subject'.$id.'" '
- .'value="' . (is_array($action['subject']) ? Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="35" '
+ .'value="' . (is_array($action['subject']) ? rcube::Q(implode(', ', $action['subject']), 'strict', false) : $action['subject']) . '" size="35" '
. $this->error_class($id, 'action', 'subject', 'action_subject') .' />';
- $out .= '<br /><span class="label">' .Q($this->gettext('vacationaddresses')) . '</span><br />'
+ $out .= '<br /><span class="label">' .rcube::Q($this->gettext('vacationaddresses')) . '</span><br />'
.'<input type="text" name="_action_addresses['.$id.']" id="action_addr'.$id.'" '
- .'value="' . (is_array($action['addresses']) ? Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="35" '
+ .'value="' . (is_array($action['addresses']) ? rcube::Q(implode(', ', $action['addresses']), 'strict', false) : $action['addresses']) . '" size="35" '
. $this->error_class($id, 'action', 'addresses', 'action_addr') .' />';
- $out .= '<br /><span class="label">' . Q($this->gettext('vacationdays')) . '</span><br />'
+ $out .= '<br /><span class="label">' . rcube::Q($this->gettext('vacationdays')) . '</span><br />'
.'<input type="text" name="_action_days['.$id.']" id="action_days'.$id.'" '
- .'value="' .Q($action['days'], 'strict', false) . '" size="2" '
+ .'value="' .rcube::Q($action['days'], 'strict', false) . '" size="2" '
. $this->error_class($id, 'action', 'days', 'action_days') .' />';
$out .= '</div>';
// flags
$flags = array(
'read' => '\\Seen',
'answered' => '\\Answered',
'flagged' => '\\Flagged',
'deleted' => '\\Deleted',
'draft' => '\\Draft',
);
$flags_target = (array)$action['target'];
$out .= '<div id="action_flags' .$id.'" style="display:'
. (preg_match('/^(set|add|remove)flag$/', $action['type']) ? 'inline' : 'none') . '"'
. $this->error_class($id, 'action', 'flags', 'action_flags') . '>';
foreach ($flags as $fidx => $flag) {
$out .= '<input type="checkbox" name="_action_flags[' .$id .'][]" value="' . $flag . '"'
. (in_array_nocase($flag, $flags_target) ? 'checked="checked"' : '') . ' />'
- . Q($this->gettext('flag'.$fidx)) .'<br>';
+ . rcube::Q($this->gettext('flag'.$fidx)) .'<br>';
}
$out .= '</div>';
// set variable
$set_modifiers = array(
'lower',
'upper',
'lowerfirst',
'upperfirst',
'quotewildcard',
'length'
);
$out .= '<div id="action_set' .$id.'" style="display:' .($action['type']=='set' ? 'inline' : 'none') .'">';
- $out .= '<span class="label">' .Q($this->gettext('setvarname')) . '</span><br />'
+ $out .= '<span class="label">' .rcube::Q($this->gettext('setvarname')) . '</span><br />'
.'<input type="text" name="_action_varname['.$id.']" id="action_varname'.$id.'" '
- .'value="' . Q($action['name']) . '" size="35" '
+ .'value="' . rcube::Q($action['name']) . '" size="35" '
. $this->error_class($id, 'action', 'name', 'action_varname') .' />';
- $out .= '<br /><span class="label">' .Q($this->gettext('setvarvalue')) . '</span><br />'
+ $out .= '<br /><span class="label">' .rcube::Q($this->gettext('setvarvalue')) . '</span><br />'
.'<input type="text" name="_action_varvalue['.$id.']" id="action_varvalue'.$id.'" '
- .'value="' . Q($action['value']) . '" size="35" '
+ .'value="' . rcube::Q($action['value']) . '" size="35" '
. $this->error_class($id, 'action', 'value', 'action_varvalue') .' />';
- $out .= '<br /><span class="label">' .Q($this->gettext('setvarmodifiers')) . '</span><br />';
+ $out .= '<br /><span class="label">' .rcube::Q($this->gettext('setvarmodifiers')) . '</span><br />';
foreach ($set_modifiers as $j => $s_m) {
$s_m_id = 'action_varmods' . $id . $s_m;
$out .= sprintf('<input type="checkbox" name="_action_varmods[%s][]" value="%s" id="%s"%s />%s<br>',
$id, $s_m, $s_m_id,
(array_key_exists($s_m, (array)$action) && $action[$s_m] ? ' checked="checked"' : ''),
- Q($this->gettext('var' . $s_m)));
+ rcube::Q($this->gettext('var' . $s_m)));
}
$out .= '</div>';
// notify
// skip :options tag - not used by the mailto method
$out .= '<div id="action_notify' .$id.'" style="display:' .($action['type']=='notify' ? 'inline' : 'none') .'">';
- $out .= '<span class="label">' .Q($this->gettext('notifyaddress')) . '</span><br />'
+ $out .= '<span class="label">' .rcube::Q($this->gettext('notifyaddress')) . '</span><br />'
.'<input type="text" name="_action_notifyaddress['.$id.']" id="action_notifyaddress'.$id.'" '
- .'value="' . Q($action['address']) . '" size="35" '
+ .'value="' . rcube::Q($action['address']) . '" size="35" '
. $this->error_class($id, 'action', 'address', 'action_notifyaddress') .' />';
- $out .= '<br /><span class="label">'. Q($this->gettext('notifybody')) .'</span><br />'
+ $out .= '<br /><span class="label">'. rcube::Q($this->gettext('notifybody')) .'</span><br />'
.'<textarea name="_action_notifybody['.$id.']" id="action_notifybody' .$id. '" '
.'rows="3" cols="35" '. $this->error_class($id, 'action', 'method', 'action_notifybody') . '>'
- . Q($action['body'], 'strict', false) . "</textarea>\n";
- $out .= '<br /><span class="label">' .Q($this->gettext('notifysubject')) . '</span><br />'
+ . rcube::Q($action['body'], 'strict', false) . "</textarea>\n";
+ $out .= '<br /><span class="label">' .rcube::Q($this->gettext('notifysubject')) . '</span><br />'
.'<input type="text" name="_action_notifymessage['.$id.']" id="action_notifymessage'.$id.'" '
- .'value="' . Q($action['message']) . '" size="35" '
+ .'value="' . rcube::Q($action['message']) . '" size="35" '
. $this->error_class($id, 'action', 'message', 'action_notifymessage') .' />';
- $out .= '<br /><span class="label">' .Q($this->gettext('notifyfrom')) . '</span><br />'
+ $out .= '<br /><span class="label">' .rcube::Q($this->gettext('notifyfrom')) . '</span><br />'
.'<input type="text" name="_action_notifyfrom['.$id.']" id="action_notifyfrom'.$id.'" '
- .'value="' . Q($action['from']) . '" size="35" '
+ .'value="' . rcube::Q($action['from']) . '" size="35" '
. $this->error_class($id, 'action', 'from', 'action_notifyfrom') .' />';
$importance_options = array(
3 => 'notifyimportancelow',
2 => 'notifyimportancenormal',
1 => 'notifyimportancehigh'
);
$select_importance = new html_select(array(
'name' => '_action_notifyimportance[' . $id . ']',
'id' => '_action_notifyimportance' . $id,
'class' => $this->error_class($id, 'action', 'importance', 'action_notifyimportance')));
foreach ($importance_options as $io_v => $io_n) {
- $select_importance->add(Q($this->gettext($io_n)), $io_v);
+ $select_importance->add(rcube::Q($this->gettext($io_n)), $io_v);
}
- $out .= '<br /><span class="label">' . Q($this->gettext('notifyimportance')) . '</span><br />';
+ $out .= '<br /><span class="label">' . rcube::Q($this->gettext('notifyimportance')) . '</span><br />';
$out .= $select_importance->show($action['importance'] ? $action['importance'] : 2);
$out .= '</div>';
// mailbox select
if ($action['type'] == 'fileinto')
$mailbox = $this->mod_mailbox($action['target'], 'out');
else
$mailbox = '';
- $select = rcmail_mailbox_select(array(
+ $select = $this->rc->folder_selector(array(
'realnames' => false,
'maxlength' => 100,
'id' => 'action_mailbox' . $id,
'name' => "_action_mailbox[$id]",
'style' => 'display:'.(!isset($action) || $action['type']=='fileinto' ? 'inline' : 'none')
));
$out .= $select->show($mailbox);
$out .= '</td>';
// add/del buttons
$out .= '<td class="rowbuttons">';
- $out .= '<a href="#" id="actionadd' . $id .'" title="'. Q($this->gettext('add')). '"
+ $out .= '<a href="#" id="actionadd' . $id .'" title="'. rcube::Q($this->gettext('add')). '"
onclick="rcmail.managesieve_actionadd(' . $id .')" class="button add"></a>';
- $out .= '<a href="#" id="actiondel' . $id .'" title="'. Q($this->gettext('del')). '"
+ $out .= '<a href="#" id="actiondel' . $id .'" title="'. rcube::Q($this->gettext('del')). '"
onclick="rcmail.managesieve_actiondel(' . $id .')" class="button del' . ($rows_num<2 ? ' disabled' : '') .'"></a>';
$out .= '</td>';
$out .= '</tr></table>';
$out .= $div ? "</div>\n" : '';
return $out;
}
private function genid()
{
$result = preg_replace('/[^0-9]/', '', microtime(true));
return $result;
}
private function strip_value($str, $allow_html=false)
{
if (!$allow_html)
$str = strip_tags($str);
return trim($str);
}
private function error_class($id, $type, $target, $elem_prefix='')
{
// TODO: tooltips
if (($type == 'test' && ($str = $this->errors['tests'][$id][$target])) ||
($type == 'action' && ($str = $this->errors['actions'][$id][$target]))
) {
$this->add_tip($elem_prefix.$id, $str, true);
return ' class="error"';
}
return '';
}
private function add_tip($id, $str, $error=false)
{
if ($error)
$str = html::span('sieve error', $str);
$this->tips[] = array($id, $str);
}
private function print_tips()
{
if (empty($this->tips))
return;
- $script = JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
+ $script = rcmail_output::JS_OBJECT_NAME.'.managesieve_tip_register('.json_encode($this->tips).');';
$this->rc->output->add_script($script, 'foot');
}
/**
* Converts mailbox name from/to UTF7-IMAP from/to internal Sieve encoding
* with delimiter replacement.
*
* @param string $mailbox Mailbox name
* @param string $mode Conversion direction ('in'|'out')
*
* @return string Mailbox name
*/
private function mod_mailbox($mailbox, $mode = 'out')
{
$delimiter = $_SESSION['imap_delimiter'];
$replace_delimiter = $this->rc->config->get('managesieve_replace_delimiter');
$mbox_encoding = $this->rc->config->get('managesieve_mbox_encoding', 'UTF7-IMAP');
if ($mode == 'out') {
- $mailbox = rcube_charset_convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
+ $mailbox = rcube_charset::convert($mailbox, $mbox_encoding, 'UTF7-IMAP');
if ($replace_delimiter && $replace_delimiter != $delimiter)
$mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
}
else {
- $mailbox = rcube_charset_convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
+ $mailbox = rcube_charset::convert($mailbox, 'UTF7-IMAP', $mbox_encoding);
if ($replace_delimiter && $replace_delimiter != $delimiter)
$mailbox = str_replace($delimiter, $replace_delimiter, $mailbox);
}
return $mailbox;
}
/**
* List sieve scripts
*
* @return array Scripts list
*/
public function list_scripts()
{
if ($this->list !== null) {
return $this->list;
}
$this->list = $this->sieve->get_scripts();
// Handle active script(s) and list of scripts according to Kolab's KEP:14
if ($this->rc->config->get('managesieve_kolab_master')) {
// Skip protected names
foreach ((array)$this->list as $idx => $name) {
$_name = strtoupper($name);
if ($_name == 'MASTER')
$master_script = $name;
else if ($_name == 'MANAGEMENT')
$management_script = $name;
else if($_name == 'USER')
$user_script = $name;
else
continue;
unset($this->list[$idx]);
}
// get active script(s), read USER script
if ($user_script) {
$extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
$filename_regex = '/'.preg_quote($extension, '/').'$/';
$_SESSION['managesieve_user_script'] = $user_script;
$this->sieve->load($user_script);
foreach ($this->sieve->script->as_array() as $rules) {
foreach ($rules['actions'] as $action) {
if ($action['type'] == 'include' && empty($action['global'])) {
$name = preg_replace($filename_regex, '', $action['target']);
$this->active[] = $name;
}
}
}
}
// create USER script if it doesn't exist
else {
$content = "# USER Management Script\n"
."#\n"
."# This script includes the various active sieve scripts\n"
."# it is AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY!\n"
."#\n"
."# For more information, see http://wiki.kolab.org/KEP:14#USER\n"
."#\n";
if ($this->sieve->save_script('USER', $content)) {
$_SESSION['managesieve_user_script'] = 'USER';
if (empty($this->master_file))
$this->sieve->activate('USER');
}
}
}
else if (!empty($this->list)) {
// Get active script name
if ($active = $this->sieve->get_active()) {
$this->active = array($active);
}
// Hide scripts from config
$exceptions = $this->rc->config->get('managesieve_filename_exceptions');
if (!empty($exceptions)) {
$this->list = array_diff($this->list, (array)$exceptions);
}
}
return $this->list;
}
/**
* Removes sieve script
*
* @param string $name Script name
*
* @return bool True on success, False on failure
*/
public function remove_script($name)
{
$result = $this->sieve->remove($name);
// Kolab's KEP:14
if ($result && $this->rc->config->get('managesieve_kolab_master')) {
$this->deactivate_script($name);
}
return $result;
}
/**
* Activates sieve script
*
* @param string $name Script name
*
* @return bool True on success, False on failure
*/
public function activate_script($name)
{
// Kolab's KEP:14
if ($this->rc->config->get('managesieve_kolab_master')) {
$extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
$user_script = $_SESSION['managesieve_user_script'];
// if the script is not active...
if ($user_script && ($key = array_search($name, $this->active)) === false) {
// ...rewrite USER file adding appropriate include command
if ($this->sieve->load($user_script)) {
$script = $this->sieve->script->as_array();
$list = array();
$regexp = '/' . preg_quote($extension, '/') . '$/';
// Create new include entry
$rule = array(
'actions' => array(
0 => array(
'target' => $name.$extension,
'type' => 'include',
'personal' => true,
)));
// get all active scripts for sorting
foreach ($script as $rid => $rules) {
foreach ($rules['actions'] as $aid => $action) {
if ($action['type'] == 'include' && empty($action['global'])) {
$target = $extension ? preg_replace($regexp, '', $action['target']) : $action['target'];
$list[] = $target;
}
}
}
$list[] = $name;
// Sort and find current script position
asort($list, SORT_LOCALE_STRING);
$list = array_values($list);
$index = array_search($name, $list);
// add rule at the end of the script
if ($index === false || $index == count($list)-1) {
$this->sieve->script->add_rule($rule);
}
// add rule at index position
else {
$script2 = array();
foreach ($script as $rid => $rules) {
if ($rid == $index) {
$script2[] = $rule;
}
$script2[] = $rules;
}
$this->sieve->script->content = $script2;
}
$result = $this->sieve->save();
if ($result) {
$this->active[] = $name;
}
}
}
}
else {
$result = $this->sieve->activate($name);
if ($result)
$this->active = array($name);
}
return $result;
}
/**
* Deactivates sieve script
*
* @param string $name Script name
*
* @return bool True on success, False on failure
*/
public function deactivate_script($name)
{
// Kolab's KEP:14
if ($this->rc->config->get('managesieve_kolab_master')) {
$extension = $this->rc->config->get('managesieve_filename_extension', '.sieve');
$user_script = $_SESSION['managesieve_user_script'];
// if the script is active...
if ($user_script && ($key = array_search($name, $this->active)) !== false) {
// ...rewrite USER file removing appropriate include command
if ($this->sieve->load($user_script)) {
$script = $this->sieve->script->as_array();
$name = $name.$extension;
foreach ($script as $rid => $rules) {
foreach ($rules['actions'] as $aid => $action) {
if ($action['type'] == 'include' && empty($action['global'])
&& $action['target'] == $name
) {
break 2;
}
}
}
// Entry found
if ($rid < count($script)) {
$this->sieve->script->delete_rule($rid);
$result = $this->sieve->save();
if ($result) {
unset($this->active[$key]);
}
}
}
}
}
else {
$result = $this->sieve->deactivate();
if ($result)
$this->active = array();
}
return $result;
}
/**
* Saves current script (adding some variables)
*/
public function save_script($name = null)
{
// Kolab's KEP:14
if ($this->rc->config->get('managesieve_kolab_master')) {
$this->sieve->script->set_var('EDITOR', self::PROGNAME);
$this->sieve->script->set_var('EDITOR_VERSION', self::VERSION);
}
return $this->sieve->save($name);
}
/**
* Returns list of rules from the current script
*
* @return array List of rules
*/
public function list_rules()
{
$result = array();
$i = 1;
foreach ($this->script as $idx => $filter) {
if ($filter['type'] != 'if') {
continue;
}
$fname = $filter['name'] ? $filter['name'] : "#$i";
$result[] = array(
'id' => $idx,
- 'name' => Q($fname),
+ 'name' => rcube::Q($fname),
'class' => $filter['disabled'] ? 'disabled' : '',
);
$i++;
}
return $result;
}
}
diff --git a/plugins/markasjunk/markasjunk.php b/plugins/markasjunk/markasjunk.php
index 4db90c1bc..76b14c140 100644
--- a/plugins/markasjunk/markasjunk.php
+++ b/plugins/markasjunk/markasjunk.php
@@ -1,63 +1,63 @@
<?php
/**
* Mark as Junk
*
* Sample plugin that adds a new button to the mailbox toolbar
* to mark the selected messages as Junk and move them to the Junk folder
*
* @version @package_version@
* @license GNU GPLv3+
* @author Thomas Bruederli
*/
class markasjunk extends rcube_plugin
{
public $task = 'mail';
function init()
{
$rcmail = rcmail::get_instance();
$this->register_action('plugin.markasjunk', array($this, 'request_action'));
if ($rcmail->action == '' || $rcmail->action == 'show') {
$skin_path = $this->local_skin_path();
$this->include_script('markasjunk.js');
if (is_file($this->home . "/$skin_path/markasjunk.css"))
$this->include_stylesheet("$skin_path/markasjunk.css");
$this->add_texts('localization', true);
$this->add_button(array(
'type' => 'link',
'label' => 'buttontext',
'command' => 'plugin.markasjunk',
'class' => 'button buttonPas junk disabled',
'classact' => 'button junk',
'title' => 'buttontitle',
'domain' => 'markasjunk'), 'toolbar');
}
}
function request_action()
{
$this->add_texts('localization');
$GLOBALS['IMAP_FLAGS']['JUNK'] = 'Junk';
$GLOBALS['IMAP_FLAGS']['NONJUNK'] = 'NonJunk';
- $uids = get_input_value('_uid', RCUBE_INPUT_POST);
- $mbox = get_input_value('_mbox', RCUBE_INPUT_POST);
+ $uids = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
+ $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
$rcmail = rcmail::get_instance();
$rcmail->storage->unset_flag($uids, 'NONJUNK');
$rcmail->storage->set_flag($uids, 'JUNK');
if (($junk_mbox = $rcmail->config->get('junk_mbox')) && $mbox != $junk_mbox) {
$rcmail->output->command('move_messages', $junk_mbox);
}
$rcmail->output->command('display_message', $this->gettext('reportedasjunk'), 'confirmation');
$rcmail->output->send();
}
}
diff --git a/plugins/new_user_dialog/new_user_dialog.php b/plugins/new_user_dialog/new_user_dialog.php
index 9c9dcce1c..871384e47 100644
--- a/plugins/new_user_dialog/new_user_dialog.php
+++ b/plugins/new_user_dialog/new_user_dialog.php
@@ -1,145 +1,145 @@
<?php
/**
* Present identities settings dialog to new users
*
* When a new user is created, this plugin checks the default identity
* and sets a session flag in case it is incomplete. An overlay box will appear
* on the screen until the user has reviewed/completed his identity.
*
* @version @package_version@
* @license GNU GPLv3+
* @author Thomas Bruederli
*/
class new_user_dialog extends rcube_plugin
{
public $task = 'login|mail';
function init()
{
$this->add_hook('identity_create', array($this, 'create_identity'));
$this->register_action('plugin.newusersave', array($this, 'save_data'));
// register additional hooks if session flag is set
if ($_SESSION['plugin.newuserdialog']) {
$this->add_hook('render_page', array($this, 'render_page'));
}
}
/**
* Check newly created identity at first login
*/
function create_identity($p)
{
// set session flag when a new user was created and the default identity seems to be incomplete
if ($p['login'] && !$p['complete'])
$_SESSION['plugin.newuserdialog'] = true;
}
/**
* Callback function when HTML page is rendered
* We'll add an overlay box here.
*/
function render_page($p)
{
if ($_SESSION['plugin.newuserdialog'] && $p['template'] == 'mail') {
$this->add_texts('localization');
$rcmail = rcmail::get_instance();
$identity = $rcmail->user->get_identity();
$identities_level = intval($rcmail->config->get('identities_level', 0));
// compose user-identity dialog
$table = new html_table(array('cols' => 2));
$table->add('title', $this->gettext('name'));
$table->add(null, html::tag('input', array(
'type' => 'text',
'name' => '_name',
'value' => $identity['name']
)));
$table->add('title', $this->gettext('email'));
$table->add(null, html::tag('input', array(
'type' => 'text',
'name' => '_email',
- 'value' => rcube_idn_to_utf8($identity['email']),
+ 'value' => rcube_utils::idn_to_utf8($identity['email']),
'disabled' => ($identities_level == 1 || $identities_level == 3)
)));
$table->add('title', $this->gettext('organization'));
$table->add(null, html::tag('input', array(
'type' => 'text',
'name' => '_organization',
'value' => $identity['organization']
)));
$table->add('title', $this->gettext('signature'));
$table->add(null, html::tag('textarea', array(
'name' => '_signature',
'rows' => '3',
),$identity['signature']
));
// add overlay input box to html page
$rcmail->output->add_footer(html::tag('form', array(
'id' => 'newuserdialog',
'action' => $rcmail->url('plugin.newusersave'),
'method' => 'post'),
- html::tag('h3', null, Q($this->gettext('identitydialogtitle'))) .
- html::p('hint', Q($this->gettext('identitydialoghint'))) .
+ html::tag('h3', null, rcube::Q($this->gettext('identitydialogtitle'))) .
+ html::p('hint', rcube::Q($this->gettext('identitydialoghint'))) .
$table->show() .
html::p(array('class' => 'formbuttons'),
html::tag('input', array('type' => 'submit',
'class' => 'button mainaction', 'value' => $this->gettext('save'))))
));
// disable keyboard events for messages list (#1486726)
$rcmail->output->add_script(
"rcmail.message_list.key_press = function(){};
rcmail.message_list.key_down = function(){};
$('#newuserdialog').show().dialog({ modal:true, resizable:false, closeOnEscape:false, width:420 });
$('input[name=_name]').focus();
", 'docready');
$this->include_stylesheet('newuserdialog.css');
}
}
/**
* Handler for submitted form
*
* Check fields and save to default identity if valid.
* Afterwards the session flag is removed and we're done.
*/
function save_data()
{
$rcmail = rcmail::get_instance();
$identity = $rcmail->user->get_identity();
$identities_level = intval($rcmail->config->get('identities_level', 0));
$save_data = array(
- 'name' => get_input_value('_name', RCUBE_INPUT_POST),
- 'email' => get_input_value('_email', RCUBE_INPUT_POST),
- 'organization' => get_input_value('_organization', RCUBE_INPUT_POST),
- 'signature' => get_input_value('_signature', RCUBE_INPUT_POST),
+ 'name' => rcube_utils::get_input_value('_name', rcube_utils::INPUT_POST),
+ 'email' => rcube_utils::get_input_value('_email', rcube_utils::INPUT_POST),
+ 'organization' => rcube_utils::get_input_value('_organization', rcube_utils::INPUT_POST),
+ 'signature' => rcube_utils::get_input_value('_signature', rcube_utils::INPUT_POST),
);
// don't let the user alter the e-mail address if disabled by config
if ($identities_level == 1 || $identities_level == 3)
$save_data['email'] = $identity['email'];
else
- $save_data['email'] = rcube_idn_to_ascii($save_data['email']);
+ $save_data['email'] = rcube_utils::idn_to_ascii($save_data['email']);
// save data if not empty
if (!empty($save_data['name']) && !empty($save_data['email'])) {
$rcmail->user->update_identity($identity['identity_id'], $save_data);
$rcmail->session->remove('plugin.newuserdialog');
}
$rcmail->output->redirect('');
}
}
?>
diff --git a/plugins/new_user_identity/new_user_identity.php b/plugins/new_user_identity/new_user_identity.php
index 200d9accd..f98145b6c 100644
--- a/plugins/new_user_identity/new_user_identity.php
+++ b/plugins/new_user_identity/new_user_identity.php
@@ -1,86 +1,86 @@
<?php
/**
* New user identity
*
* Populates a new user's default identity from LDAP on their first visit.
*
* This plugin requires that a working public_ldap directory be configured.
*
* @version @package_version@
* @author Kris Steinhoff
*
* Example configuration:
*
* // The id of the address book to use to automatically set a new
* // user's full name in their new identity. (This should be an
* // string, which refers to the $rcmail_config['ldap_public'] array.)
* $rcmail_config['new_user_identity_addressbook'] = 'People';
*
* // When automatically setting a new users's full name in their
* // new identity, match the user's login name against this field.
* $rcmail_config['new_user_identity_match'] = 'uid';
*/
class new_user_identity extends rcube_plugin
{
public $task = 'login';
private $ldap;
function init()
{
$this->add_hook('user_create', array($this, 'lookup_user_name'));
}
function lookup_user_name($args)
{
$rcmail = rcmail::get_instance();
if ($this->init_ldap($args['host'])) {
$results = $this->ldap->search('*', $args['user'], true);
if (count($results->records) == 1) {
$user_name = is_array($results->records[0]['name']) ? $results->records[0]['name'][0] : $results->records[0]['name'];
$user_email = is_array($results->records[0]['email']) ? $results->records[0]['email'][0] : $results->records[0]['email'];
$args['user_name'] = $user_name;
if (!$args['user_email'] && strpos($user_email, '@')) {
- $args['user_email'] = rcube_idn_to_ascii($user_email);
+ $args['user_email'] = rcube_utils::idn_to_ascii($user_email);
}
}
}
return $args;
}
private function init_ldap($host)
{
if ($this->ldap) {
return $this->ldap->ready;
}
$rcmail = rcmail::get_instance();
$addressbook = $rcmail->config->get('new_user_identity_addressbook');
$ldap_config = (array)$rcmail->config->get('ldap_public');
$match = $rcmail->config->get('new_user_identity_match');
if (empty($addressbook) || empty($match) || empty($ldap_config[$addressbook])) {
return false;
}
$this->ldap = new new_user_identity_ldap_backend(
$ldap_config[$addressbook],
$rcmail->config->get('ldap_debug'),
$rcmail->config->mail_domain($host),
$match);
return $this->ldap->ready;
}
}
class new_user_identity_ldap_backend extends rcube_ldap
{
function __construct($p, $debug, $mail_domain, $search)
{
parent::__construct($p, $debug, $mail_domain);
$this->prop['search_fields'] = (array)$search;
}
}
diff --git a/plugins/newmail_notifier/newmail_notifier.php b/plugins/newmail_notifier/newmail_notifier.php
index 942421166..a45eeaedb 100644
--- a/plugins/newmail_notifier/newmail_notifier.php
+++ b/plugins/newmail_notifier/newmail_notifier.php
@@ -1,178 +1,178 @@
<?php
/**
* New Mail Notifier plugin
*
* Supports three methods of notification:
* 1. Basic - focus browser window and change favicon
* 2. Sound - play wav file
* 3. Desktop - display desktop notification (using webkitNotifications feature,
* supported by Chrome and Firefox with 'HTML5 Notifications' plugin)
*
* @version @package_version@
* @author Aleksander Machniak <alec@alec.pl>
*
*
* Copyright (C) 2011, Kolab Systems AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
class newmail_notifier extends rcube_plugin
{
public $task = 'mail|settings';
private $rc;
private $notified;
/**
* Plugin initialization
*/
function init()
{
$this->rc = rcmail::get_instance();
// Preferences hooks
if ($this->rc->task == 'settings') {
$this->add_hook('preferences_list', array($this, 'prefs_list'));
$this->add_hook('preferences_save', array($this, 'prefs_save'));
}
else { // if ($this->rc->task == 'mail') {
$this->add_hook('new_messages', array($this, 'notify'));
// add script when not in ajax and not in frame
if (is_a($this->rc->output, 'rcube_output_html') && empty($_REQUEST['_framed'])) {
$this->add_texts('localization/');
$this->rc->output->add_label('newmail_notifier.title', 'newmail_notifier.body');
$this->include_script('newmail_notifier.js');
}
}
}
/**
* Handler for user preferences form (preferences_list hook)
*/
function prefs_list($args)
{
if ($args['section'] != 'mailbox') {
return $args;
}
// Load configuration
$this->load_config();
// Load localization and configuration
$this->add_texts('localization/');
if (!empty($_REQUEST['_framed'])) {
$this->rc->output->add_label('newmail_notifier.title', 'newmail_notifier.testbody',
'newmail_notifier.desktopunsupported', 'newmail_notifier.desktopenabled', 'newmail_notifier.desktopdisabled');
$this->include_script('newmail_notifier.js');
}
// Check that configuration is not disabled
$dont_override = (array) $this->rc->config->get('dont_override', array());
foreach (array('basic', 'desktop', 'sound') as $type) {
$key = 'newmail_notifier_' . $type;
if (!in_array($key, $dont_override)) {
$field_id = '_' . $key;
$input = new html_checkbox(array('name' => $field_id, 'id' => $field_id, 'value' => 1));
$content = $input->show($this->rc->config->get($key))
. ' ' . html::a(array('href' => '#', 'onclick' => 'newmail_notifier_test_'.$type.'()'),
$this->gettext('test'));
$args['blocks']['new_message']['options'][$key] = array(
- 'title' => html::label($field_id, Q($this->gettext($type))),
+ 'title' => html::label($field_id, rcube::Q($this->gettext($type))),
'content' => $content
);
}
}
return $args;
}
/**
* Handler for user preferences save (preferences_save hook)
*/
function prefs_save($args)
{
if ($args['section'] != 'mailbox') {
return $args;
}
// Load configuration
$this->load_config();
// Check that configuration is not disabled
$dont_override = (array) $this->rc->config->get('dont_override', array());
foreach (array('basic', 'desktop', 'sound') as $type) {
$key = 'newmail_notifier_' . $type;
if (!in_array($key, $dont_override)) {
- $args['prefs'][$key] = get_input_value('_'.$key, RCUBE_INPUT_POST) ? true : false;
+ $args['prefs'][$key] = rcube_utils::get_input_value('_'.$key, rcube_utils::INPUT_POST) ? true : false;
}
}
return $args;
}
/**
* Handler for new message action (new_messages hook)
*/
function notify($args)
{
// Already notified or non-automatic check
if ($this->notified || !empty($_GET['_refresh'])) {
return $args;
}
// Get folders to skip checking for
if (empty($this->exceptions)) {
$this->delimiter = $this->rc->storage->get_hierarchy_delimiter();
$exceptions = array('drafts_mbox', 'sent_mbox', 'trash_mbox');
foreach ($exceptions as $folder) {
$folder = $this->rc->config->get($folder);
if (strlen($folder) && $folder != 'INBOX') {
$this->exceptions[] = $folder;
}
}
}
$mbox = $args['mailbox'];
// Skip exception (sent/drafts) folders (and their subfolders)
foreach ($this->exceptions as $folder) {
if (strpos($mbox.$this->delimiter, $folder.$this->delimiter) === 0) {
return $args;
}
}
$this->notified = true;
// Load configuration
$this->load_config();
$basic = $this->rc->config->get('newmail_notifier_basic');
$sound = $this->rc->config->get('newmail_notifier_sound');
$desktop = $this->rc->config->get('newmail_notifier_desktop');
if ($basic || $sound || $desktop) {
$this->rc->output->command('plugin.newmail_notifier',
array('basic' => $basic, 'sound' => $sound, 'desktop' => $desktop));
}
return $args;
}
}
diff --git a/plugins/password/drivers/chpasswd.php b/plugins/password/drivers/chpasswd.php
index 3ea10159c..137275e69 100644
--- a/plugins/password/drivers/chpasswd.php
+++ b/plugins/password/drivers/chpasswd.php
@@ -1,39 +1,39 @@
<?php
/**
* chpasswd Driver
*
* Driver that adds functionality to change the systems user password via
* the 'chpasswd' command.
*
* For installation instructions please read the README file.
*
* @version 2.0
* @author Alex Cartwright <acartwright@mutinydesign.co.uk>
*/
class rcube_chpasswd_password
{
public function save($currpass, $newpass)
{
$cmd = rcmail::get_instance()->config->get('password_chpasswd_cmd');
$username = $_SESSION['username'];
$handle = popen($cmd, "w");
fwrite($handle, "$username:$newpass\n");
if (pclose($handle) == 0) {
return PASSWORD_SUCCESS;
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to execute $cmd"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/dbmail.php b/plugins/password/drivers/dbmail.php
index e4c0d52e3..529027b8d 100644
--- a/plugins/password/drivers/dbmail.php
+++ b/plugins/password/drivers/dbmail.php
@@ -1,42 +1,42 @@
<?php
/**
* DBMail Password Driver
*
* Driver that adds functionality to change the users DBMail password.
* The code is derrived from the Squirrelmail "Change SASL Password" Plugin
* by Galen Johnson.
*
* It only works with dbmail-users on the same host where Roundcube runs
* and requires shell access and gcc in order to compile the binary.
*
* For installation instructions please read the README file.
*
* @version 1.0
*/
class rcube_dbmail_password
{
function password_save($currpass, $newpass)
{
$curdir = RCUBE_PLUGINS_DIR . 'password/helpers';
$username = escapeshellcmd($_SESSION['username']);
$args = rcmail::get_instance()->config->get('password_dbmail_args', '');
exec("$curdir/chgdbmailusers -c $username -w $newpass $args", $output, $returnvalue);
if ($returnvalue == 0) {
return PASSWORD_SUCCESS;
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to execute $curdir/chgdbmailusers"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/directadmin.php b/plugins/password/drivers/directadmin.php
index fb156cea9..8bf0dc613 100644
--- a/plugins/password/drivers/directadmin.php
+++ b/plugins/password/drivers/directadmin.php
@@ -1,489 +1,489 @@
<?php
/**
* DirectAdmin Password Driver
*
* Driver to change passwords via DirectAdmin Control Panel
*
* @version 2.1
* @author Victor Benincasa <vbenincasa@gmail.com>
*
*/
class rcube_directadmin_password
{
public function save($curpass, $passwd)
{
$rcmail = rcmail::get_instance();
$Socket = new HTTPSocket;
$da_user = $_SESSION['username'];
$da_curpass = $curpass;
$da_newpass = $passwd;
$da_host = $rcmail->config->get('password_directadmin_host');
$da_port = $rcmail->config->get('password_directadmin_port');
if (strpos($da_user, '@') === false) {
return array('code' => PASSWORD_ERROR, 'message' => 'Change the SYSTEM user password through control panel!');
}
$da_host = str_replace('%h', $_SESSION['imap_host'], $da_host);
$da_host = str_replace('%d', $rcmail->user->get_username('domain'), $da_host);
$Socket->connect($da_host,$da_port);
$Socket->set_method('POST');
$Socket->query('/CMD_CHANGE_EMAIL_PASSWORD',
array(
'email' => $da_user,
'oldpassword' => $da_curpass,
'password1' => $da_newpass,
'password2' => $da_newpass,
'api' => '1'
));
$response = $Socket->fetch_parsed_body();
//DEBUG
- //console("Password Plugin: [USER: $da_user] [HOST: $da_host] - Response: [SOCKET: ".$Socket->result_status_code."] [DA ERROR: ".strip_tags($response['error'])."] [TEXT: ".$response[text]."]");
+ //rcube::console("Password Plugin: [USER: $da_user] [HOST: $da_host] - Response: [SOCKET: ".$Socket->result_status_code."] [DA ERROR: ".strip_tags($response['error'])."] [TEXT: ".$response[text]."]");
if($Socket->result_status_code != 200)
return array('code' => PASSWORD_CONNECT_ERROR, 'message' => $Socket->error[0]);
elseif($response['error'] == 1)
return array('code' => PASSWORD_ERROR, 'message' => strip_tags($response['text']));
else
return PASSWORD_SUCCESS;
}
}
/**
* Socket communication class.
*
* Originally designed for use with DirectAdmin's API, this class will fill any HTTP socket need.
*
* Very, very basic usage:
* $Socket = new HTTPSocket;
* echo $Socket->get('http://user:pass@somehost.com:2222/CMD_API_SOMEAPI?query=string&this=that');
*
* @author Phi1 'l0rdphi1' Stier <l0rdphi1@liquenox.net>
* @updates 2.7 and 2.8 by Victor Benincasa <vbenincasa @ gmail.com>
* @package HTTPSocket
* @version 2.8
*/
class HTTPSocket {
var $version = '2.8';
/* all vars are private except $error, $query_cache, and $doFollowLocationHeader */
var $method = 'GET';
var $remote_host;
var $remote_port;
var $remote_uname;
var $remote_passwd;
var $result;
var $result_header;
var $result_body;
var $result_status_code;
var $lastTransferSpeed;
var $bind_host;
var $error = array();
var $warn = array();
var $query_cache = array();
var $doFollowLocationHeader = TRUE;
var $redirectURL;
var $extra_headers = array();
/**
* Create server "connection".
*
*/
function connect($host, $port = '' )
{
if (!is_numeric($port))
{
$port = 2222;
}
$this->remote_host = $host;
$this->remote_port = $port;
}
function bind( $ip = '' )
{
if ( $ip == '' )
{
$ip = $_SERVER['SERVER_ADDR'];
}
$this->bind_host = $ip;
}
/**
* Change the method being used to communicate.
*
* @param string|null request method. supports GET, POST, and HEAD. default is GET
*/
function set_method( $method = 'GET' )
{
$this->method = strtoupper($method);
}
/**
* Specify a username and password.
*
* @param string|null username. defualt is null
* @param string|null password. defualt is null
*/
function set_login( $uname = '', $passwd = '' )
{
if ( strlen($uname) > 0 )
{
$this->remote_uname = $uname;
}
if ( strlen($passwd) > 0 )
{
$this->remote_passwd = $passwd;
}
}
/**
* Query the server
*
* @param string containing properly formatted server API. See DA API docs and examples. Http:// URLs O.K. too.
* @param string|array query to pass to url
* @param int if connection KB/s drops below value here, will drop connection
*/
function query( $request, $content = '', $doSpeedCheck = 0 )
{
$this->error = $this->warn = array();
$this->result_status_code = NULL;
// is our request a http(s):// ... ?
if (preg_match('/^(http|https):\/\//i',$request))
{
$location = parse_url($request);
$this->connect($location['host'],$location['port']);
$this->set_login($location['user'],$location['pass']);
$request = $location['path'];
$content = $location['query'];
if ( strlen($request) < 1 )
{
$request = '/';
}
}
$array_headers = array(
'User-Agent' => "HTTPSocket/$this->version",
'Host' => ( $this->remote_port == 80 ? parse_url($this->remote_host,PHP_URL_HOST) : parse_url($this->remote_host,PHP_URL_HOST).":".$this->remote_port ),
'Accept' => '*/*',
'Connection' => 'Close' );
foreach ( $this->extra_headers as $key => $value )
{
$array_headers[$key] = $value;
}
$this->result = $this->result_header = $this->result_body = '';
// was content sent as an array? if so, turn it into a string
if (is_array($content))
{
$pairs = array();
foreach ( $content as $key => $value )
{
$pairs[] = "$key=".urlencode($value);
}
$content = join('&',$pairs);
unset($pairs);
}
$OK = TRUE;
// instance connection
if ($this->bind_host)
{
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket,$this->bind_host);
if (!@socket_connect($socket,$this->remote_host,$this->remote_port))
{
$OK = FALSE;
}
}
else
{
$socket = @fsockopen( $this->remote_host, $this->remote_port, $sock_errno, $sock_errstr, 10 );
}
if ( !$socket || !$OK )
{
$this->error[] = "Can't create socket connection to $this->remote_host:$this->remote_port.";
return 0;
}
// if we have a username and password, add the header
if ( isset($this->remote_uname) && isset($this->remote_passwd) )
{
$array_headers['Authorization'] = 'Basic '.base64_encode("$this->remote_uname:$this->remote_passwd");
}
// for DA skins: if $this->remote_passwd is NULL, try to use the login key system
if ( isset($this->remote_uname) && $this->remote_passwd == NULL )
{
$array_headers['Cookie'] = "session={$_SERVER['SESSION_ID']}; key={$_SERVER['SESSION_KEY']}";
}
// if method is POST, add content length & type headers
if ( $this->method == 'POST' )
{
$array_headers['Content-type'] = 'application/x-www-form-urlencoded';
$array_headers['Content-length'] = strlen($content);
}
// else method is GET or HEAD. we don't support anything else right now.
else
{
if ($content)
{
$request .= "?$content";
}
}
// prepare query
$query = "$this->method $request HTTP/1.0\r\n";
foreach ( $array_headers as $key => $value )
{
$query .= "$key: $value\r\n";
}
$query .= "\r\n";
// if POST we need to append our content
if ( $this->method == 'POST' && $content )
{
$query .= "$content\r\n\r\n";
}
// query connection
if ($this->bind_host)
{
socket_write($socket,$query);
// now load results
while ( $out = socket_read($socket,2048) )
{
$this->result .= $out;
}
}
else
{
fwrite( $socket, $query, strlen($query) );
// now load results
$this->lastTransferSpeed = 0;
$status = socket_get_status($socket);
$startTime = time();
$length = 0;
$prevSecond = 0;
while ( !feof($socket) && !$status['timed_out'] )
{
$chunk = fgets($socket,1024);
$length += strlen($chunk);
$this->result .= $chunk;
$elapsedTime = time() - $startTime;
if ( $elapsedTime > 0 )
{
$this->lastTransferSpeed = ($length/1024)/$elapsedTime;
}
if ( $doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck )
{
$this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~".( ($length/1024)/$elapsedTime )."), dropping connection...";
$this->result_status_code = 503;
break;
}
}
if ( $this->lastTransferSpeed == 0 )
{
$this->lastTransferSpeed = $length/1024;
}
}
list($this->result_header,$this->result_body) = preg_split("/\r\n\r\n/",$this->result,2);
if ($this->bind_host)
{
socket_close($socket);
}
else
{
fclose($socket);
}
$this->query_cache[] = $query;
$headers = $this->fetch_header();
// what return status did we get?
if (!$this->result_status_code)
{
preg_match("#HTTP/1\.. (\d+)#",$headers[0],$matches);
$this->result_status_code = $matches[1];
}
// did we get the full file?
if ( !empty($headers['content-length']) && $headers['content-length'] != strlen($this->result_body) )
{
$this->result_status_code = 206;
}
// now, if we're being passed a location header, should we follow it?
if ($this->doFollowLocationHeader)
{
if ($headers['location'])
{
$this->redirectURL = $headers['location'];
$this->query($headers['location']);
}
}
}
function getTransferSpeed()
{
return $this->lastTransferSpeed;
}
/**
* The quick way to get a URL's content :)
*
* @param string URL
* @param boolean return as array? (like PHP's file() command)
* @return string result body
*/
function get($location, $asArray = FALSE )
{
$this->query($location);
if ( $this->get_status_code() == 200 )
{
if ($asArray)
{
return preg_split("/\n/",$this->fetch_body());
}
return $this->fetch_body();
}
return FALSE;
}
/**
* Returns the last status code.
* 200 = OK;
* 403 = FORBIDDEN;
* etc.
*
* @return int status code
*/
function get_status_code()
{
return $this->result_status_code;
}
/**
* Adds a header, sent with the next query.
*
* @param string header name
* @param string header value
*/
function add_header($key,$value)
{
$this->extra_headers[$key] = $value;
}
/**
* Clears any extra headers.
*
*/
function clear_headers()
{
$this->extra_headers = array();
}
/**
* Return the result of a query.
*
* @return string result
*/
function fetch_result()
{
return $this->result;
}
/**
* Return the header of result (stuff before body).
*
* @param string (optional) header to return
* @return array result header
*/
function fetch_header( $header = '' )
{
$array_headers = preg_split("/\r\n/",$this->result_header);
$array_return = array( 0 => $array_headers[0] );
unset($array_headers[0]);
foreach ( $array_headers as $pair )
{
list($key,$value) = preg_split("/: /",$pair,2);
$array_return[strtolower($key)] = $value;
}
if ( $header != '' )
{
return $array_return[strtolower($header)];
}
return $array_return;
}
/**
* Return the body of result (stuff after header).
*
* @return string result body
*/
function fetch_body()
{
return $this->result_body;
}
/**
* Return parsed body in array format.
*
* @return array result parsed
*/
function fetch_parsed_body()
{
parse_str($this->result_body,$x);
return $x;
}
}
diff --git a/plugins/password/drivers/expect.php b/plugins/password/drivers/expect.php
index 7a191e254..1f68924df 100644
--- a/plugins/password/drivers/expect.php
+++ b/plugins/password/drivers/expect.php
@@ -1,58 +1,58 @@
<?php
/**
* expect Driver
*
* Driver that adds functionality to change the systems user password via
* the 'expect' command.
*
* For installation instructions please read the README file.
*
* @version 2.0
* @author Andy Theuninck <gohanman@gmail.com)
*
* Based on chpasswd roundcubemail password driver by
* @author Alex Cartwright <acartwright@mutinydesign.co.uk)
* and expect horde passwd driver by
* @author Gaudenz Steinlin <gaudenz@soziologie.ch>
*
* Configuration settings:
* password_expect_bin => location of expect (e.g. /usr/bin/expect)
* password_expect_script => path to "password-expect" file
* password_expect_params => arguments for the expect script
* see the password-expect file for details. This is probably
* a good starting default:
* -telent -host localhost -output /tmp/passwd.log -log /tmp/passwd.log
*/
class rcube_expect_password
{
public function save($currpass, $newpass)
{
$rcmail = rcmail::get_instance();
$bin = $rcmail->config->get('password_expect_bin');
$script = $rcmail->config->get('password_expect_script');
$params = $rcmail->config->get('password_expect_params');
$username = $_SESSION['username'];
$cmd = $bin . ' -f ' . $script . ' -- ' . $params;
$handle = popen($cmd, "w");
fwrite($handle, "$username\n");
fwrite($handle, "$currpass\n");
fwrite($handle, "$newpass\n");
if (pclose($handle) == 0) {
return PASSWORD_SUCCESS;
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to execute $cmd"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/hmail.php b/plugins/password/drivers/hmail.php
index 104c851ae..a8f07a23b 100644
--- a/plugins/password/drivers/hmail.php
+++ b/plugins/password/drivers/hmail.php
@@ -1,63 +1,63 @@
<?php
/**
* hMailserver password driver
*
* @version 2.0
* @author Roland 'rosali' Liebl <myroundcube@mail4us.net>
*
*/
class rcube_hmail_password
{
public function save($curpass, $passwd)
{
$rcmail = rcmail::get_instance();
if ($curpass == '' || $passwd == '') {
return PASSWORD_ERROR;
}
try {
$remote = $rcmail->config->get('hmailserver_remote_dcom', false);
if ($remote)
$obApp = new COM("hMailServer.Application", $rcmail->config->get('hmailserver_server'));
else
$obApp = new COM("hMailServer.Application");
}
catch (Exception $e) {
- write_log('errors', "Plugin password (hmail driver): " . trim(strip_tags($e->getMessage())));
- write_log('errors', "Plugin password (hmail driver): This problem is often caused by DCOM permissions not being set.");
+ rcube::write_log('errors', "Plugin password (hmail driver): " . trim(strip_tags($e->getMessage())));
+ rcube::write_log('errors', "Plugin password (hmail driver): This problem is often caused by DCOM permissions not being set.");
return PASSWORD_ERROR;
}
$username = $rcmail->user->data['username'];
if (strstr($username,'@')){
$temparr = explode('@', $username);
$domain = $temparr[1];
}
else {
$domain = $rcmail->config->get('username_domain',false);
if (!$domain) {
- write_log('errors','Plugin password (hmail driver): $rcmail_config[\'username_domain\'] is not defined.');
- write_log('errors','Plugin password (hmail driver): Hint: Use hmail_login plugin (http://myroundcube.googlecode.com');
+ rcube::write_log('errors','Plugin password (hmail driver): $rcmail_config[\'username_domain\'] is not defined.');
+ rcube::write_log('errors','Plugin password (hmail driver): Hint: Use hmail_login plugin (http://myroundcube.googlecode.com');
return PASSWORD_ERROR;
}
$username = $username . "@" . $domain;
}
$obApp->Authenticate($username, $curpass);
try {
$obDomain = $obApp->Domains->ItemByName($domain);
$obAccount = $obDomain->Accounts->ItemByAddress($username);
$obAccount->Password = $passwd;
$obAccount->Save();
return PASSWORD_SUCCESS;
}
catch (Exception $e) {
- write_log('errors', "Plugin password (hmail driver): " . trim(strip_tags($e->getMessage())));
- write_log('errors', "Plugin password (hmail driver): This problem is often caused by DCOM permissions not being set.");
+ rcube::write_log('errors', "Plugin password (hmail driver): " . trim(strip_tags($e->getMessage())));
+ rcube::write_log('errors', "Plugin password (hmail driver): This problem is often caused by DCOM permissions not being set.");
return PASSWORD_ERROR;
}
}
}
diff --git a/plugins/password/drivers/ldap.php b/plugins/password/drivers/ldap.php
index f773335ac..548d327e1 100644
--- a/plugins/password/drivers/ldap.php
+++ b/plugins/password/drivers/ldap.php
@@ -1,319 +1,319 @@
<?php
/**
* LDAP Password Driver
*
* Driver for passwords stored in LDAP
* This driver use the PEAR Net_LDAP2 class (http://pear.php.net/package/Net_LDAP2).
*
* @version 2.0
* @author Edouard MOREAU <edouard.moreau@ensma.fr>
*
* method hashPassword based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/).
* method randomSalt based on code from the phpLDAPadmin development team (http://phpldapadmin.sourceforge.net/).
*
*/
class rcube_ldap_password
{
public function save($curpass, $passwd)
{
$rcmail = rcmail::get_instance();
require_once 'Net/LDAP2.php';
// Building user DN
if ($userDN = $rcmail->config->get('password_ldap_userDN_mask')) {
$userDN = $this->substitute_vars($userDN);
} else {
$userDN = $this->search_userdn($rcmail);
}
if (empty($userDN)) {
return PASSWORD_CONNECT_ERROR;
}
// Connection Method
switch($rcmail->config->get('password_ldap_method')) {
case 'admin':
$binddn = $rcmail->config->get('password_ldap_adminDN');
$bindpw = $rcmail->config->get('password_ldap_adminPW');
break;
case 'user':
default:
$binddn = $userDN;
$bindpw = $curpass;
break;
}
// Configuration array
$ldapConfig = array (
'binddn' => $binddn,
'bindpw' => $bindpw,
'basedn' => $rcmail->config->get('password_ldap_basedn'),
'host' => $rcmail->config->get('password_ldap_host'),
'port' => $rcmail->config->get('password_ldap_port'),
'starttls' => $rcmail->config->get('password_ldap_starttls'),
'version' => $rcmail->config->get('password_ldap_version'),
);
// Connecting using the configuration array
$ldap = Net_LDAP2::connect($ldapConfig);
// Checking for connection error
if (PEAR::isError($ldap)) {
return PASSWORD_CONNECT_ERROR;
}
$crypted_pass = $this->hashPassword($passwd, $rcmail->config->get('password_ldap_encodage'));
$force = $rcmail->config->get('password_ldap_force_replace');
$pwattr = $rcmail->config->get('password_ldap_pwattr');
$lchattr = $rcmail->config->get('password_ldap_lchattr');
$smbpwattr = $rcmail->config->get('password_ldap_samba_pwattr');
$smblchattr = $rcmail->config->get('password_ldap_samba_lchattr');
$samba = $rcmail->config->get('password_ldap_samba');
// Support password_ldap_samba option for backward compat.
if ($samba && !$smbpwattr) {
$smbpwattr = 'sambaNTPassword';
$smblchattr = 'sambaPwdLastSet';
}
// Crypt new password
if (!$crypted_pass) {
return PASSWORD_CRYPT_ERROR;
}
// Crypt new samba password
if ($smbpwattr && !($samba_pass = $this->hashPassword($passwd, 'samba'))) {
return PASSWORD_CRYPT_ERROR;
}
// Writing new crypted password to LDAP
$userEntry = $ldap->getEntry($userDN);
if (Net_LDAP2::isError($userEntry)) {
return PASSWORD_CONNECT_ERROR;
}
if (!$userEntry->replace(array($pwattr => $crypted_pass), $force)) {
return PASSWORD_CONNECT_ERROR;
}
// Updating PasswordLastChange Attribute if desired
if ($lchattr) {
$current_day = (int)(time() / 86400);
if (!$userEntry->replace(array($lchattr => $current_day), $force)) {
return PASSWORD_CONNECT_ERROR;
}
}
// Update Samba password and last change fields
if ($smbpwattr) {
$userEntry->replace(array($smbpwattr => $samba_pass), $force);
}
// Update Samba password last change field
if ($smblchattr) {
$userEntry->replace(array($smblchattr => time()), $force);
}
if (Net_LDAP2::isError($userEntry->update())) {
return PASSWORD_CONNECT_ERROR;
}
// All done, no error
return PASSWORD_SUCCESS;
}
/**
* Bind with searchDN and searchPW and search for the user's DN.
* Use search_base and search_filter defined in config file.
* Return the found DN.
*/
function search_userdn($rcmail)
{
$ldapConfig = array (
'binddn' => $rcmail->config->get('password_ldap_searchDN'),
'bindpw' => $rcmail->config->get('password_ldap_searchPW'),
'basedn' => $rcmail->config->get('password_ldap_basedn'),
'host' => $rcmail->config->get('password_ldap_host'),
'port' => $rcmail->config->get('password_ldap_port'),
'starttls' => $rcmail->config->get('password_ldap_starttls'),
'version' => $rcmail->config->get('password_ldap_version'),
);
$ldap = Net_LDAP2::connect($ldapConfig);
if (PEAR::isError($ldap)) {
return '';
}
$base = $rcmail->config->get('password_ldap_search_base');
$filter = $this->substitute_vars($rcmail->config->get('password_ldap_search_filter'));
$options = array (
'scope' => 'sub',
'attributes' => array(),
);
$result = $ldap->search($base, $filter, $options);
$ldap->done();
if (PEAR::isError($result) || ($result->count() != 1)) {
return '';
}
return $result->current()->dn();
}
/**
* Substitute %login, %name, %domain, %dc in $str.
* See plugin config for details.
*/
function substitute_vars($str)
{
$rcmail = rcmail::get_instance();
$domain = $rcmail->user->get_username('domain');
$dc = 'dc='.strtr($domain, array('.' => ',dc=')); // hierarchal domain string
$str = str_replace(array(
'%login',
'%name',
'%domain',
'%dc',
), array(
$_SESSION['username'],
$rcmail->user->get_username('local'),
$domain,
$dc,
), $str
);
return $str;
}
/**
* Code originaly from the phpLDAPadmin development team
* http://phpldapadmin.sourceforge.net/
*
* Hashes a password and returns the hash based on the specified enc_type.
*
* @param string $passwordClear The password to hash in clear text.
* @param string $encodageType Standard LDAP encryption type which must be one of
* crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
* @return string The hashed password.
*
*/
function hashPassword( $passwordClear, $encodageType )
{
$encodageType = strtolower( $encodageType );
switch( $encodageType ) {
case 'crypt':
$cryptedPassword = '{CRYPT}' . crypt($passwordClear, $this->randomSalt(2));
break;
case 'ext_des':
// extended des crypt. see OpenBSD crypt man page.
if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {
// Your system crypt library does not support extended DES encryption.
return FALSE;
}
$cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
break;
case 'md5crypt':
if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {
// Your system crypt library does not support md5crypt encryption.
return FALSE;
}
$cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
break;
case 'blowfish':
if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {
// Your system crypt library does not support blowfish encryption.
return FALSE;
}
// hardcoded to second blowfish version and set number of rounds
$cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) );
break;
case 'md5':
$cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
break;
case 'sha':
if( function_exists('sha1') ) {
// use php 4.3.0+ sha1 function, if it is available.
$cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
} elseif( function_exists( 'mhash' ) ) {
$cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
} else {
return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
}
break;
case 'ssha':
if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
mt_srand( (double) microtime() * 1000000 );
$salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( 'h*', md5( mt_rand() ) ), 0, 8 ), 4 );
$cryptedPassword = '{SSHA}'.base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
} else {
return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
}
break;
case 'smd5':
if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
mt_srand( (double) microtime() * 1000000 );
$salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( 'h*', md5( mt_rand() ) ), 0, 8 ), 4 );
$cryptedPassword = '{SMD5}'.base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
} else {
return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
}
break;
case 'samba':
if (function_exists('hash')) {
- $cryptedPassword = hash('md4', rcube_charset_convert($passwordClear, RCMAIL_CHARSET, 'UTF-16LE'));
+ $cryptedPassword = hash('md4', rcube_charset::convert($passwordClear, RCUBE_CHARSET, 'UTF-16LE'));
$cryptedPassword = strtoupper($cryptedPassword);
} else {
/* Your PHP install does not have the hash() function */
return false;
}
break;
case 'clear':
default:
$cryptedPassword = $passwordClear;
}
return $cryptedPassword;
}
/**
* Code originaly from the phpLDAPadmin development team
* http://phpldapadmin.sourceforge.net/
*
* Used to generate a random salt for crypt-style passwords. Salt strings are used
* to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
* not only the user's password but also a randomly generated string. The string is
* stored as the first N characters of the hash for reference of hashing algorithms later.
*
* --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
* --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
*
* @param int $length The length of the salt string to generate.
* @return string The generated salt string.
*/
function randomSalt( $length )
{
$possible = '0123456789'.
'abcdefghijklmnopqrstuvwxyz'.
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
'./';
$str = '';
// mt_srand((double)microtime() * 1000000);
while (strlen($str) < $length)
$str .= substr($possible, (rand() % strlen($possible)), 1);
return $str;
}
}
diff --git a/plugins/password/drivers/ldap_simple.php b/plugins/password/drivers/ldap_simple.php
index 01385f2d0..d47e14492 100644
--- a/plugins/password/drivers/ldap_simple.php
+++ b/plugins/password/drivers/ldap_simple.php
@@ -1,276 +1,276 @@
<?php
/**
* Simple LDAP Password Driver
*
* Driver for passwords stored in LDAP
* This driver is based on Edouard's LDAP Password Driver, but does not
* require PEAR's Net_LDAP2 to be installed
*
* @version 2.0
* @author Wout Decre <wout@canodus.be>
*/
class rcube_ldap_simple_password
{
function save($curpass, $passwd)
{
$rcmail = rcmail::get_instance();
// Connect
if (!$ds = ldap_connect($rcmail->config->get('password_ldap_host'), $rcmail->config->get('password_ldap_port'))) {
ldap_unbind($ds);
return PASSWORD_CONNECT_ERROR;
}
// Set protocol version
if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, $rcmail->config->get('password_ldap_version'))) {
ldap_unbind($ds);
return PASSWORD_CONNECT_ERROR;
}
// Start TLS
if ($rcmail->config->get('password_ldap_starttls')) {
if (!ldap_start_tls($ds)) {
ldap_unbind($ds);
return PASSWORD_CONNECT_ERROR;
}
}
// Build user DN
if ($user_dn = $rcmail->config->get('password_ldap_userDN_mask')) {
$user_dn = $this->substitute_vars($user_dn);
}
else {
$user_dn = $this->search_userdn($rcmail, $ds);
}
if (empty($user_dn)) {
ldap_unbind($ds);
return PASSWORD_CONNECT_ERROR;
}
// Connection method
switch ($rcmail->config->get('password_ldap_method')) {
case 'admin':
$binddn = $rcmail->config->get('password_ldap_adminDN');
$bindpw = $rcmail->config->get('password_ldap_adminPW');
break;
case 'user':
default:
$binddn = $user_dn;
$bindpw = $curpass;
break;
}
$crypted_pass = $this->hash_password($passwd, $rcmail->config->get('password_ldap_encodage'));
$lchattr = $rcmail->config->get('password_ldap_lchattr');
$pwattr = $rcmail->config->get('password_ldap_pwattr');
$smbpwattr = $rcmail->config->get('password_ldap_samba_pwattr');
$smblchattr = $rcmail->config->get('password_ldap_samba_lchattr');
$samba = $rcmail->config->get('password_ldap_samba');
// Support password_ldap_samba option for backward compat.
if ($samba && !$smbpwattr) {
$smbpwattr = 'sambaNTPassword';
$smblchattr = 'sambaPwdLastSet';
}
// Crypt new password
if (!$crypted_pass) {
return PASSWORD_CRYPT_ERROR;
}
// Crypt new Samba password
if ($smbpwattr && !($samba_pass = $this->hash_password($passwd, 'samba'))) {
return PASSWORD_CRYPT_ERROR;
}
// Bind
if (!ldap_bind($ds, $binddn, $bindpw)) {
ldap_unbind($ds);
return PASSWORD_CONNECT_ERROR;
}
$entree[$pwattr] = $crypted_pass;
// Update PasswordLastChange Attribute if desired
if ($lchattr) {
$entree[$lchattr] = (int)(time() / 86400);
}
// Update Samba password
if ($smbpwattr) {
$entree[$smbpwattr] = $samba_pass;
}
// Update Samba password last change
if ($smblchattr) {
$entree[$smblchattr] = time();
}
if (!ldap_modify($ds, $user_dn, $entree)) {
ldap_unbind($ds);
return PASSWORD_CONNECT_ERROR;
}
// All done, no error
ldap_unbind($ds);
return PASSWORD_SUCCESS;
}
/**
* Bind with searchDN and searchPW and search for the user's DN
* Use search_base and search_filter defined in config file
* Return the found DN
*/
function search_userdn($rcmail, $ds)
{
/* Bind */
if (!ldap_bind($ds, $rcmail->config->get('password_ldap_searchDN'), $rcmail->config->get('password_ldap_searchPW'))) {
return false;
}
/* Search for the DN */
if (!$sr = ldap_search($ds, $rcmail->config->get('password_ldap_search_base'), $this->substitute_vars($rcmail->config->get('password_ldap_search_filter')))) {
return false;
}
/* If no or more entries were found, return false */
if (ldap_count_entries($ds, $sr) != 1) {
return false;
}
return ldap_get_dn($ds, ldap_first_entry($ds, $sr));
}
/**
* Substitute %login, %name, %domain, %dc in $str
* See plugin config for details
*/
function substitute_vars($str)
{
$str = str_replace('%login', $_SESSION['username'], $str);
$str = str_replace('%l', $_SESSION['username'], $str);
$parts = explode('@', $_SESSION['username']);
if (count($parts) == 2) {
$dc = 'dc='.strtr($parts[1], array('.' => ',dc=')); // hierarchal domain string
$str = str_replace('%name', $parts[0], $str);
$str = str_replace('%n', $parts[0], $str);
$str = str_replace('%dc', $dc, $str);
$str = str_replace('%domain', $parts[1], $str);
$str = str_replace('%d', $parts[1], $str);
}
return $str;
}
/**
* Code originaly from the phpLDAPadmin development team
* http://phpldapadmin.sourceforge.net/
*
* Hashes a password and returns the hash based on the specified enc_type
*/
function hash_password($password_clear, $encodage_type)
{
$encodage_type = strtolower($encodage_type);
switch ($encodage_type) {
case 'crypt':
$crypted_password = '{CRYPT}' . crypt($password_clear, $this->random_salt(2));
break;
case 'ext_des':
/* Extended DES crypt. see OpenBSD crypt man page */
if (!defined('CRYPT_EXT_DES') || CRYPT_EXT_DES == 0) {
/* Your system crypt library does not support extended DES encryption */
return false;
}
$crypted_password = '{CRYPT}' . crypt($password_clear, '_' . $this->random_salt(8));
break;
case 'md5crypt':
if (!defined('CRYPT_MD5') || CRYPT_MD5 == 0) {
/* Your system crypt library does not support md5crypt encryption */
return false;
}
$crypted_password = '{CRYPT}' . crypt($password_clear, '$1$' . $this->random_salt(9));
break;
case 'blowfish':
if (!defined('CRYPT_BLOWFISH') || CRYPT_BLOWFISH == 0) {
/* Your system crypt library does not support blowfish encryption */
return false;
}
/* Hardcoded to second blowfish version and set number of rounds */
$crypted_password = '{CRYPT}' . crypt($password_clear, '$2a$12$' . $this->random_salt(13));
break;
case 'md5':
$crypted_password = '{MD5}' . base64_encode(pack('H*', md5($password_clear)));
break;
case 'sha':
if (function_exists('sha1')) {
/* Use PHP 4.3.0+ sha1 function, if it is available */
$crypted_password = '{SHA}' . base64_encode(pack('H*', sha1($password_clear)));
} else if (function_exists('mhash')) {
$crypted_password = '{SHA}' . base64_encode(mhash(MHASH_SHA1, $password_clear));
} else {
/* Your PHP install does not have the mhash() function */
return false;
}
break;
case 'ssha':
if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) {
mt_srand((double) microtime() * 1000000 );
$salt = mhash_keygen_s2k(MHASH_SHA1, $password_clear, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
$crypted_password = '{SSHA}' . base64_encode(mhash(MHASH_SHA1, $password_clear . $salt) . $salt);
} else {
/* Your PHP install does not have the mhash() function */
return false;
}
break;
case 'smd5':
if (function_exists('mhash') && function_exists('mhash_keygen_s2k')) {
mt_srand((double) microtime() * 1000000 );
$salt = mhash_keygen_s2k(MHASH_MD5, $password_clear, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
$crypted_password = '{SMD5}' . base64_encode(mhash(MHASH_MD5, $password_clear . $salt) . $salt);
} else {
/* Your PHP install does not have the mhash() function */
return false;
}
break;
case 'samba':
if (function_exists('hash')) {
- $crypted_password = hash('md4', rcube_charset_convert($password_clear, RCMAIL_CHARSET, 'UTF-16LE'));
+ $crypted_password = hash('md4', rcube_charset::convert($password_clear, RCUBE_CHARSET, 'UTF-16LE'));
$crypted_password = strtoupper($crypted_password);
} else {
/* Your PHP install does not have the hash() function */
return false;
}
break;
case 'clear':
default:
$crypted_password = $password_clear;
}
return $crypted_password;
}
/**
* Code originaly from the phpLDAPadmin development team
* http://phpldapadmin.sourceforge.net/
*
* Used to generate a random salt for crypt-style passwords
*/
function random_salt($length)
{
$possible = '0123456789' . 'abcdefghijklmnopqrstuvwxyz' . 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . './';
$str = '';
// mt_srand((double)microtime() * 1000000);
while (strlen($str) < $length) {
$str .= substr($possible, (rand() % strlen($possible)), 1);
}
return $str;
}
}
diff --git a/plugins/password/drivers/pam.php b/plugins/password/drivers/pam.php
index 20524d9f1..8cd94c737 100644
--- a/plugins/password/drivers/pam.php
+++ b/plugins/password/drivers/pam.php
@@ -1,42 +1,42 @@
<?php
/**
* PAM Password Driver
*
* @version 2.0
* @author Aleksander Machniak
*/
class rcube_pam_password
{
function save($currpass, $newpass)
{
$user = $_SESSION['username'];
if (extension_loaded('pam') || extension_loaded('pam_auth')) {
if (pam_auth($user, $currpass, $error, false)) {
if (pam_chpass($user, $currpass, $newpass)) {
return PASSWORD_SUCCESS;
}
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: PAM authentication failed for user $user: $error"
), true, false);
}
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: PECL-PAM module not loaded"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/pw_usermod.php b/plugins/password/drivers/pw_usermod.php
index 5b92fcbfb..237e275a7 100644
--- a/plugins/password/drivers/pw_usermod.php
+++ b/plugins/password/drivers/pw_usermod.php
@@ -1,41 +1,41 @@
<?php
/**
* pw_usermod Driver
*
* Driver that adds functionality to change the systems user password via
* the 'pw usermod' command.
*
* For installation instructions please read the README file.
*
* @version 2.0
* @author Alex Cartwright <acartwright@mutinydesign.co.uk>
* @author Adamson Huang <adomputer@gmail.com>
*/
class rcube_pw_usermod_password
{
public function save($currpass, $newpass)
{
$username = $_SESSION['username'];
$cmd = rcmail::get_instance()->config->get('password_pw_usermod_cmd');
$cmd .= " $username > /dev/null";
$handle = popen($cmd, "w");
fwrite($handle, "$newpass\n");
if (pclose($handle) == 0) {
return PASSWORD_SUCCESS;
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to execute $cmd"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/sasl.php b/plugins/password/drivers/sasl.php
index 9380cf838..8776eff2e 100644
--- a/plugins/password/drivers/sasl.php
+++ b/plugins/password/drivers/sasl.php
@@ -1,45 +1,45 @@
<?php
/**
* SASL Password Driver
*
* Driver that adds functionality to change the users Cyrus/SASL password.
* The code is derrived from the Squirrelmail "Change SASL Password" Plugin
* by Galen Johnson.
*
* It only works with saslpasswd2 on the same host where Roundcube runs
* and requires shell access and gcc in order to compile the binary.
*
* For installation instructions please read the README file.
*
* @version 2.0
* @author Thomas Bruederli
*/
class rcube_sasl_password
{
function save($currpass, $newpass)
{
$curdir = RCUBE_PLUGINS_DIR . 'password/helpers';
$username = escapeshellcmd($_SESSION['username']);
$args = rcmail::get_instance()->config->get('password_saslpasswd_args', '');
if ($fh = popen("$curdir/chgsaslpasswd -p $args $username", 'w')) {
fwrite($fh, $newpass."\n");
$code = pclose($fh);
if ($code == 0)
return PASSWORD_SUCCESS;
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to execute $curdir/chgsaslpasswd"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/smb.php b/plugins/password/drivers/smb.php
index 88021156f..d56924eee 100644
--- a/plugins/password/drivers/smb.php
+++ b/plugins/password/drivers/smb.php
@@ -1,58 +1,58 @@
<?php
/**
* smb Driver
*
* Driver that adds functionality to change the systems user password via
* the 'smbpasswd' command.
*
* For installation instructions please read the README file.
*
* @version 2.0
* @author Andy Theuninck <gohanman@gmail.com)
*
* Based on chpasswd roundcubemail password driver by
* @author Alex Cartwright <acartwright@mutinydesign.co.uk)
* and smbpasswd horde passwd driver by
* @author Rene Lund Jensen <Rene@lundjensen.net>
*
* Configuration settings:
* password_smb_host => samba host (default: localhost)
* password_smb_cmd => smbpasswd binary (default: /usr/bin/smbpasswd)
*/
class rcube_smb_password
{
public function save($currpass, $newpass)
{
$host = rcmail::get_instance()->config->get('password_smb_host','localhost');
$bin = rcmail::get_instance()->config->get('password_smb_cmd','/usr/bin/smbpasswd');
$username = $_SESSION['username'];
$tmpfile = tempnam(sys_get_temp_dir(),'smb');
$cmd = $bin . ' -r ' . $host . ' -s -U "' . $username . '" > ' . $tmpfile . ' 2>&1';
$handle = @popen($cmd, 'w');
fputs($handle, $currpass."\n");
fputs($handle, $newpass."\n");
fputs($handle, $newpass."\n");
@pclose($handle);
$res = file($tmpfile);
unlink($tmpfile);
if (strstr($res[count($res) - 1], 'Password changed for user') !== false) {
return PASSWORD_SUCCESS;
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to execute $cmd"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/sql.php b/plugins/password/drivers/sql.php
index b08833dbf..e02bff146 100644
--- a/plugins/password/drivers/sql.php
+++ b/plugins/password/drivers/sql.php
@@ -1,200 +1,200 @@
<?php
/**
* SQL Password Driver
*
* Driver for passwords stored in SQL database
*
* @version 2.0
* @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
*
*/
class rcube_sql_password
{
function save($curpass, $passwd)
{
$rcmail = rcmail::get_instance();
if (!($sql = $rcmail->config->get('password_query')))
$sql = 'SELECT update_passwd(%c, %u)';
if ($dsn = $rcmail->config->get('password_db_dsn')) {
// #1486067: enable new_link option
if (is_array($dsn) && empty($dsn['new_link']))
$dsn['new_link'] = true;
else if (!is_array($dsn) && !preg_match('/\?new_link=true/', $dsn))
$dsn .= '?new_link=true';
$db = rcube_db::factory($dsn, '', false);
$db->set_debug((bool)$rcmail->config->get('sql_debug'));
$db->db_connect('w');
}
else {
$db = $rcmail->get_dbh();
}
if ($err = $db->is_error())
return PASSWORD_ERROR;
// crypted password
if (strpos($sql, '%c') !== FALSE) {
$salt = '';
if (!($crypt_hash = $rcmail->config->get('password_crypt_hash')))
{
if (CRYPT_MD5)
$crypt_hash = 'md5';
else if (CRYPT_STD_DES)
$crypt_hash = 'des';
}
switch ($crypt_hash)
{
case 'md5':
$len = 8;
$salt_hashindicator = '$1$';
break;
case 'des':
$len = 2;
break;
case 'blowfish':
$len = 22;
$salt_hashindicator = '$2a$';
break;
case 'sha256':
$len = 16;
$salt_hashindicator = '$5$';
break;
case 'sha512':
$len = 16;
$salt_hashindicator = '$6$';
break;
default:
return PASSWORD_CRYPT_ERROR;
}
//Restrict the character set used as salt (#1488136)
$seedchars = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
for ($i = 0; $i < $len ; $i++) {
$salt .= $seedchars[rand(0, 63)];
}
$sql = str_replace('%c', $db->quote(crypt($passwd, $salt_hashindicator ? $salt_hashindicator .$salt.'$' : $salt)), $sql);
}
// dovecotpw
if (strpos($sql, '%D') !== FALSE) {
if (!($dovecotpw = $rcmail->config->get('password_dovecotpw')))
$dovecotpw = 'dovecotpw';
if (!($method = $rcmail->config->get('password_dovecotpw_method')))
$method = 'CRAM-MD5';
// use common temp dir
$tmp_dir = $rcmail->config->get('temp_dir');
$tmpfile = tempnam($tmp_dir, 'roundcube-');
$pipe = popen("$dovecotpw -s '$method' > '$tmpfile'", "w");
if (!$pipe) {
unlink($tmpfile);
return PASSWORD_CRYPT_ERROR;
}
else {
fwrite($pipe, $passwd . "\n", 1+strlen($passwd)); usleep(1000);
fwrite($pipe, $passwd . "\n", 1+strlen($passwd));
pclose($pipe);
$newpass = trim(file_get_contents($tmpfile), "\n");
if (!preg_match('/^\{' . $method . '\}/', $newpass)) {
return PASSWORD_CRYPT_ERROR;
}
if (!$rcmail->config->get('password_dovecotpw_with_method'))
$newpass = trim(str_replace('{' . $method . '}', '', $newpass));
unlink($tmpfile);
}
$sql = str_replace('%D', $db->quote($newpass), $sql);
}
// hashed passwords
if (preg_match('/%[n|q]/', $sql)) {
if (!extension_loaded('hash')) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: 'hash' extension not loaded!"
), true, false);
return PASSWORD_ERROR;
}
if (!($hash_algo = strtolower($rcmail->config->get('password_hash_algorithm'))))
$hash_algo = 'sha1';
$hash_passwd = hash($hash_algo, $passwd);
$hash_curpass = hash($hash_algo, $curpass);
if ($rcmail->config->get('password_hash_base64')) {
$hash_passwd = base64_encode(pack('H*', $hash_passwd));
$hash_curpass = base64_encode(pack('H*', $hash_curpass));
}
$sql = str_replace('%n', $db->quote($hash_passwd, 'text'), $sql);
$sql = str_replace('%q', $db->quote($hash_curpass, 'text'), $sql);
}
// Handle clear text passwords securely (#1487034)
$sql_vars = array();
if (preg_match_all('/%[p|o]/', $sql, $m)) {
foreach ($m[0] as $var) {
if ($var == '%p') {
$sql = preg_replace('/%p/', '?', $sql, 1);
$sql_vars[] = (string) $passwd;
}
else { // %o
$sql = preg_replace('/%o/', '?', $sql, 1);
$sql_vars[] = (string) $curpass;
}
}
}
$local_part = $rcmail->user->get_username('local');
$domain_part = $rcmail->user->get_username('domain');
$username = $_SESSION['username'];
$host = $_SESSION['imap_host'];
// convert domains to/from punnycode
if ($rcmail->config->get('password_idn_ascii')) {
- $domain_part = rcube_idn_to_ascii($domain_part);
- $username = rcube_idn_to_ascii($username);
- $host = rcube_idn_to_ascii($host);
+ $domain_part = rcube_utils::idn_to_ascii($domain_part);
+ $username = rcube_utils::idn_to_ascii($username);
+ $host = rcube_utils::idn_to_ascii($host);
}
else {
- $domain_part = rcube_idn_to_utf8($domain_part);
- $username = rcube_idn_to_utf8($username);
- $host = rcube_idn_to_utf8($host);
+ $domain_part = rcube_utils::idn_to_utf8($domain_part);
+ $username = rcube_utils::idn_to_utf8($username);
+ $host = rcube_utils::idn_to_utf8($host);
}
// at least we should always have the local part
$sql = str_replace('%l', $db->quote($local_part, 'text'), $sql);
$sql = str_replace('%d', $db->quote($domain_part, 'text'), $sql);
$sql = str_replace('%u', $db->quote($username, 'text'), $sql);
$sql = str_replace('%h', $db->quote($host, 'text'), $sql);
$res = $db->query($sql, $sql_vars);
if (!$db->is_error()) {
if (strtolower(substr(trim($query),0,6))=='select') {
if ($result = $db->fetch_array($res))
return PASSWORD_SUCCESS;
} else {
// This is the good case: 1 row updated
if ($db->affected_rows($res) == 1)
return PASSWORD_SUCCESS;
// @TODO: Some queries don't affect any rows
// Should we assume a success if there was no error?
}
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/virtualmin.php b/plugins/password/drivers/virtualmin.php
index d2b765a9e..2c7aee617 100644
--- a/plugins/password/drivers/virtualmin.php
+++ b/plugins/password/drivers/virtualmin.php
@@ -1,80 +1,80 @@
<?php
/**
* Virtualmin Password Driver
*
* Driver that adds functionality to change the users Virtualmin password.
* The code is derrived from the Squirrelmail "Change Cyrus/SASL Password" Plugin
* by Thomas Bruederli.
*
* It only works with virtualmin on the same host where Roundcube runs
* and requires shell access and gcc in order to compile the binary.
*
* @version 3.0
* @author Martijn de Munnik
*/
class rcube_virtualmin_password
{
function save($currpass, $newpass)
{
$rcmail = rcmail::get_instance();
$format = $rcmail->config->get('password_virtualmin_format', 0);
$username = $_SESSION['username'];
switch ($format) {
case 1: // username%domain
$domain = substr(strrchr($username, "%"), 1);
break;
case 2: // username.domain (could be bogus)
$pieces = explode(".", $username);
$domain = $pieces[count($pieces)-2]. "." . end($pieces);
break;
case 3: // domain.username (could be bogus)
$pieces = explode(".", $username);
$domain = $pieces[0]. "." . $pieces[1];
break;
case 4: // username-domain
$domain = substr(strrchr($username, "-"), 1);
break;
case 5: // domain-username
$domain = str_replace(strrchr($username, "-"), "", $username);
break;
case 6: // username_domain
$domain = substr(strrchr($username, "_"), 1);
break;
case 7: // domain_username
$pieces = explode("_", $username);
$domain = $pieces[0];
break;
case 8: // domain taken from alias, username left as it was
$email = $rcmail->user->data['alias'];
$domain = substr(strrchr($email, "@"), 1);
break;
default: // username@domain
$domain = substr(strrchr($username, "@"), 1);
}
$username = escapeshellcmd($username);
$domain = escapeshellcmd($domain);
$newpass = escapeshellcmd($newpass);
$curdir = RCUBE_PLUGINS_DIR . 'password/helpers';
exec("$curdir/chgvirtualminpasswd modify-user --domain $domain --user $username --pass $newpass", $output, $returnvalue);
if ($returnvalue == 0) {
return PASSWORD_SUCCESS;
}
else {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to execute $curdir/chgvirtualminpasswd"
), true, false);
}
return PASSWORD_ERROR;
}
}
diff --git a/plugins/password/drivers/xmail.php b/plugins/password/drivers/xmail.php
index 33a49ffe3..37abc3001 100644
--- a/plugins/password/drivers/xmail.php
+++ b/plugins/password/drivers/xmail.php
@@ -1,106 +1,106 @@
<?php
/**
* XMail Password Driver
*
* Driver for XMail password
*
* @version 2.0
* @author Helio Cavichiolo Jr <helio@hcsistemas.com.br>
*
* Setup xmail_host, xmail_user, xmail_pass and xmail_port into
* config.inc.php of password plugin as follows:
*
* $rcmail_config['xmail_host'] = 'localhost';
* $rcmail_config['xmail_user'] = 'YourXmailControlUser';
* $rcmail_config['xmail_pass'] = 'YourXmailControlPass';
* $rcmail_config['xmail_port'] = 6017;
*
*/
class rcube_xmail_password
{
function save($currpass, $newpass)
{
$rcmail = rcmail::get_instance();
list($user,$domain) = explode('@', $_SESSION['username']);
$xmail = new XMail;
$xmail->hostname = $rcmail->config->get('xmail_host');
$xmail->username = $rcmail->config->get('xmail_user');
$xmail->password = $rcmail->config->get('xmail_pass');
$xmail->port = $rcmail->config->get('xmail_port');
if (!$xmail->connect()) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to connect to mail server"
), true, false);
return PASSWORD_CONNECT_ERROR;
}
else if (!$xmail->send("userpasswd\t".$domain."\t".$user."\t".$newpass."\n")) {
$xmail->close();
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to change password"
), true, false);
return PASSWORD_ERROR;
}
else {
$xmail->close();
return PASSWORD_SUCCESS;
}
}
}
class XMail {
var $socket;
var $hostname = 'localhost';
var $username = 'xmail';
var $password = '';
var $port = 6017;
function send($msg)
{
socket_write($this->socket,$msg);
if (substr($in = socket_read($this->socket, 512, PHP_BINARY_READ),0,1) != "+") {
return false;
}
return true;
}
function connect()
{
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($this->socket < 0)
return false;
$result = socket_connect($this->socket, $this->hostname, $this->port);
if ($result < 0) {
socket_close($this->socket);
return false;
}
if (substr($in = socket_read($this->socket, 512, PHP_BINARY_READ),0,1) != "+") {
socket_close($this->socket);
return false;
}
if (!$this->send("$this->username\t$this->password\n")) {
socket_close($this->socket);
return false;
}
return true;
}
function close()
{
$this->send("quit\n");
socket_close($this->socket);
}
}
diff --git a/plugins/password/password.php b/plugins/password/password.php
index 806db0586..39020a0bf 100644
--- a/plugins/password/password.php
+++ b/plugins/password/password.php
@@ -1,298 +1,298 @@
<?php
/*
+-------------------------------------------------------------------------+
| Password Plugin for Roundcube |
| @version @package_version@ |
| |
| Copyright (C) 2009-2010, Roundcube Dev. |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License version 2 |
| as published by the Free Software Foundation. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with this program; if not, write to the Free Software Foundation, Inc., |
| 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| |
+-------------------------------------------------------------------------+
| Author: Aleksander Machniak <alec@alec.pl> |
+-------------------------------------------------------------------------+
$Id: index.php 2645 2009-06-15 07:01:36Z alec $
*/
define('PASSWORD_CRYPT_ERROR', 1);
define('PASSWORD_ERROR', 2);
define('PASSWORD_CONNECT_ERROR', 3);
define('PASSWORD_SUCCESS', 0);
/**
* Change password plugin
*
* Plugin that adds functionality to change a users password.
* It provides common functionality and user interface and supports
* several backends to finally update the password.
*
* For installation and configuration instructions please read the README file.
*
* @author Aleksander Machniak
*/
class password extends rcube_plugin
{
public $task = 'settings';
public $noframe = true;
public $noajax = true;
function init()
{
$rcmail = rcmail::get_instance();
$this->load_config();
// Host exceptions
$hosts = $rcmail->config->get('password_hosts');
if (!empty($hosts) && !in_array($_SESSION['storage_host'], $hosts)) {
return;
}
// Login exceptions
if ($exceptions = $rcmail->config->get('password_login_exceptions')) {
$exceptions = array_map('trim', (array) $exceptions);
$exceptions = array_filter($exceptions);
$username = $_SESSION['username'];
foreach ($exceptions as $ec) {
if ($username === $ec) {
return;
}
}
}
// add Tab label
$rcmail->output->add_label('password');
$this->register_action('plugin.password', array($this, 'password_init'));
$this->register_action('plugin.password-save', array($this, 'password_save'));
$this->include_script('password.js');
}
function password_init()
{
$this->add_texts('localization/');
$this->register_handler('plugin.body', array($this, 'password_form'));
$rcmail = rcmail::get_instance();
$rcmail->output->set_pagetitle($this->gettext('changepasswd'));
$rcmail->output->send('plugin');
}
function password_save()
{
$rcmail = rcmail::get_instance();
$this->add_texts('localization/');
$this->register_handler('plugin.body', array($this, 'password_form'));
$rcmail->output->set_pagetitle($this->gettext('changepasswd'));
$confirm = $rcmail->config->get('password_confirm_current');
$required_length = intval($rcmail->config->get('password_minimum_length'));
$check_strength = $rcmail->config->get('password_require_nonalpha');
if (($confirm && !isset($_POST['_curpasswd'])) || !isset($_POST['_newpasswd'])) {
$rcmail->output->command('display_message', $this->gettext('nopassword'), 'error');
}
else {
$charset = strtoupper($rcmail->config->get('password_charset', 'ISO-8859-1'));
$rc_charset = strtoupper($rcmail->output->get_charset());
$sespwd = $rcmail->decrypt($_SESSION['password']);
- $curpwd = $confirm ? get_input_value('_curpasswd', RCUBE_INPUT_POST, true, $charset) : $sespwd;
- $newpwd = get_input_value('_newpasswd', RCUBE_INPUT_POST, true);
- $conpwd = get_input_value('_confpasswd', RCUBE_INPUT_POST, true);
+ $curpwd = $confirm ? rcube_utils::get_input_value('_curpasswd', rcube_utils::INPUT_POST, true, $charset) : $sespwd;
+ $newpwd = rcube_utils::get_input_value('_newpasswd', rcube_utils::INPUT_POST, true);
+ $conpwd = rcube_utils::get_input_value('_confpasswd', rcube_utils::INPUT_POST, true);
// check allowed characters according to the configured 'password_charset' option
// by converting the password entered by the user to this charset and back to UTF-8
$orig_pwd = $newpwd;
- $chk_pwd = rcube_charset_convert($orig_pwd, $rc_charset, $charset);
- $chk_pwd = rcube_charset_convert($chk_pwd, $charset, $rc_charset);
+ $chk_pwd = rcube_charset::convert($orig_pwd, $rc_charset, $charset);
+ $chk_pwd = rcube_charset::convert($chk_pwd, $charset, $rc_charset);
// WARNING: Default password_charset is ISO-8859-1, so conversion will
// change national characters. This may disable possibility of using
// the same password in other MUA's.
// We're doing this for consistence with Roundcube core
- $newpwd = rcube_charset_convert($newpwd, $rc_charset, $charset);
- $conpwd = rcube_charset_convert($conpwd, $rc_charset, $charset);
+ $newpwd = rcube_charset::convert($newpwd, $rc_charset, $charset);
+ $conpwd = rcube_charset::convert($conpwd, $rc_charset, $charset);
if ($chk_pwd != $orig_pwd) {
$rcmail->output->command('display_message', $this->gettext('passwordforbidden'), 'error');
}
// other passwords validity checks
else if ($conpwd != $newpwd) {
$rcmail->output->command('display_message', $this->gettext('passwordinconsistency'), 'error');
}
else if ($confirm && $sespwd != $curpwd) {
$rcmail->output->command('display_message', $this->gettext('passwordincorrect'), 'error');
}
else if ($required_length && strlen($newpwd) < $required_length) {
$rcmail->output->command('display_message', $this->gettext(
- array('name' => 'passwordshort', 'vars' => array('length' => $required_length))), 'error');
+ array('name' => 'passwordshort', 'vars' => array('length' => $required_length))), 'error');
}
else if ($check_strength && (!preg_match("/[0-9]/", $newpwd) || !preg_match("/[^A-Za-z0-9]/", $newpwd))) {
$rcmail->output->command('display_message', $this->gettext('passwordweak'), 'error');
}
// password is the same as the old one, do nothing, return success
else if ($sespwd == $newpwd) {
$rcmail->output->command('display_message', $this->gettext('successfullysaved'), 'confirmation');
}
// try to save the password
else if (!($res = $this->_save($curpwd, $newpwd))) {
$rcmail->output->command('display_message', $this->gettext('successfullysaved'), 'confirmation');
// allow additional actions after password change (e.g. reset some backends)
$plugin = $rcmail->plugins->exec_hook('password_change', array(
'old_pass' => $curpwd, 'new_pass' => $newpwd));
// Reset session password
$_SESSION['password'] = $rcmail->encrypt($plugin['new_pass']);
// Log password change
if ($rcmail->config->get('password_log')) {
- write_log('password', sprintf('Password changed for user %s (ID: %d) from %s',
- $rcmail->get_user_name(), $rcmail->user->ID, rcmail_remote_ip()));
+ rcube::write_log('password', sprintf('Password changed for user %s (ID: %d) from %s',
+ $rcmail->get_user_name(), $rcmail->user->ID, rcube_utils::remote_ip()));
}
}
else {
$rcmail->output->command('display_message', $res, 'error');
}
}
- rcmail_overwrite_action('plugin.password');
+ $rcmail->overwrite_action('plugin.password');
$rcmail->output->send('plugin');
}
function password_form()
{
$rcmail = rcmail::get_instance();
// add some labels to client
$rcmail->output->add_label(
'password.nopassword',
'password.nocurpassword',
'password.passwordinconsistency'
);
$rcmail->output->set_env('product_name', $rcmail->config->get('product_name'));
$table = new html_table(array('cols' => 2));
if ($rcmail->config->get('password_confirm_current')) {
// show current password selection
$field_id = 'curpasswd';
$input_curpasswd = new html_passwordfield(array('name' => '_curpasswd', 'id' => $field_id,
'size' => 20, 'autocomplete' => 'off'));
- $table->add('title', html::label($field_id, Q($this->gettext('curpasswd'))));
+ $table->add('title', html::label($field_id, rcube::Q($this->gettext('curpasswd'))));
$table->add(null, $input_curpasswd->show());
}
// show new password selection
$field_id = 'newpasswd';
$input_newpasswd = new html_passwordfield(array('name' => '_newpasswd', 'id' => $field_id,
'size' => 20, 'autocomplete' => 'off'));
- $table->add('title', html::label($field_id, Q($this->gettext('newpasswd'))));
+ $table->add('title', html::label($field_id, rcube::Q($this->gettext('newpasswd'))));
$table->add(null, $input_newpasswd->show());
// show confirm password selection
$field_id = 'confpasswd';
$input_confpasswd = new html_passwordfield(array('name' => '_confpasswd', 'id' => $field_id,
'size' => 20, 'autocomplete' => 'off'));
- $table->add('title', html::label($field_id, Q($this->gettext('confpasswd'))));
+ $table->add('title', html::label($field_id, rcube::Q($this->gettext('confpasswd'))));
$table->add(null, $input_confpasswd->show());
$out = html::div(array('class' => 'box'),
html::div(array('id' => 'prefs-title', 'class' => 'boxtitle'), $this->gettext('changepasswd')) .
html::div(array('class' => 'boxcontent'), $table->show() .
html::p(null,
$rcmail->output->button(array(
'command' => 'plugin.password-save',
'type' => 'input',
'class' => 'button mainaction',
'label' => 'save'
)))));
$rcmail->output->add_gui_object('passform', 'password-form');
return $rcmail->output->form_tag(array(
'id' => 'password-form',
'name' => 'password-form',
'method' => 'post',
'action' => './?_task=settings&_action=plugin.password-save',
), $out);
}
private function _save($curpass, $passwd)
{
$config = rcmail::get_instance()->config;
$driver = $config->get('password_driver', 'sql');
$class = "rcube_{$driver}_password";
$file = $this->home . "/drivers/$driver.php";
if (!file_exists($file)) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Unable to open driver file ($file)"
), true, false);
return $this->gettext('internalerror');
}
include_once $file;
if (!class_exists($class, false) || !method_exists($class, 'save')) {
- raise_error(array(
+ rcube::raise_error(array(
'code' => 600,
'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Password plugin: Broken driver $driver"
), true, false);
return $this->gettext('internalerror');
}
$object = new $class;
$result = $object->save($curpass, $passwd);
if (is_array($result)) {
$message = $result['message'];
$result = $result['code'];
}
switch ($result) {
case PASSWORD_SUCCESS:
return;
case PASSWORD_CRYPT_ERROR;
$reason = $this->gettext('crypterror');
break;
case PASSWORD_CONNECT_ERROR;
$reason = $this->gettext('connecterror');
break;
case PASSWORD_ERROR:
default:
$reason = $this->gettext('internalerror');
}
if ($message) {
$reason .= ' ' . $message;
}
return $reason;
}
}
diff --git a/plugins/squirrelmail_usercopy/squirrelmail_usercopy.php b/plugins/squirrelmail_usercopy/squirrelmail_usercopy.php
index 7849f915e..d5d0d47ec 100644
--- a/plugins/squirrelmail_usercopy/squirrelmail_usercopy.php
+++ b/plugins/squirrelmail_usercopy/squirrelmail_usercopy.php
@@ -1,190 +1,190 @@
<?php
/**
* Copy a new users identity and settings from a nearby Squirrelmail installation
*
* @version 1.4
* @author Thomas Bruederli, Johannes Hessellund, pommi, Thomas Lueder
*/
class squirrelmail_usercopy extends rcube_plugin
{
public $task = 'login';
private $prefs = null;
private $identities_level = 0;
private $abook = array();
public function init()
{
$this->add_hook('user_create', array($this, 'create_user'));
$this->add_hook('identity_create', array($this, 'create_identity'));
}
public function create_user($p)
{
$rcmail = rcmail::get_instance();
// Read plugin's config
$this->initialize();
// read prefs and add email address
$this->read_squirrel_prefs($p['user']);
if (($this->identities_level == 0 || $this->identities_level == 2) && $rcmail->config->get('squirrelmail_set_alias') && $this->prefs['email_address'])
$p['user_email'] = $this->prefs['email_address'];
return $p;
}
public function create_identity($p)
{
$rcmail = rcmail::get_instance();
// prefs are set in create_user()
if ($this->prefs) {
if ($this->prefs['full_name'])
$p['record']['name'] = $this->prefs['full_name'];
if (($this->identities_level == 0 || $this->identities_level == 2) && $this->prefs['email_address'])
$p['record']['email'] = $this->prefs['email_address'];
if ($this->prefs['___signature___'])
$p['record']['signature'] = $this->prefs['___signature___'];
if ($this->prefs['reply_to'])
$p['record']['reply-to'] = $this->prefs['reply_to'];
if (($this->identities_level == 0 || $this->identities_level == 1) && isset($this->prefs['identities']) && $this->prefs['identities'] > 1) {
for ($i=1; $i < $this->prefs['identities']; $i++) {
unset($ident_data);
$ident_data = array('name' => '', 'email' => ''); // required data
if ($this->prefs['full_name'.$i])
$ident_data['name'] = $this->prefs['full_name'.$i];
if ($this->identities_level == 0 && $this->prefs['email_address'.$i])
$ident_data['email'] = $this->prefs['email_address'.$i];
else
$ident_data['email'] = $p['record']['email'];
if ($this->prefs['reply_to'.$i])
$ident_data['reply-to'] = $this->prefs['reply_to'.$i];
if ($this->prefs['___sig'.$i.'___'])
$ident_data['signature'] = $this->prefs['___sig'.$i.'___'];
// insert identity
$identid = $rcmail->user->insert_identity($ident_data);
}
}
// copy address book
$contacts = $rcmail->get_address_book(null, true);
if ($contacts && count($this->abook)) {
foreach ($this->abook as $rec) {
// #1487096 handle multi-address and/or too long items
$rec['email'] = array_shift(explode(';', $rec['email']));
- if (check_email(rcube_idn_to_ascii($rec['email']))) {
- $rec['email'] = rcube_idn_to_utf8($rec['email']);
+ if (rcube_utils::check_email(rcube_utils::idn_to_ascii($rec['email']))) {
+ $rec['email'] = rcube_utils::idn_to_utf8($rec['email']);
$contacts->insert($rec, true);
}
}
}
// mark identity as complete for following hooks
$p['complete'] = true;
}
return $p;
}
private function initialize()
{
$rcmail = rcmail::get_instance();
// Load plugin's config file
$this->load_config();
// Set identities_level for operations of this plugin
$ilevel = $rcmail->config->get('squirrelmail_identities_level');
if ($ilevel === null)
$ilevel = $rcmail->config->get('identities_level', 0);
$this->identities_level = intval($ilevel);
}
private function read_squirrel_prefs($uname)
{
$rcmail = rcmail::get_instance();
/**** File based backend ****/
if ($rcmail->config->get('squirrelmail_driver') == 'file' && ($srcdir = $rcmail->config->get('squirrelmail_data_dir'))) {
if (($hash_level = $rcmail->config->get('squirrelmail_data_dir_hash_level')) > 0)
$srcdir = slashify($srcdir).chunk_split(substr(base_convert(crc32($uname), 10, 16), 0, $hash_level), 1, '/');
$prefsfile = slashify($srcdir) . $uname . '.pref';
$abookfile = slashify($srcdir) . $uname . '.abook';
$sigfile = slashify($srcdir) . $uname . '.sig';
$sigbase = slashify($srcdir) . $uname . '.si';
if (is_readable($prefsfile)) {
$this->prefs = array();
foreach (file($prefsfile) as $line) {
list($key, $value) = explode('=', $line);
$this->prefs[$key] = utf8_encode(rtrim($value));
}
// also read signature file if exists
if (is_readable($sigfile)) {
$this->prefs['___signature___'] = utf8_encode(file_get_contents($sigfile));
}
if (isset($this->prefs['identities']) && $this->prefs['identities'] > 1) {
for ($i=1; $i < $this->prefs['identities']; $i++) {
// read signature file if exists
if (is_readable($sigbase.$i)) {
$this->prefs['___sig'.$i.'___'] = utf8_encode(file_get_contents($sigbase.$i));
}
}
}
// parse addres book file
if (filesize($abookfile)) {
foreach(file($abookfile) as $line) {
list($rec['name'], $rec['firstname'], $rec['surname'], $rec['email']) = explode('|', utf8_encode(rtrim($line)));
if ($rec['name'] && $rec['email'])
$this->abook[] = $rec;
}
}
}
}
/**** Database backend ****/
else if ($rcmail->config->get('squirrelmail_driver') == 'sql') {
$this->prefs = array();
/* connect to squirrelmail database */
$db = rcube_db::factory($rcmail->config->get('squirrelmail_dsn'));
$db->set_debug($rcmail->config->get('sql_debug'));
$db->db_connect('r'); // connect in read mode
/* retrieve prefs */
$userprefs_table = $rcmail->config->get('squirrelmail_userprefs_table');
$address_table = $rcmail->config->get('squirrelmail_address_table');
$db_charset = $rcmail->config->get('squirrelmail_db_charset');
if ($db_charset)
$db->query('SET NAMES '.$db_charset);
$sql_result = $db->query('SELECT * FROM '.$userprefs_table.' WHERE user=?', $uname); // ? is replaced with emailaddress
while ($sql_array = $db->fetch_assoc($sql_result) ) { // fetch one row from result
- $this->prefs[$sql_array['prefkey']] = rcube_charset_convert(rtrim($sql_array['prefval']), $db_charset);
+ $this->prefs[$sql_array['prefkey']] = rcube_charset::convert(rtrim($sql_array['prefval']), $db_charset);
}
/* retrieve address table data */
$sql_result = $db->query('SELECT * FROM '.$address_table.' WHERE owner=?', $uname); // ? is replaced with emailaddress
// parse addres book
while ($sql_array = $db->fetch_assoc($sql_result) ) { // fetch one row from result
- $rec['name'] = rcube_charset_convert(rtrim($sql_array['nickname']), $db_charset);
- $rec['firstname'] = rcube_charset_convert(rtrim($sql_array['firstname']), $db_charset);
- $rec['surname'] = rcube_charset_convert(rtrim($sql_array['lastname']), $db_charset);
- $rec['email'] = rcube_charset_convert(rtrim($sql_array['email']), $db_charset);
- $rec['notes'] = rcube_charset_convert(rtrim($sql_array['label']), $db_charset);
+ $rec['name'] = rcube_charset::convert(rtrim($sql_array['nickname']), $db_charset);
+ $rec['firstname'] = rcube_charset::convert(rtrim($sql_array['firstname']), $db_charset);
+ $rec['surname'] = rcube_charset::convert(rtrim($sql_array['lastname']), $db_charset);
+ $rec['email'] = rcube_charset::convert(rtrim($sql_array['email']), $db_charset);
+ $rec['notes'] = rcube_charset::convert(rtrim($sql_array['label']), $db_charset);
if ($rec['name'] && $rec['email'])
$this->abook[] = $rec;
}
} // end if 'sql'-driver
}
}
diff --git a/plugins/subscriptions_option/subscriptions_option.php b/plugins/subscriptions_option/subscriptions_option.php
index b81a5ac8a..7678d8e94 100644
--- a/plugins/subscriptions_option/subscriptions_option.php
+++ b/plugins/subscriptions_option/subscriptions_option.php
@@ -1,92 +1,92 @@
<?php
/**
* Subscription Options
*
* A plugin which can enable or disable the use of imap subscriptions.
* It includes a toggle on the settings page under "Server Settings".
* The preference can also be locked
*
* Add it to the plugins list in config/main.inc.php to enable the user option
* The user option can be hidden and set globally by adding 'use_subscriptions'
* to the 'dont_override' configure line:
* $rcmail_config['dont_override'] = array('use_subscriptions');
* and then set the global preference
* $rcmail_config['use_subscriptions'] = true; // or false
*
* Roundcube caches folder lists. When a user changes this option or visits
* their folder list, this cache is refreshed. If the option is on the
* 'dont_override' list and the global option has changed, don't expect
* to see the change until the folder list cache is refreshed.
*
* @version @package_version@
* @author Ziba Scott
*/
class subscriptions_option extends rcube_plugin
{
public $task = 'mail|settings';
function init()
{
$this->add_texts('localization/', false);
$dont_override = rcmail::get_instance()->config->get('dont_override', array());
if (!in_array('use_subscriptions', $dont_override)) {
$this->add_hook('preferences_list', array($this, 'settings_blocks'));
$this->add_hook('preferences_save', array($this, 'save_prefs'));
}
$this->add_hook('storage_folders', array($this, 'mailboxes_list'));
$this->add_hook('folders_list', array($this, 'folders_list'));
}
function settings_blocks($args)
{
if ($args['section'] == 'server') {
$use_subscriptions = rcmail::get_instance()->config->get('use_subscriptions');
$field_id = 'rcmfd_use_subscriptions';
$checkbox = new html_checkbox(array('name' => '_use_subscriptions', 'id' => $field_id, 'value' => 1));
$args['blocks']['main']['options']['use_subscriptions'] = array(
- 'title' => html::label($field_id, Q($this->gettext('useimapsubscriptions'))),
+ 'title' => html::label($field_id, rcube::Q($this->gettext('useimapsubscriptions'))),
'content' => $checkbox->show($use_subscriptions?1:0),
);
}
return $args;
}
function save_prefs($args)
{
if ($args['section'] == 'server') {
$rcmail = rcmail::get_instance();
$use_subscriptions = $rcmail->config->get('use_subscriptions');
$args['prefs']['use_subscriptions'] = isset($_POST['_use_subscriptions']) ? true : false;
// if the use_subscriptions preference changes, flush the folder cache
if (($use_subscriptions && !isset($_POST['_use_subscriptions'])) ||
(!$use_subscriptions && isset($_POST['_use_subscriptions']))) {
$storage = $rcmail->get_storage();
$storage->clear_cache('mailboxes');
}
}
return $args;
}
function mailboxes_list($args)
{
$rcmail = rcmail::get_instance();
if (!$rcmail->config->get('use_subscriptions', true)) {
$args['folders'] = $rcmail->get_storage()->list_folders_direct();
}
return $args;
}
function folders_list($args)
{
$rcmail = rcmail::get_instance();
if (!$rcmail->config->get('use_subscriptions', true)) {
$args['table']->remove_column('subscribed');
}
return $args;
}
}
diff --git a/plugins/userinfo/userinfo.php b/plugins/userinfo/userinfo.php
index efb65f51d..a175563ef 100644
--- a/plugins/userinfo/userinfo.php
+++ b/plugins/userinfo/userinfo.php
@@ -1,55 +1,55 @@
<?php
/**
* Sample plugin that adds a new tab to the settings section
* to display some information about the current user
*/
class userinfo extends rcube_plugin
{
public $task = 'settings';
public $noajax = true;
public $noframe = true;
function init()
{
$this->add_texts('localization/', array('userinfo'));
$this->register_action('plugin.userinfo', array($this, 'infostep'));
$this->include_script('userinfo.js');
}
function infostep()
{
$this->register_handler('plugin.body', array($this, 'infohtml'));
rcmail::get_instance()->output->send('plugin');
}
function infohtml()
{
$rcmail = rcmail::get_instance();
$user = $rcmail->user;
$table = new html_table(array('cols' => 2, 'cellpadding' => 3));
$table->add('title', 'ID');
- $table->add('', Q($user->ID));
+ $table->add('', rcube::Q($user->ID));
- $table->add('title', Q($this->gettext('username')));
- $table->add('', Q($user->data['username']));
+ $table->add('title', rcube::Q($this->gettext('username')));
+ $table->add('', rcube::Q($user->data['username']));
- $table->add('title', Q($this->gettext('server')));
- $table->add('', Q($user->data['mail_host']));
+ $table->add('title', rcube::Q($this->gettext('server')));
+ $table->add('', rcube::Q($user->data['mail_host']));
- $table->add('title', Q($this->gettext('created')));
- $table->add('', Q($user->data['created']));
+ $table->add('title', rcube::Q($this->gettext('created')));
+ $table->add('', rcube::Q($user->data['created']));
- $table->add('title', Q($this->gettext('lastlogin')));
- $table->add('', Q($user->data['last_login']));
+ $table->add('title', rcube::Q($this->gettext('lastlogin')));
+ $table->add('', rcube::Q($user->data['last_login']));
$identity = $user->get_identity();
- $table->add('title', Q($this->gettext('defaultidentity')));
- $table->add('', Q($identity['name'] . ' <' . $identity['email'] . '>'));
+ $table->add('title', rcube::Q($this->gettext('defaultidentity')));
+ $table->add('', rcube::Q($identity['name'] . ' <' . $identity['email'] . '>'));
- return html::tag('h4', null, Q('Infos for ' . $user->get_username())) . $table->show();
+ return html::tag('h4', null, rcube::Q('Infos for ' . $user->get_username())) . $table->show();
}
}
diff --git a/plugins/vcard_attachments/vcard_attachments.php b/plugins/vcard_attachments/vcard_attachments.php
index e7f7d5f1f..4905b373e 100644
--- a/plugins/vcard_attachments/vcard_attachments.php
+++ b/plugins/vcard_attachments/vcard_attachments.php
@@ -1,228 +1,228 @@
<?php
/**
* Detect VCard attachments and show a button to add them to address book
*
* @version @package_version@
* @license GNU GPLv3+
* @author Thomas Bruederli, Aleksander Machniak
*/
class vcard_attachments extends rcube_plugin
{
public $task = 'mail';
private $message;
private $vcard_parts = array();
private $vcard_bodies = array();
function init()
{
$rcmail = rcmail::get_instance();
if ($rcmail->action == 'show' || $rcmail->action == 'preview') {
$this->add_hook('message_load', array($this, 'message_load'));
$this->add_hook('template_object_messagebody', array($this, 'html_output'));
}
else if (!$rcmail->output->framed && (!$rcmail->action || $rcmail->action == 'list')) {
$icon = 'plugins/vcard_attachments/' .$this->local_skin_path(). '/vcard.png';
$rcmail->output->set_env('vcard_icon', $icon);
$this->include_script('vcardattach.js');
}
$this->register_action('plugin.savevcard', array($this, 'save_vcard'));
}
/**
* Check message bodies and attachments for vcards
*/
function message_load($p)
{
$this->message = $p['object'];
// handle attachments vcard attachments
foreach ((array)$this->message->attachments as $attachment) {
if ($this->is_vcard($attachment)) {
$this->vcard_parts[] = $attachment->mime_id;
}
}
// the same with message bodies
foreach ((array)$this->message->parts as $idx => $part) {
if ($this->is_vcard($part)) {
$this->vcard_parts[] = $part->mime_id;
$this->vcard_bodies[] = $part->mime_id;
}
}
if ($this->vcard_parts)
$this->add_texts('localization');
}
/**
* This callback function adds a box below the message content
* if there is a vcard attachment available
*/
function html_output($p)
{
$attach_script = false;
$icon = 'plugins/vcard_attachments/' .$this->local_skin_path(). '/vcard_add_contact.png';
foreach ($this->vcard_parts as $part) {
$vcards = rcube_vcard::import($this->message->get_part_content($part, null, true));
// successfully parsed vcards?
if (empty($vcards)) {
continue;
}
// remove part's body
if (in_array($part, $this->vcard_bodies)) {
$p['content'] = '';
}
foreach ($vcards as $idx => $vcard) {
// skip invalid vCards
if (empty($vcard->email) || empty($vcard->email[0])) {
continue;
}
$display = $vcard->displayname . ' <'.$vcard->email[0].'>';
// add box below message body
$p['content'] .= html::p(array('class' => 'vcardattachment'),
html::a(array(
'href' => "#",
- 'onclick' => "return plugin_vcard_save_contact('" . JQ($part.':'.$idx) . "')",
+ 'onclick' => "return plugin_vcard_save_contact('" . rcube::JQ($part.':'.$idx) . "')",
'title' => $this->gettext('addvcardmsg'),
),
- html::span(null, Q($display)))
+ html::span(null, rcube::Q($display)))
);
}
$attach_script = true;
}
if ($attach_script) {
$this->include_script('vcardattach.js');
$this->include_stylesheet($this->local_skin_path() . '/style.css');
}
return $p;
}
/**
* Handler for request action
*/
function save_vcard()
{
$this->add_texts('localization', true);
- $uid = get_input_value('_uid', RCUBE_INPUT_POST);
- $mbox = get_input_value('_mbox', RCUBE_INPUT_POST);
- $mime_id = get_input_value('_part', RCUBE_INPUT_POST);
+ $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_POST);
+ $mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_POST);
+ $mime_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_POST);
$rcmail = rcmail::get_instance();
$storage = $rcmail->get_storage();
$storage->set_folder($mbox);
if ($uid && $mime_id) {
list($mime_id, $index) = explode(':', $mime_id);
$part = $storage->get_message_part($uid, $mime_id, null, null, null, true);
}
$error_msg = $this->gettext('vcardsavefailed');
if ($part && ($vcards = rcube_vcard::import($part))
&& ($vcard = $vcards[$index]) && $vcard->displayname && $vcard->email
) {
$CONTACTS = $this->get_address_book();
$email = $vcard->email[0];
$contact = $vcard->get_assoc();
$valid = true;
// skip entries without an e-mail address or invalid
if (empty($email) || !$CONTACTS->validate($contact, true)) {
$valid = false;
}
else {
// We're using UTF8 internally
- $email = rcube_idn_to_utf8($email);
+ $email = rcube_utils::idn_to_utf8($email);
// compare e-mail address
$existing = $CONTACTS->search('email', $email, 1, false);
// compare display name
if (!$existing->count && $vcard->displayname) {
$existing = $CONTACTS->search('name', $vcard->displayname, 1, false);
}
if ($existing->count) {
$rcmail->output->command('display_message', $this->gettext('contactexists'), 'warning');
$valid = false;
}
}
if ($valid) {
$plugin = $rcmail->plugins->exec_hook('contact_create', array('record' => $contact, 'source' => null));
$contact = $plugin['record'];
if (!$plugin['abort'] && $CONTACTS->insert($contact))
$rcmail->output->command('display_message', $this->gettext('addedsuccessfully'), 'confirmation');
else
$rcmail->output->command('display_message', $error_msg, 'error');
}
}
else {
$rcmail->output->command('display_message', $error_msg, 'error');
}
$rcmail->output->send();
}
/**
* Checks if specified message part is a vcard data
*
* @param rcube_message_part Part object
*
* @return boolean True if part is of type vcard
*/
function is_vcard($part)
{
return (
// Content-Type: text/vcard;
$part->mimetype == 'text/vcard' ||
// Content-Type: text/x-vcard;
$part->mimetype == 'text/x-vcard' ||
// Content-Type: text/directory; profile=vCard;
($part->mimetype == 'text/directory' && (
($part->ctype_parameters['profile'] &&
strtolower($part->ctype_parameters['profile']) == 'vcard')
// Content-Type: text/directory; (with filename=*.vcf)
|| ($part->filename && preg_match('/\.vcf$/i', $part->filename))
)
)
);
}
/**
* Getter for default (writable) addressbook
*/
private function get_address_book()
{
if ($this->abook) {
return $this->abook;
}
$rcmail = rcmail::get_instance();
$abook = $rcmail->config->get('default_addressbook');
// Get configured addressbook
$CONTACTS = $rcmail->get_address_book($abook, true);
// Get first writeable addressbook if the configured doesn't exist
// This can happen when user deleted the addressbook (e.g. Kolab folder)
if ($abook === null || $abook === '' || !is_object($CONTACTS)) {
$source = reset($rcmail->get_address_sources(true));
$CONTACTS = $rcmail->get_address_book($source['id'], true);
}
return $this->abook = $CONTACTS;
}
}
diff --git a/plugins/virtuser_file/virtuser_file.php b/plugins/virtuser_file/virtuser_file.php
index 01032616c..2c705b2d0 100644
--- a/plugins/virtuser_file/virtuser_file.php
+++ b/plugins/virtuser_file/virtuser_file.php
@@ -1,107 +1,107 @@
<?php
/**
* File based User-to-Email and Email-to-User lookup
*
* Add it to the plugins list in config/main.inc.php and set
* path to a virtuser table file to resolve user names and e-mail
* addresses
* $rcmail_config['virtuser_file'] = '';
*
* @version @package_version@
* @license GNU GPLv3+
* @author Aleksander Machniak
*/
class virtuser_file extends rcube_plugin
{
private $file;
private $app;
function init()
{
$this->app = rcmail::get_instance();
$this->file = $this->app->config->get('virtuser_file');
if ($this->file) {
$this->add_hook('user2email', array($this, 'user2email'));
$this->add_hook('email2user', array($this, 'email2user'));
}
}
/**
* User > Email
*/
function user2email($p)
{
$r = $this->findinvirtual('/\s' . preg_quote($p['user'], '/') . '\s*$/');
$result = array();
for ($i=0; $i<count($r); $i++)
{
$arr = preg_split('/\s+/', $r[$i]);
if (count($arr) > 0 && strpos($arr[0], '@')) {
- $result[] = rcube_idn_to_ascii(trim(str_replace('\\@', '@', $arr[0])));
+ $result[] = rcube_utils::idn_to_ascii(trim(str_replace('\\@', '@', $arr[0])));
if ($p['first']) {
$p['email'] = $result[0];
break;
}
}
}
$p['email'] = empty($result) ? NULL : $result;
return $p;
}
/**
* Email > User
*/
function email2user($p)
{
$r = $this->findinvirtual('/^' . preg_quote($p['email'], '/') . '\s/');
for ($i=0; $i<count($r); $i++) {
$arr = preg_split('/\s+/', trim($r[$i]));
if (count($arr) > 0) {
$p['user'] = trim($arr[count($arr)-1]);
break;
}
}
return $p;
}
/**
* Find matches of the given pattern in virtuser file
*
* @param string Regular expression to search for
* @return array Matching entries
*/
private function findinvirtual($pattern)
{
$result = array();
$virtual = null;
if ($this->file)
$virtual = file($this->file);
if (empty($virtual))
return $result;
// check each line for matches
foreach ($virtual as $line) {
$line = trim($line);
if (empty($line) || $line[0]=='#')
continue;
if (preg_match($pattern, $line))
$result[] = $line;
}
return $result;
}
}
diff --git a/plugins/virtuser_query/virtuser_query.php b/plugins/virtuser_query/virtuser_query.php
index 073b4e230..c479a4f7f 100644
--- a/plugins/virtuser_query/virtuser_query.php
+++ b/plugins/virtuser_query/virtuser_query.php
@@ -1,120 +1,120 @@
<?php
/**
* DB based User-to-Email and Email-to-User lookup
*
* Add it to the plugins list in config/main.inc.php and set
* SQL queries to resolve usernames, e-mail addresses and hostnames from the database
* %u will be replaced with the current username for login.
* %m will be replaced with the current e-mail address for login.
*
* Queries should select the user's e-mail address, username or the imap hostname as first column
* The email query could optionally select identity data columns in specified order:
* name, organization, reply-to, bcc, signature, html_signature
*
* $rcmail_config['virtuser_query'] = array('email' => '', 'user' => '', 'host' => '');
*
* The email query can return more than one record to create more identities.
* This requires identities_level option to be set to value less than 2.
*
* @version @package_version@
* @author Aleksander Machniak <alec@alec.pl>
* @author Steffen Vogel
*/
class virtuser_query extends rcube_plugin
{
private $config;
private $app;
function init()
{
- $this->app = rcmail::get_instance();
- $this->config = $this->app->config->get('virtuser_query');
+ $this->app = rcmail::get_instance();
+ $this->config = $this->app->config->get('virtuser_query');
if (!empty($this->config)) {
if (is_string($this->config)) {
$this->config = array('email' => $this->config);
}
if ($this->config['email']) {
$this->add_hook('user2email', array($this, 'user2email'));
}
if ($this->config['user']) {
$this->add_hook('email2user', array($this, 'email2user'));
}
if ($this->config['host']) {
$this->add_hook('authenticate', array($this, 'user2host'));
}
}
}
/**
* User > Email
*/
function user2email($p)
{
- $dbh = $this->app->get_dbh();
-
- $sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($p['user']), $this->config['email']));
-
- while ($sql_arr = $dbh->fetch_array($sql_result)) {
- if (strpos($sql_arr[0], '@')) {
- if ($p['extended'] && count($sql_arr) > 1) {
- $result[] = array(
- 'email' => rcube_idn_to_ascii($sql_arr[0]),
- 'name' => $sql_arr[1],
- 'organization' => $sql_arr[2],
- 'reply-to' => rcube_idn_to_ascii($sql_arr[3]),
- 'bcc' => rcube_idn_to_ascii($sql_arr[4]),
- 'signature' => $sql_arr[5],
- 'html_signature' => (int)$sql_arr[6],
- );
- }
- else {
- $result[] = $sql_arr[0];
- }
-
- if ($p['first'])
- break;
- }
- }
-
- $p['email'] = $result;
-
- return $p;
+ $dbh = $this->app->get_dbh();
+
+ $sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($p['user']), $this->config['email']));
+
+ while ($sql_arr = $dbh->fetch_array($sql_result)) {
+ if (strpos($sql_arr[0], '@')) {
+ if ($p['extended'] && count($sql_arr) > 1) {
+ $result[] = array(
+ 'email' => rcube_utils::idn_to_ascii($sql_arr[0]),
+ 'name' => $sql_arr[1],
+ 'organization' => $sql_arr[2],
+ 'reply-to' => rcube_utils::idn_to_ascii($sql_arr[3]),
+ 'bcc' => rcube_utils::idn_to_ascii($sql_arr[4]),
+ 'signature' => $sql_arr[5],
+ 'html_signature' => (int)$sql_arr[6],
+ );
+ }
+ else {
+ $result[] = $sql_arr[0];
+ }
+
+ if ($p['first'])
+ break;
+ }
+ }
+
+ $p['email'] = $result;
+
+ return $p;
}
/**
* EMail > User
*/
function email2user($p)
{
$dbh = $this->app->get_dbh();
$sql_result = $dbh->query(preg_replace('/%m/', $dbh->escapeSimple($p['email']), $this->config['user']));
if ($sql_arr = $dbh->fetch_array($sql_result)) {
$p['user'] = $sql_arr[0];
}
return $p;
}
/**
* User > Host
*/
function user2host($p)
{
$dbh = $this->app->get_dbh();
$sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($p['user']), $this->config['host']));
if ($sql_arr = $dbh->fetch_array($sql_result)) {
$p['host'] = $sql_arr[0];
}
return $p;
}
}
diff --git a/plugins/zipdownload/zipdownload.php b/plugins/zipdownload/zipdownload.php
index 8bad9b341..96c76eec9 100644
--- a/plugins/zipdownload/zipdownload.php
+++ b/plugins/zipdownload/zipdownload.php
@@ -1,267 +1,272 @@
<?php
/**
* ZipDownload
*
* Plugin to allow the download of all message attachments in one zip file
*
* @version @package_version@
* @requires php_zip extension (including ZipArchive class)
* @author Philip Weir
* @author Thomas Bruderli
*/
class zipdownload extends rcube_plugin
{
public $task = 'mail';
private $charset = 'ASCII';
/**
* Plugin initialization
*/
public function init()
{
// check requirements first
if (!class_exists('ZipArchive', false)) {
rcmail::raise_error(array(
'code' => 520, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "php_zip extension is required for the zipdownload plugin"), true, false);
return;
}
$rcmail = rcmail::get_instance();
- $this->charset = $rcmail->config->get('zipdownload_charset', RCMAIL_CHARSET);
+ $this->charset = $rcmail->config->get('zipdownload_charset', RCUBE_CHARSET);
$this->load_config();
$this->add_texts('localization');
if ($rcmail->config->get('zipdownload_attachments', 1) > -1 && ($rcmail->action == 'show' || $rcmail->action == 'preview'))
$this->add_hook('template_object_messageattachments', array($this, 'attachment_ziplink'));
$this->register_action('plugin.zipdownload.zip_attachments', array($this, 'download_attachments'));
$this->register_action('plugin.zipdownload.zip_messages', array($this, 'download_selection'));
$this->register_action('plugin.zipdownload.zip_folder', array($this, 'download_folder'));
if ($rcmail->config->get('zipdownload_folder', false) || $rcmail->config->get('zipdownload_selection', false)) {
$this->include_script('zipdownload.js');
$this->api->output->set_env('zipdownload_selection', $rcmail->config->get('zipdownload_selection', false));
if ($rcmail->config->get('zipdownload_folder', false) && ($rcmail->action == '' || $rcmail->action == 'show')) {
$zipdownload = $this->api->output->button(array('command' => 'plugin.zipdownload.zip_folder', 'type' => 'link', 'classact' => 'active', 'content' => $this->gettext('downloadfolder')));
$this->api->add_content(html::tag('li', array('class' => 'separator_above'), $zipdownload), 'mailboxoptions');
}
}
}
/**
* Place a link/button after attachments listing to trigger download
*/
public function attachment_ziplink($p)
{
$rcmail = rcmail::get_instance();
// only show the link if there is more than the configured number of attachments
if (substr_count($p['content'], '<li') > $rcmail->config->get('zipdownload_attachments', 1)) {
- $link = html::a(array(
- 'href' => rcmail_url('plugin.zipdownload.zip_attachments', array('_mbox' => $rcmail->output->env['mailbox'], '_uid' => $rcmail->output->env['uid'])),
- 'class' => 'button zipdownload',
- ),
- Q($this->gettext('downloadall'))
+ $href = $rcmail->url(array(
+ '_action' => 'plugin.zipdownload.zip_attachments',
+ '_mbox' => $rcmail->output->env['mailbox'],
+ '_uid' => $rcmail->output->env['uid'],
+ ));
+
+ $link = html::a(array('href' => $href, 'class' => 'button zipdownload'),
+ rcube::Q($this->gettext('downloadall'))
);
// append link to attachments list, slightly different in some skins
switch (rcmail::get_instance()->config->get('skin')) {
case 'classic':
$p['content'] = str_replace('</ul>', html::tag('li', array('class' => 'zipdownload'), $link) . '</ul>', $p['content']);
break;
default:
$p['content'] .= $link;
break;
}
$this->include_stylesheet($this->local_skin_path() . '/zipdownload.css');
}
return $p;
}
/**
* Handler for attachment download action
*/
public function download_attachments()
{
$rcmail = rcmail::get_instance();
$imap = $rcmail->storage;
$temp_dir = $rcmail->config->get('temp_dir');
$tmpfname = tempnam($temp_dir, 'zipdownload');
$tempfiles = array($tmpfname);
- $message = new rcube_message(get_input_value('_uid', RCUBE_INPUT_GET));
+ $message = new rcube_message(rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET));
// open zip file
$zip = new ZipArchive();
$zip->open($tmpfname, ZIPARCHIVE::OVERWRITE);
foreach ($message->attachments as $part) {
$pid = $part->mime_id;
$part = $message->mime_parts[$pid];
$disp_name = $this->_convert_filename($part->filename, $part->charset);
if ($part->body) {
$orig_message_raw = $part->body;
$zip->addFromString($disp_name, $orig_message_raw);
}
else {
$tmpfn = tempnam($temp_dir, 'zipattach');
$tmpfp = fopen($tmpfn, 'w');
$imap->get_message_part($message->uid, $part->mime_id, $part, null, $tmpfp, true);
$tempfiles[] = $tmpfn;
fclose($tmpfp);
$zip->addFile($tmpfn, $disp_name);
}
}
$zip->close();
$filename = ($message->subject ? $message->subject : 'roundcube') . '.zip';
$this->_deliver_zipfile($tmpfname, $filename);
// delete temporary files from disk
foreach ($tempfiles as $tmpfn)
unlink($tmpfn);
exit;
}
/**
* Handler for message download action
*/
public function download_selection()
{
if (isset($_REQUEST['_uid'])) {
- $uids = explode(",", get_input_value('_uid', RCUBE_INPUT_GPC));
+ $uids = explode(",", rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GPC));
if (sizeof($uids) > 0)
$this->_download_messages($uids);
}
}
/**
* Handler for folder download action
*/
public function download_folder()
{
$imap = rcmail::get_instance()->storage;
$mbox_name = $imap->get_folder();
// initialize searching result if search_filter is used
if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL') {
- $imap->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET);
+ $imap->search($mbox_name, $_SESSION['search_filter'], RCUBE_CHARSET);
}
// fetch message headers for all pages
$uids = array();
if ($count = $imap->count($mbox_name, $imap->get_threading() ? 'THREADS' : 'ALL', FALSE)) {
for ($i = 0; ($i * $imap->get_pagesize()) <= $count; $i++) {
$a_headers = $imap->list_messages($mbox_name, ($i + 1));
foreach ($a_headers as $n => $header) {
if (empty($header))
continue;
array_push($uids, $header->uid);
}
}
}
if (sizeof($uids) > 0)
$this->_download_messages($uids);
}
/**
* Helper method to packs all the given messages into a zip archive
*
* @param array List of message UIDs to download
*/
private function _download_messages($uids)
{
$rcmail = rcmail::get_instance();
$imap = $rcmail->storage;
$temp_dir = $rcmail->config->get('temp_dir');
$tmpfname = tempnam($temp_dir, 'zipdownload');
$tempfiles = array($tmpfname);
// open zip file
$zip = new ZipArchive();
$zip->open($tmpfname, ZIPARCHIVE::OVERWRITE);
foreach ($uids as $key => $uid){
$headers = $imap->get_message_headers($uid);
$subject = rcube_mime::decode_mime_string((string)$headers->subject);
$subject = $this->_convert_filename($subject);
$subject = substr($subject, 0, 16);
if (isset($subject) && $subject !="")
$disp_name = $subject . ".eml";
else
$disp_name = "message_rfc822.eml";
$disp_name = $uid . "_" . $disp_name;
$tmpfn = tempnam($temp_dir, 'zipmessage');
$tmpfp = fopen($tmpfn, 'w');
$imap->get_raw_body($uid, $tmpfp);
$tempfiles[] = $tmpfn;
fclose($tmpfp);
$zip->addFile($tmpfn, $disp_name);
}
$zip->close();
$this->_deliver_zipfile($tmpfname, $imap->get_folder() . '.zip');
// delete temporary files from disk
foreach ($tempfiles as $tmpfn)
unlink($tmpfn);
exit;
}
/**
* Helper method to send the zip archive to the browser
*/
private function _deliver_zipfile($tmpfname, $filename)
{
$browser = new rcube_browser;
- send_nocacheing_headers();
+ $rcmail = rcmail::get_instance();
+
+ $rcmail->output->nocacheing_headers();
if ($browser->ie && $browser->ver < 7)
$filename = rawurlencode(abbreviate_string($filename, 55));
else if ($browser->ie)
$filename = rawurlencode($filename);
else
$filename = addcslashes($filename, '"');
// send download headers
header("Content-Type: application/octet-stream");
if ($browser->ie)
header("Content-Type: application/force-download");
// don't kill the connection if download takes more than 30 sec.
@set_time_limit(0);
header("Content-Disposition: attachment; filename=\"". $filename ."\"");
header("Content-length: " . filesize($tmpfname));
readfile($tmpfname);
}
/**
* Helper function to convert filenames to the configured charset
*/
- private function _convert_filename($str, $from = RCMAIL_CHARSET)
+ private function _convert_filename($str, $from = RCUBE_CHARSET)
{
- return strtr(rcube_charset_convert($str, $from, $this->charset), array(':'=>'', '/'=>'-'));
+ return strtr(rcube_charset::convert($str, $from, $this->charset), array(':'=>'', '/'=>'-'));
}
}
?>
\ No newline at end of file
diff --git a/program/include/rcmail.php b/program/include/rcmail.php
index c734216ac..5f2a2177b 100644
--- a/program/include/rcmail.php
+++ b/program/include/rcmail.php
@@ -1,2131 +1,2131 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/rcmail.php |
| |
| This file is part of the Roundcube Webmail client |
| Copyright (C) 2008-2012, The Roundcube Dev Team |
| Copyright (C) 2011-2012, Kolab Systems AG |
| |
| Licensed under the GNU General Public License version 3 or |
| any later version with exceptions for skins & plugins. |
| See the README file for a full license statement. |
| |
| PURPOSE: |
| Application class providing core functions and holding |
| instances of all 'global' objects like db- and imap-connections |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
| Author: Aleksander Machniak <alec@alec.pl> |
+-----------------------------------------------------------------------+
*/
/**
* Application class of Roundcube Webmail
* implemented as singleton
*
* @package Core
*/
class rcmail extends rcube
{
/**
* Main tasks.
*
* @var array
*/
static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
/**
* Current task.
*
* @var string
*/
public $task;
/**
* Current action.
*
* @var string
*/
public $action = '';
public $comm_path = './';
private $address_books = array();
private $action_map = array();
const ERROR_STORAGE = -2;
const ERROR_INVALID_REQUEST = 1;
const ERROR_INVALID_HOST = 2;
const ERROR_COOKIES_DISABLED = 3;
/**
* This implements the 'singleton' design pattern
*
* @return rcmail The one and only instance
*/
static function get_instance()
{
if (!self::$instance || !is_a(self::$instance, 'rcmail')) {
self::$instance = new rcmail();
self::$instance->startup(); // init AFTER object was linked with self::$instance
}
return self::$instance;
}
/**
* Initial startup function
* to register session, create database and imap connections
*/
protected function startup()
{
$this->init(self::INIT_WITH_DB | self::INIT_WITH_PLUGINS);
// start session
$this->session_init();
// create user object
$this->set_user(new rcube_user($_SESSION['user_id']));
// set task and action properties
$this->set_task(rcube_utils::get_input_value('_task', rcube_utils::INPUT_GPC));
$this->action = asciiwords(rcube_utils::get_input_value('_action', rcube_utils::INPUT_GPC));
// reset some session parameters when changing task
if ($this->task != 'utils') {
if ($this->session && $_SESSION['task'] != $this->task)
$this->session->remove('page');
// set current task to session
$_SESSION['task'] = $this->task;
}
// init output class
if (!empty($_REQUEST['_remote']))
$GLOBALS['OUTPUT'] = $this->json_init();
else
$GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
// load plugins
$this->plugins->init($this, $this->task);
$this->plugins->load_plugins((array)$this->config->get('plugins', array()), array('filesystem_attachments', 'jqueryui'));
}
/**
* Setter for application task
*
* @param string Task to set
*/
public function set_task($task)
{
$task = asciiwords($task);
if ($this->user && $this->user->ID)
$task = !$task ? 'mail' : $task;
else
$task = 'login';
$this->task = $task;
$this->comm_path = $this->url(array('task' => $this->task));
if ($this->output)
$this->output->set_env('task', $this->task);
}
/**
* Setter for system user object
*
* @param rcube_user Current user instance
*/
public function set_user($user)
{
if (is_object($user)) {
$this->user = $user;
// overwrite config with user preferences
$this->config->set_user_prefs((array)$this->user->get_prefs());
}
$lang = $this->language_prop($this->config->get('language', $_SESSION['language']));
$_SESSION['language'] = $this->user->language = $lang;
// set localization
setlocale(LC_ALL, $lang . '.utf8', $lang . '.UTF-8', 'en_US.utf8', 'en_US.UTF-8');
// workaround for http://bugs.php.net/bug.php?id=18556
if (in_array($lang, array('tr_TR', 'ku', 'az_AZ'))) {
setlocale(LC_CTYPE, 'en_US.utf8', 'en_US.UTF-8');
}
}
/**
* Return instance of the internal address book class
*
* @param string Address book identifier (-1 for default addressbook)
* @param boolean True if the address book needs to be writeable
*
* @return rcube_contacts Address book object
*/
public function get_address_book($id, $writeable = false)
{
$contacts = null;
$ldap_config = (array)$this->config->get('ldap_public');
// 'sql' is the alias for '0' used by autocomplete
if ($id == 'sql')
$id = '0';
else if ($id == -1) {
$id = $this->config->get('default_addressbook');
$default = true;
}
// use existing instance
if (isset($this->address_books[$id]) && ($this->address_books[$id] instanceof rcube_addressbook)) {
$contacts = $this->address_books[$id];
}
else if ($id && $ldap_config[$id]) {
$contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['storage_host']));
}
else if ($id === '0') {
$contacts = new rcube_contacts($this->db, $this->get_user_id());
}
else {
$plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
// plugin returned instance of a rcube_addressbook
if ($plugin['instance'] instanceof rcube_addressbook) {
$contacts = $plugin['instance'];
}
}
// when user requested default writeable addressbook
// we need to check if default is writeable, if not we
// will return first writeable book (if any exist)
if ($contacts && $default && $contacts->readonly && $writeable) {
$contacts = null;
}
// Get first addressbook from the list if configured default doesn't exist
// This can happen when user deleted the addressbook (e.g. Kolab folder)
if (!$contacts && (!$id || $default)) {
$source = reset($this->get_address_sources($writeable, !$default));
if (!empty($source)) {
$contacts = $this->get_address_book($source['id']);
if ($contacts) {
$id = $source['id'];
}
}
}
if (!$contacts) {
self::raise_error(array(
'code' => 700, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Addressbook source ($id) not found!"),
true, true);
}
// add to the 'books' array for shutdown function
$this->address_books[$id] = $contacts;
if ($writeable && $contacts->readonly) {
return null;
}
// set configured sort order
if ($sort_col = $this->config->get('addressbook_sort_col')) {
$contacts->set_sort_order($sort_col);
}
return $contacts;
}
/**
* Return address books list
*
* @param boolean True if the address book needs to be writeable
* @param boolean True if the address book needs to be not hidden
*
* @return array Address books array
*/
public function get_address_sources($writeable = false, $skip_hidden = false)
{
$abook_type = strtolower($this->config->get('address_book_type'));
$ldap_config = $this->config->get('ldap_public');
$autocomplete = (array) $this->config->get('autocomplete_addressbooks');
$list = array();
// We are using the DB address book or a plugin address book
if ($abook_type != 'ldap' && $abook_type != '') {
if (!isset($this->address_books['0']))
$this->address_books['0'] = new rcube_contacts($this->db, $this->get_user_id());
$list['0'] = array(
'id' => '0',
'name' => $this->gettext('personaladrbook'),
'groups' => $this->address_books['0']->groups,
'readonly' => $this->address_books['0']->readonly,
'autocomplete' => in_array('sql', $autocomplete),
'undelete' => $this->address_books['0']->undelete && $this->config->get('undo_timeout'),
);
}
if ($ldap_config) {
$ldap_config = (array) $ldap_config;
foreach ($ldap_config as $id => $prop) {
// handle misconfiguration
if (empty($prop) || !is_array($prop)) {
continue;
}
$list[$id] = array(
'id' => $id,
'name' => html::quote($prop['name']),
'groups' => is_array($prop['groups']),
'readonly' => !$prop['writable'],
'hidden' => $prop['hidden'],
'autocomplete' => in_array($id, $autocomplete)
);
}
}
$plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
$list = $plugin['sources'];
foreach ($list as $idx => $item) {
// register source for shutdown function
if (!is_object($this->address_books[$item['id']])) {
$this->address_books[$item['id']] = $item;
}
// remove from list if not writeable as requested
if ($writeable && $item['readonly']) {
unset($list[$idx]);
}
// remove from list if hidden as requested
else if ($skip_hidden && $item['hidden']) {
unset($list[$idx]);
}
}
return $list;
}
/**
* Init output object for GUI and add common scripts.
* This will instantiate a rcmail_output_html object and set
* environment vars according to the current session and configuration
*
* @param boolean True if this request is loaded in a (i)frame
* @return rcube_output Reference to HTML output object
*/
public function load_gui($framed = false)
{
// init output page
if (!($this->output instanceof rcmail_output_html))
$this->output = new rcmail_output_html($this->task, $framed);
// set refresh interval
$this->output->set_env('refresh_interval', $this->config->get('refresh_interval', 0));
$this->output->set_env('session_lifetime', $this->config->get('session_lifetime', 0) * 60);
if ($framed) {
$this->comm_path .= '&_framed=1';
$this->output->set_env('framed', true);
}
$this->output->set_env('task', $this->task);
$this->output->set_env('action', $this->action);
$this->output->set_env('comm_path', $this->comm_path);
$this->output->set_charset(RCUBE_CHARSET);
// add some basic labels to client
$this->output->add_label('loading', 'servererror', 'requesttimedout', 'refreshing');
return $this->output;
}
/**
* Create an output object for JSON responses
*
* @return rcube_output Reference to JSON output object
*/
public function json_init()
{
if (!($this->output instanceof rcmail_output_json))
$this->output = new rcmail_output_json($this->task);
return $this->output;
}
/**
* Create session object and start the session.
*/
public function session_init()
{
parent::session_init();
// set initial session vars
if (!$_SESSION['user_id'])
$_SESSION['temp'] = true;
// restore skin selection after logout
if ($_SESSION['temp'] && !empty($_SESSION['skin']))
$this->config->set('skin', $_SESSION['skin']);
}
/**
* Perfom login to the mail server and to the webmail service.
* This will also create a new user entry if auto_create_user is configured.
*
* @param string Mail storage (IMAP) user name
* @param string Mail storage (IMAP) password
* @param string Mail storage (IMAP) host
* @param bool Enables cookie check
*
* @return boolean True on success, False on failure
*/
function login($username, $pass, $host = null, $cookiecheck = false)
{
$this->login_error = null;
if (empty($username)) {
return false;
}
if ($cookiecheck && empty($_COOKIE)) {
$this->login_error = self::ERROR_COOKIES_DISABLED;
return false;
}
$config = $this->config->all();
if (!$host)
$host = $config['default_host'];
// Validate that selected host is in the list of configured hosts
if (is_array($config['default_host'])) {
$allowed = false;
foreach ($config['default_host'] as $key => $host_allowed) {
if (!is_numeric($key))
$host_allowed = $key;
if ($host == $host_allowed) {
$allowed = true;
break;
}
}
if (!$allowed) {
$host = null;
}
}
else if (!empty($config['default_host']) && $host != rcube_utils::parse_host($config['default_host'])) {
$host = null;
}
if (!$host) {
$this->login_error = self::ERROR_INVALID_HOST;
return false;
}
// parse $host URL
$a_host = parse_url($host);
if ($a_host['host']) {
$host = $a_host['host'];
$ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
if (!empty($a_host['port']))
$port = $a_host['port'];
else if ($ssl && $ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
$port = 993;
}
if (!$port) {
$port = $config['default_port'];
}
/* Modify username with domain if required
Inspired by Marco <P0L0_notspam_binware.org>
*/
// Check if we need to add domain
if (!empty($config['username_domain']) && strpos($username, '@') === false) {
if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
$username .= '@'.rcube_utils::parse_host($config['username_domain'][$host], $host);
else if (is_string($config['username_domain']))
$username .= '@'.rcube_utils::parse_host($config['username_domain'], $host);
}
if (!isset($config['login_lc'])) {
$config['login_lc'] = 2; // default
}
// Convert username to lowercase. If storage backend
// is case-insensitive we need to store always the same username (#1487113)
if ($config['login_lc']) {
if ($config['login_lc'] == 2 || $config['login_lc'] === true) {
$username = mb_strtolower($username);
}
else if (strpos($username, '@')) {
// lowercase domain name
list($local, $domain) = explode('@', $username);
$username = $local . '@' . mb_strtolower($domain);
}
}
// try to resolve email address from virtuser table
if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
$username = $virtuser;
}
// Here we need IDNA ASCII
// Only rcube_contacts class is using domain names in Unicode
$host = rcube_utils::idn_to_ascii($host);
$username = rcube_utils::idn_to_ascii($username);
// user already registered -> overwrite username
if ($user = rcube_user::query($username, $host)) {
$username = $user->data['username'];
}
$storage = $this->get_storage();
// try to log in
if (!$storage->connect($host, $username, $pass, $port, $ssl)) {
return false;
}
// user already registered -> update user's record
if (is_object($user)) {
// update last login timestamp
$user->touch();
}
// create new system user
else if ($config['auto_create_user']) {
if ($created = rcube_user::create($username, $host)) {
$user = $created;
}
else {
self::raise_error(array(
'code' => 620, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Failed to create a user record. Maybe aborted by a plugin?"
), true, false);
}
}
else {
self::raise_error(array(
'code' => 621, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Access denied for new user $username. 'auto_create_user' is disabled"
), true, false);
}
// login succeeded
if (is_object($user) && $user->ID) {
// Configure environment
$this->set_user($user);
$this->set_storage_prop();
// fix some old settings according to namespace prefix
$this->fix_namespace_settings($user);
// create default folders on first login
if ($config['create_default_folders'] && (!empty($created) || empty($user->data['last_login']))) {
$storage->create_default_folders();
}
// set session vars
$_SESSION['user_id'] = $user->ID;
$_SESSION['username'] = $user->data['username'];
$_SESSION['storage_host'] = $host;
$_SESSION['storage_port'] = $port;
$_SESSION['storage_ssl'] = $ssl;
$_SESSION['password'] = $this->encrypt($pass);
$_SESSION['login_time'] = time();
if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
$_SESSION['timezone'] = rcube_utils::get_input_value('_timezone', rcube_utils::INPUT_GPC);
// force reloading complete list of subscribed mailboxes
$storage->clear_cache('mailboxes', true);
return true;
}
return false;
}
/**
* Returns error code of last login operation
*
* @return int Error code
*/
public function login_error()
{
if ($this->login_error) {
return $this->login_error;
}
if ($this->storage && $this->storage->get_error_code() < -1) {
return self::ERROR_STORAGE;
}
}
/**
* Auto-select IMAP host based on the posted login information
*
* @return string Selected IMAP host
*/
public function autoselect_host()
{
$default_host = $this->config->get('default_host');
$host = null;
if (is_array($default_host)) {
$post_host = rcube_utils::get_input_value('_host', rcube_utils::INPUT_POST);
$post_user = rcube_utils::get_input_value('_user', rcube_utils::INPUT_POST);
list($user, $domain) = explode('@', $post_user);
// direct match in default_host array
if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
$host = $post_host;
}
// try to select host by mail domain
else if (!empty($domain)) {
foreach ($default_host as $storage_host => $mail_domains) {
if (is_array($mail_domains) && in_array_nocase($domain, $mail_domains)) {
$host = $storage_host;
break;
}
else if (stripos($storage_host, $domain) !== false || stripos(strval($mail_domains), $domain) !== false) {
$host = is_numeric($storage_host) ? $mail_domains : $storage_host;
break;
}
}
}
// take the first entry if $host is still not set
if (empty($host)) {
list($key, $val) = each($default_host);
$host = is_numeric($key) ? $val : $key;
}
}
else if (empty($default_host)) {
$host = rcube_utils::get_input_value('_host', rcube_utils::INPUT_POST);
}
else
$host = rcube_utils::parse_host($default_host);
return $host;
}
/**
* Destroy session data and remove cookie
*/
public function kill_session()
{
$this->plugins->exec_hook('session_destroy');
$this->session->kill();
$_SESSION = array('language' => $this->user->language, 'temp' => true, 'skin' => $this->config->get('skin'));
$this->user->reset();
}
/**
* Do server side actions on logout
*/
public function logout_actions()
{
$config = $this->config->all();
$storage = $this->get_storage();
if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
$storage->clear_folder($config['trash_mbox']);
}
if ($config['logout_expunge']) {
$storage->expunge_folder('INBOX');
}
// Try to save unsaved user preferences
if (!empty($_SESSION['preferences'])) {
$this->user->save_prefs(unserialize($_SESSION['preferences']));
}
}
/**
* Generate a unique token to be used in a form request
*
* @return string The request token
*/
public function get_request_token()
{
$sess_id = $_COOKIE[ini_get('session.name')];
if (!$sess_id) $sess_id = session_id();
$plugin = $this->plugins->exec_hook('request_token', array(
'value' => md5('RT' . $this->get_user_id() . $this->config->get('des_key') . $sess_id)));
return $plugin['value'];
}
/**
* Check if the current request contains a valid token
*
* @param int Request method
* @return boolean True if request token is valid false if not
*/
public function check_request($mode = rcube_utils::INPUT_POST)
{
$token = rcube_utils::get_input_value('_token', $mode);
$sess_id = $_COOKIE[ini_get('session.name')];
return !empty($sess_id) && $token == $this->get_request_token();
}
/**
* Create unique authorization hash
*
* @param string Session ID
* @param int Timestamp
* @return string The generated auth hash
*/
private function get_auth_hash($sess_id, $ts)
{
$auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
$sess_id,
$ts,
$this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
$_SERVER['HTTP_USER_AGENT']);
if (function_exists('sha1'))
return sha1($auth_string);
else
return md5($auth_string);
}
/**
* Build a valid URL to this instance of Roundcube
*
* @param mixed Either a string with the action or url parameters as key-value pairs
*
* @return string Valid application URL
*/
public function url($p)
{
if (!is_array($p)) {
if (strpos($p, 'http') === 0)
return $p;
$p = array('_action' => @func_get_arg(0));
}
$task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
$p['_task'] = $task;
unset($p['task']);
$url = './';
$delm = '?';
foreach (array_reverse($p) as $key => $val) {
if ($val !== '' && $val !== null) {
$par = $key[0] == '_' ? $key : '_'.$key;
$url .= $delm.urlencode($par).'='.urlencode($val);
$delm = '&';
}
}
return $url;
}
/**
* Function to be executed in script shutdown
*/
public function shutdown()
{
parent::shutdown();
foreach ($this->address_books as $book) {
if (is_object($book) && is_a($book, 'rcube_addressbook'))
$book->close();
}
// before closing the database connection, write session data
if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
session_write_close();
}
// write performance stats to logs/console
if ($this->config->get('devel_mode')) {
if (function_exists('memory_get_usage'))
$mem = $this->show_bytes(memory_get_usage());
if (function_exists('memory_get_peak_usage'))
$mem .= '/'.$this->show_bytes(memory_get_peak_usage());
$log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
if (defined('RCMAIL_START'))
self::print_timer(RCMAIL_START, $log);
else
self::console($log);
}
}
/**
* Registers action aliases for current task
*
* @param array $map Alias-to-filename hash array
*/
public function register_action_map($map)
{
if (is_array($map)) {
foreach ($map as $idx => $val) {
$this->action_map[$idx] = $val;
}
}
}
/**
* Returns current action filename
*
* @param array $map Alias-to-filename hash array
*/
public function get_action_file()
{
if (!empty($this->action_map[$this->action])) {
return $this->action_map[$this->action];
}
return strtr($this->action, '-', '_') . '.inc';
}
/**
* Fixes some user preferences according to namespace handling change.
* Old Roundcube versions were using folder names with removed namespace prefix.
* Now we need to add the prefix on servers where personal namespace has prefix.
*
* @param rcube_user $user User object
*/
private function fix_namespace_settings($user)
{
$prefix = $this->storage->get_namespace('prefix');
$prefix_len = strlen($prefix);
if (!$prefix_len)
return;
$prefs = $this->config->all();
if (!empty($prefs['namespace_fixed']))
return;
// Build namespace prefix regexp
$ns = $this->storage->get_namespace();
$regexp = array();
foreach ($ns as $entry) {
if (!empty($entry)) {
foreach ($entry as $item) {
if (strlen($item[0])) {
$regexp[] = preg_quote($item[0], '/');
}
}
}
}
$regexp = '/^('. implode('|', $regexp).')/';
// Fix preferences
$opts = array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox', 'archive_mbox');
foreach ($opts as $opt) {
if ($value = $prefs[$opt]) {
if ($value != 'INBOX' && !preg_match($regexp, $value)) {
$prefs[$opt] = $prefix.$value;
}
}
}
if (!empty($prefs['default_folders'])) {
foreach ($prefs['default_folders'] as $idx => $name) {
if ($name != 'INBOX' && !preg_match($regexp, $name)) {
$prefs['default_folders'][$idx] = $prefix.$name;
}
}
}
if (!empty($prefs['search_mods'])) {
$folders = array();
foreach ($prefs['search_mods'] as $idx => $value) {
if ($idx != 'INBOX' && $idx != '*' && !preg_match($regexp, $idx)) {
$idx = $prefix.$idx;
}
$folders[$idx] = $value;
}
$prefs['search_mods'] = $folders;
}
if (!empty($prefs['message_threading'])) {
$folders = array();
foreach ($prefs['message_threading'] as $idx => $value) {
if ($idx != 'INBOX' && !preg_match($regexp, $idx)) {
$idx = $prefix.$idx;
}
$folders[$prefix.$idx] = $value;
}
$prefs['message_threading'] = $folders;
}
if (!empty($prefs['collapsed_folders'])) {
$folders = explode('&&', $prefs['collapsed_folders']);
$count = count($folders);
$folders_str = '';
if ($count) {
$folders[0] = substr($folders[0], 1);
$folders[$count-1] = substr($folders[$count-1], 0, -1);
}
foreach ($folders as $value) {
if ($value != 'INBOX' && !preg_match($regexp, $value)) {
$value = $prefix.$value;
}
$folders_str .= '&'.$value.'&';
}
$prefs['collapsed_folders'] = $folders_str;
}
$prefs['namespace_fixed'] = true;
// save updated preferences and reset imap settings (default folders)
$user->save_prefs($prefs);
$this->set_storage_prop();
}
/**
* Overwrite action variable
*
* @param string New action value
*/
public function overwrite_action($action)
{
$this->action = $action;
$this->output->set_env('action', $action);
}
/**
* Send the given message using the configured method.
*
* @param object $message Reference to Mail_MIME object
* @param string $from Sender address string
* @param array $mailto Array of recipient address strings
* @param array $error SMTP error array (reference)
* @param string $body_file Location of file with saved message body (reference),
* used when delay_file_io is enabled
* @param array $options SMTP options (e.g. DSN request)
*
* @return boolean Send status.
*/
public function deliver_message(&$message, $from, $mailto, &$error, &$body_file = null, $options = null)
{
$plugin = $this->plugins->exec_hook('message_before_send', array(
'message' => $message,
'from' => $from,
'mailto' => $mailto,
'options' => $options,
));
$from = $plugin['from'];
$mailto = $plugin['mailto'];
$options = $plugin['options'];
$message = $plugin['message'];
$headers = $message->headers();
// send thru SMTP server using custom SMTP library
if ($this->config->get('smtp_server')) {
// generate list of recipients
$a_recipients = array($mailto);
if (strlen($headers['Cc']))
$a_recipients[] = $headers['Cc'];
if (strlen($headers['Bcc']))
$a_recipients[] = $headers['Bcc'];
// clean Bcc from header for recipients
$send_headers = $headers;
unset($send_headers['Bcc']);
// here too, it because txtHeaders() below use $message->_headers not only $send_headers
unset($message->_headers['Bcc']);
$smtp_headers = $message->txtHeaders($send_headers, true);
if ($message->getParam('delay_file_io')) {
// use common temp dir
$temp_dir = $this->config->get('temp_dir');
$body_file = tempnam($temp_dir, 'rcmMsg');
if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
self::raise_error(array('code' => 650, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Could not create message: ".$mime_result->getMessage()),
TRUE, FALSE);
return false;
}
$msg_body = fopen($body_file, 'r');
}
else {
$msg_body = $message->get();
}
// send message
if (!is_object($this->smtp)) {
$this->smtp_init(true);
}
$sent = $this->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $options);
$response = $this->smtp->get_response();
$error = $this->smtp->get_error();
// log error
if (!$sent) {
self::raise_error(array('code' => 800, 'type' => 'smtp',
'line' => __LINE__, 'file' => __FILE__,
'message' => "SMTP error: ".join("\n", $response)), TRUE, FALSE);
}
}
// send mail using PHP's mail() function
else {
// unset some headers because they will be added by the mail() function
$headers_enc = $message->headers($headers);
$headers_php = $message->_headers;
unset($headers_php['To'], $headers_php['Subject']);
// reset stored headers and overwrite
$message->_headers = array();
$header_str = $message->txtHeaders($headers_php);
// #1485779
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
$headers_enc['To'] = implode(', ', $m[1]);
}
}
$msg_body = $message->get();
if (PEAR::isError($msg_body)) {
self::raise_error(array('code' => 650, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Could not create message: ".$msg_body->getMessage()),
TRUE, FALSE);
}
else {
$delim = $this->config->header_delimiter();
$to = $headers_enc['To'];
$subject = $headers_enc['Subject'];
$header_str = rtrim($header_str);
if ($delim != "\r\n") {
$header_str = str_replace("\r\n", $delim, $header_str);
$msg_body = str_replace("\r\n", $delim, $msg_body);
$to = str_replace("\r\n", $delim, $to);
$subject = str_replace("\r\n", $delim, $subject);
}
if (ini_get('safe_mode'))
$sent = mail($to, $subject, $msg_body, $header_str);
else
$sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
}
}
if ($sent) {
$this->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
// remove MDN headers after sending
unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
// get all recipients
if ($headers['Cc'])
$mailto .= $headers['Cc'];
if ($headers['Bcc'])
$mailto .= $headers['Bcc'];
if (preg_match_all('/<([^@]+@[^>]+)>/', $mailto, $m))
$mailto = implode(', ', array_unique($m[1]));
if ($this->config->get('smtp_log')) {
self::write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
$this->user->get_username(),
$_SERVER['REMOTE_ADDR'],
$mailto,
!empty($response) ? join('; ', $response) : ''));
}
}
if (is_resource($msg_body)) {
fclose($msg_body);
}
$message->_headers = array();
$message->headers($headers);
return $sent;
}
/**
* Unique Message-ID generator.
*
* @return string Message-ID
*/
public function gen_message_id()
{
$local_part = md5(uniqid('rcmail'.mt_rand(),true));
$domain_part = $this->user->get_username('domain');
// Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
if (!preg_match('/\.[a-z]+$/i', $domain_part)) {
foreach (array($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']) as $host) {
$host = preg_replace('/:[0-9]+$/', '', $host);
if ($host && preg_match('/\.[a-z]+$/i', $host)) {
$domain_part = $host;
}
}
}
return sprintf('<%s@%s>', $local_part, $domain_part);
}
/**
* Returns RFC2822 formatted current date in user's timezone
*
* @return string Date
*/
public function user_date()
{
// get user's timezone
try {
$tz = new DateTimeZone($this->config->get('timezone'));
$date = new DateTime('now', $tz);
}
catch (Exception $e) {
$date = new DateTime();
}
return $date->format('r');
}
/**
* Write login data (name, ID, IP address) to the 'userlogins' log file.
*/
public function log_login()
{
if (!$this->config->get('log_logins')) {
return;
}
$user_name = $this->get_user_name();
$user_id = $this->get_user_id();
if (!$user_id) {
return;
}
self::write_log('userlogins',
sprintf('Successful login for %s (ID: %d) from %s in session %s',
$user_name, $user_id, rcube_utils::remote_ip(), session_id()));
}
/**
* Create a HTML table based on the given data
*
* @param array Named table attributes
* @param mixed Table row data. Either a two-dimensional array or a valid SQL result set
* @param array List of cols to show
* @param string Name of the identifier col
*
* @return string HTML table code
*/
public function table_output($attrib, $table_data, $a_show_cols, $id_col)
{
$table = new html_table(/*array('cols' => count($a_show_cols))*/);
// add table header
if (!$attrib['noheader']) {
foreach ($a_show_cols as $col) {
$table->add_header($col, $this->Q($this->gettext($col)));
}
}
if (!is_array($table_data)) {
$db = $this->get_dbh();
while ($table_data && ($sql_arr = $db->fetch_assoc($table_data))) {
$table->add_row(array('id' => 'rcmrow' . rcube_utils::html_identifier($sql_arr[$id_col])));
// format each col
foreach ($a_show_cols as $col) {
$table->add($col, $this->Q($sql_arr[$col]));
}
}
}
else {
foreach ($table_data as $row_data) {
$class = !empty($row_data['class']) ? $row_data['class'] : '';
$rowid = 'rcmrow' . rcube_utils::html_identifier($row_data[$id_col]);
$table->add_row(array('id' => $rowid, 'class' => $class));
// format each col
foreach ($a_show_cols as $col) {
$table->add($col, $this->Q(is_array($row_data[$col]) ? $row_data[$col][0] : $row_data[$col]));
}
}
}
return $table->show($attrib);
}
/**
* Convert the given date to a human readable form
* This uses the date formatting properties from config
*
* @param mixed Date representation (string, timestamp or DateTime object)
* @param string Date format to use
* @param bool Enables date convertion according to user timezone
*
* @return string Formatted date string
*/
public function format_date($date, $format = null, $convert = true)
{
if (is_object($date) && is_a($date, 'DateTime')) {
$timestamp = $date->format('U');
}
else {
if (!empty($date)) {
$timestamp = rcube_utils::strtotime($date);
}
if (empty($timestamp)) {
return '';
}
try {
$date = new DateTime("@".$timestamp);
}
catch (Exception $e) {
return '';
}
}
if ($convert) {
try {
// convert to the right timezone
$stz = date_default_timezone_get();
$tz = new DateTimeZone($this->config->get('timezone'));
$date->setTimezone($tz);
date_default_timezone_set($tz->getName());
$timestamp = $date->format('U');
}
catch (Exception $e) {
}
}
// define date format depending on current time
if (!$format) {
$now = time();
$now_date = getdate($now);
$today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
$week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
$pretty_date = $this->config->get('prettydate');
if ($pretty_date && $timestamp > $today_limit && $timestamp < $now) {
$format = $this->config->get('date_today', $this->config->get('time_format', 'H:i'));
$today = true;
}
else if ($pretty_date && $timestamp > $week_limit && $timestamp < $now) {
$format = $this->config->get('date_short', 'D H:i');
}
else {
$format = $this->config->get('date_long', 'Y-m-d H:i');
}
}
// strftime() format
if (preg_match('/%[a-z]+/i', $format)) {
$format = strftime($format, $timestamp);
if ($stz) {
date_default_timezone_set($stz);
}
return $today ? ($this->gettext('today') . ' ' . $format) : $format;
}
// parse format string manually in order to provide localized weekday and month names
// an alternative would be to convert the date() format string to fit with strftime()
$out = '';
for ($i=0; $i<strlen($format); $i++) {
if ($format[$i] == "\\") { // skip escape chars
continue;
}
// write char "as-is"
if ($format[$i] == ' ' || $format[$i-1] == "\\") {
$out .= $format[$i];
}
// weekday (short)
else if ($format[$i] == 'D') {
$out .= $this->gettext(strtolower(date('D', $timestamp)));
}
// weekday long
else if ($format[$i] == 'l') {
$out .= $this->gettext(strtolower(date('l', $timestamp)));
}
// month name (short)
else if ($format[$i] == 'M') {
$out .= $this->gettext(strtolower(date('M', $timestamp)));
}
// month name (long)
else if ($format[$i] == 'F') {
$out .= $this->gettext('long'.strtolower(date('M', $timestamp)));
}
else if ($format[$i] == 'x') {
$out .= strftime('%x %X', $timestamp);
}
else {
$out .= date($format[$i], $timestamp);
}
}
if ($today) {
$label = $this->gettext('today');
// replcae $ character with "Today" label (#1486120)
if (strpos($out, '$') !== false) {
$out = preg_replace('/\$/', $label, $out, 1);
}
else {
$out = $label . ' ' . $out;
}
}
if ($stz) {
date_default_timezone_set($stz);
}
return $out;
}
/**
* Return folders list in HTML
*
* @param array $attrib Named parameters
*
* @return string HTML code for the gui object
*/
public function folder_list($attrib)
{
static $a_mailboxes;
$attrib += array('maxlength' => 100, 'realnames' => false, 'unreadwrap' => ' (%s)');
$rcmail = rcmail::get_instance();
$storage = $rcmail->get_storage();
// add some labels to client
$rcmail->output->add_label('purgefolderconfirm', 'deletemessagesconfirm');
$type = $attrib['type'] ? $attrib['type'] : 'ul';
unset($attrib['type']);
if ($type == 'ul' && !$attrib['id']) {
$attrib['id'] = 'rcmboxlist';
}
if (empty($attrib['folder_name'])) {
$attrib['folder_name'] = '*';
}
// get current folder
$mbox_name = $storage->get_folder();
// build the folders tree
if (empty($a_mailboxes)) {
// get mailbox list
$a_folders = $storage->list_folders_subscribed(
'', $attrib['folder_name'], $attrib['folder_filter']);
$delimiter = $storage->get_hierarchy_delimiter();
$a_mailboxes = array();
foreach ($a_folders as $folder) {
$rcmail->build_folder_tree($a_mailboxes, $folder, $delimiter);
}
}
// allow plugins to alter the folder tree or to localize folder names
$hook = $rcmail->plugins->exec_hook('render_mailboxlist', array(
'list' => $a_mailboxes,
'delimiter' => $delimiter,
'type' => $type,
'attribs' => $attrib,
));
$a_mailboxes = $hook['list'];
$attrib = $hook['attribs'];
if ($type == 'select') {
$attrib['is_escaped'] = true;
$select = new html_select($attrib);
// add no-selection option
if ($attrib['noselection']) {
$select->add(html::quote($rcmail->gettext($attrib['noselection'])), '');
}
$rcmail->render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
$out = $select->show($attrib['default']);
}
else {
$js_mailboxlist = array();
$out = html::tag('ul', $attrib, $rcmail->render_folder_tree_html($a_mailboxes, $mbox_name, $js_mailboxlist, $attrib), html::$common_attrib);
$rcmail->output->add_gui_object('mailboxlist', $attrib['id']);
$rcmail->output->set_env('mailboxes', $js_mailboxlist);
$rcmail->output->set_env('unreadwrap', $attrib['unreadwrap']);
$rcmail->output->set_env('collapsed_folders', (string)$rcmail->config->get('collapsed_folders'));
}
return $out;
}
/**
* Return folders list as html_select object
*
* @param array $p Named parameters
*
* @return html_select HTML drop-down object
*/
public function folder_selector($p = array())
{
$p += array('maxlength' => 100, 'realnames' => false, 'is_escaped' => true);
$a_mailboxes = array();
$storage = $this->get_storage();
if (empty($p['folder_name'])) {
$p['folder_name'] = '*';
}
if ($p['unsubscribed']) {
$list = $storage->list_folders('', $p['folder_name'], $p['folder_filter'], $p['folder_rights']);
}
else {
$list = $storage->list_folders_subscribed('', $p['folder_name'], $p['folder_filter'], $p['folder_rights']);
}
$delimiter = $storage->get_hierarchy_delimiter();
foreach ($list as $folder) {
if (empty($p['exceptions']) || !in_array($folder, $p['exceptions'])) {
$this->build_folder_tree($a_mailboxes, $folder, $delimiter);
}
}
$select = new html_select($p);
if ($p['noselection']) {
$select->add(html::quote($p['noselection']), '');
}
$this->render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames'], 0, $p);
return $select;
}
/**
* Create a hierarchical array of the mailbox list
*/
public function build_folder_tree(&$arrFolders, $folder, $delm = '/', $path = '')
{
// Handle namespace prefix
$prefix = '';
if (!$path) {
$n_folder = $folder;
$folder = $this->storage->mod_folder($folder);
if ($n_folder != $folder) {
$prefix = substr($n_folder, 0, -strlen($folder));
}
}
$pos = strpos($folder, $delm);
if ($pos !== false) {
$subFolders = substr($folder, $pos+1);
$currentFolder = substr($folder, 0, $pos);
// sometimes folder has a delimiter as the last character
if (!strlen($subFolders)) {
$virtual = false;
}
else if (!isset($arrFolders[$currentFolder])) {
$virtual = true;
}
else {
$virtual = $arrFolders[$currentFolder]['virtual'];
}
}
else {
$subFolders = false;
$currentFolder = $folder;
$virtual = false;
}
$path .= $prefix . $currentFolder;
if (!isset($arrFolders[$currentFolder])) {
$arrFolders[$currentFolder] = array(
'id' => $path,
'name' => rcube_charset::convert($currentFolder, 'UTF7-IMAP'),
'virtual' => $virtual,
'folders' => array());
}
else {
$arrFolders[$currentFolder]['virtual'] = $virtual;
}
if (strlen($subFolders)) {
$this->build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
}
}
/**
* Return html for a structured list &lt;ul&gt; for the mailbox tree
*/
public function render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel = 0)
{
$maxlength = intval($attrib['maxlength']);
$realnames = (bool)$attrib['realnames'];
$msgcounts = $this->storage->get_cache('messagecount');
$collapsed = $this->config->get('collapsed_folders');
$out = '';
foreach ($arrFolders as $key => $folder) {
$title = null;
$folder_class = $this->folder_classname($folder['id']);
$is_collapsed = strpos($collapsed, '&'.rawurlencode($folder['id']).'&') !== false;
$unread = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
if ($folder_class && !$realnames) {
$foldername = $this->gettext($folder_class);
}
else {
$foldername = $folder['name'];
// shorten the folder name to a given length
if ($maxlength && $maxlength > 1) {
$fname = abbreviate_string($foldername, $maxlength);
if ($fname != $foldername) {
$title = $foldername;
}
$foldername = $fname;
}
}
// make folder name safe for ids and class names
$folder_id = rcube_utils::html_identifier($folder['id'], true);
$classes = array('mailbox');
// set special class for Sent, Drafts, Trash and Junk
if ($folder_class) {
$classes[] = $folder_class;
}
if ($folder['id'] == $mbox_name) {
$classes[] = 'selected';
}
if ($folder['virtual']) {
$classes[] = 'virtual';
}
else if ($unread) {
$classes[] = 'unread';
}
$js_name = $this->JQ($folder['id']);
$html_name = $this->Q($foldername) . ($unread ? html::span('unreadcount', sprintf($attrib['unreadwrap'], $unread)) : '');
$link_attrib = $folder['virtual'] ? array() : array(
'href' => $this->url(array('_mbox' => $folder['id'])),
'onclick' => sprintf("return %s.command('list','%s',this)", rcmail_output::JS_OBJECT_NAME, $js_name),
'rel' => $folder['id'],
'title' => $title,
);
$out .= html::tag('li', array(
'id' => "rcmli".$folder_id,
'class' => join(' ', $classes),
'noclose' => true),
html::a($link_attrib, $html_name) .
(!empty($folder['folders']) ? html::div(array(
'class' => ($is_collapsed ? 'collapsed' : 'expanded'),
'style' => "position:absolute",
'onclick' => sprintf("%s.command('collapse-folder', '%s')", rcmail_output::JS_OBJECT_NAME, $js_name)
), '&nbsp;') : ''));
$jslist[$folder_id] = array(
'id' => $folder['id'],
'name' => $foldername,
'virtual' => $folder['virtual']
);
if (!empty($folder['folders'])) {
$out .= html::tag('ul', array('style' => ($is_collapsed ? "display:none;" : null)),
$this->render_folder_tree_html($folder['folders'], $mbox_name, $jslist, $attrib, $nestLevel+1));
}
$out .= "</li>\n";
}
return $out;
}
/**
* Return html for a flat list <select> for the mailbox tree
*/
public function render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames = false, $nestLevel = 0, $opts = array())
{
$out = '';
foreach ($arrFolders as $key => $folder) {
// skip exceptions (and its subfolders)
if (!empty($opts['exceptions']) && in_array($folder['id'], $opts['exceptions'])) {
continue;
}
// skip folders in which it isn't possible to create subfolders
if (!empty($opts['skip_noinferiors'])) {
$attrs = $this->storage->folder_attributes($folder['id']);
if ($attrs && in_array('\\Noinferiors', $attrs)) {
continue;
}
}
if (!$realnames && ($folder_class = $this->folder_classname($folder['id']))) {
$foldername = $this->gettext($folder_class);
}
else {
$foldername = $folder['name'];
// shorten the folder name to a given length
if ($maxlength && $maxlength > 1) {
$foldername = abbreviate_string($foldername, $maxlength);
}
}
$select->add(str_repeat('&nbsp;', $nestLevel*4) . html::quote($foldername), $folder['id']);
if (!empty($folder['folders'])) {
$out .= $this->render_folder_tree_select($folder['folders'], $mbox_name, $maxlength,
$select, $realnames, $nestLevel+1, $opts);
}
}
return $out;
}
/**
* Return internal name for the given folder if it matches the configured special folders
*/
public function folder_classname($folder_id)
{
if ($folder_id == 'INBOX') {
return 'inbox';
}
// for these mailboxes we have localized labels and css classes
foreach (array('sent', 'drafts', 'trash', 'junk') as $smbx)
{
if ($folder_id === $this->config->get($smbx.'_mbox')) {
return $smbx;
}
}
}
/**
* Try to localize the given IMAP folder name.
* UTF-7 decode it in case no localized text was found
*
* @param string $name Folder name
* @param bool $with_path Enable path localization
*
* @return string Localized folder name in UTF-8 encoding
*/
public function localize_foldername($name, $with_path = true)
{
// try to localize path of the folder
if ($with_path) {
$storage = $this->get_storage();
$delimiter = $storage->get_hierarchy_delimiter();
$path = explode($delimiter, $name);
$count = count($path);
if ($count > 1) {
- for ($i = 1; $i < $count; $i++) {
+ for ($i = 0; $i < $count; $i++) {
$folder = implode($delimiter, array_slice($path, 0, -$i));
if ($folder_class = $this->folder_classname($folder)) {
$name = implode($delimiter, array_slice($path, $count - $i));
return $this->gettext($folder_class) . $delimiter . rcube_charset::convert($name, 'UTF7-IMAP');
}
}
}
}
if ($folder_class = $this->folder_classname($name)) {
return $this->gettext($folder_class);
}
else {
return rcube_charset::convert($name, 'UTF7-IMAP');
}
}
public function localize_folderpath($path)
{
$protect_folders = $this->config->get('protect_default_folders');
$default_folders = (array) $this->config->get('default_folders');
$delimiter = $this->storage->get_hierarchy_delimiter();
$path = explode($delimiter, $path);
$result = array();
foreach ($path as $idx => $dir) {
$directory = implode($delimiter, array_slice($path, 0, $idx+1));
if ($protect_folders && in_array($directory, $default_folders)) {
unset($result);
$result[] = $this->localize_foldername($directory);
}
else {
$result[] = rcube_charset::convert($dir, 'UTF7-IMAP');
}
}
return implode($delimiter, $result);
}
public static function quota_display($attrib)
{
$rcmail = rcmail::get_instance();
if (!$attrib['id']) {
$attrib['id'] = 'rcmquotadisplay';
}
$_SESSION['quota_display'] = !empty($attrib['display']) ? $attrib['display'] : 'text';
$rcmail->output->add_gui_object('quotadisplay', $attrib['id']);
$quota = $rcmail->quota_content($attrib);
$rcmail->output->add_script('rcmail.set_quota('.rcube_output::json_serialize($quota).');', 'docready');
return html::span($attrib, '');
}
public function quota_content($attrib = null)
{
$quota = $this->storage->get_quota();
$quota = $this->plugins->exec_hook('quota', $quota);
$quota_result = (array) $quota;
$quota_result['type'] = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
if (!$quota['total'] && $this->config->get('quota_zero_as_unlimited')) {
$quota_result['title'] = $this->gettext('unlimited');
$quota_result['percent'] = 0;
}
else if ($quota['total']) {
if (!isset($quota['percent'])) {
$quota_result['percent'] = min(100, round(($quota['used']/max(1,$quota['total']))*100));
}
$title = sprintf('%s / %s (%.0f%%)',
$this->show_bytes($quota['used'] * 1024), $this->show_bytes($quota['total'] * 1024),
$quota_result['percent']);
$quota_result['title'] = $title;
if ($attrib['width']) {
$quota_result['width'] = $attrib['width'];
}
if ($attrib['height']) {
$quota_result['height'] = $attrib['height'];
}
}
else {
$quota_result['title'] = $this->gettext('unknown');
$quota_result['percent'] = 0;
}
return $quota_result;
}
/**
* Outputs error message according to server error/response codes
*
* @param string $fallback Fallback message label
* @param array $fallback_args Fallback message label arguments
*/
public function display_server_error($fallback = null, $fallback_args = null)
{
$err_code = $this->storage->get_error_code();
$res_code = $this->storage->get_response_code();
if ($res_code == rcube_storage::NOPERM) {
$this->output->show_message('errornoperm', 'error');
}
else if ($res_code == rcube_storage::READONLY) {
$this->output->show_message('errorreadonly', 'error');
}
else if ($err_code && ($err_str = $this->storage->get_error_str())) {
// try to detect access rights problem and display appropriate message
if (stripos($err_str, 'Permission denied') !== false) {
$this->output->show_message('errornoperm', 'error');
}
else {
$this->output->show_message('servererrormsg', 'error', array('msg' => $err_str));
}
}
else if ($err_code < 0) {
$this->output->show_message('storageerror', 'error');
}
else if ($fallback) {
$this->output->show_message($fallback, 'error', $fallback_args);
}
}
/**
* Output HTML editor scripts
*
* @param string $mode Editor mode
*/
public function html_editor($mode = '')
{
$hook = $this->plugins->exec_hook('html_editor', array('mode' => $mode));
if ($hook['abort']) {
return;
}
$lang = strtolower($_SESSION['language']);
// TinyMCE uses two-letter lang codes, with exception of Chinese
if (strpos($lang, 'zh_') === 0) {
$lang = str_replace('_', '-', $lang);
}
else {
$lang = substr($lang, 0, 2);
}
if (!file_exists(INSTALL_PATH . 'program/js/tiny_mce/langs/'.$lang.'.js')) {
$lang = 'en';
}
$script = json_encode(array(
'mode' => $mode,
'lang' => $lang,
'skin_path' => $this->output->get_skin_path(),
'spellcheck' => intval($this->config->get('enable_spellcheck')),
'spelldict' => intval($this->config->get('spellcheck_dictionary'))
));
$this->output->include_script('tiny_mce/tiny_mce.js');
$this->output->include_script('editor.js');
$this->output->add_script("rcmail_editor_init($script)", 'docready');
}
/**
* Replaces TinyMCE's emoticon images with plain-text representation
*
* @param string $html HTML content
*
* @return string HTML content
*/
public static function replace_emoticons($html)
{
$emoticons = array(
'8-)' => 'smiley-cool',
':-#' => 'smiley-foot-in-mouth',
':-*' => 'smiley-kiss',
':-X' => 'smiley-sealed',
':-P' => 'smiley-tongue-out',
':-@' => 'smiley-yell',
":'(" => 'smiley-cry',
':-(' => 'smiley-frown',
':-D' => 'smiley-laughing',
':-)' => 'smiley-smile',
':-S' => 'smiley-undecided',
':-$' => 'smiley-embarassed',
'O:-)' => 'smiley-innocent',
':-|' => 'smiley-money-mouth',
':-O' => 'smiley-surprised',
';-)' => 'smiley-wink',
);
foreach ($emoticons as $idx => $file) {
// <img title="Cry" src="http://.../program/js/tiny_mce/plugins/emotions/img/smiley-cry.gif" border="0" alt="Cry" />
$search[] = '/<img title="[a-z ]+" src="https?:\/\/[a-z0-9_.\/-]+\/tiny_mce\/plugins\/emotions\/img\/'.$file.'.gif"[^>]+\/>/i';
$replace[] = $idx;
}
return preg_replace($search, $replace, $html);
}
/**
* File upload progress handler.
*/
public function upload_progress()
{
$prefix = ini_get('apc.rfc1867_prefix');
$params = array(
'action' => $this->action,
'name' => rcube_utils::get_input_value('_progress', rcube_utils::INPUT_GET),
);
if (function_exists('apc_fetch')) {
$status = apc_fetch($prefix . $params['name']);
if (!empty($status)) {
$status['percent'] = round($status['current']/$status['total']*100);
$params = array_merge($status, $params);
}
}
if (isset($params['percent']))
$params['text'] = $this->gettext(array('name' => 'uploadprogress', 'vars' => array(
'percent' => $params['percent'] . '%',
'current' => $this->show_bytes($params['current']),
'total' => $this->show_bytes($params['total'])
)));
$this->output->command('upload_progress_update', $params);
$this->output->send();
}
/**
* Initializes file uploading interface.
*/
public function upload_init()
{
// Enable upload progress bar
if (($seconds = $this->config->get('upload_progress')) && ini_get('apc.rfc1867')) {
if ($field_name = ini_get('apc.rfc1867_name')) {
$this->output->set_env('upload_progress_name', $field_name);
$this->output->set_env('upload_progress_time', (int) $seconds);
}
}
// find max filesize value
$max_filesize = parse_bytes(ini_get('upload_max_filesize'));
$max_postsize = parse_bytes(ini_get('post_max_size'));
if ($max_postsize && $max_postsize < $max_filesize) {
$max_filesize = $max_postsize;
}
$this->output->set_env('max_filesize', $max_filesize);
$max_filesize = self::show_bytes($max_filesize);
$this->output->set_env('filesizeerror', $this->gettext(array(
'name' => 'filesizeerror', 'vars' => array('size' => $max_filesize))));
return $max_filesize;
}
/**
* Initializes client-side autocompletion.
*/
public function autocomplete_init()
{
static $init;
if ($init) {
return;
}
$init = 1;
if (($threads = (int)$this->config->get('autocomplete_threads')) > 0) {
$book_types = (array) $this->config->get('autocomplete_addressbooks', 'sql');
if (count($book_types) > 1) {
$this->output->set_env('autocomplete_threads', $threads);
$this->output->set_env('autocomplete_sources', $book_types);
}
}
$this->output->set_env('autocomplete_max', (int)$this->config->get('autocomplete_max', 15));
$this->output->set_env('autocomplete_min_length', $this->config->get('autocomplete_min_length'));
$this->output->add_label('autocompletechars', 'autocompletemore');
}
/**
* Returns supported font-family specifications
*
* @param string $font Font name
*
* @param string|array Font-family specification array or string (if $font is used)
*/
public static function font_defs($font = null)
{
$fonts = array(
'Andale Mono' => '"Andale Mono",Times,monospace',
'Arial' => 'Arial,Helvetica,sans-serif',
'Arial Black' => '"Arial Black","Avant Garde",sans-serif',
'Book Antiqua' => '"Book Antiqua",Palatino,serif',
'Courier New' => '"Courier New",Courier,monospace',
'Georgia' => 'Georgia,Palatino,serif',
'Helvetica' => 'Helvetica,Arial,sans-serif',
'Impact' => 'Impact,Chicago,sans-serif',
'Tahoma' => 'Tahoma,Arial,Helvetica,sans-serif',
'Terminal' => 'Terminal,Monaco,monospace',
'Times New Roman' => '"Times New Roman",Times,serif',
'Trebuchet MS' => '"Trebuchet MS",Geneva,sans-serif',
'Verdana' => 'Verdana,Geneva,sans-serif',
);
if ($font) {
return $fonts[$font];
}
return $fonts;
}
/**
* Create a human readable string for a number of bytes
*
* @param int Number of bytes
*
* @return string Byte string
*/
public function show_bytes($bytes)
{
if ($bytes >= 1073741824) {
$gb = $bytes/1073741824;
$str = sprintf($gb>=10 ? "%d " : "%.1f ", $gb) . $this->gettext('GB');
}
else if ($bytes >= 1048576) {
$mb = $bytes/1048576;
$str = sprintf($mb>=10 ? "%d " : "%.1f ", $mb) . $this->gettext('MB');
}
else if ($bytes >= 1024) {
$str = sprintf("%d ", round($bytes/1024)) . $this->gettext('KB');
}
else {
$str = sprintf('%d ', $bytes) . $this->gettext('B');
}
return $str;
}
/**
* Returns real size (calculated) of the message part
*
* @param rcube_message_part Message part
*
* @return string Part size (and unit)
*/
public function message_part_size($part)
{
if (isset($part->d_parameters['size'])) {
$size = $this->show_bytes((int)$part->d_parameters['size']);
}
else {
$size = $part->size;
if ($part->encoding == 'base64') {
$size = $size / 1.33;
}
$size = '~' . $this->show_bytes($size);
}
return $size;
}
/************************************************************************
********* Deprecated methods (to be removed) *********
***********************************************************************/
public static function setcookie($name, $value, $exp = 0)
{
rcube_utils::setcookie($name, $value, $exp);
}
public function imap_connect()
{
return $this->storage_connect();
}
public function imap_init()
{
return $this->storage_init();
}
/**
* Connect to the mail storage server with stored session data
*
* @return bool True on success, False on error
*/
public function storage_connect()
{
$storage = $this->get_storage();
if ($_SESSION['storage_host'] && !$storage->is_connected()) {
$host = $_SESSION['storage_host'];
$user = $_SESSION['username'];
$port = $_SESSION['storage_port'];
$ssl = $_SESSION['storage_ssl'];
$pass = $this->decrypt($_SESSION['password']);
if (!$storage->connect($host, $user, $pass, $port, $ssl)) {
if (is_object($this->output)) {
$this->output->show_message('storageerror', 'error');
}
}
else {
$this->set_storage_prop();
}
}
return $storage->is_connected();
}
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, Mar 1, 7:04 AM (1 d, 8 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
166199
Default Alt Text
(425 KB)

Event Timeline