Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F9785582
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Size
224 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/INSTALL b/INSTALL
index efe060499..0c7e7cbbf 100644
--- a/INSTALL
+++ b/INSTALL
@@ -1,98 +1,108 @@
REQUIREMENTS
============
* The Apache Webserver
* .htaccess support allowing overrides for DirectoryIndex
* PHP Version 4.3.1 or greater
* PCRE (perl compatible regular expression) installed with PHP
* php.ini options:
- error_reporting E_ALL & ~E_NOTICE (or lower)
- file_uploads on (for attachment upload features)
- memory_limit (increase as suitable to support large attachments)
* A MySQL or PostgreSQL database engine or the SQLite extension for PHP
* A database with permission to create tables
INSTALLATION
============
1. Decompress and put this folder somewhere inside your document root
2. Make sure that the following directories (and the files within)
are writable by the webserver
- /temp
- /logs
3. Create a new database and a database user for RoundCube (see DATABASE SETUP)
4. Create database tables using the queries in file 'SQL/*.initial.sql'
(* stands for your database type)
5. Rename the files config/*.inc.php.dist to config/*.inc.php
6. Modify the files in config/* to suit your local environment
7. Done!
DATABASE SETUP
==============
-* MySQL
--------
+* MySQL 4.0.x
+-------------
Setting up the mysql database can be done by creating an empty database,
importing the table layout and granting the proper permissions to the
roundcube user. Here is an example of that procedure:
# mysql
> CREATE DATABASE 'roundcubemail';
> GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@localhost
IDENTIFIED BY 'password';
> quit
# mysql roundcubemail < SQL/mysql.initial.sql
+
+* MySQL 4.1.x/5.x
+-----------------
For MySQL version 4.1 and up, it's recommended to create the database for
-RoundCube with the following command:
+RoundCube with utf-8 charset. Here's an example of the init procedure:
+
+# mysql
> CREATE DATABASE 'roundcubemail' DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
+> GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@localhost
+ IDENTIFIED BY 'password';
+> quit
+
+# mysql roundcubemail < SQL/mysql5.initial.sql
* SQLite
--------
Sqlite requires specifically php5 (sqlite in php4 currently doesn't
work with roundcube), and you need sqlite 2 (preferably 2.8) to setup
the sqlite db (sqlite 3.x also doesn't work at the moment). Here is
an example how you can setup the sqlite.db for roundcube:
# sqlite -init SQL/sqlite.initial.sql sqlite.db
Make sure your configuration points to the sqlite.db file and that the
webserver can write to the file.
* PostgreSQL
------------
To use RoundCube with PostgreSQL support you have to follow the next
simple steps, which have to be done with the postgres system user (or
which ever is the database superuser):
$ createuser roundcubemail
$ createdb -O roundcubemail roundcubemail
$ psql roundcubemail
roundcubemail =# ALTER USER roundcube WITH PASSWORD 'the_new_password';
roundcubemail =# \c - roundcubemail
roundcubemail => \i SQL/postgres.initial.sql
All this has been tested with PostgreSQL 8.0.x and 7.4.x. Older
versions don't have a -O option for the createdb, so if you are
using that version you'll have to change ownership of the DB later.
CONFIGURATION
=============
Change the files in config/* according your to environment and your needs.
Details about the config paramaters can be found in the config files.
UPGRADING
=========
If you already have a previous version of RoundCube installed,
please refer to the instructions in UPGRADING guide.
diff --git a/SQL/mysql.initial.sql b/SQL/mysql.initial.sql
index 9e3ee2758..7546e52da 100644
--- a/SQL/mysql.initial.sql
+++ b/SQL/mysql.initial.sql
@@ -1,127 +1,127 @@
-- RoundCube Webmail initial database structure
--- Version 0.1b
+-- Version 0.1beta2
--
-- --------------------------------------------------------
--
-- Table structure for table `cache`
--
CREATE TABLE `cache` (
`cache_id` int(10) unsigned NOT NULL auto_increment,
`user_id` int(10) unsigned NOT NULL default '0',
`session_id` varchar(40) default NULL,
`cache_key` varchar(128) NOT NULL default '',
`created` datetime NOT NULL default '0000-00-00 00:00:00',
`data` longtext NOT NULL,
PRIMARY KEY (`cache_id`),
KEY `user_id` (`user_id`),
KEY `cache_key` (`cache_key`),
KEY `session_id` (`session_id`)
);
-- --------------------------------------------------------
--
-- Table structure for table `contacts`
--
CREATE TABLE `contacts` (
`contact_id` int(10) unsigned NOT NULL auto_increment,
`user_id` int(10) unsigned NOT NULL default '0',
`changed` datetime NOT NULL default '0000-00-00 00:00:00',
`del` tinyint(1) NOT NULL default '0',
`name` varchar(128) NOT NULL default '',
`email` varchar(128) NOT NULL default '',
`firstname` varchar(128) NOT NULL default '',
`surname` varchar(128) NOT NULL default '',
`vcard` text NOT NULL,
PRIMARY KEY (`contact_id`),
KEY `user_id` (`user_id`)
);
-- --------------------------------------------------------
--
-- Table structure for table `identities`
--
CREATE TABLE `identities` (
`identity_id` int(10) unsigned NOT NULL auto_increment,
`user_id` int(10) unsigned NOT NULL default '0',
`del` tinyint(1) NOT NULL default '0',
`standard` tinyint(1) NOT NULL default '0',
`name` varchar(128) NOT NULL default '',
`organization` varchar(128) NOT NULL default '',
`email` varchar(128) NOT NULL default '',
`reply-to` varchar(128) NOT NULL default '',
`bcc` varchar(128) NOT NULL default '',
`signature` text NOT NULL,
PRIMARY KEY (`identity_id`),
KEY `user_id` (`user_id`)
);
-- --------------------------------------------------------
--
-- Table structure for table `session`
--
CREATE TABLE `session` (
`sess_id` varchar(40) NOT NULL default '',
`created` datetime NOT NULL default '0000-00-00 00:00:00',
`changed` datetime NOT NULL default '0000-00-00 00:00:00',
`ip` VARCHAR(15) NOT NULL default '',
`vars` text NOT NULL,
PRIMARY KEY (`sess_id`)
);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`user_id` int(10) unsigned NOT NULL auto_increment,
`username` varchar(128) NOT NULL default '',
`mail_host` varchar(128) NOT NULL default '',
`alias` varchar(128) NOT NULL default '',
`created` datetime NOT NULL default '0000-00-00 00:00:00',
`last_login` datetime NOT NULL default '0000-00-00 00:00:00',
`language` varchar(5) NOT NULL default 'en',
`preferences` text NOT NULL default '',
PRIMARY KEY (`user_id`)
);
-- --------------------------------------------------------
--
-- Table structure for table `messages`
--
CREATE TABLE `messages` (
`message_id` int(11) unsigned NOT NULL auto_increment,
`user_id` int(11) unsigned NOT NULL default '0',
`del` tinyint(1) NOT NULL default '0',
`cache_key` varchar(128) NOT NULL default '',
`created` datetime NOT NULL default '0000-00-00 00:00:00',
`idx` int(11) unsigned NOT NULL default '0',
`uid` int(11) unsigned NOT NULL default '0',
`subject` varchar(255) NOT NULL default '',
`from` varchar(255) NOT NULL default '',
`to` varchar(255) NOT NULL default '',
`cc` varchar(255) NOT NULL default '',
`date` datetime NOT NULL default '0000-00-00 00:00:00',
`size` int(11) unsigned NOT NULL default '0',
`headers` text NOT NULL,
`body` longtext,
PRIMARY KEY (`message_id`),
KEY `user_id` (`user_id`),
KEY `cache_key` (`cache_key`),
KEY `idx` (`idx`),
KEY `uid` (`uid`)
);
diff --git a/SQL/mysql5.initial.sql b/SQL/mysql5.initial.sql
new file mode 100644
index 000000000..0116468ee
--- /dev/null
+++ b/SQL/mysql5.initial.sql
@@ -0,0 +1,126 @@
+-- RoundCube Webmail initial database structure
+-- Version 0.1beta2
+--
+
+-- --------------------------------------------------------
+
+SET FOREIGN_KEY_CHECKS=0;
+
+
+-- Table structure for table `session`
+
+CREATE TABLE `session` (
+ `sess_id` varchar(40) NOT NULL,
+ `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `changed` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `ip` varchar(15) NOT NULL,
+ `vars` text NOT NULL,
+ PRIMARY KEY(`sess_id`)
+) TYPE=MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
+
+
+-- Table structure for table `users`
+
+CREATE TABLE `users` (
+ `user_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `username` varchar(128) NOT NULL,
+ `mail_host` varchar(128) NOT NULL,
+ `alias` varchar(128) NOT NULL,
+ `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `last_login` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `language` varchar(5) NOT NULL DEFAULT 'en',
+ `preferences` text NOT NULL,
+ PRIMARY KEY(`user_id`)
+) TYPE=MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
+
+
+-- Table structure for table `messages`
+
+CREATE TABLE `messages` (
+ `message_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `del` tinyint(1) NOT NULL DEFAULT '0',
+ `cache_key` varchar(128) NOT NULL,
+ `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `idx` int(11) UNSIGNED NOT NULL DEFAULT '0',
+ `uid` int(11) UNSIGNED NOT NULL DEFAULT '0',
+ `subject` varchar(255) NOT NULL,
+ `from` varchar(255) NOT NULL,
+ `to` varchar(255) NOT NULL,
+ `cc` varchar(255) NOT NULL,
+ `date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `size` int(11) UNSIGNED NOT NULL DEFAULT '0',
+ `headers` text NOT NULL,
+ `body` longtext,
+ `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
+ PRIMARY KEY(`message_id`),
+ INDEX `cache_key`(`cache_key`),
+ INDEX `idx`(`idx`),
+ INDEX `uid`(`uid`),
+ CONSTRAINT `User_ID_FK_messages` FOREIGN KEY (`user_id`)
+ REFERENCES `users`(`user_id`)
+ ON DELETE CASCADE
+ ON UPDATE CASCADE
+) TYPE=MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
+
+
+-- Table structure for table `cache`
+
+CREATE TABLE `cache` (
+ `cache_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `session_id` varchar(40),
+ `cache_key` varchar(128) NOT NULL,
+ `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `data` longtext NOT NULL,
+ `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
+ PRIMARY KEY(`cache_id`),
+ INDEX `cache_key`(`cache_key`),
+ INDEX `session_id`(`session_id`),
+ CONSTRAINT `User_ID_FK_cache` FOREIGN KEY (`user_id`)
+ REFERENCES `users`(`user_id`)
+ ON DELETE CASCADE
+ ON UPDATE CASCADE
+) TYPE=MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
+
+
+-- Table structure for table `contacts`
+
+CREATE TABLE `contacts` (
+ `contact_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `changed` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
+ `del` tinyint(1) NOT NULL DEFAULT '0',
+ `name` varchar(128) NOT NULL,
+ `email` varchar(128) NOT NULL,
+ `firstname` varchar(128) NOT NULL,
+ `surname` varchar(128) NOT NULL,
+ `vcard` text NOT NULL,
+ `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
+ PRIMARY KEY(`contact_id`),
+ CONSTRAINT `User_ID_FK_contacts` FOREIGN KEY (`user_id`)
+ REFERENCES `users`(`user_id`)
+ ON DELETE CASCADE
+ ON UPDATE CASCADE
+) TYPE=MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
+
+
+-- Table structure for table `identities`
+
+CREATE TABLE `identities` (
+ `identity_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
+ `del` tinyint(1) NOT NULL DEFAULT '0',
+ `standard` tinyint(1) NOT NULL DEFAULT '0',
+ `name` varchar(128) NOT NULL,
+ `organization` varchar(128) NOT NULL,
+ `email` varchar(128) NOT NULL,
+ `reply-to` varchar(128) NOT NULL,
+ `bcc` varchar(128) NOT NULL,
+ `signature` text NOT NULL,
+ `user_id` int(10) UNSIGNED NOT NULL DEFAULT '0',
+ PRIMARY KEY(`identity_id`),
+ CONSTRAINT `User_ID_FK_identities` FOREIGN KEY (`user_id`)
+ REFERENCES `users`(`user_id`)
+ ON DELETE CASCADE
+ ON UPDATE CASCADE
+) TYPE=MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;
+
+
+SET FOREIGN_KEY_CHECKS=1;
\ No newline at end of file
diff --git a/UPGRADING b/UPGRADING
index fd0a857b4..bb8b36bab 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -1,133 +1,133 @@
UPDATE instructions
===================
Follow these instructions if upgrading from a previous version
of RoundCube Webmail.
from versions 0.1-alpha and 0.1-20050811
----------------------------------------
- replace index.php
- replace all files in folder /program/
- replace all files in folder /skins/default/
- run all commands in SQL/*.update.sql or re-initalize database with *.initial.sql
- add these line to /config/main.inc.php
$rcmail_config['trash_mbox'] = 'Trash';
$rcmail_config['default_imap_folders'] = array('INBOX', 'Drafts', 'Sent', 'Junk', 'Trash');
$rcmail_config['prefer_html'] = TRUE;
$rcmail_config['prettydate'] = TRUE;
$rcmail_config['smtp_port'] = 25;
$rcmail_config['default_port'] = 143;
$rcmail_config['session_lifetime'] = 20;
$rcmail_config['skip_deleted'] = FALSE;
$rcmail_config['message_sort_col'] = 'date';
$rcmail_config['message_sort_order'] = 'DESC';
$rcmail_config['log_dir'] = 'logs/';
$rcmail_config['temp_dir'] = 'temp/';
$rcmail_config['message_cache_lifetime'] = '10d';
- replace database properties (db_type, db_host, db_user, db_pass, $d_name)
in /config/db.inc.php with the following line:
$rcmail_config['db_dsnw'] = 'mysql://roundcube:pass@localhost/roundcubemail';
- add these lines to /config/db.inc.php
$rcmail_config['db_max_length'] = 512000;
from version 0.1-20050820
----------------------------------------
- replace index.php
- replace all files in folder /program/
- replace all files in folder /skins/default/
- run all commands in SQL/*.update.sql or re-initalize database with *.initial.sql
- add these line to /config/main.inc.php
$rcmail_config['prettydate'] = TRUE;
$rcmail_config['smtp_port'] = 25;
$rcmail_config['default_port'] = 143;
$rcmail_config['session_lifetime'] = 20;
$rcmail_config['skip_deleted'] = FALSE;
$rcmail_config['message_sort_col'] = 'date';
$rcmail_config['message_sort_order'] = 'DESC';
$rcmail_config['log_dir'] = 'logs/';
$rcmail_config['temp_dir'] = 'temp/';
$rcmail_config['message_cache_lifetime'] = '10d';
- replace database properties (db_type, db_host, db_user, db_pass, $d_name)
in /config/db.inc.php with the following line:
$rcmail_config['db_dsnw'] = 'mysql://roundcube:pass@localhost/roundcubemail';
- add these lines to /config/db.inc.php
$rcmail_config['db_max_length'] = 512000;
from version 0.1-20051007
----------------------------------------
- replace index.php
- replace all files in folder /program/
- replace all files in folder /skins/default/
- run all commands in SQL/*.update.sql or re-initalize database with *.initial.sql
- add these lines to /config/main.inc.php
$rcmail_config['smtp_auth_type'] = ''; // if you need to specify an auth method for SMTP
$rcmail_config['session_lifetime'] = 20; // to specify the session lifetime in minutes
$rcmail_config['skip_deleted'] = FALSE;
$rcmail_config['message_sort_col'] = 'date';
$rcmail_config['message_sort_order'] = 'DESC';
$rcmail_config['log_dir'] = 'logs/';
$rcmail_config['temp_dir'] = 'temp/';
$rcmail_config['message_cache_lifetime'] = '10d';
$rcmail_config['drafts_mbox'] = 'Drafts';
$rcmail_config['product_name'] = 'RoundCube Webmail';
$rcmail_config['read_when_deleted'] = TRUE;
$rcmail_config['enable_spellcheck'] = TRUE;
- add these lines to /config/db.inc.php
$rcmail_config['db_max_length'] = 512000;
$rcmail_config['db_sequence_user_ids'] = 'user_ids';
$rcmail_config['db_sequence_identity_ids'] = 'identity_ids';
$rcmail_config['db_sequence_contact_ids'] = 'contact_ids';
$rcmail_config['db_sequence_cache_ids'] = 'cache_ids';
$rcmail_config['db_sequence_message_ids'] = 'message_ids';
$rcmail_config['db_persistent'] = TRUE;
from version 0.1-20051021
----------------------------------------
- replace index.php
- replace all files in folder /program/
- replace all files in folder /skins/default/
- run all commands in SQL/*.update.sql or re-initalize database with *.initial.sql
- add these lines to /config/main.inc.php
$rcmail_config['skip_deleted'] = FALSE;
$rcmail_config['message_sort_col'] = 'date';
$rcmail_config['message_sort_order'] = 'DESC';
$rcmail_config['log_dir'] = 'logs/';
$rcmail_config['temp_dir'] = 'temp/';
$rcmail_config['message_cache_lifetime'] = '10d';
$rcmail_config['drafts_mbox'] = 'Drafts';
$rcmail_config['product_name'] = 'RoundCube Webmail';
$rcmail_config['read_when_deleted'] = TRUE;
$rcmail_config['enable_spellcheck'] = TRUE;
- add these lines to /config/db.inc.php
$rcmail_config['db_max_length'] = 512000;
$rcmail_config['db_sequence_user_ids'] = 'user_ids';
$rcmail_config['db_sequence_identity_ids'] = 'identity_ids';
$rcmail_config['db_sequence_contact_ids'] = 'contact_ids';
$rcmail_config['db_sequence_cache_ids'] = 'cache_ids';
$rcmail_config['db_sequence_message_ids'] = 'message_ids';
$rcmail_config['db_persistent'] = TRUE;
form version 0.1-beta
----------------------------------------
- replace index.php
- replace all files in folder /program/
- replace all files in folder /skins/default/
-- add these lines to /config/db.inc.php
+- add these line to /config/db.inc.php
$rcmail_config['db_persistent'] = TRUE;
- add these lines to /config/main.inc.php
$rcmail_config['drafts_mbox'] = 'Drafts';
$rcmail_config['junk_mbox'] = 'Junk';
$rcmail_config['product_name'] = 'RoundCube Webmail';
$rcmail_config['read_when_deleted'] = TRUE;
$rcmail_config['enable_spellcheck'] = TRUE;
$rcmail_config['protect_default_folders'] = TRUE;
- replace the following line from /config/main.inc.php
@include($_SERVER['HTTP_HOST'].'.inc.php');
with
$rcmail_config['include_host_config'] = TRUE;
diff --git a/index.php b/index.php
index c496b4dc9..313ca0bfd 100644
--- a/index.php
+++ b/index.php
@@ -1,366 +1,363 @@
<?php
/*
+-----------------------------------------------------------------------+
| RoundCube Webmail IMAP Client |
- | Version 0.1-20060718 |
+ | Version 0.1-beta2 |
| |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2006, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions |
| are met: |
| |
| o Redistributions of source code must retain the above copyright |
| notice, this list of conditions and the following disclaimer. |
| o Redistributions in binary form must reproduce the above copyright |
| notice, this list of conditions and the following disclaimer in the |
| documentation and/or other materials provided with the distribution.|
| o The names of the authors may not be used to endorse or promote |
| products derived from this software without specific prior written |
| permission. |
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-define('RCMAIL_VERSION', '0.1-20060718');
+define('RCMAIL_VERSION', '0.1-beta2');
// define global vars
$CHARSET = 'UTF-8';
$OUTPUT_TYPE = 'html';
$JS_OBJECT_NAME = 'rcmail';
$INSTALL_PATH = dirname(__FILE__);
$MAIN_TASKS = array('mail','settings','addressbook','logout');
if (empty($INSTALL_PATH))
$INSTALL_PATH = './';
else
$INSTALL_PATH .= '/';
// make sure path_separator is defined
if (!defined('PATH_SEPARATOR'))
define('PATH_SEPARATOR', (eregi('win', PHP_OS) ? ';' : ':'));
// RC include folders MUST be included FIRST to avoid other
// possible not compatible libraries (i.e PEAR) to be included
// instead the ones provided by RC
ini_set('include_path', $INSTALL_PATH.PATH_SEPARATOR.$INSTALL_PATH.'program'.PATH_SEPARATOR.$INSTALL_PATH.'program/lib'.PATH_SEPARATOR.ini_get('include_path'));
ini_set('session.name', 'sessid');
ini_set('session.use_cookies', 1);
ini_set('session.gc_maxlifetime', 21600);
ini_set('session.gc_divisor', 500);
ini_set('error_reporting', E_ALL&~E_NOTICE);
// increase maximum execution time for php scripts
// (does not work in safe mode)
@set_time_limit(120);
// include base files
require_once('include/rcube_shared.inc');
require_once('include/rcube_imap.inc');
require_once('include/bugs.inc');
require_once('include/main.inc');
require_once('include/cache.inc');
require_once('PEAR.php');
// set PEAR error handling
// PEAR::setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_NOTICE);
// use gzip compression if supported
if (function_exists('ob_gzhandler') && !ini_get('zlib.output_compression'))
ob_start('ob_gzhandler');
else
ob_start();
// catch some url/post parameters
-//$_auth = get_input_value('_auth', RCUBE_INPUT_GPC);
$_task = get_input_value('_task', RCUBE_INPUT_GPC);
$_action = get_input_value('_action', RCUBE_INPUT_GPC);
$_framed = (!empty($_GET['_framed']) || !empty($_POST['_framed']));
if (empty($_task))
$_task = 'mail';
if (!empty($_GET['_remote']))
$REMOTE_REQUEST = TRUE;
// start session with requested task
rcmail_startup($_task);
// set session related variables
$COMM_PATH = sprintf('./?_task=%s', $_task);
$SESS_HIDDEN_FIELD = '';
// add framed parameter
if ($_framed)
{
$COMM_PATH .= '&_framed=1';
$SESS_HIDDEN_FIELD .= "\n".'<input type="hidden" name="_framed" value="1" />';
}
// init necessary objects for GUI
load_gui();
// check DB connections and exit on failure
if ($err_str = $DB->is_error())
{
raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
'message' => $err_str), FALSE, TRUE);
}
// error steps
if ($_action=='error' && !empty($_GET['_code']))
{
raise_error(array('code' => hexdec($_GET['_code'])), FALSE, TRUE);
}
// try to log in
if ($_action=='login' && $_task=='mail')
{
$host = $_POST['_host'] ? $_POST['_host'] : $CONFIG['default_host'];
// check if client supports cookies
if (empty($_COOKIE))
{
show_message("cookiesdisabled", 'warning');
}
else if (isset($_POST['_user']) && isset($_POST['_pass']) &&
rcmail_login(get_input_value('_user', RCUBE_INPUT_POST), $_POST['_pass'], $host))
{
// send redirect
header("Location: $COMM_PATH");
exit;
}
else
{
show_message("loginfailed", 'warning');
$_SESSION['user_id'] = '';
}
}
// end session
else if ($_action=='logout' && isset($_SESSION['user_id']))
{
show_message('loggedout');
rcmail_kill_session();
}
// check session and auth cookie
else if ($_action!='login' && $_SESSION['user_id'])
{
if (!rcmail_authenticate_session() ||
($CONFIG['session_lifetime'] && isset($SESS_CHANGED) && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < mktime()))
{
$message = show_message('sessionerror', 'error');
rcmail_kill_session();
}
}
// log in to imap server
if (!empty($_SESSION['user_id']) && $_task=='mail')
{
$conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl']);
if (!$conn)
{
show_message('imaperror', 'error');
$_SESSION['user_id'] = '';
}
else
rcmail_set_imap_prop();
}
// not logged in -> set task to 'login
if (empty($_SESSION['user_id']))
{
if ($REMOTE_REQUEST)
{
$message .= "setTimeout(\"location.href='\"+this.env.comm_path+\"'\", 2000);";
rcube_remote_response($message);
}
$_task = 'login';
}
// set task and action to client
$script = sprintf("%s.set_env('task', '%s');", $JS_OBJECT_NAME, $_task);
if (!empty($_action))
$script .= sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $_action);
$OUTPUT->add_script($script);
// not logged in -> show login page
if (!$_SESSION['user_id'])
{
parse_template('login');
exit;
}
// handle keep-alive signal
if ($_action=='keep-alive')
{
rcube_remote_response('');
exit;
}
// include task specific files
if ($_task=='mail')
{
include_once('program/steps/mail/func.inc');
if ($_action=='show' || $_action=='print')
include('program/steps/mail/show.inc');
if ($_action=='get')
include('program/steps/mail/get.inc');
if ($_action=='moveto' || $_action=='delete')
include('program/steps/mail/move_del.inc');
if ($_action=='mark')
include('program/steps/mail/mark.inc');
if ($_action=='viewsource')
include('program/steps/mail/viewsource.inc');
if ($_action=='send')
include('program/steps/mail/sendmail.inc');
if ($_action=='upload')
include('program/steps/mail/upload.inc');
if ($_action=='compose' || $_action=='remove-attachment')
include('program/steps/mail/compose.inc');
if ($_action=='addcontact')
include('program/steps/mail/addcontact.inc');
if ($_action=='expunge' || $_action=='purge')
include('program/steps/mail/folders.inc');
if ($_action=='check-recent')
include('program/steps/mail/check_recent.inc');
if ($_action=='getunread')
include('program/steps/mail/getunread.inc');
if ($_action=='list' && isset($_GET['_remote']))
include('program/steps/mail/list.inc');
if ($_action=='search')
include('program/steps/mail/search.inc');
if ($_action=='spell')
include('program/steps/mail/spell.inc');
if ($_action=='rss')
include('program/steps/mail/rss.inc');
- // kill compose entry from session
-// if (isset($_SESSION['compose']))
-// rcmail_compose_cleanup();
-
+
// make sure the message count is refreshed
$IMAP->messagecount($_SESSION['mbox'], 'ALL', TRUE);
}
// include task specific files
if ($_task=='addressbook')
{
include_once('program/steps/addressbook/func.inc');
if ($_action=='save')
include('program/steps/addressbook/save.inc');
if ($_action=='edit' || $_action=='add')
include('program/steps/addressbook/edit.inc');
if ($_action=='delete')
include('program/steps/addressbook/delete.inc');
if ($_action=='show')
include('program/steps/addressbook/show.inc');
if ($_action=='list' && $_GET['_remote'])
include('program/steps/addressbook/list.inc');
if ($_action=='ldappublicsearch')
include('program/steps/addressbook/ldapsearchform.inc');
}
// include task specific files
if ($_task=='settings')
{
include_once('program/steps/settings/func.inc');
if ($_action=='save-identity')
include('program/steps/settings/save_identity.inc');
if ($_action=='add-identity' || $_action=='edit-identity')
include('program/steps/settings/edit_identity.inc');
if ($_action=='delete-identity')
include('program/steps/settings/delete_identity.inc');
if ($_action=='identities')
include('program/steps/settings/identities.inc');
if ($_action=='save-prefs')
include('program/steps/settings/save_prefs.inc');
- if ($_action=='folders' || $_action=='subscribe' || $_action=='unsubscribe' || $_action=='create-folder' || $_action=='rename-folder' || $_action=='delete-folder')
+ if ($_action=='folders' || $_action=='subscribe' || $_action=='unsubscribe' ||
+ $_action=='create-folder' || $_action=='rename-folder' || $_action=='delete-folder')
include('program/steps/settings/manage_folders.inc');
}
// parse main template
// only allow these templates to be included
if (in_array($_task, $MAIN_TASKS))
parse_template($_task);
// if we arrive here, something went wrong
raise_error(array('code' => 404,
'type' => 'php',
'line' => __LINE__,
'file' => __FILE__,
'message' => "Invalid request"), TRUE, TRUE);
?>
diff --git a/program/include/main.inc b/program/include/main.inc
index efac8b2d2..b7f28c4e4 100644
--- a/program/include/main.inc
+++ b/program/include/main.inc
@@ -1,1818 +1,1818 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/main.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Provide basic functions for the webmail package |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
require_once('lib/des.inc');
require_once('lib/utf7.inc');
require_once('lib/utf8.class.php');
// define constannts for input reading
define('RCUBE_INPUT_GET', 0x0101);
define('RCUBE_INPUT_POST', 0x0102);
define('RCUBE_INPUT_GPC', 0x0103);
// register session and connect to server
function rcmail_startup($task='mail')
{
global $sess_id, $sess_auth, $sess_user_lang;
global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
// check client
$BROWSER = rcube_browser();
// load config file
include_once('config/main.inc.php');
$CONFIG = is_array($rcmail_config) ? $rcmail_config : array();
// load host-specific configuration
rcmail_load_host_config($CONFIG);
$CONFIG['skin_path'] = $CONFIG['skin_path'] ? unslashify($CONFIG['skin_path']) : 'skins/default';
// load db conf
include_once('config/db.inc.php');
$CONFIG = array_merge($CONFIG, $rcmail_config);
if (empty($CONFIG['log_dir']))
$CONFIG['log_dir'] = $INSTALL_PATH.'logs';
else
$CONFIG['log_dir'] = unslashify($CONFIG['log_dir']);
// set PHP error logging according to config
if ($CONFIG['debug_level'] & 1)
{
ini_set('log_errors', 1);
ini_set('error_log', $CONFIG['log_dir'].'/errors');
}
if ($CONFIG['debug_level'] & 4)
ini_set('display_errors', 1);
else
ini_set('display_errors', 0);
// set session garbage collecting time according to session_lifetime
if (!empty($CONFIG['session_lifetime']))
ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']+2)*60);
// prepare DB connection
require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
$DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
$DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
$DB->db_connect('w');
// we can use the database for storing session data
if (!$DB->is_error())
include_once('include/session.inc');
// init session
session_start();
$sess_id = session_id();
// create session and set session vars
if (!isset($_SESSION['auth_time']))
{
$_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
$_SESSION['auth_time'] = mktime();
setcookie('sessauth', rcmail_auth_hash($sess_id, $_SESSION['auth_time']));
}
// set session vars global
$sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
// overwrite config with user preferences
if (is_array($_SESSION['user_prefs']))
$CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
// reset some session parameters when changing task
if ($_SESSION['task'] != $task)
unset($_SESSION['page']);
// set current task to session
$_SESSION['task'] = $task;
// create IMAP object
if ($task=='mail')
rcmail_imap_init();
// set localization
if ($CONFIG['locale_string'])
setlocale(LC_ALL, $CONFIG['locale_string']);
else if ($sess_user_lang)
setlocale(LC_ALL, $sess_user_lang);
register_shutdown_function('rcmail_shutdown');
}
// load a host-specific config file if configured
function rcmail_load_host_config(&$config)
{
$fname = NULL;
if (is_array($config['include_host_config']))
$fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
else if (!empty($config['include_host_config']))
$fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
if ($fname && is_file('config/'.$fname))
{
include('config/'.$fname);
$config = array_merge($config, $rcmail_config);
}
}
// create authorization hash
function rcmail_auth_hash($sess_id, $ts)
{
global $CONFIG;
$auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
$sess_id,
$ts,
$CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
$_SERVER['HTTP_USER_AGENT']);
if (function_exists('sha1'))
return sha1($auth_string);
else
return md5($auth_string);
}
// compare the auth hash sent by the client with the local session credentials
function rcmail_authenticate_session()
{
$now = mktime();
$valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']));
-
- // renew auth cookie every 5 minutes
- if (!$valid || ($now-$_SESSION['auth_time'] > 300))
+
+ // renew auth cookie every 5 minutes (only for GET requests)
+ if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
{
$_SESSION['auth_time'] = $now;
setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
}
return $valid;
}
// create IMAP object and connect to server
function rcmail_imap_init($connect=FALSE)
{
global $CONFIG, $DB, $IMAP;
$IMAP = new rcube_imap($DB);
$IMAP->debug_level = $CONFIG['debug_level'];
$IMAP->skip_deleted = $CONFIG['skip_deleted'];
// connect with stored session data
if ($connect)
{
if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
show_message('imaperror', 'error');
rcmail_set_imap_prop();
}
// enable caching of imap data
if ($CONFIG['enable_caching']===TRUE)
$IMAP->set_caching(TRUE);
// set pagesize from config
if (isset($CONFIG['pagesize']))
$IMAP->set_pagesize($CONFIG['pagesize']);
}
// set root dir and last stored mailbox
// this must be done AFTER connecting to the server
function rcmail_set_imap_prop()
{
global $CONFIG, $IMAP;
// set root dir from config
if (!empty($CONFIG['imap_root']))
$IMAP->set_rootdir($CONFIG['imap_root']);
if (is_array($CONFIG['default_imap_folders']))
$IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
if (!empty($_SESSION['mbox']))
$IMAP->set_mailbox($_SESSION['mbox']);
if (isset($_SESSION['page']))
$IMAP->set_page($_SESSION['page']);
}
// do these things on script shutdown
function rcmail_shutdown()
{
global $IMAP;
if (is_object($IMAP))
{
$IMAP->close();
$IMAP->write_cache();
}
// before closing the database connection, write session data
session_write_close();
}
// destroy session data and remove cookie
function rcmail_kill_session()
{
// save user preferences
$a_user_prefs = $_SESSION['user_prefs'];
if (!is_array($a_user_prefs))
$a_user_prefs = array();
if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
(isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
{
$a_user_prefs['message_sort_col'] = $_SESSION['sort_col'];
$a_user_prefs['message_sort_order'] = $_SESSION['sort_order'];
rcmail_save_user_prefs($a_user_prefs);
}
$_SESSION = array();
session_destroy();
}
// return correct name for a specific database table
function get_table_name($table)
{
global $CONFIG;
// return table name if configured
$config_key = 'db_table_'.$table;
if (strlen($CONFIG[$config_key]))
return $CONFIG[$config_key];
return $table;
}
// return correct name for a specific database sequence
// (used for Postres only)
function get_sequence_name($sequence)
{
global $CONFIG;
// return table name if configured
$config_key = 'db_sequence_'.$sequence;
if (strlen($CONFIG[$config_key]))
return $CONFIG[$config_key];
return $table;
}
// check the given string and returns language properties
function rcube_language_prop($lang, $prop='lang')
{
global $INSTALL_PATH;
static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
if (empty($rcube_languages))
@include($INSTALL_PATH.'program/localization/index.inc');
// check if we have an alias for that language
if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
$lang = $rcube_language_aliases[$lang];
// try the first two chars
if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
{
$lang = substr($lang, 0, 2);
$lang = rcube_language_prop($lang);
}
if (!isset($rcube_languages[$lang]))
$lang = 'en_US';
// language has special charset configured
if (isset($rcube_charsets[$lang]))
$charset = $rcube_charsets[$lang];
else
$charset = 'UTF-8';
if ($prop=='charset')
return $charset;
else
return $lang;
}
// init output object for GUI and add common scripts
function load_gui()
{
global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
// init output page
$OUTPUT = new rcube_html_page();
// add common javascripts
$javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
$javascript .= "$JS_OBJECT_NAME.set_env('comm_path', '$COMM_PATH');\n";
if (isset($CONFIG['javascript_config'] )){
foreach ($CONFIG['javascript_config'] as $js_config_var){
$javascript .= "$JS_OBJECT_NAME.set_env('$js_config_var', '" . $CONFIG[$js_config_var] . "');\n";
}
}
if (!empty($GLOBALS['_framed']))
$javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
$OUTPUT->add_script($javascript);
$OUTPUT->include_script('common.js');
$OUTPUT->include_script('app.js');
$OUTPUT->scripts_path = 'program/js/';
// set locale setting
rcmail_set_locale($sess_user_lang);
// set user-selected charset
if (!empty($CONFIG['charset']))
$OUTPUT->set_charset($CONFIG['charset']);
// add some basic label to client
rcube_add_label('loading','checkingmail');
}
// set localization charset based on the given language
function rcmail_set_locale($lang)
{
global $OUTPUT, $MBSTRING, $MBSTRING_ENCODING;
static $s_mbstring_loaded = NULL;
// settings for mbstring module (by Tadashi Jokagi)
if ($s_mbstring_loaded===NULL)
{
if ($s_mbstring_loaded = extension_loaded("mbstring"))
{
$MBSTRING = TRUE;
if (function_exists("mb_mbstring_encodings"))
$MBSTRING_ENCODING = mb_mbstring_encodings();
else
$MBSTRING_ENCODING = array("ISO-8859-1", "UTF-7", "UTF7-IMAP", "UTF-8",
"ISO-2022-JP", "EUC-JP", "EUCJP-WIN",
"SJIS", "SJIS-WIN");
$MBSTRING_ENCODING = array_map("strtoupper", $MBSTRING_ENCODING);
if (in_array("SJIS", $MBSTRING_ENCODING))
$MBSTRING_ENCODING[] = "SHIFT_JIS";
}
else
{
$MBSTRING = FALSE;
$MBSTRING_ENCODING = array();
}
}
if ($MBSTRING && function_exists("mb_language"))
{
if (!@mb_language(strtok($lang, "_")))
$MBSTRING = FALSE; // unsupport language
}
$OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
}
// perfom login to the IMAP server and to the webmail service
function rcmail_login($user, $pass, $host=NULL)
{
global $CONFIG, $IMAP, $DB, $sess_user_lang;
$user_id = NULL;
if (!$host)
$host = $CONFIG['default_host'];
// parse $host URL
$a_host = parse_url($host);
if ($a_host['host'])
{
$host = $a_host['host'];
$imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
$imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
}
else
$imap_port = $CONFIG['default_port'];
/* Modify username with domain if required
Inspired by Marco <P0L0_notspam_binware.org>
*/
// Check if we need to add domain
if ($CONFIG['username_domain'] && !strstr($user, '@'))
{
if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
$user .= '@'.$CONFIG['username_domain'][$host];
else if (!empty($CONFIG['username_domain']))
$user .= '@'.$CONFIG['username_domain'];
}
// query if user already registered
$sql_result = $DB->query("SELECT user_id, username, language, preferences
FROM ".get_table_name('users')."
WHERE mail_host=? AND (username=? OR alias=?)",
$host,
$user,
$user);
// user already registered -> overwrite username
if ($sql_arr = $DB->fetch_assoc($sql_result))
{
$user_id = $sql_arr['user_id'];
$user = $sql_arr['username'];
}
// try to resolve email address from virtuser table
if (!empty($CONFIG['virtuser_file']) && strstr($user, '@'))
$user = rcmail_email2user($user);
// exit if IMAP login failed
if (!($imap_login = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
return FALSE;
// user already registered
if ($user_id && !empty($sql_arr))
{
// get user prefs
if (strlen($sql_arr['preferences']))
{
$user_prefs = unserialize($sql_arr['preferences']);
$_SESSION['user_prefs'] = $user_prefs;
array_merge($CONFIG, $user_prefs);
}
// set user specific language
if (strlen($sql_arr['language']))
$sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
// update user's record
$DB->query("UPDATE ".get_table_name('users')."
SET last_login=now()
WHERE user_id=?",
$user_id);
}
// create new system user
else if ($CONFIG['auto_create_user'])
{
$user_id = rcmail_create_user($user, $host);
}
if ($user_id)
{
$_SESSION['user_id'] = $user_id;
$_SESSION['imap_host'] = $host;
$_SESSION['imap_port'] = $imap_port;
$_SESSION['imap_ssl'] = $imap_ssl;
$_SESSION['username'] = $user;
$_SESSION['user_lang'] = $sess_user_lang;
$_SESSION['password'] = encrypt_passwd($pass);
// force reloading complete list of subscribed mailboxes
rcmail_set_imap_prop();
$IMAP->clear_cache('mailboxes');
$IMAP->create_default_folders();
return TRUE;
}
return FALSE;
}
// create new entry in users and identities table
function rcmail_create_user($user, $host)
{
global $DB, $CONFIG, $IMAP;
$user_email = '';
// try to resolve user in virtusertable
if (!empty($CONFIG['virtuser_file']) && strstr($user, '@')==FALSE)
$user_email = rcmail_user2email($user);
$DB->query("INSERT INTO ".get_table_name('users')."
(created, last_login, username, mail_host, alias, language)
VALUES (now(), now(), ?, ?, ?, ?)",
$user,
$host,
$user_email,
$_SESSION['user_lang']);
if ($user_id = $DB->insert_id(get_sequence_name('users')))
{
$mail_domain = $host;
if (is_array($CONFIG['mail_domain']))
{
if (isset($CONFIG['mail_domain'][$host]))
$mail_domain = $CONFIG['mail_domain'][$host];
}
else if (!empty($CONFIG['mail_domain']))
$mail_domain = $CONFIG['mail_domain'];
if ($user_email=='')
$user_email = strstr($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
$user_name = $user!=$user_email ? $user : '';
// try to resolve the e-mail address from the virtuser table
if (!empty($CONFIG['virtuser_query']))
{
$sql_result = $DB->query(preg_replace('/%u/', $user, $CONFIG['virtuser_query']));
if ($sql_arr = $DB->fetch_array($sql_result))
$user_email = $sql_arr[0];
}
// also create new identity records
$DB->query("INSERT INTO ".get_table_name('identities')."
(user_id, del, standard, name, email)
VALUES (?, 0, 1, ?, ?)",
$user_id,
$user_name,
$user_email);
// get existing mailboxes
$a_mailboxes = $IMAP->list_mailboxes();
}
else
{
raise_error(array('code' => 500,
'type' => 'php',
'line' => __LINE__,
'file' => __FILE__,
'message' => "Failed to create new user"), TRUE, FALSE);
}
return $user_id;
}
// load virtuser table in array
function rcmail_getvirtualfile()
{
global $CONFIG;
if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
return FALSE;
// read file
$a_lines = file($CONFIG['virtuser_file']);
return $a_lines;
}
// find matches of the given pattern in virtuser table
function rcmail_findinvirtual($pattern)
{
$result = array();
$virtual = rcmail_getvirtualfile();
if ($virtual==FALSE)
return $result;
// check each line for matches
foreach ($virtual as $line)
{
$line = trim($line);
if (empty($line) || $line{0}=='#')
continue;
if (eregi($pattern, $line))
$result[] = $line;
}
return $result;
}
// resolve username with virtuser table
function rcmail_email2user($email)
{
$user = $email;
$r = rcmail_findinvirtual("^$email");
for ($i=0; $i<count($r); $i++)
{
$data = $r[$i];
$arr = preg_split('/\s+/', $data);
if(count($arr)>0)
{
$user = trim($arr[count($arr)-1]);
break;
}
}
return $user;
}
// resolve e-mail address with virtuser table
function rcmail_user2email($user)
{
$email = "";
$r = rcmail_findinvirtual("$user$");
for ($i=0; $i<count($r); $i++)
{
$data=$r[$i];
$arr = preg_split('/\s+/', $data);
if (count($arr)>0)
{
$email = trim($arr[0]);
break;
}
}
return $email;
}
function rcmail_save_user_prefs($a_user_prefs)
{
global $DB, $CONFIG, $sess_user_lang;
$DB->query("UPDATE ".get_table_name('users')."
SET preferences=?,
language=?
WHERE user_id=?",
serialize($a_user_prefs),
$sess_user_lang,
$_SESSION['user_id']);
if ($DB->affected_rows())
{
$_SESSION['user_prefs'] = $a_user_prefs;
$CONFIG = array_merge($CONFIG, $a_user_prefs);
return TRUE;
}
return FALSE;
}
// overwrite action variable
function rcmail_overwrite_action($action)
{
global $OUTPUT, $JS_OBJECT_NAME;
$GLOBALS['_action'] = $action;
$OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $action));
}
function show_message($message, $type='notice', $vars=NULL)
{
global $OUTPUT, $JS_OBJECT_NAME, $REMOTE_REQUEST;
$framed = $GLOBALS['_framed'];
$command = sprintf("display_message('%s', '%s');",
addslashes(rep_specialchars_output(rcube_label(array('name' => $message, 'vars' => $vars)))),
$type);
if ($REMOTE_REQUEST)
return 'this.'.$command;
else
$OUTPUT->add_script(sprintf("%s%s.%s\n",
$framed ? sprintf('if(parent.%s)parent.', $JS_OBJECT_NAME) : '',
$JS_OBJECT_NAME,
$command));
// console(rcube_label($message));
}
function console($msg, $type=1)
{
if ($GLOBALS['REMOTE_REQUEST'])
print "// $msg\n";
else
{
print $msg;
print "\n<hr>\n";
}
}
// encrypt IMAP password using DES encryption
function encrypt_passwd($pass)
{
$cypher = des(get_des_key(), $pass, 1, 0, NULL);
return base64_encode($cypher);
}
// decrypt IMAP password using DES encryption
function decrypt_passwd($cypher)
{
$pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
return preg_replace('/\x00/', '', $pass);
}
// return a 24 byte key for the DES encryption
function get_des_key()
{
$key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
$len = strlen($key);
// make sure the key is exactly 24 chars long
if ($len<24)
$key .= str_repeat('_', 24-$len);
else if ($len>24)
substr($key, 0, 24);
return $key;
}
// send correct response on a remote request
function rcube_remote_response($js_code, $flush=FALSE)
{
global $OUTPUT, $CHARSET;
static $s_header_sent = FALSE;
if (!$s_header_sent)
{
$s_header_sent = TRUE;
send_nocacheing_headers();
header('Content-Type: application/x-javascript; charset='.$CHARSET);
print '/** remote response ['.date('d/M/Y h:i:s O')."] **/\n";
}
// send response code
print rcube_charset_convert($js_code, $CHARSET, $OUTPUT->get_charset());
if ($flush) // flush the output buffer
flush();
else // terminate script
exit;
}
// send correctly formatted response for a request posted to an iframe
function rcube_iframe_response($js_code='')
{
global $OUTPUT, $JS_OBJECT_NAME;
if (!empty($js_code))
$OUTPUT->add_script("if(parent.$JS_OBJECT_NAME){\n" . $js_code . "\n}");
$OUTPUT->write();
exit;
}
// read directory program/localization/ and return a list of available languages
function rcube_list_languages()
{
global $CONFIG, $INSTALL_PATH;
static $sa_languages = array();
if (!sizeof($sa_languages))
{
@include($INSTALL_PATH.'program/localization/index.inc');
if ($dh = @opendir($INSTALL_PATH.'program/localization'))
{
while (($name = readdir($dh)) !== false)
{
if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
continue;
if ($label = $rcube_languages[$name])
$sa_languages[$name] = $label ? $label : $name;
}
closedir($dh);
}
}
return $sa_languages;
}
// add a localized label to the client environment
function rcube_add_label()
{
global $OUTPUT, $JS_OBJECT_NAME;
$arg_list = func_get_args();
foreach ($arg_list as $i => $name)
$OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
$JS_OBJECT_NAME,
$name,
rep_specialchars_output(rcube_label($name), 'js')));
}
// remove temp files of a session
function rcmail_clear_session_temp($sess_id)
{
global $CONFIG;
$temp_dir = slashify($CONFIG['temp_dir']);
$cache_dir = $temp_dir.$sess_id;
if (is_dir($cache_dir))
{
clear_directory($cache_dir);
rmdir($cache_dir);
}
}
// remove all expired message cache records
function rcmail_message_cache_gc()
{
global $DB, $CONFIG;
// no cache lifetime configured
if (empty($CONFIG['message_cache_lifetime']))
return;
// get target timestamp
$ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
$DB->query("DELETE FROM ".get_table_name('messages')."
WHERE created < ".$DB->fromunixtime($ts));
}
// convert a string from one charset to another
// this function is not complete and not tested well
function rcube_charset_convert($str, $from, $to=NULL)
{
global $MBSTRING, $MBSTRING_ENCODING;
$from = strtoupper($from);
$to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
if ($from==$to)
return $str;
// convert charset using mbstring module
if ($MBSTRING)
{
$to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
$from = $from=="UTF-7" ? "UTF7-IMAP": $from;
if (in_array($to, $MBSTRING_ENCODING) && in_array($from, $MBSTRING_ENCODING))
return mb_convert_encoding($str, $to, $from);
}
// convert charset using iconv module
if (function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7')
return iconv($from, $to, $str);
$conv = new utf8();
// convert string to UTF-8
if ($from=='UTF-7')
$str = rcube_charset_convert(UTF7DecodeString($str), 'ISO-8859-1');
else if ($from=='ISO-8859-1' && function_exists('utf8_encode'))
$str = utf8_encode($str);
else if ($from!='UTF-8')
{
$conv->loadCharset($from);
$str = $conv->strToUtf8($str);
}
// encode string for output
if ($to=='UTF-7')
return UTF7EncodeString($str);
else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
return utf8_decode($str);
else if ($to!='UTF-8')
{
$conv->loadCharset($to);
return $conv->utf8ToStr($str);
}
// return UTF-8 string
return $str;
}
// replace specials characters to a specific encoding type
function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
{
global $OUTPUT_TYPE, $OUTPUT;
static $html_encode_arr, $js_rep_table, $rtf_rep_table, $xml_rep_table;
if (!$enctype)
$enctype = $GLOBALS['OUTPUT_TYPE'];
// convert nbsps back to normal spaces if not html
if ($enctype!='html')
$str = str_replace(chr(160), ' ', $str);
// encode for plaintext
if ($enctype=='text')
return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
// encode for HTML output
if ($enctype=='html')
{
if (!$html_encode_arr)
{
$html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
unset($html_encode_arr['?']);
unset($html_encode_arr['&']);
}
$ltpos = strpos($str, '<');
$encode_arr = $html_encode_arr;
// don't replace quotes and html tags
if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
{
unset($encode_arr['"']);
unset($encode_arr['<']);
unset($encode_arr['>']);
}
else if ($mode=='remove')
$str = strip_tags($str);
$out = strtr($str, $encode_arr);
return $newlines ? nl2br($out) : $out;
}
if ($enctype=='url')
return rawurlencode($str);
// if the replace tables for RTF, XML and JS are not yet defined
if (!$js_rep_table)
{
$js_rep_table = $rtf_rep_table = $xml_rep_table = array();
$xml_rep_table['&'] = '&';
for ($c=160; $c<256; $c++) // can be increased to support more charsets
{
$hex = dechex($c);
$rtf_rep_table[Chr($c)] = "\\'$hex";
$xml_rep_table[Chr($c)] = "&#$c;";
if ($OUTPUT->get_charset()=='ISO-8859-1')
$js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
}
$js_rep_table['"'] = sprintf("\u%s%s", str_repeat('0', 4-strlen(dechex(34))), dechex(34));
$xml_rep_table['"'] = '"';
}
// encode for RTF
if ($enctype=='xml')
return strtr($str, $xml_rep_table);
// encode for javascript use
if ($enctype=='js')
{
if ($OUTPUT->get_charset()!='UTF-8')
$str = rcube_charset_convert($str, $GLOBALS['CHARSET'], $OUTPUT->get_charset());
return preg_replace(array("/\r\n/", '/"/', "/([^\\\])'/"), array('\n', '\"', "$1\'"), strtr($str, $js_rep_table));
}
// encode for RTF
if ($enctype=='rtf')
return preg_replace("/\r\n/", "\par ", strtr($str, $rtf_rep_table));
// no encoding given -> return original string
return $str;
}
/**
* Read input value and convert it for internal use
* Performs stripslashes() and charset conversion if necessary
*
* @param string Field name to read
* @param int Source to get value from (GPC)
* @param boolean Allow HTML tags in field value
* @param string Charset to convert into
* @return string Field value or NULL if not available
*/
function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
{
global $OUTPUT;
$value = NULL;
if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
$value = $_GET[$fname];
else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
$value = $_POST[$fname];
else if ($source==RCUBE_INPUT_GPC)
{
if (isset($_POST[$fname]))
$value = $_POST[$fname];
else if (isset($_GET[$fname]))
$value = $_GET[$fname];
else if (isset($_COOKIE[$fname]))
$value = $_COOKIE[$fname];
}
// strip slashes if magic_quotes enabled
if ((bool)get_magic_quotes_gpc())
$value = stripslashes($value);
// remove HTML tags if not allowed
if (!$allow_html)
$value = strip_tags($value);
// convert to internal charset
if (is_object($OUTPUT))
return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
else
return $value;
}
// ************** template parsing and gui functions **************
// return boolean if a specific template exists
function template_exists($name)
{
global $CONFIG, $OUTPUT;
$skin_path = $CONFIG['skin_path'];
// check template file
return is_file("$skin_path/templates/$name.html");
}
// get page template an replace variable
// similar function as used in nexImage
function parse_template($name='main', $exit=TRUE)
{
global $CONFIG, $OUTPUT;
$skin_path = $CONFIG['skin_path'];
// read template file
$templ = '';
$path = "$skin_path/templates/$name.html";
if($fp = @fopen($path, 'r'))
{
$templ = fread($fp, filesize($path));
fclose($fp);
}
else
{
raise_error(array('code' => 500,
'type' => 'php',
'line' => __LINE__,
'file' => __FILE__,
'message' => "Error loading template for '$name'"), TRUE, TRUE);
return FALSE;
}
// parse for specialtags
$output = parse_rcube_xml($templ);
$OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
if ($exit)
exit;
}
// replace all strings ($varname) with the content of the according global variable
function parse_with_globals($input)
{
$GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
$output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
return $output;
}
function parse_rcube_xml($input)
{
$output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
return $output;
}
function rcube_xml_command($command, $str_attrib, $add_attrib=array())
{
global $IMAP, $CONFIG, $OUTPUT;
$command = strtolower($command);
$attrib = parse_attrib_string($str_attrib) + $add_attrib;
// execute command
switch ($command)
{
// return a button
case 'button':
if ($attrib['command'])
return rcube_button($attrib);
break;
// show a label
case 'label':
if ($attrib['name'] || $attrib['command'])
return rep_specialchars_output(rcube_label($attrib));
break;
// create a menu item
case 'menu':
if ($attrib['command'] && $attrib['group'])
rcube_menu($attrib);
break;
// include a file
case 'include':
$path = realpath($CONFIG['skin_path'].$attrib['file']);
if($fp = @fopen($path, 'r'))
{
$incl = fread($fp, filesize($path));
fclose($fp);
return parse_rcube_xml($incl);
}
break;
// return code for a specific application object
case 'object':
$object = strtolower($attrib['name']);
$object_handlers = array(
// GENERAL
'loginform' => 'rcmail_login_form',
'username' => 'rcmail_current_username',
// MAIL
'mailboxlist' => 'rcmail_mailbox_list',
'message' => 'rcmail_message_container',
'messages' => 'rcmail_message_list',
'messagecountdisplay' => 'rcmail_messagecount_display',
'quotadisplay' => 'rcmail_quota_display',
'messageheaders' => 'rcmail_message_headers',
'messagebody' => 'rcmail_message_body',
'messageattachments' => 'rcmail_message_attachments',
'blockedobjects' => 'rcmail_remote_objects_msg',
'messagecontentframe' => 'rcmail_messagecontent_frame',
'messagepartframe' => 'rcmail_message_part_frame',
'messagepartcontrols' => 'rcmail_message_part_controls',
'composeheaders' => 'rcmail_compose_headers',
'composesubject' => 'rcmail_compose_subject',
'composebody' => 'rcmail_compose_body',
'composeattachmentlist' => 'rcmail_compose_attachment_list',
'composeattachmentform' => 'rcmail_compose_attachment_form',
'composeattachment' => 'rcmail_compose_attachment_field',
'priorityselector' => 'rcmail_priority_selector',
'charsetselector' => 'rcmail_charset_selector',
'searchform' => 'rcmail_search_form',
'receiptcheckbox' => 'rcmail_receipt_checkbox',
// ADDRESS BOOK
'addresslist' => 'rcmail_contacts_list',
'addressframe' => 'rcmail_contact_frame',
'recordscountdisplay' => 'rcmail_rowcount_display',
'contactdetails' => 'rcmail_contact_details',
'contacteditform' => 'rcmail_contact_editform',
'ldappublicsearch' => 'rcmail_ldap_public_search_form',
'ldappublicaddresslist' => 'rcmail_ldap_public_list',
// USER SETTINGS
'userprefs' => 'rcmail_user_prefs_form',
'itentitieslist' => 'rcmail_identities_list',
'identityframe' => 'rcmail_identity_frame',
'identityform' => 'rcube_identity_form',
'foldersubscription' => 'rcube_subscription_form',
'createfolder' => 'rcube_create_folder_form',
'renamefolder' => 'rcube_rename_folder_form',
'composebody' => 'rcmail_compose_body'
);
// execute object handler function
if ($object_handlers[$object] && function_exists($object_handlers[$object]))
return call_user_func($object_handlers[$object], $attrib);
else if ($object=='productname')
{
$name = !empty($CONFIG['product_name']) ? $CONFIG['product_name'] : 'RoundCube Webmail';
return rep_specialchars_output($name, 'html', 'all');
}
else if ($object=='version')
{
return (string)RCMAIL_VERSION;
}
else if ($object=='pagetitle')
{
$task = $GLOBALS['_task'];
$title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
if ($task=='login')
$title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $CONFIG['product_name'])));
else if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
$title .= $GLOBALS['MESSAGE']['subject'];
else if (isset($GLOBALS['PAGE_TITLE']))
$title .= $GLOBALS['PAGE_TITLE'];
else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
$title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
else
$title .= ucfirst($task);
return rep_specialchars_output($title, 'html', 'all');
}
break;
}
return '';
}
// create and register a button
function rcube_button($attrib)
{
global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER, $COMM_PATH, $MAIN_TASKS;
static $sa_buttons = array();
static $s_button_count = 100;
// these commands can be called directly via url
$a_static_commands = array('compose', 'list');
$skin_path = $CONFIG['skin_path'];
if (!($attrib['command'] || $attrib['name']))
return '';
// try to find out the button type
if ($attrib['type'])
$attrib['type'] = strtolower($attrib['type']);
else
$attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imageact']) ? 'image' : 'link';
$command = $attrib['command'];
// take the button from the stack
if($attrib['name'] && $sa_buttons[$attrib['name']])
$attrib = $sa_buttons[$attrib['name']];
// add button to button stack
else if($attrib['image'] || $arg['imageact'] || $attrib['imagepas'] || $attrib['class'])
{
if(!$attrib['name'])
$attrib['name'] = $command;
if (!$attrib['image'])
$attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
$sa_buttons[$attrib['name']] = $attrib;
}
// get saved button for this command/name
else if ($command && $sa_buttons[$command])
$attrib = $sa_buttons[$command];
//else
// return '';
// set border to 0 because of the link arround the button
if ($attrib['type']=='image' && !isset($attrib['border']))
$attrib['border'] = 0;
if (!$attrib['id'])
$attrib['id'] = sprintf('rcmbtn%d', $s_button_count++);
// get localized text for labels and titles
if ($attrib['title'])
$attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
if ($attrib['label'])
$attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
if ($attrib['alt'])
$attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
// set title to alt attribute for IE browsers
if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
{
$attrib['alt'] = $attrib['title'];
unset($attrib['title']);
}
// add empty alt attribute for XHTML compatibility
if (!isset($attrib['alt']))
$attrib['alt'] = '';
// register button in the system
if ($attrib['command'])
{
$OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
$JS_OBJECT_NAME,
$command,
$attrib['id'],
$attrib['type'],
$attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
$attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
$attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
// make valid href to specific buttons
if (in_array($attrib['command'], $MAIN_TASKS))
$attrib['href'] = htmlentities(ereg_replace('_task=[a-z]+', '_task='.$attrib['command'], $COMM_PATH));
else if (in_array($attrib['command'], $a_static_commands))
$attrib['href'] = htmlentities($COMM_PATH.'&_action='.$attrib['command']);
}
// overwrite attributes
if (!$attrib['href'])
$attrib['href'] = '#';
if ($command)
$attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
if ($command && $attrib['imageover'])
{
$attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
$attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
}
if ($command && $attrib['imagesel'])
{
$attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
$attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
}
$out = '';
// generate image tag
if ($attrib['type']=='image')
{
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
$img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
$btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
if ($attrib['label'])
$btn_content .= ' '.$attrib['label'];
$link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
}
else if ($attrib['type']=='link')
{
$btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
$link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
}
else if ($attrib['type']=='input')
{
$attrib['type'] = 'button';
if ($attrib['label'])
$attrib['value'] = $attrib['label'];
$attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
$out = sprintf('<input%s disabled />', $attrib_str);
}
// generate html code for button
if ($btn_content)
{
$attrib_str = create_attrib_string($attrib, $link_attrib);
$out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
}
return $out;
}
function rcube_menu($attrib)
{
return '';
}
function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
{
global $DB;
// allow the following attributes to be added to the <table> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
$table = '<table' . $attrib_str . ">\n";
// add table title
$table .= "<thead><tr>\n";
foreach ($a_show_cols as $col)
$table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
$table .= "</tr></thead>\n<tbody>\n";
$c = 0;
if (!is_array($table_data))
{
while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
{
$zebra_class = $c%2 ? 'even' : 'odd';
$table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
// format each col
foreach ($a_show_cols as $col)
{
$cont = rep_specialchars_output($sql_arr[$col]);
$table .= '<td class="'.$col.'">' . $cont . "</td>\n";
}
$table .= "</tr>\n";
$c++;
}
}
else
{
foreach ($table_data as $row_data)
{
$zebra_class = $c%2 ? 'even' : 'odd';
$table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
// format each col
foreach ($a_show_cols as $col)
{
$cont = rep_specialchars_output($row_data[$col]);
$table .= '<td class="'.$col.'">' . $cont . "</td>\n";
}
$table .= "</tr>\n";
$c++;
}
}
// complete message table
$table .= "</tbody></table>\n";
return $table;
}
function rcmail_get_edit_field($col, $value, $attrib, $type='text')
{
$fname = '_'.$col;
$attrib['name'] = $fname;
if ($type=='checkbox')
{
$attrib['value'] = '1';
$input = new checkbox($attrib);
}
else if ($type=='textarea')
{
$attrib['cols'] = $attrib['size'];
$input = new textarea($attrib);
}
else
$input = new textfield($attrib);
// use value from post
if (!empty($_POST[$fname]))
$value = $_POST[$fname];
$out = $input->show($value);
return $out;
}
// compose a valid attribute string for HTML tags
function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
{
// allow the following attributes to be added to the <iframe> tag
$attrib_str = '';
foreach ($allowed_attribs as $a)
if (isset($attrib[$a]))
$attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '"', $attrib[$a]));
return $attrib_str;
}
// convert a HTML attribute string attributes to an associative array (name => value)
function parse_attrib_string($str)
{
$attrib = array();
preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str), $regs, PREG_SET_ORDER);
// convert attributes to an associative array (name => value)
if ($regs)
foreach ($regs as $attr)
$attrib[strtolower($attr[1])] = $attr[2];
return $attrib;
}
function format_date($date, $format=NULL)
{
global $CONFIG, $sess_user_lang;
$ts = NULL;
if (is_numeric($date))
$ts = $date;
else if (!empty($date))
$ts = @strtotime($date);
if (empty($ts))
return '';
// get user's timezone
$tz = $CONFIG['timezone'];
if ($CONFIG['dst_active'])
$tz++;
// convert time to user's timezone
$timestamp = $ts - date('Z', $ts) + ($tz * 3600);
// get current timestamp in user's timezone
$now = time(); // local time
$now -= (int)date('Z'); // make GMT time
$now += ($tz * 3600); // user's time
$now_date = getdate();
$today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
$week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
// define date format depending on current time
if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
$format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
else if (!$format)
$format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
// parse format string manually in order to provide localized weekday and month names
// an alternative would be to convert the date() format string to fit with strftime()
$out = '';
for($i=0; $i<strlen($format); $i++)
{
if ($format{$i}=='\\') // skip escape chars
continue;
// write char "as-is"
if ($format{$i}==' ' || $format{$i-1}=='\\')
$out .= $format{$i};
// weekday (short)
else if ($format{$i}=='D')
$out .= rcube_label(strtolower(date('D', $timestamp)));
// weekday long
else if ($format{$i}=='l')
$out .= rcube_label(strtolower(date('l', $timestamp)));
// month name (short)
else if ($format{$i}=='M')
$out .= rcube_label(strtolower(date('M', $timestamp)));
// month name (long)
else if ($format{$i}=='F')
$out .= rcube_label(strtolower(date('F', $timestamp)));
else
$out .= date($format{$i}, $timestamp);
}
return $out;
}
// ************** functions delivering gui objects **************
function rcmail_message_container($attrib)
{
global $OUTPUT, $JS_OBJECT_NAME;
if (!$attrib['id'])
$attrib['id'] = 'rcmMessageContainer';
// allow the following attributes to be added to the <table> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
$out = '<div' . $attrib_str . "></div>";
$OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
return $out;
}
// return the IMAP username of the current session
function rcmail_current_username($attrib)
{
global $DB;
static $s_username;
// alread fetched
if (!empty($s_username))
return $s_username;
// get e-mail address form default identity
$sql_result = $DB->query("SELECT email AS mailto
FROM ".get_table_name('identities')."
WHERE user_id=?
AND standard=1
AND del<>1",
$_SESSION['user_id']);
if ($DB->num_rows($sql_result))
{
$sql_arr = $DB->fetch_assoc($sql_result);
$s_username = $sql_arr['mailto'];
}
else if (strstr($_SESSION['username'], '@'))
$s_username = $_SESSION['username'];
else
$s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
return $s_username;
}
// return code for the webmail login form
function rcmail_login_form($attrib)
{
global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
$labels = array();
$labels['user'] = rcube_label('username');
$labels['pass'] = rcube_label('password');
$labels['host'] = rcube_label('server');
$input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30));
$input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
$input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
$fields = array();
$fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
$fields['pass'] = $input_pass->show();
$fields['action'] = $input_action->show();
if (is_array($CONFIG['default_host']))
{
$select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
foreach ($CONFIG['default_host'] as $key => $value)
$select_host->add($value, (is_numeric($key) ? $value : $key));
$fields['host'] = $select_host->show($_POST['_host']);
}
else if (!strlen($CONFIG['default_host']))
{
$input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
$fields['host'] = $input_host->show($_POST['_host']);
}
$form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
$form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
$form_end = !strlen($attrib['form']) ? '</form>' : '';
if ($fields['host'])
$form_host = <<<EOF
</tr><tr>
<td class="title"><label for="rcmloginhost">$labels[host]</label></td>
<td>$fields[host]</td>
EOF;
$OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
$out = <<<EOF
$form_start
$SESS_HIDDEN_FIELD
$fields[action]
<table><tr>
<td class="title"><label for="rcmloginuser">$labels[user]</label></td>
<td>$fields[user]</td>
</tr><tr>
<td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
<td>$fields[pass]</td>
$form_host
</tr></table>
$form_end
EOF;
return $out;
}
function rcmail_charset_selector($attrib)
{
global $OUTPUT;
// pass the following attributes to the form class
$field_attrib = array('name' => '_charset');
foreach ($attrib as $attr => $value)
if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
$field_attrib[$attr] = $value;
$charsets = array(
'US-ASCII' => 'ASCII (English)',
'EUC-JP' => 'EUC-JP (Japanese)',
'EUC-KR' => 'EUC-KR (Korean)',
'BIG5' => 'BIG5 (Chinese)',
'GB2312' => 'GB2312 (Chinese)',
'ISO-2022-JP' => 'ISO-2022-JP (Japanese)',
'ISO-8859-1' => 'ISO-8859-1 (Latin-1)',
'ISO-8859-2' => 'ISO-8895-2 (Central European)',
'ISO-8859-7' => 'ISO-8859-7 (Greek)',
'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
'Windows-1251' => 'Windows-1251 (Cyrillic)',
'Windows-1252' => 'Windows-1252 (Western)',
'Windows-1255' => 'Windows-1255 (Hebrew)',
'Windows-1256' => 'Windows-1256 (Arabic)',
'Windows-1257' => 'Windows-1257 (Baltic)',
'UTF-8' => 'UTF-8'
);
$select = new select($field_attrib);
$select->add(array_values($charsets), array_keys($charsets));
$set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
return $select->show($set);
}
/****** debugging function ********/
function rcube_timer()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function rcube_print_time($timer, $label='Timer')
{
static $print_count = 0;
$print_count++;
$now = rcube_timer();
$diff = $now-$timer;
if (empty($label))
$label = 'Timer '.$print_count;
console(sprintf("%s: %0.4f sec", $label, $diff));
}
?>
diff --git a/program/js/app.js b/program/js/app.js
index 83a50a0e9..f8c5aaf54 100644
--- a/program/js/app.js
+++ b/program/js/app.js
@@ -1,3895 +1,3904 @@
/*
+-----------------------------------------------------------------------+
| RoundCube Webmail Client Script |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Authors: Thomas Bruederli <roundcube@gmail.com> |
| Charles McNulty <charles@charlesmcnulty.com> |
+-----------------------------------------------------------------------+
$Id$
*/
// Constants
var CONTROL_KEY = 1;
var SHIFT_KEY = 2;
var CONTROL_SHIFT_KEY = 3;
var rcube_webmail_client;
function rcube_webmail()
{
this.env = new Object();
this.labels = new Object();
this.buttons = new Object();
this.gui_objects = new Object();
this.commands = new Object();
this.selection = new Array();
this.last_selected = 0;
this.in_message_list = false;
// create public reference to myself
rcube_webmail_client = this;
this.ref = 'rcube_webmail_client';
// webmail client settings
this.dblclick_time = 600;
this.message_time = 5000;
this.mbox_expression = new RegExp('[^0-9a-z\-_]', 'gi');
// mimetypes supported by the browser (default settings)
this.mimetypes = new Array('text/plain', 'text/html', 'text/xml',
'image/jpeg', 'image/gif', 'image/png',
'application/x-javascript', 'application/pdf',
'application/x-shockwave-flash');
// default environment vars
this.env.keep_alive = 60; // seconds
this.env.request_timeout = 180; // seconds
this.env.draft_autosave = 300; // seconds
// set environment variable
this.set_env = function(name, value)
{
this.env[name] = value;
};
// add a localized label to the client environment
this.add_label = function(key, value)
{
this.labels[key] = value;
};
// add a button to the button list
this.register_button = function(command, id, type, act, sel, over)
{
if (!this.buttons[command])
this.buttons[command] = new Array();
var button_prop = {id:id, type:type};
if (act) button_prop.act = act;
if (sel) button_prop.sel = sel;
if (over) button_prop.over = over;
this.buttons[command][this.buttons[command].length] = button_prop;
};
// register a specific gui object
this.gui_object = function(name, id)
{
this.gui_objects[name] = id;
};
// initialize webmail client
this.init = function()
{
this.task = this.env.task;
// check browser
if (!bw.dom || !bw.xmlhttp_test())
{
location.href = this.env.comm_path+'&_action=error&_code=0x199';
return;
}
// find all registered gui objects
for (var n in this.gui_objects)
this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
// tell parent window that this frame is loaded
if (this.env.framed && parent.rcmail && parent.rcmail.set_busy)
parent.rcmail.set_busy(false);
// enable general commands
this.enable_command('logout', 'mail', 'addressbook', 'settings', true);
switch (this.task)
{
case 'mail':
var msg_list_frame = this.gui_objects.mailcontframe;
var msg_list = this.gui_objects.messagelist;
if (msg_list)
{
msg_list_frame.onmousedown = function(e){return rcube_webmail_client.click_on_list(e);};
this.init_messagelist(msg_list);
this.enable_command('toggle_status', true);
}
// enable mail commands
this.enable_command('list', 'checkmail', 'compose', 'add-contact', 'search', 'reset-search', true);
if (this.env.action=='show')
{
this.enable_command('show', 'reply', 'reply-all', 'forward', 'moveto', 'delete', 'viewsource', 'print', 'load-attachment', true);
if (this.env.next_uid)
this.enable_command('nextmessage', true);
if (this.env.prev_uid)
this.enable_command('previousmessage', true);
}
if (this.env.action=='show' && this.env.blockedobjects)
{
if (this.gui_objects.remoteobjectsmsg)
this.gui_objects.remoteobjectsmsg.style.display = 'block';
this.enable_command('load-images', true);
}
if (this.env.action=='compose')
{
this.enable_command('add-attachment', 'send-attachment', 'remove-attachment', 'send', true);
if (this.env.spellcheck)
this.enable_command('spellcheck', true);
if (this.env.drafts_mailbox)
this.enable_command('savedraft', true);
}
if (this.env.messagecount)
this.enable_command('select-all', 'select-none', 'sort', 'expunge', true);
if (this.env.messagecount && (this.env.mailbox==this.env.trash_mailbox || this.env.mailbox==this.env.junk_mailbox))
this.enable_command('purge', true);
this.set_page_buttons();
// focus this window
window.focus();
// init message compose form
if (this.env.action=='compose')
this.init_messageform();
// show printing dialog
if (this.env.action=='print')
window.print();
// get unread count for each mailbox
if (this.gui_objects.mailboxlist)
this.http_request('getunread', '');
break;
case 'addressbook':
var contacts_list = this.gui_objects.contactslist;
var ldap_contacts_list = this.gui_objects.ldapcontactslist;
if (contacts_list)
this.init_contactslist(contacts_list);
if (ldap_contacts_list)
this.init_ldapsearchlist(ldap_contacts_list);
this.set_page_buttons();
if (this.env.cid)
this.enable_command('show', 'edit', true);
if ((this.env.action=='add' || this.env.action=='edit') && this.gui_objects.editform)
this.enable_command('save', true);
this.enable_command('list', 'add', true);
this.enable_command('ldappublicsearch', this.env.ldappublicsearch);
break;
case 'settings':
this.enable_command('preferences', 'identities', 'save', 'folders', true);
if (this.env.action=='identities' || this.env.action=='edit-identity' || this.env.action=='add-identity')
this.enable_command('edit', 'add', 'delete', true);
if (this.env.action=='edit-identity' || this.env.action=='add-identity')
this.enable_command('save', true);
if (this.env.action=='folders')
this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', 'delete-folder', true);
var identities_list = this.gui_objects.identitieslist;
if (identities_list)
this.init_identitieslist(identities_list);
break;
case 'login':
var input_user = rcube_find_object('_user');
var input_pass = rcube_find_object('_pass');
if (input_user && input_user.value=='')
input_user.focus();
else if (input_pass)
input_pass.focus();
this.enable_command('login', true);
break;
default:
break;
}
// enable basic commands
this.enable_command('logout', true);
// disable browser's contextmenus
// document.oncontextmenu = function(){ return false; }
// load body click event
document.onmousedown = function(){ return rcube_webmail_client.reset_click(); };
document.onkeydown = function(e){ return rcube_webmail_client.key_pressed(e, msg_list_frame); };
// flag object as complete
this.loaded = true;
// show message
if (this.pending_message)
this.display_message(this.pending_message[0], this.pending_message[1]);
// start keep-alive interval
this.start_keepalive();
};
// start interval for keep-alive/recent_check signal
this.start_keepalive = function()
{
if (this.env.keep_alive && this.task=='mail' && this.gui_objects.messagelist)
this._int = setInterval(this.ref+'.check_for_recent()', this.env.keep_alive * 1000);
else if (this.env.keep_alive && this.task!='login')
this._int = setInterval(this.ref+'.send_keep_alive()', this.env.keep_alive * 1000);
}
// reset last clicked if user clicks on anything other than the message table
this.reset_click = function()
{
var id;
this.in_message_list = false;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
if (this.list_rows[id] && this.list_rows[id].obj)
{
this.set_classname(this.list_rows[id].obj, 'selected', false);
this.set_classname(this.list_rows[id].obj, 'unfocused', true);
}
}
};
this.click_on_list = function(e)
{
if (!e)
e = window.event;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
if (this.list_rows[id].obj)
{
this.set_classname(this.list_rows[id].obj, 'selected', true);
this.set_classname(this.list_rows[id].obj, 'unfocused', false);
}
}
var mbox_li;
if (mbox_li = this.get_mailbox_li())
this.set_classname(mbox_li, 'unfocused', true);
this.in_message_list = true;
e.cancelBubble = true;
};
this.key_pressed = function(e, msg_list_frame) {
if (this.in_message_list != true)
return true;
var keyCode = document.layers ? e.which : document.all ? event.keyCode : document.getElementById ? e.keyCode : 0;
var mod_key = this.get_modifier(e);
switch (keyCode) {
case 13:
this.command('show','',this);
break;
case 40:
case 38:
return this.use_arrow_key(keyCode, mod_key, msg_list_frame);
break;
case 46:
return this.use_delete_key(keyCode, mod_key, msg_list_frame);
break;
default:
return true;
}
return true;
}
this.use_arrow_key = function(keyCode, mod_key, msg_list_frame) {
var scroll_to = 0;
if (keyCode == 40) { // down arrow key pressed
new_row = this.get_next_row();
if (!new_row) return false;
scroll_to = (Number(new_row.offsetTop) + Number(new_row.offsetHeight)) - Number(msg_list_frame.offsetHeight);
} else if (keyCode == 38) { // up arrow key pressed
new_row = this.get_prev_row();
if (!new_row) return false;
scroll_to = new_row.offsetTop;
} else {return true;}
this.select_row(new_row.uid,mod_key,true);
if (((Number(new_row.offsetTop)) < (Number(msg_list_frame.scrollTop))) ||
((Number(new_row.offsetTop) + Number(new_row.offsetHeight)) > (Number(msg_list_frame.scrollTop) + Number(msg_list_frame.offsetHeight)))) {
msg_list_frame.scrollTop = scroll_to;
}
return false;
};
this.use_delete_key = function(keyCode, mod_key, msg_list_frame){
this.command('delete','',this);
return false;
}
// get all message rows from HTML table and init each row
this.init_messagelist = function(msg_list)
{
if (msg_list && msg_list.tBodies[0])
{
this.message_rows = new Array();
var row;
for(var r=0; r<msg_list.tBodies[0].childNodes.length; r++)
{
row = msg_list.tBodies[0].childNodes[r];
while (row && (row.nodeType != 1 || row.style.display == 'none')) {
row = row.nextSibling;
r++;
}
//row = msg_list.tBodies[0].rows[r];
if (row) this.init_message_row(row);
}
}
// alias to common rows array
this.list_rows = this.message_rows;
};
// make references in internal array and set event handlers
this.init_message_row = function(row)
{
var uid, msg_icon;
if (String(row.id).match(/rcmrow([0-9]+)/))
{
uid = RegExp.$1;
row.uid = uid;
this.message_rows[uid] = {id:row.id, obj:row,
classname:row.className,
deleted:this.env.messages[uid] ? this.env.messages[uid].deleted : null,
unread:this.env.messages[uid] ? this.env.messages[uid].unread : null,
replied:this.env.messages[uid] ? this.env.messages[uid].replied : null};
// set eventhandlers to table row
row.onmousedown = function(e){ return rcube_webmail_client.drag_row(e, this.uid); };
row.onmouseup = function(e){ return rcube_webmail_client.click_row(e, this.uid); };
if (document.all)
row.onselectstart = function() { return false; };
// set eventhandler to message icon
if ((msg_icon = row.cells[0].childNodes[0]) && row.cells[0].childNodes[0].nodeName=='IMG')
{
msg_icon.id = 'msgicn_'+uid;
msg_icon._row = row;
msg_icon.onmousedown = function(e) { rcube_webmail_client.command('toggle_status', this); };
// get message icon and save original icon src
this.message_rows[uid].icon = msg_icon;
}
}
};
// init message compose form: set focus and eventhandlers
this.init_messageform = function()
{
if (!this.gui_objects.messageform)
return false;
//this.messageform = this.gui_objects.messageform;
var input_from = rcube_find_object('_from');
var input_to = rcube_find_object('_to');
var input_cc = rcube_find_object('_cc');
var input_bcc = rcube_find_object('_bcc');
var input_replyto = rcube_find_object('_replyto');
var input_subject = rcube_find_object('_subject');
var input_message = rcube_find_object('_message');
// init live search events
if (input_to)
this.init_address_input_events(input_to);
if (input_cc)
this.init_address_input_events(input_cc);
if (input_bcc)
this.init_address_input_events(input_bcc);
// add signature according to selected identity
if (input_from && input_from.type=='select-one')
this.change_identity(input_from);
if (input_to && input_to.value=='')
input_to.focus();
else if (input_subject && input_subject.value=='')
input_subject.focus();
else if (input_message)
this.set_caret2start(input_message); // input_message.focus();
// get summary of all field values
this.cmp_hash = this.compose_field_hash();
// start the auto-save timer
this.auto_save_start();
};
this.init_address_input_events = function(obj)
{
var handler = function(e){ return rcube_webmail_client.ksearch_keypress(e,this); };
var handler2 = function(e){ return rcube_webmail_client.ksearch_blur(e,this); };
if (bw.safari)
{
obj.addEventListener('keydown', handler, false);
// obj.addEventListener('blur', handler2, false);
}
else if (bw.mz)
{
obj.addEventListener('keypress', handler, false);
obj.addEventListener('blur', handler2, false);
}
else if (bw.ie)
{
obj.onkeydown = handler;
//obj.attachEvent('onkeydown', handler);
// obj.attachEvent('onblur', handler2, false);
}
obj.setAttribute('autocomplete', 'off');
};
// get all contact rows from HTML table and init each row
this.init_contactslist = function(contacts_list)
{
if (contacts_list && contacts_list.tBodies[0])
{
this.contact_rows = new Array();
var row;
for(var r=0; r<contacts_list.tBodies[0].childNodes.length; r++)
{
row = contacts_list.tBodies[0].childNodes[r];
this.init_table_row(row, 'contact_rows');
}
}
// alias to common rows array
this.list_rows = this.contact_rows;
if (this.env.cid)
this.highlight_row(this.env.cid);
};
// get all contact rows from HTML table and init each row
this.init_ldapsearchlist = function(ldap_contacts_list)
{
if (ldap_contacts_list && ldap_contacts_list.tBodies[0])
{
this.ldap_contact_rows = new Array();
var row;
for(var r=0; r<ldap_contacts_list.tBodies[0].childNodes.length; r++)
{
row = ldap_contacts_list.tBodies[0].childNodes[r];
this.init_table_row(row, 'ldap_contact_rows');
}
}
// alias to common rows array
this.list_rows = this.ldap_contact_rows;
};
// make references in internal array and set event handlers
this.init_table_row = function(row, array_name)
{
var cid;
if (String(row.id).match(/rcmrow([0-9]+)/))
{
cid = RegExp.$1;
row.cid = cid;
this[array_name][cid] = {id:row.id,
obj:row,
classname:row.className};
// set eventhandlers to table row
row.onmousedown = function(e) { rcube_webmail_client.in_selection_before=this.cid; return false; }; // fake for drag handler
row.onmouseup = function(e){ return rcube_webmail_client.click_row(e, this.cid); };
}
};
// get all contact rows from HTML table and init each row
this.init_identitieslist = function(identities_list)
{
if (identities_list && identities_list.tBodies[0])
{
this.identity_rows = new Array();
var row;
for(var r=0; r<identities_list.tBodies[0].childNodes.length; r++)
{
row = identities_list.tBodies[0].childNodes[r];
this.init_table_row(row, 'identity_rows');
}
}
// alias to common rows array
this.list_rows = this.identity_rows;
if (this.env.iid)
this.highlight_row(this.env.iid);
};
/*********************************************************/
/********* client command interface *********/
/*********************************************************/
// execute a specific command on the web client
this.command = function(command, props, obj)
{
if (obj && obj.blur)
obj.blur();
if (this.busy)
return false;
// command not supported or allowed
if (!this.commands[command])
{
// pass command to parent window
if (this.env.framed && parent.rcmail && parent.rcmail.command)
parent.rcmail.command(command, props);
return false;
}
// check input before leaving compose step
if (this.task=='mail' && this.env.action=='compose' && (command=='list' || command=='mail' || command=='addressbook' || command=='settings'))
{
if (this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
return false;
}
// process command
switch (command)
{
case 'login':
if (this.gui_objects.loginform)
this.gui_objects.loginform.submit();
break;
case 'logout':
location.href = this.env.comm_path+'&_action=logout';
break;
// commands to switch task
case 'mail':
case 'addressbook':
case 'settings':
this.switch_task(command);
break;
// misc list commands
case 'list':
if (this.task=='mail')
{
if (this.env.search_request<0 || (this.env.search_request && props != this.env.mailbox))
this.reset_qsearch();
// Reset message list header, unless returning from compose/read/etc
// don't know what this is good for (thomasb, 2006/07/25)
//if (this.env.mailbox != props && this.message_rows)
// this.clear_message_list_header();
this.list_mailbox(props);
}
else if (this.task=='addressbook')
this.list_contacts();
break;
case 'sort':
// get the type of sorting
var a_sort = props.split('_');
var sort_col = a_sort[0];
var sort_order = a_sort[1] ? a_sort[1].toUpperCase() : null;
var header;
// no sort order specified: toggle
if (sort_order==null)
{
if (this.env.sort_col==sort_col)
sort_order = this.env.sort_order=='ASC' ? 'DESC' : 'ASC';
else
sort_order = this.env.sort_order;
}
if (this.env.sort_col==sort_col && this.env.sort_order==sort_order)
break;
// set table header class
if (header = document.getElementById('rcmHead'+this.env.sort_col))
this.set_classname(header, 'sorted'+(this.env.sort_order.toUpperCase()), false);
if (header = document.getElementById('rcmHead'+sort_col))
this.set_classname(header, 'sorted'+sort_order, true);
// save new sort properties
this.env.sort_col = sort_col;
this.env.sort_order = sort_order;
// reload message list
this.list_mailbox('', '', sort_col+'_'+sort_order);
break;
case 'nextpage':
this.list_page('next');
break;
case 'previouspage':
this.list_page('prev');
break;
case 'expunge':
if (this.env.messagecount)
this.expunge_mailbox(this.env.mailbox);
break;
case 'purge':
case 'empty-mailbox':
if (this.env.messagecount)
this.purge_mailbox(this.env.mailbox);
break;
// common commands used in multiple tasks
case 'show':
if (this.task=='mail')
{
var uid = this.get_single_uid();
if (uid && (!this.env.uid || uid != this.env.uid))
{
if (this.env.mailbox==this.env.drafts_mailbox)
{
this.set_busy(true);
location.href = this.env.comm_path+'&_action=compose&_draft_uid='+uid+'&_mbox='+escape(this.env.mailbox);
}
else
this.show_message(uid);
}
}
else if (this.task=='addressbook')
{
var cid = props ? props : this.get_single_cid();
if (cid && !(this.env.action=='show' && cid==this.env.cid))
this.load_contact(cid, 'show');
}
break;
case 'add':
if (this.task=='addressbook')
if (!window.frames[this.env.contentframe].rcmail)
this.load_contact(0, 'add');
else
{
if (window.frames[this.env.contentframe].rcmail.selection.length)
this.add_ldap_contacts();
else
this.load_contact(0, 'add');
}
else if (this.task=='settings')
{
this.clear_selection();
this.load_identity(0, 'add-identity');
}
break;
case 'edit':
var cid;
if (this.task=='addressbook' && (cid = this.get_single_cid()))
this.load_contact(cid, 'edit');
else if (this.task=='settings' && props)
this.load_identity(props, 'edit-identity');
break;
case 'save-identity':
case 'save':
if (this.gui_objects.editform)
{
var input_pagesize = rcube_find_object('_pagesize');
var input_name = rcube_find_object('_name');
var input_email = rcube_find_object('_email');
// user prefs
if (input_pagesize && isNaN(input_pagesize.value))
{
alert(this.get_label('nopagesizewarning'));
input_pagesize.focus();
break;
}
// contacts/identities
else
{
if (input_name && input_name.value == '')
{
alert(this.get_label('nonamewarning'));
input_name.focus();
break;
}
else if (input_email && !rcube_check_email(input_email.value))
{
alert(this.get_label('noemailwarning'));
input_email.focus();
break;
}
}
this.gui_objects.editform.submit();
}
break;
case 'delete':
// mail task
if (this.task=='mail')
this.delete_messages();
// addressbook task
else if (this.task=='addressbook')
this.delete_contacts();
// user settings task
else if (this.task=='settings')
this.delete_identity();
break;
// mail task commands
case 'move':
case 'moveto':
this.move_messages(props);
break;
case 'toggle_status':
if (props && !props._row)
break;
var uid;
var flag = 'read';
if (props._row.uid)
{
uid = props._row.uid;
this.dont_select = true;
// toggle read/unread
if (this.message_rows[uid].deleted) {
flag = 'undelete';
} else if (!this.message_rows[uid].unread)
flag = 'unread';
}
this.mark_message(flag, uid);
break;
case 'load-images':
if (this.env.uid)
this.show_message(this.env.uid, true);
break;
case 'load-attachment':
var url = this.env.comm_path+'&_action=get&_mbox='+this.env.mailbox+'&_uid='+this.env.uid+'&_part='+props.part;
// open attachment in frame if it's of a supported mimetype
if (this.env.uid && props.mimetype && find_in_array(props.mimetype, this.mimetypes)>=0)
{
this.attachment_win = window.open(url+'&_frame=1', 'rcubemailattachment');
if (this.attachment_win)
{
setTimeout(this.ref+'.attachment_win.focus()', 10);
break;
}
}
location.href = url;
break;
case 'select-all':
this.select_all(props);
break;
case 'select-none':
this.clear_selection();
break;
case 'nextmessage':
if (this.env.next_uid)
this.show_message(this.env.next_uid);
//location.href = this.env.comm_path+'&_action=show&_uid='+this.env.next_uid+'&_mbox='+this.env.mailbox;
break;
case 'previousmessage':
if (this.env.prev_uid)
this.show_message(this.env.prev_uid);
//location.href = this.env.comm_path+'&_action=show&_uid='+this.env.prev_uid+'&_mbox='+this.env.mailbox;
break;
case 'checkmail':
this.check_for_recent();
break;
case 'compose':
var url = this.env.comm_path+'&_action=compose';
if (this.task=='mail' && this.env.mailbox==this.env.drafts_mailbox)
{
- var uid = this.get_single_uid();
- url += '&_draft_uid='+uid+'&_mbox='+escape(this.env.mailbox);
+ var uid;
+ if (uid = this.get_single_uid())
+ url += '&_draft_uid='+uid+'&_mbox='+escape(this.env.mailbox);
}
// modify url if we're in addressbook
else if (this.task=='addressbook')
{
url = this.get_task_url('mail', url);
var a_cids = new Array();
// use contact_id passed as command parameter
if (props)
a_cids[a_cids.length] = props;
// get selected contacts
else
{
if (!window.frames[this.env.contentframe].rcmail.selection.length)
{
for (var n=0; n<this.selection.length; n++)
a_cids[a_cids.length] = this.selection[n];
}
else
{
var frameRcmail = window.frames[this.env.contentframe].rcmail;
// get the email address(es)
for (var n=0; n<frameRcmail.selection.length; n++)
a_cids[a_cids.length] = frameRcmail.ldap_contact_rows[frameRcmail.selection[n]].obj.cells[1].innerHTML;
}
}
if (a_cids.length)
url += '&_to='+a_cids.join(',');
else
break;
}
else if (props)
url += '&_to='+encodeURIComponent(props);
// don't know if this is necessary...
url = url.replace(/&_framed=1/, "");
this.set_busy(true);
// need parent in case we are coming from the contact frame
if (this.env.framed)
parent.location.href = url;
else
location.href = url;
break;
case 'spellcheck':
if (this.env.spellcheck && this.env.spellcheck.spellCheck)
this.env.spellcheck.spellCheck(this.env.spellcheck.check_link);
break;
case 'savedraft':
// Reset the auto-save timer
self.clearTimeout(this.save_timer);
if (!this.gui_objects.messageform)
break;
// if saving Drafts is disabled in main.inc.php
if (!this.env.drafts_mailbox)
break;
this.set_busy(true, 'savingmessage');
var form = this.gui_objects.messageform;
form.target = "savetarget";
form.submit();
break;
case 'send':
if (!this.gui_objects.messageform)
break;
if (!this.check_compose_input())
break;
// Reset the auto-save timer
self.clearTimeout(this.save_timer);
// all checks passed, send message
this.set_busy(true, 'sendingmessage');
var form = this.gui_objects.messageform;
form.target = "savetarget";
form._draft.value = '';
form.submit();
// clear timeout (sending could take longer)
clearTimeout(this.request_timer);
break;
case 'add-attachment':
this.show_attachment_form(true);
case 'send-attachment':
// Reset the auto-save timer
self.clearTimeout(this.save_timer);
this.upload_file(props)
break;
case 'remove-attachment':
this.remove_attachment(props);
break;
case 'reply-all':
case 'reply':
var uid;
if (uid = this.get_single_uid())
{
this.set_busy(true);
location.href = this.env.comm_path+'&_action=compose&_reply_uid='+uid+'&_mbox='+escape(this.env.mailbox)+(command=='reply-all' ? '&_all=1' : '');
}
break;
case 'forward':
var uid;
if (uid = this.get_single_uid())
{
this.set_busy(true);
location.href = this.env.comm_path+'&_action=compose&_forward_uid='+uid+'&_mbox='+escape(this.env.mailbox);
}
break;
case 'print':
var uid;
if (uid = this.get_single_uid())
{
this.printwin = window.open(this.env.comm_path+'&_action=print&_uid='+uid+'&_mbox='+escape(this.env.mailbox)+(this.env.safemode ? '&_safe=1' : ''));
if (this.printwin)
setTimeout(this.ref+'.printwin.focus()', 20);
}
break;
case 'viewsource':
var uid;
if (uid = this.get_single_uid())
{
this.sourcewin = window.open(this.env.comm_path+'&_action=viewsource&_uid='+this.env.uid+'&_mbox='+escape(this.env.mailbox));
if (this.sourcewin)
setTimeout(this.ref+'.sourcewin.focus()', 20);
}
break;
case 'add-contact':
this.add_contact(props);
break;
// mail quicksearch
case 'search':
if (!props && this.gui_objects.qsearchbox)
props = this.gui_objects.qsearchbox.value;
if (props)
this.qsearch(escape(props), this.env.mailbox);
break;
// reset quicksearch
case 'reset-search':
var s = this.env.search_request;
this.reset_qsearch();
if (s)
this.list_mailbox(this.env.mailbox);
break;
// ldap search
case 'ldappublicsearch':
if (this.gui_objects.ldappublicsearchform)
this.gui_objects.ldappublicsearchform.submit();
else
this.ldappublicsearch(command);
break;
// user settings commands
case 'preferences':
location.href = this.env.comm_path;
break;
case 'identities':
location.href = this.env.comm_path+'&_action=identities';
break;
case 'delete-identity':
this.delete_identity();
case 'folders':
location.href = this.env.comm_path+'&_action=folders';
break;
case 'subscribe':
this.subscribe_folder(props);
break;
case 'unsubscribe':
this.unsubscribe_folder(props);
break;
case 'create-folder':
this.create_folder(props);
break;
case 'rename-folder':
this.rename_folder(props);
break;
case 'delete-folder':
if (confirm(this.get_label('deletefolderconfirm')))
this.delete_folder(props);
break;
}
return obj ? false : true;
};
// set command enabled or disabled
this.enable_command = function()
{
var args = arguments;
if(!args.length) return -1;
var command;
var enable = args[args.length-1];
for(var n=0; n<args.length-1; n++)
{
command = args[n];
this.commands[command] = enable;
this.set_button(command, (enable ? 'act' : 'pas'));
}
return true;
};
// lock/unlock interface
this.set_busy = function(a, message)
{
if (a && message)
{
var msg = this.get_label(message);
if (msg==message)
msg = 'Loading...';
this.display_message(msg, 'loading', true);
}
else if (!a && this.busy)
this.hide_message();
this.busy = a;
//document.body.style.cursor = a ? 'wait' : 'default';
if (this.gui_objects.editform)
this.lock_form(this.gui_objects.editform, a);
// clear pending timer
if (this.request_timer)
clearTimeout(this.request_timer);
// set timer for requests
if (a && this.env.request_timeout)
this.request_timer = setTimeout(this.ref+'.request_timed_out()', this.env.request_timeout * 1000);
};
// return a localized string
this.get_label = function(name)
{
if (this.labels[name])
return this.labels[name];
else
return name;
};
// switch to another application task
this.switch_task = function(task)
{
if (this.task===task && task!='mail')
return;
var url = this.get_task_url(task);
if (task=='mail')
url += '&_mbox=INBOX';
this.set_busy(true);
location.href = url;
};
this.get_task_url = function(task, url)
{
if (!url)
url = this.env.comm_path;
return url.replace(/_task=[a-z]+/, '_task='+task);
};
// called when a request timed out
this.request_timed_out = function()
{
this.set_busy(false);
this.display_message('Request timed out!', 'error');
};
/*********************************************************/
/********* event handling methods *********/
/*********************************************************/
// onmouseup handler for mailboxlist item
this.mbox_mouse_up = function(mbox)
{
if (this.drag_active)
{
this.unfocus_mailbox(mbox);
this.command('moveto', mbox);
}
else
this.command('list', mbox);
return false;
};
// onmousedown-handler of message list row
this.drag_row = function(e, id)
{
this.in_selection_before = this.in_selection(id) ? id : false;
// don't do anything (another action processed before)
if (this.dont_select)
return false;
// selects currently unselected row
if (!this.in_selection_before && !this.list_rows[id].clicked)
{
var mod_key = this.get_modifier(e);
this.select_row(id,mod_key,false);
}
if (this.selection.length)
{
this.drag_start = true;
document.onmousemove = function(e){ return rcube_webmail_client.drag_mouse_move(e); };
document.onmouseup = function(e){ return rcube_webmail_client.drag_mouse_up(e); };
}
return false;
};
// onmouseup-handler of message list row
this.click_row = function(e, id)
{
var mod_key = this.get_modifier(e);
// don't do anything (another action processed before)
if (this.dont_select)
{
this.dont_select = false;
return false;
}
// unselects currently selected row
if (!this.drag_active && this.in_selection_before==id && !this.list_rows[id].clicked)
this.select_row(id,mod_key,false);
this.drag_start = false;
this.in_selection_before = false;
// row was double clicked
if (this.task=='mail' && this.list_rows && this.list_rows[id].clicked && this.in_selection(id))
{
if (this.env.mailbox==this.env.drafts_mailbox)
{
this.set_busy(true);
location.href = this.env.comm_path+'&_action=compose&_draft_uid='+id+'&_mbox='+escape(this.env.mailbox);
}
else
{
this.show_message(id);
}
return false;
}
else if (this.task=='addressbook')
{
if (this.contact_rows && this.selection.length==1)
{
this.load_contact(this.selection[0], 'show', true);
// change the text for the add contact button
var links = parent.document.getElementById('abooktoolbar').getElementsByTagName('A');
for (i = 0; i < links.length; i++)
{
var onclickstring = new String(links[i].onclick);
if (onclickstring.search('\"add\"') != -1)
links[i].title = this.env.newcontact;
}
}
else if (this.contact_rows && this.contact_rows[id].clicked)
{
this.load_contact(id, 'show');
return false;
}
else if (this.ldap_contact_rows && !this.ldap_contact_rows[id].clicked)
{
// clear selection
parent.rcmail.clear_selection();
// disable delete
parent.rcmail.set_button('delete', 'pas');
// change the text for the add contact button
var links = parent.document.getElementById('abooktoolbar').getElementsByTagName('A');
for (i = 0; i < links.length; i++)
{
var onclickstring = new String(links[i].onclick);
if (onclickstring.search('\"add\"') != -1)
links[i].title = this.env.addcontact;
}
}
// handle double click event
else if (this.ldap_contact_rows && this.selection.length==1 && this.ldap_contact_rows[id].clicked)
this.command('compose', this.ldap_contact_rows[id].obj.cells[1].innerHTML);
else if (this.env.contentframe)
{
var elm = document.getElementById(this.env.contentframe);
elm.style.visibility = 'hidden';
}
}
else if (this.task=='settings')
{
if (this.selection.length==1)
this.command('edit', this.selection[0]);
}
this.list_rows[id].clicked = true;
setTimeout(this.ref+'.list_rows['+id+'].clicked=false;', this.dblclick_time);
return false;
};
/*********************************************************/
/********* (message) list functionality *********/
/*********************************************************/
// get next and previous rows that are not hidden
this.get_next_row = function(){
if (!this.list_rows) return false;
var last_selected_row = this.list_rows[this.last_selected];
var new_row = last_selected_row.obj.nextSibling;
while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none')) {
new_row = new_row.nextSibling;
}
return new_row;
}
this.get_prev_row = function(){
if (!this.list_rows) return false;
var last_selected_row = this.list_rows[this.last_selected];
var new_row = last_selected_row.obj.previousSibling;
while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none')) {
new_row = new_row.previousSibling;
}
return new_row;
}
// highlight/unhighlight a row
this.highlight_row = function(id, multiple)
{
var selected = false
if (this.list_rows[id] && !multiple)
{
this.clear_selection();
this.selection[0] = id;
this.list_rows[id].obj.className += ' selected';
selected = true;
}
else if (this.list_rows[id])
{
if (!this.in_selection(id)) // select row
{
this.selection[this.selection.length] = id;
this.set_classname(this.list_rows[id].obj, 'selected', true);
}
else // unselect row
{
var p = find_in_array(id, this.selection);
var a_pre = this.selection.slice(0, p);
var a_post = this.selection.slice(p+1, this.selection.length);
this.selection = a_pre.concat(a_post);
this.set_classname(this.list_rows[id].obj, 'selected', false);
this.set_classname(this.list_rows[id].obj, 'unfocused', false);
}
selected = (this.selection.length==1);
}
// enable/disable commands for message
if (this.task=='mail')
{
if (this.env.mailbox==this.env.drafts_mailbox)
{
this.enable_command('show', selected);
this.enable_command('delete', 'moveto', this.selection.length>0 ? true : false);
}
else
{
this.enable_command('show', 'reply', 'reply-all', 'forward', 'print', selected);
this.enable_command('delete', 'moveto', this.selection.length>0 ? true : false);
}
}
else if (this.task=='addressbook')
{
this.enable_command('edit', /*'print',*/ selected);
this.enable_command('delete', 'compose', this.selection.length>0 ? true : false);
}
};
// selects or unselects the proper row depending on the modifier key pressed
this.select_row = function(id,mod_key,with_mouse) {
if (!mod_key) {
this.shift_start = id;
this.highlight_row(id, false);
} else {
switch (mod_key) {
case SHIFT_KEY: {
this.shift_select(id,false);
break; }
case CONTROL_KEY: {
this.shift_start = id;
if (!with_mouse)
this.highlight_row(id, true);
break;
}
case CONTROL_SHIFT_KEY: {
this.shift_select(id,true);
break;
}
default: {
this.highlight_row(id, false);
break;
}
}
}
if (this.last_selected != 0 && this.list_rows[this.last_selected])
this.set_classname(this.list_rows[this.last_selected].obj, 'focused', false);
this.last_selected = id;
this.set_classname(this.list_rows[id].obj, 'focused', true);
};
this.shift_select = function(id, control) {
var from_rowIndex = this.list_rows[this.shift_start].obj.rowIndex;
var to_rowIndex = this.list_rows[id].obj.rowIndex;
var i = ((from_rowIndex < to_rowIndex)? from_rowIndex : to_rowIndex);
var j = ((from_rowIndex > to_rowIndex)? from_rowIndex : to_rowIndex);
// iterate through the entire message list
for (var n in this.list_rows) {
if ((this.list_rows[n].obj.rowIndex >= i) && (this.list_rows[n].obj.rowIndex <= j)) {
if (!this.in_selection(n))
this.highlight_row(n, true);
} else {
if (this.in_selection(n) && !control)
this.highlight_row(n, true);
}
}
};
this.clear_selection = function()
{
for(var n=0; n<this.selection.length; n++)
if (this.list_rows[this.selection[n]]) {
this.set_classname(this.list_rows[this.selection[n]].obj, 'selected', false);
this.set_classname(this.list_rows[this.selection[n]].obj, 'unfocused', false);
}
this.selection = new Array();
};
// check if given id is part of the current selection
this.in_selection = function(id)
{
for(var n in this.selection)
if (this.selection[n]==id)
return true;
return false;
};
// select each row in list
this.select_all = function(filter)
{
if (!this.list_rows || !this.list_rows.length)
return false;
// reset selection first
this.clear_selection();
for (var n in this.list_rows)
{
if (!filter || this.list_rows[n][filter]==true)
{
this.last_selected = n;
this.highlight_row(n, true);
}
}
return true;
};
// when user doble-clicks on a row
this.show_message = function(id, safe)
{
var add_url = '';
var target = window;
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
{
target = window.frames[this.env.contentframe];
add_url = '&_framed=1';
}
if (safe)
add_url = '&_safe=1';
if (id)
{
this.set_busy(true, 'loading');
target.location.href = this.env.comm_path+'&_action=show&_uid='+id+'&_mbox='+escape(this.env.mailbox)+add_url;
}
};
// list a specific page
this.list_page = function(page)
{
if (page=='next')
page = this.env.current_page+1;
if (page=='prev' && this.env.current_page>1)
page = this.env.current_page-1;
if (page > 0 && page <= this.env.pagecount)
{
this.env.current_page = page;
if (this.task=='mail')
this.list_mailbox(this.env.mailbox, page);
else if (this.task=='addressbook')
this.list_contacts(page);
}
};
// list messages of a specific mailbox
this.list_mailbox = function(mbox, page, sort)
{
this.last_selected = 0;
var add_url = '';
var target = window;
if (!mbox)
mbox = this.env.mailbox;
// add sort to url if set
if (sort)
add_url += '&_sort=' + sort;
// set page=1 if changeing to another mailbox
if (!page && mbox != this.env.mailbox)
{
page = 1;
add_url += '&_refresh=1';
this.env.current_page = page;
this.clear_selection();
}
// also send search request to get the right messages
if (this.env.search_request)
add_url += '&_search='+this.env.search_request;
this.select_mailbox(mbox);
// load message list remotely
if (this.gui_objects.messagelist)
{
this.list_mailbox_remote(mbox, page, add_url);
return;
}
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
{
target = window.frames[this.env.contentframe];
add_url += '&_framed=1';
}
// load message list to target frame/window
if (mbox)
{
this.set_busy(true, 'loading');
target.location.href = this.env.comm_path+'&_mbox='+escape(mbox)+(page ? '&_page='+page : '')+add_url;
}
};
// send remote request to load message list
this.list_mailbox_remote = function(mbox, page, add_url)
{
// clear message list first
this.clear_message_list();
// send request to server
var url = '_mbox='+escape(mbox)+(page ? '&_page='+page : '');
this.set_busy(true, 'loading');
this.http_request('list', url+add_url, true);
};
this.clear_message_list = function()
{
var table = this.gui_objects.messagelist;
var tbody = document.createElement('TBODY');
table.insertBefore(tbody, table.tBodies[0]);
table.removeChild(table.tBodies[1]);
this.message_rows = new Array();
this.list_rows = this.message_rows;
};
this.clear_message_list_header = function()
{
var table;
if (table = this.gui_objects.messagelist)
{
if (table.colgroup)
table.removeChild(table.colgroup);
if (table.tHead)
table.removeChild(table.tHead);
var colgroup = document.createElement('COLGROUP');
var thead = document.createElement('THEAD');
table.insertBefore(colgroup, table.tBodies[0]);
table.insertBefore(thead, table.tBodies[0]);
}
};
this.expunge_mailbox = function(mbox)
{
var lock = false;
var add_url = '';
// lock interface if it's the active mailbox
if (mbox == this.env.mailbox)
{
lock = true;
this.set_busy(true, 'loading');
add_url = '&_reload=1';
}
// send request to server
var url = '_mbox='+escape(mbox);
this.http_request('expunge', url+add_url, lock);
};
this.purge_mailbox = function(mbox)
{
var lock = false;
var add_url = '';
if (!confirm(this.get_label('purgefolderconfirm')))
return false;
// lock interface if it's the active mailbox
if (mbox == this.env.mailbox)
{
lock = true;
this.set_busy(true, 'loading');
add_url = '&_reload=1';
}
// send request to server
var url = '_mbox='+escape(mbox);
this.http_request('purge', url+add_url, lock);
return true;
};
this.focus_mailbox = function(mbox)
{
var mbox_li;
if (this.drag_active && mbox != this.env.mailbox && (mbox_li = this.get_mailbox_li(mbox)))
this.set_classname(mbox_li, 'droptarget', true);
}
this.unfocus_mailbox = function(mbox)
{
var mbox_li;
if (this.drag_active && (mbox_li = this.get_mailbox_li(mbox)))
this.set_classname(mbox_li, 'droptarget', false);
}
// move selected messages to the specified mailbox
this.move_messages = function(mbox)
{
// exit if no mailbox specified or if selection is empty
if (!mbox || !(this.selection.length || this.env.uid) || mbox==this.env.mailbox)
return;
var a_uids = new Array();
if (this.env.uid)
a_uids[a_uids.length] = this.env.uid;
else
{
var id;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
a_uids[a_uids.length] = id;
// 'remove' message row from list (just hide it)
if (this.message_rows[id].obj)
this.message_rows[id].obj.style.display = 'none';
}
next_row = this.get_next_row();
prev_row = this.get_prev_row();
new_row = (next_row) ? next_row : prev_row;
if (new_row) this.select_row(new_row.uid,false,false);
}
var lock = false;
// show wait message
if (this.env.action=='show')
{
lock = true;
this.set_busy(true, 'movingmessage');
}
// send request to server
this.http_request('moveto', '_uid='+a_uids.join(',')+'&_mbox='+escape(this.env.mailbox)+'&_target_mbox='+escape(mbox)+'&_from='+(this.env.action ? this.env.action : ''), lock);
};
this.permanently_remove_messages = function() {
// exit if no mailbox specified or if selection is empty
if (!(this.selection.length || this.env.uid))
return;
var a_uids = new Array();
if (this.env.uid)
a_uids[a_uids.length] = this.env.uid;
else
{
var id;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
a_uids[a_uids.length] = id;
// 'remove' message row from list (just hide it)
if (this.message_rows[id].obj)
this.message_rows[id].obj.style.display = 'none';
}
}
next_row = this.get_next_row();
prev_row = this.get_prev_row();
new_row = (next_row) ? next_row : prev_row;
if (new_row) this.select_row(new_row.uid,false,false);
// send request to server
this.http_request('delete', '_uid='+a_uids.join(',')+'&_mbox='+escape(this.env.mailbox)+'&_from='+(this.env.action ? this.env.action : ''));
}
// delete selected messages from the current mailbox
this.delete_messages = function()
{
// exit if no mailbox specified or if selection is empty
if (!(this.selection.length || this.env.uid))
return;
// if there is a trash mailbox defined and we're not currently in it:
if (this.env.trash_mailbox && String(this.env.mailbox).toLowerCase()!=String(this.env.trash_mailbox).toLowerCase())
this.move_messages(this.env.trash_mailbox);
// if there is a trash mailbox defined but we *are* in it:
else if (this.env.trash_mailbox && String(this.env.mailbox).toLowerCase() == String(this.env.trash_mailbox).toLowerCase())
this.permanently_remove_messages();
// if there isn't a defined trash mailbox and the config is set to flag for deletion
else if (!this.env.trash_mailbox && this.env.flag_for_deletion) {
flag = 'delete';
this.mark_message(flag);
if(this.env.action=="show"){
this.command('nextmessage','',this);
} else if (this.selection.length == 1) {
next_row = this.get_next_row();
prev_row = this.get_prev_row();
new_row = (next_row) ? next_row : prev_row;
if (new_row) this.select_row(new_row.uid,false,false);
}
// if there isn't a defined trash mailbox and the config is set NOT to flag for deletion
}else if (!this.env.trash_mailbox && !this.env.flag_for_deletion) {
this.permanently_remove_messages();
}
return;
};
// set a specific flag to one or more messages
this.mark_message = function(flag, uid)
{
var a_uids = new Array();
if (uid)
a_uids[0] = uid;
else if (this.env.uid)
a_uids[0] = this.env.uid;
else
{
var id;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
a_uids[a_uids.length] = id;
}
}
switch (flag) {
case 'read':
case 'unread':
this.toggle_read_status(flag,a_uids);
break;
case 'delete':
case 'undelete':
this.toggle_delete_status(a_uids);
break;
}
};
// set class to read/unread
this.toggle_read_status = function(flag, a_uids) {
// mark all message rows as read/unread
var icn_src;
for (var i=0; i<a_uids.length; i++)
{
uid = a_uids[i];
if (this.message_rows[uid])
{
this.message_rows[uid].unread = (flag=='unread' ? true : false);
if (this.message_rows[uid].classname.indexOf('unread')<0 && this.message_rows[uid].unread)
{
this.message_rows[uid].classname += ' unread';
this.set_classname(this.message_rows[uid].obj, 'unread', true);
if (this.env.unreadicon)
icn_src = this.env.unreadicon;
}
else if (!this.message_rows[uid].unread)
{
this.message_rows[uid].classname = this.message_rows[uid].classname.replace(/\s*unread/, '');
this.set_classname(this.message_rows[uid].obj, 'unread', false);
if (this.message_rows[uid].replied && this.env.repliedicon)
icn_src = this.env.repliedicon;
else if (this.env.messageicon)
icn_src = this.env.messageicon;
}
if (this.message_rows[uid].icon && icn_src)
this.message_rows[uid].icon.src = icn_src;
}
}
this.http_request('mark', '_uid='+a_uids.join(',')+'&_flag='+flag);
}
// mark all message rows as deleted/undeleted
this.toggle_delete_status = function(a_uids) {
if (this.env.read_when_deleted) {
this.toggle_read_status('read',a_uids);
}
// if deleting message from "view message" don't bother with delete icon
if (this.env.action == "show")
return false;
if (a_uids.length==1){
if(this.message_rows[a_uids[0]].classname.indexOf('deleted') < 0 ){
this.flag_as_deleted(a_uids)
} else {
this.flag_as_undeleted(a_uids)
}
return true;
}
var all_deleted = true;
for (var i=0; i<a_uids.length; i++) {
uid = a_uids[i];
if (this.message_rows[uid]) {
if (this.message_rows[uid].classname.indexOf('deleted')<0) {
all_deleted = false;
break;
}
}
}
if (all_deleted)
this.flag_as_undeleted(a_uids);
else
this.flag_as_deleted(a_uids);
return true;
}
this.flag_as_undeleted = function(a_uids){
// if deleting message from "view message" don't bother with delete icon
if (this.env.action == "show")
return false;
var icn_src;
for (var i=0; i<a_uids.length; i++) {
uid = a_uids[i];
if (this.message_rows[uid]) {
this.message_rows[uid].deleted = false;
if (this.message_rows[uid].classname.indexOf('deleted') > 0) {
this.message_rows[uid].classname = this.message_rows[uid].classname.replace(/\s*deleted/, '');
this.set_classname(this.message_rows[uid].obj, 'deleted', false);
}
if (this.message_rows[uid].unread && this.env.unreadicon)
icn_src = this.env.unreadicon;
else if (this.message_rows[uid].replied && this.env.repliedicon)
icn_src = this.env.repliedicon;
else if (this.env.messageicon)
icn_src = this.env.messageicon;
if (this.message_rows[uid].icon && icn_src)
this.message_rows[uid].icon.src = icn_src;
}
}
this.http_request('mark', '_uid='+a_uids.join(',')+'&_flag=undelete');
return true;
}
this.flag_as_deleted = function(a_uids) {
// if deleting message from "view message" don't bother with delete icon
if (this.env.action == "show")
return false;
for (var i=0; i<a_uids.length; i++) {
uid = a_uids[i];
if (this.message_rows[uid]) {
this.message_rows[uid].deleted = true;
if (this.message_rows[uid].classname.indexOf('deleted')<0) {
this.message_rows[uid].classname += ' deleted';
this.set_classname(this.message_rows[uid].obj, 'deleted', true);
}
if (this.message_rows[uid].icon && this.env.deletedicon)
this.message_rows[uid].icon.src = this.env.deletedicon;
}
}
this.http_request('mark', '_uid='+a_uids.join(',')+'&_flag=delete');
return true;
}
this.get_mailbox_li = function(mbox)
{
if (this.gui_objects.mailboxlist)
{
mbox = String((mbox ? mbox : this.env.mailbox)).toLowerCase().replace(this.mbox_expression, '');
return document.getElementById('rcmbx'+mbox);
}
return null;
};
/*********************************************************/
/********* message compose methods *********/
/*********************************************************/
// checks the input fields before sending a message
this.check_compose_input = function()
{
// check input fields
var input_to = rcube_find_object('_to');
var input_subject = rcube_find_object('_subject');
var input_message = rcube_find_object('_message');
// check for empty recipient
if (input_to && !rcube_check_email(input_to.value, true))
{
alert(this.get_label('norecipientwarning'));
input_to.focus();
return false;
}
// display localized warning for missing subject
if (input_subject && input_subject.value == '')
{
var subject = prompt(this.get_label('nosubjectwarning'), this.get_label('nosubject'));
// user hit cancel, so don't send
if (!subject && subject !== '')
{
input_subject.focus();
return false;
}
else
{
input_subject.value = subject ? subject : this.get_label('nosubject');
}
}
// check for empty body
if (input_message.value=='')
{
if (!confirm(this.get_label('nobodywarning')))
{
input_message.focus();
return false;
}
}
return true;
};
this.auto_save_start = function()
{
if (this.env.draft_autosave)
this.save_timer = self.setTimeout(this.ref+'.command("savedraft")', this.env.draft_autosave * 1000);
};
this.compose_field_hash = function()
{
// check input fields
var input_to = rcube_find_object('_to');
var input_cc = rcube_find_object('_to');
var input_bcc = rcube_find_object('_to');
var input_subject = rcube_find_object('_subject');
var input_message = rcube_find_object('_message');
var str = '';
if (input_to && input_to.value)
str += input_to.value+':';
if (input_cc && input_cc.value)
str += input_cc.value+':';
if (input_bcc && input_bcc.value)
str += input_bcc.value+':';
if (input_subject && input_subject.value)
str += input_subject.value+':';
if (input_message && input_message.value)
str += input_message.value;
return str;
};
this.change_identity = function(obj)
{
if (!obj || !obj.options)
return false;
var id = obj.options[obj.selectedIndex].value;
var input_message = rcube_find_object('_message');
var message = input_message ? input_message.value : '';
var sig, p;
if (!this.env.identity)
this.env.identity = id
// remove the 'old' signature
if (this.env.identity && this.env.signatures && this.env.signatures[this.env.identity])
{
sig = this.env.signatures[this.env.identity];
if (sig.indexOf('--')!=0)
sig = '--\n'+sig;
p = message.lastIndexOf(sig);
if (p>=0)
message = message.substring(0, p-1) + message.substring(p+sig.length, message.length);
}
// add the new signature string
if (this.env.signatures && this.env.signatures[id])
{
sig = this.env.signatures[id];
if (sig.indexOf('--')!=0)
sig = '--\n'+sig;
message += '\n'+sig;
}
if (input_message)
input_message.value = message;
this.env.identity = id;
return true;
};
this.show_attachment_form = function(a)
{
if (!this.gui_objects.uploadbox)
return false;
var elm, list;
if (elm = this.gui_objects.uploadbox)
{
if (a && (list = this.gui_objects.attachmentlist))
{
var pos = rcube_get_object_pos(list);
var left = pos.x;
var top = pos.y + list.offsetHeight + 10;
elm.style.top = top+'px';
elm.style.left = left+'px';
}
elm.style.visibility = a ? 'visible' : 'hidden';
}
// clear upload form
if (!a && this.gui_objects.attachmentform && this.gui_objects.attachmentform!=this.gui_objects.messageform)
this.gui_objects.attachmentform.reset();
return true;
};
// upload attachment file
this.upload_file = function(form)
{
if (!form)
return false;
// get file input fields
var send = false;
for (var n=0; n<form.elements.length; n++)
if (form.elements[n].type=='file' && form.elements[n].value)
{
send = true;
break;
}
// create hidden iframe and post upload form
if (send)
{
var ts = new Date().getTime();
var frame_name = 'rcmupload'+ts;
// have to do it this way for IE
// otherwise the form will be posted to a new window
if(document.all && !window.opera)
{
var html = '<iframe name="'+frame_name+'" src="program/blank.gif" style="width:0;height:0;visibility:hidden;"></iframe>';
document.body.insertAdjacentHTML('BeforeEnd',html);
}
else // for standards-compilant browsers
{
var frame = document.createElement('IFRAME');
frame.name = frame_name;
frame.width = 10;
frame.height = 10;
frame.style.visibility = 'hidden';
document.body.appendChild(frame);
}
form.target = frame_name;
form.action = this.env.comm_path+'&_action=upload';
form.setAttribute('enctype', 'multipart/form-data');
form.submit();
}
// set reference to the form object
this.gui_objects.attachmentform = form;
return true;
};
// add file name to attachment list
// called from upload page
this.add2attachment_list = function(name, content)
{
if (!this.gui_objects.attachmentlist)
return false;
+ alert(content);
+
var li = document.createElement('LI');
li.id = name;
li.innerHTML = content;
this.gui_objects.attachmentlist.appendChild(li);
return true;
};
this.remove_from_attachment_list = function(name)
{
if (!this.gui_objects.attachmentlist)
return false;
var list = this.gui_objects.attachmentlist.getElementsByTagName("li");
for (i=0;i<list.length;i++)
if (list[i].id == name)
this.gui_objects.attachmentlist.removeChild(list[i]);
};
this.remove_attachment = function(name)
{
if (name)
this.http_request('remove-attachment', '_file='+escape(name));
return true;
};
// send remote request to add a new contact
this.add_contact = function(value)
{
if (value)
this.http_request('addcontact', '_address='+value);
return true;
};
// send remote request to search mail
this.qsearch = function(value, mbox)
{
if (value && mbox)
{
this.clear_message_list();
this.set_busy(true, 'searching');
this.http_request('search', '_search='+value+'&_mbox='+mbox, true);
}
return true;
};
// reset quick-search form
this.reset_qsearch = function()
{
if (this.gui_objects.qsearchbox)
this.gui_objects.qsearchbox.value = '';
this.env.search_request = null;
return true;
};
this.sent_successfully = function(msg)
{
this.list_mailbox();
this.display_message(msg, 'confirmation', true);
}
/*********************************************************/
/********* keyboard live-search methods *********/
/*********************************************************/
// handler for keyboard events on address-fields
this.ksearch_keypress = function(e, obj)
{
if (typeof(this.env.contacts)!='object' || !this.env.contacts.length)
return true;
if (this.ksearch_timer)
clearTimeout(this.ksearch_timer);
if (!e)
e = window.event;
var highlight;
var key = e.keyCode ? e.keyCode : e.which;
switch (key)
{
case 38: // key up
case 40: // key down
if (!this.ksearch_pane)
break;
var dir = key==38 ? 1 : 0;
var next;
highlight = document.getElementById('rcmksearchSelected');
if (!highlight)
highlight = this.ksearch_pane.ul.firstChild;
if (highlight && (next = dir ? highlight.previousSibling : highlight.nextSibling))
{
highlight.removeAttribute('id');
//highlight.removeAttribute('class');
this.set_classname(highlight, 'selected', false);
}
if (next)
{
next.setAttribute('id', 'rcmksearchSelected');
this.set_classname(next, 'selected', true);
this.ksearch_selected = next._rcm_id;
}
if (e.preventDefault)
e.preventDefault();
return false;
case 9: // tab
if(e.shiftKey)
break;
case 13: // enter
if (this.ksearch_selected===null || !this.ksearch_input || !this.ksearch_value)
break;
// get cursor pos
var inp_value = this.ksearch_input.value.toLowerCase();
var cpos = this.get_caret_pos(this.ksearch_input);
var p = inp_value.lastIndexOf(this.ksearch_value, cpos);
// replace search string with full address
var pre = this.ksearch_input.value.substring(0, p);
var end = this.ksearch_input.value.substring(p+this.ksearch_value.length, this.ksearch_input.value.length);
var insert = this.env.contacts[this.ksearch_selected]+', ';
this.ksearch_input.value = pre + insert + end;
//this.ksearch_input.value = this.ksearch_input.value.substring(0, p)+insert;
// set caret to insert pos
cpos = p+insert.length;
if (this.ksearch_input.setSelectionRange)
this.ksearch_input.setSelectionRange(cpos, cpos);
// hide ksearch pane
this.ksearch_hide();
if (e.preventDefault)
e.preventDefault();
return false;
case 27: // escape
this.ksearch_hide();
break;
}
// start timer
this.ksearch_timer = setTimeout(this.ref+'.ksearch_get_results()', 200);
this.ksearch_input = obj;
return true;
};
// address search processor
this.ksearch_get_results = function()
{
var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
if (inp_value===null)
return;
// get string from current cursor pos to last comma
var cpos = this.get_caret_pos(this.ksearch_input);
var p = inp_value.lastIndexOf(',', cpos-1);
var q = inp_value.substring(p+1, cpos);
// trim query string
q = q.replace(/(^\s+|\s+$)/g, '').toLowerCase();
if (!q.length || q==this.ksearch_value)
{
if (!q.length && this.ksearch_pane && this.ksearch_pane.visible)
this.ksearch_pane.show(0);
return;
}
this.ksearch_value = q;
// start searching the contact list
var a_results = new Array();
var a_result_ids = new Array();
var c=0;
for (var i=0; i<this.env.contacts.length; i++)
{
if (this.env.contacts[i].toLowerCase().indexOf(q)>=0)
{
a_results[c] = this.env.contacts[i];
a_result_ids[c++] = i;
if (c==15) // limit search results
break;
}
}
// display search results
if (c && a_results.length)
{
var p, ul, li;
// create results pane if not present
if (!this.ksearch_pane)
{
ul = document.createElement('UL');
this.ksearch_pane = new rcube_layer('rcmKSearchpane', {vis:0, zindex:30000});
this.ksearch_pane.elm.appendChild(ul);
this.ksearch_pane.ul = ul;
}
else
ul = this.ksearch_pane.ul;
// remove all search results
ul.innerHTML = '';
// add each result line to list
for (i=0; i<a_results.length; i++)
{
li = document.createElement('LI');
li.innerHTML = a_results[i].replace(/</, '<').replace(/>/, '>');
li._rcm_id = a_result_ids[i];
ul.appendChild(li);
}
// check if last selected item is still in result list
if (this.ksearch_selected!==null)
{
p = find_in_array(this.ksearch_selected, a_result_ids);
if (p>=0 && ul.childNodes)
{
ul.childNodes[p].setAttribute('id', 'rcmksearchSelected');
this.set_classname(ul.childNodes[p], 'selected', true);
}
else
this.ksearch_selected = null;
}
// if no item selected, select the first one
if (this.ksearch_selected===null)
{
ul.firstChild.setAttribute('id', 'rcmksearchSelected');
this.set_classname(ul.firstChild, 'selected', true);
this.ksearch_selected = a_result_ids[0];
}
// resize the containing layer to fit the list
//this.ksearch_pane.resize(ul.offsetWidth, ul.offsetHeight);
// move the results pane right under the input box and make it visible
var pos = rcube_get_object_pos(this.ksearch_input);
this.ksearch_pane.move(pos.x, pos.y+this.ksearch_input.offsetHeight);
this.ksearch_pane.show(1);
}
// hide results pane
else
this.ksearch_hide();
};
this.ksearch_blur = function(e, obj)
{
if (this.ksearch_timer)
clearTimeout(this.ksearch_timer);
this.ksearch_value = '';
this.ksearch_input = null;
this.ksearch_hide();
};
this.ksearch_hide = function()
{
this.ksearch_selected = null;
if (this.ksearch_pane)
this.ksearch_pane.show(0);
};
/*********************************************************/
/********* address book methods *********/
/*********************************************************/
this.list_contacts = function(page)
{
var add_url = '';
var target = window;
if (page && this.current_page==page)
return false;
// load contacts remotely
if (this.gui_objects.contactslist)
{
this.list_contacts_remote(page);
return;
}
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
{
target = window.frames[this.env.contentframe];
add_url = '&_framed=1';
}
this.set_busy(true, 'loading');
location.href = this.env.comm_path+(page ? '&_page='+page : '')+add_url;
};
// send remote request to load contacts list
this.list_contacts_remote = function(page)
{
// clear list
var table = this.gui_objects.contactslist;
var tbody = document.createElement('TBODY');
table.insertBefore(tbody, table.tBodies[0]);
table.tBodies[1].style.display = 'none';
this.contact_rows = new Array();
this.list_rows = this.contact_rows;
// send request to server
var url = page ? '&_page='+page : '';
this.set_busy(true, 'loading');
this.http_request('list', url, true);
};
// load contact record
this.load_contact = function(cid, action, framed)
{
var add_url = '';
var target = window;
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
{
add_url = '&_framed=1';
target = window.frames[this.env.contentframe];
document.getElementById(this.env.contentframe).style.visibility = 'inherit';
}
else if (framed)
return false;
//if (this.env.framed && add_url=='')
// add_url = '&_framed=1';
if (action && (cid || action=='add'))
{
this.set_busy(true);
target.location.href = this.env.comm_path+'&_action='+action+'&_cid='+cid+add_url;
}
return true;
};
this.delete_contacts = function()
{
// exit if no mailbox specified or if selection is empty
if (!(this.selection.length || this.env.cid) || !confirm(this.get_label('deletecontactconfirm')))
return;
var a_cids = new Array();
if (this.env.cid)
a_cids[a_cids.length] = this.env.cid;
else
{
var id;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
a_cids[a_cids.length] = id;
// 'remove' row from list (just hide it)
if (this.contact_rows[id].obj)
this.contact_rows[id].obj.style.display = 'none';
}
// hide content frame if we delete the currently displayed contact
if (this.selection.length==1 && this.env.contentframe)
{
var elm = document.getElementById(this.env.contentframe);
elm.style.visibility = 'hidden';
}
}
// send request to server
this.http_request('delete', '_cid='+a_cids.join(',')+'&_from='+(this.env.action ? this.env.action : ''));
return true;
};
// update a contact record in the list
this.update_contact_row = function(cid, cols_arr)
{
if (!this.contact_rows[cid] || !this.contact_rows[cid].obj)
return false;
var row = this.contact_rows[cid].obj;
for (var c=0; c<cols_arr.length; c++){
if (row.cells[c])
row.cells[c].innerHTML = cols_arr[c];
}
return true;
};
// load ldap search form
this.ldappublicsearch = function(action)
{
var add_url = '';
var target = window;
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
{
add_url = '&_framed=1';
target = window.frames[this.env.contentframe];
document.getElementById(this.env.contentframe).style.visibility = 'inherit';
}
else
return false;
if (action == 'ldappublicsearch')
target.location.href = this.env.comm_path+'&_action='+action+add_url;
return true;
};
// add ldap contacts to address book
this.add_ldap_contacts = function()
{
if (window.frames[this.env.contentframe].rcmail)
{
var frame = window.frames[this.env.contentframe];
// build the url
var url = '&_framed=1';
var emails = '&_emails=';
var names = '&_names=';
var end = '';
for (var n=0; n<frame.rcmail.selection.length; n++)
{
end = n < frame.rcmail.selection.length - 1 ? ',' : '';
emails += frame.rcmail.ldap_contact_rows[frame.rcmail.selection[n]].obj.cells[1].innerHTML + end;
names += frame.rcmail.ldap_contact_rows[frame.rcmail.selection[n]].obj.cells[0].innerHTML + end;
}
frame.location.href = this.env.comm_path + '&_action=save&_framed=1' + emails + names;
}
return false;
}
/*********************************************************/
/********* user settings methods *********/
/*********************************************************/
// load contact record
this.load_identity = function(id, action)
{
if (action=='edit-identity' && (!id || id==this.env.iid))
return false;
var add_url = '';
var target = window;
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
{
add_url = '&_framed=1';
target = window.frames[this.env.contentframe];
document.getElementById(this.env.contentframe).style.visibility = 'inherit';
}
if (action && (id || action=='add-identity'))
{
this.set_busy(true);
target.location.href = this.env.comm_path+'&_action='+action+'&_iid='+id+add_url;
}
return true;
};
this.delete_identity = function(id)
{
// exit if no mailbox specified or if selection is empty
if (!(this.selection.length || this.env.iid))
return;
if (!id)
id = this.env.iid ? this.env.iid : this.selection[0];
/*
// 'remove' row from list (just hide it)
if (this.identity_rows && this.identity_rows[id].obj)
{
this.clear_selection();
this.identity_rows[id].obj.style.display = 'none';
}
*/
// if (this.env.framed && id)
this.set_busy(true);
location.href = this.env.comm_path+'&_action=delete-identity&_iid='+id;
// else if (id)
// this.http_request('delete-identity', '_iid='+id);
return true;
};
// tell server to create and subscribe a new mailbox
this.create_folder = function(name)
{
if (this.edit_folder)
this.reset_folder_rename();
var form;
if ((form = this.gui_objects.editform) && form.elements['_folder_name'])
name = form.elements['_folder_name'].value;
if (name)
this.http_request('create-folder', '_name='+escape(name), true);
else if (form.elements['_folder_name'])
form.elements['_folder_name'].focus();
};
// entry point for folder renaming
this.rename_folder = function(props)
{
var form, oldname, newname;
// rename a specific mailbox
if (props)
this.edit_foldername(props);
// use a dropdown and input field (old behavior)
else if ((form = this.gui_objects.editform) && form.elements['_folder_oldname'] && form.elements['_folder_newname'])
{
oldname = form.elements['_folder_oldname'].value;
newname = form.elements['_folder_newname'].value;
}
if (oldname && newname)
this.http_request('rename-folder', '_folder_oldname='+escape(oldname)+'&_folder_newname='+escape(newname));
};
// start editing the mailbox name.
// this will replace the name string with an input field
this.edit_foldername = function(folder)
{
var temp, row, form;
var id = this.get_folder_row_id(folder);
// reset current renaming
if (temp = this.edit_folder)
{
this.reset_folder_rename();
if (temp == id)
return;
}
if (id && (row = document.getElementById(id)))
{
this.name_input = document.createElement('INPUT');
this.name_input.value = this.env.subscriptionrows[id];
this.name_input.style.width = '100%';
this.name_input.onkeypress = function(e){ rcmail.name_input_keypress(e); };
row.cells[0].replaceChild(this.name_input, row.cells[0].firstChild);
this.edit_folder = id;
this.name_input.select();
if (form = this.gui_objects.editform)
form.onsubmit = function(){ return false; };
}
};
// remove the input field and write the current mailbox name to the table cell
this.reset_folder_rename = function()
{
var cell = this.name_input ? this.name_input.parentNode : null;
if (cell && this.edit_folder)
cell.innerHTML = this.env.subscriptionrows[this.edit_folder];
this.edit_folder = null;
};
// handler for keyboard events on the input field
this.name_input_keypress = function(e)
{
var key = document.all ? event.keyCode : document.getElementById ? e.keyCode : 0;
// enter
if (key==13)
{
var newname = this.name_input ? this.name_input.value : null;
if (this.edit_folder && newname)
this.http_request('rename-folder', '_folder_oldname='+escape(this.env.subscriptionrows[this.edit_folder])+'&_folder_newname='+escape(newname));
}
// escape
else if (key==27)
this.reset_folder_rename();
};
// delete a specific mailbox with all its messages
this.delete_folder = function(folder)
{
if (this.edit_folder)
this.reset_folder_rename();
if (folder)
this.http_request('delete-folder', '_mboxes='+escape(folder));
};
// add a new folder to the subscription list by cloning a folder row
this.add_folder_row = function(name, replace)
{
name = name.replace('\\',"");
if (!this.gui_objects.subscriptionlist)
return false;
for (var refid in this.env.subscriptionrows)
if (this.env.subscriptionrows[refid]!=null)
break;
var refrow, form;
var tbody = this.gui_objects.subscriptionlist.tBodies[0];
var id = replace && replace.id ? replace.id : tbody.childNodes.length+1;
if (!id || !(refrow = document.getElementById(refid)))
{
// Refresh page if we don't have a table row to clone
location.href = this.env.comm_path+'&_action=folders';
}
else
{
// clone a table row if there are existing rows
var row = this.clone_table_row(refrow);
row.id = 'rcmrow'+id;
if (replace)
tbody.replaceChild(row, replace);
else
tbody.appendChild(row);
}
// add to folder/row-ID map
this.env.subscriptionrows[row.id] = name;
// set folder name
row.cells[0].innerHTML = name;
if (row.cells[1] && row.cells[1].firstChild.tagName=='INPUT')
{
row.cells[1].firstChild.value = name;
row.cells[1].firstChild.checked = true;
}
if (row.cells[2] && row.cells[2].firstChild.tagName=='A')
row.cells[2].firstChild.onclick = new Function(this.ref+".command('rename-folder','"+name.replace('\'','\\\'')+"')");
if (row.cells[3] && row.cells[3].firstChild.tagName=='A')
row.cells[3].firstChild.onclick = new Function(this.ref+".command('delete-folder','"+name.replace('\'','\\\'')+"')");
// add new folder to rename-folder list and clear input field
if (!replace && (form = this.gui_objects.editform))
{
if (form.elements['_folder_oldname'])
form.elements['_folder_oldname'].options[form.elements['_folder_oldname'].options.length] = new Option(name,name);
if (form.elements['_folder_name'])
form.elements['_folder_name'].value = '';
}
};
// replace an existing table row with a new folder line
this.replace_folder_row = function(newfolder, oldfolder)
{
var id = this.get_folder_row_id(oldfolder);
var row = document.getElementById(id);
// replace an existing table row (if found)
this.add_folder_row(newfolder, row);
this.env.subscriptionrows[id] = null;
// rename folder in rename-folder dropdown
var form, elm;
if ((form = this.gui_objects.editform) && (elm = form.elements['_folder_oldname']))
{
for (var i=0;i<elm.options.length;i++)
{
if (elm.options[i].value == oldfolder)
{
elm.options[i].text = newfolder;
elm.options[i].value = newfolder;
break;
}
}
form.elements['_folder_newname'].value = '';
}
};
// remove the table row of a specific mailbox from the table
// (the row will not be removed, just hidden)
this.remove_folder_row = function(folder)
{
var row;
var id = this.get_folder_row_id(folder);
if (id && (row = document.getElementById(id)))
row.style.display = 'none';
// remove folder from rename-folder list
var form;
if ((form = this.gui_objects.editform) && form.elements['_folder_oldname'])
{
for (var i=0;i<form.elements['_folder_oldname'].options.length;i++)
{
if (form.elements['_folder_oldname'].options[i].value == folder)
{
form.elements['_folder_oldname'].options[i] = null;
break;
}
}
}
if (form && form.elements['_folder_newname'])
form.elements['_folder_newname'].value = '';
};
this.subscribe_folder = function(folder)
{
var form;
if ((form = this.gui_objects.editform) && form.elements['_unsubscribed'])
this.change_subscription('_unsubscribed', '_subscribed', 'subscribe');
else if (folder)
this.http_request('subscribe', '_mboxes='+escape(folder));
};
this.unsubscribe_folder = function(folder)
{
var form;
if ((form = this.gui_objects.editform) && form.elements['_subscribed'])
this.change_subscription('_subscribed', '_unsubscribed', 'unsubscribe');
else if (folder)
this.http_request('unsubscribe', '_mboxes='+escape(folder));
};
this.change_subscription = function(from, to, action)
{
var form;
if (form = this.gui_objects.editform)
{
var a_folders = new Array();
var list_from = form.elements[from];
for (var i=0; list_from && i<list_from.options.length; i++)
{
if (list_from.options[i] && list_from.options[i].selected)
{
a_folders[a_folders.length] = list_from.options[i].value;
list_from[i] = null;
i--;
}
}
// yes, we have some folders selected
if (a_folders.length)
{
var list_to = form.elements[to];
var index;
for (var n=0; n<a_folders.length; n++)
{
index = list_to.options.length;
list_to[index] = new Option(a_folders[n]);
}
this.http_request(action, '_mboxes='+escape(a_folders.join(',')));
}
}
};
// helper method to find a specific mailbox row ID
this.get_folder_row_id = function(folder)
{
for (var id in this.env.subscriptionrows)
if (this.env.subscriptionrows[id]==folder)
break;
return id;
};
// duplicate a specific table row
this.clone_table_row = function(row)
{
var cell, td;
var new_row = document.createElement('TR');
for(var n=0; n<row.childNodes.length; n++)
{
cell = row.childNodes[n];
td = document.createElement('TD');
if (cell.className)
td.className = cell.className;
if (cell.align)
td.setAttribute('align', cell.align);
td.innerHTML = cell.innerHTML;
new_row.appendChild(td);
}
return new_row;
};
/*********************************************************/
/********* GUI functionality *********/
/*********************************************************/
// eable/disable buttons for page shifting
this.set_page_buttons = function()
{
this.enable_command('nextpage', (this.env.pagecount > this.env.current_page));
this.enable_command('previouspage', (this.env.current_page > 1));
}
// set button to a specific state
this.set_button = function(command, state)
{
var a_buttons = this.buttons[command];
var button, obj;
if(!a_buttons || !a_buttons.length)
return;
for(var n=0; n<a_buttons.length; n++)
{
button = a_buttons[n];
obj = document.getElementById(button.id);
// get default/passive setting of the button
if (obj && button.type=='image' && !button.status)
button.pas = obj._original_src ? obj._original_src : obj.src;
else if (obj && !button.status)
button.pas = String(obj.className);
// set image according to button state
if (obj && button.type=='image' && button[state])
{
button.status = state;
obj.src = button[state];
}
// set class name according to button state
else if (obj && typeof(button[state])!='undefined')
{
button.status = state;
obj.className = button[state];
}
// disable/enable input buttons
if (obj && button.type=='input')
{
button.status = state;
obj.disabled = !state;
}
}
};
// mouse over button
this.button_over = function(command, id)
{
var a_buttons = this.buttons[command];
var button, img;
if(!a_buttons || !a_buttons.length)
return;
for(var n=0; n<a_buttons.length; n++)
{
button = a_buttons[n];
if(button.id==id && button.status=='act')
{
img = document.getElementById(button.id);
if (img && button.over)
img.src = button.over;
}
}
};
// mouse down on button
this.button_sel = function(command, id)
{
var a_buttons = this.buttons[command];
var button, img;
if(!a_buttons || !a_buttons.length)
return;
for(var n=0; n<a_buttons.length; n++)
{
button = a_buttons[n];
if(button.id==id && button.status=='act')
{
img = document.getElementById(button.id);
if (img && button.sel)
img.src = button.sel;
}
}
};
// mouse out of button
this.button_out = function(command, id)
{
var a_buttons = this.buttons[command];
var button, img;
if(!a_buttons || !a_buttons.length)
return;
for(var n=0; n<a_buttons.length; n++)
{
button = a_buttons[n];
if(button.id==id && button.status=='act')
{
img = document.getElementById(button.id);
if (img && button.act)
img.src = button.act;
}
}
};
// set/unset a specific class name
this.set_classname = function(obj, classname, set)
{
var reg = new RegExp('\s*'+classname, 'i');
if (!set && obj.className.match(reg))
obj.className = obj.className.replace(reg, '');
else if (set && !obj.className.match(reg))
obj.className += ' '+classname;
};
// display a specific alttext
this.alttext = function(text)
{
};
// display a system message
this.display_message = function(msg, type, hold)
{
this.set_busy(false);
if (!this.loaded) // save message in order to display after page loaded
{
this.pending_message = new Array(msg, type);
return true;
}
if (!this.gui_objects.message)
return false;
if (this.message_timer)
clearTimeout(this.message_timer);
var cont = msg;
if (type)
cont = '<div class="'+type+'">'+cont+'</div>';
this.gui_objects.message._rcube = this;
this.gui_objects.message.innerHTML = cont;
this.gui_objects.message.style.display = 'block';
if (type!='loading')
this.gui_objects.message.onmousedown = function(){ this._rcube.hide_message(); return true; };
if (!hold)
this.message_timer = setTimeout(this.ref+'.hide_message()', this.message_time);
};
// make a message row disapear
this.hide_message = function()
{
if (this.gui_objects.message)
{
this.gui_objects.message.style.display = 'none';
this.gui_objects.message.onmousedown = null;
}
};
// mark a mailbox as selected and set environment variable
this.select_mailbox = function(mbox)
{
if (this.gui_objects.mailboxlist )
{
var item, reg, text_obj;
var current_li = this.get_mailbox_li();
var mbox_li = this.get_mailbox_li(mbox);
if (current_li)
{
this.set_classname(current_li, 'selected', false);
this.set_classname(current_li, 'unfocused', false);
}
if (mbox_li || this.env.mailbox == mbox)
{
this.set_classname(mbox_li, 'unfocused', false);
this.set_classname(mbox_li, 'selected', true);
}
}
// also update mailbox name in window title
if (document.title)
{
var doc_title = String(document.title);
var reg = new RegExp(this.env.mailbox.toLowerCase(), 'i');
if (this.env.mailbox && doc_title.match(reg))
document.title = doc_title.replace(reg, mbox).replace(/^\([0-9]+\)\s+/i, '');
}
this.env.mailbox = mbox;
};
// for reordering column array, Konqueror workaround
this.set_message_coltypes = function(coltypes)
{
this.coltypes = coltypes;
// set correct list titles
var cell, col;
var thead = this.gui_objects.messagelist ? this.gui_objects.messagelist.tHead : null;
for (var n=0; thead && n<this.coltypes.length; n++)
{
col = this.coltypes[n];
if ((cell = thead.rows[0].cells[n+1]) && (col=='from' || col=='to'))
{
// if we have links for sorting, it's a bit more complicated...
if (cell.firstChild && cell.firstChild.tagName=='A')
{
cell.firstChild.innerHTML = this.get_label(this.coltypes[n]);
cell.firstChild.onclick = function(){ return rcmail.command('sort', this.__col, this); };
cell.firstChild.__col = col;
}
else
cell.innerHTML = this.get_label(this.coltypes[n]);
cell.id = 'rcmHead'+col;
}
}
};
// create a table row in the message list
this.add_message_row = function(uid, cols, flags, attachment, attop)
{
if (!this.gui_objects.messagelist || !this.gui_objects.messagelist.tBodies[0])
return false;
var tbody = this.gui_objects.messagelist.tBodies[0];
var rowcount = tbody.rows.length;
var even = rowcount%2;
this.env.messages[uid] = {deleted:flags.deleted?1:0,
replied:flags.replied?1:0,
unread:flags.unread?1:0};
var row = document.createElement('TR');
row.id = 'rcmrow'+uid;
row.className = 'message '+(even ? 'even' : 'odd')+(flags.unread ? ' unread' : '')+(flags.deleted ? ' deleted' : '');
if (this.in_selection(uid))
row.className += ' selected';
var icon = flags.deleted && this.env.deletedicon ? this.env.deletedicon:
(flags.unread && this.env.unreadicon ? this.env.unreadicon :
(flags.replied && this.env.repliedicon ? this.env.repliedicon : this.env.messageicon));
var col = document.createElement('TD');
col.className = 'icon';
col.innerHTML = icon ? '<img src="'+icon+'" alt="" border="0" />' : '';
row.appendChild(col);
// add each submitted col
for (var n = 0; n < this.coltypes.length; n++)
{
var c = this.coltypes[n];
col = document.createElement('TD');
col.className = String(c).toLowerCase();
col.innerHTML = cols[c];
row.appendChild(col);
}
col = document.createElement('TD');
col.className = 'icon';
col.innerHTML = attachment && this.env.attachmenticon ? '<img src="'+this.env.attachmenticon+'" alt="" border="0" />' : '';
row.appendChild(col);
if (attop && tbody.rows.length)
tbody.insertBefore(row, tbody.firstChild);
else
tbody.appendChild(row);
this.init_message_row(row);
};
// replace content of row count display
this.set_rowcount = function(text)
{
if (this.gui_objects.countdisplay)
this.gui_objects.countdisplay.innerHTML = text;
// update page navigation buttons
this.set_page_buttons();
};
// replace content of quota display
this.set_quota = function(text)
{
if (this.gui_objects.quotadisplay)
this.gui_objects.quotadisplay.innerHTML = text;
};
// update the mailboxlist
this.set_unread_count = function(mbox, count, set_title)
{
if (!this.gui_objects.mailboxlist)
return false;
if (mbox==this.env.mailbox)
set_title = true;
var reg, text_obj;
var item = this.get_mailbox_li(mbox);
mbox = String(mbox).toLowerCase().replace(this.mbox_expression, '');
if (item && item.className && item.className.indexOf('mailbox '+mbox)>=0)
{
// set new text
text_obj = item.firstChild;
reg = /\s+\([0-9]+\)$/i;
if (count && text_obj.innerHTML.match(reg))
text_obj.innerHTML = text_obj.innerHTML.replace(reg, ' ('+count+')');
else if (count)
text_obj.innerHTML += ' ('+count+')';
else
text_obj.innerHTML = text_obj.innerHTML.replace(reg, '');
// set the right classes
this.set_classname(item, 'unread', count>0 ? true : false);
}
// set unread count to window title
reg = /^\([0-9]+\)\s+/i;
if (set_title && document.title)
{
var doc_title = String(document.title);
if (count && doc_title.match(reg))
document.title = doc_title.replace(reg, '('+count+') ');
else if (count)
document.title = '('+count+') '+doc_title;
else
document.title = doc_title.replace(reg, '');
}
};
// add row to contacts list
this.add_contact_row = function(cid, cols)
{
if (!this.gui_objects.contactslist || !this.gui_objects.contactslist.tBodies[0])
return false;
var tbody = this.gui_objects.contactslist.tBodies[0];
var rowcount = tbody.rows.length;
var even = rowcount%2;
var row = document.createElement('TR');
row.id = 'rcmrow'+cid;
row.className = 'contact '+(even ? 'even' : 'odd');
if (this.in_selection(cid))
row.className += ' selected';
// add each submitted col
for (var c in cols)
{
col = document.createElement('TD');
col.className = String(c).toLowerCase();
col.innerHTML = cols[c];
row.appendChild(col);
}
tbody.appendChild(row);
this.init_table_row(row, 'contact_rows');
};
/********************************************************/
/********* drag & drop methods *********/
/********************************************************/
this.drag_mouse_move = function(e)
{
if (this.drag_start)
{
if (!this.draglayer)
this.draglayer = new rcube_layer('rcmdraglayer', {x:0, y:0, width:300, vis:0, zindex:2000});
// get subjects of selectedd messages
var names = '';
var c, subject, obj;
for(var n=0; n<this.selection.length; n++)
{
if (n>12) // only show 12 lines
{
names += '...';
break;
}
if (this.message_rows[this.selection[n]].obj)
{
obj = this.message_rows[this.selection[n]].obj;
subject = '';
for(c=0; c<obj.childNodes.length; c++)
if (!subject && obj.childNodes[c].nodeName=='TD' && obj.childNodes[c].firstChild && obj.childNodes[c].firstChild.nodeType==3)
{
subject = obj.childNodes[c].firstChild.data;
names += (subject.length > 50 ? subject.substring(0, 50)+'...' : subject) + '<br />';
}
}
}
this.draglayer.write(names);
this.draglayer.show(1);
}
var pos = this.get_mouse_pos(e);
this.draglayer.move(pos.x+20, pos.y-5);
this.drag_start = false;
this.drag_active = true;
return false;
};
this.drag_mouse_up = function()
{
document.onmousemove = null;
if (this.draglayer && this.draglayer.visible)
this.draglayer.show(0);
this.drag_active = false;
return false;
};
/********************************************************/
/********* remote request methods *********/
/********************************************************/
this.http_sockets = new Array();
// find a non-busy socket or create a new one
this.get_request_obj = function()
{
for (var n=0; n<this.http_sockets.length; n++)
{
if (!this.http_sockets[n].busy)
return this.http_sockets[n];
}
// create a new XMLHTTP object
var i = this.http_sockets.length;
this.http_sockets[i] = new rcube_http_request();
return this.http_sockets[i];
};
// send a http request to the server
this.http_request = function(action, querystring, lock)
{
var request_obj = this.get_request_obj();
querystring += '&_remote=1';
// add timestamp to request url to avoid cacheing problems in Safari
if (bw.safari)
querystring += '&_ts='+(new Date().getTime());
// send request
if (request_obj)
{
// prompt('request', this.env.comm_path+'&_action='+escape(action)+'&'+querystring);
console('HTTP request: '+this.env.comm_path+'&_action='+escape(action)+'&'+querystring);
if (lock)
this.set_busy(true);
request_obj.__lock = lock ? true : false;
request_obj.__action = action;
request_obj.onerror = function(o){ rcube_webmail_client.http_error(o); };
request_obj.oncomplete = function(o){ rcube_webmail_client.http_response(o); };
request_obj.GET(this.env.comm_path+'&_action='+escape(action)+'&'+querystring);
}
};
// handle HTTP response
this.http_response = function(request_obj)
{
var ctype = request_obj.get_header('Content-Type');
if (ctype){
ctype = String(ctype).toLowerCase();
var ctype_array=ctype.split(";");
ctype = ctype_array[0];
}
this.set_busy(false);
console(request_obj.get_text());
// if we get javascript code from server -> execute it
if (request_obj.get_text() && (ctype=='text/javascript' || ctype=='application/x-javascript'))
eval(request_obj.get_text());
// process the response data according to the sent action
switch (request_obj.__action)
{
case 'delete':
case 'moveto':
if (this.env.action=='show')
this.command('list');
break;
case 'list':
if (this.env.messagecount)
this.enable_command('purge', (this.env.mailbox==this.env.trash_mailbox));
case 'expunge':
this.enable_command('select-all', 'select-none', 'expunge', this.env.messagecount ? true : false);
break;
}
request_obj.reset();
};
// handle HTTP request errors
this.http_error = function(request_obj)
{
//alert('Error sending request: '+request_obj.url);
if (request_obj.__lock)
this.set_busy(false);
request_obj.reset();
request_obj.__lock = false;
};
// use an image to send a keep-alive siganl to the server
this.send_keep_alive = function()
{
var d = new Date();
this.http_request('keep-alive', '_t='+d.getTime());
};
// send periodic request to check for recent messages
this.check_for_recent = function()
{
+ if (this.busy)
+ {
+ this.send_keep_alive();
+ return;
+ }
+
this.set_busy(true, 'checkingmail');
var d = new Date();
this.http_request('check-recent', '_t='+d.getTime());
};
/********************************************************/
/********* helper methods *********/
/********************************************************/
// check if we're in show mode or if we have a unique selection
// and return the message uid
this.get_single_uid = function()
{
return this.env.uid ? this.env.uid : (this.selection.length==1 ? this.selection[0] : null);
};
// same as above but for contacts
this.get_single_cid = function()
{
return this.env.cid ? this.env.cid : (this.selection.length==1 ? this.selection[0] : null);
};
/* deprecated methods
// check if Shift-key is pressed on event
this.check_shiftkey = function(e)
{
if(!e && window.event)
e = window.event;
if(bw.linux && bw.ns4 && e.modifiers)
return true;
else if((bw.ns4 && e.modifiers & Event.SHIFT_MASK) || (e && e.shiftKey))
return true;
else
return false;
}
// check if Shift-key is pressed on event
this.check_ctrlkey = function(e)
{
if(!e && window.event)
e = window.event;
if(bw.linux && bw.ns4 && e.modifiers)
return true;
else if (bw.mac)
return this.check_shiftkey(e);
else if((bw.ns4 && e.modifiers & Event.CTRL_MASK) || (e && e.ctrlKey))
return true;
else
return false;
}
*/
// returns modifier key (constants defined at top of file)
this.get_modifier = function(e)
{
var opcode = 0;
e = e || window.event;
if (bw.mac && e)
{
opcode += (e.metaKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
return opcode;
}
if (e)
{
opcode += (e.ctrlKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
return opcode;
}
if (e.cancelBubble)
{
e.cancelBubble = true;
e.returnValue = false;
}
else if (e.preventDefault)
e.preventDefault();
}
this.get_mouse_pos = function(e)
{
if(!e) e = window.event;
var mX = (e.pageX) ? e.pageX : e.clientX;
var mY = (e.pageY) ? e.pageY : e.clientY;
if(document.body && document.all)
{
mX += document.body.scrollLeft;
mY += document.body.scrollTop;
}
return { x:mX, y:mY };
};
this.get_caret_pos = function(obj)
{
if (typeof(obj.selectionEnd)!='undefined')
return obj.selectionEnd;
else if (document.selection && document.selection.createRange)
{
var range = document.selection.createRange();
if (range.parentElement()!=obj)
return 0;
var gm = range.duplicate();
if (obj.tagName=='TEXTAREA')
gm.moveToElementText(obj);
else
gm.expand('textedit');
gm.setEndPoint('EndToStart', range);
var p = gm.text.length;
return p<=obj.value.length ? p : -1;
}
else
return obj.value.length;
};
this.set_caret2start = function(obj)
{
if (obj.createTextRange)
{
var range = obj.createTextRange();
range.collapse(true);
range.select();
}
else if (obj.setSelectionRange)
obj.setSelectionRange(0,0);
obj.focus();
};
// set all fields of a form disabled
this.lock_form = function(form, lock)
{
if (!form || !form.elements)
return;
var type;
for (var n=0; n<form.elements.length; n++)
{
type = form.elements[n];
if (type=='hidden')
continue;
form.elements[n].disabled = lock;
}
};
} // end object rcube_webmail
// class for HTTP requests
function rcube_http_request()
{
this.url = '';
this.busy = false;
this.xmlhttp = null;
// reset object properties
this.reset = function()
{
// set unassigned event handlers
this.onloading = function(){ };
this.onloaded = function(){ };
this.oninteractive = function(){ };
this.oncomplete = function(){ };
this.onabort = function(){ };
this.onerror = function(){ };
this.url = '';
this.busy = false;
this.xmlhttp = null;
}
// create HTMLHTTP object
this.build = function()
{
if (window.XMLHttpRequest)
this.xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject)
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
else
{
}
}
// sedn GET request
this.GET = function(url)
{
this.build();
if (!this.xmlhttp)
{
this.onerror(this);
return false;
}
var ref = this;
this.url = url;
this.busy = true;
this.xmlhttp.onreadystatechange = function(){ ref.xmlhttp_onreadystatechange(); };
this.xmlhttp.open('GET', url);
this.xmlhttp.send(null);
};
this.POST = function(url, a_param)
{
// not implemented yet
};
// handle onreadystatechange event
this.xmlhttp_onreadystatechange = function()
{
if(this.xmlhttp.readyState == 1)
this.onloading(this);
else if(this.xmlhttp.readyState == 2)
this.onloaded(this);
else if(this.xmlhttp.readyState == 3)
this.oninteractive(this);
else if(this.xmlhttp.readyState == 4)
{
try {
if (this.xmlhttp.status == 0)
this.onabort(this);
else if(this.xmlhttp.status == 200)
this.oncomplete(this);
else
this.onerror(this);
this.busy = false;
}
catch(err)
{
this.onerror(this);
this.busy = false;
}
}
}
// getter method for HTTP headers
this.get_header = function(name)
{
return this.xmlhttp.getResponseHeader(name);
};
this.get_text = function()
{
return this.xmlhttp.responseText;
};
this.get_xml = function()
{
return this.xmlhttp.responseXML;
};
this.reset();
} // end class rcube_http_request
function console(str)
{
if (document.debugform && document.debugform.console)
document.debugform.console.value += str+'\n--------------------------------------\n';
}
// set onload handler
window.onload = function(e)
{
if (window.rcube_webmail_client)
rcube_webmail_client.init();
};
diff --git a/program/steps/mail/compose.inc b/program/steps/mail/compose.inc
index 32378f59c..639ea684e 100644
--- a/program/steps/mail/compose.inc
+++ b/program/steps/mail/compose.inc
@@ -1,797 +1,798 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/compose.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Compose a new mail message with all headers and attachments |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
require_once('Mail/mimeDecode.php');
// remove an attachment
-if ($_action=='remove-attachment' && !empty($_GET['_filename']))
+if ($_action=='remove-attachment' && preg_match('/^rcmfile([0-9]+)$/', $_GET['_file'], $regs))
{
- if (is_array($_SESSION['compose']['attachments']))
- foreach ($_SESSION['compose']['attachments'] as $i => $attachment)
- if ($attachment['name'] == $_GET['_filename'])
- {
- @unlink($attachment['path']);
- unset($_SESSION['compose']['attachments'][$i]);
- $commands = sprintf("parent.%s.remove_from_attachment_list('%s');\n", $JS_OBJECT_NAME, $_GET['_filename']);
- rcube_remote_response($commands);
- exit;
- }
+ $id = $regs[1];
+ if (is_array($_SESSION['compose']['attachments'][$id]))
+ {
+ @unlink($_SESSION['compose']['attachments'][$id]['path']);
+ $_SESSION['compose']['attachments'][$id] = NULL;
+ $commands = sprintf("parent.%s.remove_from_attachment_list('rcmfile%d');\n", $JS_OBJECT_NAME, $id);
+ rcube_remote_response($commands);
+ exit;
+ }
}
+
$MESSAGE_FORM = NULL;
$REPLY_MESSAGE = NULL;
$FORWARD_MESSAGE = NULL;
$DRAFT_MESSAGE = NULL;
// nothing below is called during message composition, only at "new/forward/reply/draft" initialization
// since there are many ways to leave the compose page improperly, it seems necessary to clean-up an old
// compose when a "new/forward/reply/draft" is called - otherwise the old session attachments will appear
rcmail_compose_cleanup();
$_SESSION['compose'] = array('id' => uniqid(rand()));
// add some labels to client
rcube_add_label('nosubject', 'norecipientwarning', 'nosubjectwarning', 'nobodywarning', 'notsentwarning', 'savingmessage', 'sendingmessage', 'messagesaved');
if ($_GET['_reply_uid'] || $_GET['_forward_uid'] || $_GET['_draft_uid'])
{
$msg_uid = ($_GET['_reply_uid'] ? $_GET['_reply_uid'] : ($_GET['_forward_uid'] ? $_GET['_forward_uid'] : $_GET['_draft_uid']));
// similar as in program/steps/mail/show.inc
$MESSAGE = array();
$MESSAGE['headers'] = $IMAP->get_headers($msg_uid);
$MESSAGE['source'] = rcmail_message_source($msg_uid);
$mmd = new Mail_mimeDecode($MESSAGE['source']);
$MESSAGE['structure'] = $mmd->decode(array('include_bodies' => TRUE,
'decode_headers' => TRUE,
'decode_bodies' => FALSE));
$MESSAGE['subject'] = $IMAP->decode_header($MESSAGE['headers']->subject);
$MESSAGE['parts'] = $mmd->getMimeNumbers($MESSAGE['structure']);
if ($_GET['_reply_uid'])
{
$REPLY_MESSAGE = &$MESSAGE;
$_SESSION['compose']['reply_uid'] = $_GET['_reply_uid'];
$_SESSION['compose']['reply_msgid'] = $REPLY_MESSAGE['headers']->messageID;
$_SESSION['compose']['references'] = $REPLY_MESSAGE['headers']->reference;
$_SESSION['compose']['references'] .= !empty($REPLY_MESSAGE['headers']->reference) ? ' ' : '';
$_SESSION['compose']['references'] .= $REPLY_MESSAGE['headers']->messageID;
if ($_GET['_all'])
$REPLY_MESSAGE['reply_all'] = 1;
}
else if ($_GET['_forward_uid'])
{
$FORWARD_MESSAGE = $MESSAGE;
$_SESSION['compose']['forward_uid'] = $_GET['_forward_uid'];
}
else
{
$DRAFT_MESSAGE = $MESSAGE;
$_SESSION['compose']['draft_uid'] = $_GET['_draft_uid'];
}
}
/****** compose mode functions ********/
function rcmail_compose_headers($attrib)
{
global $IMAP, $REPLY_MESSAGE, $DRAFT_MESSAGE, $DB;
static $sa_recipients = array();
list($form_start, $form_end) = get_form_tags($attrib);
$out = '';
$part = strtolower($attrib['part']);
switch ($part)
{
case 'from':
return rcmail_compose_header_from($attrib);
case 'to':
$fname = '_to';
$header = 'to';
// we have contact id's as get parameters
if (!empty($_GET['_to']) && preg_match('/^[0-9]+(,[0-9]+)*$/', $_GET['_to']))
{
$a_recipients = array();
$sql_result = $DB->query("SELECT name, email
FROM ".get_table_name('contacts')."
WHERE user_id=?
AND del<>1
AND contact_id IN (".$_GET['_to'].")",
$_SESSION['user_id']);
while ($sql_arr = $DB->fetch_assoc($sql_result))
$a_recipients[] = format_email_recipient($sql_arr['email'], $sql_arr['name']);
if (sizeof($a_recipients))
$fvalue = join(', ', $a_recipients);
}
else if (!empty($_GET['_to']))
$fvalue = $_GET['_to'];
case 'cc':
if (!$fname)
{
$fname = '_cc';
$header = 'cc';
}
case 'bcc':
if (!$fname)
$fname = '_bcc';
$allow_attrib = array('id', 'class', 'style', 'cols', 'rows', 'wrap', 'tabindex');
$field_type = 'textarea';
break;
case 'replyto':
case 'reply-to':
$fname = '_replyto';
$allow_attrib = array('id', 'class', 'style', 'size', 'tabindex');
$field_type = 'textfield';
break;
}
if ($fname && !empty($_POST[$fname]))
$fvalue = get_input_value($fname, RCUBE_INPUT_POST, TRUE);
else if ($header && is_object($REPLY_MESSAGE['headers']))
{
// get recipent address(es) out of the message headers
if ($header=='to' && $REPLY_MESSAGE['headers']->replyto)
$fvalue = $IMAP->decode_header($REPLY_MESSAGE['headers']->replyto);
else if ($header=='to' && $REPLY_MESSAGE['headers']->from)
$fvalue = $IMAP->decode_header($REPLY_MESSAGE['headers']->from);
// add recipent of original message if reply to all
else if ($header=='cc' && $REPLY_MESSAGE['reply_all'])
{
if ($IMAP->decode_header($REPLY_MESSAGE['headers']->to))
$fvalue .= $IMAP->decode_header($REPLY_MESSAGE['headers']->to);
if ($IMAP->decode_header($REPLY_MESSAGE['headers']->cc))
{
if($fvalue)
$fvalue .= ', ';
$fvalue .= $IMAP->decode_header($REPLY_MESSAGE['headers']->cc);
}
}
// split recipients and put them back together in a unique way
if (!empty($fvalue))
{
$to_addresses = $IMAP->decode_address_list($fvalue);
$fvalue = '';
foreach ($to_addresses as $addr_part)
{
if (!in_array($addr_part['mailto'], $sa_recipients) && (!$REPLY_MESSAGE['FROM'] || !in_array($addr_part['mailto'], $REPLY_MESSAGE['FROM'])))
{
$fvalue .= (strlen($fvalue) ? ', ':'').$addr_part['string'];
$sa_recipients[] = $addr_part['mailto'];
}
}
}
}
else if ($header && is_object($DRAFT_MESSAGE['headers']))
{
// get drafted headers
if ($header=='to' && $DRAFT_MESSAGE['headers']->to)
$fvalue = $IMAP->decode_header($DRAFT_MESSAGE['headers']->to);
if ($header=='cc' && $DRAFT_MESSAGE['headers']->cc)
$fvalue = $IMAP->decode_header($DRAFT_MESSAGE['headers']->cc);
if ($header=='bcc' && $DRAFT_MESSAGE['headers']->bcc)
$fvalue = $IMAP->decode_header($DRAFT_MESSAGE['headers']->bcc);
}
if ($fname && $field_type)
{
// pass the following attributes to the form class
$field_attrib = array('name' => $fname);
foreach ($attrib as $attr => $value)
if (in_array($attr, $allow_attrib))
$field_attrib[$attr] = $value;
// create teaxtarea object
$input = new $field_type($field_attrib);
$out = $input->show($fvalue);
}
if ($form_start)
$out = $form_start.$out;
return $out;
}
function rcmail_compose_header_from($attrib)
{
global $IMAP, $REPLY_MESSAGE, $DRAFT_MESSAGE, $DB, $OUTPUT, $JS_OBJECT_NAME;
// pass the following attributes to the form class
$field_attrib = array('name' => '_from');
foreach ($attrib as $attr => $value)
if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
$field_attrib[$attr] = $value;
// extract all recipients of the reply-message
$a_recipients = array();
if ($REPLY_MESSAGE && is_object($REPLY_MESSAGE['headers']))
{
$REPLY_MESSAGE['FROM'] = array();
$a_to = $IMAP->decode_address_list($REPLY_MESSAGE['headers']->to);
foreach ($a_to as $addr)
{
if (!empty($addr['mailto']))
$a_recipients[] = $addr['mailto'];
}
if (!empty($REPLY_MESSAGE['headers']->cc))
{
$a_cc = $IMAP->decode_address_list($REPLY_MESSAGE['headers']->cc);
foreach ($a_cc as $addr)
{
if (!empty($addr['mailto']))
$a_recipients[] = $addr['mailto'];
}
}
}
// get this user's identities
$sql_result = $DB->query("SELECT identity_id, name, email, signature
FROM ".get_table_name('identities')."
WHERE user_id=?
AND del<>1
ORDER BY ".$DB->quoteIdentifier('standard')." DESC, name ASC",
$_SESSION['user_id']);
if ($DB->num_rows($sql_result))
{
$from_id = 0;
$a_signatures = array();
$field_attrib['onchange'] = "$JS_OBJECT_NAME.change_identity(this)";
$select_from = new select($field_attrib);
while ($sql_arr = $DB->fetch_assoc($sql_result))
{
$select_from->add(format_email_recipient($sql_arr['email'], $sql_arr['name']), $sql_arr['identity_id']);
// add signature to array
if (!empty($sql_arr['signature']))
$a_signatures[$sql_arr['identity_id']] = $sql_arr['signature'];
// set identity if it's one of the reply-message recipients
if (in_array($sql_arr['email'], $a_recipients))
$from_id = $sql_arr['identity_id'];
if ($REPLY_MESSAGE && is_array($REPLY_MESSAGE['FROM']))
$REPLY_MESSAGE['FROM'][] = $sql_arr['email'];
if (strstr($DRAFT_MESSAGE['headers']->from,$sql_arr['email']))
$from_id = $sql_arr['identity_id'];
}
// overwrite identity selection with post parameter
if (isset($_POST['_from']))
$from_id = $_POST['_from'];
$out = $select_from->show($from_id);
// add signatures to client
$OUTPUT->add_script(sprintf("%s.set_env('signatures', %s);", $JS_OBJECT_NAME, array2js($a_signatures)));
}
else
{
$input_from = new textfield($field_attrib);
$out = $input_from->show($_POST['_from']);
}
if ($form_start)
$out = $form_start.$out;
return $out;
}
function rcmail_compose_body($attrib)
{
global $CONFIG, $OUTPUT, $REPLY_MESSAGE, $FORWARD_MESSAGE, $DRAFT_MESSAGE, $JS_OBJECT_NAME;
list($form_start, $form_end) = get_form_tags($attrib);
unset($attrib['form']);
if (empty($attrib['id']))
$attrib['id'] = 'rcmComposeMessage';
$attrib['name'] = '_message';
$textarea = new textarea($attrib);
$body = '';
// use posted message body
if (!empty($_POST['_message']))
$body = get_input_value('_message', RCUBE_INPUT_POST, TRUE);
// compose reply-body
else if (is_array($REPLY_MESSAGE['parts']))
{
$body = rcmail_first_text_part($REPLY_MESSAGE['parts']);
if (strlen($body))
$body = rcmail_create_reply_body($body);
}
// forward message body inline
else if (is_array($FORWARD_MESSAGE['parts']))
{
$body = rcmail_first_text_part($FORWARD_MESSAGE['parts']);
if (strlen($body))
$body = rcmail_create_forward_body($body);
}
// forward message body inline
else if (is_array($DRAFT_MESSAGE['parts']))
{
$body = rcmail_first_text_part($DRAFT_MESSAGE['parts']);
if (strlen($body))
$body = rcmail_create_draft_body($body);
}
$out = $form_start ? "$form_start\n" : '';
$saveid = new hiddenfield(array('name' => '_draft_saveid', 'value' => str_replace(array('<','>'),"",$DRAFT_MESSAGE['headers']->messageID) ));
$out .= $saveid->show();
$drafttoggle = new hiddenfield(array('name' => '_draft', 'value' => 'yes'));
$out .= $drafttoggle->show();
$out .= $textarea->show($body);
$out .= $form_end ? "\n$form_end" : '';
// include GoogieSpell
if (!empty($CONFIG['enable_spellcheck']))
{
$OUTPUT->include_script('googiespell.js');
$OUTPUT->add_script(sprintf("var googie = new GoogieSpell('\$__skin_path/images/googiespell/','%s&_action=spell&lang=');\n".
"googie.lang_chck_spell = \"%s\";\n".
"googie.lang_rsm_edt = \"%s\";\n".
"googie.lang_close = \"%s\";\n".
"googie.lang_revert = \"%s\";\n".
"googie.lang_no_error_found = \"%s\";\n".
"googie.decorateTextarea('%s');\n".
"%s.set_env('spellcheck', googie);",
$GLOBALS['COMM_PATH'],
rep_specialchars_output(rcube_label('checkspelling')),
rep_specialchars_output(rcube_label('resumeediting')),
rep_specialchars_output(rcube_label('close')),
rep_specialchars_output(rcube_label('revertto')),
rep_specialchars_output(rcube_label('nospellerrors')),
$attrib['id'],
$JS_OBJECT_NAME), 'foot');
rcube_add_label('checking');
}
$out .= "\n".'<iframe name="savetarget" src="program/blank.gif" style="width:0;height:0;visibility:hidden;"></iframe>';
return $out;
}
function rcmail_create_reply_body($body)
{
global $IMAP, $REPLY_MESSAGE;
// soft-wrap message first
$body = wordwrap($body, 75);
// split body into single lines
$a_lines = preg_split('/\r?\n/', $body);
// add > to each line
for($n=0; $n<sizeof($a_lines); $n++)
{
if (strpos($a_lines[$n], '>')===0)
$a_lines[$n] = '>'.$a_lines[$n];
else
$a_lines[$n] = '> '.$a_lines[$n];
}
$body = join("\n", $a_lines);
// add title line
$pefix = sprintf("\n\n\nOn %s, %s wrote:\n",
$REPLY_MESSAGE['headers']->date,
$IMAP->decode_header($REPLY_MESSAGE['headers']->from));
// try to remove the signature
if ($sp = strrpos($body, '-- '))
{
if ($body{$sp+3}==' ' || $body{$sp+3}=="\n" || $body{$sp+3}=="\r")
$body = substr($body, 0, $sp-1);
}
return $pefix.$body;
}
function rcmail_create_forward_body($body)
{
global $IMAP, $FORWARD_MESSAGE;
// soft-wrap message first
$body = wordwrap($body, 80);
$prefix = sprintf("\n\n\n-------- Original Message --------\nSubject: %s\nDate: %s\nFrom: %s\nTo: %s\n\n",
$FORWARD_MESSAGE['subject'],
$FORWARD_MESSAGE['headers']->date,
$IMAP->decode_header($FORWARD_MESSAGE['headers']->from),
$IMAP->decode_header($FORWARD_MESSAGE['headers']->to));
// add attachments
if (!isset($_SESSION['compose']['forward_attachments']) && is_array($FORWARD_MESSAGE['parts']) && sizeof($FORWARD_MESSAGE['parts'])>1)
{
$temp_dir = rcmail_create_compose_tempdir();
if (!is_array($_SESSION['compose']['attachments']))
$_SESSION['compose']['attachments'] = array();
foreach ($FORWARD_MESSAGE['parts'] as $part)
{
if ($part->disposition=='attachment' || $part->disposition=='inline' || $part->headers['content-id'] ||
(empty($part->disposition) && ($part->d_parameters['filename'] || $part->ctype_parameters['name'])))
- {
+ {
$tmp_path = tempnam($temp_dir, 'rcmAttmnt');
if ($fp = fopen($tmp_path, 'w'))
{
fwrite($fp, $IMAP->mime_decode($part->body, $part->headers['content-transfer-encoding']));
fclose($fp);
if ($part->d_parameters['filename'])
$_SESSION['compose']['attachments'][] = array('name' => $part->d_parameters['filename'],
'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
'path' => $tmp_path);
else if ($part->ctype_parameters['name'])
$_SESSION['compose']['attachments'][] = array('name' => $part->ctype_parameters['name'],
'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
'path' => $tmp_path);
else if ($part->headers['content-description'])
$_SESSION['compose']['attachments'][] = array('name' => $part->headers['content-description'],
'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
'path' => $tmp_path);
}
}
}
$_SESSION['compose']['forward_attachments'] = TRUE;
}
return $prefix.$body;
}
function rcmail_create_draft_body($body)
{
global $IMAP, $DRAFT_MESSAGE;
// add attachments
if (!isset($_SESSION['compose']['forward_attachments']) && is_array($DRAFT_MESSAGE['parts']) && sizeof($DRAFT_MESSAGE['parts'])>1)
{
$temp_dir = rcmail_create_compose_tempdir();
if (!is_array($_SESSION['compose']['attachments']))
$_SESSION['compose']['attachments'] = array();
foreach ($DRAFT_MESSAGE['parts'] as $part)
{
if ($part->disposition=='attachment' || $part->disposition=='inline' || $part->headers['content-id'] ||
(empty($part->disposition) && ($part->d_parameters['filename'] || $part->ctype_parameters['name'])))
{
$tmp_path = tempnam($temp_dir, 'rcmAttmnt');
if ($fp = fopen($tmp_path, 'w'))
{
fwrite($fp, $IMAP->mime_decode($part->body, $part->headers['content-transfer-encoding']));
fclose($fp);
if ($part->d_parameters['filename'])
$_SESSION['compose']['attachments'][] = array('name' => $part->d_parameters['filename'],
'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
'path' => $tmp_path);
else if ($part->ctype_parameters['name'])
$_SESSION['compose']['attachments'][] = array('name' => $part->ctype_parameters['name'],
'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
'path' => $tmp_path);
else if ($part->headers['content-description'])
$_SESSION['compose']['attachments'][] = array('name' => $part->headers['content-description'],
'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
'path' => $tmp_path);
}
}
}
$_SESSION['compose']['forward_attachments'] = TRUE;
}
return $body;
}
function rcmail_compose_subject($attrib)
{
global $CONFIG, $REPLY_MESSAGE, $FORWARD_MESSAGE, $DRAFT_MESSAGE;
list($form_start, $form_end) = get_form_tags($attrib);
unset($attrib['form']);
$attrib['name'] = '_subject';
$textfield = new textfield($attrib);
$subject = '';
// use subject from post
if (isset($_POST['_subject']))
$subject = get_input_value('_subject', RCUBE_INPUT_POST, TRUE);
// create a reply-subject
else if (isset($REPLY_MESSAGE['subject']))
{
if (eregi('^re:', $REPLY_MESSAGE['subject']))
$subject = $REPLY_MESSAGE['subject'];
else
$subject = 'Re: '.$REPLY_MESSAGE['subject'];
}
// create a forward-subject
else if (isset($FORWARD_MESSAGE['subject']))
{
if (eregi('^fwd:', $REPLY_MESSAGE['subject']))
$subject = $FORWARD_MESSAGE['subject'];
else
$subject = 'Fwd: '.$FORWARD_MESSAGE['subject'];
}
// creeate a draft-subject
else if (isset($DRAFT_MESSAGE['subject']))
$subject = $DRAFT_MESSAGE['subject'];
$out = $form_start ? "$form_start\n" : '';
$out .= $textfield->show($subject);
$out .= $form_end ? "\n$form_end" : '';
return $out;
}
function rcmail_compose_attachment_list($attrib)
{
global $OUTPUT, $JS_OBJECT_NAME;
// add ID if not given
if (!$attrib['id'])
$attrib['id'] = 'rcmAttachmentList';
// allow the following attributes to be added to the <ul> tag
$attrib_str = create_attrib_string($attrib, array('id', 'class', 'style'));
$out = '<ul'. $attrib_str . ">\n";
if (is_array($_SESSION['compose']['attachments']))
{
if ($attrib['deleteicon'])
- $button = sprintf('<img src="%s%s" alt="%s" border="0" / style="padding-right:2px;vertical-align:middle">',
+ $button = sprintf('<img src="%s%s" alt="%s" border="0" style="padding-right:2px;vertical-align:middle" />',
$CONFIG['skin_path'],
$attrib['deleteicon'],
rcube_label('delete'));
else
$button = rcube_label('delete');
- foreach ($_SESSION['compose']['attachments'] as $i => $a_prop)
- $out .= sprintf('<li id="%s"><a href="#" onclick="%s.command(\'remove-attachment\',\'%s\')" title="%s">%s</a>%s</li>',
- $a_prop['name'],
+ foreach ($_SESSION['compose']['attachments'] as $id => $a_prop)
+ $out .= sprintf('<li id="rcmfile%d"><a href="#delete" onclick="return %s.command(\'remove-attachment\',\'rcmfile%d\', this)" title="%s">%s</a>%s</li>',
+ $id,
$JS_OBJECT_NAME,
- $a_prop['name'],
+ $id,
rcube_label('delete'),
- $button, $a_prop['name']);
+ $button,
+ rep_specialchars_output($a_prop['name']));
}
$OUTPUT->add_script(sprintf("%s.gui_object('attachmentlist', '%s');", $JS_OBJECT_NAME, $attrib['id']));
$out .= '</ul>';
return $out;
}
function rcmail_compose_attachment_form($attrib)
{
global $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
// add ID if not given
if (!$attrib['id'])
$attrib['id'] = 'rcmUploadbox';
// allow the following attributes to be added to the <div> tag
$attrib_str = create_attrib_string($attrib, array('id', 'class', 'style'));
$input_field = rcmail_compose_attachment_field(array());
$label_send = rcube_label('upload');
$label_close = rcube_label('close');
$out = <<<EOF
<div$attrib_str>
<form action="./" method="post" enctype="multipart/form-data">
$SESS_HIDDEN_FIELD
$input_field<br />
<input type="button" value="$label_close" class="button" onclick="document.getElementById('$attrib[id]').style.visibility='hidden'" />
<input type="button" value="$label_send" class="button" onclick="$JS_OBJECT_NAME.command('send-attachment', this.form)" />
</form>
</div>
EOF;
$OUTPUT->add_script(sprintf("%s.gui_object('uploadbox', '%s');", $JS_OBJECT_NAME, $attrib['id']));
return $out;
}
function rcmail_compose_attachment_field($attrib)
{
// allow the following attributes to be added to the <input> tag
$attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'size'));
$out = '<input type="file" name="_attachments[]"'. $attrib_str . " />";
return $out;
}
function rcmail_priority_selector($attrib)
{
list($form_start, $form_end) = get_form_tags($attrib);
unset($attrib['form']);
$attrib['name'] = '_priority';
$selector = new select($attrib);
$selector->add(array(rcube_label('lowest'),
rcube_label('low'),
rcube_label('normal'),
rcube_label('high'),
rcube_label('highest')),
array(5, 4, 0, 2, 1));
$sel = isset($_POST['_priority']) ? $_POST['_priority'] : 0;
$out = $form_start ? "$form_start\n" : '';
$out .= $selector->show($sel);
$out .= $form_end ? "\n$form_end" : '';
return $out;
}
function rcmail_receipt_checkbox($attrib)
{
list($form_start, $form_end) = get_form_tags($attrib);
unset($attrib['form']);
if (!isset($attrib['id']))
$attrib['id'] = 'receipt';
$attrib['name'] = '_receipt';
$attrib['value'] = '1';
$checkbox = new checkbox($attrib);
$out = $form_start ? "$form_start\n" : '';
$out .= $checkbox->show(0);
$out .= $form_end ? "\n$form_end" : '';
return $out;
}
function get_form_tags($attrib)
{
global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $MESSAGE_FORM, $SESS_HIDDEN_FIELD;
$form_start = '';
if (!strlen($MESSAGE_FORM))
{
$hiddenfields = new hiddenfield(array('name' => '_task', 'value' => $GLOBALS['_task']));
$hiddenfields->add(array('name' => '_action', 'value' => 'send'));
$form_start = empty($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
$form_start .= "\n$SESS_HIDDEN_FIELD\n";
$form_start .= $hiddenfields->show();
}
$form_end = (strlen($MESSAGE_FORM) && !strlen($attrib['form'])) ? '</form>' : '';
$form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
if (!strlen($MESSAGE_FORM))
$OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('messageform', '$form_name');");
$MESSAGE_FORM = $form_name;
return array($form_start, $form_end);
}
function format_email_recipient($email, $name='')
{
if ($name && $name != $email)
return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
else
return $email;
}
function rcmail_charset_pulldown($selected='ISO-8859-1')
{
$select = new select();
return $select->show($selected);
}
/****** get contacts for this user and add them to client scripts ********/
$sql_result = $DB->query("SELECT name, email
FROM ".get_table_name('contacts')." WHERE user_id=?
AND del<>1",$_SESSION['user_id']);
if ($DB->num_rows($sql_result))
{
$a_contacts = array();
while ($sql_arr = $DB->fetch_assoc($sql_result))
if ($sql_arr['email'])
$a_contacts[] = format_email_recipient($sql_arr['email'], rep_specialchars_output($sql_arr['name'], 'js'));
$OUTPUT->add_script(sprintf("$JS_OBJECT_NAME.set_env('contacts', %s);", array2js($a_contacts)));
}
parse_template('compose');
?>
diff --git a/program/steps/mail/upload.inc b/program/steps/mail/upload.inc
index abab3891b..850ccd01d 100644
--- a/program/steps/mail/upload.inc
+++ b/program/steps/mail/upload.inc
@@ -1,64 +1,80 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/upload.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Handle file-upload and make them available as attachments |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
if (!$_SESSION['compose'])
{
exit;
}
// create temp dir for file uploads
$temp_dir = rcmail_create_compose_tempdir();
if (!is_array($_SESSION['compose']['attachments']))
$_SESSION['compose']['attachments'] = array();
$response = '';
foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
{
$tmpfname = tempnam($temp_dir, 'rcmAttmnt');
if (move_uploaded_file($filepath, $tmpfname))
{
+ $id = count($_SESSION['compose']['attachments']);
$_SESSION['compose']['attachments'][] = array('name' => $_FILES['_attachments']['name'][$i],
'mimetype' => $_FILES['_attachments']['type'][$i],
'path' => $tmpfname);
- $button = sprintf('<img src="%s/images/icons/remove-attachment.png" alt="%s" border="0" style="padding-right:2px;vertical-align:middle">', $CONFIG['skin_path'], rcube_label('delete'));
- $content = sprintf('<a href="#" onclick="%s.command(\\\'remove-attachment\\\',\\\'%s\\\')" title="%s">%s</a>%s',$JS_OBJECT_NAME, $_FILES['_attachments']['name'][$i], rcube_label('delete'), $button, $_FILES['_attachments']['name'][$i]);
- $response .= sprintf('parent.%s.add2attachment_list(\'%s\',\'%s\');',$JS_OBJECT_NAME, $_FILES['_attachments']['name'][$i], $content);
+ if (is_file($CONFIG['skin_path'] . '/images/icons/remove-attachment.png'))
+ $button = sprintf('<img src="%s/images/icons/remove-attachment.png" alt="%s" border="0" style="padding-right:2px;vertical-align:middle" />',
+ $CONFIG['skin_path'],
+ rcube_label('delete'));
+ else
+ $button = rcube_label('delete');
+
+ $content = sprintf('<a href="#delete" onclick="return %s.command(\\\'remove-attachment\\\', \\\'rcmfile%d\\\', this)" title="%s">%s</a>%s',
+ $JS_OBJECT_NAME,
+ $id,
+ rcube_label('delete'),
+ $button,
+ rep_specialchars_output($_FILES['_attachments']['name'][$i], 'js'));
+
+ $response .= sprintf('parent.%s.add2attachment_list(\'rcmfile%d\',\'%s\');',
+ $JS_OBJECT_NAME,
+ $id,
+ $content);
}
}
// send html page with JS calls as response
$frameout = <<<EOF
$response
parent.$JS_OBJECT_NAME.show_attachment_form(false);
parent.$JS_OBJECT_NAME.auto_save_start();
EOF;
rcube_iframe_response($frameout);
?>
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Mon, Aug 17, 6:12 PM (1 d, 8 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1257479
Default Alt Text
(224 KB)
Attached To
Mode
R3 roundcubemail
Attached
Detach File
Event Timeline
Log In to Comment