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 8879a6050..28139e92c 100644
--- a/plugins/acl/acl.php
+++ b/plugins/acl/acl.php
@@ -1,730 +1,729 @@
<?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(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 = 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' => $this->rc->gettext('info'),
'content' => array());
// Display folder rights to 'Info' fieldset
$args['form']['props']['fieldsets']['info']['content']['myrights'] = array(
'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' => 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 $key => $val) {
$id = "acl$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 = 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', 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(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);
$result = 0;
foreach ($users as $user) {
$user = trim($user);
if (!empty($this->specials) && in_array($user, $this->specials)) {
$username = $this->gettext($user);
}
else if (!empty($user)) {
if (!strpos($user, '@') && ($realm = $this->get_realm())) {
$user .= '@' . rcube_utils::idn_to_ascii(preg_replace('/^@/', '', $realm));
}
$username = $user;
}
if (!$acl || !$user || !strlen($mbox)) {
continue;
}
$user = $this->mod_login($user);
$username = $this->mod_login($username);
if ($user != $_SESSION['username'] && $username != $_SESSION['username']) {
if ($this->rc->storage->set_acl($mbox, $user, $acl)) {
$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(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', 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(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, rcube::Q($this->gettext('acl' . $right)));
}
}
if (count($list) == count($supported))
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;
}
/**
* Modify user login according to 'login_lc' setting
*/
protected function mod_login($user)
{
$login_lc = $this->rc->config->get('login_lc');
if ($login_lc === true || $login_lc == 2) {
$user = mb_strtolower($user);
}
// lowercase domain name
else if ($login_lc && strpos($user, '@')) {
list($local, $domain) = explode('@', $user);
$user = $local . '@' . mb_strtolower($domain);
}
return $user;
}
}
diff --git a/plugins/autologon/autologon.php b/plugins/autologon/autologon.php
index 63ffb943e..9c7d5b6fc 100644
--- a/plugins/autologon/autologon.php
+++ b/plugins/autologon/autologon.php
@@ -1,50 +1,48 @@
<?php
/**
* Sample plugin to try out some hooks.
* This performs an automatic login if accessed from localhost
*
* @license GNU GPLv3+
* @author Thomas Bruederli
*/
class autologon extends rcube_plugin
{
public $task = 'login';
function init()
{
$this->add_hook('startup', array($this, 'startup'));
$this->add_hook('authenticate', array($this, 'authenticate'));
}
function startup($args)
{
- $rcmail = rcmail::get_instance();
-
// change action to login
if (empty($_SESSION['user_id']) && !empty($_GET['_autologin']) && $this->is_localhost())
$args['action'] = 'login';
return $args;
}
function authenticate($args)
{
if (!empty($_GET['_autologin']) && $this->is_localhost()) {
$args['user'] = 'me';
$args['pass'] = '******';
$args['host'] = 'localhost';
$args['cookiecheck'] = false;
$args['valid'] = true;
}
-
+
return $args;
}
function is_localhost()
{
return $_SERVER['REMOTE_ADDR'] == '::1' || $_SERVER['REMOTE_ADDR'] == '127.0.0.1';
}
}
diff --git a/plugins/debug_logger/runlog/runlog.php b/plugins/debug_logger/runlog/runlog.php
index c9f672615..0c766a13c 100644
--- a/plugins/debug_logger/runlog/runlog.php
+++ b/plugins/debug_logger/runlog/runlog.php
@@ -1,227 +1,227 @@
<?php
/**
* runlog
*
* @author Ziba Scott <ziba@umich.edu>
*/
class runlog {
private $start_time = FALSE;
private $parent_stack = array();
public $print_to_console = FALSE;
private $file_handles = array();
private $indent = 0;
public $threshold = 0;
public $tag_count = array();
public $timestamp = "d-M-Y H:i:s O";
public $max_line_size = 150;
private $run_log = array();
function runlog()
{
$this->start_time = microtime( TRUE );
}
public function start( $name, $tag = FALSE )
{
$this->run_log[] = array( 'type' => 'start',
'tag' => $tag,
'index' => count($this->run_log),
'value' => $name,
'time' => microtime( TRUE ),
'parents' => $this->parent_stack,
'ended' => false,
);
$this->parent_stack[] = $name;
$this->print_to_console("start: ".$name, $tag, 'start');
$this->print_to_file("start: ".$name, $tag, 'start');
$this->indent++;
}
public function end()
{
$name = array_pop( $this->parent_stack );
foreach ( $this->run_log as $k => $entry ) {
if ( $entry['value'] == $name && $entry['type'] == 'start' && $entry['ended'] == false) {
$lastk = $k;
}
}
$start = $this->run_log[$lastk]['time'];
$this->run_log[$lastk]['duration'] = microtime( TRUE ) - $start;
$this->run_log[$lastk]['ended'] = true;
$this->run_log[] = array( 'type' => 'end',
'tag' => $this->run_log[$lastk]['tag'],
'index' => $lastk,
'value' => $name,
'time' => microtime( TRUE ),
'duration' => microtime( TRUE ) - $start,
'parents' => $this->parent_stack,
);
$this->indent--;
if($this->run_log[$lastk]['duration'] >= $this->threshold){
$tag_report = "";
foreach($this->tag_count as $tag=>$count){
$tag_report .= "$tag: $count, ";
}
if(!empty($tag_report)){
// $tag_report = "\n$tag_report\n";
}
$end_txt = sprintf("end: $name - %0.4f seconds $tag_report", $this->run_log[$lastk]['duration'] );
$this->print_to_console($end_txt, $this->run_log[$lastk]['tag'] , 'end');
$this->print_to_file($end_txt, $this->run_log[$lastk]['tag'], 'end');
}
}
public function increase_tag_count($tag){
if(!isset($this->tag_count[$tag])){
$this->tag_count[$tag] = 0;
}
$this->tag_count[$tag]++;
}
public function get_text(){
$text = "";
foreach($this->run_log as $entry){
$text .= str_repeat(" ",count($entry['parents']));
if($entry['tag'] != 'text'){
$text .= $entry['tag'].': ';
}
$text .= $entry['value'];
if($entry['tag'] == 'end'){
$text .= sprintf(" - %0.4f seconds", $entry['duration'] );
}
$text .= "\n";
}
return $text;
}
public function set_file($filename, $tag = 'master'){
if(!isset($this->file_handle[$tag])){
$this->file_handles[$tag] = fopen($filename, 'a');
if(!$this->file_handles[$tag]){
trigger_error('Could not open file for writing: '.$filename);
}
}
}
public function note( $msg, $tag = FALSE )
{
if($tag){
$this->increase_tag_count($tag);
}
if ( is_array( $msg )) {
$msg = '<pre>' . print_r( $msg, TRUE ) . '</pre>';
}
$this->debug_messages[] = $msg;
$this->run_log[] = array( 'type' => 'note',
'tag' => $tag ? $tag:"text",
'value' => htmlentities($msg),
'time' => microtime( TRUE ),
'parents' => $this->parent_stack,
);
$this->print_to_file($msg, $tag);
$this->print_to_console($msg, $tag);
}
public function print_to_file($msg, $tag = FALSE, $type = FALSE){
if(!$tag){
$file_handle_tag = 'master';
}
else{
$file_handle_tag = $tag;
}
if($file_handle_tag != 'master' && isset($this->file_handles[$file_handle_tag])){
$buffer = $this->get_indent();
$buffer .= "$msg\n";
if(!empty($this->timestamp)){
$buffer = sprintf("[%s] %s",date($this->timestamp, mktime()), $buffer);
}
fwrite($this->file_handles[$file_handle_tag], wordwrap($buffer, $this->max_line_size, "\n "));
}
if(isset($this->file_handles['master']) && $this->file_handles['master']){
$buffer = $this->get_indent();
if($tag){
$buffer .= "$tag: ";
}
$msg = str_replace("\n","",$msg);
$buffer .= "$msg";
if(!empty($this->timestamp)){
$buffer = sprintf("[%s] %s",date($this->timestamp, mktime()), $buffer);
}
if(strlen($buffer) > $this->max_line_size){
$buffer = substr($buffer,0,$this->max_line_size - 3)."...";
}
fwrite($this->file_handles['master'], $buffer."\n");
}
}
public function print_to_console($msg, $tag=FALSE){
if($this->print_to_console){
if(is_array($this->print_to_console)){
if(in_array($tag, $this->print_to_console)){
echo $this->get_indent();
if($tag){
echo "$tag: ";
}
echo "$msg\n";
}
}
else{
echo $this->get_indent();
if($tag){
echo "$tag: ";
}
echo "$msg\n";
}
}
}
public function print_totals(){
$totals = array();
- foreach ( $this->run_log as $k => $entry ) {
+ foreach ($this->run_log as $entry) {
if ( $entry['type'] == 'start' && $entry['ended'] == true) {
$totals[$entry['value']]['duration'] += $entry['duration'];
$totals[$entry['value']]['count'] += 1;
}
}
if($this->file_handle){
foreach($totals as $name=>$details){
fwrite($this->file_handle,$name.": ".number_format($details['duration'],4)."sec, ".$details['count']." calls \n");
}
}
}
private function get_indent(){
$buf = "";
for($i = 0; $i < $this->indent; $i++){
$buf .= " ";
}
return $buf;
}
function __destruct(){
foreach($this->file_handles as $handle){
fclose($handle);
}
}
}
?>
diff --git a/plugins/enigma/enigma.php b/plugins/enigma/enigma.php
index 1194d26c8..25520a27d 100644
--- a/plugins/enigma/enigma.php
+++ b/plugins/enigma/enigma.php
@@ -1,476 +1,476 @@
<?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;
$section = rcube_utils::get_input_value('_section', rcube_utils::INPUT_GET);
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
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'];
+// $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' => 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 = rcube::Q(str_replace('$keyid', enigma_key::format_id($status->getData('id')),
$this->gettext('decryptnokey')));
else if ($code == enigma_error::E_BADPASS)
$msg = rcube::Q($this->gettext('decryptbadpass'));
else
$msg = rcube::Q($this->gettext('decrypterror'));
}
else {
$attrib['class'] = 'enigmanotice';
$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 = rcube::Q(str_replace('$sender', $sender, $this->gettext('sigvalid')));
}
else {
$attrib['class'] = 'enigmawarning';
$sender = ($sig->name ? $sig->name . ' ' : '') . '<' . $sig->email . '>';
$msg = rcube::Q(str_replace('$sender', $sender, $this->gettext('siginvalid')));
}
}
else if ($sig->getCode() == enigma_error::E_KEYNOTFOUND) {
$attrib['class'] = 'enigmawarning';
$msg = rcube::Q(str_replace('$keyid', enigma_key::format_id($sig->getData('id')),
$this->gettext('signokey')));
}
else {
$attrib['class'] = 'enigmaerror';
$msg = rcube::Q($this->gettext('sigerror'));
}
/*
$msg .= '&nbsp;' . html::a(array('href' => "#sigdetails",
'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) {
+ foreach ((array)$this->message->parts as $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 ".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 a30a517ec..8a64c07ff 100644
--- a/plugins/enigma/lib/enigma_engine.php
+++ b/plugins/enigma/lib/enigma_engine.php
@@ -1,543 +1,533 @@
<?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) {
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) {
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) {
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) {
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)
rcube::raise_error(array(
'code' => 600, 'type' => 'php',
'file' => __FILE__, 'line' => __LINE__,
'message' => "Enigma plugin: " . $sig->getMessage()
), true, false);
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
$key = ''; $pass = ''; // @TODO
$result = $this->pgp_driver->decrypt($msg_body, $key, $pass);
if ($result instanceof enigma_error) {
$err_code = $result->getCode();
if (!in_array($err_code, array(enigma_error::E_KEYNOTFOUND, enigma_error::E_BADPASS)))
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) {
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) {
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) {
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 = 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);
+ $storage = $this->rc->get_storage();
if ($uid && $mime_id) {
- $part = $this->rc->storage->get_message_part($uid, $mime_id);
+ $storage->set_folder($mbox);
+ $part = $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 47366b7e8..adb619d0c 100644
--- a/plugins/enigma/lib/enigma_ui.php
+++ b/plugins/enigma/lib/enigma_ui.php
@@ -1,456 +1,455 @@
<?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 = 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 = $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(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();
+// $a_show_cols = array('name');
// 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) {
+ foreach ($list as $key) {
$this->rc->output->command('enigma_add_list_row',
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 = 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 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, 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' => $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,
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'),
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'),
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'),
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/help/help.php b/plugins/help/help.php
index 4b11dceb3..69da6828e 100644
--- a/plugins/help/help.php
+++ b/plugins/help/help.php
@@ -1,96 +1,94 @@
<?php
/**
* Help Plugin
*
* @author Aleksander 'A.L.E.C' Machniak
* @license GNU GPLv3+
*
* Configuration (see config.inc.php.dist)
*
**/
class help extends rcube_plugin
{
// all task excluding 'login' and 'logout'
public $task = '?(?!login|logout).*';
// we've got no ajax handlers
public $noajax = true;
// skip frames
public $noframe = true;
function init()
{
- $rcmail = rcmail::get_instance();
-
$this->add_texts('localization/', false);
// register task
$this->register_task('help');
// register actions
$this->register_action('index', array($this, 'action'));
$this->register_action('about', array($this, 'action'));
$this->register_action('license', array($this, 'action'));
// add taskbar button
$this->add_button(array(
'command' => 'help',
'class' => 'button-help',
'classsel' => 'button-help button-selected',
'innerclass' => 'button-inner',
'label' => 'help.help',
), 'taskbar');
// add style for taskbar button (must be here) and Help UI
$skin_path = $this->local_skin_path();
if (is_file($this->home . "/$skin_path/help.css")) {
$this->include_stylesheet("$skin_path/help.css");
}
}
function action()
{
$rcmail = rcmail::get_instance();
$this->load_config();
// register UI objects
$rcmail->output->add_handlers(array(
'helpcontent' => array($this, 'content'),
));
if ($rcmail->action == 'about')
$rcmail->output->set_pagetitle($this->gettext('about'));
else if ($rcmail->action == 'license')
$rcmail->output->set_pagetitle($this->gettext('license'));
else
$rcmail->output->set_pagetitle($this->gettext('help'));
$rcmail->output->send('help.help');
}
function content($attrib)
{
$rcmail = rcmail::get_instance();
if ($rcmail->action == 'about') {
return @file_get_contents($this->home.'/content/about.html');
}
else if ($rcmail->action == 'license') {
return @file_get_contents($this->home.'/content/license.html');
}
// default content: iframe
if ($src = $rcmail->config->get('help_source'))
$attrib['src'] = $src;
if (empty($attrib['id']))
$attrib['id'] = 'rcmailhelpcontent';
$attrib['name'] = $attrib['id'];
return $rcmail->output->frame($attrib);
}
}
diff --git a/plugins/managesieve/lib/Roundcube/rcube_sieve_script.php b/plugins/managesieve/lib/Roundcube/rcube_sieve_script.php
index 80f590f4b..0e95b0fba 100644
--- a/plugins/managesieve/lib/Roundcube/rcube_sieve_script.php
+++ b/plugins/managesieve/lib/Roundcube/rcube_sieve_script.php
@@ -1,1155 +1,1153 @@
<?php
/**
* Class for operations on Sieve scripts
*
* 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.
*/
class rcube_sieve_script
{
public $content = array(); // script rules array
private $vars = array(); // "global" variables
private $prefix = ''; // script header (comments)
private $supported = array( // Sieve extensions supported by class
'fileinto', // RFC5228
'envelope', // RFC5228
'reject', // RFC5429
'ereject', // RFC5429
'copy', // RFC3894
'vacation', // RFC5230
'vacation-seconds', // RFC6131
'relational', // RFC3431
'regex', // draft-ietf-sieve-regex-01
'imapflags', // draft-melnikov-sieve-imapflags-06
'imap4flags', // RFC5232
'include', // draft-ietf-sieve-include-12
'variables', // RFC5229
'body', // RFC5173
'subaddress', // RFC5233
'enotify', // RFC5435
'notify', // draft-ietf-sieve-notify-00
// @TODO: spamtest+virustest, mailbox, date
);
/**
* Object constructor
*
* @param string Script's text content
* @param array List of capabilities supported by server
*/
public function __construct($script, $capabilities=array())
{
$capabilities = array_map('strtolower', (array) $capabilities);
// disable features by server capabilities
if (!empty($capabilities)) {
foreach ($this->supported as $idx => $ext) {
if (!in_array($ext, $capabilities)) {
unset($this->supported[$idx]);
}
}
}
// Parse text content of the script
$this->_parse_text($script);
}
/**
* Adds rule to the script (at the end)
*
* @param string Rule name
* @param array Rule content (as array)
*
* @return int The index of the new rule
*/
public function add_rule($content)
{
// TODO: check this->supported
array_push($this->content, $content);
return sizeof($this->content)-1;
}
public function delete_rule($index)
{
if(isset($this->content[$index])) {
unset($this->content[$index]);
return true;
}
return false;
}
public function size()
{
return sizeof($this->content);
}
public function update_rule($index, $content)
{
// TODO: check this->supported
if ($this->content[$index]) {
$this->content[$index] = $content;
return $index;
}
return false;
}
/**
* Sets "global" variable
*
* @param string $name Variable name
* @param string $value Variable value
* @param array $mods Variable modifiers
*/
public function set_var($name, $value, $mods = array())
{
// Check if variable exists
for ($i=0, $len=count($this->vars); $i<$len; $i++) {
if ($this->vars[$i]['name'] == $name) {
break;
}
}
$var = array_merge($mods, array('name' => $name, 'value' => $value));
$this->vars[$i] = $var;
}
/**
* Unsets "global" variable
*
* @param string $name Variable name
*/
public function unset_var($name)
{
// Check if variable exists
foreach ($this->vars as $idx => $var) {
if ($var['name'] == $name) {
unset($this->vars[$idx]);
break;
}
}
}
/**
* Gets the value of "global" variable
*
* @param string $name Variable name
*
* @return string Variable value
*/
public function get_var($name)
{
// Check if variable exists
for ($i=0, $len=count($this->vars); $i<$len; $i++) {
if ($this->vars[$i]['name'] == $name) {
return $this->vars[$i]['name'];
}
}
}
/**
* Sets script header content
*
* @param string $text Header content
*/
public function set_prefix($text)
{
$this->prefix = $text;
}
/**
* Returns script as text
*/
public function as_text()
{
$output = '';
$exts = array();
$idx = 0;
if (!empty($this->vars)) {
if (in_array('variables', (array)$this->supported)) {
$has_vars = true;
array_push($exts, 'variables');
}
foreach ($this->vars as $var) {
if (empty($has_vars)) {
// 'variables' extension not supported, put vars in comments
$output .= sprintf("# %s %s\n", $var['name'], $var['value']);
}
else {
$output .= 'set ';
foreach (array_diff(array_keys($var), array('name', 'value')) as $opt) {
$output .= ":$opt ";
}
$output .= self::escape_string($var['name']) . ' ' . self::escape_string($var['value']) . ";\n";
}
}
}
$imapflags = in_array('imap4flags', $this->supported) ? 'imap4flags' : 'imapflags';
$notify = in_array('enotify', $this->supported) ? 'enotify' : 'notify';
// rules
foreach ($this->content as $rule) {
- $extension = '';
$script = '';
$tests = array();
$i = 0;
// header
if (!empty($rule['name']) && strlen($rule['name'])) {
$script .= '# rule:[' . $rule['name'] . "]\n";
}
// constraints expressions
if (!empty($rule['tests'])) {
foreach ($rule['tests'] as $test) {
$tests[$i] = '';
switch ($test['test']) {
case 'size':
$tests[$i] .= ($test['not'] ? 'not ' : '');
$tests[$i] .= 'size :' . ($test['type']=='under' ? 'under ' : 'over ') . $test['arg'];
break;
case 'true':
$tests[$i] .= ($test['not'] ? 'false' : 'true');
break;
case 'exists':
$tests[$i] .= ($test['not'] ? 'not ' : '');
$tests[$i] .= 'exists ' . self::escape_string($test['arg']);
break;
case 'header':
$tests[$i] .= ($test['not'] ? 'not ' : '');
$tests[$i] .= 'header';
if (!empty($test['type'])) {
// relational operator + comparator
if (preg_match('/^(value|count)-([gteqnl]{2})/', $test['type'], $m)) {
array_push($exts, 'relational');
array_push($exts, 'comparator-i;ascii-numeric');
$tests[$i] .= ' :' . $m[1] . ' "' . $m[2] . '" :comparator "i;ascii-numeric"';
}
else {
$this->add_comparator($test, $tests[$i], $exts);
if ($test['type'] == 'regex') {
array_push($exts, 'regex');
}
$tests[$i] .= ' :' . $test['type'];
}
}
$tests[$i] .= ' ' . self::escape_string($test['arg1']);
$tests[$i] .= ' ' . self::escape_string($test['arg2']);
break;
case 'address':
case 'envelope':
if ($test['test'] == 'envelope') {
array_push($exts, 'envelope');
}
$tests[$i] .= ($test['not'] ? 'not ' : '');
$tests[$i] .= $test['test'];
if (!empty($test['part'])) {
$tests[$i] .= ' :' . $test['part'];
if ($test['part'] == 'user' || $test['part'] == 'detail') {
array_push($exts, 'subaddress');
}
}
$this->add_comparator($test, $tests[$i], $exts);
if (!empty($test['type'])) {
if ($test['type'] == 'regex') {
array_push($exts, 'regex');
}
$tests[$i] .= ' :' . $test['type'];
}
$tests[$i] .= ' ' . self::escape_string($test['arg1']);
$tests[$i] .= ' ' . self::escape_string($test['arg2']);
break;
case 'body':
array_push($exts, 'body');
$tests[$i] .= ($test['not'] ? 'not ' : '') . 'body';
$this->add_comparator($test, $tests[$i], $exts);
if (!empty($test['part'])) {
$tests[$i] .= ' :' . $test['part'];
if (!empty($test['content']) && $test['part'] == 'content') {
$tests[$i] .= ' ' . self::escape_string($test['content']);
}
}
if (!empty($test['type'])) {
if ($test['type'] == 'regex') {
array_push($exts, 'regex');
}
$tests[$i] .= ' :' . $test['type'];
}
$tests[$i] .= ' ' . self::escape_string($test['arg']);
break;
}
$i++;
}
}
// disabled rule: if false #....
if (!empty($tests)) {
$script .= 'if ' . ($rule['disabled'] ? 'false # ' : '');
if (count($tests) > 1) {
$tests_str = implode(', ', $tests);
}
else {
$tests_str = $tests[0];
}
if ($rule['join'] || count($tests) > 1) {
$script .= sprintf('%s (%s)', $rule['join'] ? 'allof' : 'anyof', $tests_str);
}
else {
$script .= $tests_str;
}
$script .= "\n{\n";
}
// action(s)
if (!empty($rule['actions'])) {
foreach ($rule['actions'] as $action) {
$action_script = '';
switch ($action['type']) {
case 'fileinto':
array_push($exts, 'fileinto');
$action_script .= 'fileinto ';
if ($action['copy']) {
$action_script .= ':copy ';
array_push($exts, 'copy');
}
$action_script .= self::escape_string($action['target']);
break;
case 'redirect':
$action_script .= 'redirect ';
if ($action['copy']) {
$action_script .= ':copy ';
array_push($exts, 'copy');
}
$action_script .= self::escape_string($action['target']);
break;
case 'reject':
case 'ereject':
array_push($exts, $action['type']);
$action_script .= $action['type'].' '
. self::escape_string($action['target']);
break;
case 'addflag':
case 'setflag':
case 'removeflag':
array_push($exts, $imapflags);
$action_script .= $action['type'].' '
. self::escape_string($action['target']);
break;
case 'keep':
case 'discard':
case 'stop':
$action_script .= $action['type'];
break;
case 'include':
array_push($exts, 'include');
$action_script .= 'include ';
foreach (array_diff(array_keys($action), array('target', 'type')) as $opt) {
$action_script .= ":$opt ";
}
$action_script .= self::escape_string($action['target']);
break;
case 'set':
array_push($exts, 'variables');
$action_script .= 'set ';
foreach (array_diff(array_keys($action), array('name', 'value', 'type')) as $opt) {
$action_script .= ":$opt ";
}
$action_script .= self::escape_string($action['name']) . ' ' . self::escape_string($action['value']);
break;
case 'notify':
array_push($exts, $notify);
$action_script .= 'notify';
// Here we support only 00 version of notify draft, there
// were a couple regressions in 00 to 04 changelog, we use
// the version used by Cyrus
if ($notify == 'notify') {
switch ($action['importance']) {
case 1: $action_script .= " :high"; break;
case 2: $action_script .= " :normal"; break;
case 3: $action_script .= " :low"; break;
}
unset($action['importance']);
}
foreach (array('from', 'importance', 'options', 'message') as $n_tag) {
if (!empty($action[$n_tag])) {
$action_script .= " :$n_tag " . self::escape_string($action[$n_tag]);
}
}
if (!empty($action['address'])) {
$method = 'mailto:' . $action['address'];
if (!empty($action['body'])) {
$method .= '?body=' . rawurlencode($action['body']);
}
}
else {
$method = $action['method'];
}
// method is optional in notify extension
if (!empty($method)) {
$action_script .= ($notify == 'notify' ? " :method " : " ") . self::escape_string($method);
}
break;
case 'vacation':
array_push($exts, 'vacation');
$action_script .= 'vacation';
if (isset($action['seconds'])) {
array_push($exts, 'vacation-seconds');
$action_script .= " :seconds " . intval($action['seconds']);
}
else if (!empty($action['days'])) {
$action_script .= " :days " . intval($action['days']);
}
if (!empty($action['addresses']))
$action_script .= " :addresses " . self::escape_string($action['addresses']);
if (!empty($action['subject']))
$action_script .= " :subject " . self::escape_string($action['subject']);
if (!empty($action['handle']))
$action_script .= " :handle " . self::escape_string($action['handle']);
if (!empty($action['from']))
$action_script .= " :from " . self::escape_string($action['from']);
if (!empty($action['mime']))
$action_script .= " :mime";
$action_script .= " " . self::escape_string($action['reason']);
break;
}
if ($action_script) {
$script .= !empty($tests) ? "\t" : '';
$script .= $action_script . ";\n";
}
}
}
if ($script) {
$output .= $script . (!empty($tests) ? "}\n" : '');
$idx++;
}
}
// requires
if (!empty($exts)) {
$exts = array_unique($exts);
if (in_array('vacation-seconds', $exts) && ($key = array_search('vacation', $exts)) !== false) {
unset($exts[$key]);
}
$output = 'require ["' . implode('","', $exts) . "\"];\n" . $output;
}
if (!empty($this->prefix)) {
$output = $this->prefix . "\n\n" . $output;
}
return $output;
}
/**
* Returns script object
*
*/
public function as_array()
{
return $this->content;
}
/**
* Returns array of supported extensions
*
*/
public function get_extensions()
{
return array_values($this->supported);
}
/**
* Converts text script to rules array
*
* @param string Text script
*/
private function _parse_text($script)
{
$prefix = '';
$options = array();
while ($script) {
$script = trim($script);
$rule = array();
// Comments
while (!empty($script) && $script[0] == '#') {
$endl = strpos($script, "\n");
$line = $endl ? substr($script, 0, $endl) : $script;
// Roundcube format
if (preg_match('/^# rule:\[(.*)\]/', $line, $matches)) {
$rulename = $matches[1];
}
// KEP:14 variables
else if (preg_match('/^# (EDITOR|EDITOR_VERSION) (.+)$/', $line, $matches)) {
$this->set_var($matches[1], $matches[2]);
}
// Horde-Ingo format
else if (!empty($options['format']) && $options['format'] == 'INGO'
&& preg_match('/^# (.*)/', $line, $matches)
) {
$rulename = $matches[1];
}
else if (empty($options['prefix'])) {
$prefix .= $line . "\n";
}
$script = ltrim(substr($script, strlen($line) + 1));
}
// handle script header
if (empty($options['prefix'])) {
$options['prefix'] = true;
if ($prefix && strpos($prefix, 'horde.org/ingo')) {
$options['format'] = 'INGO';
}
}
// Control structures/blocks
if (preg_match('/^(if|else|elsif)/i', $script)) {
$rule = $this->_tokenize_rule($script);
if (strlen($rulename) && !empty($rule)) {
$rule['name'] = $rulename;
}
}
// Simple commands
else {
$rule = $this->_parse_actions($script, ';');
if (!empty($rule[0]) && is_array($rule)) {
// set "global" variables
if ($rule[0]['type'] == 'set') {
unset($rule[0]['type']);
$this->vars[] = $rule[0];
}
else {
$rule = array('actions' => $rule);
}
}
}
$rulename = '';
if (!empty($rule)) {
$this->content[] = $rule;
}
}
if (!empty($prefix)) {
$this->prefix = trim($prefix);
}
}
/**
* Convert text script fragment to rule object
*
* @param string Text rule
*
* @return array Rule data
*/
private function _tokenize_rule(&$content)
{
$cond = strtolower(self::tokenize($content, 1));
if ($cond != 'if' && $cond != 'elsif' && $cond != 'else') {
return null;
}
$disabled = false;
$join = false;
// disabled rule (false + comment): if false # .....
if (preg_match('/^\s*false\s+#/i', $content)) {
$content = preg_replace('/^\s*false\s+#\s*/i', '', $content);
$disabled = true;
}
while (strlen($content)) {
$tokens = self::tokenize($content, true);
$separator = array_pop($tokens);
if (!empty($tokens)) {
$token = array_shift($tokens);
}
else {
$token = $separator;
}
$token = strtolower($token);
if ($token == 'not') {
$not = true;
$token = strtolower(array_shift($tokens));
}
else {
$not = false;
}
switch ($token) {
case 'allof':
$join = true;
break;
case 'anyof':
break;
case 'size':
$size = array('test' => 'size', 'not' => $not);
for ($i=0, $len=count($tokens); $i<$len; $i++) {
if (!is_array($tokens[$i])
&& preg_match('/^:(under|over)$/i', $tokens[$i])
) {
$size['type'] = strtolower(substr($tokens[$i], 1));
}
else {
$size['arg'] = $tokens[$i];
}
}
$tests[] = $size;
break;
case 'header':
$header = array('test' => 'header', 'not' => $not, 'arg1' => '', 'arg2' => '');
for ($i=0, $len=count($tokens); $i<$len; $i++) {
if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) {
$header['comparator'] = $tokens[++$i];
}
else if (!is_array($tokens[$i]) && preg_match('/^:(count|value)$/i', $tokens[$i])) {
$header['type'] = strtolower(substr($tokens[$i], 1)) . '-' . $tokens[++$i];
}
else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
$header['type'] = strtolower(substr($tokens[$i], 1));
}
else {
$header['arg1'] = $header['arg2'];
$header['arg2'] = $tokens[$i];
}
}
$tests[] = $header;
break;
case 'address':
case 'envelope':
$header = array('test' => $token, 'not' => $not, 'arg1' => '', 'arg2' => '');
for ($i=0, $len=count($tokens); $i<$len; $i++) {
if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) {
$header['comparator'] = $tokens[++$i];
}
else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
$header['type'] = strtolower(substr($tokens[$i], 1));
}
else if (!is_array($tokens[$i]) && preg_match('/^:(localpart|domain|all|user|detail)$/i', $tokens[$i])) {
$header['part'] = strtolower(substr($tokens[$i], 1));
}
else {
$header['arg1'] = $header['arg2'];
$header['arg2'] = $tokens[$i];
}
}
$tests[] = $header;
break;
case 'body':
$header = array('test' => 'body', 'not' => $not, 'arg' => '');
for ($i=0, $len=count($tokens); $i<$len; $i++) {
if (!is_array($tokens[$i]) && preg_match('/^:comparator$/i', $tokens[$i])) {
$header['comparator'] = $tokens[++$i];
}
else if (!is_array($tokens[$i]) && preg_match('/^:(is|contains|matches|regex)$/i', $tokens[$i])) {
$header['type'] = strtolower(substr($tokens[$i], 1));
}
else if (!is_array($tokens[$i]) && preg_match('/^:(raw|content|text)$/i', $tokens[$i])) {
$header['part'] = strtolower(substr($tokens[$i], 1));
if ($header['part'] == 'content') {
$header['content'] = $tokens[++$i];
}
}
else {
$header['arg'] = $tokens[$i];
}
}
$tests[] = $header;
break;
case 'exists':
$tests[] = array('test' => 'exists', 'not' => $not,
'arg' => array_pop($tokens));
break;
case 'true':
$tests[] = array('test' => 'true', 'not' => $not);
break;
case 'false':
$tests[] = array('test' => 'true', 'not' => !$not);
break;
}
// goto actions...
if ($separator == '{') {
break;
}
}
// ...and actions block
$actions = $this->_parse_actions($content);
if ($tests && $actions) {
$result = array(
'type' => $cond,
'tests' => $tests,
'actions' => $actions,
'join' => $join,
'disabled' => $disabled,
);
}
return $result;
}
/**
* Parse body of actions section
*
* @param string $content Text body
* @param string $end End of text separator
*
* @return array Array of parsed action type/target pairs
*/
private function _parse_actions(&$content, $end = '}')
{
$result = null;
while (strlen($content)) {
$tokens = self::tokenize($content, true);
$separator = array_pop($tokens);
if (!empty($tokens)) {
$token = array_shift($tokens);
}
else {
$token = $separator;
}
switch ($token) {
case 'discard':
case 'keep':
case 'stop':
$result[] = array('type' => $token);
break;
case 'fileinto':
case 'redirect':
$copy = false;
$target = '';
for ($i=0, $len=count($tokens); $i<$len; $i++) {
if (strtolower($tokens[$i]) == ':copy') {
$copy = true;
}
else {
$target = $tokens[$i];
}
}
$result[] = array('type' => $token, 'copy' => $copy,
'target' => $target);
break;
case 'reject':
case 'ereject':
$result[] = array('type' => $token, 'target' => array_pop($tokens));
break;
case 'vacation':
$vacation = array('type' => 'vacation', 'reason' => array_pop($tokens));
for ($i=0, $len=count($tokens); $i<$len; $i++) {
$tok = strtolower($tokens[$i]);
if ($tok == ':mime') {
$vacation['mime'] = true;
}
else if ($tok[0] == ':') {
$vacation[substr($tok, 1)] = $tokens[++$i];
}
}
$result[] = $vacation;
break;
case 'setflag':
case 'addflag':
case 'removeflag':
$result[] = array('type' => $token,
// Flags list: last token (skip optional variable)
'target' => $tokens[count($tokens)-1]
);
break;
case 'include':
$include = array('type' => 'include', 'target' => array_pop($tokens));
// Parameters: :once, :optional, :global, :personal
for ($i=0, $len=count($tokens); $i<$len; $i++) {
$tok = strtolower($tokens[$i]);
if ($tok[0] == ':') {
$include[substr($tok, 1)] = true;
}
}
$result[] = $include;
break;
case 'set':
$set = array('type' => 'set', 'value' => array_pop($tokens), 'name' => array_pop($tokens));
// Parameters: :lower :upper :lowerfirst :upperfirst :quotewildcard :length
for ($i=0, $len=count($tokens); $i<$len; $i++) {
$tok = strtolower($tokens[$i]);
if ($tok[0] == ':') {
$set[substr($tok, 1)] = true;
}
}
$result[] = $set;
break;
case 'require':
// skip, will be build according to used commands
// $result[] = array('type' => 'require', 'target' => $tokens);
break;
case 'notify':
$notify = array('type' => 'notify');
$priorities = array(':high' => 1, ':normal' => 2, ':low' => 3);
// Parameters: :from, :importance, :options, :message
// additional (optional) :method parameter for notify extension
for ($i=0, $len=count($tokens); $i<$len; $i++) {
$tok = strtolower($tokens[$i]);
if ($tok[0] == ':') {
// Here we support only 00 version of notify draft, there
// were a couple regressions in 00 to 04 changelog, we use
// the version used by Cyrus
if (isset($priorities[$tok])) {
$notify['importance'] = $priorities[$tok];
}
else {
$notify[substr($tok, 1)] = $tokens[++$i];
}
}
else {
// unnamed parameter is a :method in enotify extension
$notify['method'] = $tokens[$i];
}
}
$method_components = parse_url($notify['method']);
if ($method_components['scheme'] == 'mailto') {
$notify['address'] = $method_components['path'];
$method_params = array();
if (array_key_exists('query', $method_components)) {
parse_str($method_components['query'], $method_params);
}
$method_params = array_change_key_case($method_params, CASE_LOWER);
// magic_quotes_gpc and magic_quotes_sybase affect the output of parse_str
if (ini_get('magic_quotes_gpc') || ini_get('magic_quotes_sybase')) {
array_map('stripslashes', $method_params);
}
$notify['body'] = (array_key_exists('body', $method_params)) ? $method_params['body'] : '';
}
$result[] = $notify;
break;
}
if ($separator == $end)
break;
}
return $result;
}
/**
*
*/
private function add_comparator($test, &$out, &$exts)
{
if (empty($test['comparator'])) {
return;
}
if ($test['comparator'] == 'i;ascii-numeric') {
array_push($exts, 'relational');
array_push($exts, 'comparator-i;ascii-numeric');
}
else if (!in_array($test['comparator'], array('i;octet', 'i;ascii-casemap'))) {
array_push($exts, 'comparator-' . $test['comparator']);
}
// skip default comparator
if ($test['comparator'] != 'i;ascii-casemap') {
$out .= ' :comparator ' . self::escape_string($test['comparator']);
}
}
/**
* Escape special chars into quoted string value or multi-line string
* or list of strings
*
* @param string $str Text or array (list) of strings
*
* @return string Result text
*/
static function escape_string($str)
{
if (is_array($str) && count($str) > 1) {
foreach($str as $idx => $val)
$str[$idx] = self::escape_string($val);
return '[' . implode(',', $str) . ']';
}
else if (is_array($str)) {
$str = array_pop($str);
}
// multi-line string
if (preg_match('/[\r\n\0]/', $str) || strlen($str) > 1024) {
return sprintf("text:\n%s\n.\n", self::escape_multiline_string($str));
}
// quoted-string
else {
return '"' . addcslashes($str, '\\"') . '"';
}
}
/**
* Escape special chars in multi-line string value
*
* @param string $str Text
*
* @return string Text
*/
static function escape_multiline_string($str)
{
$str = preg_split('/(\r?\n)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($str as $idx => $line) {
// dot-stuffing
if (isset($line[0]) && $line[0] == '.') {
$str[$idx] = '.' . $line;
}
}
return implode($str);
}
/**
* Splits script into string tokens
*
* @param string &$str The script
* @param mixed $num Number of tokens to return, 0 for all
* or True for all tokens until separator is found.
* Separator will be returned as last token.
- * @param int $in_list Enable to call recursively inside a list
*
* @return mixed Tokens array or string if $num=1
*/
- static function tokenize(&$str, $num=0, $in_list=false)
+ static function tokenize(&$str, $num=0)
{
$result = array();
// remove spaces from the beginning of the string
while (($str = ltrim($str)) !== ''
&& (!$num || $num === true || count($result) < $num)
) {
switch ($str[0]) {
// Quoted string
case '"':
$len = strlen($str);
for ($pos=1; $pos<$len; $pos++) {
if ($str[$pos] == '"') {
break;
}
if ($str[$pos] == "\\") {
if ($str[$pos + 1] == '"' || $str[$pos + 1] == "\\") {
$pos++;
}
}
}
if ($str[$pos] != '"') {
// error
}
// we need to strip slashes for a quoted string
$result[] = stripslashes(substr($str, 1, $pos - 1));
$str = substr($str, $pos + 1);
break;
// Parenthesized list
case '[':
$str = substr($str, 1);
- $result[] = self::tokenize($str, 0, true);
+ $result[] = self::tokenize($str, 0);
break;
case ']':
$str = substr($str, 1);
return $result;
break;
// list/test separator
case ',':
// command separator
case ';':
// block/tests-list
case '(':
case ')':
case '{':
case '}':
$sep = $str[0];
$str = substr($str, 1);
if ($num === true) {
$result[] = $sep;
break 2;
}
break;
// bracket-comment
case '/':
if ($str[1] == '*') {
if ($end_pos = strpos($str, '*/')) {
$str = substr($str, $end_pos + 2);
}
else {
// error
$str = '';
}
}
break;
// hash-comment
case '#':
if ($lf_pos = strpos($str, "\n")) {
$str = substr($str, $lf_pos);
break;
}
else {
$str = '';
}
// String atom
default:
// empty or one character
if ($str === '' || $str === null) {
break 2;
}
if (strlen($str) < 2) {
$result[] = $str;
$str = '';
break;
}
// tag/identifier/number
if (preg_match('/^([a-z0-9:_]+)/i', $str, $m)) {
$str = substr($str, strlen($m[1]));
if ($m[1] != 'text:') {
$result[] = $m[1];
}
// multiline string
else {
// possible hash-comment after "text:"
if (preg_match('/^( |\t)*(#[^\n]+)?\n/', $str, $m)) {
$str = substr($str, strlen($m[0]));
}
// get text until alone dot in a line
if (preg_match('/^(.*)\r?\n\.\r?\n/sU', $str, $m)) {
$text = $m[1];
// remove dot-stuffing
$text = str_replace("\n..", "\n.", $text);
$str = substr($str, strlen($m[0]));
}
else {
$text = '';
}
$result[] = $text;
}
}
// fallback, skip one character as infinite loop prevention
else {
$str = substr($str, 1);
}
break;
}
}
return $num === 1 ? (isset($result[0]) ? $result[0] : null) : $result;
}
}
diff --git a/plugins/managesieve/managesieve.php b/plugins/managesieve/managesieve.php
index 817fa8650..fc2a79ddb 100644
--- a/plugins/managesieve/managesieve.php
+++ b/plugins/managesieve/managesieve.php
@@ -1,2059 +1,2059 @@
<?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.2';
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_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 = 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;
}
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 = 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) 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = $this->rc->gettext(array('name' => 'filesizeerror',
'vars' => array('size' =>
$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(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 = 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);
$intervals = rcube_utils::get_input_value('_action_interval', rcube_utils::INPUT_POST);
$interval_types = rcube_utils::get_input_value('_action_interval_type', 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], false, false);
$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 (!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]);
$interval_type = $interval_types[$idx] == 'seconds' ? 'seconds' : 'days';
$this->form['actions'][$i]['reason'] = str_replace("\r\n", "\n", $reason);
$this->form['actions'][$i]['subject'] = $subject[$idx];
$this->form['actions'][$i]['addresses'] = explode(',', $addresses[$idx]);
$this->form['actions'][$i][$interval_type] = $intervals[$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(!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][$interval_type] && !preg_match('/^[0-9]+$/', $this->form['actions'][$i][$interval_type]))
$this->errors['actions'][$i]['interval'] = $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 (!rcube_utils::check_email($notifyaddrs[$idx])) {
$this->errors['actions'][$i]['address'] = $this->gettext('noemailwarning');
}
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' => 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 = $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' => rcube::Q($set),
'id' => 'S'.$idx,
'class' => !in_array($set, $this->active) ? 'disabled' : '',
);
}
}
// create XHTML table
$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 = 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', 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', 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', 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', 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 = 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, 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, rcube::Q($this->gettext('filterset')),
$this->filtersets_list(array('id' => 'sievescriptname'), true));
}
$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, 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, 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, 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>' . 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(rcube::Q($this->gettext($name)), Q($val));
if (in_array('body', $this->exts))
$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="' .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(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(rcube::Q($this->gettext('filterregex')), 'regex');
$select_op->add(rcube::Q($this->gettext('filternotregex')), 'notregex');
}
if (in_array('relational', $this->exts)) {
$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="' .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(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') .' />
<label><input type="radio" name="_rule_size_item['.$id.']" value=""'
. (!$sizeitem ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('B').'</label>
<label><input type="radio" name="_rule_size_item['.$id.']" value="K"'
. ($sizeitem=='K' ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('KB').'</label>
<label><input type="radio" name="_rule_size_item['.$id.']" value="M"'
. ($sizeitem=='M' ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('MB').'</label>
<label><input type="radio" name="_rule_size_item['.$id.']" value="G"'
. ($sizeitem=='G' ? ' checked="checked"' : '') .' class="radio" />'.$this->rc->gettext('GB').'</label>';
$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(rcube::Q($this->gettext('none')), '');
$select_mod->add(rcube::Q($this->gettext('address')), 'address');
if (in_array('envelope', $this->exts))
$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(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(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 .= 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 .= 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(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 .= 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(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(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 .= 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="'. 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="'. rcube::Q($this->gettext('add')). '"
onclick="rcmail.managesieve_ruleadd(' . $id .')" class="button add"></a>';
$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(rcube::Q($this->gettext('messagemoveto')), 'fileinto');
if (in_array('fileinto', $this->exts) && in_array('copy', $this->exts))
$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(rcube::Q($this->gettext('messagesendcopy')), 'redirect_copy');
if (in_array('reject', $this->exts))
$select_action->add(rcube::Q($this->gettext('messagediscard')), 'reject');
else if (in_array('ereject', $this->exts))
$select_action->add(rcube::Q($this->gettext('messagediscard')), 'ereject');
if (in_array('vacation', $this->exts))
$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(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(rcube::Q($this->gettext('setvariable')), 'set');
}
if (in_array('enotify', $this->exts) || in_array('notify', $this->exts)) {
$select_action->add(rcube::Q($this->gettext('notify')), 'notify');
}
$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' ? 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')) ? rcube::Q($action['target'], 'strict', false) : '')
. "</textarea>\n";
// vacation
$vsec = in_array('vacation-seconds', $this->exts);
$out .= '<div id="action_vacation' .$id.'" style="display:' .($action['type']=='vacation' ? 'inline' : 'none') .'">';
$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">' .rcube::Q($this->gettext('vacationsubject')) . '</span><br />'
.'<input type="text" name="_action_subject['.$id.']" id="action_subject'.$id.'" '
.'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">' .rcube::Q($this->gettext('vacationaddresses')) . '</span><br />'
.'<input type="text" name="_action_addresses['.$id.']" id="action_addr'.$id.'" '
.'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">' . rcube::Q($this->gettext($vsec ? 'vacationinterval' : 'vacationdays')) . '</span><br />'
.'<input type="text" name="_action_interval['.$id.']" id="action_interval'.$id.'" '
.'value="' .rcube::Q(isset($action['seconds']) ? $action['seconds'] : $action['days'], 'strict', false) . '" size="2" '
. $this->error_class($id, 'action', 'interval', 'action_interval') .' />';
if ($vsec) {
$out .= '&nbsp;<label><input type="radio" name="_action_interval_type['.$id.']" value="days"'
. (!isset($action['seconds']) ? ' checked="checked"' : '') .' class="radio" />'.$this->gettext('days').'</label>'
. '&nbsp;<label><input type="radio" name="_action_interval_type['.$id.']" value="seconds"'
. (isset($action['seconds']) ? ' checked="checked"' : '') .' class="radio" />'.$this->gettext('seconds').'</label>';
}
$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"' : '') . ' />'
. 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">' .rcube::Q($this->gettext('setvarname')) . '</span><br />'
.'<input type="text" name="_action_varname['.$id.']" id="action_varname'.$id.'" '
.'value="' . rcube::Q($action['name']) . '" size="35" '
. $this->error_class($id, 'action', 'name', 'action_varname') .' />';
$out .= '<br /><span class="label">' .rcube::Q($this->gettext('setvarvalue')) . '</span><br />'
.'<input type="text" name="_action_varvalue['.$id.']" id="action_varvalue'.$id.'" '
.'value="' . rcube::Q($action['value']) . '" size="35" '
. $this->error_class($id, 'action', 'value', 'action_varvalue') .' />';
$out .= '<br /><span class="label">' .rcube::Q($this->gettext('setvarmodifiers')) . '</span><br />';
- foreach ($set_modifiers as $j => $s_m) {
+ foreach ($set_modifiers as $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"' : ''),
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">' .rcube::Q($this->gettext('notifyaddress')) . '</span><br />'
.'<input type="text" name="_action_notifyaddress['.$id.']" id="action_notifyaddress'.$id.'" '
.'value="' . rcube::Q($action['address']) . '" size="35" '
. $this->error_class($id, 'action', 'address', 'action_notifyaddress') .' />';
$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') . '>'
. 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="' . rcube::Q($action['message']) . '" size="35" '
. $this->error_class($id, 'action', 'message', 'action_notifymessage') .' />';
$out .= '<br /><span class="label">' .rcube::Q($this->gettext('notifyfrom')) . '</span><br />'
.'<input type="text" name="_action_notifyfrom['.$id.']" id="action_notifyfrom'.$id.'" '
.'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(rcube::Q($this->gettext($io_n)), $io_v);
}
$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 = $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="'. rcube::Q($this->gettext('add')). '"
onclick="rcmail.managesieve_actionadd(' . $id .')" class="button add"></a>';
$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()
{
return preg_replace('/[^0-9]/', '', microtime(true));
}
private function strip_value($str, $allow_html = false, $trim = true)
{
if (!$allow_html) {
$str = strip_tags($str);
}
return $trim ? trim($str) : $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 = 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');
if ($replace_delimiter && $replace_delimiter != $delimiter)
$mailbox = str_replace($replace_delimiter, $delimiter, $mailbox);
}
else {
$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) {
+ if ($user_script && 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) {
+ foreach ($rules['actions'] as $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) {
+ foreach ($rules['actions'] as $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' => rcube::Q($fname),
'class' => $filter['disabled'] ? 'disabled' : '',
);
$i++;
}
return $result;
}
}
diff --git a/plugins/new_user_identity/new_user_identity.php b/plugins/new_user_identity/new_user_identity.php
index f98145b6c..d32051e00 100644
--- a/plugins/new_user_identity/new_user_identity.php
+++ b/plugins/new_user_identity/new_user_identity.php
@@ -1,86 +1,84 @@
<?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_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/password/drivers/directadmin.php b/plugins/password/drivers/directadmin.php
index 8bf0dc613..44ecea406 100644
--- a/plugins/password/drivers/directadmin.php
+++ b/plugins/password/drivers/directadmin.php
@@ -1,489 +1,488 @@
<?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
//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/sql.php b/plugins/password/drivers/sql.php
index de9ea0a3f..7a51dfe44 100644
--- a/plugins/password/drivers/sql.php
+++ b/plugins/password/drivers/sql.php
@@ -1,200 +1,201 @@
<?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())
+ if ($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')) {
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_utils::idn_to_ascii($domain_part);
$username = rcube_utils::idn_to_ascii($username);
$host = rcube_utils::idn_to_ascii($host);
}
else {
$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($sql),0,6)) == 'select') {
- if ($result = $db->fetch_array($res))
+ if ($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/xmail.php b/plugins/password/drivers/xmail.php
index 37abc3001..59e467c5b 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()) {
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();
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) != "+") {
+ if (substr(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) != "+") {
+ if (substr(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/squirrelmail_usercopy/squirrelmail_usercopy.php b/plugins/squirrelmail_usercopy/squirrelmail_usercopy.php
index d5d0d47ec..e882a2f37 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);
+ $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 (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);
}
/* 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);
if ($rec['name'] && $rec['email'])
$this->abook[] = $rec;
}
} // end if 'sql'-driver
}
}
diff --git a/plugins/vcard_attachments/vcard_attachments.php b/plugins/vcard_attachments/vcard_attachments.php
index 4905b373e..cf7e22d3a 100644
--- a/plugins/vcard_attachments/vcard_attachments.php
+++ b/plugins/vcard_attachments/vcard_attachments.php
@@ -1,228 +1,227 @@
<?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) {
+ foreach ((array)$this->message->parts as $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('" . rcube::JQ($part.':'.$idx) . "')",
'title' => $this->gettext('addvcardmsg'),
),
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 = 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_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/zipdownload/zipdownload.php b/plugins/zipdownload/zipdownload.php
index 7e132bfbb..fbf1d2342 100644
--- a/plugins/zipdownload/zipdownload.php
+++ b/plugins/zipdownload/zipdownload.php
@@ -1,272 +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->load_config();
$this->charset = $rcmail->config->get('zipdownload_charset', RCUBE_CHARSET);
$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)) {
$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(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(",", 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'], 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) {
+ foreach ($a_headers as $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){
+ foreach ($uids as $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;
$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 = RCUBE_CHARSET)
{
$str = rcube_charset::convert($str, $from == '' ? RCUBE_CHARSET : $from, $this->charset);
return strtr($str, array(':'=>'', '/'=>'-'));
}
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, Mar 1, 8:14 AM (1 d, 12 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
166386
Default Alt Text
(270 KB)

Event Timeline