Page MenuHomePhorge

No OneTemporary

Size
751 KB
Referenced Files
None
Subscribers
None
This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/README b/README
index 417e59c9f..2eb7eaad2 100644
--- a/README
+++ b/README
@@ -1,83 +1,83 @@
RoundCube Webmail (http://roundcube.net)
ATTENTION
---------
This is just a snapshot of the current SVN repository and is NOT A STABLE
version of RoundCube. There have been major changes since the latest release
so please read the update instructions carefully. It's not recommended to
replace an existing installation of RoundCube with this version. Also using
a separate database or this installation is highly recommended.
Introduction:
-------------
RoundCube Webmail is a browser-based multilingual IMAP client with an
application-like user interface. It provides full functionality you expect
from an e-mail client, including MIME support, address book, folder manipulation,
message searching and spell checking. RoundCube Webmail is written in PHP and
requires the MySQL or Postgres database. The user interface is fully skinnable
using XHTML and CSS 2.
This project is meant to be a modern webmail solution which is easy to
install/configure and that runs on a standard PHP plus MySQL or Postgres
configuration. It includes open-source classes/libraries like PEAR
(http://pear.php.net) and the IMAP wrapper from IlohaMail
(http://www.ilohamail.org).
The current development skin uses icons designed by Stephen Horlander and Kevin
Gerich for Mozilla.org.
+Installation:
+-------------
+For detailed instructions on how to install RoundCube webmail on your server,
+please refer to the INSTALL document in the same directory as this document.
+
+
+Licensing:
+----------
+This product is distributed under the GPL. Please read through the file
+LICENSE for more information about our license.
+
+
How it works:
-------------
The main authority for the RoundCube access is the IMAP server. If
'auto_create_user' is set to TRUE in config/main.inc.php a new record in the
user table will be created once the IMAP login succeeded. This user record does
not store a password, it's just used to assign identities, contacts and cache
records. If you have 'auto_create_user' set to FALSE only IMAP logins which
already have a corresponding entry in the user's table (username and hostname)
will be allowed.
Code Layout:
------------
-
Basic sequence (index.php):
- - index.php -> load_gui -> parse_template
+ - index.php -> rcmail_load_gui -> new rcmail_template -> rcmail_template::send
- authentication details in this sequence
Tasks
- index.php limits tasks to set list
- can see task in roundcube link when you mouse over it
- task templates stored in skins/default/templates
- - templates "roundcube:" tokens that get replaced in parse_template
+ - templates "roundcube:" tokens that get replaced in rcmail_template class
program/include/rcube_shared.inc
- defines rcube_html_page, class that lays out a roundcube web page
- defines form control classes
-
-
-Installation:
--------------
-For detailed instructions on how to install RoundCube webmail on your server,
-please refer to the INSTALL document in the same directory as this document.
-
-
-Licensing:
-----------
-This product is distributed under the GPL. Please read through the file
-LICENSE for more information about our license.
+ - provides common functions
Contact:
--------
For any bug reports or feature requests please refer to the tracking system
at trac.roundcube.net (http://trac.roundcube.net/trac.cgi/report) or
subscribe to our mailing list. See http://www.roundcube.net/?p=mailinglists
for details.
You're always welcome to send a message to the project admin:
roundcube@gmail.com
diff --git a/UPGRADING b/UPGRADING
index 4fc257692..4dbec2c7e 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -1,152 +1,154 @@
UPDATE instructions
===================
Follow these instructions if upgrading from a previous version
of RoundCube Webmail.
from version 1.0-beta2
----------------------------------------
* 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['draft_autosave'] = 300;
$rcmail_config['htmleditor'] = TRUE;
$rcmail_config['preview_pane'] = TRUE;
$rcmail_config['date_today'] = 'H:i';
$rcmail_config['double_auth'] = TRUE;
+* If you have LDAP servers configured, change prop key 'mail_field'
+ to 'email_field' for each server confgured in /config/main.inc.php
form version 0.1-beta
----------------------------------------
* 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/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;
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-0.1a.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;
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-0.1a.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-20050820
----------------------------------------
* replace index.php
* replace all files in folder /program/
* replace all files in folder /skins/default/
* run all commands in SQL/*.update-0.1a.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 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-0.1a.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;
diff --git a/bin/html2text.php b/bin/html2text.php
new file mode 100644
index 000000000..e0e2679f7
--- /dev/null
+++ b/bin/html2text.php
@@ -0,0 +1,16 @@
+<?php
+
+require_once('../program/lib/html2text.inc');
+
+$htmlText = $HTTP_RAW_POST_DATA;
+$converter = new html2text($htmlText);
+
+header('Content-Type: text/plain; charset=UTF-8');
+$plaintext = $converter->get_text();
+
+if (function_exists('html_entity_decode'))
+ print html_entity_decode($plaintext, ENT_COMPAT, 'UTF-8');
+else
+ print $plaintext;
+
+?>
\ No newline at end of file
diff --git a/program/steps/mail/quotaimg.inc b/bin/quotaimg.php
similarity index 93%
rename from program/steps/mail/quotaimg.inc
rename to bin/quotaimg.php
index 643ae1c55..47696ef69 100644
--- a/program/steps/mail/quotaimg.inc
+++ b/bin/quotaimg.php
@@ -1,172 +1,169 @@
<?php
/*
+-----------------------------------------------------------------------+
- | program/steps/mail/quotaimg.inc |
+ | program/bin/quotaimg.php |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Create a GIF image showing the mailbox quot as bar |
| |
+-----------------------------------------------------------------------+
| Author: Brett Patterson <brett2@umbc.edu> |
+-----------------------------------------------------------------------+
$Id: $
*/
$used = ((isset($_GET['u']) && !empty($_GET['u'])) || $_GET['u']=='0')?(int)$_GET['u']:'??';
$quota = ((isset($_GET['q']) && !empty($_GET['q'])) || $_GET['q']=='0')?(int)$_GET['q']:'??';
$width = empty($_GET['w']) ? 100 : (int)$_GET['w'];
$height = empty($_GET['h']) ? 14 : (int)$_GET['h'];
function genQuota($used, $total, $width, $height)
{
/**
* Quota Display
*
* Modify the following few elements to change the display of the image.
* Modifiable attributes are:
* bool border :: Defines whether you want to show a border around it or not.
* bool unknown :: Leave default; Defines whether quota is "unknown"
*
* int height :: Defines height of the image
* int width :: Defines width of the image
* int font :: Changes the font size & font used in the GD library.
* Available values are from 1 to 5.
* int padding :: Changes the offset (in pixels) from the top of the image to
* where the top of the text will be aligned. User greater than
* 0 to ensure text is off the border.
* array limit :: Holds the integer values of in an associative array as to what
* defines the upper and lower levels for quota display.
* High - Quota is nearing capacity.
* Mid - Quota is around the middle
* Low - Currently not used.
* array color :: An associative array of strings of comma separated values (R,G,B)
* for use in color creation. Define the RGB values you'd like to
* use. A list of colors (and their RGB values) can be found here:
* http://www.december.com/html/spec/colorcodes.html
**/
$unknown = false;
$border = 0;
$font = 2;
$padding = 0;
$limit['high'] = 70;
$limit['mid'] = 45;
$limit['low'] = 0;
// Fill Colors
$color['fill']['high'] = '215, 13, 13'; // Near quota fill color
$color['fill']['mid'] = '126, 192, 238';// Mid-area of quota fill color
$color['fill']['low'] = '147, 225, 100'; // Far from quota fill color
// Background colors
$color['bg']['OL'] = '215, 13, 13'; // Over limit bbackground
$color['bg']['Unknown'] = '238, 99, 99';// Unknown background
$color['bg']['quota'] = '255, 255, 255';// Normal quota background
// Misc. Colors
$color['border'] = '0, 0, 0';
$color['text'] = '102, 102, 102';
/****************************
***** DO NOT EDIT BELOW HERE *****
****************************/
- if(ereg("^[^0-9?]*$", $used) || ereg("^[^0-9?]*$", $total))
- {
+ if (ereg("^[^0-9?]*$", $used) || ereg("^[^0-9?]*$", $total))
return false;
- }
- if(strpos($used, '?')!==false || strpos($total, '?')!==false && $used != 0)
- {
+
+ if (strpos($used, '?')!==false || strpos($total, '?')!==false && $used != 0)
$unknown = true;
- }
$im = imagecreate($width, $height);
- if($border)
- {
+ if ($border)
+ {
list($r, $g, $b) = explode(',', $color['border']);
$borderc = imagecolorallocate($im, $r, $g, $b);
imageline($im, 0, 0, $width, 0, $borderc);
imageline($im, 0, $height-$border, 0, 0, $borderc);
imageline($im, $width-1, 0, $width-$border, $height, $borderc);
imageline($im, $width, $height-$border, 0, $height-$border, $borderc);
- }
+ }
list($r, $g, $b) = explode(',', $color['text']);
$text = imagecolorallocate($im, $r, $g, $b);
- if($unknown)
- {
+ if ($unknown)
+ {
list($r, $g, $b) = explode(',', $color['bg']['Unknown']);
$background = imagecolorallocate($im, $r, $g, $b);
imagefilledrectangle($im, 0, 0, $width, $height, $background);
$string = 'Unknown';
$mid = floor(($width-(strlen($string)*imagefontwidth($font)))/2)+1;
imagestring($im, $font, $mid, $padding, $string, $text);
- }
- else if($used > $total)
- {
+ }
+ else if ($used > $total)
+ {
list($r, $g, $b) = explode(',', $color['bg']['OL']);
$background = imagecolorallocate($im, $r, $g, $b);
imagefilledrectangle($im, 0, 0, $width, $height, $background);
$string = 'Over Limit';
$mid = floor(($width-(strlen($string)*imagefontwidth($font)))/2)+1;
imagestring($im, $font, $mid, $padding, $string, $text);
- }
+ }
else
- {
+ {
list($r, $g, $b) = explode(',', $color['bg']['quota']);
$background = imagecolorallocate($im, $r, $b, $g);
imagefilledrectangle($im, 0, 0, $width, $height, $background);
$quota = ($used==0)?0:(round($used/$total, 2)*100);
- if($quota >= $limit['high'])
- {
+ if ($quota >= $limit['high'])
+ {
list($r, $g, $b) = explode(',', $color['fill']['high']);
$fill = imagecolorallocate($im, $r, $g, $b);
- }
+ }
elseif($quota >= $limit['mid'])
- {
+ {
list($r, $g, $b) = explode(',', $color['fill']['mid']);
$fill = imagecolorallocate($im, $r, $g, $b);
- }
+ }
else // if($quota >= $limit['low'])
- {
+ {
list($r, $g, $b) = explode(',', $color['fill']['low']);
$fill = imagecolorallocate($im, $r, $g, $b);
- }
+ }
$quota_width = $quota / 100 * $width;
imagefilledrectangle($im, $border, 0, $quota, $height-2*$border, $fill);
$string = $quota.'%';
$mid = floor(($width-(strlen($string)*imagefontwidth($font)))/2)+1;
imagestring($im, $font, $mid, $padding, $string, $text); // Print percent in black
- }
+ }
header('Content-Type: image/gif');
- header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+86400)." GMT");
+ header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+86400)." GMT");
header("Cache-Control: ");
header("Pragma: ");
imagegif($im);
imagedestroy($im);
}
genQuota($used, $quota, $width, $height);
exit;
?>
\ No newline at end of file
diff --git a/config/main.inc.php.dist b/config/main.inc.php.dist
index c2c9d3947..894dfa4d8 100644
--- a/config/main.inc.php.dist
+++ b/config/main.inc.php.dist
@@ -1,248 +1,250 @@
<?php
/*
+-----------------------------------------------------------------------+
| Main configuration file |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
*/
$rcmail_config = array();
// system error reporting: 1 = log; 2 = report (not implemented yet), 4 = show, 8 = trace
$rcmail_config['debug_level'] = 1;
// enable caching of messages and mailbox data in the local database.
// this is recommended if the IMAP server does not run on the same machine
$rcmail_config['enable_caching'] = TRUE;
// lifetime of message cache
// possible units: s, m, h, d, w
$rcmail_config['message_cache_lifetime'] = '10d';
// automatically create a new RoundCube user when log-in the first time.
// a new user will be created once the IMAP login succeeds.
// set to false if only registered users can use this service
$rcmail_config['auto_create_user'] = TRUE;
// the mail host chosen to perform the log-in
// leave blank to show a textbox at login, give a list of hosts
// to display a pulldown menu or set one host as string.
// To use SSL connection, enter ssl://hostname:993
$rcmail_config['default_host'] = '';
// TCP port used for IMAP connections
$rcmail_config['default_port'] = 143;
// Automatically add this domain to user names for login
// Only for IMAP servers that require full e-mail addresses for login
// Specify an array with 'host' => 'domain' values to support multiple hosts
$rcmail_config['username_domain'] = '';
// This domain will be used to form e-mail addresses of new users
// Specify an array with 'host' => 'domain' values to support multiple hosts
$rcmail_config['mail_domain'] = '';
// Path to a virtuser table file to resolve user names and e-mail addresses
$rcmail_config['virtuser_file'] = '';
// Query to resolve user names and e-mail addresses from the database
// %u will be replaced with the current username for login.
// The query should select the user's e-mail address as first col
$rcmail_config['virtuser_query'] = '';
// use this host for sending mails.
// to use SSL connection, set ssl://smtp.host.com
// if left blank, the PHP mail() function is used
$rcmail_config['smtp_server'] = '';
// SMTP port (default is 25; 465 for SSL)
$rcmail_config['smtp_port'] = 25;
// SMTP username (if required) if you use %u as the username RoundCube
// will use the current username for login
$rcmail_config['smtp_user'] = '';
// SMTP password (if required) if you use %p as the password RoundCube
// will use the current user's password for login
$rcmail_config['smtp_pass'] = '';
// SMTP AUTH type (DIGEST-MD5, CRAM-MD5, LOGIN, PLAIN or empty to use
// best server supported one)
$rcmail_config['smtp_auth_type'] = '';
// Log sent messages
$rcmail_config['smtp_log'] = TRUE;
// these cols are shown in the message list
// available cols are: subject, from, to, cc, replyto, date, size, encoding
$rcmail_config['list_cols'] = array('subject', 'from', 'date', 'size');
// relative path to the skin folder
$rcmail_config['skin_path'] = 'skins/default/';
// use this folder to store temp files (must be writebale for apache user)
$rcmail_config['temp_dir'] = 'temp/';
// use this folder to store log files (must be writebale for apache user)
$rcmail_config['log_dir'] = 'logs/';
// session lifetime in minutes
$rcmail_config['session_lifetime'] = 10;
// check client IP in session athorization
$rcmail_config['ip_check'] = false;
// Use an additional frequently changing cookie to athenticate user sessions.
// There have been problems reported with this feature.
$rcmail_config['double_auth'] = false;
// this key is used to encrypt the users imap password which is stored
// in the session record (and the client cookie if remember password is enabled).
// please provide a string of exactly 24 chars.
$rcmail_config['des_key'] = 'rcmail-!24ByteDESkey*Str';
// the default locale setting
$rcmail_config['locale_string'] = 'en';
// use this format for short date display
$rcmail_config['date_short'] = 'D H:i';
// use this format for detailed date/time formatting
$rcmail_config['date_long'] = 'd.m.Y H:i';
// use this format for today's date display
$rcmail_config['date_today'] = 'H:i';
// add this user-agent to message headers when sending
$rcmail_config['useragent'] = 'RoundCube Webmail/0.1b';
// use this name to compose page titles
$rcmail_config['product_name'] = 'RoundCube Webmail';
// only list folders within this path
$rcmail_config['imap_root'] = '';
// store draft message is this mailbox
// leave blank if draft messages should not be stored
$rcmail_config['drafts_mbox'] = 'Drafts';
// store spam messages in this mailbox
$rcmail_config['junk_mbox'] = 'Junk';
// store sent message is this mailbox
// leave blank if sent messages should not be stored
$rcmail_config['sent_mbox'] = 'Sent';
// move messages to this folder when deleting them
// leave blank if they should be deleted directly
$rcmail_config['trash_mbox'] = 'Trash';
// display these folders separately in the mailbox list.
// these folders will automatically be created if they do not exist
$rcmail_config['default_imap_folders'] = array('INBOX', 'Drafts', 'Sent', 'Junk', 'Trash');
// protect the default folders from renames, deletes, and subscription changes
$rcmail_config['protect_default_folders'] = TRUE;
// Set TRUE if deleted messages should not be displayed
// This will make the application run slower
$rcmail_config['skip_deleted'] = FALSE;
// Set true to Mark deleted messages as read as well as deleted
// False means that a message's read status is not affected by marking it as deleted
$rcmail_config['read_when_deleted'] = TRUE;
// When a Trash folder is not present and a message is deleted, flag
// the message for deletion rather than deleting it immediately. Setting this to
// false causes deleted messages to be permanantly removed if there is no Trash folder
$rcmail_config['flag_for_deletion'] = TRUE;
// Make use of the built-in spell checker. It is based on GoogieSpell.
$rcmail_config['enable_spellcheck'] = TRUE;
// For a locally installed Nox Spell Server, please specify the URI to call it.
// Get Nox Spell Server from http://orangoo.com/labs/?page_id=72
// Leave empty to use the Google spell checking service, what means
// that the message content will be sent to Google in order to check spelling
$rcmail_config['spellcheck_uri'] = '';
// These languages can be selected for spell checking.
// Configure as a PHP style hash array: array('en'=>'English', 'de'=>'Deutsch');
// Leave empty for default set of Google spell check languages
$rcmail_config['spellcheck_languages'] = NULL;
// path to a text file which will be added to each sent message
// paths are relative to the RoundCube root folder
$rcmail_config['generic_message_footer'] = '';
// this string is used as a delimiter for message headers when sending
// leave empty for auto-detection
$rcmail_config['mail_header_delimiter'] = NULL;
// in order to enable public ldap search, create a config array
// like the Verisign example below. if you would like to test,
// simply uncomment the Verisign example.
/**
- * example config for Verisign directory
+ * example config for Verisign directory
*
- * $rcmail_config['ldap_public']['Verisign'] = array('hosts' => array('directory.verisign.com'),
- * 'port' => 389,
- * 'base_dn' => '',
- * 'search_fields' => array('Email' => 'mail', 'Name' => 'cn'),
- * 'name_field' => 'cn',
- * 'mail_field' => 'mail',
- * 'scope' => 'sub',
- * 'fuzzy_search' => 0);
+ * $rcmail_config['ldap_public']['Verisign'] = array(
+ * 'name' => 'Verisign.com',
+ * 'hosts' => array('directory.verisign.com'),
+ * 'port' => 389,
+ * 'base_dn' => '',
+ * 'search_fields' => array('mail', 'cn'), // fields to search in
+ * 'name_field' => 'cn', // this field represents the contact's name
+ * 'email_field' => 'mail', // this field represents the contact's e-mail
+ * 'scope' => 'sub', // search mode: sub|base|list
+ * 'fuzzy_search' => true); // server allows wildcard search
*/
// don't allow these settings to be overriden by the user
$rcmail_config['dont_override'] = array();
// list of configuration option names that need to be available in Javascript.
$rcmail_config['javascript_config'] = array('read_when_deleted', 'flag_for_deletion');
// try to load host-specific configuration
$rcmail_config['include_host_config'] = FALSE;
/***** these settings can be overwritten by user's preferences *****/
// show up to X items in list view
$rcmail_config['pagesize'] = 40;
// use this timezone to display date/time
$rcmail_config['timezone'] = 1;
// daylight savings are On
$rcmail_config['dst_active'] = TRUE;
// prefer displaying HTML messages
$rcmail_config['prefer_html'] = TRUE;
// compose html formatted messages by default
$rcmail_config['htmleditor'] = TRUE;
// show pretty dates as standard
$rcmail_config['prettydate'] = TRUE;
// default sort col
$rcmail_config['message_sort_col'] = 'date';
// default sort order
$rcmail_config['message_sort_order'] = 'DESC';
// save compose message every 300 seconds (5min)
$rcmail_config['draft_autosave'] = 300;
// default setting if preview pane is enabled
$rcmail_config['preview_pane'] = FALSE;
// end of config file
?>
diff --git a/index.php b/index.php
index 638bc8e94..f62e9ebce 100644
--- a/index.php
+++ b/index.php
@@ -1,395 +1,379 @@
<?php
/*
+-----------------------------------------------------------------------+
| RoundCube Webmail IMAP Client |
- | Version 0.1-20070411 |
+ | Version 0.1-20070428 |
| |
| Copyright (C) 2005-2007, 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-20070411');
+// application constants
+define('RCMAIL_VERSION', '0.1-20070428');
+define('RCMAIL_CHARSET', 'UTF-8');
+define('JS_OBJECT_NAME', 'rcmail');
// 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)
if (!ini_get('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('lib/html2text.inc');
require_once('PEAR.php');
// set PEAR error handling
// PEAR::setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_NOTICE);
// catch some url/post parameters
$_task = strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC));
$_action = strip_quotes(get_input_value('_action', RCUBE_INPUT_GPC));
$_framed = (!empty($_GET['_framed']) || !empty($_POST['_framed']));
// use main task if empty or invalid value
if (empty($_task) || !in_array($_task, $MAIN_TASKS))
$_task = 'mail';
-if (!empty($_GET['_remote']))
- $REMOTE_REQUEST = TRUE;
-
// set output buffering
if ($_action != 'get' && $_action != 'viewsource')
- {
+{
// use gzip compression if supported
if (function_exists('ob_gzhandler') && ini_get('zlib.output_compression'))
ob_start('ob_gzhandler');
else
ob_start();
- }
+}
// 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 .= '&amp;_framed=1';
+{
+ $COMM_PATH .= '&_framed=1';
$SESS_HIDDEN_FIELD .= "\n".'<input type="hidden" name="_framed" value="1" />';
- }
+}
// init necessary objects for GUI
-load_gui();
+rcmail_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);
- }
+{
+ raise_error(array(
+ 'code' => 603,
+ 'type' => 'db',
+ 'message' => $err_str), FALSE, TRUE);
+}
// error steps
if ($_action=='error' && !empty($_GET['_code']))
- {
raise_error(array('code' => hexdec($_GET['_code'])), FALSE, TRUE);
- }
-
-// handle HTML->text conversion
-if ($_action=='html2text')
- {
- $htmlText = $HTTP_RAW_POST_DATA;
- $converter = new html2text($htmlText);
-
- // TODO possibly replace with rcube_remote_response()
- header('Content-Type: text/plain');
- $plaintext = $converter->get_text();
- print $plaintext;
-
- exit;
- }
// try to log in
if ($_action=='login' && $_task=='mail')
- {
+{
$host = rcmail_autoselect_host();
// check if client supports cookies
if (empty($_COOKIE))
- {
- show_message("cookiesdisabled", 'warning');
- }
+ {
+ $OUTPUT->show_message("cookiesdisabled", 'warning');
+ }
else if ($_SESSION['temp'] && !empty($_POST['_user']) && isset($_POST['_pass']) &&
rcmail_login(get_input_value('_user', RCUBE_INPUT_POST),
get_input_value('_pass', RCUBE_INPUT_POST, true, 'ISO-8859-1'), $host))
- {
+ {
// create new session ID
unset($_SESSION['temp']);
sess_regenerate_id();
// send auth cookie if necessary
rcmail_authenticate_session();
// send redirect
header("Location: $COMM_PATH");
exit;
- }
+ }
else
- {
- show_message("loginfailed", 'warning');
+ {
+ $OUTPUT->show_message("loginfailed", 'warning');
$_SESSION['user_id'] = '';
- }
}
+}
// end session
-else if ($_action=='logout' && isset($_SESSION['user_id']))
- {
- show_message('loggedout');
+else if (($_task=='logout' || $_action=='logout') && isset($_SESSION['user_id']))
+{
+ $OUTPUT->show_message('loggedout');
rcmail_kill_session();
- }
+}
// check session and auth cookie
else if ($_action != 'login' && $_SESSION['user_id'] && $_action != 'send')
- {
+{
if (!rcmail_authenticate_session())
- {
- $message = show_message('sessionerror', 'error');
+ {
+ $OUTPUT->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');
+ {
+ $OUTPUT->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);
- }
+{
+ if ($OUTPUT->ajax_call)
+ $OUTPUT->remote_response("setTimeout(\"location.href='\"+this.env.comm_path+\"'\", 2000);");
$_task = 'login';
- }
+}
// set task and action to client
-$script = sprintf("%s.set_env('task', '%s');", $JS_OBJECT_NAME, $_task);
+$OUTPUT->set_env('task', $_task);
if (!empty($_action))
- $script .= sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $_action);
-
-$OUTPUT->add_script($script);
+ $OUTPUT->set_env('action', $_action);
// not logged in -> show login page
if (!$_SESSION['user_id'])
- {
- parse_template('login');
+{
+ $OUTPUT->task = 'login';
+ $OUTPUT->send('login');
exit;
- }
+}
// handle keep-alive signal
if ($_action=='keep-alive')
- {
- rcube_remote_response('');
+{
+ $OUTPUT->reset();
+ $OUTPUT->send('');
exit;
- }
+}
// include task specific files
if ($_task=='mail')
- {
+{
include_once('program/steps/mail/func.inc');
if ($_action=='show' || $_action=='preview' || $_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');
- if ($_action=='quotaimg')
- include('program/steps/mail/quotaimg.inc');
-
if ($_action=='quotadisplay')
include('program/steps/mail/quotadisplay.inc');
// 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');
- }
+ if ($_action=='search')
+ include('program/steps/addressbook/search.inc');
+
+ if ($_action=='copy')
+ include('program/steps/addressbook/copy.inc');
+
+ if ($_action=='mailto')
+ include('program/steps/addressbook/mailto.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')
include('program/steps/settings/manage_folders.inc');
- }
+}
// parse main template
-parse_template($_task);
+$OUTPUT->send($_task);
// if we arrive here, something went wrong
-raise_error(array('code' => 404,
- 'type' => 'php',
- 'line' => __LINE__,
- 'file' => __FILE__,
- 'message' => "Invalid request"), TRUE, TRUE);
+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 6d77d5a07..71534f6b1 100644
--- a/program/include/main.inc
+++ b/program/include/main.inc
@@ -1,2052 +1,1670 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/main.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev, - Switzerland |
+ | Copyright (C) 2005-2007, 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');
+require_once('include/rcmail_template.inc');
// 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_user_lang;
- global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
+ global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB;
// check client
$BROWSER = rcube_browser();
// load configuration
$CONFIG = rcmail_load_config();
// set session garbage collecting time according to session_lifetime
if (!empty($CONFIG['session_lifetime']))
ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
// 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');
// use database for storing session data
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'] = time();
$_SESSION['temp'] = true;
}
// 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 roundcube configuration into global var
function rcmail_load_config()
{
- global $INSTALL_PATH;
+ global $INSTALL_PATH;
// load config file
- include_once('config/main.inc.php');
- $conf = is_array($rcmail_config) ? $rcmail_config : array();
+ include_once('config/main.inc.php');
+ $conf = is_array($rcmail_config) ? $rcmail_config : array();
// load host-specific configuration
rcmail_load_host_config($conf);
$conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
// load db conf
include_once('config/db.inc.php');
$conf = array_merge($conf, $rcmail_config);
if (empty($conf['log_dir']))
$conf['log_dir'] = $INSTALL_PATH.'logs';
else
$conf['log_dir'] = unslashify($conf['log_dir']);
// set PHP error logging according to config
if ($conf['debug_level'] & 1)
{
ini_set('log_errors', 1);
ini_set('error_log', $conf['log_dir'].'/errors');
}
if ($conf['debug_level'] & 4)
ini_set('display_errors', 1);
else
ini_set('display_errors', 0);
return $conf;
}
// 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()
{
global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
// advanced session authentication
if ($CONFIG['double_auth'])
{
$now = time();
$valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
$_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
// renew auth cookie every 5 minutes (only for GET requests)
if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
{
$_SESSION['last_auth'] = $_SESSION['auth_time'];
$_SESSION['auth_time'] = $now;
setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
}
}
else
$valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
// check session filetime
if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED) && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < time())
$valid = false;
return $valid;
}
// create IMAP object and connect to server
function rcmail_imap_init($connect=FALSE)
{
- global $CONFIG, $DB, $IMAP;
+ global $CONFIG, $DB, $IMAP, $OUTPUT;
$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');
+ $OUTPUT->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('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
setcookie('sessauth', '-del-', time()-60);
}
// 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()
+function rcmail_load_gui()
{
- global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
+ global $CONFIG, $OUTPUT, $sess_user_lang;
// init output page
- $OUTPUT = new rcube_html_page();
-
- // add common javascripts
- $javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
- $javascript .= sprintf("%s.set_env('comm_path', '%s');\n", $JS_OBJECT_NAME, str_replace('&amp;', '&', $COMM_PATH));
+ $OUTPUT = new rcmail_template($CONFIG, $GLOBALS['_task']);
+ $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
- 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 (is_array($CONFIG['javascript_config']))
+ {
+ foreach ($CONFIG['javascript_config'] as $js_config_var)
+ $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
}
- // don't wait for page onload. Call init at the bottom of the page (delayed)
- $javascript_foot = "if (window.call_init)\n call_init('$JS_OBJECT_NAME');";
-
if (!empty($GLOBALS['_framed']))
- $javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
-
- $OUTPUT->add_script($javascript, 'head');
- $OUTPUT->add_script($javascript_foot, 'foot');
- $OUTPUT->include_script('common.js');
- $OUTPUT->include_script('app.js');
- $OUTPUT->scripts_path = 'program/js/';
+ $OUTPUT->set_env('framed', true);
// set locale setting
rcmail_set_locale($sess_user_lang);
// set user-selected charset
if (!empty($CONFIG['charset']))
$OUTPUT->set_charset($CONFIG['charset']);
+
+ // register common UI objects
+ $OUTPUT->add_handlers(array(
+ 'loginform' => 'rcmail_login_form',
+ 'username' => 'rcmail_current_username',
+ 'message' => 'rcmail_message_container',
+ 'charsetselector' => 'rcmail_charset_selector',
+ ));
// add some basic label to client
- rcube_add_label('loading','checkingmail');
+ if (!$OUTPUT->ajax_call)
+ rcube_add_label('loading');
}
// set localization charset based on the given language
function rcmail_set_locale($lang)
{
- global $OUTPUT, $CHARSET, $MBSTRING;
+ global $OUTPUT, $MBSTRING;
static $s_mbstring_loaded = NULL;
// settings for mbstring module (by Tadashi Jokagi)
if (is_null($s_mbstring_loaded))
$MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring");
else
$MBSTRING = $s_mbstring_loaded = FALSE;
if ($MBSTRING)
- mb_internal_encoding($CHARSET);
+ mb_internal_encoding(RCMAIL_CHARSET);
$OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
}
// auto-select IMAP host based on the posted login information
function rcmail_autoselect_host()
{
global $CONFIG;
$host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
if (is_array($host))
{
list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
if (!empty($domain))
{
foreach ($host as $imap_host => $mail_domains)
if (is_array($mail_domains) && in_array($domain, $mail_domains))
{
$host = $imap_host;
break;
}
}
// take the first entry if $host is still an array
if (is_array($host))
$host = array_shift($host);
}
return $host;
}
// 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'];
// Validate that selected host is in the list of configured hosts
if (is_array($CONFIG['default_host']))
{
$allowed = FALSE;
foreach ($CONFIG['default_host'] as $key => $host_allowed)
{
if (!is_numeric($key))
$host_allowed = $key;
if ($host == $host_allowed)
{
$allowed = TRUE;
break;
}
}
if (!$allowed)
return FALSE;
}
else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
return FALSE;
// 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 (!empty($CONFIG['username_domain']) && !strstr($user, '@'))
{
if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
$user .= '@'.$CONFIG['username_domain'][$host];
else if (is_string($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=".$DB->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);
$_SESSION['login_time'] = mktime();
// 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 (".$DB->now().", ".$DB->now().", ?, ?, ?, ?)",
strip_newlines($user),
strip_newlines($host),
strip_newlines($user_email),
$_SESSION['user_lang']);
if ($user_id = $DB->insert_id(get_sequence_name('users')))
{
$mail_domain = rcmail_mail_domain($host);
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']))) &&
($DB->num_rows()>0))
while ($sql_arr = $DB->fetch_array($sql_result))
{
$DB->query("INSERT INTO ".get_table_name('identities')."
(user_id, del, standard, name, email)
VALUES (?, 0, 1, ?, ?)",
$user_id,
strip_newlines($user_name),
preg_replace('/^@/', $user . '@', $sql_arr[0]));
}
else
{
// also create new identity records
$DB->query("INSERT INTO ".get_table_name('identities')."
(user_id, del, standard, name, email)
VALUES (?, 0, 1, ?, ?)",
$user_id,
strip_newlines($user_name),
strip_newlines($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;
+ global $OUTPUT;
$GLOBALS['_action'] = $action;
-
- $OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $action));
+ $OUTPUT->set_env('action', $action);
}
-function show_message($message, $type='notice', $vars=NULL)
- {
- global $OUTPUT, $JS_OBJECT_NAME, $REMOTE_REQUEST;
+// compose a URL to the given action
+function rcmail_self_url($action, $p=array(), $task=null)
+{
+ global $MAIN_TASKS, $COMM_PATH;
+ $qstring = '';
+ $base = $COMM_PATH;
- $framed = $GLOBALS['_framed'];
- $command = sprintf("display_message('%s', '%s');",
- JQ(rcube_label(array('name' => $message, 'vars' => $vars))),
- $type);
-
- if ($REMOTE_REQUEST)
- return 'this.'.$command;
+ if ($task && in_array($task, $MAIN_TASKS))
+ $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
- else
- $OUTPUT->add_script(sprintf("%s%s.%s\n",
- $framed ? sprintf('if(parent.%s)parent.', $JS_OBJECT_NAME) : '',
- $JS_OBJECT_NAME,
- $command));
+ if (is_array($p))
+ foreach ($p as $key => $val)
+ $qstring .= '&'.urlencode($key).'='.urlencode($val);
+
+ return $base . ($action ? '&_action='.$action : '') . $qstring;
+}
+
+
+// @deprecated
+function show_message($message, $type='notice', $vars=NULL)
+ {
+ global $OUTPUT;
+ $OUTPUT->show_message($message, $type, $vars);
}
// 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;
+ global $OUTPUT;
$arg_list = func_get_args();
foreach ($arg_list as $i => $name)
- $OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
- $JS_OBJECT_NAME,
- $name,
- JQ(rcube_label($name))));
+ $OUTPUT->command('add_label', $name, rcube_label($name));
}
// remove temp files older than two day
function rcmail_temp_gc()
{
$tmp = unslashify($CONFIG['temp_dir']);
$expire = mktime() - 172800; // expire in 48 hours
if ($dir = opendir($tmp))
{
while (($fname = readdir($dir)) !== false)
{
if ($fname{0} == '.')
continue;
if (filemtime($tmp.'/'.$fname) < $expire)
@unlink($tmp.'/'.$fname);
}
closedir($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.
* Uses mbstring and iconv functions if possible
*
* @param string Input string
* @param string Suspected charset of the input string
- * @param string Target charset to convert to; defaults to $GLOBALS['CHARSET']
+ * @param string Target charset to convert to; defaults to RCMAIL_CHARSET
* @return Converted string
*/
function rcube_charset_convert($str, $from, $to=NULL)
{
global $MBSTRING;
$from = strtoupper($from);
- $to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
+ $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
if ($from==$to || $str=='' || empty($from))
return $str;
// convert charset using mbstring module
if ($MBSTRING)
{
$to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
$from = $from=="UTF-7" ? "UTF7-IMAP": $from;
// return if convert succeeded
if (($out = mb_convert_encoding($str, $to, $from)) != '')
return $out;
}
// 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 = utf7_to_utf8($str);
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 utf8_to_utf7($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;
}
/**
* Replacing specials characters to a specific encoding type
*
* @param string Input string
* @param string Encoding type: text|html|xml|js|url
* @param string Replace mode for tags: show|replace|remove
* @param boolean Convert newlines
* @return The quoted string
*/
function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
{
global $OUTPUT_TYPE, $OUTPUT;
static $html_encode_arr, $js_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['?']);
}
$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['>']);
unset($encode_arr['&']);
}
else if ($mode=='remove')
$str = strip_tags($str);
// avoid douple quotation of &
$out = preg_replace('/&amp;([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
return $newlines ? nl2br($out) : $out;
}
if ($enctype=='url')
return rawurlencode($str);
// if the replace tables for XML and JS are not yet defined
if (!$js_rep_table)
{
$js_rep_table = $xml_rep_table = array();
$xml_rep_table['&'] = '&amp;';
for ($c=160; $c<256; $c++) // can be increased to support more charsets
{
$hex = dechex($c);
$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);
}
$xml_rep_table['"'] = '&quot;';
}
// encode for XML
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());
+ $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
- return addslashes(preg_replace(array("/\r\n/", "/\r/"), array('\n', '\n'), strtr($str, $js_rep_table)));
+ return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
}
// no encoding given -> return original string
return $str;
}
-
+
/**
* Quote a given string. Alias function for rep_specialchars_output
* @see rep_specialchars_output
*/
function Q($str, $mode='strict', $newlines=TRUE)
{
return rep_specialchars_output($str, 'html', $mode, $newlines);
}
/**
* Quote a given string. Alias function for rep_specialchars_output
* @see rep_specialchars_output
*/
function JQ($str)
{
return rep_specialchars_output($str, 'js');
}
/**
* 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;
}
/**
* Remove single and double quotes from given string
*/
function strip_quotes($str)
{
return preg_replace('/[\'"]/', '', $str);
}
/**
* Remove new lines characters from given string
*/
function strip_newlines($str)
{
return preg_replace('/[\r\n]/', '', $str);
}
-// ************** 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(parse_rcube_conditions($templ));
-
- // add debug console
- if ($CONFIG['debug_level'] & 8)
- $OUTPUT->footer = '<div style="position:absolute;top:5px;left:5px;width:400px;opacity:0.8;z-index:9000;"><form name="debugform"><textarea name="console" rows="15" cols="40" style="width:400px;border:none;font-size:x-small"></textarea></form>';
-
- $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;
- }
-
-
-// parse conditional code
-function parse_rcube_conditions($input)
- {
- if (($matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE)) && count($matches)==4)
- {
- if (preg_match('/^(else|endif)$/i', $matches[1]))
- return $matches[0] . parse_rcube_conditions($matches[3]);
- else
- {
- $attrib = parse_attrib_string($matches[2]);
- if (isset($attrib['condition']))
- {
- $condmet = rcube_xml_condition($attrib['condition']);
- $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
-
- if ($condmet)
- $result = $submatches[0] . preg_replace('/.*<roundcube:endif\s+[^>]+>/is', '', $submatches[3]);
- else
- $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
-
- return $matches[0] . parse_rcube_conditions($result);
- }
- else
- {
- raise_error(array('code' => 500, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__,
- 'message' => "Unable to parse conditional tag " . $matches[2]), TRUE, FALSE);
- }
- }
- }
-
- return $input;
- }
-
-
/**
- * Determines if a given condition is met
+ * Compose an URL for a specific action
*
- * @return True if condition is valid, False is not
- */
-function rcube_xml_condition($condition)
- {
- $condition = preg_replace(
- array('/session:([a-z0-9_]+)/i', '/config:([a-z0-9_]+)/i', '/request:([a-z0-9_]+)/ie'),
- array("\$_SESSION['\\1']", "\$GLOBALS['CONFIG']['\\1']", "get_input_value('\\1', RCUBE_INPUT_GPC)"),
- $condition);
-
- return @eval("return (".$condition.");");
- }
-
-
-function parse_rcube_xml($input)
- {
- $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
- return $output;
- }
-
-
-/**
- * Convert a xml command tag into real content
+ * @param string Request action
+ * @param array More URL parameters
+ * @return The application URL
*/
-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;
-
- // empty output if required condition is not met
- if (!empty($attrib['condition']) && !rcube_xml_condition($attrib['condition']))
- return '';
-
- // 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 Q(rcube_label($attrib + array('vars' => array('product' => $CONFIG['product_name']))));
- 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',
- 'editorselector' => 'rcmail_editor_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 Q($name);
- }
- 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 Q($title);
- }
+function rcmail_url($action, $param=NULL)
+{
+ $url = $GLOBALS['COMM_PATH'] . '&'.$action;
- break;
- }
+ if (is_array($param))
+ foreach ($param as $p => $val)
+ $url .= sprintf('&%s=%s', urlencode($p), urlencode($val));
- return '';
- }
+ return $url;
+}
-// create and register a button
-function rcube_button($attrib)
+// return boolean if a specific template exists
+function template_exists($name)
{
- 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');
-
+ global $CONFIG;
$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'] || $attrib['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'] || $attrib['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'] = Q(rcube_label($attrib['title']));
- if ($attrib['label'])
- $attrib['label'] = Q(rcube_label($attrib['label']));
-
- if ($attrib['alt'])
- $attrib['alt'] = Q(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;
+ // check template file
+ return is_file("$skin_path/templates/$name.html");
}
-function rcube_menu($attrib)
+// Wrapper for rcmail_template::parse()
+// @deprecated
+function parse_template($name='main', $exit=true)
{
-
- return '';
+ $GLOBALS['OUTPUT']->parse($name, $exit);
}
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.'">' . Q(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 = Q($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 = Q($row_data[$col]);
$table .= '<td class="'.$col.'">' . $cont . "</td>\n";
}
$table .= "</tr>\n";
$c++;
}
}
// complete message table
$table .= "</tbody></table>\n";
return $table;
}
/**
* Create an edit field for inclusion on a form
*
* @param string col field name
* @param string value field value
* @param array attrib HTML element attributes for field
* @param string type HTML element type (default 'text')
* @return string HTML field definition
*/
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;
}
+// return the mail domain configured for the given host
+function rcmail_mail_domain($host)
+ {
+ global $CONFIG;
+
+ $domain = $host;
+ if (is_array($CONFIG['mail_domain']))
+ {
+ if (isset($CONFIG['mail_domain'][$host]))
+ $domain = $CONFIG['mail_domain'][$host];
+ }
+ else if (!empty($CONFIG['mail_domain']))
+ $domain = $CONFIG['mail_domain'];
+
+ return $domain;
+ }
+
+
// 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('"', '&quot;', $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]+)=(["\'])([^"]+)\2/Ui', 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[3];
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($now);
$today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
$week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
// define date format depending on current time
if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
$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;
}
+function format_email_recipient($email, $name='')
+ {
+ if ($name && $name != $email)
+ return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
+ else
+ return $email;
+ }
+
+
+
// ************** functions delivering gui objects **************
function rcmail_message_container($attrib)
{
- global $OUTPUT, $JS_OBJECT_NAME;
+ global $OUTPUT;
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]');");
+ $OUTPUT->add_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 the mail domain configured for the given host
-function rcmail_mail_domain($host)
- {
- global $CONFIG;
-
- $domain = $host;
- if (is_array($CONFIG['mail_domain']))
- {
- if (isset($CONFIG['mail_domain'][$host]))
- $domain = $CONFIG['mail_domain'][$host];
- }
- else if (!empty($CONFIG['mail_domain']))
- $domain = $CONFIG['mail_domain'];
-
- return $domain;
- }
-
-
// return code for the webmail login form
function rcmail_login_form($attrib)
{
- global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
+ global $CONFIG, $OUTPUT, $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, 'autocomplete' => 'off'));
$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)
{
if (!is_array($value))
$select_host->add($value, (is_numeric($key) ? $value : $key));
else
{
unset($select_host);
break;
}
}
$fields['host'] = isset($select_host) ? $select_host->show($_POST['_host']) : null;
}
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');");
+ $OUTPUT->add_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);
}
+// return code for search function
+function rcmail_search_form($attrib)
+ {
+ global $OUTPUT;
+
+ // add some labels to client
+ rcube_add_label('searching');
+
+ $attrib['name'] = '_q';
+
+ if (empty($attrib['id']))
+ $attrib['id'] = 'rcmqsearchbox';
+
+ $input_q = new textfield($attrib);
+ $out = $input_q->show();
+
+ $OUTPUT->add_gui_object('qsearchbox', $attrib['id']);
+
+ // add form tag around text field
+ if (empty($attrib['form']))
+ $out = sprintf(
+ '<form name="rcmqsearchform" action="./" '.
+ 'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',
+ JS_OBJECT_NAME,
+ $out);
+
+ return $out;
+ }
+
+
/****** debugging functions ********/
/**
* Print or write debug messages
*
* @param mixed Debug message or data
*/
function console($msg)
{
if (!is_string($msg))
$msg = var_export($msg, true);
if (!($GLOBALS['CONFIG']['debug_level'] & 4))
write_log('console', $msg);
else if ($GLOBALS['REMOTE_REQUEST'])
print "/*\n $msg \n*/\n";
else
{
print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
print $msg;
print "</pre></div>\n";
}
}
/**
* Append a line to a logfile in the logs directory.
* Date will be added automatically to the line.
*
* @param $name Name of logfile
* @param $line Line to append
*/
function write_log($name, $line)
{
global $CONFIG;
if (!is_string($line))
$line = var_export($line, true);
$log_entry = sprintf("[%s]: %s\n",
date("d-M-Y H:i:s O", mktime()),
$line);
if (empty($CONFIG['log_dir']))
$CONFIG['log_dir'] = $INSTALL_PATH.'logs';
// try to open specific log file for writing
if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))
{
fwrite($fp, $log_entry);
fclose($fp);
}
}
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/include/rcmail_template.inc b/program/include/rcmail_template.inc
new file mode 100644
index 000000000..e2fa682e4
--- /dev/null
+++ b/program/include/rcmail_template.inc
@@ -0,0 +1,631 @@
+<?php
+
+/*
+ +-----------------------------------------------------------------------+
+ | program/include/rcmail_template.inc |
+ | |
+ | This file is part of the RoundCube Webmail client |
+ | Copyright (C) 2007, RoundCube Dev. - Switzerland |
+ | Licensed under the GNU GPL |
+ | |
+ | PURPOSE: |
+ | Class to handle HTML page output using a skin template. |
+ | Extends rcube_html_page class from rcube_shared.inc |
+ | |
+ +-----------------------------------------------------------------------+
+ | Author: Thomas Bruederli <roundcube@gmail.com> |
+ +-----------------------------------------------------------------------+
+
+ $Id: $
+
+*/
+
+require_once('include/rcube_shared.inc');
+
+
+class rcmail_template extends rcube_html_page
+{
+ var $config;
+ var $task = '';
+ var $framed = false;
+ var $ajax_call = false;
+ var $pagetitle = '';
+ var $env = array();
+ var $js_env = array();
+ var $js_commands = array();
+ var $object_handlers = array();
+
+
+ // PHP 5 constructor
+ function __construct(&$config, $task)
+ {
+ parent::__construct();
+
+ $this->task = $task;
+ $this->config = $config;
+ $this->ajax_call = !empty($_GET['_remote']) || !empty($_POST['_remote']);
+
+ // add common javascripts
+ if (!$this->ajax_call)
+ {
+ $javascript = "var ".JS_OBJECT_NAME." = new rcube_webmail();";
+
+ // don't wait for page onload. Call init at the bottom of the page (delayed)
+ $javascript_foot = "if (window.call_init)\n call_init('".JS_OBJECT_NAME."');";
+
+ $this->add_script($javascript, 'head_top');
+ $this->add_script($javascript_foot, 'foot');
+ $this->scripts_path = 'program/js/';
+ $this->include_script('common.js');
+ $this->include_script('app.js');
+ }
+ }
+
+ // PHP 4 compatibility
+ function rcmail_template(&$config, $task)
+ {
+ $this->__construct($config, $task);
+ }
+
+
+ /**
+ * Set environment variable
+ */
+ function set_env($name, $value, $addtojs=true)
+ {
+ $this->env[$name] = $value;
+ if ($addtojs || isset($this->js_env[$name]))
+ $this->js_env[$name] = $value;
+ }
+
+
+ /**
+ * Set page title variable
+ */
+ function set_pagetitle($title)
+ {
+ $this->pagetitle = $title;
+ }
+
+
+ /**
+ * Register a template object handler
+ *
+ * @param string Object name
+ * @param string Function name to call
+ */
+ function add_handler($obj, $func)
+ {
+ $this->object_handlers[$obj] = $func;
+ }
+
+ /**
+ * Register a list of template object handlers
+ *
+ * @param array Hash array with object=>handler pairs
+ */
+ function add_handlers($arr)
+ {
+ $this->object_handlers = array_merge($this->object_handlers, $arr);
+ }
+
+ /**
+ * Register a GUI object to the client script
+ *
+ * @param string Object name
+ * @param string Object ID
+ */
+ function add_gui_object($obj, $id)
+ {
+ $this->add_script(JS_OBJECT_NAME.".gui_object('$obj', '$id');");
+ }
+
+
+ /**
+ * Call a client method
+ *
+ * @param string Method to call
+ * @param ... Additional arguments
+ */
+ function command()
+ {
+ $this->js_commands[] = func_get_args();
+ }
+
+
+ /**
+ * Invoke display_message command
+ */
+ function show_message($message, $type='notice', $vars=NULL)
+ {
+ $this->command(
+ 'display_message',
+ rcube_label(array('name' => $message, 'vars' => $vars)),
+ $type);
+ }
+
+
+ /**
+ * Delete all stored env variables and commands
+ */
+ function reset()
+ {
+ $this->env = array();
+ $this->js_env = array();
+ $this->js_commands = array();
+ $this->object_handlers = array();
+ parent::reset();
+ }
+
+ /**
+ * Send the request output to the client.
+ * This will either parse a skin tempalte or send an AJAX response
+ *
+ * @param string Template name
+ * @param boolean True if script should terminate (default)
+ */
+ function send($templ=null, $exit=true)
+ {
+ if ($this->ajax_call)
+ $this->remote_response('', !$exit);
+ else if ($templ != 'iframe')
+ $this->parse($templ, false);
+ else
+ {
+ $this->framed = $templ == 'iframe' ? true : $this->framed;
+ $this->write();
+ }
+
+ if ($exit)
+ exit;
+ }
+
+
+ /**
+ * Send an AJAX response with executable JS code
+ *
+ * @param string Additional JS code
+ * @param boolean True if output buffer should be flushed
+ */
+ function remote_response($add='', $flush=false)
+ {
+ static $s_header_sent = FALSE;
+
+ if (!$s_header_sent)
+ {
+ $s_header_sent = TRUE;
+ send_nocacheing_headers();
+ header('Content-Type: application/x-javascript; charset='.RCMAIL_CHARSET);
+ print '/** ajax response ['.date('d/M/Y h:i:s O')."] **/\n";
+ }
+
+ // unset default env vars
+ unset($this->js_env['task'], $this->js_env['action'], $this->js_env['comm_path']);
+
+ // send response code
+ print rcube_charset_convert($this->get_js_commands() . $add, RCMAIL_CHARSET, $this->get_charset());
+
+ if ($flush) // flush the output buffer
+ flush();
+ }
+
+
+ /**
+ * @override
+ */
+ function write($template='')
+ {
+ // write all env variables to client
+ $js = $this->framed ? "if(window.parent) {\n" : '';
+ $js .= $this->get_js_commands() . ($this->framed ? ' }' : '');
+ $this->add_script($js, 'head_top');
+
+ // call super method
+ parent::write($template, $this->config['skin_path']);
+ }
+
+
+ /**
+ * Parse a specific skin template and deliver to stdout
+ *
+ * @param string Template name
+ * @param boolean Exit script
+ */
+ function parse($name='main', $exit=true)
+ {
+ $skin_path = $this->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' => 501,
+ 'type' => 'php',
+ 'line' => __LINE__,
+ 'file' => __FILE__,
+ 'message' => "Error loading template for '$name'"), TRUE, TRUE);
+ return FALSE;
+ }
+
+ // parse for specialtags
+ $output = $this->parse_xml($this->parse_conditions($templ));
+
+ // add debug console
+ if ($this->config['debug_level'] & 8)
+ $this->add_footer('<div style="position:absolute;top:5px;left:5px;width:400px;padding:0.2em;background:white;opacity:0.8;z-index:9000">
+ <a href="#toggle" onclick="con=document.getElementById(\'dbgconsole\');con.style.display=(con.style.display==\'none\'?\'block\':\'none\');return false">console</a>
+ <form action="/" name="debugform"><textarea name="console" id="dbgconsole" rows="20" cols="40" wrap="off" style="display:none;width:400px;border:none;font-size:x-small"></textarea></form></div>');
+
+ $this->write(trim($this->parse_with_globals($output)), $skin_path);
+
+ if ($exit)
+ exit;
+ }
+
+
+ /**
+ * Return executable javascript code for all registered commands
+ * @private
+ */
+ function get_js_commands()
+ {
+ $out = '';
+ if (!$this->framed)
+ $out .= ($this->ajax_call ? 'this' : JS_OBJECT_NAME) . '.set_env('.json_serialize($this->js_env).");\n";
+
+ foreach ($this->js_commands as $i => $args)
+ {
+ $method = array_shift($args);
+ foreach ($args as $i => $arg)
+ $args[$i] = json_serialize($arg);
+
+ $parent = $this->framed || preg_match('/^parent\./', $method);
+ $out .= sprintf(
+ "%s.%s(%s);\n",
+ $this->ajax_call ? 'this' : ($parent ? 'parent.' : '') . JS_OBJECT_NAME,
+ preg_replace('/^parent\./', '', $method),
+ join(',', $args));
+ }
+
+ return $out;
+ }
+
+ /**
+ * Make URLs starting with a slash point to skin directory
+ */
+ function abs_url($str)
+ {
+ return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
+ }
+
+
+
+ /***** Template parsing methods *****/
+
+ /**
+ * Replace all strings ($varname) with the content
+ * of the according global variable.
+ */
+ function parse_with_globals($input)
+ {
+ $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
+ return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
+ }
+
+
+ /**
+ * Parse for conditional tags
+ */
+ function parse_conditions($input)
+ {
+ if (($matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE)) && count($matches)==4)
+ {
+ if (preg_match('/^(else|endif)$/i', $matches[1]))
+ return $matches[0] . $this->parse_conditions($matches[3]);
+ else
+ {
+ $attrib = parse_attrib_string($matches[2]);
+ if (isset($attrib['condition']))
+ {
+ $condmet = $this->check_condition($attrib['condition']);
+ $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
+
+ if ($condmet)
+ $result = $submatches[0] . preg_replace('/.*<roundcube:endif\s+[^>]+>/is', '', $submatches[3]);
+ else
+ $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
+
+ return $matches[0] . $this->parse_conditions($result);
+ }
+ else
+ {
+ raise_error(array('code' => 500, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__,
+ 'message' => "Unable to parse conditional tag " . $matches[2]), TRUE, FALSE);
+ }
+ }
+ }
+
+ return $input;
+ }
+
+
+ /**
+ * Determines if a given condition is met
+ *
+ * @return True if condition is valid, False is not
+ */
+ function check_condition($condition)
+ {
+ $condition = preg_replace(
+ array('/session:([a-z0-9_]+)/i', '/config:([a-z0-9_]+)/i', '/env:([a-z0-9_]+)/i', '/request:([a-z0-9_]+)/ie'),
+ array("\$_SESSION['\\1']", "\$this->config['\\1']", "\$this->env['\\1']", "get_input_value('\\1', RCUBE_INPUT_GPC)"),
+ $condition);
+
+ return @eval("return (".$condition.");");
+ }
+
+
+ /**
+ * Search for special tags in input and replace them
+ * with the appropriate content
+ *
+ * @param string Input string to parse
+ * @return Altered input string
+ */
+ function parse_xml($input)
+ {
+ return preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "\$this->xml_command('\\1', '\\2')", $input);
+ }
+
+
+ /**
+ * Convert a xml command tag into real content
+ *
+ * @param string Tag command: object,button,label, etc.
+ * @param string Attribute string
+ * @return Tag/Object content string
+ */
+ function xml_command($command, $str_attrib, $add_attrib=array())
+ {
+ $command = strtolower($command);
+ $attrib = parse_attrib_string($str_attrib) + $add_attrib;
+
+ // empty output if required condition is not met
+ if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition']))
+ return '';
+
+ // execute command
+ switch ($command)
+ {
+ // return a button
+ case 'button':
+ if ($attrib['command'])
+ return $this->button($attrib);
+ break;
+
+ // show a label
+ case 'label':
+ if ($attrib['name'] || $attrib['command'])
+ return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
+ break;
+
+ // include a file
+ case 'include':
+ $path = realpath($this->config['skin_path'].$attrib['file']);
+ if ($fp = @fopen($path, 'r'))
+ {
+ $incl = fread($fp, filesize($path));
+ fclose($fp);
+ return $this->parse_xml($incl);
+ }
+ break;
+
+ // return code for a specific application object
+ case 'object':
+ $object = strtolower($attrib['name']);
+
+ // execute object handler function
+ if ($this->object_handlers[$object] && function_exists($this->object_handlers[$object]))
+ return call_user_func($this->object_handlers[$object], $attrib);
+
+ else if ($object=='productname')
+ {
+ $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
+ return Q($name);
+ }
+ else if ($object=='version')
+ {
+ return (string)RCMAIL_VERSION;
+ }
+ else if ($object=='pagetitle')
+ {
+ $task = $this->task;
+ $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
+
+ if (!empty($this->pagetitle))
+ $title .= $this->pagetitle;
+ else if ($task == 'login')
+ $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $this->config['product_name'])));
+ else
+ $title .= ucfirst($task);
+
+ return Q($title);
+ }
+
+ break;
+ }
+
+ return '';
+ }
+
+
+ /**
+ * Create and register a button
+ *
+ * @param array Button attributes
+ * @return HTML button
+ */
+ function button($attrib)
+ {
+ global $CONFIG, $OUTPUT, $BROWSER, $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 = $this->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'] || $attrib['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'] || $attrib['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'] = Q(rcube_label($attrib['title']));
+ if ($attrib['label'])
+ $attrib['label'] = Q(rcube_label($attrib['label']));
+
+ if ($attrib['alt'])
+ $attrib['alt'] = Q(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'])
+ {
+ $this->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'] = Q(rcmail_self_url(null, null, $attrib['command']));
+ else if (in_array($attrib['command'], $a_static_commands))
+ $attrib['href'] = Q(rcmail_self_url($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;
+ }
+
+}
+
+?>
\ No newline at end of file
diff --git a/program/include/rcube_contacts.inc b/program/include/rcube_contacts.inc
new file mode 100644
index 000000000..cc801c6db
--- /dev/null
+++ b/program/include/rcube_contacts.inc
@@ -0,0 +1,429 @@
+<?php
+
+/*
+ +-----------------------------------------------------------------------+
+ | program/include/rcube_contacts.inc |
+ | |
+ | This file is part of the RoundCube Webmail client |
+ | Copyright (C) 2006-2007, RoundCube Dev. - Switzerland |
+ | Licensed under the GNU GPL |
+ | |
+ | PURPOSE: |
+ | Interface to the local address book database |
+ | |
+ +-----------------------------------------------------------------------+
+ | Author: Thomas Bruederli <roundcube@gmail.com> |
+ +-----------------------------------------------------------------------+
+
+ $Id: rcube_contacts.inc 328 2006-08-30 17:41:21Z thomasb $
+
+*/
+
+class rcube_contacts
+{
+ var $db = null;
+ var $db_name = '';
+ var $user_id = 0;
+ var $filter = '1';
+ var $result = null;
+ var $search_fields;
+ var $search_string;
+ var $table_cols = array('name', 'email', 'firstname', 'surname');
+
+ /** public properties */
+ var $primary_key = 'contact_id';
+ var $readonly = false;
+ var $list_page = 1;
+ var $page_size = 10;
+ var $ready = false;
+
+
+ /**
+ * Object constructor
+ *
+ * @param object Instance of the rcube_db class
+ * @param integer User-ID
+ */
+ function __construct($dbconn, $user)
+ {
+ $this->db = $dbconn;
+ $this->db_name = get_table_name('contacts');
+ $this->user_id = $user;
+ $this->ready = $this->db && !$this->db->is_error();
+ }
+
+ /**
+ * PHP 4 object constructor
+ *
+ * @see rcube_contacts::__construct
+ */
+ function rcube_contacts($dbconn, $user)
+ {
+ $this->__construct($dbconn, $user);
+ }
+
+
+ /**
+ * Set internal list page
+ *
+ * @param number Page number to list
+ * @access public
+ */
+ function set_page($page)
+ {
+ $this->list_page = (int)$page;
+ }
+
+
+ /**
+ * Set internal page size
+ *
+ * @param number Number of messages to display on one page
+ * @access public
+ */
+ function set_pagesize($size)
+ {
+ $this->page_size = (int)$size;
+ }
+
+
+ /**
+ * Save a search string for future listings
+ *
+ * @param string SQL params to use in listing method
+ */
+ function set_search_set($filter)
+ {
+ $this->filter = $filter;
+ }
+
+
+ /**
+ * Getter for saved search properties
+ *
+ * @return mixed Search properties used by this class
+ */
+ function get_search_set()
+ {
+ return $this->filter;
+ }
+
+
+ /**
+ * Reset all saved results and search parameters
+ */
+ function reset()
+ {
+ $this->result = null;
+ $this->filter = '1';
+ $this->search_fields = null;
+ $this->search_string = null;
+ }
+
+
+ /**
+ * List the current set of contact records
+ *
+ * @param array List of cols to show
+ * @return array Indexed list of contact records, each a hash array
+ */
+ function list_records($cols=null, $subset=0)
+ {
+ // count contacts for this user
+ $this->result = $this->count();
+ $sql_result = NULL;
+
+ // get contacts from DB
+ if ($this->result->count)
+ {
+ $start_row = $subset < 0 ? $this->result->first + $this->page_size + $subset : $this->result->first;
+ $length = $subset != 0 ? abs($subset) : $this->page_size;
+
+ $sql_result = $this->db->limitquery(
+ "SELECT * FROM ".$this->db_name."
+ WHERE del<>1
+ AND user_id=?
+ AND (".$this->filter.")
+ ORDER BY name",
+ $start_row,
+ $length,
+ $this->user_id);
+ }
+
+ while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result)))
+ {
+ $sql_arr['ID'] = $sql_arr[$this->primary_key];
+ // make sure we have a name to display
+ if (empty($sql_arr['name']))
+ $sql_arr['name'] = $sql_arr['email'];
+ $this->result->add($sql_arr);
+ }
+
+ return $this->result;
+ }
+
+
+ /**
+ * Search contacts
+ *
+ * @param array List of fields to search in
+ * @param string Search value
+ * @param boolean True if results are requested, False if count only
+ * @return Indexed list of contact records and 'count' value
+ */
+ function search($fields, $value, $select=true)
+ {
+ if (!is_array($fields))
+ $fields = array($fields);
+
+ $add_where = array();
+ foreach ($fields as $col)
+ {
+ if ($col == 'ID' || $col == $this->primary_key)
+ {
+ $ids = !is_array($value) ? split(',', $value) : $value;
+ $add_where[] = $this->primary_key." IN (".join(',', $ids).")";
+ }
+ else
+ $add_where[] = $this->db->quoteIdentifier($col)." LIKE ".$this->db->quote(strlen($value)>2 ? "%$value%" : "$value%");
+ }
+
+ if (!empty($add_where))
+ {
+ $this->set_search_set(join(' OR ', $add_where));
+ if ($select)
+ $this->list_records();
+ else
+ $this->result = $this->count();
+ }
+
+ return $this->result;
+ }
+
+
+ /**
+ * Count number of available contacts in database
+ *
+ * @return Result array with values for 'count' and 'first'
+ */
+ function count()
+ {
+ // count contacts for this user
+ $sql_result = $this->db->query(
+ "SELECT COUNT(contact_id) AS rows
+ FROM ".$this->db_name."
+ WHERE del<>1
+ AND user_id=?
+ AND (".$this->filter.")",
+ $this->user_id);
+
+ $sql_arr = $this->db->fetch_assoc($sql_result);
+ return new rcube_result_set($sql_arr['rows'], ($this->list_page-1) * $this->page_size);;
+ }
+
+
+ /**
+ * Return the last result set
+ *
+ * @return Result array or NULL if nothing selected yet
+ */
+ function get_result($as_res=true)
+ {
+ return $this->result;
+ }
+
+
+ /**
+ * Get a specific contact record
+ *
+ * @param mixed record identifier(s)
+ * @return Result object with all record fields or False if not found
+ */
+ function get_record($id, $assoc=false)
+ {
+ // return cached result
+ if ($this->result && ($first = $this->result->first()) && $first[$this->primary_key] == $id)
+ return $assoc ? $first : $this->result;
+
+ $this->db->query(
+ "SELECT * FROM ".$this->db_name."
+ WHERE contact_id=?
+ AND user_id=?
+ AND del<>1",
+ $id,
+ $this->user_id);
+
+ if ($sql_arr = $this->db->fetch_assoc())
+ {
+ $sql_arr['ID'] = $sql_arr[$this->primary_key];
+ $this->result = new rcube_result_set(1);
+ $this->result->add($sql_arr);
+ }
+
+ return $assoc && $sql_arr ? $sql_arr : $this->result;
+ }
+
+
+ /**
+ * Create a new contact record
+ *
+ * @param array Assoziative array with save data
+ * @return The created record ID on success, False on error
+ */
+ function insert($save_data, $check=false)
+ {
+ if (is_object($save_data) && is_a($save_data, rcube_result_set))
+ return $this->insert_recset($save_data, $check);
+
+ $insert_id = $existing = false;
+
+ if ($check)
+ $existing = $this->search('email', $save_data['email'], false);
+
+ $a_insert_cols = $a_insert_values = array();
+ foreach ($this->table_cols as $col)
+ if (isset($save_data[$col]))
+ {
+ $a_insert_cols[] = $this->db->quoteIdentifier($col);
+ $a_insert_values[] = $this->db->quote($save_data[$col]);
+ }
+
+ if (!$existing->count && !empty($a_insert_cols))
+ {
+ $this->db->query(
+ "INSERT INTO ".$this->db_name."
+ (user_id, changed, del, ".join(', ', $a_insert_cols).")
+ VALUES (?, ".$this->db->now().", 0, ".join(', ', $a_insert_values).")",
+ $this->user_id);
+
+ $insert_id = $this->db->insert_id(get_sequence_name('contacts'));
+ }
+
+ return $insert_id;
+ }
+
+
+ /**
+ * Insert new contacts for each row in set
+ */
+ function insert_recset($result, $check=false)
+ {
+ $ids = array();
+ while ($row = $result->next())
+ {
+ if ($insert = $this->insert($row, $check))
+ $ids[] = $insert;
+ }
+ return $ids;
+ }
+
+
+ /**
+ * Update a specific contact record
+ *
+ * @param mixed Record identifier
+ * @param array Assoziative array with save data
+ * @return True on success, False on error
+ */
+ function update($id, $save_cols)
+ {
+ $updated = false;
+ $write_sql = array();
+ foreach ($this->table_cols as $col)
+ if (isset($save_cols[$col]))
+ $write_sql[] = sprintf("%s=%s", $this->db->quoteIdentifier($col), $this->db->quote($save_cols[$col]));
+
+ if (!empty($write_sql))
+ {
+ $this->db->query(
+ "UPDATE ".$this->db_name."
+ SET changed=".$this->db->now().", ".join(', ', $write_sql)."
+ WHERE contact_id=?
+ AND user_id=?
+ AND del<>1",
+ $id,
+ $this->user_id);
+
+ $updated = $this->db->affected_rows();
+ }
+
+ return $updated;
+ }
+
+
+ /**
+ * Mark one or more contact records as deleted
+ *
+ * @param array Record identifiers
+ */
+ function delete($ids)
+ {
+ if (is_array($ids))
+ $ids = join(',', $ids);
+
+ $this->db->query(
+ "UPDATE ".$this->db_name."
+ SET del=1
+ WHERE user_id=?
+ AND contact_id IN (".$ids.")",
+ $this->user_id);
+
+ return $this->db->affected_rows();
+ }
+
+}
+
+
+/**
+ * RoundCube result set class.
+ * Representing an address directory result set.
+ */
+class rcube_result_set
+{
+ var $count = 0;
+ var $first = 0;
+ var $current = 0;
+ var $records = array();
+
+ function __construct($c=0, $f=0)
+ {
+ $this->count = (int)$c;
+ $this->first = (int)$f;
+ }
+
+ function rcube_result_set($c=0, $f=0)
+ {
+ $this->__construct($c, $f);
+ }
+
+ function add($rec)
+ {
+ $this->records[] = $rec;
+ }
+
+ function iterate()
+ {
+ return $this->records[$this->current++];
+ }
+
+ function first()
+ {
+ $this->current = 0;
+ return $this->records[$this->current++];
+ }
+
+ // alias
+ function next()
+ {
+ return $this->iterate();
+ }
+
+ function seek($i)
+ {
+ $this->current = $i;
+ }
+
+}
+
+
+?>
\ No newline at end of file
diff --git a/program/include/rcube_db.inc b/program/include/rcube_db.inc
index 6f362a31d..626cb64df 100755
--- a/program/include/rcube_db.inc
+++ b/program/include/rcube_db.inc
@@ -1,583 +1,583 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/rcube_db.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| PEAR:DB wrapper class that implements PEAR DB functions |
| See http://pear.php.net/package/DB |
| |
+-----------------------------------------------------------------------+
| Author: David Saez Padros <david@ols.es> |
| Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
/**
* Obtain the PEAR::DB class that is used for abstraction
*/
require_once('DB.php');
/**
* Database independent query interface
*
* This is a wrapper for the PEAR::DB class
*
* @package RoundCube Webmail
* @author David Saez Padros <david@ols.es>
* @author Thomas Bruederli <roundcube@gmail.com>
* @version 1.17
* @link http://pear.php.net/package/DB
*/
class rcube_db
{
var $db_dsnw; // DSN for write operations
var $db_dsnr; // DSN for read operations
var $db_connected = false; // Already connected ?
var $db_mode = ''; // Connection mode
var $db_handle = 0; // Connection handle
var $db_pconn = false; // Use persistent connections
var $db_error = false;
var $db_error_msg = '';
var $a_query_results = array('dummy');
var $last_res_id = 0;
/**
* Object constructor
*
* @param string DSN for read/write operations
* @param string Optional DSN for read only operations
*/
function __construct($db_dsnw, $db_dsnr='', $pconn=false)
{
if ($db_dsnr=='')
$db_dsnr=$db_dsnw;
$this->db_dsnw = $db_dsnw;
$this->db_dsnr = $db_dsnr;
$this->db_pconn = $pconn;
$dsn_array = DB::parseDSN($db_dsnw);
$this->db_provider = $dsn_array['phptype'];
}
/**
* PHP 4 object constructor
*
* @see rcube_db::__construct
*/
function rcube_db($db_dsnw, $db_dsnr='', $pconn=false)
{
$this->__construct($db_dsnw, $db_dsnr, $pconn);
}
/**
* Connect to specific database
*
* @param string DSN for DB connections
* @return object PEAR database handle
* @access private
*/
function dsn_connect($dsn)
{
// Use persistent connections if available
$dbh = DB::connect($dsn, array('persistent' => $this->db_pconn));
if (DB::isError($dbh))
{
$this->db_error = TRUE;
$this->db_error_msg = $dbh->getMessage();
- raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
+ raise_error(array('code' => 603, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
'message' => $this->db_error_msg), TRUE, FALSE);
return FALSE;
}
else if ($this->db_provider=='sqlite')
{
$dsn_array = DB::parseDSN($dsn);
if (!filesize($dsn_array['database']) && !empty($this->sqlite_initials))
$this->_sqlite_create_database($dbh, $this->sqlite_initials);
}
return $dbh;
}
/**
* Connect to appropiate databse
* depending on the operation
*
* @param string Connection mode (r|w)
* @access public
*/
function db_connect($mode)
{
$this->db_mode = $mode;
// Already connected
if ($this->db_connected)
{
// no replication, current connection is ok
if ($this->db_dsnw==$this->db_dsnr)
return;
// connected to master, current connection is ok
if ($this->db_mode=='w')
return;
// Same mode, current connection is ok
if ($this->db_mode==$mode)
return;
}
if ($mode=='r')
$dsn = $this->db_dsnr;
else
$dsn = $this->db_dsnw;
$this->db_handle = $this->dsn_connect($dsn);
$this->db_connected = $this->db_handle ? TRUE : FALSE;
}
/**
* Getter for error state
*
* @param boolean True on error
*/
function is_error()
{
return $this->db_error ? $this->db_error_msg : FALSE;
}
/**
* Execute a SQL query
*
* @param string SQL query to execute
* @param mixed Values to be inserted in query
* @return number Query handle identifier
* @access public
*/
function query()
{
$params = func_get_args();
$query = array_shift($params);
return $this->_query($query, 0, 0, $params);
}
/**
* Execute a SQL query with limits
*
* @param string SQL query to execute
* @param number Offset for LIMIT statement
* @param number Number of rows for LIMIT statement
* @param mixed Values to be inserted in query
* @return number Query handle identifier
* @access public
*/
function limitquery()
{
$params = func_get_args();
$query = array_shift($params);
$offset = array_shift($params);
$numrows = array_shift($params);
return $this->_query($query, $offset, $numrows, $params);
}
/**
* Execute a SQL query with limits
*
* @param string SQL query to execute
* @param number Offset for LIMIT statement
* @param number Number of rows for LIMIT statement
* @param array Values to be inserted in query
* @return number Query handle identifier
* @access private
*/
function _query($query, $offset, $numrows, $params)
{
// Read or write ?
if (strtolower(trim(substr($query,0,6)))=='select')
$mode='r';
else
$mode='w';
$this->db_connect($mode);
if (!$this->db_connected)
return FALSE;
if ($this->db_provider == 'sqlite')
$this->_sqlite_prepare();
if ($numrows || $offset)
$result = $this->db_handle->limitQuery($query,$offset,$numrows,$params);
else
$result = $this->db_handle->query($query, $params);
// add result, even if it's an error
return $this->_add_result($result);
}
/**
* Get number of rows for a SQL query
* If no query handle is specified, the last query will be taken as reference
*
* @param number Optional query handle identifier
* @return mixed Number of rows or FALSE on failure
* @access public
*/
function num_rows($res_id=NULL)
{
if (!$this->db_handle)
return FALSE;
if ($result = $this->_get_result($res_id))
return $result->numRows();
else
return FALSE;
}
/**
* Get number of affected rows fort he last query
*
* @return mixed Number of rows or FALSE on failure
* @access public
*/
function affected_rows()
{
if (!$this->db_handle)
return FALSE;
return $this->db_handle->affectedRows();
}
/**
* Get last inserted record ID
* For Postgres databases, a sequence name is required
*
* @param string Sequence name for increment
* @return mixed ID or FALSE on failure
* @access public
*/
function insert_id($sequence = '')
{
if (!$this->db_handle || $this->db_mode=='r')
return FALSE;
switch($this->db_provider)
{
case 'pgsql':
$result = &$this->db_handle->getOne("SELECT CURRVAL('$sequence')");
if (DB::isError($result))
raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
'message' => $result->getMessage()), TRUE, FALSE);
return $result;
case 'mssql':
$result = &$this->db_handle->getOne("SELECT @@IDENTITY");
if (DB::isError($result))
raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
'message' => $result->getMessage()), TRUE, FALSE);
return $result;
case 'mysql': // This is unfortuneate
return mysql_insert_id($this->db_handle->connection);
case 'mysqli':
return mysqli_insert_id($this->db_handle->connection);
case 'sqlite':
return sqlite_last_insert_rowid($this->db_handle->connection);
default:
die("portability issue with this database, please have the developer fix");
}
}
/**
* Get an associative array for one row
* If no query handle is specified, the last query will be taken as reference
*
* @param number Optional query handle identifier
* @return mixed Array with col values or FALSE on failure
* @access public
*/
function fetch_assoc($res_id=NULL)
{
$result = $this->_get_result($res_id);
return $this->_fetch_row($result, DB_FETCHMODE_ASSOC);
}
/**
* Get an index array for one row
* If no query handle is specified, the last query will be taken as reference
*
* @param number Optional query handle identifier
* @return mixed Array with col values or FALSE on failure
* @access public
*/
function fetch_array($res_id=NULL)
{
$result = $this->_get_result($res_id);
return $this->_fetch_row($result, DB_FETCHMODE_ORDERED);
}
/**
* Get co values for a result row
*
* @param object Query result handle
* @param number Fetch mode identifier
* @return mixed Array with col values or FALSE on failure
* @access private
*/
function _fetch_row($result, $mode)
{
if (!$result || DB::isError($result))
{
raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
'message' => $this->db_link->getMessage()), TRUE, FALSE);
return FALSE;
}
elseif (!is_object($result))
return FALSE;
return $result->fetchRow($mode);
}
/**
* Formats input so it can be safely used in a query
*
* @param mixed Value to quote
* @return string Quoted/converted string for use in query
* @access public
*/
function quote($input)
{
// create DB handle if not available
if (!$this->db_handle)
$this->db_connect('r');
// escape pear identifier chars
$rep_chars = array('?' => '\?',
'!' => '\!',
'&' => '\&');
return $this->db_handle->quoteSmart(strtr($input, $rep_chars));
}
/**
* Quotes a string so it can be safely used as a table or column name
*
* @param string Value to quote
* @return string Quoted string for use in query
* @deprecated Replaced by rcube_db::quote_identifier
* @see rcube_db::quote_identifier
* @access public
*/
function quoteIdentifier($str)
{
return $this->quote_identifier($str);
}
/**
* Quotes a string so it can be safely used as a table or column name
*
* @param string Value to quote
* @return string Quoted string for use in query
* @access public
*/
function quote_identifier($str)
{
if (!$this->db_handle)
$this->db_connect('r');
return $this->db_handle->quoteIdentifier($str);
}
/*
* Return SQL function for current time and date
*
* @return string SQL function to use in query
* @access public
*/
function now()
{
switch($this->db_provider)
{
case 'mssql':
return "getdate()";
default:
return "now()";
}
}
/**
* Return SQL statement to convert a field value into a unix timestamp
*
* @param string Field name
* @return string SQL statement to use in query
* @access public
*/
function unixtimestamp($field)
{
switch($this->db_provider)
{
case 'pgsql':
return "EXTRACT (EPOCH FROM $field)";
case 'mssql':
return "datediff(s, '1970-01-01 00:00:00', $field)";
default:
return "UNIX_TIMESTAMP($field)";
}
}
/**
* Return SQL statement to convert from a unix timestamp
*
* @param string Field name
* @return string SQL statement to use in query
* @access public
*/
function fromunixtime($timestamp)
{
switch($this->db_provider)
{
case 'mysqli':
case 'mysql':
case 'sqlite':
return sprintf("FROM_UNIXTIME(%d)", $timestamp);
default:
return date("'Y-m-d H:i:s'", $timestamp);
}
}
/**
* Adds a query result and returns a handle ID
*
* @param object Query handle
* @return mixed Handle ID or FALE on failure
* @access private
*/
function _add_result($res)
{
// sql error occured
if (DB::isError($res))
{
raise_error(array('code' => 500, 'type' => 'db', 'line' => __LINE__, 'file' => __FILE__,
'message' => $res->getMessage() . " Query: " . substr(preg_replace('/[\r\n]+\s*/', ' ', $res->userinfo), 0, 512)), TRUE, FALSE);
return FALSE;
}
else
{
$res_id = sizeof($this->a_query_results);
$this->a_query_results[$res_id] = $res;
$this->last_res_id = $res_id;
return $res_id;
}
}
/**
* Resolves a given handle ID and returns the according query handle
* If no ID is specified, the last ressource handle will be returned
*
* @param number Handle ID
* @return mixed Ressource handle or FALE on failure
* @access private
*/
function _get_result($res_id=NULL)
{
if ($res_id==NULL)
$res_id = $this->last_res_id;
if ($res_id && isset($this->a_query_results[$res_id]))
return $this->a_query_results[$res_id];
else
return FALSE;
}
/**
* Create a sqlite database from a file
*
* @param object SQLite database handle
* @param string File path to use for DB creation
* @access private
*/
function _sqlite_create_database($dbh, $file_name)
{
if (empty($file_name) || !is_string($file_name))
return;
$data = '';
if ($fd = fopen($file_name, 'r'))
{
$data = fread($fd, filesize($file_name));
fclose($fd);
}
if (strlen($data))
sqlite_exec($dbh->connection, $data);
}
/**
* Add some proprietary database functions to the current SQLite handle
* in order to make it MySQL compatible
*
* @access private
*/
function _sqlite_prepare()
{
include_once('include/rcube_sqlite.inc');
// we emulate via callback some missing MySQL function
sqlite_create_function($this->db_handle->connection, "from_unixtime", "rcube_sqlite_from_unixtime");
sqlite_create_function($this->db_handle->connection, "unix_timestamp", "rcube_sqlite_unix_timestamp");
sqlite_create_function($this->db_handle->connection, "now", "rcube_sqlite_now");
sqlite_create_function($this->db_handle->connection, "md5", "rcube_sqlite_md5");
}
} // end class rcube_db
?>
\ No newline at end of file
diff --git a/program/include/rcube_imap.inc b/program/include/rcube_imap.inc
index 3f4f2ebbd..c0016d332 100644
--- a/program/include/rcube_imap.inc
+++ b/program/include/rcube_imap.inc
@@ -1,2686 +1,2684 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/rcube_imap.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005-2006, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| IMAP wrapper that implements the Iloha IMAP Library (IIL) |
| See http://ilohamail.org/ for details |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
/**
* Obtain classes from the Iloha IMAP library
*/
require_once('lib/imap.inc');
require_once('lib/mime.inc');
/**
* Interface class for accessing an IMAP server
*
* This is a wrapper that implements the Iloha IMAP Library (IIL)
*
* @package RoundCube Webmail
* @author Thomas Bruederli <roundcube@gmail.com>
* @version 1.36
* @link http://ilohamail.org
*/
class rcube_imap
{
var $db;
var $conn;
var $root_ns = '';
var $root_dir = '';
var $mailbox = 'INBOX';
var $list_page = 1;
var $page_size = 10;
var $sort_field = 'date';
var $sort_order = 'DESC';
var $delimiter = NULL;
var $caching_enabled = FALSE;
var $default_folders = array('INBOX');
var $default_folders_lc = array('inbox');
var $cache = array();
var $cache_keys = array();
var $cache_changes = array();
var $uid_id_map = array();
var $msg_headers = array();
var $capabilities = array();
var $skip_deleted = FALSE;
var $search_set = NULL;
var $search_subject = '';
var $search_string = '';
var $search_charset = '';
var $debug_level = 1;
/**
* Object constructor
*
* @param object Database connection
*/
function __construct($db_conn)
{
$this->db = $db_conn;
}
/**
* PHP 4 object constructor
*
* @see rcube_imap::__construct
*/
function rcube_imap($db_conn)
{
$this->__construct($db_conn);
}
/**
* Connect to an IMAP server
*
* @param string Host to connect
* @param string Username for IMAP account
* @param string Password for IMAP account
* @param number Port to connect to
* @param boolean Use SSL connection
* @return boolean TRUE on success, FALSE on failure
* @access public
*/
function connect($host, $user, $pass, $port=143, $use_ssl=FALSE)
{
global $ICL_SSL, $ICL_PORT, $IMAP_USE_INTERNAL_DATE;
// check for Open-SSL support in PHP build
if ($use_ssl && in_array('openssl', get_loaded_extensions()))
$ICL_SSL = TRUE;
else if ($use_ssl)
{
raise_error(array('code' => 403, 'type' => 'imap', 'file' => __FILE__,
'message' => 'Open SSL not available;'), TRUE, FALSE);
$port = 143;
}
$ICL_PORT = $port;
$IMAP_USE_INTERNAL_DATE = false;
$this->conn = iil_Connect($host, $user, $pass, array('imap' => 'check'));
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->port = $port;
$this->ssl = $use_ssl;
// print trace mesages
if ($this->conn && ($this->debug_level & 8))
console($this->conn->message);
// write error log
else if (!$this->conn && $GLOBALS['iil_error'])
{
raise_error(array('code' => 403,
'type' => 'imap',
'message' => $GLOBALS['iil_error']), TRUE, FALSE);
}
// get server properties
if ($this->conn)
{
$this->_parse_capability($this->conn->capability);
if (!empty($this->conn->delimiter))
$this->delimiter = $this->conn->delimiter;
if (!empty($this->conn->rootdir))
{
$this->set_rootdir($this->conn->rootdir);
$this->root_ns = ereg_replace('[\.\/]$', '', $this->conn->rootdir);
}
}
return $this->conn ? TRUE : FALSE;
}
/**
* Close IMAP connection
* Usually done on script shutdown
*
* @access public
*/
function close()
{
if ($this->conn)
iil_Close($this->conn);
}
/**
* Close IMAP connection and re-connect
* This is used to avoid some strange socket errors when talking to Courier IMAP
*
* @access public
*/
function reconnect()
{
$this->close();
$this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
}
/**
* Set a root folder for the IMAP connection.
*
* Only folders within this root folder will be displayed
* and all folder paths will be translated using this folder name
*
* @param string Root folder
* @access public
*/
function set_rootdir($root)
{
if (ereg('[\.\/]$', $root)) //(substr($root, -1, 1)==='/')
$root = substr($root, 0, -1);
$this->root_dir = $root;
if (empty($this->delimiter))
$this->get_hierarchy_delimiter();
}
/**
* This list of folders will be listed above all other folders
*
* @param array Indexed list of folder names
* @access public
*/
function set_default_mailboxes($arr)
{
if (is_array($arr))
{
$this->default_folders = $arr;
$this->default_folders_lc = array();
// add inbox if not included
if (!in_array_nocase('INBOX', $this->default_folders))
array_unshift($this->default_folders, 'INBOX');
// create a second list with lower cased names
foreach ($this->default_folders as $mbox)
$this->default_folders_lc[] = strtolower($mbox);
}
}
/**
* Set internal mailbox reference.
*
* All operations will be perfomed on this mailbox/folder
*
* @param string Mailbox/Folder name
* @access public
*/
function set_mailbox($new_mbox)
{
$mailbox = $this->_mod_mailbox($new_mbox);
if ($this->mailbox == $mailbox)
return;
$this->mailbox = $mailbox;
// clear messagecount cache for this mailbox
$this->_clear_messagecount($mailbox);
}
/**
* Set internal list page
*
* @param number Page number to list
* @access public
*/
function set_page($page)
{
$this->list_page = (int)$page;
}
/**
* Set internal page size
*
* @param number Number of messages to display on one page
* @access public
*/
function set_pagesize($size)
{
$this->page_size = (int)$size;
}
/**
* Save a set of message ids for future message listing methods
*
* @param array List of IMAP fields to search in
* @param string Search string
* @param array List of message ids or NULL if empty
*/
function set_search_set($subject, $str=null, $msgs=null, $charset=null)
{
if (is_array($subject) && $str == null && $msgs == null)
list($subject, $str, $msgs, $charset) = $subject;
if ($msgs != null && !is_array($msgs))
$msgs = split(',', $msgs);
$this->search_subject = $subject;
$this->search_string = $str;
$this->search_set = is_array($msgs) ? $msgs : NULL;
$this->search_charset = $charset;
}
/**
* Return the saved search set as hash array
*/
function get_search_set()
{
return array($this->search_subject, $this->search_string, $this->search_set, $this->search_charset);
}
/**
* Returns the currently used mailbox name
*
* @return string Name of the mailbox/folder
* @access public
*/
function get_mailbox_name()
{
return $this->conn ? $this->_mod_mailbox($this->mailbox, 'out') : '';
}
/**
* Returns the IMAP server's capability
*
* @param string Capability name
* @return mixed Capability value or TRUE if supported, FALSE if not
* @access public
*/
function get_capability($cap)
{
$cap = strtoupper($cap);
return $this->capabilities[$cap];
}
/**
* Returns the delimiter that is used by the IMAP server for folder separation
*
* @return string Delimiter string
* @access public
*/
function get_hierarchy_delimiter()
{
if ($this->conn && empty($this->delimiter))
$this->delimiter = iil_C_GetHierarchyDelimiter($this->conn);
if (empty($this->delimiter))
$this->delimiter = '/';
return $this->delimiter;
}
/**
* Public method for mailbox listing.
*
* Converts mailbox name with root dir first
*
* @param string Optional root folder
* @param string Optional filter for mailbox listing
* @return array List of mailboxes/folders
* @access public
*/
function list_mailboxes($root='', $filter='*')
{
$a_out = array();
$a_mboxes = $this->_list_mailboxes($root, $filter);
foreach ($a_mboxes as $mbox_row)
{
$name = $this->_mod_mailbox($mbox_row, 'out');
if (strlen($name))
$a_out[] = $name;
}
// INBOX should always be available
if (!in_array_nocase('INBOX', $a_out))
array_unshift($a_out, 'INBOX');
// sort mailboxes
$a_out = $this->_sort_mailbox_list($a_out);
return $a_out;
}
/**
* Private method for mailbox listing
*
* @return array List of mailboxes/folders
* @access private
* @see rcube_imap::list_mailboxes
*/
function _list_mailboxes($root='', $filter='*')
{
$a_defaults = $a_out = array();
// get cached folder list
$a_mboxes = $this->get_cache('mailboxes');
if (is_array($a_mboxes))
return $a_mboxes;
// retrieve list of folders from IMAP server
$a_folders = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox($root), $filter);
if (!is_array($a_folders) || !sizeof($a_folders))
$a_folders = array();
// write mailboxlist to cache
$this->update_cache('mailboxes', $a_folders);
return $a_folders;
}
/**
* Get message count for a specific mailbox
*
* @param string Mailbox/folder name
* @param string Mode for count [ALL|UNSEEN|RECENT]
* @param boolean Force reading from server and update cache
* @return number Number of messages
* @access public
*/
function messagecount($mbox_name='', $mode='ALL', $force=FALSE)
{
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
return $this->_messagecount($mailbox, $mode, $force);
}
/**
* Private method for getting nr of messages
*
* @access private
* @see rcube_imap::messagecount
*/
function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
{
$a_mailbox_cache = FALSE;
$mode = strtoupper($mode);
if (empty($mailbox))
$mailbox = $this->mailbox;
// count search set
if ($this->search_set && $mailbox == $this->mailbox && $mode == 'ALL')
return count($this->search_set);
$a_mailbox_cache = $this->get_cache('messagecount');
// return cached value
if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
return $a_mailbox_cache[$mailbox][$mode];
// RECENT count is fetched abit different
if ($mode == 'RECENT')
$count = iil_C_CheckForRecent($this->conn, $mailbox);
// use SEARCH for message counting
else if ($this->skip_deleted)
{
$search_str = "ALL UNDELETED";
// get message count and store in cache
if ($mode == 'UNSEEN')
$search_str .= " UNSEEN";
// get message count using SEARCH
// not very performant but more precise (using UNDELETED)
$count = 0;
$index = $this->_search_index($mailbox, $search_str);
if (is_array($index))
{
$str = implode(",", $index);
if (!empty($str))
$count = count($index);
}
}
else
{
if ($mode == 'UNSEEN')
$count = iil_C_CountUnseen($this->conn, $mailbox);
else
$count = iil_C_CountMessages($this->conn, $mailbox);
}
if (!is_array($a_mailbox_cache[$mailbox]))
$a_mailbox_cache[$mailbox] = array();
$a_mailbox_cache[$mailbox][$mode] = (int)$count;
// write back to cache
$this->update_cache('messagecount', $a_mailbox_cache);
return (int)$count;
}
/**
* Public method for listing headers
* convert mailbox name with root dir first
*
* @param string Mailbox/folder name
* @param number Current page to list
* @param string Header field to sort by
* @param string Sort order [ASC|DESC]
* @return array Indexed array with message header objects
* @access public
*/
function list_headers($mbox_name='', $page=NULL, $sort_field=NULL, $sort_order=NULL)
{
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
return $this->_list_headers($mailbox, $page, $sort_field, $sort_order);
}
/**
* Private method for listing message headers
*
* @access private
* @see rcube_imap::list_headers
*/
function _list_headers($mailbox='', $page=NULL, $sort_field=NULL, $sort_order=NULL, $recursive=FALSE)
{
if (!strlen($mailbox))
return array();
// use saved message set
if ($this->search_set && $mailbox == $this->mailbox)
return $this->_list_header_set($mailbox, $this->search_set, $page, $sort_field, $sort_order);
if ($sort_field!=NULL)
$this->sort_field = $sort_field;
if ($sort_order!=NULL)
$this->sort_order = strtoupper($sort_order);
$max = $this->_messagecount($mailbox);
$start_msg = ($this->list_page-1) * $this->page_size;
list($begin, $end) = $this->_get_message_range($max, $page);
// mailbox is empty
if ($begin >= $end)
return array();
$headers_sorted = FALSE;
$cache_key = $mailbox.'.msg';
$cache_status = $this->check_cache_status($mailbox, $cache_key);
// cache is OK, we can get all messages from local cache
if ($cache_status>0)
{
$a_msg_headers = $this->get_message_cache($cache_key, $start_msg, $start_msg+$this->page_size, $this->sort_field, $this->sort_order);
$headers_sorted = TRUE;
}
// cache is dirty, sync it
else if ($this->caching_enabled && $cache_status==-1 && !$recursive)
{
$this->sync_header_index($mailbox);
return $this->_list_headers($mailbox, $page, $this->sort_field, $this->sort_order, TRUE);
}
else
{
// retrieve headers from IMAP
if ($this->get_capability('sort') && ($msg_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, $this->skip_deleted ? 'UNDELETED' : '')))
{
$msgs = $msg_index[$begin];
for ($i=$begin+1; $i < $end; $i++)
$msgs = $msgs.','.$msg_index[$i];
}
else
{
$msgs = sprintf("%d:%d", $begin+1, $end);
$i = 0;
for ($msg_seqnum = $begin; $msg_seqnum <= $end; $msg_seqnum++)
$msg_index[$i++] = $msg_seqnum;
}
// use this class for message sorting
$sorter = new rcube_header_sorter();
$sorter->set_sequence_numbers($msg_index);
// fetch reuested headers from server
$a_msg_headers = array();
$deleted_count = $this->_fetch_headers($mailbox, $msgs, $a_msg_headers, $cache_key);
// delete cached messages with a higher index than $max+1
// Changed $max to $max+1 to fix this bug : #1484295
$this->clear_message_cache($cache_key, $max + 1);
// kick child process to sync cache
// ...
}
// return empty array if no messages found
if (!is_array($a_msg_headers) || empty($a_msg_headers))
return array();
// if not already sorted
if (!$headers_sorted)
{
$sorter->sort_headers($a_msg_headers);
if ($this->sort_order == 'DESC')
$a_msg_headers = array_reverse($a_msg_headers);
}
return array_values($a_msg_headers);
}
/**
* Public method for listing a specific set of headers
* convert mailbox name with root dir first
*
* @param string Mailbox/folder name
* @param array List of message ids to list
* @param number Current page to list
* @param string Header field to sort by
* @param string Sort order [ASC|DESC]
* @return array Indexed array with message header objects
* @access public
*/
function list_header_set($mbox_name='', $msgs, $page=NULL, $sort_field=NULL, $sort_order=NULL)
{
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
return $this->_list_header_set($mailbox, $msgs, $page, $sort_field, $sort_order);
}
/**
* Private method for listing a set of message headers
*
* @access private
* @see rcube_imap::list_header_set
*/
function _list_header_set($mailbox, $msgs, $page=NULL, $sort_field=NULL, $sort_order=NULL)
{
// also accept a comma-separated list of message ids
if (is_string($msgs))
$msgs = split(',', $msgs);
if (!strlen($mailbox) || empty($msgs))
return array();
if ($sort_field!=NULL)
$this->sort_field = $sort_field;
if ($sort_order!=NULL)
$this->sort_order = strtoupper($sort_order);
$max = count($msgs);
$start_msg = ($this->list_page-1) * $this->page_size;
// fetch reuested headers from server
$a_msg_headers = array();
$this->_fetch_headers($mailbox, join(',', $msgs), $a_msg_headers, NULL);
// return empty array if no messages found
if (!is_array($a_msg_headers) || empty($a_msg_headers))
return array();
// if not already sorted
$a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order);
// only return the requested part of the set
return array_slice(array_values($a_msg_headers), $start_msg, min($max-$start_msg, $this->page_size));
}
/**
* Helper function to get first and last index of the requested set
*
* @param number message count
* @param mixed page number to show, or string 'all'
* @return array array with two values: first index, last index
* @access private
*/
function _get_message_range($max, $page)
{
$start_msg = ($this->list_page-1) * $this->page_size;
if ($page=='all')
{
$begin = 0;
$end = $max;
}
else if ($this->sort_order=='DESC')
{
$begin = $max - $this->page_size - $start_msg;
$end = $max - $start_msg;
}
else
{
$begin = $start_msg;
$end = $start_msg + $this->page_size;
}
if ($begin < 0) $begin = 0;
if ($end < 0) $end = $max;
if ($end > $max) $end = $max;
return array($begin, $end);
}
/**
* Fetches message headers
* Used for loop
*
* @param string Mailbox name
* @param string Message index to fetch
* @param array Reference to message headers array
* @param array Array with cache index
* @return number Number of deleted messages
* @access private
*/
function _fetch_headers($mailbox, $msgs, &$a_msg_headers, $cache_key)
{
// cache is incomplete
$cache_index = $this->get_message_cache_index($cache_key);
// fetch reuested headers from server
$a_header_index = iil_C_FetchHeaders($this->conn, $mailbox, $msgs);
$deleted_count = 0;
if (!empty($a_header_index))
{
foreach ($a_header_index as $i => $headers)
{
if ($headers->deleted && $this->skip_deleted)
{
// delete from cache
if ($cache_index[$headers->id] && $cache_index[$headers->id] == $headers->uid)
$this->remove_message_cache($cache_key, $headers->id);
$deleted_count++;
continue;
}
// add message to cache
if ($this->caching_enabled && $cache_index[$headers->id] != $headers->uid)
$this->add_message_cache($cache_key, $headers->id, $headers);
$a_msg_headers[$headers->uid] = $headers;
}
}
return $deleted_count;
}
/**
* Return sorted array of message UIDs
*
* @param string Mailbox to get index from
* @param string Sort column
* @param string Sort order [ASC, DESC]
* @return array Indexed array with message ids
*/
function message_index($mbox_name='', $sort_field=NULL, $sort_order=NULL)
{
if ($sort_field!=NULL)
$this->sort_field = $sort_field;
if ($sort_order!=NULL)
$this->sort_order = strtoupper($sort_order);
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
$key = "$mbox:".$this->sort_field.":".$this->sort_order.".msgi";
// have stored it in RAM
if (isset($this->cache[$key]))
return $this->cache[$key];
// check local cache
$cache_key = $mailbox.'.msg';
$cache_status = $this->check_cache_status($mailbox, $cache_key);
// cache is OK
if ($cache_status>0)
{
$a_index = $this->get_message_cache_index($cache_key, TRUE, $this->sort_field, $this->sort_order);
return array_values($a_index);
}
// fetch complete message index
$msg_count = $this->_messagecount($mailbox);
if ($this->get_capability('sort') && ($a_index = iil_C_Sort($this->conn, $mailbox, $this->sort_field, '', TRUE)))
{
if ($this->sort_order == 'DESC')
$a_index = array_reverse($a_index);
$this->cache[$key] = $a_index;
}
else
{
$a_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:$msg_count", $this->sort_field);
$a_uids = iil_C_FetchUIDs($this->conn, $mailbox);
if ($this->sort_order=="ASC")
asort($a_index);
else if ($this->sort_order=="DESC")
arsort($a_index);
$i = 0;
$this->cache[$key] = array();
foreach ($a_index as $index => $value)
$this->cache[$key][$i++] = $a_uids[$index];
}
return $this->cache[$key];
}
function sync_header_index($mailbox)
{
$cache_key = $mailbox.'.msg';
$cache_index = $this->get_message_cache_index($cache_key);
$msg_count = $this->_messagecount($mailbox);
// fetch complete message index
$a_message_index = iil_C_FetchHeaderIndex($this->conn, $mailbox, "1:$msg_count", 'UID');
foreach ($a_message_index as $id => $uid)
{
// message in cache at correct position
if ($cache_index[$id] == $uid)
{
unset($cache_index[$id]);
continue;
}
// message in cache but in wrong position
if (in_array((string)$uid, $cache_index, TRUE))
{
unset($cache_index[$id]);
}
// other message at this position
if (isset($cache_index[$id]))
{
$this->remove_message_cache($cache_key, $id);
unset($cache_index[$id]);
}
// fetch complete headers and add to cache
$headers = iil_C_FetchHeader($this->conn, $mailbox, $id);
$this->add_message_cache($cache_key, $headers->id, $headers);
}
// those ids that are still in cache_index have been deleted
if (!empty($cache_index))
{
foreach ($cache_index as $id => $uid)
$this->remove_message_cache($cache_key, $id);
}
}
/**
* Invoke search request to IMAP server
*
* @param string mailbox name to search in
* @param string search criteria (ALL, TO, FROM, SUBJECT, etc)
* @param string search string
* @return array search results as list of message ids
* @access public
*/
function search($mbox_name='', $criteria='ALL', $str=NULL, $charset=NULL)
{
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
// have an array of criterias => execute multiple searches
if (is_array($criteria) && $str)
{
$results = array();
foreach ($criteria as $crit)
if ($search_result = $this->search($mbox_name, $crit, $str, $charset))
$results = array_merge($results, $search_result);
$results = array_unique($results);
$this->set_search_set($criteria, $str, $results, $charset);
return $results;
}
else if ($str && $criteria)
{
$search = (!empty($charset) ? "CHARSET $charset " : '') . sprintf("%s {%d}\r\n%s", $criteria, strlen($str), $str);
$results = $this->_search_index($mailbox, $search);
// try search with ISO charset (should be supported by server)
if (empty($results) && !empty($charset) && $charset!='ISO-8859-1')
$results = $this->search($mbox_name, $criteria, rcube_charset_convert($str, $charset, 'ISO-8859-1'), 'ISO-8859-1');
$this->set_search_set($criteria, $str, $results, $charset);
return $results;
}
else
return $this->_search_index($mailbox, $criteria);
}
/**
* Private search method
*
* @return array search results as list of message ids
* @access private
* @see rcube_imap::search()
*/
function _search_index($mailbox, $criteria='ALL')
{
$a_messages = iil_C_Search($this->conn, $mailbox, $criteria);
// clean message list (there might be some empty entries)
if (is_array($a_messages))
{
foreach ($a_messages as $i => $val)
if (empty($val))
unset($a_messages[$i]);
}
return $a_messages;
}
/**
* Refresh saved search set
*/
function refresh_search()
{
if (!empty($this->search_subject) && !empty($this->search_string))
$this->search_set = $this->search('', $this->search_subject, $this->search_string, $this->search_charset);
return $this->get_search_set();
}
/**
* Return message headers object of a specific message
*
* @param int Message ID
* @param string Mailbox to read from
* @param boolean True if $id is the message UID
* @return object Message headers representation
*/
function get_headers($id, $mbox_name=NULL, $is_uid=TRUE)
{
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
$uid = $is_uid ? $id : $this->_id2uid($id);
// get cached headers
if ($uid && ($headers = &$this->get_cached_message($mailbox.'.msg', $uid)))
return $headers;
$headers = iil_C_FetchHeader($this->conn, $mailbox, $id, $is_uid);
// write headers cache
if ($headers)
{
if ($is_uid)
$this->uid_id_map[$mbox_name][$uid] = $headers->id;
$this->add_message_cache($mailbox.'.msg', $headers->id, $headers);
}
return $headers;
}
/**
* Fetch body structure from the IMAP server and build
* an object structure similar to the one generated by PEAR::Mail_mimeDecode
*
* @param Int Message UID to fetch
* @return object Standard object tree or False on failure
*/
function &get_structure($uid)
{
$cache_key = $this->mailbox.'.msg';
$headers = &$this->get_cached_message($cache_key, $uid, true);
// return cached message structure
if (is_object($headers) && is_object($headers->structure))
return $headers->structure;
// resolve message sequence number
if (!($msg_id = $this->_uid2id($uid)))
return FALSE;
$structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
$structure = iml_GetRawStructureArray($structure_str);
$struct = false;
// parse structure and add headers
if (!empty($structure))
{
$this->_msg_id = $msg_id;
$headers = $this->get_headers($msg_id, NULL, FALSE);
$struct = &$this->_structure_part($structure);
$struct->headers = get_object_vars($headers);
// don't trust given content-type
if (empty($struct->parts) && !empty($struct->headers['ctype']))
{
$struct->mime_id = '1';
$struct->mimetype = strtolower($struct->headers['ctype']);
list($struct->ctype_primary, $struct->ctype_secondary) = explode('/', $struct->mimetype);
}
// write structure to cache
if ($this->caching_enabled)
$this->add_message_cache($cache_key, $msg_id, $headers, $struct);
}
return $struct;
}
/**
* Build message part object
*
* @access private
*/
function &_structure_part($part, $count=0, $parent='')
{
$struct = new rcube_message_part;
$struct->mime_id = empty($parent) ? (string)$count : "$parent.$count";
// multipart
if (is_array($part[0]))
{
$struct->ctype_primary = 'multipart';
// find first non-array entry
for ($i=1; count($part); $i++)
if (!is_array($part[$i]))
{
$struct->ctype_secondary = strtolower($part[$i]);
break;
}
$struct->mimetype = 'multipart/'.$struct->ctype_secondary;
$struct->parts = array();
for ($i=0, $count=0; $i<count($part); $i++)
if (is_array($part[$i]) && count($part[$i]) > 5)
$struct->parts[] = $this->_structure_part($part[$i], ++$count, $struct->mime_id);
return $struct;
}
// regular part
$struct->ctype_primary = strtolower($part[0]);
$struct->ctype_secondary = strtolower($part[1]);
$struct->mimetype = $struct->ctype_primary.'/'.$struct->ctype_secondary;
// read content type parameters
if (is_array($part[2]))
{
$struct->ctype_parameters = array();
for ($i=0; $i<count($part[2]); $i+=2)
$struct->ctype_parameters[strtolower($part[2][$i])] = $part[2][$i+1];
if (isset($struct->ctype_parameters['charset']))
$struct->charset = $struct->ctype_parameters['charset'];
}
// read content encoding
if (!empty($part[5]) && $part[5]!='NIL')
{
$struct->encoding = strtolower($part[5]);
$struct->headers['content-transfer-encoding'] = $struct->encoding;
}
// get part size
if (!empty($part[6]) && $part[6]!='NIL')
$struct->size = intval($part[6]);
// read part disposition
$di = count($part) - 2;
if ((is_array($part[$di]) && count($part[$di]) == 2 && is_array($part[$di][1])) ||
(is_array($part[--$di]) && count($part[$di]) == 2))
{
$struct->disposition = strtolower($part[$di][0]);
if (is_array($part[$di][1]))
for ($n=0; $n<count($part[$di][1]); $n+=2)
$struct->d_parameters[strtolower($part[$di][1][$n])] = $part[$di][1][$n+1];
}
// get child parts
if (is_array($part[8]) && $di != 8)
{
$struct->parts = array();
for ($i=0, $count=0; $i<count($part[8]); $i++)
if (is_array($part[8][$i]) && count($part[8][$i]) > 5)
$struct->parts[] = $this->_structure_part($part[8][$i], ++$count, $struct->mime_id);
}
// get part ID
if (!empty($part[3]) && $part[3]!='NIL')
{
$struct->content_id = $part[3];
$struct->headers['content-id'] = $part[3];
if (empty($struct->disposition))
$struct->disposition = 'inline';
}
// fetch message headers if message/rfc822
if ($struct->ctype_primary=='message')
{
$headers = iil_C_FetchPartBody($this->conn, $this->mailbox, $this->_msg_id, $struct->mime_id.'.HEADER');
$struct->headers = $this->_parse_headers($headers);
if (is_array($part[8]) && empty($struct->parts))
$struct->parts[] = $this->_structure_part($part[8], ++$count, $struct->mime_id);
}
// normalize filename property
if (!empty($struct->d_parameters['filename']))
$struct->filename = $this->decode_mime_string($struct->d_parameters['filename']);
else if (!empty($struct->ctype_parameters['name']))
$struct->filename = $this->decode_mime_string($struct->ctype_parameters['name']);
else if (!empty($struct->headers['content-description']))
$struct->filename = $this->decode_mime_string($struct->headers['content-description']);
return $struct;
}
/**
* Return a flat array with references to all parts, indexed by part numbers
*
* @param object Message body structure
* @return Array with part number -> object pairs
*/
function get_mime_numbers(&$structure)
{
$a_parts = array();
$this->_get_part_numbers($structure, $a_parts);
return $a_parts;
}
/**
* Helper method for recursive calls
*
* @access
*/
function _get_part_numbers(&$part, &$a_parts)
{
if ($part->mime_id)
$a_parts[$part->mime_id] = &$part;
if (is_array($part->parts))
for ($i=0; $i<count($part->parts); $i++)
$this->_get_part_numbers($part->parts[$i], $a_parts);
}
/**
* Fetch message body of a specific message from the server
*
* @param int Message UID
* @param string Part number
* @param object Part object created by get_structure()
* @param mixed True to print part, ressource to write part contents in
* @return Message/part body if not printed
*/
function &get_message_part($uid, $part=1, $o_part=NULL, $print=NULL)
{
if (!($msg_id = $this->_uid2id($uid)))
return FALSE;
// get part encoding if not provided
if (!is_object($o_part))
{
$structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
$structure = iml_GetRawStructureArray($structure_str);
$part_type = iml_GetPartTypeCode($structure, $part);
$o_part = new rcube_message_part;
$o_part->ctype_primary = $part_type==0 ? 'text' : ($part_type==2 ? 'message' : 'other');
$o_part->encoding = strtolower(iml_GetPartEncodingString($structure, $part));
$o_part->charset = iml_GetPartCharset($structure, $part);
}
// TODO: Add caching for message parts
if ($print)
{
iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, ($o_part->encoding=='base64'?3:2));
$body = TRUE;
}
else
{
$body = iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, $part, 1);
// decode part body
if ($o_part->encoding=='base64' || $o_part->encoding=='quoted-printable')
$body = $this->mime_decode($body, $o_part->encoding);
// convert charset (if text or message part)
if ($o_part->ctype_primary=='text' || $o_part->ctype_primary=='message')
{
// assume ISO-8859-1 if no charset specified
if (empty($o_part->charset))
$o_part->charset = 'ISO-8859-1';
$body = rcube_charset_convert($body, $o_part->charset);
}
}
return $body;
}
/**
* Fetch message body of a specific message from the server
*
* @param int Message UID
* @return Message/part body
* @see ::get_message_part()
*/
function &get_body($uid, $part=1)
{
return $this->get_message_part($uid, $part);
}
/**
* Returns the whole message source as string
*
* @param int Message UID
* @return Message source string
*/
function &get_raw_body($uid)
{
if (!($msg_id = $this->_uid2id($uid)))
return FALSE;
$body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
$body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
return $body;
}
/**
* Sends the whole message source to stdout
*
* @param int Message UID
*/
function print_raw_body($uid)
{
if (!($msg_id = $this->_uid2id($uid)))
return FALSE;
print iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
flush();
iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 2);
}
/**
* Set message flag to one or several messages
*
* @param mixed Message UIDs as array or as comma-separated string
* @param string Flag to set: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT
* @return True on success, False on failure
*/
function set_flag($uids, $flag)
{
$flag = strtoupper($flag);
$msg_ids = array();
if (!is_array($uids))
$uids = explode(',',$uids);
foreach ($uids as $uid) {
$msg_ids[$uid] = $this->_uid2id($uid);
}
if ($flag=='UNDELETED')
$result = iil_C_Undelete($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
else if ($flag=='UNSEEN')
$result = iil_C_Unseen($this->conn, $this->mailbox, join(',', array_values($msg_ids)));
else
$result = iil_C_Flag($this->conn, $this->mailbox, join(',', array_values($msg_ids)), $flag);
// reload message headers if cached
$cache_key = $this->mailbox.'.msg';
if ($this->caching_enabled)
{
foreach ($msg_ids as $uid => $id)
{
if ($cached_headers = $this->get_cached_message($cache_key, $uid))
{
$this->remove_message_cache($cache_key, $id);
//$this->get_headers($uid);
}
}
// close and re-open connection
// this prevents connection problems with Courier
$this->reconnect();
}
// set nr of messages that were flaged
$count = count($msg_ids);
// clear message count cache
if ($result && $flag=='SEEN')
$this->_set_messagecount($this->mailbox, 'UNSEEN', $count*(-1));
else if ($result && $flag=='UNSEEN')
$this->_set_messagecount($this->mailbox, 'UNSEEN', $count);
else if ($result && $flag=='DELETED')
$this->_set_messagecount($this->mailbox, 'ALL', $count*(-1));
return $result;
}
// append a mail message (source) to a specific mailbox
function save_message($mbox_name, &$message)
{
$mbox_name = stripslashes($mbox_name);
$mailbox = $this->_mod_mailbox($mbox_name);
// make sure mailbox exists
if (in_array($mailbox, $this->_list_mailboxes()))
$saved = iil_C_Append($this->conn, $mailbox, $message);
if ($saved)
{
// increase messagecount of the target mailbox
$this->_set_messagecount($mailbox, 'ALL', 1);
}
return $saved;
}
// move a message from one mailbox to another
function move_message($uids, $to_mbox, $from_mbox='')
{
$to_mbox = stripslashes($to_mbox);
$from_mbox = stripslashes($from_mbox);
$to_mbox = $this->_mod_mailbox($to_mbox);
$from_mbox = $from_mbox ? $this->_mod_mailbox($from_mbox) : $this->mailbox;
// make sure mailbox exists
if (!in_array($to_mbox, $this->_list_mailboxes()))
{
if (in_array(strtolower($to_mbox), $this->default_folders))
$this->create_mailbox($to_mbox, TRUE);
else
return FALSE;
}
// convert the list of uids to array
$a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
// exit if no message uids are specified
if (!is_array($a_uids))
return false;
// convert uids to message ids
$a_mids = array();
foreach ($a_uids as $uid)
$a_mids[] = $this->_uid2id($uid, $from_mbox);
$iil_move = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
$moved = !($iil_move === false || $iil_move < 0);
// send expunge command in order to have the moved message
// really deleted from the source mailbox
if ($moved)
{
$this->_expunge($from_mbox, FALSE);
$this->_clear_messagecount($from_mbox);
$this->_clear_messagecount($to_mbox);
}
// remove message ids from search set
if ($moved && $this->search_set && $from_mbox == $this->mailbox)
$this->search_set = array_diff($this->search_set, $a_mids);
// update cached message headers
$cache_key = $from_mbox.'.msg';
if ($moved && ($a_cache_index = $this->get_message_cache_index($cache_key)))
{
$start_index = 100000;
foreach ($a_uids as $uid)
{
if (($index = array_search($uid, $a_cache_index)) !== FALSE)
$start_index = min($index, $start_index);
}
// clear cache from the lowest index on
$this->clear_message_cache($cache_key, $start_index);
}
return $moved;
}
// mark messages as deleted and expunge mailbox
function delete_message($uids, $mbox_name='')
{
$mbox_name = stripslashes($mbox_name);
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
// convert the list of uids to array
$a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
// exit if no message uids are specified
if (!is_array($a_uids))
return false;
// convert uids to message ids
$a_mids = array();
foreach ($a_uids as $uid)
$a_mids[] = $this->_uid2id($uid, $mailbox);
$deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_mids));
// send expunge command in order to have the deleted message
// really deleted from the mailbox
if ($deleted)
{
$this->_expunge($mailbox, FALSE);
$this->_clear_messagecount($mailbox);
}
// remove message ids from search set
if ($moved && $this->search_set && $mailbox == $this->mailbox)
$this->search_set = array_diff($this->search_set, $a_mids);
// remove deleted messages from cache
$cache_key = $mailbox.'.msg';
if ($deleted && ($a_cache_index = $this->get_message_cache_index($cache_key)))
{
$start_index = 100000;
foreach ($a_uids as $uid)
{
if (($index = array_search($uid, $a_cache_index)) !== FALSE)
$start_index = min($index, $start_index);
}
// clear cache from the lowest index on
$this->clear_message_cache($cache_key, $start_index);
}
return $deleted;
}
// clear all messages in a specific mailbox
function clear_mailbox($mbox_name=NULL)
{
$mbox_name = stripslashes($mbox_name);
$mailbox = !empty($mbox_name) ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
$msg_count = $this->_messagecount($mailbox, 'ALL');
if ($msg_count>0)
{
$cleared = iil_C_ClearFolder($this->conn, $mailbox);
// make sure the message count cache is cleared as well
if ($cleared)
{
$this->clear_message_cache($mailbox.'.msg');
$a_mailbox_cache = $this->get_cache('messagecount');
unset($a_mailbox_cache[$mailbox]);
$this->update_cache('messagecount', $a_mailbox_cache);
}
return $cleared;
}
else
return 0;
}
// send IMAP expunge command and clear cache
function expunge($mbox_name='', $clear_cache=TRUE)
{
$mbox_name = stripslashes($mbox_name);
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
return $this->_expunge($mailbox, $clear_cache);
}
// send IMAP expunge command and clear cache
function _expunge($mailbox, $clear_cache=TRUE)
{
$result = iil_C_Expunge($this->conn, $mailbox);
if ($result>=0 && $clear_cache)
{
//$this->clear_message_cache($mailbox.'.msg');
$this->_clear_messagecount($mailbox);
}
return $result;
}
/* --------------------------------
* folder managment
* --------------------------------*/
/**
* Get a list of all folders available on the IMAP server
*
* @param string IMAP root dir
* @return array Inbdexed array with folder names
*/
function list_unsubscribed($root='')
{
static $sa_unsubscribed;
if (is_array($sa_unsubscribed))
return $sa_unsubscribed;
// retrieve list of folders from IMAP server
$a_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
// modify names with root dir
foreach ($a_mboxes as $mbox_name)
{
$name = $this->_mod_mailbox($mbox_name, 'out');
if (strlen($name))
$a_folders[] = $name;
}
// filter folders and sort them
$sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
return $sa_unsubscribed;
}
/**
* Get quota
* added by Nuny
*/
function get_quota()
{
if ($this->get_capability('QUOTA'))
return iil_C_GetQuota($this->conn);
return FALSE;
}
/**
* subscribe to a specific mailbox(es)
*/
function subscribe($mbox_name, $mode='subscribe')
{
if (is_array($mbox_name))
$a_mboxes = $mbox_name;
else if (is_string($mbox_name) && strlen($mbox_name))
$a_mboxes = explode(',', $mbox_name);
// let this common function do the main work
return $this->_change_subscription($a_mboxes, 'subscribe');
}
/**
* unsubscribe mailboxes
*/
function unsubscribe($mbox_name)
{
if (is_array($mbox_name))
$a_mboxes = $mbox_name;
else if (is_string($mbox_name) && strlen($mbox_name))
$a_mboxes = explode(',', $mbox_name);
// let this common function do the main work
return $this->_change_subscription($a_mboxes, 'unsubscribe');
}
/**
* Create a new mailbox on the server and register it in local cache
*
* @param string New mailbox name (as utf-7 string)
* @param boolean True if the new mailbox should be subscribed
* @param string Name of the created mailbox, false on error
*/
function create_mailbox($name, $subscribe=FALSE)
{
$result = FALSE;
// replace backslashes
$name = preg_replace('/[\\\]+/', '-', $name);
// reduce mailbox name to 100 chars
$name = substr($name, 0, 100);
$abs_name = $this->_mod_mailbox($name);
$a_mailbox_cache = $this->get_cache('mailboxes');
if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array_nocase($abs_name, $a_mailbox_cache)))
$result = iil_C_CreateFolder($this->conn, $abs_name);
// try to subscribe it
if ($subscribe)
$this->subscribe($name);
return $result ? $name : FALSE;
}
/**
* Set a new name to an existing mailbox
*
* @param string Mailbox to rename (as utf-7 string)
* @param string New mailbox name (as utf-7 string)
* @param string Name of the renames mailbox, false on error
*/
function rename_mailbox($mbox_name, $new_name)
{
$result = FALSE;
// replace backslashes
$name = preg_replace('/[\\\]+/', '-', $new_name);
// encode mailbox name and reduce it to 100 chars
$name = substr($new_name, 0, 100);
// make absolute path
$mailbox = $this->_mod_mailbox($mbox_name);
$abs_name = $this->_mod_mailbox($name);
// check if mailbox is subscribed
$a_subscribed = $this->_list_mailboxes();
$subscribed = in_array($mailbox, $a_subscribed);
// unsubscribe folder
if ($subscribed)
iil_C_UnSubscribe($this->conn, $mailbox);
if (strlen($abs_name))
$result = iil_C_RenameFolder($this->conn, $mailbox, $abs_name);
// clear cache
if ($result)
{
$this->clear_message_cache($mailbox.'.msg');
$this->clear_cache('mailboxes');
}
// try to subscribe it
if ($result && $subscribed)
iil_C_Subscribe($this->conn, $abs_name);
return $result ? $name : FALSE;
}
/**
* remove mailboxes from server
*/
function delete_mailbox($mbox_name)
{
$deleted = FALSE;
if (is_array($mbox_name))
$a_mboxes = $mbox_name;
else if (is_string($mbox_name) && strlen($mbox_name))
$a_mboxes = explode(',', $mbox_name);
if (is_array($a_mboxes))
foreach ($a_mboxes as $mbox_name)
{
$mailbox = $this->_mod_mailbox($mbox_name);
// unsubscribe mailbox before deleting
iil_C_UnSubscribe($this->conn, $mailbox);
// send delete command to server
$result = iil_C_DeleteFolder($this->conn, $mailbox);
if ($result>=0)
$deleted = TRUE;
}
// clear mailboxlist cache
if ($deleted)
{
$this->clear_message_cache($mailbox.'.msg');
$this->clear_cache('mailboxes');
}
return $deleted;
}
/**
* Create all folders specified as default
*/
function create_default_folders()
{
$a_folders = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox(''), '*');
$a_subscribed = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox(''), '*');
// create default folders if they do not exist
foreach ($this->default_folders as $folder)
{
$abs_name = $this->_mod_mailbox($folder);
if (!in_array_nocase($abs_name, $a_subscribed))
{
if (!in_array_nocase($abs_name, $a_folders))
$this->create_mailbox($folder, TRUE);
else
$this->subscribe($folder);
}
else if (!in_array_nocase($abs_name, $a_folders))
{
$this->create_mailbox($folder, FALSE);
}
}
}
/* --------------------------------
* internal caching methods
* --------------------------------*/
function set_caching($set)
{
if ($set && is_object($this->db))
$this->caching_enabled = TRUE;
else
$this->caching_enabled = FALSE;
}
function get_cache($key)
{
// read cache
if (!isset($this->cache[$key]) && $this->caching_enabled)
{
$cache_data = $this->_read_cache_record('IMAP.'.$key);
$this->cache[$key] = strlen($cache_data) ? unserialize($cache_data) : FALSE;
}
return $this->cache[$key];
}
function update_cache($key, $data)
{
$this->cache[$key] = $data;
$this->cache_changed = TRUE;
$this->cache_changes[$key] = TRUE;
}
function write_cache()
{
if ($this->caching_enabled && $this->cache_changed)
{
foreach ($this->cache as $key => $data)
{
if ($this->cache_changes[$key])
$this->_write_cache_record('IMAP.'.$key, serialize($data));
}
}
}
function clear_cache($key=NULL)
{
if ($key===NULL)
{
foreach ($this->cache as $key => $data)
$this->_clear_cache_record('IMAP.'.$key);
$this->cache = array();
$this->cache_changed = FALSE;
$this->cache_changes = array();
}
else
{
$this->_clear_cache_record('IMAP.'.$key);
$this->cache_changes[$key] = FALSE;
unset($this->cache[$key]);
}
}
function _read_cache_record($key)
{
$cache_data = FALSE;
if ($this->db)
{
// get cached data from DB
$sql_result = $this->db->query(
"SELECT cache_id, data
FROM ".get_table_name('cache')."
WHERE user_id=?
AND cache_key=?",
$_SESSION['user_id'],
$key);
if ($sql_arr = $this->db->fetch_assoc($sql_result))
{
$cache_data = $sql_arr['data'];
$this->cache_keys[$key] = $sql_arr['cache_id'];
}
}
return $cache_data;
}
function _write_cache_record($key, $data)
{
if (!$this->db)
return FALSE;
// check if we already have a cache entry for this key
if (!isset($this->cache_keys[$key]))
{
$sql_result = $this->db->query(
"SELECT cache_id
FROM ".get_table_name('cache')."
WHERE user_id=?
AND cache_key=?",
$_SESSION['user_id'],
$key);
if ($sql_arr = $this->db->fetch_assoc($sql_result))
$this->cache_keys[$key] = $sql_arr['cache_id'];
else
$this->cache_keys[$key] = FALSE;
}
// update existing cache record
if ($this->cache_keys[$key])
{
$this->db->query(
"UPDATE ".get_table_name('cache')."
SET created=".$this->db->now().",
data=?
WHERE user_id=?
AND cache_key=?",
$data,
$_SESSION['user_id'],
$key);
}
// add new cache record
else
{
$this->db->query(
"INSERT INTO ".get_table_name('cache')."
(created, user_id, cache_key, data)
VALUES (".$this->db->now().", ?, ?, ?)",
$_SESSION['user_id'],
$key,
$data);
}
}
function _clear_cache_record($key)
{
$this->db->query(
"DELETE FROM ".get_table_name('cache')."
WHERE user_id=?
AND cache_key=?",
$_SESSION['user_id'],
$key);
}
/* --------------------------------
* message caching methods
* --------------------------------*/
// checks if the cache is up-to-date
// return: -3 = off, -2 = incomplete, -1 = dirty
function check_cache_status($mailbox, $cache_key)
{
if (!$this->caching_enabled)
return -3;
$cache_index = $this->get_message_cache_index($cache_key, TRUE);
$msg_count = $this->_messagecount($mailbox);
$cache_count = count($cache_index);
// console("Cache check: $msg_count !== ".count($cache_index));
if ($cache_count==$msg_count)
{
// get highest index
$header = iil_C_FetchHeader($this->conn, $mailbox, "$msg_count");
$cache_uid = array_pop($cache_index);
// uids of highest message matches -> cache seems OK
if ($cache_uid == $header->uid)
return 1;
// cache is dirty
return -1;
}
// if cache count differs less than 10% report as dirty
else if (abs($msg_count - $cache_count) < $msg_count/10)
return -1;
else
return -2;
}
function get_message_cache($key, $from, $to, $sort_field, $sort_order)
{
$cache_key = "$key:$from:$to:$sort_field:$sort_order";
$db_header_fields = array('idx', 'uid', 'subject', 'from', 'to', 'cc', 'date', 'size');
if (!in_array($sort_field, $db_header_fields))
$sort_field = 'idx';
if ($this->caching_enabled && !isset($this->cache[$cache_key]))
{
$this->cache[$cache_key] = array();
$sql_result = $this->db->limitquery(
"SELECT idx, uid, headers
FROM ".get_table_name('messages')."
WHERE user_id=?
AND cache_key=?
ORDER BY ".$this->db->quoteIdentifier($sort_field)." ".
strtoupper($sort_order),
$from,
$to-$from,
$_SESSION['user_id'],
$key);
while ($sql_arr = $this->db->fetch_assoc($sql_result))
{
$uid = $sql_arr['uid'];
$this->cache[$cache_key][$uid] = unserialize($sql_arr['headers']);
}
}
return $this->cache[$cache_key];
}
function &get_cached_message($key, $uid, $struct=false)
{
if (!$this->caching_enabled)
return FALSE;
$internal_key = '__single_msg';
if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) ||
($struct && empty($this->cache[$internal_key][$uid]->structure))))
{
$sql_select = "idx, uid, headers" . ($struct ? ", structure" : '');
$sql_result = $this->db->query(
"SELECT $sql_select
FROM ".get_table_name('messages')."
WHERE user_id=?
AND cache_key=?
AND uid=?",
$_SESSION['user_id'],
$key,
$uid);
if ($sql_arr = $this->db->fetch_assoc($sql_result))
{
$this->cache[$internal_key][$uid] = unserialize($sql_arr['headers']);
if (is_object($this->cache[$internal_key][$uid]) && !empty($sql_arr['structure']))
$this->cache[$internal_key][$uid]->structure = unserialize($sql_arr['structure']);
}
}
return $this->cache[$internal_key][$uid];
}
function get_message_cache_index($key, $force=FALSE, $sort_col='idx', $sort_order='ASC')
{
static $sa_message_index = array();
// empty key -> empty array
if (empty($key))
return array();
if (!empty($sa_message_index[$key]) && !$force)
return $sa_message_index[$key];
$sa_message_index[$key] = array();
$sql_result = $this->db->query(
"SELECT idx, uid
FROM ".get_table_name('messages')."
WHERE user_id=?
AND cache_key=?
ORDER BY ".$this->db->quote_identifier($sort_col)." ".$sort_order,
$_SESSION['user_id'],
$key);
while ($sql_arr = $this->db->fetch_assoc($sql_result))
$sa_message_index[$key][$sql_arr['idx']] = $sql_arr['uid'];
return $sa_message_index[$key];
}
function add_message_cache($key, $index, $headers, $struct=null)
{
if (empty($key) || !is_object($headers) || empty($headers->uid))
return;
// check for an existing record (probly headers are cached but structure not)
$sql_result = $this->db->query(
"SELECT message_id
FROM ".get_table_name('messages')."
WHERE user_id=?
AND cache_key=?
AND uid=?
AND del<>1",
$_SESSION['user_id'],
$key,
$headers->uid);
// update cache record
if ($sql_arr = $this->db->fetch_assoc($sql_result))
{
$this->db->query(
"UPDATE ".get_table_name('messages')."
SET idx=?, headers=?, structure=?
WHERE message_id=?",
$index,
serialize($headers),
is_object($struct) ? serialize($struct) : NULL,
$sql_arr['message_id']
);
}
else // insert new record
{
$this->db->query(
"INSERT INTO ".get_table_name('messages')."
(user_id, del, cache_key, created, idx, uid, subject, ".$this->db->quoteIdentifier('from').", ".$this->db->quoteIdentifier('to').", cc, date, size, headers, structure)
VALUES (?, 0, ?, ".$this->db->now().", ?, ?, ?, ?, ?, ?, ".$this->db->fromunixtime($headers->timestamp).", ?, ?, ?)",
$_SESSION['user_id'],
$key,
$index,
$headers->uid,
(string)substr($this->decode_header($headers->subject, TRUE), 0, 128),
(string)substr($this->decode_header($headers->from, TRUE), 0, 128),
(string)substr($this->decode_header($headers->to, TRUE), 0, 128),
(string)substr($this->decode_header($headers->cc, TRUE), 0, 128),
(int)$headers->size,
serialize($headers),
is_object($struct) ? serialize($struct) : NULL
);
}
}
function remove_message_cache($key, $index)
{
$this->db->query(
"DELETE FROM ".get_table_name('messages')."
WHERE user_id=?
AND cache_key=?
AND idx=?",
$_SESSION['user_id'],
$key,
$index);
}
function clear_message_cache($key, $start_index=1)
{
$this->db->query(
"DELETE FROM ".get_table_name('messages')."
WHERE user_id=?
AND cache_key=?
AND idx>=?",
$_SESSION['user_id'],
$key,
$start_index);
}
/* --------------------------------
* encoding/decoding methods
* --------------------------------*/
- function decode_address_list($input, $max=NULL)
+ function decode_address_list($input, $max=null, $decode=true)
{
- $a = $this->_parse_address_list($input);
+ $a = $this->_parse_address_list($input, $decode);
$out = array();
if (!is_array($a))
return $out;
$c = count($a);
$j = 0;
foreach ($a as $val)
{
$j++;
$address = $val['address'];
$name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
if ($name && $address && $name != $address)
$string = sprintf('%s <%s>', strpos($name, ',')!==FALSE ? '"'.$name.'"' : $name, $address);
else if ($address)
$string = $address;
else if ($name)
$string = $name;
$out[$j] = array('name' => $name,
'mailto' => $address,
'string' => $string);
if ($max && $j==$max)
break;
}
return $out;
}
function decode_header($input, $remove_quotes=FALSE)
{
$str = $this->decode_mime_string((string)$input);
if ($str{0}=='"' && $remove_quotes)
- {
$str = str_replace('"', '', $str);
- }
return $str;
}
/**
* Decode a mime-encoded string to internal charset
*
* @access static
*/
- function decode_mime_string($input, $recursive=false)
+ function decode_mime_string($input, $fallback=null)
{
$out = '';
$pos = strpos($input, '=?');
if ($pos !== false)
{
$out = substr($input, 0, $pos);
$end_cs_pos = strpos($input, "?", $pos+2);
$end_en_pos = strpos($input, "?", $end_cs_pos+1);
$end_pos = strpos($input, "?=", $end_en_pos+1);
$encstr = substr($input, $pos+2, ($end_pos-$pos-2));
$rest = substr($input, $end_pos+2);
$out .= rcube_imap::_decode_mime_string_part($encstr);
- $out .= rcube_imap::decode_mime_string($rest);
+ $out .= rcube_imap::decode_mime_string($rest, $fallback);
return $out;
}
- // no encoding information, defaults to what is specified in the class header
- return rcube_charset_convert($input, 'ISO-8859-1');
+ // no encoding information, use fallback
+ return rcube_charset_convert($input, !empty($fallback) ? $fallback : 'ISO-8859-1');
}
/**
* Decode a part of a mime-encoded string
*
* @access static
*/
function _decode_mime_string_part($str)
{
$a = explode('?', $str);
$count = count($a);
// should be in format "charset?encoding?base64_string"
if ($count >= 3)
{
for ($i=2; $i<$count; $i++)
$rest.=$a[$i];
if (($a[1]=="B")||($a[1]=="b"))
$rest = base64_decode($rest);
else if (($a[1]=="Q")||($a[1]=="q"))
{
$rest = str_replace("_", " ", $rest);
$rest = quoted_printable_decode($rest);
}
return rcube_charset_convert($rest, $a[0]);
}
else
return $str; // we dont' know what to do with this
}
function mime_decode($input, $encoding='7bit')
{
switch (strtolower($encoding))
{
case '7bit':
return $input;
break;
case 'quoted-printable':
return quoted_printable_decode($input);
break;
case 'base64':
return base64_decode($input);
break;
default:
return $input;
}
}
function mime_encode($input, $encoding='7bit')
{
switch ($encoding)
{
case 'quoted-printable':
return quoted_printable_encode($input);
break;
case 'base64':
return base64_encode($input);
break;
default:
return $input;
}
}
// convert body chars according to the ctype_parameters
function charset_decode($body, $ctype_param)
{
if (is_array($ctype_param) && !empty($ctype_param['charset']))
return rcube_charset_convert($body, $ctype_param['charset']);
// defaults to what is specified in the class header
return rcube_charset_convert($body, 'ISO-8859-1');
}
/* --------------------------------
* private methods
* --------------------------------*/
function _mod_mailbox($mbox_name, $mode='in')
{
if (empty($mbox_name) || (!empty($this->root_ns) && $this->root_ns == $mbox_name) || $mbox_name == 'INBOX')
return $mbox_name;
if (!empty($this->root_dir) && $mode=='in')
$mbox_name = $this->root_dir.$this->delimiter.$mbox_name;
else if (strlen($this->root_dir) && $mode=='out')
$mbox_name = substr($mbox_name, strlen($this->root_dir)+1);
return $mbox_name;
}
// sort mailboxes first by default folders and then in alphabethical order
function _sort_mailbox_list($a_folders)
{
$a_out = $a_defaults = array();
// find default folders and skip folders starting with '.'
foreach($a_folders as $i => $folder)
{
if ($folder{0}=='.')
continue;
if (($p = array_search(strtolower($folder), $this->default_folders_lc))!==FALSE)
$a_defaults[$p] = $folder;
else
$a_out[] = $folder;
}
sort($a_out);
ksort($a_defaults);
return array_merge($a_defaults, $a_out);
}
function get_id($uid, $mbox_name=NULL)
{
return $this->_uid2id($uid, $this->_mod_mailbox($mbox_name));
}
function get_uid($id,$mbox_name=NULL)
{
return $this->_id2uid($id, $this->_mod_mailbox($mbox_name));
}
function _uid2id($uid, $mbox_name=NULL)
{
if (!$mbox_name)
$mbox_name = $this->mailbox;
if (!isset($this->uid_id_map[$mbox_name][$uid]))
$this->uid_id_map[$mbox_name][$uid] = iil_C_UID2ID($this->conn, $mbox_name, $uid);
return $this->uid_id_map[$mbox_name][$uid];
}
function _id2uid($id, $mbox_name=NULL)
{
if (!$mbox_name)
$mbox_name = $this->mailbox;
return iil_C_ID2UID($this->conn, $mbox_name, $id);
}
// parse string or array of server capabilities and put them in internal array
function _parse_capability($caps)
{
if (!is_array($caps))
$cap_arr = explode(' ', $caps);
else
$cap_arr = $caps;
foreach ($cap_arr as $cap)
{
if ($cap=='CAPABILITY')
continue;
if (strpos($cap, '=')>0)
{
list($key, $value) = explode('=', $cap);
if (!is_array($this->capabilities[$key]))
$this->capabilities[$key] = array();
$this->capabilities[$key][] = $value;
}
else
$this->capabilities[$cap] = TRUE;
}
}
// subscribe/unsubscribe a list of mailboxes and update local cache
function _change_subscription($a_mboxes, $mode)
{
$updated = FALSE;
if (is_array($a_mboxes))
foreach ($a_mboxes as $i => $mbox_name)
{
$mailbox = $this->_mod_mailbox($mbox_name);
$a_mboxes[$i] = $mailbox;
if ($mode=='subscribe')
$result = iil_C_Subscribe($this->conn, $mailbox);
else if ($mode=='unsubscribe')
$result = iil_C_UnSubscribe($this->conn, $mailbox);
if ($result>=0)
$updated = TRUE;
}
// get cached mailbox list
if ($updated)
{
$a_mailbox_cache = $this->get_cache('mailboxes');
if (!is_array($a_mailbox_cache))
return $updated;
// modify cached list
if ($mode=='subscribe')
$a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
else if ($mode=='unsubscribe')
$a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
// write mailboxlist to cache
$this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
}
return $updated;
}
// increde/decrese messagecount for a specific mailbox
function _set_messagecount($mbox_name, $mode, $increment)
{
$a_mailbox_cache = FALSE;
$mailbox = $mbox_name ? $mbox_name : $this->mailbox;
$mode = strtoupper($mode);
$a_mailbox_cache = $this->get_cache('messagecount');
if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
return FALSE;
// add incremental value to messagecount
$a_mailbox_cache[$mailbox][$mode] += $increment;
// there's something wrong, delete from cache
if ($a_mailbox_cache[$mailbox][$mode] < 0)
unset($a_mailbox_cache[$mailbox][$mode]);
// write back to cache
$this->update_cache('messagecount', $a_mailbox_cache);
return TRUE;
}
// remove messagecount of a specific mailbox from cache
function _clear_messagecount($mbox_name='')
{
$a_mailbox_cache = FALSE;
$mailbox = $mbox_name ? $mbox_name : $this->mailbox;
$a_mailbox_cache = $this->get_cache('messagecount');
if (is_array($a_mailbox_cache[$mailbox]))
{
unset($a_mailbox_cache[$mailbox]);
$this->update_cache('messagecount', $a_mailbox_cache);
}
}
// split RFC822 header string into an associative array
function _parse_headers($headers)
{
$a_headers = array();
$lines = explode("\n", $headers);
$c = count($lines);
for ($i=0; $i<$c; $i++)
{
if ($p = strpos($lines[$i], ': '))
{
$field = strtolower(substr($lines[$i], 0, $p));
$value = trim(substr($lines[$i], $p+1));
if (!empty($value))
$a_headers[$field] = $value;
}
}
return $a_headers;
}
- function _parse_address_list($str)
+ function _parse_address_list($str, $decode=true)
{
// remove any newlines and carriage returns before
$a = $this->_explode_quoted_string('[,;]', preg_replace( "/[\r\n]/", " ", $str));
$result = array();
foreach ($a as $key => $val)
{
$val = preg_replace("/([\"\w])</", "$1 <", $val);
- $sub_a = $this->_explode_quoted_string(' ', $this->decode_header($val));
+ $sub_a = $this->_explode_quoted_string(' ', $decode ? $this->decode_header($val) : $val);
$result[$key]['name'] = '';
foreach ($sub_a as $k => $v)
{
if (strpos($v, '@') > 0)
$result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
else
$result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
}
if (empty($result[$key]['name']))
$result[$key]['name'] = $result[$key]['address'];
}
return $result;
}
function _explode_quoted_string($delimiter, $string)
{
$result = array();
$strlen = strlen($string);
for ($q=$p=$i=0; $i < $strlen; $i++)
{
if ($string{$i} == "\"" && $string{$i-1} != "\\")
$q = $q ? false : true;
else if (!$q && preg_match("/$delimiter/", $string{$i}))
{
$result[] = substr($string, $p, $i - $p);
$p = $i + 1;
}
}
$result[] = substr($string, $p);
return $result;
}
}
/**
* Class representing a message part
*/
class rcube_message_part
{
var $mime_id = '';
var $ctype_primary = 'text';
var $ctype_secondary = 'plain';
var $mimetype = 'text/plain';
var $disposition = '';
var $filename = '';
var $encoding = '8bit';
var $charset = '';
var $size = 0;
var $headers = array();
var $d_parameters = array();
var $ctype_parameters = array();
}
/**
* rcube_header_sorter
*
* Class for sorting an array of iilBasicHeader objects in a predetermined order.
*
* @author Eric Stadtherr
*/
class rcube_header_sorter
{
var $sequence_numbers = array();
/**
* set the predetermined sort order.
*
* @param array $seqnums numerically indexed array of IMAP message sequence numbers
*/
function set_sequence_numbers($seqnums)
{
$this->sequence_numbers = $seqnums;
}
/**
* sort the array of header objects
*
* @param array $headers array of iilBasicHeader objects indexed by UID
*/
function sort_headers(&$headers)
{
/*
* uksort would work if the keys were the sequence number, but unfortunately
* the keys are the UIDs. We'll use uasort instead and dereference the value
* to get the sequence number (in the "id" field).
*
* uksort($headers, array($this, "compare_seqnums"));
*/
uasort($headers, array($this, "compare_seqnums"));
}
/**
* get the position of a message sequence number in my sequence_numbers array
*
* @param integer $seqnum message sequence number contained in sequence_numbers
*/
function position_of($seqnum)
{
$c = count($this->sequence_numbers);
for ($pos = 0; $pos <= $c; $pos++)
{
if ($this->sequence_numbers[$pos] == $seqnum)
return $pos;
}
return -1;
}
/**
* Sort method called by uasort()
*/
function compare_seqnums($a, $b)
{
// First get the sequence number from the header object (the 'id' field).
$seqa = $a->id;
$seqb = $b->id;
// then find each sequence number in my ordered list
$posa = $this->position_of($seqa);
$posb = $this->position_of($seqb);
// return the relative position as the comparison value
$ret = $posa - $posb;
return $ret;
}
}
/**
* Add quoted-printable encoding to a given string
*
* @param string $input string to encode
* @param int $line_max add new line after this number of characters
* @param boolena $space_conf true if spaces should be converted into =20
* @return encoded string
*/
function quoted_printable_encode($input, $line_max=76, $space_conv=false)
{
$hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
$lines = preg_split("/(?:\r\n|\r|\n)/", $input);
$eol = "\r\n";
$escape = "=";
$output = "";
while( list(, $line) = each($lines))
{
//$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
$linlen = strlen($line);
$newline = "";
for($i = 0; $i < $linlen; $i++)
{
$c = substr( $line, $i, 1 );
$dec = ord( $c );
if ( ( $i == 0 ) && ( $dec == 46 ) ) // convert first point in the line into =2E
{
$c = "=2E";
}
if ( $dec == 32 )
{
if ( $i == ( $linlen - 1 ) ) // convert space at eol only
{
$c = "=20";
}
else if ( $space_conv )
{
$c = "=20";
}
}
else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) // always encode "\t", which is *not* required
{
$h2 = floor($dec/16);
$h1 = floor($dec%16);
$c = $escape.$hex["$h2"].$hex["$h1"];
}
if ( (strlen($newline) + strlen($c)) >= $line_max ) // CRLF is not counted
{
$output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
$newline = "";
// check if newline first character will be point or not
if ( $dec == 46 )
{
$c = "=2E";
}
}
$newline .= $c;
} // end of for
$output .= $newline.$eol;
} // end of while
return trim($output);
}
?>
diff --git a/program/include/rcube_ldap.inc b/program/include/rcube_ldap.inc
index 7cb9dee53..06a99ad0b 100644
--- a/program/include/rcube_ldap.inc
+++ b/program/include/rcube_ldap.inc
@@ -1,259 +1,436 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/rcube_ldap.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2006-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
- | Manage an LDAP connection |
+ | Interface to an LDAP address directory |
| |
+-----------------------------------------------------------------------+
- | Author: Jeremy Jongsma <jeremy@jongsma.org> |
+ | Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-require_once("bugs.inc");
-
class rcube_ldap
- {
+{
var $conn;
- var $host;
- var $port;
- var $protocol;
- var $base_dn;
- var $bind_dn;
- var $bind_pass;
-
- // PHP 5 constructor
- function __construct()
- {
- }
+ var $prop = array();
+ var $fieldmap = array();
+
+ var $filter = '';
+ var $result = null;
+ var $ldap_result = null;
+ var $sort_col = '';
+
+ /** public properties */
+ var $primary_key = 'ID';
+ var $readonly = true;
+ var $list_page = 1;
+ var $page_size = 10;
+ var $ready = false;
+
+
+ /**
+ * Object constructor
+ *
+ * @param array LDAP connection properties
+ * @param integer User-ID
+ */
+ function __construct($p)
+ {
+ $this->prop = $p;
+
+ foreach ($p as $prop => $value)
+ if (preg_match('/^(.+)_field$/', $prop, $matches))
+ $this->fieldmap[$matches[1]] = $value;
+
+ // $this->filter = "(dn=*)";
+ $this->connect();
+ }
- // PHP 4 constructor
- function rcube_ldap()
- {
- $this->__construct();
- }
+ /**
+ * PHP 4 object constructor
+ *
+ * @see rcube_ldap::__construct
+ */
+ function rcube_ldap($p)
+ {
+ $this->__construct($p);
+ }
+
- function connect($hosts, $port=389, $protocol=3)
- {
+ /**
+ * Establish a connection to the LDAP server
+ */
+ function connect()
+ {
if (!function_exists('ldap_connect'))
- raise_error(array("type" => "ldap",
- "message" => "No ldap support in this installation of php."),
- TRUE);
+ raise_error(array('type' => 'ldap', 'message' => "No ldap support in this installation of PHP"), true);
if (is_resource($this->conn))
- return TRUE;
+ return true;
- if (!is_array($hosts))
- $hosts = array($hosts);
+ if (!is_array($this->prop['hosts']))
+ $this->prop['hosts'] = array($this->prop['hosts']);
- foreach ($hosts as $host)
+ foreach ($this->prop['hosts'] as $host)
+ {
+ if ($lc = @ldap_connect($host, $this->prop['port']))
{
- if ($lc = @ldap_connect($host, $port))
- {
- @ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $protocol);
- $this->host = $host;
- $this->port = $port;
- $this->protocol = $protocol;
+ ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, $this->prop['port']);
+ $this->prop['host'] = $host;
$this->conn = $lc;
- return TRUE;
- }
+ break;
}
-
- if (!is_resource($this->conn))
- raise_error(array("type" => "ldap",
- "message" => "Could not connect to any LDAP server, tried $host:$port last"),
- TRUE);
}
+
+ if (is_resource($this->conn))
+ $this->ready = true;
+ else
+ raise_error(array('type' => 'ldap', 'message' => "Could not connect to any LDAP server, tried $host:{$this->prop[port]} last"), true);
+ }
- function close()
- {
- if ($this->conn)
- {
- if (@ldap_unbind($this->conn))
- return TRUE;
- else
- raise_error(array("code" => ldap_errno($this->conn),
- "type" => "ldap",
- "message" => "Could not close connection to LDAP server: ".ldap_error($this->conn)),
- TRUE);
- }
- return FALSE;
- }
- // Merge with connect()?
+ /**
+ * Merge with connect()?
+ */
function bind($dn=null, $pass=null)
- {
+ {
if ($this->conn)
- {
+ {
if ($dn)
+ {
if (@ldap_bind($this->conn, $dn, $pass))
- return TRUE;
+ return true;
else
- raise_error(array("code" => ldap_errno($this->conn),
- "type" => "ldap",
- "message" => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
- TRUE);
+ raise_error(array('code' => ldap_errno($this->conn),
+ 'type' => 'ldap',
+ 'message' => "Bind failed for dn=$dn: ".ldap_error($this->conn)),
+ true);
+ }
else
+ {
if (@ldap_bind($this->conn))
- return TRUE;
+ return true;
else
- raise_error(array("code" => ldap_errno($this->conn),
- "type" => "ldap",
- "message" => "Anonymous bind failed: ".ldap_error($this->conn)),
- TRUE);
- }
+ raise_error(array('code' => ldap_errno($this->conn),
+ 'type' => 'ldap',
+ 'message' => "Anonymous bind failed: ".ldap_error($this->conn)),
+ true);
+ }
+ }
else
- raise_error(array("type" => "ldap",
- "message" => "Attempted bind on nonexistent connection"), TRUE);
- return FALSE;
+ raise_error(array('type' => 'ldap', 'message' => "Attempted bind on nonexistent connection"), true);
+
+ return false;
}
- function count($base, $filter=null, $attributes=null, $scope="sub")
- {
+
+ /**
+ * Close connection to LDAP server
+ */
+ function close()
+ {
if ($this->conn)
- {
- if ($scope === 'sub')
- $sr = @ldap_search($this->conn, $base, $filter, $attributes, 0, $limit);
- else if ($scope === 'one')
- $sr = @ldap_list($this->conn, $base, $filter, $attributes, 0, $limit);
- else if ($scope === 'base')
- $sr = @ldap_read($this->conn, $base, $filter, $attributes, 0, $limit);
- if ($sr)
- return @ldap_count_entries($this->conn, $sr);
- }
- else
- raise_error(array("type" => "ldap",
- "message" => "Attempted count search on nonexistent connection"), TRUE);
- return FALSE;
+ @ldap_unbind($this->conn);
+ }
+
+
+ /**
+ * Set internal list page
+ *
+ * @param number Page number to list
+ * @access public
+ */
+ function set_page($page)
+ {
+ $this->list_page = (int)$page;
+ }
+
+
+ /**
+ * Set internal page size
+ *
+ * @param number Number of messages to display on one page
+ * @access public
+ */
+ function set_pagesize($size)
+ {
+ $this->page_size = (int)$size;
+ }
+
+
+ /**
+ * Save a search string for future listings
+ *
+ * @param string ??
+ */
+ function set_search_set($filter)
+ {
+ $this->filter = $filter;
+ }
+
+
+ /**
+ * Getter for saved search properties
+ *
+ * @return mixed Search properties used by this class
+ */
+ function get_search_set()
+ {
+ return $this->filter;
+ }
+
+
+ /**
+ * Reset all saved results and search parameters
+ */
+ function reset()
+ {
+ $this->result = null;
+ $this->ldap_result = null;
+ $this->filter = '';
+ }
+
+
+ /**
+ * List the current set of contact records
+ *
+ * @param array List of cols to show
+ * @return array Indexed list of contact records, each a hash array
+ */
+ function list_records($cols=null, $subset=0)
+ {
+ // exec LDAP search if no result resource is stored
+ if ($this->conn && !$this->ldap_result)
+ $this->_exec_search();
+
+ // count contacts for this user
+ $this->result = $this->count();
+
+ // we have a search result resource
+ if ($this->ldap_result && $this->result->count > 0)
+ {
+ if ($this->sort_col && $this->prop['scope'] !== "base")
+ @ldap_sort($this->conn, $this->ldap_result, $this->sort_col);
+
+ $entries = ldap_get_entries($this->conn, $this->ldap_result);
+ for ($i = $this->result->first; $i < min($entries['count'], $this->result->first + $this->page_size); $i++)
+ $this->result->add($this->_ldap2result($entries[$i]));
}
- function search($base, $filter=null, $attributes=null, $scope='sub', $sort=null, $limit=0)
+ return $this->result;
+ }
+
+
+ /**
+ * Search contacts
+ *
+ * @param array List of fields to search in
+ * @param string Search value
+ * @param boolean True if results are requested, False if count only
+ * @return Indexed list of contact records and 'count' value
+ */
+ function search($fields, $value, $select=true)
+ {
+ // special treatment for ID-based search
+ if ($fields == 'ID' || $fields == $this->primary_key)
{
- if ($this->conn)
- {
- if ($scope === 'sub')
- $sr = @ldap_search($this->conn, $base, $filter, $attributes, 0, $limit);
- else if ($scope === 'one')
- $sr = @ldap_list($this->conn, $base, $filter, $attributes, 0, $limit);
- else if ($scope === 'base')
- $sr = @ldap_read($this->conn, $base, $filter, $attributes, 0, $limit);
- if ($sr)
+ $ids = explode(',', $value);
+ $result = new rcube_result_set();
+ foreach ($ids as $id)
+ if ($rec = $this->get_record($id, true))
{
- if ($sort && $scope !== "base")
- {
- if (is_array($sort))
- {
- // Start from the end so first sort field has highest priority
- $sortfields = array_reverse($sort);
- foreach ($sortfields as $sortfield)
- @ldap_sort($this->conn, $sr, $sortfield);
- }
- else
- @ldap_sort($this->conn, $sr, $sort);
- }
- return @ldap_get_entries($this->conn, $sr);
+ $result->add($rec);
+ $result->count++;
}
- }
- else
- raise_error(array("type" => "ldap",
- "message" => "Attempted search on nonexistent connection"), TRUE);
- return FALSE;
+
+ return $result;
}
-
- function add($dn, $object)
+
+ $filter = '(|';
+ $wc = $this->prop['fuzzy_search'] ? '*' : '';
+ if (is_array($this->prop['search_fields']))
{
- if ($this->conn)
- {
- if (@ldap_add($this->conn, $dn, $object))
- return TRUE;
- else
- raise_error(array("code" => ldap_errno($this->conn),
- "type" => "ldap",
- "message" => "Add object failed: ".ldap_error($this->conn)),
- TRUE);
- }
+ foreach ($this->prop['search_fields'] as $k => $field)
+ $filter .= "($field=$wc" . rcube_ldap::quote_string($value) . "$wc)";
+ }
else
- raise_error(array("type" => "ldap",
- "message" => "Add object faile: no connection"),
- TRUE);
- return FALSE;
+ {
+ foreach ((array)$fields as $field)
+ if ($f = $this->_map_field($field))
+ $filter .= "($f=$wc" . rcube_ldap::quote_string($value) . "$wc)";
}
+ $filter .= ')';
- function modify($dn, $object)
- {
- if ($this->conn)
- {
- if (@ldap_modify($this->conn, $dn, $object))
- return TRUE;
- else
- raise_error(array("code" => ldap_errno($this->conn),
- "type" => "ldap",
- "message" => "Modify object failed: ".ldap_error($this->conn)),
- TRUE);
- }
+ // set filter string and execute search
+ $this->set_search_set($filter);
+ $this->_exec_search();
+
+ if ($select)
+ $this->list_records();
else
- raise_error(array("type" => "ldap",
- "message" => "Modify object failed: no connection"),
- TRUE);
- return FALSE;
- }
+ $this->result = $this->count();
+
+ return $this->result;
+ }
- function rename($dn, $newrdn, $parentdn)
- {
- if ($this->protocol < 3)
- {
- raise_error(array("type" => "ldap",
- "message" => "rename() support requires LDAPv3 or above "),
- TRUE);
- return FALSE;
- }
- if ($this->conn)
+ /**
+ * Count number of available contacts in database
+ *
+ * @return Result array with values for 'count' and 'first'
+ */
+ function count()
+ {
+ $count = 0;
+ if ($this->conn && $this->ldap_result)
+ $count = ldap_count_entries($this->conn, $this->ldap_result);
+
+ return new rcube_result_set($count, ($this->list_page-1) * $this->page_size);
+ }
+
+
+ /**
+ * Return the last result set
+ *
+ * @return Result array or NULL if nothing selected yet
+ */
+ function get_result()
+ {
+ return $this->result;
+ }
+
+
+ /**
+ * Get a specific contact record
+ *
+ * @param mixed record identifier
+ * @return Hash array with all record fields or False if not found
+ */
+ function get_record($dn, $assoc=false)
+ {
+ $res = null;
+ if ($this->conn && $dn)
+ {
+ $this->ldap_result = @ldap_read($this->conn, base64_decode($dn), "(objectclass=*)", array_values($this->fieldmap));
+ $entry = @ldap_first_entry($this->conn, $this->ldap_result);
+
+ if ($entry && ($rec = ldap_get_attributes($this->conn, $entry)))
{
- if (@ldap_rename($this->conn, $dn, $newrdn, $parentdn, TRUE))
- return TRUE;
- else
- raise_error(array("code" => ldap_errno($this->conn),
- "type" => "ldap",
- "message" => "Rename object failed: ".ldap_error($this->conn)),
- TRUE);
+ $res = $this->_ldap2result($rec);
+ $this->result = new rcube_result_set(1);
+ $this->result->add($res);
}
- else
- raise_error(array("type" => "ldap",
- "message" => "Rename object failed: no connection"),
- TRUE);
- return FALSE;
}
- function delete($dn)
+ return $assoc ? $res : $this->result;
+ }
+
+
+ /**
+ * Create a new contact record
+ *
+ * @param array Assoziative array with save data
+ * @return The create record ID on success, False on error
+ */
+ function insert($save_cols)
+ {
+ // TODO
+ return false;
+ }
+
+
+ /**
+ * Update a specific contact record
+ *
+ * @param mixed Record identifier
+ * @param array Assoziative array with save data
+ * @return True on success, False on error
+ */
+ function update($id, $save_cols)
+ {
+ // TODO
+ return false;
+ }
+
+
+ /**
+ * Mark one or more contact records as deleted
+ *
+ * @param array Record identifiers
+ */
+ function delete($ids)
+ {
+ // TODO
+ return false;
+ }
+
+
+ /**
+ * Execute the LDAP search based on the stored credentials
+ *
+ * @private
+ */
+ function _exec_search()
+ {
+ if ($this->conn && $this->filter)
{
- if ($this->conn)
- {
- if (@ldap_delete($this->conn, $dn))
- return TRUE;
- else
- raise_error(array("code" => ldap_errno($this->conn),
- "type" => "ldap",
- "message" => "Delete object failed: ".ldap_error($this->conn)),
- TRUE);
- }
+ $function = $this->prop['scope'] == 'sub' ? 'ldap_search' : ($this->prop['scope'] == 'base' ? 'ldap_read' : 'ldap_list');
+ $this->ldap_result = @$function($this->conn, $this->prop['base_dn'], $this->filter, array_values($this->fieldmap), 0, 0);
+ return true;
+ }
else
- raise_error(array("type" => "ldap",
- "message" => "Delete object failed: no connection"),
- TRUE);
- return FALSE;
+ return false;
+ }
+
+
+ /**
+ * @private
+ */
+ function _ldap2result($rec)
+ {
+ $out = array();
+
+ if ($rec['dn'])
+ $out[$this->primary_key] = base64_encode($rec['dn']);
+
+ foreach ($this->fieldmap as $rf => $lf)
+ {
+ if ($rec[$lf]['count'])
+ $out[$rf] = $rec[$lf][0];
}
-
+
+ return $out;
+ }
+
+
+ /**
+ * @private
+ */
+ function _map_field($field)
+ {
+ return $this->fieldmap[$field];
}
+
+
+ /**
+ * @static
+ */
+ function quote_string($str)
+ {
+ return strtr($str, array('*'=>'\2a', '('=>'\28', ')'=>'\29', '\\'=>'\5c'));
+ }
+
+
+}
-// vi: et ts=2 sw=2
-?>
+?>
\ No newline at end of file
diff --git a/program/include/rcube_shared.inc b/program/include/rcube_shared.inc
index 0d502f81c..0f8be06c2 100644
--- a/program/include/rcube_shared.inc
+++ b/program/include/rcube_shared.inc
@@ -1,1605 +1,1597 @@
<?php
/*
+-----------------------------------------------------------------------+
| rcube_shared.inc |
| |
| This file is part of the RoundCube PHP suite |
- | Copyright (C) 2005-2006, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| CONTENTS: |
| Shared functions and classes used in PHP projects |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
// ********* round cube schared classes *********
class rcube_html_page
{
var $css;
var $scripts_path = '';
var $script_files = array();
var $external_scripts = array();
var $scripts = array();
var $charset = 'ISO-8859-1';
var $script_tag_file = "<script type=\"text/javascript\" src=\"%s%s\"></script>\n";
var $script_tag = "<script type=\"text/javascript\">\n<!--\n%s\n\n//-->\n</script>\n";
var $default_template = "<html>\n<head><title></title></head>\n<body></body>\n</html>";
var $tag_format_external_script = "<script type=\"text/javascript\" src=\"%s\"></script>\n";
var $title = '';
var $header = '';
var $footer = '';
var $body = '';
var $body_attrib = array();
var $meta_tags = array();
// PHP 5 constructor
function __construct()
{
$this->css = new rcube_css();
}
// PHP 4 compatibility
function rcube_html_page()
{
$this->__construct();
}
function include_script($file, $position='head')
{
static $sa_files = array();
if (in_array($file, $sa_files))
return;
if (!is_array($this->script_files[$position]))
$this->script_files[$position] = array();
$this->script_files[$position][] = $file;
}
function include_external_script($script_location, $position='head')
{
if (!is_array($this->external_scripts[$position]))
{
$this->external_scripts[$position] = array();
}
$this->external_scripts[$position][] = $script_location;
}
function add_script($script, $position='head')
{
if (!isset($this->scripts[$position]))
- $this->scripts[$position] = "\n$script";
+ $this->scripts[$position] = "\n".rtrim($script);
else
- $this->scripts[$position] .= "\n$script";
+ $this->scripts[$position] .= "\n".rtrim($script);
}
+ function add_header($str)
+ {
+ $this->header .= "\n".$str;
+ }
+
+ function add_footer($str)
+ {
+ $this->footer .= "\n".$str;
+ }
function set_title($t)
{
$this->title = $t;
}
function set_charset($charset)
{
global $MBSTRING;
$this->charset = $charset;
if ($MBSTRING && function_exists("mb_internal_encoding"))
{
if(!@mb_internal_encoding($charset))
$MBSTRING = FALSE;
}
}
function get_charset()
{
return $this->charset;
}
function reset()
{
$this->css = new rcube_css();
$this->script_files = array();
$this->scripts = array();
$this->title = '';
+ $this->header = '';
+ $this->footer = '';
}
function write($templ='', $base_path='')
{
$output = empty($templ) ? $this->default_template : trim($templ);
// set default page title
if (empty($this->title))
$this->title = 'RoundCube Mail';
// replace specialchars in content
$__page_title = Q($this->title, 'show', FALSE);
$__page_header = $__page_body = $__page_footer = '';
// include meta tag with charset
if (!empty($this->charset))
{
header('Content-Type: text/html; charset='.$this->charset);
$__page_header = '<meta http-equiv="content-type" content="text/html; charset='.$this->charset.'" />'."\n";
}
// definition of the code to be placed in the document header and footer
if (is_array($this->script_files['head']))
foreach ($this->script_files['head'] as $file)
$__page_header .= sprintf($this->script_tag_file, $this->scripts_path, $file);
- if (is_array($this->external_scripts['head']))
- {
+ if (is_array($this->external_scripts['head']))
foreach ($this->external_scripts['head'] as $xscript)
- {
- $__page_header .= sprintf($this->tag_format_external_script, $xscript);
- }
- }
+ $__page_header .= sprintf($this->tag_format_external_script, $xscript);
+
+ $head_script = $this->scripts['head_top'] . $this->scripts['head'];
+ if (!empty($head_script))
+ $__page_header .= sprintf($this->script_tag, $head_script);
+
+ if (!empty($this->header))
+ $__page_header .= $this->header;
- if (!empty($this->scripts['head']))
- $__page_header .= sprintf($this->script_tag, $this->scripts['head']);
-
if (is_array($this->script_files['foot']))
- {
foreach ($this->script_files['foot'] as $file)
$__page_footer .= sprintf($this->script_tag_file, $this->scripts_path, $file);
- }
if (!empty($this->scripts['foot']))
$__page_footer .= sprintf($this->script_tag, $this->scripts['foot']);
- if ($this->footer)
- $__page_footer .= "\n" . $this->footer;
+ if (!empty($this->footer))
+ $__page_footer .= $this->footer;
$__page_header .= $this->css->show();
// find page header
- if($hpos = rc_strpos(rc_strtolower($output), '</head>'))
+ if($hpos = strpos(strtolower($output), '</head>'))
$__page_header .= "\n";
else
{
if (!is_numeric($hpos))
- $hpos = rc_strpos(rc_strtolower($output), '<body');
- if (!is_numeric($hpos) && ($hpos = rc_strpos(rc_strtolower($output), '<html')))
+ $hpos = strpos(strtolower($output), '<body');
+ if (!is_numeric($hpos) && ($hpos = strpos(strtolower($output), '<html')))
{
while($output[$hpos]!='>')
$hpos++;
$hpos++;
}
$__page_header = "<head>\n<title>$__page_title</title>\n$__page_header\n</head>\n";
}
// add page hader
if($hpos)
- $output = rc_substr($output,0,$hpos) . $__page_header . rc_substr($output,$hpos,rc_strlen($output));
+ $output = substr($output,0,$hpos) . $__page_header . substr($output,$hpos,strlen($output));
else
$output = $__page_header . $output;
// find page body
- if($bpos = rc_strpos(rc_strtolower($output), '<body'))
+ if($bpos = strpos(strtolower($output), '<body'))
{
while($output[$bpos]!='>') $bpos++;
$bpos++;
}
else
- $bpos = rc_strpos(rc_strtolower($output), '</head>')+7;
+ $bpos = strpos(strtolower($output), '</head>')+7;
// add page body
if($bpos && $__page_body)
- $output = rc_substr($output,0,$bpos) . "\n$__page_body\n" . rc_substr($output,$bpos,rc_strlen($output));
+ $output = substr($output,0,$bpos) . "\n$__page_body\n" . substr($output,$bpos,strlen($output));
// find and add page footer
- $output_lc = rc_strtolower($output);
+ $output_lc = strtolower($output);
if(($fpos = strrstr($output_lc, '</body>')) ||
($fpos = strrstr($output_lc, '</html>')))
$output = substr($output, 0, $fpos) . "$__page_footer\n" . substr($output, $fpos);
else
$output .= "\n$__page_footer";
// reset those global vars
$__page_header = $__page_footer = '';
// correct absolute paths in images and other tags
$output = preg_replace('/(src|href|background)=(["\']?)(\/[a-z0-9_\-]+)/Ui', "\\1=\\2$base_path\\3", $output);
$output = str_replace('$__skin_path', $base_path, $output);
print rcube_charset_convert($output, 'UTF-8', $this->charset);
}
function _parse($templ)
{
}
}
class rcube_css
{
var $css_data = array();
var $css_groups = array();
var $include_files = array();
var $grouped_output = TRUE;
var $content_type = 'text/css';
var $base_path = '';
var $indent_chars = "\t";
// add or overwrite a css definition
// either pass porperty and value as separate arguments
// or provide an associative array as second argument
function set_style($selector, $property, $value='')
{
$a_elements = $this->_parse_selectors($selector);
foreach ($a_elements as $element)
{
if (!is_array($property))
$property = array($property => $value);
foreach ($property as $name => $value)
$this->css_data[$element][strtolower($name)] = $value;
}
// clear goups array
$this->css_groups = array();
}
// unset a style property
function remove_style($selector, $property)
{
if (!is_array($property))
$property = array($property);
foreach ($property as $key)
unset($this->css_data[$selector][strtolower($key)]);
// clear goups array
$this->css_groups = array();
}
// define base path for external css files
function set_basepath($path)
{
$this->base_path = preg_replace('/\/$/', '', $path);
}
// enable/disable grouped output
function set_grouped_output($grouped)
{
$this->grouped_output = $grouped;
}
// add a css file as external source
function include_file($filename, $media='')
{
// include multiple files
if (is_array($filename))
{
foreach ($filename as $file)
$this->include_file($file, $media);
}
// add single file
else if (!in_array($filename, $this->include_files))
$this->include_files[] = array('file' => $filename,
'media' => $media);
}
// parse css code
function import_string($str)
{
$ret = FALSE;
if (strlen($str))
$ret = $this->_parse($str);
return $ret;
}
// open and parse a css file
function import_file($file)
{
$ret = FALSE;
if (!is_file($file))
return $ret;
// for php version >= 4.3.0
if (function_exists('file_get_contents'))
$ret = $this->_parse(file_get_contents($file));
// for order php versions
else if ($fp = fopen($file, 'r'))
{
$ret = $this->_parse(fread($fp, filesize($file)));
fclose($fp);
}
return $ret;
}
// copy all properties inherited from superior styles to a specific selector
function copy_inherited_styles($selector)
{
// get inherited props from body and tag/class selectors
$css_props = $this->_get_inherited_styles($selector);
// write modified props back and clear goups array
if (sizeof($css_props))
{
$this->css_data[$selector] = $css_props;
$this->css_groups = array();
}
}
// return css definition for embedding in HTML
function show()
{
$out = '';
// include external css files
if (sizeof($this->include_files))
foreach ($this->include_files as $file_arr)
$out .= sprintf('<link rel="stylesheet" type="%s" href="%s"%s>'."\n",
$this->content_type,
$this->_get_file_path($file_arr['file']),
$file_arr['media'] ? ' media="'.$file_arr['media'].'"' : '');
// compose css string
if (sizeof($this->css_data))
$out .= sprintf("<style type=\"%s\">\n<!--\n\n%s-->\n</style>",
$this->content_type,
$this->to_string());
return $out;
}
// return valid css code of the current styles grid
function to_string($selector=NULL)
{
// return code for a single selector
if ($selector)
{
$indent_str = $this->indent_chars;
$this->indent_chars = '';
$prop_arr = $this->to_array($selector);
$out = $this->_style2string($prop_arr, TRUE);
$this->indent_chars = $indent_str;
}
// compose css code for complete data grid
else
{
$out = '';
$css_data = $this->to_array();
foreach ($css_data as $key => $prop_arr)
$out .= sprintf("%s {\n%s}\n\n",
$key,
$this->_style2string($prop_arr, TRUE));
}
return $out;
}
// return a single-line string of a css definition
function to_inline($selector)
{
if ($this->css_data[$selector])
return str_replace('"', '\\"', $this->_style2string($this->css_data[$selector], FALSE));
}
// return an associative array with selector(s) as key and styles array as value
function to_array($selector=NULL)
{
if (!$selector && $this->grouped_output)
{
// build groups if desired
if (!sizeof($this->css_groups))
$this->_build_groups();
// modify group array to get an array(selector => properties)
$out_arr = array();
foreach ($this->css_groups as $group_arr)
{
$key = join(', ', $group_arr['selectors']);
$out_arr[$key] = $group_arr['properties'];
}
}
else
$out_arr = $this->css_data;
return $selector ? $out_arr[$selector] : $out_arr;
}
// create a css file
function to_file($filepath)
{
if ($fp = fopen($filepath, 'w'))
{
fwrite($fp, $this->to_string());
fclose($fp);
return TRUE;
}
return FALSE;
}
// alias method for import_string() [DEPRECATED]
function add($str)
{
$this->import_string($str);
}
// alias method for to_string() [DEPRECATED]
function get()
{
return $this->to_string();
}
// ******** private methods ********
// parse a string and add styles to internal data grid
function _parse($str)
{
// remove comments
$str = preg_replace("/\/\*(.*)?\*\//Usi", '', $str);
// parse style definitions
if (!preg_match_all ('/([a-z0-9\.#*:_][a-z0-9\.\-_#:*,\[\]\(\)\s\"\'\+\|>~=]+)\s*\{([^\}]*)\}/ims', $str, $matches, PREG_SET_ORDER))
return FALSE;
foreach ($matches as $match_arr)
{
// split selectors into array
$a_keys = $this->_parse_selectors(trim($match_arr[1]));
// parse each property of an element
$codes = explode(";", trim($match_arr[2]));
foreach ($codes as $code)
{
if (strlen(trim($code))>0)
{
// find the property and the value
if (!($sep = strpos($code, ':')))
continue;
$property = strtolower(trim(substr($code, 0, $sep)));
$value = trim(substr($code, $sep+1));
// add the property to the object array
foreach ($a_keys as $key)
$this->css_data[$key][$property] = $value;
}
}
}
// clear goups array
if (sizeof($matches))
{
$this->css_groups = array();
return TRUE;
}
return FALSE;
}
// split selector group
function _parse_selectors($selector)
{
// trim selector and remove multiple spaces
$selector = preg_replace('/\s+/', ' ', trim($selector));
if (strpos($selector, ','))
return preg_split('/[\t\s\n\r]*,[\t\s\n\r]*/mi', $selector);
else
return array($selector);
}
// compare identical styles and make groups
function _build_groups()
{
// clear group array
$this->css_groups = array();
$string_group_map = array();
// bulild css string for each selector and check if the same is already defines
foreach ($this->css_data as $selector => $prop_arr)
{
// make shure to compare props in the same order
ksort($prop_arr);
$compare_str = preg_replace('/[\s\t]+/', '', $this->_style2string($prop_arr, FALSE));
// add selector to extisting group
if (isset($string_group_map[$compare_str]))
{
$group_index = $string_group_map[$compare_str];
$this->css_groups[$group_index]['selectors'][] = $selector;
}
// create new group
else
{
$i = sizeof($this->css_groups);
$string_group_map[$compare_str] = $i;
$this->css_groups[$i] = array('selectors' => array($selector),
'properties' => $this->css_data[$selector]);
}
}
}
// convert the prop array into a valid css definition
function _style2string($prop_arr, $multiline=TRUE)
{
$out = '';
$delm = $multiline ? "\n" : '';
$spacer = $multiline ? ' ' : '';
$indent = $multiline ? $this->indent_chars : '';
if (is_array($prop_arr))
foreach ($prop_arr as $prop => $value)
if (strlen($value))
$out .= sprintf('%s%s:%s%s;%s',
$indent,
$prop,
$spacer,
$value,
$delm);
return $out;
}
// copy all properties inherited from superior styles to a specific selector
function _get_inherited_styles($selector, $loop=FALSE)
{
$css_props = $this->css_data[$selector] ? $this->css_data[$selector] : array();
// get styles from tag selector
if (preg_match('/(([a-z0-9]*)(\.[^\s]+)?)$/i', $selector, $regs))
{
$sel = $regs[1];
$tagname = $regs[2];
$class = $regs[3];
if ($sel && is_array($this->css_data[$sel]))
$css_props = $this->_merge_styles($this->css_data[$sel], $css_props);
if ($class && is_array($this->css_data[$class]))
$css_props = $this->_merge_styles($this->css_data[$class], $css_props);
if ($tagname && is_array($this->css_data[$tagname]))
$css_props = $this->_merge_styles($this->css_data[$tagname], $css_props);
}
// analyse inheritance
if (strpos($selector, ' '))
{
$a_hier = split(' ', $selector);
if (sizeof($a_hier)>1)
{
array_pop($a_hier);
$base_selector = join(' ', $a_hier);
// call this method recursively
$new_props = $this->_get_inherited_styles($base_selector, TRUE);
$css_props = $this->_merge_styles($new_props, $css_props);
}
}
// get body style
if (!$loop && is_array($this->css_data['body']))
$css_props = $this->_merge_styles($this->css_data['body'], $css_props);
return $css_props;
}
// merge two arrays with style properties together like a browser would do
function _merge_styles($one, $two)
{
// these properties are additive
foreach (array('text-decoration') as $prop)
if ($one[$prop] && $two[$prop])
{
// if value contains 'none' it's ignored
if (strstr($one[$prop], 'none'))
continue;
else if (strstr($two[$prop], 'none'))
unset($two[$prop]);
$a_values_one = split(' ', $one[$prop]);
$a_values_two = split(' ', $two[$prop]);
$two[$prop] = join(' ', array_unique(array_merge($a_values_one, $a_values_two)));
}
return array_merge($one, $two);
}
// resolve file path
function _get_file_path($file)
{
if (!$this->base_path && $GLOBALS['CSS_PATH'])
$this->set_basepath($GLOBALS['CSS_PATH']);
$base = ($file{0}=='/' || $file{0}=='.' || substr($file, 0, 7)=='http://') ? '' :
($this->base_path ? $this->base_path.'/' : '');
return $base.$file;
}
}
class base_form_element
{
var $uppertags = FALSE;
var $upperattribs = FALSE;
var $upperprops = FALSE;
var $newline = FALSE;
var $attrib = array();
// create string with attributes
function create_attrib_string($tagname='')
{
if (!sizeof($this->attrib))
return '';
if ($this->name!='')
$this->attrib['name'] = $this->name;
$attrib_arr = array();
foreach ($this->attrib as $key => $value)
{
// don't output some internally used attributes
if (in_array($key, array('form', 'quicksearch')))
continue;
// skip if size if not numeric
if (($key=='size' && !is_numeric($value)))
continue;
// skip empty eventhandlers
if ((strpos($key,'on')===0 && $value==''))
continue;
// encode textarea content
if ($key=='value')
$value = Q($value, 'strict', FALSE);
// attributes with no value
if (in_array($key, array('checked', 'multiple', 'disabled', 'selected')))
{
if ($value)
$attrib_arr[] = $key;
}
// don't convert size of value attribute
else if ($key=='value')
$attrib_arr[] = sprintf('%s="%s"', $this->_conv_case($key, 'attrib'), $value, 'value');
// regular tag attributes
else
$attrib_arr[] = sprintf('%s="%s"', $this->_conv_case($key, 'attrib'), $this->_conv_case($value, 'value'));
}
return sizeof($attrib_arr) ? ' '.implode(' ', $attrib_arr) : '';
}
// convert tags and attributes to upper-/lowercase
// $type can either be "tag" or "attrib"
function _conv_case($str, $type='attrib')
{
if ($type == 'tag')
return $this->uppertags ? strtoupper($str) : strtolower($str);
else if ($type == 'attrib')
return $this->upperattribs ? strtoupper($str) : strtolower($str);
else if ($type == 'value')
return $this->upperprops ? strtoupper($str) : strtolower($str);
}
}
class input_field extends base_form_element
{
var $type = 'text';
// PHP 5 constructor
function __construct($attrib=NULL)
{
if (is_array($attrib))
$this->attrib = $attrib;
if ($attrib['type'])
$this->type = $attrib['type'];
if ($attrib['newline'])
$this->newline = TRUE;
}
// PHP 4 compatibility
function input_field($attrib=array())
{
$this->__construct($attrib);
}
// compose input tag
function show($value=NULL, $attrib=NULL)
{
// overwrite object attributes
if (is_array($attrib))
$this->attrib = array_merge($this->attrib, $attrib);
// set value attribute
if ($value!==NULL)
$this->attrib['value'] = $value;
$this->attrib['type'] = $this->type;
// return final tag
return sprintf('<%s%s />%s',
$this->_conv_case('input', 'tag'),
$this->create_attrib_string(),
($this->newline ? "\n" : ""));
}
}
class textfield extends input_field
{
var $type = 'text';
}
class passwordfield extends input_field
{
var $type = 'password';
}
class radiobutton extends input_field
{
var $type = 'radio';
}
class checkbox extends input_field
{
var $type = 'checkbox';
function show($value='', $attrib=NULL)
{
// overwrite object attributes
if (is_array($attrib))
$this->attrib = array_merge($this->attrib, $attrib);
$this->attrib['type'] = $this->type;
if ($value && (string)$value==(string)$this->attrib['value'])
$this->attrib['checked'] = TRUE;
else
$this->attrib['checked'] = FALSE;
// return final tag
return sprintf('<%s%s />%s',
$this->_conv_case('input', 'tag'),
$this->create_attrib_string(),
($this->newline ? "\n" : ""));
}
}
class textarea extends base_form_element
{
// PHP 5 constructor
function __construct($attrib=array())
{
$this->attrib = $attrib;
if ($attrib['newline'])
$this->newline = TRUE;
}
// PHP 4 compatibility
function textarea($attrib=array())
{
$this->__construct($attrib);
}
function show($value='', $attrib=NULL)
{
// overwrite object attributes
if (is_array($attrib))
$this->attrib = array_merge($this->attrib, $attrib);
// take value attribute as content
if ($value=='')
$value = $this->attrib['value'];
// make shure we don't print the value attribute
if (isset($this->attrib['value']))
unset($this->attrib['value']);
if (!empty($value) && !isset($this->attrib['mce_editable']))
$value = Q($value, 'strict', FALSE);
// return final tag
return sprintf('<%s%s>%s</%s>%s',
$this->_conv_case('textarea', 'tag'),
$this->create_attrib_string(),
$value,
$this->_conv_case('textarea', 'tag'),
($this->newline ? "\n" : ""));
}
}
class hiddenfield extends base_form_element
{
var $fields_arr = array();
var $newline = TRUE;
// PHP 5 constructor
function __construct($attrib=NULL)
{
if (is_array($attrib))
$this->add($attrib);
}
// PHP 4 compatibility
function hiddenfield($attrib=NULL)
{
$this->__construct($attrib);
}
// add a hidden field to this instance
function add($attrib)
{
$this->fields_arr[] = $attrib;
}
function show()
{
$out = '';
foreach ($this->fields_arr as $attrib)
{
$this->attrib = $attrib;
$this->attrib['type'] = 'hidden';
$out .= sprintf('<%s%s />%s',
$this->_conv_case('input', 'tag'),
$this->create_attrib_string(),
($this->newline ? "\n" : ""));
}
return $out;
}
}
class select extends base_form_element
{
var $options = array();
/*
syntax:
-------
// create instance. arguments are used to set attributes of select-tag
$select = new select(array('name' => 'fieldname'));
// add one option
$select->add('Switzerland', 'CH');
// add multiple options
$select->add(array('Switzerland', 'Germany'),
array('CH', 'DE'));
// add 10 blank options with 50 chars
// used to fill with javascript (necessary for 4.x browsers)
$select->add_blank(10, 50);
// generate pulldown with selection 'Switzerland' and return html-code
// as second argument the same attributes available to instanciate can be used
print $select->show('CH');
*/
// PHP 5 constructor
function __construct($attrib=NULL)
{
if (is_array($attrib))
$this->attrib = $attrib;
if ($attrib['newline'])
$this->newline = TRUE;
}
// PHP 4 compatibility
function select($attrib=NULL)
{
$this->__construct($attrib);
}
function add($names, $values=NULL)
{
if (is_array($names))
{
foreach ($names as $i => $text)
$this->options[] = array('text' => $text, 'value' => (string)$values[$i]);
}
else
{
$this->options[] = array('text' => $names, 'value' => (string)$values);
}
}
function add_blank($nr, $width=0)
{
$text = $width ? str_repeat('&nbsp;', $width) : '';
for ($i=0; $i < $nr; $i++)
$this->options[] = array('text' => $text);
}
function show($select=array(), $attrib=NULL)
{
$options_str = "\n";
$value_str = $this->_conv_case(' value="%s"', 'attrib');
if (!is_array($select))
$select = array((string)$select);
foreach ($this->options as $option)
{
$selected = ((isset($option['value']) &&
in_array($option['value'], $select, TRUE)) ||
(in_array($option['text'], $select, TRUE))) ?
$this->_conv_case(' selected', 'attrib') : '';
-
+
$options_str .= sprintf("<%s%s%s>%s</%s>\n",
$this->_conv_case('option', 'tag'),
- isset($option['value']) ? sprintf($value_str, $option['value']) : '',
+ !empty($option['value']) ? sprintf($value_str, Q($option['value'])) : '',
$selected,
Q($option['text'], 'strict', FALSE),
$this->_conv_case('option', 'tag'));
}
// return final tag
return sprintf('<%s%s>%s</%s>%s',
$this->_conv_case('select', 'tag'),
$this->create_attrib_string(),
$options_str,
$this->_conv_case('select', 'tag'),
($this->newline ? "\n" : ""));
}
}
// ********* rcube schared functions *********
// provide details about the client's browser
function rcube_browser()
{
$HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
$bw['ver'] = 0;
$bw['win'] = stristr($HTTP_USER_AGENT, 'win');
$bw['mac'] = stristr($HTTP_USER_AGENT, 'mac');
$bw['linux'] = stristr($HTTP_USER_AGENT, 'linux');
$bw['unix'] = stristr($HTTP_USER_AGENT, 'unix');
$bw['ns4'] = stristr($HTTP_USER_AGENT, 'mozilla/4') && !stristr($HTTP_USER_AGENT, 'msie');
$bw['ns'] = ($bw['ns4'] || stristr($HTTP_USER_AGENT, 'netscape'));
$bw['ie'] = stristr($HTTP_USER_AGENT, 'msie');
$bw['mz'] = stristr($HTTP_USER_AGENT, 'mozilla/5');
$bw['opera'] = stristr($HTTP_USER_AGENT, 'opera');
$bw['safari'] = stristr($HTTP_USER_AGENT, 'safari');
if($bw['ns'])
{
$test = eregi("mozilla\/([0-9\.]+)", $HTTP_USER_AGENT, $regs);
$bw['ver'] = $test ? (float)$regs[1] : 0;
}
if($bw['mz'])
{
$test = ereg("rv:([0-9\.]+)", $HTTP_USER_AGENT, $regs);
$bw['ver'] = $test ? (float)$regs[1] : 0;
}
if($bw['ie'])
{
$test = eregi("msie ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
$bw['ver'] = $test ? (float)$regs[1] : 0;
}
if($bw['opera'])
{
$test = eregi("opera ([0-9\.]+)", $HTTP_USER_AGENT, $regs);
$bw['ver'] = $test ? (float)$regs[1] : 0;
}
if(eregi(" ([a-z]{2})-([a-z]{2})", $HTTP_USER_AGENT, $regs))
$bw['lang'] = $regs[1];
else
$bw['lang'] = 'en';
$bw['dom'] = ($bw['mz'] || $bw['safari'] || ($bw['ie'] && $bw['ver']>=5) || ($bw['opera'] && $bw['ver']>=7));
$bw['pngalpha'] = $bw['mz'] || $bw['safari'] || ($bw['ie'] && $bw['ver']>=5.5) ||
($bw['ie'] && $bw['ver']>=5 && $bw['mac']) || ($bw['opera'] && $bw['ver']>=7) ? TRUE : FALSE;
return $bw;
}
// get text in the desired language from the language file
function rcube_label($attrib)
{
global $sess_user_lang, $INSTALL_PATH, $OUTPUT;
static $sa_text_data, $s_language, $utf8_decode;
// extract attributes
if (is_string($attrib))
$attrib = array('name' => $attrib);
$nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
$vars = isset($attrib['vars']) ? $attrib['vars'] : '';
$command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
$alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
// load localized texts
if (!$sa_text_data || $s_language != $sess_user_lang)
{
$sa_text_data = array();
// get english labels (these should be complete)
@include($INSTALL_PATH.'program/localization/en_US/labels.inc');
@include($INSTALL_PATH.'program/localization/en_US/messages.inc');
if (is_array($labels))
$sa_text_data = $labels;
if (is_array($messages))
$sa_text_data = array_merge($sa_text_data, $messages);
// include user language files
if ($sess_user_lang!='en' && is_dir($INSTALL_PATH.'program/localization/'.$sess_user_lang))
{
include_once($INSTALL_PATH.'program/localization/'.$sess_user_lang.'/labels.inc');
include_once($INSTALL_PATH.'program/localization/'.$sess_user_lang.'/messages.inc');
if (is_array($labels))
$sa_text_data = array_merge($sa_text_data, $labels);
if (is_array($messages))
$sa_text_data = array_merge($sa_text_data, $messages);
}
$s_language = $sess_user_lang;
}
// text does not exist
if (!($text_item = $sa_text_data[$alias]))
{
/*
raise_error(array('code' => 500,
'type' => 'php',
'line' => __LINE__,
'file' => __FILE__,
'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
*/
return "[$alias]";
}
// make text item array
$a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
// decide which text to use
if ($nr==1)
$text = $a_text_item['single'];
else if ($nr>0)
$text = $a_text_item['multiple'];
else if ($nr==0)
{
if ($a_text_item['none'])
$text = $a_text_item['none'];
else if ($a_text_item['single'])
$text = $a_text_item['single'];
else if ($a_text_item['multiple'])
$text = $a_text_item['multiple'];
}
// default text is single
if ($text=='')
$text = $a_text_item['single'];
// replace vars in text
if (is_array($attrib['vars']))
{
foreach ($attrib['vars'] as $var_key=>$var_value)
$a_replace_vars[substr($var_key, 0, 1)=='$' ? substr($var_key, 1) : $var_key] = $var_value;
}
if ($a_replace_vars)
$text = preg_replace('/\${?([_a-z]{1}[_a-z0-9]*)}?/ei', '$a_replace_vars["\1"]', $text);
// remove variables in text which were not available in arg $vars and $nr
eval("\$text = <<<EOF
$text
EOF;
");
// format output
if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
return ucfirst($text);
else if ($attrib['uppercase'])
return strtoupper($text);
else if ($attrib['lowercase'])
return strtolower($text);
return $text;
}
// send HTTP header for no-cacheing steps
function send_nocacheing_headers()
{
if (headers_sent())
return;
header("Expires: ".gmdate("D, d M Y H:i:s")." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
}
// send header with expire date 30 days in future
function send_future_expire_header($offset=2600000)
{
if (headers_sent())
return;
header("Expires: ".gmdate("D, d M Y H:i:s", mktime()+$offset)." GMT");
header("Cache-Control: max-age=$offset");
header("Pragma: ");
}
// check request for If-Modified-Since and send an according response
function send_modified_header($mdate, $etag=null)
{
if (headers_sent())
return;
$iscached = false;
if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $mdate)
$iscached = true;
$etag = $etag ? "\"$etag\"" : null;
if ($etag && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag)
$iscached = true;
if ($iscached)
header("HTTP/1.x 304 Not Modified");
else
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $mdate)." GMT");
header("Cache-Control: max-age=0");
header("Expires: ");
header("Pragma: ");
if ($etag)
header("Etag: $etag");
if ($iscached)
exit;
}
-// function to convert an array to a javascript array
-function array2js($arr, $type='')
+/**
+ * Convert a variable into a javascript notation string
+ */
+function json_serialize($var)
{
- if (!$type)
- $type = 'mixed';
+ if (is_object($var))
+ $var = get_object_vars($var);
- if (is_array($arr))
+ if (is_array($var))
{
- // no items in array
- if (!sizeof($arr))
- return 'new Array()';
- else
+ // empty array
+ if (!sizeof($var))
+ return '[]';
+ else
{
- $a_pairs = array();
- $keys_arr = array_keys($arr);
- $is_assoc = $have_numeric = 0;
+ $keys_arr = array_keys($var);
+ $is_assoc = $have_numeric = 0;
- for ($i=0; $i<sizeof($keys_arr); ++$i)
+ for ($i=0; $i<sizeof($keys_arr); ++$i)
{
- if(is_numeric($keys_arr[$i]))
- $have_numeric = 1;
- if (!is_numeric($keys_arr[$i]) || $keys_arr[$i]!=$i)
- $is_assoc = 1;
- if($is_assoc && $have_numeric)
- break;
+ if (is_numeric($keys_arr[$i]))
+ $have_numeric = 1;
+ if (!is_numeric($keys_arr[$i]) || $keys_arr[$i] != $i)
+ $is_assoc = 1;
+ if ($is_assoc && $have_numeric)
+ break;
}
+
+ $brackets = $is_assoc ? '{}' : '[]';
+ $pairs = array();
- $previous_was_array = false;
- while (list($key, $value) = each($arr))
+ foreach ($var as $key => $value)
{
- // enclose key with quotes if it is not variable-name conform
- if (!ereg("^[_a-zA-Z]{1}[_a-zA-Z0-9]*$", $key) /* || is_js_reserved_word($key) */)
- $key = "'$key'";
+ // enclose key with quotes if it is not variable-name conform
+ if (!ereg("^[_a-zA-Z]{1}[_a-zA-Z0-9]*$", $key) /* || is_js_reserved_word($key) */)
+ $key = "'$key'";
- if (!is_array($value) && is_string($value))
- {
- $value = str_replace("\r\n", '\n', $value);
- $value = str_replace("\n", '\n', $value);
- }
-
- $is_string = false;
- if (!is_array($value))
- {
- if ($type=='string')
- $is_string = true;
- else if (($type == 'mixed' && is_bool($value)) || $type == 'bool')
- {
- $is_string = false;
- $value = $value ? "true" : "false";
- }
- else if ((($type=='mixed' && is_numeric($value)) || $type=='int') && rc_strlen($value)<16) // js interprets numbers with digits >15 as ...e+...
- $is_string = FALSE;
- else
- $is_string = TRUE;
- }
-
- if ($is_string)
- $value = "'".preg_replace("/(?<!\\\)'/", "\'", $value)."'";
-
- $a_pairs[] = sprintf("%s%s",
- $is_assoc ? "$key:" : '',
- is_array($value) ? array2js($value, $type) : $value);
- }
-
- if ($a_pairs)
- {
- if ($is_assoc)
- $return = '{'.implode(',', $a_pairs).'}';
- else
- $return = '['.implode(',', $a_pairs).']';
+ $pairs[] = sprintf("%s%s", $is_assoc ? "$key:" : '', json_serialize($value));
}
- return $return;
+ return $brackets{0} . implode(',', $pairs) . $brackets{1};
}
}
- else
- {
- return $arr;
- }
+ else if (is_numeric($var) && strval(intval($var)) === strval($var))
+ return $var;
+ else if (is_bool($var))
+ return $var ? '1' : '0';
+ else
+ return "'".JQ($var)."'";
+
+ }
+
+/**
+ * function to convert an array to a javascript array
+ * @deprecated
+ */
+function array2js($arr, $type='')
+ {
+ return json_serialize($arr);
}
-// similar function as in_array() ut case-insensitive
+/**
+ * Similar function as in_array() but case-insensitive
+ */
function in_array_nocase($needle, $haystack)
{
foreach ($haystack as $value)
{
if (strtolower($needle)===strtolower($value))
return TRUE;
}
return FALSE;
}
-
-// find out if the string content means TRUE or FALSE
+/**
+ * Find out if the string content means TRUE or FALSE
+ */
function get_boolean($str)
{
$str = strtolower($str);
if(in_array($str, array('false', '0', 'no', 'nein', ''), TRUE))
return FALSE;
else
return TRUE;
}
// parse a human readable string for a number of bytes
function parse_bytes($str)
{
if (is_numeric($str))
return intval($str);
if (preg_match('/([0-9]+)([a-z])/i', $str, $regs))
{
$bytes = floatval($regs[1]);
switch (strtolower($regs[2]))
{
case 'g':
$bytes *= 1073741824;
break;
case 'm':
$bytes *= 1048576;
break;
case 'k':
$bytes *= 1024;
break;
}
}
return intval($bytes);
}
// create a human readable string for a number of bytes
function show_bytes($bytes)
{
if ($bytes > 1073741824)
{
$gb = $bytes/1073741824;
$str = sprintf($gb>=10 ? "%d GB" : "%.1f GB", $gb);
}
else if ($bytes > 1048576)
{
$mb = $bytes/1048576;
$str = sprintf($mb>=10 ? "%d MB" : "%.1f MB", $mb);
}
else if ($bytes > 1024)
$str = sprintf("%d KB", round($bytes/1024));
else
$str = sprintf('%d B', $bytes);
return $str;
}
// convert paths like ../xxx to an absolute path using a base url
function make_absolute_url($path, $base_url)
{
$host_url = $base_url;
$abs_path = $path;
// cut base_url to the last directory
if (strpos($base_url, '/')>7)
{
$host_url = substr($base_url, 0, strpos($base_url, '/'));
$base_url = substr($base_url, 0, strrpos($base_url, '/'));
}
// $path is absolute
if ($path{0}=='/')
$abs_path = $host_url.$path;
else
{
// strip './' because its the same as ''
$path = preg_replace('/^\.\//', '', $path);
if(preg_match_all('/\.\.\//', $path, $matches, PREG_SET_ORDER))
foreach($matches as $a_match)
{
if (strrpos($base_url, '/'))
$base_url = substr($base_url, 0, strrpos($base_url, '/'));
$path = substr($path, 3);
}
$abs_path = $base_url.'/'.$path;
}
return $abs_path;
}
// wrapper function for strlen
function rc_strlen($str)
{
if (function_exists('mb_strlen'))
return mb_strlen($str);
else
return strlen($str);
}
// wrapper function for strtolower
function rc_strtolower($str)
{
if (function_exists('mb_strtolower'))
return mb_strtolower($str);
else
return strtolower($str);
}
// wrapper function for substr
-function rc_substr($str, $start, $len)
+function rc_substr($str, $start, $len=null)
{
if (function_exists('mb_substr'))
return mb_substr($str, $start, $len);
else
return substr($str, $start, $len);
}
// wrapper function for strpos
function rc_strpos($haystack, $needle, $offset=0)
{
if (function_exists('mb_strpos'))
return mb_strpos($haystack, $needle, $offset);
else
return strpos($haystack, $needle, $offset);
}
// wrapper function for strrpos
function rc_strrpos($haystack, $needle, $offset=0)
{
if (function_exists('mb_strrpos'))
return mb_strrpos($haystack, $needle, $offset);
else
return strrpos($haystack, $needle, $offset);
}
// replace the middle part of a string with ...
// if it is longer than the allowed length
function abbrevate_string($str, $maxlength, $place_holder='...')
{
$length = rc_strlen($str);
$first_part_length = floor($maxlength/2) - rc_strlen($place_holder);
if ($length > $maxlength)
{
$second_starting_location = $length - $maxlength + $first_part_length + 1;
$str = rc_substr($str, 0, $first_part_length) . $place_holder . rc_substr($str, $second_starting_location, $length);
}
return $str;
}
// make sure the string ends with a slash
function slashify($str)
{
return unslashify($str).'/';
}
// remove slash at the end of the string
function unslashify($str)
{
return preg_replace('/\/$/', '', $str);
}
// delete all files within a folder
function clear_directory($dir_path)
{
$dir = @opendir($dir_path);
if(!$dir) return FALSE;
while ($file = readdir($dir))
if (strlen($file)>2)
unlink("$dir_path/$file");
closedir($dir);
return TRUE;
}
// create a unix timestamp with a specified offset from now
function get_offset_time($offset_str, $factor=1)
{
if (preg_match('/^([0-9]+)\s*([smhdw])/i', $offset_str, $regs))
{
$amount = (int)$regs[1];
$unit = strtolower($regs[2]);
}
else
{
$amount = (int)$offset_str;
$unit = 's';
}
$ts = mktime();
switch ($unit)
{
case 'w':
$amount *= 7;
case 'd':
$amount *= 24;
case 'h':
$amount *= 60;
case 'm':
$amount *= 60;
case 's':
$ts += $amount * $factor;
}
return $ts;
}
/**
* strrstr
*
* return the last occurence of a string in another string
* @param haystack string string in which to search
* @param needle string string for which to search
* @return index of needle within haystack, or false if not found
*/
function strrstr($haystack, $needle)
{
$pver = phpversion();
if ($pver[0] >= 5)
{
return strrpos($haystack, $needle);
}
else
{
$index = strpos(strrev($haystack), strrev($needle));
if($index === false) {
return false;
}
$index = strlen($haystack) - strlen($needle) - $index;
return $index;
}
}
?>
diff --git a/program/js/app.js b/program/js/app.js
index 7406df2ff..8d97a512a 100644
--- a/program/js/app.js
+++ b/program/js/app.js
@@ -1,3571 +1,3598 @@
/*
+-----------------------------------------------------------------------+
| RoundCube Webmail Client Script |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005-2007, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Authors: Thomas Bruederli <roundcube@gmail.com> |
| Charles McNulty <charles@charlesmcnulty.com> |
+-----------------------------------------------------------------------+
| Requires: common.js, list.js |
+-----------------------------------------------------------------------+
$Id$
*/
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.onloads = new Array();
// create protected reference to myself
rcube_webmail_client = this;
this.ref = 'rcube_webmail_client';
var ref = this;
// webmail client settings
this.dblclick_time = 500;
this.message_time = 5000;
- this.mbox_expression = new RegExp('[^0-9a-z\-_]', 'gi');
+ this.identifier_expr = 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 = 0; // seconds
+ this.env.comm_path = './';
+ this.env.bin_path = './bin/';
+ this.env.blankpage = 'program/blank.gif';
- // set environment variable
- this.set_env = function(name, value)
+ // set environment variable(s)
+ this.set_env = function(p, value)
{
- this.env[name] = value;
+ if (p != null && typeof(p) == 'object' && !value)
+ for (var n in p)
+ this.env[n] = p[n];
+ else
+ this.env[p] = 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;
};
// execute the given script on load
this.add_onload = function(f)
{
this.onloads[this.onloads.length] = f;
};
// initialize webmail client
this.init = function()
{
var p = this;
this.task = this.env.task;
// check browser
if (!bw.dom || !bw.xmlhttp_test())
{
this.goto_url('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':
if (this.gui_objects.messagelist)
{
this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {multiselect:true, draggable:true, keyboard:true, dblclick_time:this.dblclick_time});
this.message_list.row_init = function(o){ p.init_message_row(o); };
this.message_list.addEventListener('dblclick', function(o){ p.msglist_dbl_click(o); });
this.message_list.addEventListener('keypress', function(o){ p.msglist_keypress(o); });
this.message_list.addEventListener('select', function(o){ p.msglist_select(o); });
this.message_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
this.message_list.addEventListener('dragend', function(o){ p.drag_active = false; });
this.message_list.init();
this.enable_command('toggle_status', true);
if (this.gui_objects.mailcontframe)
{
this.gui_objects.mailcontframe.onmousedown = function(e){ return p.click_on_list(e); };
document.onmouseup = function(e){ return p.doc_mouse_up(e); };
}
else
this.message_list.focus();
}
// enable mail commands
this.enable_command('list', 'checkmail', 'compose', 'add-contact', 'search', 'reset-search', true);
if (this.env.action=='show' || this.env.action=='preview')
{
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);
this.enable_command('lastmessage', true);
}
if (this.env.prev_uid)
{
this.enable_command('previousmessage', true);
this.enable_command('firstmessage', true);
}
}
// make preview/message frame visible
if (this.env.action == 'preview' && this.env.framed && parent.rcmail)
{
this.enable_command('compose', 'add-contact', false);
- parent.rcmail.show_messageframe(true);
+ parent.rcmail.show_contentframe(true);
parent.rcmail.mark_message('read', this.uid);
}
if ((this.env.action=='show' || this.env.action=='preview') && 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.env.spellcheck.spelling_state_observer = function(s){ ref.set_spellcheck_state(s); };
this.set_spellcheck_state('ready');
}
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.gui_objects.folderlist = this.gui_objects.mailboxlist;
this.http_request('getunread', '');
+ }
break;
case 'addressbook':
if (this.gui_objects.contactslist)
{
- this.contact_list = new rcube_list_widget(this.gui_objects.contactslist, {multiselect:true, draggable:false, keyboard:true});
+ this.contact_list = new rcube_list_widget(this.gui_objects.contactslist, {multiselect:true, draggable:true, keyboard:true});
this.contact_list.addEventListener('keypress', function(o){ p.contactlist_keypress(o); });
this.contact_list.addEventListener('select', function(o){ p.contactlist_select(o); });
+ this.contact_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
+ this.contact_list.addEventListener('dragend', function(o){ p.drag_active = false; });
this.contact_list.init();
if (this.env.cid)
this.contact_list.highlight_row(this.env.cid);
if (this.gui_objects.contactslist.parentNode)
{
this.gui_objects.contactslist.parentNode.onmousedown = function(e){ return p.click_on_list(e); };
document.onmouseup = function(e){ return p.doc_mouse_up(e); };
}
else
this.contact_list.focus();
}
this.set_page_buttons();
-
+
+ var writeable;
+ if ((writeable = this.env.address_sources && !this.env.address_sources[this.env.source].readonly))
+ this.enable_command('add', true);
+
if (this.env.cid)
this.enable_command('show', 'edit', true);
- if ((this.env.action=='add' || this.env.action=='edit') && this.gui_objects.editform)
+ if ((this.env.action=='add' || this.env.action=='edit') && writeable && this.gui_objects.editform)
this.enable_command('save', true);
+ else
+ this.enable_command('search', 'reset-search', 'moveto', true);
- this.enable_command('list', 'add', true);
-
- // this.enable_command('ldappublicsearch', this.env.ldappublicsearch);
-
+ this.enable_command('list', true);
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);
if (this.gui_objects.identitieslist)
{
this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist, {multiselect:false, draggable:false, keyboard:false});
this.identity_list.addEventListener('select', function(o){ p.identity_select(o); });
this.identity_list.init();
this.identity_list.focus();
if (this.env.iid)
this.identity_list.highlight_row(this.env.iid);
}
break;
case 'login':
var input_user = rcube_find_object('_user');
var input_pass = rcube_find_object('_pass');
if (input_user)
input_user.onkeypress = function(e){ return rcmail.login_user_keypress(e); };
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);
// 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();
// execute all foreign onload scripts
for (var i=0; i<this.onloads.length; i++)
{
if (typeof(this.onloads[i]) == 'string')
eval(this.onloads[i]);
else if (typeof(this.onloads[i]) == 'function')
this.onloads[i]();
}
};
// start interval for keep-alive/recent_check signal
this.start_keepalive = function()
{
if (this.env.keep_alive && !this.env.framed && this.task=='mail' && this.gui_objects.messagelist)
this._int = setInterval(function(){ ref.check_for_recent(); }, this.env.keep_alive * 1000);
else if (this.env.keep_alive && !this.env.framed && this.task!='login')
this._int = setInterval(function(){ ref.send_keep_alive(); }, this.env.keep_alive * 1000);
}
this.init_message_row = function(row)
{
var uid = row.uid;
if (uid && this.env.messages[uid])
{
row.deleted = this.env.messages[uid].deleted;
row.unread = this.env.messages[uid].unread;
row.replied = this.env.messages[uid].replied;
}
// set eventhandler to message icon
if ((row.icon = row.obj.cells[0].childNodes[0]) && row.icon.nodeName=='IMG')
{
var p = this;
row.icon.id = 'msgicn_'+row.uid;
row.icon._row = row.obj;
row.icon.onmousedown = function(e) { p.command('toggle_status', this); };
}
};
// 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);
// get summary of all field values
- this.cmp_hash = this.compose_field_hash();
+ this.compose_field_hash(true);
// start the auto-save timer
this.auto_save_start();
};
this.init_address_input_events = function(obj)
{
var handler = function(e){ return ref.ksearch_keypress(e,this); };
var handler2 = function(e){ return ref.ksearch_blur(e,this); };
if (obj.addEventListener)
{
obj.addEventListener(bw.safari ? 'keydown' : 'keypress', handler, false);
obj.addEventListener('blur', handler2, false);
}
else
{
obj.onkeydown = handler;
obj.onblur = handler2;
}
obj.setAttribute('autocomplete', 'off');
};
/*********************************************************/
/********* 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':
this.goto_url('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();
this.list_mailbox(props);
}
else if (this.task=='addressbook')
- this.list_contacts();
+ {
+ if (this.env.search_request<0 || (this.env.search_request && props != this.env.source))
+ this.reset_qsearch();
+
+ this.list_contacts(props);
+ this.enable_command('add', (this.env.address_sources && !this.env.address_sources[props].readonly));
+ }
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 'lastpage':
this.list_page('last');
break;
case 'previouspage':
this.list_page('prev');
break;
case 'firstpage':
this.list_page('first');
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.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
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')
this.load_contact(0, 'add');
-
- /* LDAP stuff, has to be re-written with new address book
- 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.identity_list.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);
+ if (this.task == 'mail')
+ this.move_messages(props);
+ else if (this.task == 'addressbook' && this.drag_active)
+ this.copy_contact(null, props);
break;
case 'toggle_status':
if (props && !props._row)
break;
var uid;
var flag = 'read';
if (props._row.uid)
{
uid = props._row.uid;
this.message_list.dont_select = true;
// toggle read/unread
if (this.message_list.rows[uid].deleted) {
flag = 'undelete';
} else if (!this.message_list.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, this.env.action=='preview');
break;
case 'load-attachment':
var qstring = '_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)
{
if (props.mimetype == 'text/html')
qstring += '&_safe=1';
this.attachment_win = window.open(this.env.comm_path+'&_action=get&'+qstring+'&_frame=1', 'rcubemailattachment');
if (this.attachment_win)
{
setTimeout(function(){ ref.attachment_win.focus(); }, 10);
break;
}
}
this.goto_url('get', qstring+'&_download=1');
break;
case 'select-all':
this.message_list.select_all(props);
break;
case 'select-none':
this.message_list.clear_selection();
break;
case 'nextmessage':
if (this.env.next_uid)
this.show_message(this.env.next_uid, false, this.env.action=='preview');
break;
case 'lastmessage':
if (this.env.last_uid)
this.show_message(this.env.last_uid);
break;
case 'previousmessage':
if (this.env.prev_uid)
this.show_message(this.env.prev_uid, false, this.env.action=='preview');
break;
case 'firstmessage':
if (this.env.first_uid)
this.show_message(this.env.first_uid);
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;
if (uid = this.get_single_uid())
url += '&_draft_uid='+uid+'&_mbox='+urlencode(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();
+ // switch to mail compose step directly
+ if (props && props.indexOf('@') > 0)
+ {
+ url = this.get_task_url('mail', url);
+ this.redirect(url + '&_to='+urlencode(props));
+ break;
+ }
// use contact_id passed as command parameter
+ var a_cids = new Array();
if (props)
a_cids[a_cids.length] = props;
// get selected contacts
- else
+ else if (this.contact_list)
{
var selection = this.contact_list.get_selection();
for (var n=0; n<selection.length; n++)
a_cids[a_cids.length] = selection[n];
-
- /* LDAP stuff, has to be re-written with new address book
- if (!window.frames[this.env.contentframe].rcmail.selection.length)
- {
- for (var n=0; n<selection.length; n++)
- a_cids[a_cids.length] = 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;
+ this.http_request('mailto', '_cid='+urlencode(a_cids.join(','))+'&_source='+urlencode(this.env.source), true);
+
+ break;
}
else if (props)
url += '&_to='+urlencode(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;
+ this.redirect(url);
break;
case 'spellcheck':
if (this.env.spellcheck && this.env.spellcheck.spellCheck && this.spellcheck_ready)
{
this.env.spellcheck.spellCheck(this.env.spellcheck.check_link);
this.set_spellcheck_state('checking');
}
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
// or if compose form did not change
if (!this.env.drafts_mailbox || this.cmp_hash == this.compose_field_hash())
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.goto_url('compose', '_reply_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(command=='reply-all' ? '&_all=1' : ''), true);
break;
case 'forward':
var uid;
if (uid = this.get_single_uid())
this.goto_url('compose', '_forward_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
break;
case 'print':
var uid;
if (uid = this.get_single_uid())
{
ref.printwin = window.open(this.env.comm_path+'&_action=print&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(this.env.safemode ? '&_safe=1' : ''));
if (this.printwin)
setTimeout(function(){ ref.printwin.focus(); }, 20);
}
break;
case 'viewsource':
var uid;
if (uid = this.get_single_uid())
{
ref.sourcewin = window.open(this.env.comm_path+'&_action=viewsource&_uid='+this.env.uid+'&_mbox='+urlencode(this.env.mailbox));
if (this.sourcewin)
setTimeout(function(){ ref.sourcewin.focus(); }, 20);
}
break;
case 'add-contact':
this.add_contact(props);
break;
- // mail quicksearch
+ // quicksearch
case 'search':
if (!props && this.gui_objects.qsearchbox)
props = this.gui_objects.qsearchbox.value;
if (props)
- this.qsearch(urlencode(props), this.env.mailbox);
- break;
+ {
+ this.qsearch(props);
+ break;
+ }
// reset quicksearch
case 'reset-search':
var s = this.env.search_request;
this.reset_qsearch();
- if (s)
+ if (s && this.env.mailbox)
this.list_mailbox(this.env.mailbox);
+ else if (s && this.task == 'addressbook')
+ this.list_contacts(this.env.source);
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':
this.goto_url('');
break;
case 'identities':
this.goto_url('identities');
break;
case 'delete-identity':
this.delete_identity();
case 'folders':
this.goto_url('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(function(){ 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.redirect(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 *********/
/*********************************************************/
this.doc_mouse_up = function(e)
{
if (this.message_list)
this.message_list.blur();
else if (this.contact_list)
this.contact_list.blur();
};
+ this.focus_folder = function(id)
+ {
+ var li;
+ if (this.drag_active && this.check_droptarget(id) && (li = this.get_folder_li(id)))
+ this.set_classname(li, 'droptarget', true);
+ }
+
+ this.unfocus_folder = function(id)
+ {
+ var li;
+ if (this.drag_active && (li = this.get_folder_li(id)))
+ this.set_classname(li, 'droptarget', false);
+ }
- // onmouseup handler for mailboxlist item
- this.mbox_mouse_up = function(mbox)
+ // onmouseup handler for folder list item
+ this.folder_mouse_up = function(id)
{
if (this.drag_active)
{
- this.unfocus_mailbox(mbox);
- this.command('moveto', mbox);
+ this.unfocus_folder(id);
+ this.command('moveto', id);
}
- else
- this.command('list', mbox);
return false;
};
-
this.click_on_list = function(e)
{
if (this.message_list)
this.message_list.focus();
else if (this.contact_list)
this.contact_list.focus();
var mbox_li;
- if (mbox_li = this.get_mailbox_li())
+ if (mbox_li = this.get_folder_li())
this.set_classname(mbox_li, 'unfocused', true);
rcube_event.cancel(e);
};
this.msglist_select = function(list)
{
if (this.preview_timer)
clearTimeout(this.preview_timer);
var selected = list.selection.length==1;
if (this.env.mailbox == this.env.drafts_mailbox)
{
this.enable_command('show', selected);
this.enable_command('delete', 'moveto', list.selection.length>0 ? true : false);
}
else
{
this.enable_command('show', 'reply', 'reply-all', 'forward', 'print', selected);
this.enable_command('delete', 'moveto', list.selection.length>0 ? true : false);
}
// start timer for message preview (wait for double click)
if (selected && this.env.contentframe)
this.preview_timer = setTimeout(function(){ ref.msglist_get_preview(); }, this.dblclick_time + 10);
else if (this.env.contentframe)
- this.show_messageframe(false);
+ this.show_contentframe(false);
};
this.msglist_dbl_click = function(list)
{
if (this.preview_timer)
clearTimeout(this.preview_timer);
var uid = list.get_single_selection();
if (uid && this.env.mailbox == this.env.drafts_mailbox)
this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
else if (uid)
this.show_message(uid, false, false);
};
this.msglist_keypress = function(list)
{
if (list.key_pressed == list.ENTER_KEY)
this.command('show');
else if (list.key_pressed == list.DELETE_KEY)
this.command('delete');
};
this.msglist_get_preview = function()
{
var uid = this.get_single_uid();
- if (uid && this.env.contentframe)
+ if (uid && this.env.contentframe && !this.drag_active)
this.show_message(uid, false, true);
else if (this.env.contentframe)
- this.show_messageframe(false);
+ this.show_contentframe(false);
+ };
+
+
+ this.check_droptarget = function(id)
+ {
+ if (this.task == 'mail')
+ return (id != this.env.mailbox);
+ else if (this.task == 'addressbook')
+ return (id != this.env.source && this.env.address_sources[id] && !this.env.address_sources[id].readonly);
};
/*********************************************************/
/********* (message) list functionality *********/
/*********************************************************/
// when user doble-clicks on a row
this.show_message = function(id, safe, preview)
{
var add_url = '';
var action = preview ? 'preview': 'show';
var target = window;
if (preview && 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)
{
var url = '&_action='+action+'&_uid='+id+'&_mbox='+urlencode(this.env.mailbox)+add_url;
if (action == 'preview' && String(target.location.href).indexOf(url) >= 0)
- this.show_messageframe(true);
+ this.show_contentframe(true);
else
{
this.set_busy(true, 'loading');
target.location.href = this.env.comm_path+url;
}
}
};
- this.show_messageframe = function(show)
+ this.show_contentframe = function(show)
{
var frm;
if (this.env.contentframe && (frm = rcube_find_object(this.env.contentframe)))
{
- if (window.frames[this.env.contentframe] && !show)
- window.frames[this.env.contentframe].location.href = 'program/blank.gif';
- frm.style.display = show ? 'block' : 'none';
+ if (!show && window.frames[this.env.contentframe] && frames[this.env.contentframe].location.href.indexOf(this.env.blankpage)<0)
+ frames[this.env.contentframe].location.href = this.env.blankpage;
+ if (!bw.safari)
+ frm.style.display = show ? 'block' : 'none';
}
if (!show && this.busy)
this.set_busy(false);
};
// list a specific page
this.list_page = function(page)
{
if (page=='next')
page = this.env.current_page+1;
if (page=='last')
page = this.env.pagecount;
if (page=='prev' && this.env.current_page>1)
page = this.env.current_page-1;
if (page=='first' && this.env.current_page>1)
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);
+ this.list_contacts(this.env.source, 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;
+
+ // also send search request to get the right messages
+ if (this.env.search_request)
+ add_url += '&_search='+this.env.search_request;
// 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;
if (this.message_list)
this.message_list.clear_selection();
- this.show_messageframe(false);
+ this.show_contentframe(false);
}
- // 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);
+ this.select_folder(mbox, this.env.mailbox);
+ this.env.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='+urlencode(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.message_list.clear();
// send request to server
var url = '_mbox='+urlencode(mbox)+(page ? '&_page='+page : '');
this.set_busy(true, 'loading');
this.http_request('list', url+add_url, true);
};
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='+urlencode(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='+urlencode(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 current or no mailbox specified or if selection is empty
if (!mbox || !this.env.uid || mbox==this.env.mailbox)
{
if (!this.message_list || !this.message_list.get_selection().length)
return;
}
var lock = false;
var add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
// show wait message
if (this.env.action=='show')
{
lock = true;
this.set_busy(true, 'movingmessage');
}
else
- this.show_messageframe(false);
+ this.show_contentframe(false);
this._with_selected_messages('moveto', lock, add_url);
};
// delete selected messages from the current mailbox
this.delete_messages = function()
{
var selection = this.message_list ? this.message_list.get_selection() : new Array();
// exit if no mailbox specified or if selection is empty
if (!this.env.uid && !selection.length)
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())
{
// if shift was pressed delete it immediately
if (this.message_list && this.message_list.shiftkey)
{
if (confirm(this.get_label('deletemessagesconfirm')))
this.permanently_remove_messages();
}
else
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)
{
this.mark_message('delete');
if(this.env.action=="show")
this.command('nextmessage','',this);
else if (selection.length == 1)
this.message_list.select_next();
}
// 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.permanently_remove_messages();
};
// delete the selected messages permanently
this.permanently_remove_messages = function()
{
// exit if no mailbox specified or if selection is empty
if (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length))
return;
- this.show_messageframe(false);
+ this.show_contentframe(false);
this._with_selected_messages('delete', false, '&_from='+(this.env.action ? this.env.action : ''));
};
// Send a specifc request with UIDs of all selected messages
// @private
this._with_selected_messages = function(action, lock, add_url)
{
var a_uids = new Array();
if (this.env.uid)
a_uids[a_uids.length] = this.env.uid;
else
{
var selection = this.message_list.get_selection();
var id;
for (var n=0; n<selection.length; n++)
{
id = selection[n];
a_uids[a_uids.length] = id;
this.message_list.remove_row(id);
}
this.message_list.select_next();
}
-
- // also send search request to get the right messages
- if (this.env.search_request)
+
+ // also send search request to get the right messages
+ if (this.env.search_request)
add_url += '&_search='+this.env.search_request;
// send request to server
this.http_request(action, '_uid='+a_uids.join(',')+'&_mbox='+urlencode(this.env.mailbox)+add_url, lock);
};
// set a specific flag to one or more messages
this.mark_message = function(flag, uid)
{
var a_uids = new Array();
var selection = this.message_list ? this.message_list.get_selection() : new Array();
if (uid)
a_uids[0] = uid;
else if (this.env.uid)
a_uids[0] = this.env.uid;
else if (this.message_list)
{
for (var id, n=0; n<selection.length; n++)
{
id = selection[n];
if ((flag=='read' && this.message_list.rows[id].unread) || (flag=='unread' && !this.message_list.rows[id].unread)
|| (flag=='delete' && !this.message_list.rows[id].deleted) || (flag=='undelete' && this.message_list.rows[id].deleted))
a_uids[a_uids.length] = id;
}
}
// nothing to do
if (!a_uids.length)
return;
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;
var rows = this.message_list.rows;
for (var i=0; i<a_uids.length; i++)
{
uid = a_uids[i];
if (rows[uid])
{
rows[uid].unread = (flag=='unread' ? true : false);
if (rows[uid].classname.indexOf('unread')<0 && rows[uid].unread)
{
rows[uid].classname += ' unread';
this.set_classname(rows[uid].obj, 'unread', true);
if (this.env.unreadicon)
icn_src = this.env.unreadicon;
}
else if (!rows[uid].unread)
{
rows[uid].classname = rows[uid].classname.replace(/\s*unread/, '');
this.set_classname(rows[uid].obj, 'unread', false);
if (rows[uid].replied && this.env.repliedicon)
icn_src = this.env.repliedicon;
else if (this.env.messageicon)
icn_src = this.env.messageicon;
}
if (rows[uid].icon && icn_src)
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;
var rows = this.message_list.rows;
if (a_uids.length==1)
{
if (rows[a_uids[0]] && 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 (rows[uid]) {
if (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;
var rows = this.message_list.rows;
for (var i=0; i<a_uids.length; i++)
{
uid = a_uids[i];
if (rows[uid]) {
rows[uid].deleted = false;
if (rows[uid].classname.indexOf('deleted') > 0)
{
rows[uid].classname = rows[uid].classname.replace(/\s*deleted/, '');
this.set_classname(rows[uid].obj, 'deleted', false);
}
if (rows[uid].unread && this.env.unreadicon)
icn_src = this.env.unreadicon;
else if (rows[uid].replied && this.env.repliedicon)
icn_src = this.env.repliedicon;
else if (this.env.messageicon)
icn_src = this.env.messageicon;
if (rows[uid].icon && icn_src)
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;
var rows = this.message_list.rows;
for (var i=0; i<a_uids.length; i++)
{
uid = a_uids[i];
if (rows[uid]) {
rows[uid].deleted = true;
if (rows[uid].classname.indexOf('deleted')<0) {
rows[uid].classname += ' deleted';
this.set_classname(rows[uid].obj, 'deleted', true);
}
if (rows[uid].icon && this.env.deletedicon)
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;
- };
-
-
/*********************************************************/
/********* login form methods *********/
/*********************************************************/
// handler for keyboard events on the _user field
this.login_user_keypress = function(e)
{
var key = rcube_event.get_keycode(e);
var elm;
// enter
if ((key==13) && (elm = rcube_find_object('_pass')))
{
elm.focus();
return false;
}
};
-
+
/*********************************************************/
/********* 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=='')&&(tinyMCE.getContent()==''))
{
if (!confirm(this.get_label('nobodywarning')))
{
input_message.focus();
return false;
}
}
return true;
};
this.set_spellcheck_state = function(s)
{
this.spellcheck_ready = (s=='check_spelling' || s=='ready');
this.enable_command('spellcheck', this.spellcheck_ready);
};
+ this.set_draft_id = function(id)
+ {
+ var f;
+ if (f = rcube_find_object('_draft_saveid'))
+ f.value = id;
+ };
+
this.auto_save_start = function()
{
if (this.env.draft_autosave)
this.save_timer = self.setTimeout(function(){ ref.command("savedraft"); }, this.env.draft_autosave * 1000);
};
- this.compose_field_hash = function()
+ this.compose_field_hash = function(save)
{
// 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;
-
+
+ if (save)
+ this.cmp_hash = str;
+
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 is_html = (rcube_find_object('_is_html').value == '1');
var sig, p;
if (!this.env.identity)
this.env.identity = id
if (!is_html)
{
// remove the 'old' signature
if (this.env.identity && this.env.signatures && this.env.signatures[this.env.identity])
{
sig = this.env.signatures[this.env.identity]['text'];
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]['text'];
if (this.env.signatures[id]['is_html'])
{
sig = this.env.signatures[id]['plain_text'];
}
if (sig.indexOf('-- ')!=0)
sig = '-- \n'+sig;
message += '\n'+sig;
}
}
else
{
var eid = tinyMCE.getEditorId('_message');
// editor is a TinyMCE_Control object
var editor = tinyMCE.getInstanceById(eid);
var msgDoc = editor.getDoc();
var msgBody = msgDoc.body;
if (this.env.signatures && this.env.signatures[id])
{
// Append the signature as a span within the body
var sigElem = msgDoc.getElementById("_rc_sig");
if (!sigElem)
{
sigElem = msgDoc.createElement("span");
sigElem.setAttribute("id", "_rc_sig");
msgBody.appendChild(sigElem);
}
if (this.env.signatures[id]['is_html'])
{
sigElem.innerHTML = this.env.signatures[id]['text'];
}
else
{
sigElem.innerHTML = '<pre>' + this.env.signatures[id]['text'] + '</pre>';
}
}
}
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;
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='+urlencode(name));
return true;
};
// send remote request to add a new contact
this.add_contact = function(value)
{
if (value)
- this.http_request('addcontact', '_address='+value);
+ this.http_post('addcontact', '_address='+value);
return true;
};
- // send remote request to search mail
- this.qsearch = function(value, mbox)
+ // send remote request to search mail or contacts
+ this.qsearch = function(value)
{
- if (value && mbox)
+ if (value != '')
{
- this.message_list.clear();
+ if (this.message_list)
+ this.message_list.clear();
+ else if (this.contact_list) {
+ this.contact_list.clear(true);
+ this.show_contentframe(false);
+ }
+
+ // reset vars
+ this.env.current_page = 1;
this.set_busy(true, 'searching');
- this.http_request('search', '_search='+value+'&_mbox='+mbox, true);
+ this.http_request('search', '_q='+urlencode(value)+(this.env.mailbox ? '&_mbox='+this.env.mailbox : '')+(this.env.source ? '&_source='+urlencode(this.env.source) : ''), 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);
var highlight;
var key = rcube_event.get_keycode(e);
var mod = rcube_event.get_modifier(e);
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');
this.set_classname(highlight, 'selected', false);
}
if (next)
{
next.setAttribute('id', 'rcmksearchSelected');
this.set_classname(next, 'selected', true);
this.ksearch_selected = next._rcm_id;
}
return rcube_event.cancel(e);
case 9: // tab
if(mod == SHIFT_KEY)
break;
case 13: // enter
if (this.ksearch_selected===null || !this.ksearch_input || !this.ksearch_value)
break;
// insert selected address and hide ksearch pane
this.insert_recipient(this.ksearch_selected);
this.ksearch_hide();
return rcube_event.cancel(e);
case 27: // escape
this.ksearch_hide();
break;
}
// start timer
this.ksearch_timer = setTimeout(function(){ ref.ksearch_get_results(); }, 200);
this.ksearch_input = obj;
return true;
};
this.insert_recipient = function(id)
{
if (!this.env.contacts[id] || !this.ksearch_input)
return;
// 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[id]+', ';
this.ksearch_input.value = pre + insert + end;
// set caret to insert pos
cpos = p+insert.length;
if (this.ksearch_input.setSelectionRange)
this.ksearch_input.setSelectionRange(cpos, cpos);
};
// 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(/</, '&lt;').replace(/>/, '&gt;');
li.onmousedown = function(e){ ref.insert_recipient(this._rcm_id); ref.ksearch_pane.show(0); return rcube_event.cancel(e); };
li.style.cursor = 'pointer';
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];
}
// 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.contactlist_keypress = function(list)
{
if (list.key_pressed == list.DELETE_KEY)
this.command('delete');
};
this.contactlist_select = function(list)
{
- var id, frame;
+ if (this.preview_timer)
+ clearTimeout(this.preview_timer);
+
+ var id, frame, ref = this;
if (id = list.get_single_selection())
- this.load_contact(id, 'show');
- else if (frame = document.getElementById(this.env.contentframe))
- frame.style.visibility = 'hidden';
+ this.preview_timer = setTimeout(function(){ ref.load_contact(id, 'show'); }, this.dblclick_time + 10);
+ else if (this.env.contentframe)
+ this.show_contentframe(false);
this.enable_command('edit', id?true:false);
+ this.enable_command('compose', list.selection.length > 0);
+ this.enable_command('delete', list.selection.length && this.env.address_sources && !this.env.address_sources[this.env.source].readonly);
- if (list.selection.length)
- this.enable_command('delete', 'compose', true);
-
- return false;
+ return false;
};
- this.list_contacts = function(page)
+ this.list_contacts = function(src, page)
{
var add_url = '';
var target = window;
- if (page && this.current_page==page)
+ if (!src)
+ src = this.env.source;
+
+ if (page && this.current_page==page && src == this.env.source)
return false;
+
+ if (src != this.env.source)
+ {
+ page = 1;
+ this.env.current_page = page;
+ }
+
+ this.select_folder(src, this.env.source);
+ this.env.source = src;
// load contacts remotely
if (this.gui_objects.contactslist)
{
- this.list_contacts_remote(page);
+ this.list_contacts_remote(src, page);
return;
}
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe])
{
target = window.frames[this.env.contentframe];
add_url = '&_framed=1';
}
+ // also send search request to get the correct listing
+ if (this.env.search_request)
+ add_url += '&_search='+this.env.search_request;
+
this.set_busy(true, 'loading');
- target.location.href = this.env.comm_path+(page ? '&_page='+page : '')+add_url;
+ target.location.href = this.env.comm_path+(src ? '&_source='+urlencode(src) : '')+(page ? '&_page='+page : '')+add_url;
};
// send remote request to load contacts list
- this.list_contacts_remote = function(page)
+ this.list_contacts_remote = function(src, page)
{
// clear message list first
- this.contact_list.clear();
+ this.contact_list.clear(true);
+ this.show_contentframe(false);
+ this.enable_command('delete', 'compose', false);
// send request to server
- var url = page ? '&_page='+page : '';
+ var url = (src ? '&_source='+urlencode(src) : '') + (page ? '&_page='+page : '');
+ this.env.source = src;
+
+ // also send search request to get the right messages
+ if (this.env.search_request)
+ url += '&_search='+this.env.search_request;
+
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';
+ this.show_contentframe(true);
}
else if (framed)
return false;
-
- if (action && (cid || action=='add'))
+
+ if (action && (cid || action=='add') && !this.drag_active)
{
this.set_busy(true);
- target.location.href = this.env.comm_path+'&_action='+action+'&_cid='+cid+add_url;
+ target.location.href = this.env.comm_path+'&_action='+action+'&_source='+urlencode(this.env.source)+'&_cid='+urlencode(cid) + add_url;
}
return true;
};
+ // copy a contact to the specified target (group or directory)
+ this.copy_contact = function(cid, to)
+ {
+ if (!cid)
+ cid = this.contact_list.get_selection().join(',');
+
+ if (to != this.env.source && cid && this.env.address_sources[to] && !this.env.address_sources[to].readonly)
+ this.http_post('copy', '_cid='+urlencode(cid)+'&_source='+urlencode(this.env.source)+'&_to='+urlencode(to));
+ };
+
this.delete_contacts = function()
{
// exit if no mailbox specified or if selection is empty
var selection = this.contact_list.get_selection();
if (!(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<selection.length; n++)
{
id = selection[n];
a_cids[a_cids.length] = id;
this.contact_list.remove_row(id);
}
// hide content frame if we delete the currently displayed contact
- if (selection.length==1 && this.env.contentframe)
- {
- var elm = document.getElementById(this.env.contentframe);
- elm.style.visibility = 'hidden';
- }
+ if (selection.length == 1)
+ this.show_contentframe(false);
}
// send request to server
- this.http_request('delete', '_cid='+a_cids.join(',')+'&_from='+(this.env.action ? this.env.action : ''));
+ this.http_request('delete', '_cid='+urlencode(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)
{
var row;
if (this.contact_list.rows[cid] && (row = this.contact_list.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;
}
return false;
};
- // load ldap search form
- // deprecated
- 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 *********/
/*********************************************************/
this.identity_select = function(list)
{
var id;
if (id = list.get_single_selection())
this.load_identity(id, 'edit-identity');
};
// 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
var selection = this.identity_list.get_selection();
if (!(selection.length || this.env.iid))
return;
if (!id)
id = this.env.iid ? this.env.iid : 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.goto_url('delete-identity', '_iid='+id, true);
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='+urlencode(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='+urlencode(oldname)+'&_folder_newname='+urlencode(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][1];
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 && this.env.subscriptionrows[this.edit_folder])
cell.innerHTML = this.env.subscriptionrows[this.edit_folder][1];
this.edit_folder = null;
};
// handler for keyboard events on the input field
this.name_input_keypress = function(e)
{
var key = rcube_event.get_keycode(e);
// 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='+urlencode(this.env.subscriptionrows[this.edit_folder][0])+'&_folder_newname='+urlencode(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='+urlencode(folder));
};
// add a new folder to the subscription list by cloning a folder row
this.add_folder_row = function(name, display_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
this.goto_url('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, display_name];
// set folder name
row.cells[0].innerHTML = display_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 = '';
}
this.sort_subscription_list();
};
// replace an existing table row with a new folder line
this.replace_folder_row = function(oldfolder, newfolder, display_name)
{
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, display_name, 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 = display_name;
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='+urlencode(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='+urlencode(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='+urlencode(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] && this.env.subscriptionrows[id][0] == 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;
};
// sort subscription folder list
this.sort_subscription_list = function()
{
var index = new Array();
var tbody = this.gui_objects.subscriptionlist.tBodies[0];
var swapped = false;
for (var i = 0; i<(tbody.childNodes.length-1); i++)
if (this.env.subscriptionrows[tbody.childNodes[i].id]!=null)
index.push(i);
for (i = 0; i<(index.length-1); i++)
{
if (this.env.subscriptionrows[tbody.childNodes[index[i]].id][0]>
this.env.subscriptionrows[tbody.childNodes[index[i+1]].id][0])
{
var swap = tbody.replaceChild(tbody.childNodes[index[i]], tbody.childNodes[index[i+1]]);
if (typeof(tbody.childNodes[index[i]]) != 'undefined')
tbody.insertBefore(swap, tbody.childNodes[index[i]])
else
tbody.appendChild(swap);
swapped = true;
}
}
if (swapped)
this.sort_subscription_list();
};
/*********************************************************/
/********* 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('lastpage', (this.env.pagecount > this.env.current_page));
this.enable_command('previouspage', (this.env.current_page > 1));
this.enable_command('firstpage', (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)
{
+ // pass command to parent window
+ if (this.env.framed && parent.rcmail )
+ return parent.rcmail.display_message(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(function(){ 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)
+ this.select_folder = function(name, old)
+ {
+ if (this.gui_objects.folderlist)
{
- 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);
+ var current_li, target_li;
- if (current_li)
- {
+ if ((current_li = this.get_folder_li(old)))
+ {
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)
+ if ((target_li = this.get_folder_li(name)))
{
- 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.set_classname(target_li, 'unfocused', false);
+ this.set_classname(target_li, 'selected', true);
}
-
- this.env.mailbox = mbox;
- };
+ }
+ };
+
+ // helper method to find a folder list item
+ this.get_folder_li = function(name)
+ {
+ if (this.gui_objects.folderlist)
+ {
+ name = String(name).replace(this.identifier_expr, '');
+ return document.getElementById('rcmli'+name);
+ }
+
+ return null;
+ };
// 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.message_list)
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.message_list.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);
this.message_list.insert_row(row, attop);
};
// 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()
- {
- if (this.gui_objects.quotadisplay &&
- this.gui_objects.quotadisplay.attributes.getNamedItem('display') &&
- this.gui_objects.quotadisplay.attributes.getNamedItem('id'))
- this.http_request('quotadisplay', '_display='+
- this.gui_objects.quotadisplay.attributes.getNamedItem('display').nodeValue+
- '&_id='+this.gui_objects.quotadisplay.attributes.getNamedItem('id').nodeValue, false);
+ this.set_quota = function()
+ {
+ if (this.gui_objects.quotadisplay &&
+ this.gui_objects.quotadisplay.attributes.getNamedItem('display') &&
+ this.gui_objects.quotadisplay.attributes.getNamedItem('id'))
+ this.http_request('quotadisplay', '_display='+
+ this.gui_objects.quotadisplay.attributes.getNamedItem('display').nodeValue+
+ '&_id='+this.gui_objects.quotadisplay.attributes.getNamedItem('id').nodeValue, false);
};
// 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, '');
+ var item = this.get_folder_li(mbox);
+ mbox = String(mbox).toLowerCase().replace(this.identifier_expr, '');
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, select)
{
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.contact_list.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);
}
this.contact_list.insert_row(row);
};
this.toggle_editor = function(checkbox, textElementName)
{
var ischecked = checkbox.checked;
if (ischecked)
{
tinyMCE.execCommand('mceAddControl', true, textElementName);
}
else
{
tinyMCE.execCommand('mceRemoveControl', true, textElementName);
}
};
/********************************************************/
/********* remote request methods *********/
/********************************************************/
+ this.redirect = function(url)
+ {
+ this.set_busy(true);
+ if (this.env.framed && window.parent)
+ parent.location.href = url;
+ else
+ location.href = url;
+ };
this.goto_url = function(action, query, lock)
{
if (lock)
this.set_busy(true);
var querystring = query ? '&'+query : '';
- location.href = this.env.comm_path+'&_action='+action+querystring;
+ this.redirect(this.env.comm_path+'&_action='+action+querystring);
};
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 += (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='+urlencode(action)+'&'+querystring);
- console('HTTP request: '+this.env.comm_path+'&_action='+action+'&'+querystring);
+ console.log('HTTP request: '+this.env.comm_path+'&_action='+action+'&'+querystring);
if (lock)
this.set_busy(true);
+ var rcm = this;
request_obj.__lock = lock ? true : false;
request_obj.__action = action;
request_obj.onerror = function(o){ ref.http_error(o); };
request_obj.oncomplete = function(o){ ref.http_response(o); };
request_obj.GET(this.env.comm_path+'&_action='+action+'&'+querystring);
}
};
+ // send a http POST request to the server
+ this.http_post = function(action, postdata, lock)
+ {
+ var request_obj;
+ if (postdata && typeof(postdata) == 'object')
+ postdata._remote = 1;
+ else
+ postdata += (postdata ? '&' : '') + '_remote=1';
+
+ // send request
+ if (request_obj = this.get_request_obj())
+ {
+ console.log('HTTP POST: '+this.env.comm_path+'&_action='+action);
+
+ if (lock)
+ this.set_busy(true);
+
+ var rcm = this;
+ request_obj.__lock = lock ? true : false;
+ request_obj.__action = action;
+ request_obj.onerror = function(o){ rcm.http_error(o); };
+ request_obj.oncomplete = function(o){ rcm.http_response(o); };
+ request_obj.POST(this.env.comm_path+'&_action='+action, postdata);
+ }
+ };
// 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());
+ console.log(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');
else if (this.message_list)
this.message_list.init();
break;
case 'list':
if (this.env.messagecount)
this.enable_command('purge', (this.env.mailbox==this.env.trash_mailbox || this.env.mailbox==this.env.junk_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.message_list ? this.message_list.get_single_selection() : null);
};
// same as above but for contacts
this.get_single_cid = function()
{
return this.env.cid ? this.env.cid : (this.contact_list ? this.contact_list.get_single_selection() : null);
};
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 sending HTTP requests
* @constructor
*/
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");
+ {
+ try { this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
+ catch(e) { this.xmlhttp = null; }
+ }
else
{
}
}
// send 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, body, contentType)
{
// default value for contentType if not provided
- contentType = typeof(contentType) != 'undefined' ?
- contentType : 'application/x-www-form-urlencoded';
+ if (typeof(contentType) == 'undefined')
+ contentType = 'application/x-www-form-urlencoded';
this.build();
if (!this.xmlhttp)
{
this.onerror(this);
return false;
}
+
+ var req_body = body;
+ if (typeof(body) == 'object')
+ {
+ req_body = '';
+ for (var p in body)
+ req_body += (req_body ? '&' : '') + p+'='+urlencode(body[p]);
+ }
- var ref=this;
+ var ref = this;
this.url = url;
this.busy = true;
this.xmlhttp.onreadystatechange = function() { ref.xmlhttp_onreadystatechange(); };
this.xmlhttp.open('POST', url, true);
this.xmlhttp.setRequestHeader('Content-Type', contentType);
- this.xmlhttp.send(body);
+ this.xmlhttp.send(req_body);
};
// 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
// helper function to call the init method with a delay
function call_init(o)
{
if (window[o] && window[o].init)
setTimeout(o+'.init()', 200);
}
-function console(str)
- {
- if (document.debugform && document.debugform.console)
- document.debugform.console.value += str+'\n--------------------------------------\n';
- }
-
diff --git a/program/js/common.js b/program/js/common.js
index be9a131c2..d9216a58d 100644
--- a/program/js/common.js
+++ b/program/js/common.js
@@ -1,605 +1,626 @@
/*
+-----------------------------------------------------------------------+
| RoundCube common js library |
| |
| This file is part of the RoundCube web development suite |
| Copyright (C) 2005-2006, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
// Constants
var CONTROL_KEY = 1;
var SHIFT_KEY = 2;
var CONTROL_SHIFT_KEY = 3;
/**
* Default browser check class
* @construcotr
*/
function roundcube_browser()
{
this.ver = parseFloat(navigator.appVersion);
this.appver = navigator.appVersion;
this.agent = navigator.userAgent;
this.name = navigator.appName;
this.vendor = navigator.vendor ? navigator.vendor : '';
this.vendver = navigator.vendorSub ? parseFloat(navigator.vendorSub) : 0;
this.product = navigator.product ? navigator.product : '';
this.platform = String(navigator.platform).toLowerCase();
this.lang = (navigator.language) ? navigator.language.substring(0,2) :
(navigator.browserLanguage) ? navigator.browserLanguage.substring(0,2) :
(navigator.systemLanguage) ? navigator.systemLanguage.substring(0,2) : 'en';
this.win = (this.platform.indexOf('win')>=0) ? true : false;
this.mac = (this.platform.indexOf('mac')>=0) ? true : false;
this.linux = (this.platform.indexOf('linux')>=0) ? true : false;
this.unix = (this.platform.indexOf('unix')>=0) ? true : false;
this.dom = document.getElementById ? true : false;
this.dom2 = (document.addEventListener && document.removeEventListener);
this.ie = (document.all) ? true : false;
this.ie4 = (this.ie && !this.dom);
this.ie5 = (this.dom && this.appver.indexOf('MSIE 5')>0);
this.ie6 = (this.dom && this.appver.indexOf('MSIE 6')>0);
this.mz = (this.dom && this.ver>=5); // (this.dom && this.product=='Gecko')
this.ns = ((this.ver<5 && this.name=='Netscape') || (this.ver>=5 && this.vendor.indexOf('Netscape')>=0));
this.ns4 = (this.ns && parseInt(this.ver)==4);
this.ns6 = (this.ns && parseInt(this.vendver)==6); // (this.mz && this.ns) ? true : false;
this.ns7 = (this.ns && parseInt(this.vendver)==7); // this.agent.indexOf('Netscape/7')>0);
this.safari = (this.agent.toLowerCase().indexOf('safari')>0 || this.agent.toLowerCase().indexOf('applewebkit')>0);
this.konq = (this.agent.toLowerCase().indexOf('konqueror')>0);
this.opera = (window.opera) ? true : false;
this.opera5 = (this.opera5 && this.agent.indexOf('Opera 5')>0) ? true : false;
this.opera6 = (this.opera && this.agent.indexOf('Opera 6')>0) ? true : false;
this.opera7 = (this.opera && this.agent.indexOf('Opera 7')>0) ? true : false;
if(this.opera && window.RegExp)
this.vendver = (/opera(\s|\/)([0-9\.]+)/i.test(navigator.userAgent)) ? parseFloat(RegExp.$2) : -1;
else if(!this.vendver && this.safari)
this.vendver = (/(safari|applewebkit)\/([0-9]+)/i.test(this.agent)) ? parseInt(RegExp.$2) : 0;
else if((!this.vendver && this.mz) || this.agent.indexOf('Camino')>0)
this.vendver = (/rv:([0-9\.]+)/.test(this.agent)) ? parseFloat(RegExp.$1) : 0;
else if(this.ie && window.RegExp)
this.vendver = (/msie\s+([0-9\.]+)/i.test(this.agent)) ? parseFloat(RegExp.$1) : 0;
else if(this.konq && window.RegExp)
this.vendver = (/khtml\/([0-9\.]+)/i.test(this.agent)) ? parseFloat(RegExp.$1) : 0;
// get real language out of safari's user agent
if(this.safari && (/;\s+([a-z]{2})-[a-z]{2}\)/i.test(this.agent)))
this.lang = RegExp.$1;
this.dhtml = ((this.ie4 && this.win) || this.ie5 || this.ie6 || this.ns4 || this.mz);
this.layers = this.ns4; // (document.layers);
this.div = (this.ie4 || this.dom);
this.vml = (this.win && this.ie && this.dom && !this.opera);
this.linkborder = (this.ie || this.mz);
this.rollover = (this.ver>=4 || (this.ns && this.ver>=3)); // (document.images) ? true : false;
this.pngalpha = (this.mz || (this.opera && this.vendver>=6) || (this.ie && this.mac && this.vendver>=5) ||
(this.ie && this.win && this.vendver>=5.5) || this.safari);
this.opacity = (this.mz || (this.ie && this.vendver>=5.5 && !this.opera) || (this.safari && this.vendver>=100));
this.cookies = navigator.cookieEnabled;
// test for XMLHTTP support
this.xmlhttp_test = function()
{
var activeX_test = new Function("try{var o=new ActiveXObject('Microsoft.XMLHTTP');return true;}catch(err){return false;}");
this.xmlhttp = (window.XMLHttpRequest || (window.ActiveXObject && activeX_test())) ? true : false;
return this.xmlhttp;
}
}
// static functions for event handling
var rcube_event = {
/**
* returns the event key code
*/
get_keycode: function(e)
{
e = e || window.event;
return e && e.keyCode ? e.keyCode : (e && e.which ? e.which : 0);
},
/**
* returns modifier key (constants defined at top of file)
*/
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;
}
},
/**
* Return absolute mouse position of an event
*/
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 };
},
/**
* Add an object method as event listener to a certain element
*/
add_listener: function(p)
{
if (!p.object || !p.method) // not enough arguments
return;
if (!p.element)
p.element = document;
if (!p.object._rc_events)
p.object._rc_events = [];
var key = p.event + '*' + p.method;
if (!p.object._rc_events[key])
p.object._rc_events[key] = function(e){ return p.object[p.method](e); };
if (p.element.addEventListener)
p.element.addEventListener(p.event, p.object._rc_events[key], false);
else if (p.element.attachEvent)
p.element.attachEvent('on'+p.event, p.object._rc_events[key]);
else
p.element['on'+p.event] = p.object._rc_events[key];
},
/**
* Remove event listener
*/
remove_listener: function(p)
{
if (!p.element)
p.element = document;
var key = p.event + '*' + p.method;
if (p.object && p.object._rc_events && p.object._rc_events[key]) {
if (p.element.removeEventListener)
p.element.removeEventListener(p.event, p.object._rc_events[key], false);
else if (p.element.detachEvent)
p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
else
p.element['on'+p.event] = null;
}
},
/**
* Prevent event propagation and bubbeling
*/
cancel: function(evt)
{
var e = evt ? evt : window.event;
if (e.preventDefault)
e.preventDefault();
if (e.stopPropagation)
e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
}
};
var rcube_layer_objects = new Array();
/**
* RoundCube generic layer (floating box) class
*
* @constructor
*/
function rcube_layer(id, attributes)
{
this.name = id;
// create a new layer in the current document
this.create = function(arg)
{
var l = (arg.x) ? arg.x : 0;
var t = (arg.y) ? arg.y : 0;
var w = arg.width;
var h = arg.height;
var z = arg.zindex;
var vis = arg.vis;
var parent = arg.parent;
var obj;
obj = document.createElement('DIV');
with(obj)
{
id = this.name;
with(style)
{
position = 'absolute';
visibility = (vis) ? (vis==2) ? 'inherit' : 'visible' : 'hidden';
left = l+'px';
top = t+'px';
if(w) width = w+'px';
if(h) height = h+'px';
if(z) zIndex = z;
}
}
if(parent) parent.appendChild(obj);
else document.body.appendChild(obj);
this.elm = obj;
};
// create new layer
if(attributes!=null)
{
this.create(attributes);
this.name = this.elm.id;
}
else // just refer to the object
this.elm = document.getElementById(id);
if(!this.elm)
return false;
// ********* layer object properties *********
this.css = this.elm.style;
this.event = this.elm;
this.width = this.elm.offsetWidth;
this.height = this.elm.offsetHeight;
this.x = parseInt(this.elm.offsetLeft);
this.y = parseInt(this.elm.offsetTop);
this.visible = (this.css.visibility=='visible' || this.css.visibility=='show' || this.css.visibility=='inherit') ? true : false;
this.id = rcube_layer_objects.length;
this.obj = 'rcube_layer_objects['+this.id+']';
rcube_layer_objects[this.id] = this;
// ********* layer object methods *********
// move the layer to a specific position
this.move = function(x, y)
{
this.x = x;
this.y = y;
this.css.left = Math.round(this.x)+'px';
this.css.top = Math.round(this.y)+'px';
}
// move the layer for a specific step
this.shift = function(x,y)
{
x = Math.round(x*100)/100;
y = Math.round(y*100)/100;
this.move(this.x+x, this.y+y);
}
// change the layers width and height
this.resize = function(w,h)
{
this.css.width = w+'px';
this.css.height = h+'px';
this.width = w;
this.height = h;
}
// cut the layer (top,width,height,left)
this.clip = function(t,w,h,l)
{
this.css.clip='rect('+t+' '+w+' '+h+' '+l+')';
this.clip_height = h;
this.clip_width = w;
}
// show or hide the layer
this.show = function(a)
{
if(a==1)
{
this.css.visibility = 'visible';
this.visible = true;
}
else if(a==2)
{
this.css.visibility = 'inherit';
this.visible = true;
}
else
{
this.css.visibility = 'hidden';
this.visible = false;
}
}
// write new content into a Layer
this.write = function(cont)
{
this.elm.innerHTML = cont;
}
// set the given color to the layer background
this.set_bgcolor = function(c)
{
if(!c || c=='#')
c = 'transparent';
this.css.backgroundColor = c;
}
// set the opacity of a layer to the given ammount (in %)
this.set_opacity = function(v)
{
if(!bw.opacity)
return;
var op = v<=1 ? Math.round(v*100) : parseInt(v);
if(bw.ie)
this.css.filter = 'alpha(opacity:'+op+')';
else if(bw.safari)
{
this.css.opacity = op/100;
this.css.KhtmlOpacity = op/100;
}
else if(bw.mz)
this.css.MozOpacity = op/100;
}
}
// check if input is a valid email address
// By Cal Henderson <cal@iamcal.com>
// http://code.iamcal.com/php/rfc822/
function rcube_check_email(input, inline)
{
if (input && window.RegExp)
{
var no_ws_ctl = "[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]";
var alpha = "[\\x41-\\x5a\\x61-\\x7a]";
var digit = "[\\x30-\\x39]";
var cr = "\\x0d";
var lf = "\\x0a";
var crlf = "(" + cr + lf + ")";
var obs_char = "[\\x00-\\x09\\x0b\\x0c\\x0e-\\x7f]";
var obs_text = "("+lf+"*"+cr+"*("+obs_char+lf+"*"+cr+"*)*)";
var text = "([\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f]|"+obs_text+")";
var obs_qp = "(\\x5c[\\x00-\\x7f])";
var quoted_pair = "(\\x5c"+text+"|"+obs_qp+")";
var wsp = "[\\x20\\x09]";
var obs_fws = "("+wsp+"+("+crlf+wsp+"+)*)";
var fws = "((("+wsp+"*"+crlf+")?"+wsp+"+)|"+obs_fws+")";
var ctext = "("+no_ws_ctl+"|[\\x21-\\x27\\x2A-\\x5b\\x5d-\\x7e])";
var ccontent = "("+ctext+"|"+quoted_pair+")";
var comment = "(\\x28("+fws+"?"+ccontent+")*"+fws+"?\\x29)";
var cfws = "(("+fws+"?"+comment+")*("+fws+"?"+comment+"|"+fws+"))";
var cfws = fws+"*";
var atext = "("+alpha+"|"+digit+"|[\\x21\\x23-\\x27\\x2a\\x2b\\x2d\\x2e\\x3d\\x3f\\x5e\\x5f\\x60\\x7b-\\x7e])";
var atom = "("+cfws+"?"+atext+"+"+cfws+"?)";
var qtext = "("+no_ws_ctl+"|[\\x21\\x23-\\x5b\\x5d-\\x7e])";
var qcontent = "("+qtext+"|"+quoted_pair+")";
var quoted_string = "("+cfws+"?\\x22("+fws+"?"+qcontent+")*"+fws+"?\\x22"+cfws+"?)";
var word = "("+atom+"|"+quoted_string+")";
var obs_local_part = "("+word+"(\\x2e"+word+")*)";
var obs_domain = "("+atom+"(\\x2e"+atom+")*)";
var dot_atom_text = "("+atext+"+(\\x2e"+atext+"+)*)";
var dot_atom = "("+cfws+"?"+dot_atom_text+cfws+"?)";
var dtext = "("+no_ws_ctl+"|[\\x21-\\x5a\\x5e-\\x7e])";
var dcontent = "("+dtext+"|"+quoted_pair+")";
var domain_literal = "("+cfws+"?\\x5b("+fws+"?"+dcontent+")*"+fws+"?\\x5d"+cfws+"?)";
var local_part = "("+dot_atom+"|"+quoted_string+"|"+obs_local_part+")";
var domain = "("+dot_atom+"|"+domain_literal+"|"+obs_domain+")";
var addr_spec = "("+local_part+"\\x40"+domain+")";
var reg1 = inline ? new RegExp(addr_spec, 'i') : new RegExp('^'+addr_spec+'$', 'i');
return reg1.test(input) ? true : false;
}
return false;
}
// find a value in a specific array and returns the index
function find_in_array()
{
var args = find_in_array.arguments;
if(!args.length) return -1;
var haystack = typeof(args[0])=='object' ? args[0] : args.length>1 && typeof(args[1])=='object' ? args[1] : new Array();
var needle = typeof(args[0])!='object' ? args[0] : args.length>1 && typeof(args[1])!='object' ? args[1] : '';
var nocase = args.length==3 ? args[2] : false;
if(!haystack.length) return -1;
for(var i=0; i<haystack.length; i++)
if(nocase && haystack[i].toLowerCase()==needle.toLowerCase())
return i;
else if(haystack[i]==needle)
return i;
return -1;
}
// make a string URL safe
function urlencode(str)
{
return window.encodeURIComponent ? encodeURIComponent(str) : escape(str);
}
// get any type of html objects by id/name
function rcube_find_object(id, d)
{
var n, f, obj, e;
if(!d) d = document;
if(d.getElementsByName && (e = d.getElementsByName(id)))
obj = e[0];
if(!obj && d.getElementById)
obj = d.getElementById(id);
if(!obj && d.all)
obj = d.all[id];
if(!obj && d.images.length)
obj = d.images[id];
if(!obj && d.forms.length)
for(f=0; f<d.forms.length; f++)
{
if(d.forms[f].name == id)
obj = d.forms[f];
else if(d.forms[f].elements[id])
obj = d.forms[f].elements[id];
}
if(!obj && d.layers)
{
if(d.layers[id]) obj = d.layers[id];
for(n=0; !obj && n<d.layers.length; n++)
obj = rcube_find_object(id, d.layers[n].document);
}
return obj;
}
// return the absolute position of an object within the document
function rcube_get_object_pos(obj)
{
if(typeof(obj)=='string')
obj = rcube_find_object(obj);
if(!obj) return {x:0, y:0};
var iX = (bw.layers) ? obj.x : obj.offsetLeft;
var iY = (bw.layers) ? obj.y : obj.offsetTop;
if(bw.ie || bw.mz)
{
var elm = obj.offsetParent;
while(elm && elm!=null)
{
iX += elm.offsetLeft;
iY += elm.offsetTop;
elm = elm.offsetParent;
}
}
//if(bw.mac && bw.ie5) iX += document.body.leftMargin;
//if(bw.mac && bw.ie5) iY += document.body.topMargin;
return {x:iX, y:iY};
}
/**
* Return the currently applied value of a css property
*
* @param {Object} html_element Node reference
* @param {String} css_property Property name to read in Javascript notation (eg. 'textAlign')
* @param {String} mozilla_equivalent Equivalent property name in CSS notation (eg. 'text-align')
* @return CSS property value
* @type String
*/
function get_elements_computed_style(html_element, css_property, mozilla_equivalent)
{
if (arguments.length==2)
mozilla_equivalent = css_property;
var el = html_element;
if (typeof(html_element)=='string')
el = rcube_find_object(html_element);
if (el && el.currentStyle)
return el.currentStyle[css_property];
else if (el && document.defaultView && document.defaultView.getComputedStyle)
return document.defaultView.getComputedStyle(el, null).getPropertyValue(mozilla_equivalent);
else
return false;
}
// cookie functions by GoogieSpell
function setCookie(name, value, expires, path, domain, secure)
{
var curCookie = name + "=" + escape(value) +
(expires ? "; expires=" + expires.toGMTString() : "") +
(path ? "; path=" + path : "") +
(domain ? "; domain=" + domain : "") +
(secure ? "; secure" : "");
document.cookie = curCookie;
}
roundcube_browser.prototype.set_cookie = setCookie;
function getCookie(name)
{
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1)
{
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1)
end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}
roundcube_browser.prototype.get_cookie = getCookie;
+// tiny replacement for Firebox functionality
+function rcube_console()
+{
+ this.box = rcube_find_object('console');
+
+ this.log = function(msg)
+ {
+ if (this.box)
+ this.box.value += str+'\n--------------------------------------\n';
+ };
+
+ this.reset = function()
+ {
+ if (this.box)
+ this.box.value = '';
+ };
+}
+
var bw = new roundcube_browser();
+
+if (!window.console)
+ console = new rcube_console();
diff --git a/program/js/editor.js b/program/js/editor.js
index 590388ccf..536ad2ada 100644
--- a/program/js/editor.js
+++ b/program/js/editor.js
@@ -1,148 +1,148 @@
/*
+-----------------------------------------------------------------------+
| RoundCube editor js library |
| |
| This file is part of the RoundCube web development suite |
| Copyright (C) 2006, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Eric Stadtherr <estadtherr@gmail.com> |
+-----------------------------------------------------------------------+
$Id: editor.js 000 2006-05-18 19:12:28Z roundcube $
*/
// Initialize the message editor
function rcmail_editor_init(skin_path)
{
tinyMCE.init({ mode : 'specific_textareas',
accessibility_focus : false,
apply_source_formatting : true,
theme : 'advanced',
plugins : 'emotions,media,nonbreaking,table,searchreplace,spellchecker,visualchars',
theme_advanced_buttons1 : 'bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,outdent,indent,separator,forecolor,backcolor,formatselect,fontselect,fontsizeselect',
theme_advanced_buttons2 : 'undo,redo,image,media,hr,link,unlink,emotions,charmap,code,nonbreaking,visualchars,separator,search,replace,spellchecker,separator,tablecontrols',
theme_advanced_buttons3 : '',
theme_advanced_toolbar_location : 'top',
theme_advanced_toolbar_align : 'left',
extended_valid_elements : 'font[face|size|color|style],span[id|class|align|style]',
content_css : skin_path + '/editor_content.css',
popups_css : skin_path + '/editor_popup.css',
editor_css : skin_path + '/editor_ui.css'
});
}
// Set the state of the HTML/Plain toggles based on the _is_html field value
function rcmail_set_editor_toggle_states()
{
// set the editor toggle based on the state of the editor
var htmlFlag = document.getElementsByName('_is_html')[0];
var toggles = document.getElementsByName('_editorSelect');
for(var t=0; t<toggles.length; t++)
{
if (toggles[t].value == 'html')
{
toggles[t].checked = (htmlFlag.value == "1");
}
else
{
toggles[t].checked = (htmlFlag.value == "0");
}
}
}
// Toggle between the HTML and Plain Text editors
function rcmail_toggle_editor(toggler)
{
var selectedEditor = toggler.value;
// determine the currently displayed editor
var htmlFlag = document.getElementsByName('_is_html')[0];
var currentEditor = htmlFlag.value;
if (selectedEditor == currentEditor)
{
return;
}
// do the appropriate conversion
var composeElement = document.getElementById('compose-body');
if (selectedEditor == 'html')
{
var existingPlainText = composeElement.value;
var htmlText = "<pre>" + existingPlainText + "</pre>";
composeElement.value = htmlText;
tinyMCE.execCommand('mceAddControl', true, '_message');
htmlFlag.value = "1";
}
else
{
rcmail.set_busy(true, 'converting');
var thisMCE = tinyMCE.getInstanceById('_message');
var existingHtml = tinyMCE.getContent();
rcmail_html2plain(existingHtml);
tinyMCE.execCommand('mceRemoveControl', true, '_message');
htmlFlag.value = "0";
}
}
function rcmail_html2plain(htmlText)
{
var http_request = new rcube_http_request();
http_request.onerror = function(o) { rcmail_handle_toggle_error(o); };
http_request.oncomplete = function(o) { rcmail_set_text_value(o); };
- var url=rcmail.env.comm_path+'&_action=html2text';
- console('HTTP request: ' + url);
+ var url = rcmail.env.bin_path+'html2text.php';
+ console.log('HTTP request: ' + url);
http_request.POST(url, htmlText, 'application/octet-stream');
}
/*
function old_html2Plain(htmlText)
{
var http_request = false;
if (window.XMLHttpRequest)
{
http_request = new XMLHttpRequest();
//http_request.overrideMimeType('text/plain');
}
if (http_request)
{
rcmail.set_busy(true);
http_request.onreadystatechange = function()
{ setTextValue(http_request); };
//var url = window.location.protocol + '://' +
//window.location.host + window.location.pathname +
//'conv_html.php';
var url = 'conv_html.php';
//alert('calling ' + url);
var reqbody = 'htmlText=' + htmlText;
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.send(reqbody);
}
}
*/
function rcmail_set_text_value(httpRequest)
{
rcmail.set_busy(false);
var composeElement = document.getElementById('compose-body');
composeElement.value = httpRequest.get_text();
}
function rcmail_handle_toggle_error(httpRequest)
{
alert('html2text request returned with error ' + httpRequest.xmlhttp.status);
}
diff --git a/program/js/list.js b/program/js/list.js
index 0797295ee..719585893 100644
--- a/program/js/list.js
+++ b/program/js/list.js
@@ -1,708 +1,710 @@
/*
+-----------------------------------------------------------------------+
| RoundCube List Widget |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2006, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Authors: Thomas Bruederli <roundcube@gmail.com> |
| Charles McNulty <charles@charlesmcnulty.com> |
+-----------------------------------------------------------------------+
| Requires: common.js |
+-----------------------------------------------------------------------+
$Id: list.js 344 2006-09-18 03:49:28Z thomasb $
*/
/**
* RoundCube List Widget class
* @contructor
*/
function rcube_list_widget(list, p)
{
// static contants
this.ENTER_KEY = 13;
this.DELETE_KEY = 46;
this.list = list ? list : null;
this.frame = null;
this.rows = [];
this.selection = [];
this.shiftkey = false;
this.multiselect = false;
this.draggable = false;
this.keyboard = false;
this.dont_select = false;
this.drag_active = false;
this.last_selected = 0;
this.in_selection_before = false;
this.focused = false;
this.drag_mouse_start = null;
this.dblclick_time = 600;
this.row_init = function(){};
this.events = { click:[], dblclick:[], select:[], keypress:[], dragstart:[], dragend:[] };
// overwrite default paramaters
if (p && typeof(p)=='object')
for (var n in p)
this[n] = p[n];
}
rcube_list_widget.prototype = {
/**
* get all message rows from HTML table and init each row
*/
init: function()
{
if (this.list && this.list.tBodies[0])
{
this.rows = new Array();
var row;
for(var r=0; r<this.list.tBodies[0].childNodes.length; r++)
{
row = this.list.tBodies[0].childNodes[r];
while (row && (row.nodeType != 1 || row.style.display == 'none'))
{
row = row.nextSibling;
r++;
}
this.init_row(row);
}
this.frame = this.list.parentNode;
// set body events
if (this.keyboard)
rcube_event.add_listener({element:document, event:'keydown', object:this, method:'key_press'});
}
},
/**
*
*/
init_row: function(row)
{
// make references in internal array and set event handlers
- if (row && String(row.id).match(/rcmrow([0-9]+)/))
+ if (row && String(row.id).match(/rcmrow([a-z0-9\-_=]+)/i))
{
var p = this;
var uid = RegExp.$1;
row.uid = uid;
this.rows[uid] = {uid:uid, id:row.id, obj:row, classname:row.className};
// set eventhandlers to table row
row.onmousedown = function(e){ return p.drag_row(e, this.uid); };
row.onmouseup = function(e){ return p.click_row(e, this.uid); };
if (document.all)
row.onselectstart = function() { return false; };
this.row_init(this.rows[uid]);
}
},
/**
*
*/
-clear: function()
+clear: function(sel)
{
var tbody = document.createElement('TBODY');
this.list.insertBefore(tbody, this.list.tBodies[0]);
this.list.removeChild(this.list.tBodies[1]);
- this.rows = new Array();
+ this.rows = new Array();
+
+ if (sel) this.clear_selection();
},
/**
* 'remove' message row from list (just hide it)
*/
remove_row: function(uid)
{
if (this.rows[uid].obj)
this.rows[uid].obj.style.display = 'none';
this.rows[uid] = null;
},
/**
*
*/
insert_row: function(row, attop)
{
var tbody = this.list.tBodies[0];
if (attop && tbody.rows.length)
tbody.insertBefore(row, tbody.firstChild);
else
tbody.appendChild(row);
this.init_row(row);
},
/**
* Set focur to the list
*/
focus: function(e)
{
this.focused = true;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
if (this.rows[id].obj)
{
this.set_classname(this.rows[id].obj, 'selected', true);
this.set_classname(this.rows[id].obj, 'unfocused', false);
}
}
if (e || (e = window.event))
rcube_event.cancel(e);
},
/**
* remove focus from the list
*/
blur: function()
{
var id;
this.focused = false;
for (var n=0; n<this.selection.length; n++)
{
id = this.selection[n];
if (this.rows[id] && this.rows[id].obj)
{
this.set_classname(this.rows[id].obj, 'selected', false);
this.set_classname(this.rows[id].obj, 'unfocused', true);
}
}
},
/**
* onmousedown-handler of message list row
*/
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)
{
var mod_key = rcube_event.get_modifier(e);
this.select_row(id, mod_key, false);
}
if (this.draggable && this.selection.length)
{
this.drag_start = true;
this.drag_mouse_start = rcube_event.get_mouse_pos(e);
rcube_event.add_listener({element:document, event:'mousemove', object:this, method:'drag_mouse_move'});
rcube_event.add_listener({element:document, event:'mouseup', object:this, method:'drag_mouse_up'});
}
return false;
},
/**
* onmouseup-handler of message list row
*/
click_row: function(e, id)
{
var now = new Date().getTime();
var mod_key = rcube_event.get_modifier(e);
// don't do anything (another action processed before)
if (this.dont_select)
{
this.dont_select = false;
return false;
}
var dblclicked = now - this.rows[id].clicked < this.dblclick_time;
// unselects currently selected row
if (!this.drag_active && this.in_selection_before == id && !dblclicked)
this.select_row(id, mod_key, false);
this.drag_start = false;
this.in_selection_before = false;
// row was double clicked
if (this.rows && dblclicked && this.in_selection(id))
this.trigger_event('dblclick');
else
this.trigger_event('click');
if (!this.drag_active)
rcube_event.cancel(e);
this.rows[id].clicked = now;
return false;
},
/**
* get next and previous rows that are not hidden
*/
get_next_row: function()
{
if (!this.rows)
return false;
var last_selected_row = this.rows[this.last_selected];
var new_row = last_selected_row ? last_selected_row.obj.nextSibling : null;
while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none'))
new_row = new_row.nextSibling;
return new_row;
},
get_prev_row: function()
{
if (!this.rows)
return false;
var last_selected_row = this.rows[this.last_selected];
var new_row = last_selected_row ? last_selected_row.obj.previousSibling : null;
while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none'))
new_row = new_row.previousSibling;
return new_row;
},
// selects or unselects the proper row depending on the modifier key pressed
select_row: function(id, mod_key, with_mouse)
{
var select_before = this.selection.join(',');
if (!this.multiselect)
mod_key = 0;
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;
}
}
// trigger event if selection changed
if (this.selection.join(',') != select_before)
this.trigger_event('select');
if (this.last_selected != 0 && this.rows[this.last_selected])
this.set_classname(this.rows[this.last_selected].obj, 'focused', false);
this.last_selected = id;
this.set_classname(this.rows[id].obj, 'focused', true);
},
/**
* Alias method for select_row
*/
select: function(id)
{
this.select_row(id, false);
this.scrollto(id);
},
/**
* Select row next to the last selected one.
* Either below or above.
*/
select_next: function()
{
var next_row = this.get_next_row();
var prev_row = this.get_prev_row();
var new_row = (next_row) ? next_row : prev_row;
if (new_row)
this.select_row(new_row.uid, false, false);
},
/**
* Perform selection when shift key is pressed
*/
shift_select: function(id, control)
{
var from_rowIndex = this.rows[this.shift_start].obj.rowIndex;
var to_rowIndex = this.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.rows)
{
if ((this.rows[n].obj.rowIndex >= i) && (this.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);
}
}
},
/**
* Check if given id is part of the current selection
*/
in_selection: function(id)
{
for(var n in this.selection)
if (this.selection[n]==id)
return true;
return false;
},
/**
* Select each row in list
*/
select_all: function(filter)
{
if (!this.rows || !this.rows.length)
return false;
// reset selection first
this.clear_selection();
for (var n in this.rows)
{
if (!filter || this.rows[n][filter]==true)
{
this.last_selected = n;
this.highlight_row(n, true);
}
}
return true;
},
/**
* Unselect all selected rows
*/
clear_selection: function()
{
for(var n=0; n<this.selection.length; n++)
if (this.rows[this.selection[n]])
{
this.set_classname(this.rows[this.selection[n]].obj, 'selected', false);
this.set_classname(this.rows[this.selection[n]].obj, 'unfocused', false);
}
this.selection = new Array();
},
/**
* Getter for the selection array
*/
get_selection: function()
{
return this.selection;
},
/**
* Return the ID if only one row is selected
*/
get_single_selection: function()
{
if (this.selection.length == 1)
return this.selection[0];
else
return null;
},
/**
* Highlight/unhighlight a row
*/
highlight_row: function(id, multiple)
{
if (this.rows[id] && !multiple)
{
this.clear_selection();
this.selection[0] = id;
this.set_classname(this.rows[id].obj, 'selected', true)
}
else if (this.rows[id])
{
if (!this.in_selection(id)) // select row
{
this.selection[this.selection.length] = id;
this.set_classname(this.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.rows[id].obj, 'selected', false);
this.set_classname(this.rows[id].obj, 'unfocused', false);
}
}
},
/**
* Handler for keyboard events
*/
key_press: function(e)
{
if (this.focused != true)
return true;
this.shiftkey = e.shiftKey;
var keyCode = document.layers ? e.which : document.all ? event.keyCode : document.getElementById ? e.keyCode : 0;
var mod_key = rcube_event.get_modifier(e);
switch (keyCode)
{
case 40:
case 38:
return this.use_arrow_key(keyCode, mod_key);
break;
default:
this.key_pressed = keyCode;
this.trigger_event('keypress');
}
return true;
},
/**
* Special handling method for arrow keys
*/
use_arrow_key: function(keyCode, mod_key)
{
var new_row;
if (keyCode == 40) // down arrow key pressed
new_row = this.get_next_row();
else if (keyCode == 38) // up arrow key pressed
new_row = this.get_prev_row();
if (new_row)
{
this.select_row(new_row.uid, mod_key, true);
this.scrollto(new_row.uid);
}
return false;
},
/**
* Try to scroll the list to make the specified row visible
*/
scrollto: function(id)
{
var row = this.rows[id].obj;
if (row && this.frame)
{
var scroll_to = Number(row.offsetTop);
if (scroll_to < Number(this.frame.scrollTop))
this.frame.scrollTop = scroll_to;
else if (scroll_to + Number(row.offsetHeight) > Number(this.frame.scrollTop) + Number(this.frame.offsetHeight))
this.frame.scrollTop = (scroll_to + Number(row.offsetHeight)) - Number(this.frame.offsetHeight);
}
},
/**
* Handler for mouse move events
*/
drag_mouse_move: function(e)
{
if (this.drag_start)
{
// check mouse movement, of less than 3 pixels, don't start dragging
var m = rcube_event.get_mouse_pos(e);
if (!this.drag_mouse_start || (Math.abs(m.x - this.drag_mouse_start.x) < 3 && Math.abs(m.y - this.drag_mouse_start.y) < 3))
return false;
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.rows[this.selection[n]].obj)
{
obj = this.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);
this.drag_active = true;
this.trigger_event('dragstart');
}
if (this.drag_active && this.draglayer)
{
var pos = rcube_event.get_mouse_pos(e);
this.draglayer.move(pos.x+20, pos.y-5);
}
this.drag_start = false;
return false;
},
/**
* Handler for mouse up events
*/
drag_mouse_up: function(e)
{
document.onmousemove = null;
if (this.draglayer && this.draglayer.visible)
this.draglayer.show(0);
this.drag_active = false;
this.trigger_event('dragend');
rcube_event.remove_listener({element:document, event:'mousemove', object:this, method:'drag_mouse_move'});
rcube_event.remove_listener({element:document, event:'mouseup', object:this, method:'drag_mouse_up'});
return rcube_event.cancel(e);
},
/**
* set/unset a specific class name
*/
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;
},
/**
* Setter for object event handlers
*
* @param {String} Event name
* @param {Function} Handler function
* @return Listener ID (used to remove this handler later on)
*/
addEventListener: function(evt, handler)
{
if (this.events[evt]) {
var handle = this.events[evt].length;
this.events[evt][handle] = handler;
return handle;
}
else
return false;
},
/**
* Removes a specific event listener
*
* @param {String} Event name
* @param {Int} Listener ID to remove
*/
removeEventListener: function(evt, handle)
{
if (this.events[evt] && this.events[evt][handle])
this.events[evt][handle] = null;
},
/**
* This will execute all registered event handlers
* @private
*/
trigger_event: function(evt)
{
if (this.events[evt] && this.events[evt].length) {
for (var i=0; i<this.events[evt].length; i++)
if (typeof(this.events[evt][i]) == 'function')
this.events[evt][i](this);
}
}
};
diff --git a/program/localization/de_CH/messages.inc b/program/localization/de_CH/messages.inc
index dab8057fe..3cf497f14 100644
--- a/program/localization/de_CH/messages.inc
+++ b/program/localization/de_CH/messages.inc
@@ -1,71 +1,73 @@
<?php
/*
+-----------------------------------------------------------------------+
| language/de_CH/messages.inc |
| |
| Language file of the RoundCube Webmail client |
| Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
@version $Id$
*/
$messages = array();
$messages['loginfailed'] = 'Login fehlgeschlagen';
$messages['cookiesdisabled'] = 'Ihr Browser akzeptiert keine Cookies';
$messages['sessionerror'] = 'Ihre Session ist ungültig oder abgelaufen';
$messages['imaperror'] = 'Keine Verbindung zum IMAP Server';
$messages['nomessagesfound'] = 'Keine Nachrichten in diesem Ordner';
$messages['loggedout'] = 'Sie haben Ihre Session erfolgreich beendet. Auf Wiedersehen!';
$messages['mailboxempty'] = 'Ordner ist leer';
$messages['loading'] = $messages['loadingdata'] = 'Daten werden geladen...';
$messages['checkingmail'] = 'Überprüfung auf neue Nachrichten...';
$messages['sendingmessage'] = 'Nachricht wird gesendet...';
$messages['messagesent'] = 'Nachricht erfolgreich gesendet';
$messages['savingmessage'] = 'Nachricht wird gespeichert...';
$messages['messagesaved'] = 'Nachricht als Entwurf gespeichert';
$messages['successfullysaved'] = 'Erfolgreich gespeichert';
$messages['addedsuccessfully'] = 'Kontakt zum Adressbuch hinzugefügt';
$messages['contactexists'] = 'Es existiert bereits ein Eintrag mit dieser E-Mail-Adresse';
$messages['blockedimages'] = 'Um Ihre Privatsphäre zur schützen, wurden externe Bilder blockiert.';
$messages['encryptedmessage'] = 'Dies ist eine verschlüsselte Nachricht und kann leider nicht angezeigt werden.';
$messages['nocontactsfound'] = 'Keine Kontakte gefunden';
+$messages['contactnotfound'] = 'Die gewählte Adresse wurde nicht gefunden';
+
$messages['sendingfailed'] = 'Versand der Nachricht fehlgeschlagen';
$messages['errorsaving'] = 'Beim Speichern ist ein Fehler aufgetreten';
$messages['errormoving'] = 'Nachricht konnte nicht verschoben werden';
$messages['errordeleting'] = 'Nachricht konnte nicht gelöscht werden';
$messages['deletecontactconfirm'] = 'Wollen Sie die ausgewählten Kontakte wirklich löschen';
$messages['deletemessagesconfirm'] = 'Wollen Sie die ausgewählten Nachrichten wirklich löschen?';
$messages['deletefolderconfirm'] = 'Wollen Sie diesen Ordner wirklich löschen?';
$messages['purgefolderconfirm'] = 'Wollen Sie diesen Ordner wirklich leeren?';
$messages['formincomplete'] = 'Das Formular wurde nicht vollständig ausgefüllt';
$messages['noemailwarning'] = 'Bitte geben Sie eine gültige E-Mail-Adresse ein';
$messages['nonamewarning'] = 'Bitte geben Sie einen Namen ein';
$messages['nopagesizewarning'] = 'Bitte geben Sie eine Einträge pro Seite ein';
$messages['norecipientwarning'] = 'Bitte geben Sie mindestens einen Empfänger an';
$messages['nosubjectwarning'] = 'Die Betreffzeile ist leer. Möchten Sie jetzt einen Betreff eingeben?';
$messages['nobodywarning'] = 'Diese Nachricht ohne Inhalt senden?';
$messages['notsentwarning'] = 'Ihre Nachricht wurde nicht gesendet. Wollen Sie die Nachricht verwerfen?';
$messages['noldapserver'] = 'Bitte wählen Sie einen LDAP-Server aus';
$messages['nocontactsreturned'] = 'Es wurden keine Kontakte gefunden';
$messages['nosearchname'] = 'Bitte geben Sie einen Namen oder eine E-Mail-Adresse ein';
$messages['searchsuccessful'] = '$nr Nachrichten gefunden';
$messages['searchnomatch'] = 'Keine Treffer';
$messages['searching'] = 'Suche...';
$messages['checking'] = 'Prüfe...';
$messages['nospellerrors'] = 'Keine Rechtschreibfehler gefunden';
$messages['folderdeleted'] = 'Ordner erfolgreich gelöscht';
$messages['deletedsuccessfully'] = "Erfolgreich gelöscht";
$messages['converting'] = 'Entferne Formatierungen...';
$messages['messageopenerror'] = 'Die Nachricht konnte nicht vom Server geladen werden';
$messages['fileuploaderror'] = 'Der Dateiupload ist fehlgeschlagen';
$messages['filesizeerror'] = 'Die Datei überschreitet die maximale Grösse von $size';
?>
\ No newline at end of file
diff --git a/program/localization/en_GB/labels.inc b/program/localization/en_GB/labels.inc
index e478016d2..71e73c830 100644
--- a/program/localization/en_GB/labels.inc
+++ b/program/localization/en_GB/labels.inc
@@ -1,204 +1,195 @@
<?php
/*
+-----------------------------------------------------------------------+
| language/en_GB/labels.inc |
| |
| Language file of the RoundCube Webmail client |
| Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Weiran Zhang (weiran@weiran.co.uk) |
+-----------------------------------------------------------------------+
@version $Id$
*/
$labels = array();
// login page
$labels['welcome'] = 'Welcome to $product';
$labels['username'] = 'Username';
$labels['password'] = 'Password';
$labels['server'] = 'Server';
$labels['login'] = 'Login';
// taskbar
$labels['logout'] = 'Logout';
$labels['mail'] = 'E-Mail';
$labels['settings'] = 'Personal Settings';
$labels['addressbook'] = 'Address Book';
// mailbox names
$labels['inbox'] = 'Inbox';
$labels['drafts'] = 'Drafts';
$labels['sent'] = 'Sent';
$labels['trash'] = 'Deleted Items';
$labels['drafts'] = 'Drafts';
$labels['junk'] = 'Junk';
// message listing
$labels['subject'] = 'Subject';
$labels['from'] = 'Sender';
$labels['to'] = 'Recipient';
$labels['cc'] = 'Copy';
$labels['bcc'] = 'Bcc';
$labels['replyto'] = 'Reply-To';
$labels['date'] = 'Date';
$labels['size'] = 'Size';
$labels['priority'] = 'Priority';
$labels['organization'] = 'Organisation';
// aliases
$labels['reply-to'] = $labels['replyto'];
$labels['mailboxlist'] = 'Folders';
$labels['messagesfromto'] = 'Messages $from to $to of $count';
$labels['messagenrof'] = 'Message $nr of $count';
$labels['moveto'] = 'move to...';
$labels['download'] = 'download';
$labels['filename'] = 'File name';
$labels['filesize'] = 'File size';
$labels['preferhtml'] = 'Prefer HTML';
$labels['htmlmessage'] = 'HTML Message';
$labels['prettydate'] = 'Pretty dates';
$labels['addtoaddressbook'] = 'Add to address book';
// weekdays short
$labels['sun'] = 'Sun';
$labels['mon'] = 'Mon';
$labels['tue'] = 'Tue';
$labels['wed'] = 'Wed';
$labels['thu'] = 'Thu';
$labels['fri'] = 'Fri';
$labels['sat'] = 'Sat';
// weekdays long
$labels['sunday'] = 'Sunday';
$labels['monday'] = 'Monday';
$labels['tuesday'] = 'Tuesday';
$labels['wednesday'] = 'Wednesday';
$labels['thursday'] = 'Thursday';
$labels['friday'] = 'Friday';
$labels['saturday'] = 'Saturday';
$labels['today'] = 'Today';
// toolbar buttons
$labels['checkmail'] = 'Check for new messages';
$labels['writenewmessage'] = 'Create a new message';
$labels['replytomessage'] = 'Reply to the message';
$labels['replytoallmessage'] = 'Reply to sender and all recipients';
$labels['forwardmessage'] = 'Forward the message';
$labels['deletemessage'] = 'Move message to trash';
$labels['printmessage'] = 'Print this message';
$labels['previousmessages'] = 'Show previous set of messages';
$labels['nextmessages'] = 'Show next set of messages';
$labels['backtolist'] = 'Back to message list';
$labels['viewsource'] = 'Show source';
$labels['select'] = 'Select';
$labels['all'] = 'All';
$labels['none'] = 'None';
$labels['unread'] = 'Unread';
$labels['compact'] = 'Compact';
$labels['empty'] = 'Empty';
$labels['purge'] = 'Purge';
$labels['quota'] = 'Disk usage';
// message compose
$labels['compose'] = 'Compose a message';
$labels['savemessage'] = 'Save this draft';
$labels['sendmessage'] = 'Send the message now';
$labels['addattachment'] = 'Attach a file';
$labels['charset'] = 'Charset';
$labels['attachments'] = 'Attachments';
$labels['upload'] = 'Upload';
$labels['close'] = 'Close';
$labels['low'] = 'Low';
$labels['lowest'] = 'Lowest';
$labels['normal'] = 'Normal';
$labels['high'] = 'High';
$labels['highest'] = 'Highest';
$labels['nosubject'] = '(no subject)';
$labels['showimages'] = 'Display images';
// address boook
$labels['name'] = 'Display name';
$labels['firstname'] = 'First name';
$labels['surname'] = 'Last name';
$labels['email'] = 'E-Mail';
$labels['addcontact'] = 'Add new contact';
$labels['editcontact'] = 'Edit contact';
$labels['edit'] = 'Edit';
$labels['cancel'] = 'Cancel';
$labels['save'] = 'Save';
$labels['delete'] = 'Delete';
$labels['newcontact'] = 'Create new contact card';
$labels['deletecontact'] = 'Delete selected contacts';
$labels['composeto'] = 'Compose mail to';
$labels['contactsfromto'] = 'Contacts $from to $to of $count';
$labels['print'] = 'Print';
$labels['export'] = 'Export';
-// LDAP search
-$labels['ldapsearch'] = 'LDAP directory search';
-
-$labels['ldappublicsearchname'] = 'Contact name';
-$labels['ldappublicsearchtype'] = 'Exact match?';
-$labels['ldappublicserverselect'] = 'Select servers';
-$labels['ldappublicsearchfield'] = 'Search on';
-$labels['ldappublicsearchform'] = 'Look for a contact';
-$labels['ldappublicsearch'] = 'Search';
// settings
$labels['settingsfor'] = 'Settings for';
$labels['preferences'] = 'Preferences';
$labels['userpreferences'] = 'User preferences';
$labels['editpreferences'] = 'Edit user preferences';
$labels['identities'] = 'Identities';
$labels['manageidentities'] = 'Manage identities for this account';
$labels['newidentity'] = 'New identity';
$labels['newitem'] = 'New item';
$labels['edititem'] = 'Edit item';
$labels['setdefault'] = 'Set default';
$labels['language'] = 'Language';
$labels['timezone'] = 'Time zone';
$labels['pagesize'] = 'Rows per page';
$labels['signature'] = 'Signature';
$labels['folder'] = 'Folder';
$labels['folders'] = 'Folders';
$labels['foldername'] = 'Folder name';
$labels['subscribed'] = 'Subscribed';
$labels['create'] = 'Create';
$labels['createfolder'] = 'Create new folder';
$labels['deletefolder'] = 'Delete folder';
$labels['managefolders'] = 'Manage folders';
$labels['sortby'] = 'Sort by';
$labels['sortasc'] = 'Sort ascending';
$labels['sortdesc'] = 'Sort descending';
?>
\ No newline at end of file
diff --git a/program/localization/en_US/labels.inc b/program/localization/en_US/labels.inc
index 530a8ece5..201af0bd5 100644
--- a/program/localization/en_US/labels.inc
+++ b/program/localization/en_US/labels.inc
@@ -1,240 +1,232 @@
<?php
/*
+-----------------------------------------------------------------------+
| language/en_US/labels.inc |
| |
| Language file of the RoundCube Webmail client |
| Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
@version $Id$
*/
$labels = array();
// login page
$labels['welcome'] = 'Welcome to $product';
$labels['username'] = 'Username';
$labels['password'] = 'Password';
$labels['server'] = 'Server';
$labels['login'] = 'Login';
// taskbar
$labels['logout'] = 'Logout';
$labels['mail'] = 'E-Mail';
$labels['settings'] = 'Personal Settings';
$labels['addressbook'] = 'Address Book';
// mailbox names
$labels['inbox'] = 'Inbox';
$labels['drafts'] = 'Drafts';
$labels['sent'] = 'Sent';
$labels['trash'] = 'Trash';
$labels['junk'] = 'Junk';
// message listing
$labels['subject'] = 'Subject';
$labels['from'] = 'Sender';
$labels['to'] = 'Recipient';
$labels['cc'] = 'Copy';
$labels['bcc'] = 'Bcc';
$labels['replyto'] = 'Reply-To';
$labels['date'] = 'Date';
$labels['size'] = 'Size';
$labels['priority'] = 'Priority';
$labels['organization'] = 'Organization';
// aliases
$labels['reply-to'] = $labels['replyto'];
$labels['mailboxlist'] = 'Folders';
$labels['messagesfromto'] = 'Messages $from to $to of $count';
$labels['messagenrof'] = 'Message $nr of $count';
$labels['moveto'] = 'move to...';
$labels['download'] = 'download';
$labels['filename'] = 'File name';
$labels['filesize'] = 'File size';
$labels['preferhtml'] = 'Display HTML';
$labels['htmlmessage'] = 'HTML Message';
$labels['prettydate'] = 'Pretty dates';
$labels['addtoaddressbook'] = 'Add to address book';
// weekdays short
$labels['sun'] = 'Sun';
$labels['mon'] = 'Mon';
$labels['tue'] = 'Tue';
$labels['wed'] = 'Wed';
$labels['thu'] = 'Thu';
$labels['fri'] = 'Fri';
$labels['sat'] = 'Sat';
// weekdays long
$labels['sunday'] = 'Sunday';
$labels['monday'] = 'Monday';
$labels['tuesday'] = 'Tuesday';
$labels['wednesday'] = 'Wednesday';
$labels['thursday'] = 'Thursday';
$labels['friday'] = 'Friday';
$labels['saturday'] = 'Saturday';
$labels['today'] = 'Today';
// toolbar buttons
$labels['checkmail'] = 'Check for new messages';
$labels['writenewmessage'] = 'Create a new message';
$labels['replytomessage'] = 'Reply to the message';
$labels['replytoallmessage'] = 'Reply to sender and all recipients';
$labels['forwardmessage'] = 'Forward the message';
$labels['deletemessage'] = 'Move message to trash';
$labels['printmessage'] = 'Print this message';
$labels['previousmessage'] = 'Show the previous message';
$labels['previousmessages'] = 'Show previous set of messages';
$labels['firstmessage'] = 'Show the first message';
$labels['firstmessages'] = 'Show first set of messages';
$labels['nextmessage'] = 'Show the next message';
$labels['nextmessages'] = 'Show next set of messages';
$labels['lastmessage'] = 'Show the last message';
$labels['lastmessages'] = 'Show last set of messages';
$labels['backtolist'] = 'Back to message list';
$labels['viewsource'] = 'Show source';
$labels['select'] = 'Select';
$labels['all'] = 'All';
$labels['none'] = 'None';
$labels['unread'] = 'Unread';
$labels['compact'] = 'Compact';
$labels['empty'] = 'Empty';
$labels['purge'] = 'Purge';
$labels['quota'] = 'Disk usage';
$labels['unknown'] = 'unknown';
$labels['unlimited'] = 'unlimited';
$labels['quicksearch'] = 'Quick search';
$labels['resetsearch'] = 'Reset search';
// message compose
$labels['compose'] = 'Compose a message';
$labels['sendmessage'] = 'Send the message now';
$labels['savemessage'] = 'Save this draft';
$labels['addattachment'] = 'Attach a file';
$labels['charset'] = 'Charset';
$labels['editortype'] = 'Editor type';
$labels['returnreceipt'] = 'Return receipt';
$labels['checkspelling'] = 'Check spelling';
$labels['resumeediting'] = 'Resume editing';
$labels['revertto'] = 'Revert to';
$labels['attachments'] = 'Attachments';
$labels['upload'] = 'Upload';
$labels['close'] = 'Close';
$labels['low'] = 'Low';
$labels['lowest'] = 'Lowest';
$labels['normal'] = 'Normal';
$labels['high'] = 'High';
$labels['highest'] = 'Highest';
$labels['nosubject'] = '(no subject)';
$labels['showimages'] = 'Display images';
$labels['htmltoggle'] = 'HTML';
$labels['plaintoggle'] = 'Plain text';
// address boook
$labels['name'] = 'Display name';
$labels['firstname'] = 'First name';
$labels['surname'] = 'Last name';
$labels['email'] = 'E-Mail';
$labels['addcontact'] = 'Add new contact';
$labels['editcontact'] = 'Edit contact';
$labels['edit'] = 'Edit';
$labels['cancel'] = 'Cancel';
$labels['save'] = 'Save';
$labels['delete'] = 'Delete';
$labels['newcontact'] = 'Create new contact card';
$labels['deletecontact'] = 'Delete selected contacts';
$labels['composeto'] = 'Compose mail to';
$labels['contactsfromto'] = 'Contacts $from to $to of $count';
$labels['print'] = 'Print';
$labels['export'] = 'Export';
$labels['previouspage'] = 'Show previous set';
$labels['firstpage'] = 'Show first set';
$labels['nextpage'] = 'Show next set';
$labels['lastpage'] = 'Show last set';
-
-// LDAP search
-$labels['ldapsearch'] = 'LDAP directory search';
-
-$labels['ldappublicsearchname'] = 'Contact name';
-$labels['ldappublicsearchtype'] = 'Exact match?';
-$labels['ldappublicserverselect'] = 'Select servers';
-$labels['ldappublicsearchfield'] = 'Search on';
-$labels['ldappublicsearchform'] = 'Look for a contact';
-$labels['ldappublicsearch'] = 'Search';
+$labels['groups'] = 'Groups';
+$labels['personaladrbook'] = 'Personal Addresses';
// settings
$labels['settingsfor'] = 'Settings for';
$labels['preferences'] = 'Preferences';
$labels['userpreferences'] = 'User preferences';
$labels['editpreferences'] = 'Edit user preferences';
$labels['identities'] = 'Identities';
$labels['manageidentities'] = 'Manage identities for this account';
$labels['newidentity'] = 'New identity';
$labels['newitem'] = 'New item';
$labels['edititem'] = 'Edit item';
$labels['setdefault'] = 'Set default';
$labels['language'] = 'Language';
$labels['timezone'] = 'Time zone';
$labels['pagesize'] = 'Rows per page';
$labels['signature'] = 'Signature';
$labels['dstactive'] = 'Daylight savings';
$labels['htmleditor'] = 'Compose HTML messages';
$labels['htmlsignature'] = 'HTML signature';
$labels['previewpane'] = 'Show preview pane';
$labels['autosavedraft'] = 'Automatically save draft';
$labels['everynminutes'] = 'every $n minutes';
$labels['never'] = 'never';
$labels['folder'] = 'Folder';
$labels['folders'] = 'Folders';
$labels['foldername'] = 'Folder name';
$labels['subscribed'] = 'Subscribed';
$labels['create'] = 'Create';
$labels['createfolder'] = 'Create new folder';
$labels['rename'] = 'Rename';
$labels['renamefolder'] = 'Rename folder';
$labels['deletefolder'] = 'Delete folder';
$labels['managefolders'] = 'Manage folders';
$labels['sortby'] = 'Sort by';
$labels['sortasc'] = 'Sort ascending';
$labels['sortdesc'] = 'Sort descending';
?>
\ No newline at end of file
diff --git a/program/localization/en_US/messages.inc b/program/localization/en_US/messages.inc
index 51cc313c7..bb132a583 100644
--- a/program/localization/en_US/messages.inc
+++ b/program/localization/en_US/messages.inc
@@ -1,72 +1,79 @@
<?php
/*
+-----------------------------------------------------------------------+
| language/en/messages.inc |
| |
| Language file of the RoundCube Webmail client |
| Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
@version $Id$
*/
$messages = array();
$messages['loginfailed'] = 'Login failed';
$messages['cookiesdisabled'] = 'Your browser does not accept cookies';
$messages['sessionerror'] = 'Your session is invalid or expired';
$messages['imaperror'] = 'Connection to IMAP server failed';
$messages['nomessagesfound'] = 'No messages found in this mailbox';
$messages['loggedout'] = 'You have successfully terminated the session. Good bye!';
$messages['mailboxempty'] = 'Mailbox is empty';
$messages['loading'] = 'Loading...';
$messages['loadingdata'] = 'Loading data...';
$messages['checkingmail'] = 'Checking for new messages...';
$messages['sendingmessage'] = 'Sending message...';
$messages['messagesent'] = 'Message sent successfully';
$messages['savingmessage'] = 'Saving message...';
$messages['messagesaved'] = 'Message saved to Drafts';
$messages['successfullysaved'] = 'Successfully saved';
$messages['addedsuccessfully'] = 'Contact added successfully to address book';
$messages['contactexists'] = 'A contact with this e-mail address already exists';
$messages['blockedimages'] = 'To protect your privacy, remote images are blocked in this message.';
$messages['encryptedmessage'] = 'This is an encrypted message and can not be displayed. Sorry!';
$messages['nocontactsfound'] = 'No contacts found';
+$messages['contactnotfound'] = 'The requested contact was not found';
+
$messages['sendingfailed'] = 'Failed to send message';
$messages['errorsaving'] = 'An error occured while saving';
$messages['errormoving'] = 'Could not move the message';
$messages['errordeleting'] = 'Could not delete the message';
$messages['deletecontactconfirm'] = 'Do you really want to delete the selected contact(s)?';
$messages['deletemessagesconfirm'] = 'Do you really want to delete the selected message(s)?';
$messages['deletefolderconfirm'] = 'Do you really want to delete this folder?';
$messages['purgefolderconfirm'] = 'Do you really want to delete all messages in this folder?';
$messages['formincomplete'] = 'The form was not completely filled out';
$messages['noemailwarning'] = 'Please enter a valid email address';
$messages['nonamewarning'] = 'Please enter a name';
$messages['nopagesizewarning'] = 'Please enter a page size';
$messages['norecipientwarning'] = 'Please enter at least one recipient';
$messages['nosubjectwarning'] = 'The "Subject" field is empty. Would you like to enter one now?';
$messages['nobodywarning'] = 'Send this message without text?';
$messages['notsentwarning'] = 'Message has not been sent. Do you want to discard your message?';
$messages['noldapserver'] = 'Please select an ldap server to search';
$messages['nocontactsreturned'] = 'No contacts were found';
$messages['nosearchname'] = 'Please enter a contact name or email address';
$messages['searchsuccessful'] = '$nr messages found';
$messages['searchnomatch'] = 'Search returned no matches';
$messages['searching'] = 'Searching...';
$messages['checking'] = 'Checking...';
$messages['nospellerrors'] = 'No spelling errors found';
$messages['folderdeleted'] = 'Folder successfully deleted';
$messages['deletedsuccessfully'] = "Successfully deleted";
$messages['converting'] = 'Removing formatting from message...';
$messages['messageopenerror'] = 'Could not load message from server';
$messages['fileuploaderror'] = 'File upload failed';
$messages['filesizeerror'] = 'The uploaded file exceeds the maximum size of $size';
-?>
\ No newline at end of file
+$messages['copysuccess'] = 'Successfully copied $nr addresses';
+$messages['copyerror'] = 'Could not copy any addresses';
+$messages['sourceisreadonly'] = 'This address source is read only';
+$messages['errorsavingcontact'] = 'Could not save the contact address';
+
+?>
diff --git a/program/steps/addressbook/copy.inc b/program/steps/addressbook/copy.inc
new file mode 100644
index 000000000..e6d917e92
--- /dev/null
+++ b/program/steps/addressbook/copy.inc
@@ -0,0 +1,44 @@
+<?php
+
+/*
+ +-----------------------------------------------------------------------+
+ | program/steps/addressbook/copy.inc |
+ | |
+ | This file is part of the RoundCube Webmail client |
+ | Copyright (C) 2007, RoundCube Dev. - Switzerland |
+ | Licensed under the GNU GPL |
+ | |
+ | PURPOSE: |
+ | Copy a contact record from one direcotry to another |
+ | |
+ +-----------------------------------------------------------------------+
+ | Author: Thomas Bruederli <roundcube@gmail.com> |
+ +-----------------------------------------------------------------------+
+
+ $Id: copy.inc 471 2007-02-09 21:25:50Z thomasb $
+
+*/
+
+$cid = get_input_value('_cid', RCUBE_INPUT_POST);
+$target = get_input_value('_to', RCUBE_INPUT_POST);
+if ($cid && preg_match('/^[a-z0-9\-_=]+(,[a-z0-9\-_=]+)*$/i', $cid) && strlen($target) && $target != $source)
+{
+ if ($target != '0')
+ $TARGET = new rcube_ldap($CONFIG['ldap_public'][$target]);
+ else
+ $TARGET = new rcube_contacts($DB, $_SESSION['user_id']);
+
+ $success = false;
+ if ($TARGET && $TARGET->ready && !$TARGET->readonly)
+ $success = $TARGET->insert($CONTACTS->search($CONTACTS->primary_key, $cid), true);
+
+ if (empty($success))
+ $OUTPUT->show_message('copyerror', 'error');
+ else
+ $OUTPUT->show_message('copysuccess', 'notice', array('nr' => count($success)));
+}
+
+// send response
+$OUTPUT->send();
+
+?>
\ No newline at end of file
diff --git a/program/steps/addressbook/delete.inc b/program/steps/addressbook/delete.inc
index 3e33cd864..e5c762844 100644
--- a/program/steps/addressbook/delete.inc
+++ b/program/steps/addressbook/delete.inc
@@ -1,99 +1,48 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/addressbook/delete.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Delete the submitted contacts (CIDs) from the users address book |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
-
-if ($_GET['_cid'] && preg_match('/^[0-9]+(,[0-9]+)*$/',$_GET['_cid']))
+if (($cid = get_input_value('_cid', RCUBE_INPUT_GPC)) && preg_match('/^[0-9]+(,[0-9]+)*$/', $cid))
{
- $DB->query("UPDATE ".get_table_name('contacts')."
- SET del=1
- WHERE user_id=?
- AND contact_id IN (".$_GET['_cid'].")",
- $_SESSION['user_id']);
-
- $count = $DB->affected_rows();
- if (!$count)
+ $deleted = $CONTACTS->delete($cid);
+ if (!$deleted)
{
// send error message
exit;
}
-
// count contacts for this user
- $sql_result = $DB->query("SELECT COUNT(contact_id) AS rows
- FROM ".get_table_name('contacts')."
- WHERE del<>1
- AND user_id=?",
- $_SESSION['user_id']);
-
- $sql_arr = $DB->fetch_assoc($sql_result);
- $rowcount = $sql_arr['rows'];
+ $result = $CONTACTS->count();
// update message count display
- $pages = ceil($rowcount/$CONFIG['pagesize']);
- $commands = sprintf("this.set_rowcount('%s');\n", rcmail_get_rowcount_text($rowcount));
- $commands .= sprintf("this.set_env('pagecount', %d);\n", $pages);
-
+ $OUTPUT->set_env('pagecount', ceil($result->count / $CONTACTS->page_size));
+ $OUTPUT->command('set_rowcount', rcmail_get_rowcount_text($result->count));
// add new rows from next page (if any)
- if ($_GET['_from']!='show' && $pages>1 && $_SESSION['page'] < $pages)
- {
- $start_row = ($_SESSION['page'] * $CONFIG['pagesize']) - $count;
-
- // get contacts from DB
- $sql_result = $DB->limitquery("SELECT * FROM ".get_table_name('contacts')."
- WHERE del<>1
- AND user_id=?
- ORDER BY name",
- $start_row,
- $count,
- $_SESSION['user_id']);
-
- $commands .= rcmail_js_contacts_list($sql_result);
-
-/*
- // define list of cols to be displayed
- $a_show_cols = array('name', 'email');
-
- while ($sql_arr = $DB->fetch_assoc($sql_result))
- {
- $a_row_cols = array();
-
- // format each col
- foreach ($a_show_cols as $col)
- {
- $cont = rep_specialchars_output($sql_arr[$col]);
- $a_row_cols[$col] = $cont;
- }
-
- $commands .= sprintf("this.add_contact_row(%s, %s);\n",
- $sql_arr['contact_id'],
- array2js($a_row_cols));
- }
-*/
- }
+ $pages = ceil(($result->count + $deleted) / $CONTACTS->page_size);
+ if ($_GET['_from'] != 'show' && $pages > 1 && $CONTACTS->list_page < $pages)
+ rcmail_js_contacts_list($CONTACTS->list_records(null, -$deleted));
// send response
- rcube_remote_response($commands);
+ $OUTPUT->send();
}
exit;
?>
diff --git a/program/steps/addressbook/edit.inc b/program/steps/addressbook/edit.inc
index 245c02409..47db7197d 100644
--- a/program/steps/addressbook/edit.inc
+++ b/program/steps/addressbook/edit.inc
@@ -1,126 +1,121 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/addressbook/edit.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Show edit form for a contact entry or to add a new one |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-if (($_GET['_cid'] || $_POST['_cid']) && $_action=='edit')
- {
- $cid = $_POST['_cid'] ? $_POST['_cid'] : $_GET['_cid'];
- $DB->query("SELECT * FROM ".get_table_name('contacts')."
- WHERE contact_id=?
- AND user_id=?
- AND del<>1",
- $cid,
- $_SESSION['user_id']);
-
- $CONTACT_RECORD = $DB->fetch_assoc();
-
- if (is_array($CONTACT_RECORD))
- $OUTPUT->add_script(sprintf("%s.set_env('cid', '%s');", $JS_OBJECT_NAME, $CONTACT_RECORD['contact_id']));
- }
-
+if (($cid = get_input_value('_cid', RCUBE_INPUT_GPC)) && ($record = $CONTACTS->get_record($cid, true)))
+ $OUTPUT->set_env('cid', $record['ID']);
+// adding not allowed here
+if ($CONTACTS->readonly)
+{
+ $OUTPUT->show_message('sourceisreadonly');
+ rcmail_overwrite_action('show');
+ return;
+}
function rcmail_contact_editform($attrib)
- {
- global $CONTACT_RECORD, $JS_OBJECT_NAME;
+{
+ global $CONTACTS, $OUTPUT;
- if (!$CONTACT_RECORD && $GLOBALS['_action']!='add')
- return rcube_label('contactnotfound');
+ // check if we have a valid result
+ if ($GLOBALS['_action'] != 'add' && !(($result = $CONTACTS->get_result()) && ($record = $result->first())))
+ {
+ $OUTPUT->show_message('contactnotfound');
+ return false;
+ }
// add some labels to client
rcube_add_label('noemailwarning');
rcube_add_label('nonamewarning');
list($form_start, $form_end) = get_form_tags($attrib);
unset($attrib['form']);
-
// a specific part is requested
if ($attrib['part'])
- {
+ {
$out = $form_start;
- $out .= rcmail_get_edit_field($attrib['part'], $CONTACT_RECORD[$attrib['part']], $attrib);
+ $out .= rcmail_get_edit_field($attrib['part'], $record[$attrib['part']], $attrib);
return $out;
- }
+ }
// return the complete address edit form as table
$out = "$form_start<table>\n\n";
$a_show_cols = array('name', 'firstname', 'surname', 'email');
foreach ($a_show_cols as $col)
- {
+ {
$attrib['id'] = 'rcmfd_'.$col;
- $title = rcube_label($col);
- $value = rcmail_get_edit_field($col, $CONTACT_RECORD[$col], $attrib);
+ $value = rcmail_get_edit_field($col, $record[$col], $attrib);
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$attrib['id'],
- $title,
+ Q(rcube_label($col)),
$value);
- }
+ }
$out .= "\n</table>$form_end";
return $out;
- }
+}
+
+$OUTPUT->add_handler('contacteditform', 'rcmail_contact_editform');
// similar function as in /steps/settings/edit_identity.inc
function get_form_tags($attrib)
{
- global $CONTACT_RECORD, $OUTPUT, $JS_OBJECT_NAME, $EDIT_FORM, $SESS_HIDDEN_FIELD;
+ global $CONTACTS, $OUTPUT, $EDIT_FORM, $SESS_HIDDEN_FIELD;
+ $result = $CONTACTS->get_result();
$form_start = '';
if (!strlen($EDIT_FORM))
{
$hiddenfields = new hiddenfield(array('name' => '_task', 'value' => $GLOBALS['_task']));
- $hiddenfields->add(array('name' => '_action', 'value' => 'save'));
-
- if ($GLOBALS['_framed'])
- $hiddenfields->add(array('name' => '_framed', 'value' => 1));
+ $hiddenfields->add(array('name' => '_action', 'value' => 'save', 'source' => get_input_value('_source', RCUBE_INPUT_GPC)));
- if ($CONTACT_RECORD['contact_id'])
- $hiddenfields->add(array('name' => '_cid', 'value' => $CONTACT_RECORD['contact_id']));
+ if (($result = $CONTACTS->get_result()) && ($record = $result->first()))
+ $hiddenfields->add(array('name' => '_cid', 'value' => $record['ID']));
$form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
$form_start .= "\n$SESS_HIDDEN_FIELD\n";
$form_start .= $hiddenfields->show();
}
$form_end = (strlen($EDIT_FORM) && !strlen($attrib['form'])) ? '</form>' : '';
$form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
if (!strlen($EDIT_FORM))
- $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('editform', '$form_name');");
+ $OUTPUT->add_gui_object('editform', $form_name);
$EDIT_FORM = $form_name;
return array($form_start, $form_end);
}
-if (!$CONTACT_RECORD && template_exists('addcontact'))
+if (!$CONTACTS->get_result() && template_exists('addcontact'))
parse_template('addcontact');
// this will be executed if no template for addcontact exists
parse_template('editcontact');
?>
\ No newline at end of file
diff --git a/program/steps/addressbook/func.inc b/program/steps/addressbook/func.inc
index 1f993a9d3..5329270c2 100644
--- a/program/steps/addressbook/func.inc
+++ b/program/steps/addressbook/func.inc
@@ -1,204 +1,239 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/addressbook/func.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Provide addressbook functionality and GUI objects |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$CONTACTS_LIST = array();
+require_once('include/rcube_contacts.inc');
+require_once('include/rcube_ldap.inc');
+
+// instantiate a contacts object according to the given source
+if (($source = get_input_value('_source', RCUBE_INPUT_GPC)) && isset($CONFIG['ldap_public'][$source]))
+ $CONTACTS = new rcube_ldap($CONFIG['ldap_public'][$source]);
+else
+ $CONTACTS = new rcube_contacts($DB, $_SESSION['user_id']);
+
+$CONTACTS->set_pagesize($CONFIG['pagesize']);
// set list properties and session vars
-if (strlen($_GET['_page']))
+if (!empty($_GET['_page']))
{
- $CONTACTS_LIST['page'] = $_GET['_page'];
+ $CONTACTS->set_page(intval($_GET['_page']));
$_SESSION['page'] = $_GET['_page'];
}
else
- $CONTACTS_LIST['page'] = $_SESSION['page'] ? $_SESSION['page'] : 1;
+ $CONTACTS->set_page(isset($_SESSION['page']) ?$_SESSION['page'] : 1);
+
+// set message set for search result
+if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
+ $CONTACTS->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
+
+// set data source env
+$OUTPUT->set_env('source', $source ? $source : '0');
+$OUTPUT->set_env('readonly', $CONTACTS->readonly, false);
+
+
+function rcmail_directory_list($attrib)
+{
+ global $CONFIG, $OUTPUT;
+
+ if (!$attrib['id'])
+ $attrib['id'] = 'rcmdirectorylist';
+
+ $local_id = '0';
+ $current = get_input_value('_source', RCUBE_INPUT_GPC);
+ $line_templ = '<li id="%s" class="%s"><a href="%s"' .
+ ' onclick="return %s.command(\'list\',\'%s\',this)"' .
+ ' onmouseover="return %s.focus_folder(\'%s\')"' .
+ ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
+ ' onmouseup="return %s.folder_mouse_up(\'%s\')">%s'.
+ "</a></li>\n";
+
+ $js_list = array("$local_id" => array('id' => $local_id, 'readonly' => false));
+
+ // allow the following attributes to be added to the <ul> tag
+ $out = '<ul' . create_attrib_string($attrib, array('style', 'class', 'id')) . ">\n";
+ $out .= sprintf($line_templ,
+ 'rcmli'.$local_id,
+ !$current ? 'selected' : '',
+ Q(rcmail_self_url('list', array('_source' => 0))),
+ JS_OBJECT_NAME,
+ $local_id,
+ JS_OBJECT_NAME,
+ $local_id,
+ JS_OBJECT_NAME,
+ $local_id,
+ JS_OBJECT_NAME,
+ $local_id,
+ rcube_label('personaladrbook'));
+
+ foreach ((array)$CONFIG['ldap_public'] as $id => $prop)
+ {
+ $js_id = JQ($id);
+ $dom_id = preg_replace('/[^a-z0-9\-_]/i', '', $id);
+ $out .= sprintf($line_templ,
+ 'rcmli'.$dom_id,
+ $current == $id ? 'selected' : '',
+ Q(rcmail_self_url('list', array('_source' => $id))),
+ JS_OBJECT_NAME,
+ $js_id,
+ JS_OBJECT_NAME,
+ $js_id,
+ JS_OBJECT_NAME,
+ $js_id,
+ JS_OBJECT_NAME,
+ $js_id,
+ !empty($prop['name']) ? Q($prop['name']) : Q($id));
+
+ $js_list[$id] = array('id' => $id, 'readonly' => !$prop['writeable']);
+ }
+
+ $out .= '</ul>';
-// disable the ldap public search button if there's no servers configured
-$enable_ldap = 'true';
-if (!$CONFIG['ldap_public'])
- $enable_ldap = 'false';
+ $OUTPUT->add_gui_object('folderlist', $attrib['id']);
+ $OUTPUT->set_env('address_sources', $js_list);
-$OUTPUT->add_script("$JS_OBJECT_NAME.set_env('ldappublicsearch', $enable_ldap);");
+ return $out;
+}
+
// return the message list as HTML table
function rcmail_contacts_list($attrib)
{
- global $DB, $CONFIG, $OUTPUT, $CONTACTS_LIST, $JS_OBJECT_NAME;
-
- //$skin_path = $CONFIG['skin_path'];
- //$image_tag = '<img src="%s%s" alt="%s" border="0" />';
+ global $CONTACTS, $OUTPUT;
// count contacts for this user
- $sql_result = $DB->query("SELECT COUNT(contact_id) AS rows
- FROM ".get_table_name('contacts')."
- WHERE del<>1
- AND user_id=?",
- $_SESSION['user_id']);
-
- $sql_arr = $DB->fetch_assoc($sql_result);
- $rowcount = $sql_arr['rows'];
-
- if ($rowcount)
- {
- $start_row = ($CONTACTS_LIST['page']-1) * $CONFIG['pagesize'];
-
- // get contacts from DB
- $sql_result = $DB->limitquery("SELECT * FROM ".get_table_name('contacts')."
- WHERE del<>1
- AND user_id= ?
- ORDER BY name",
- $start_row,
- $CONFIG['pagesize'],
- $_SESSION['user_id']);
- }
- else
- $sql_result = NULL;
-
-
+ $result = $CONTACTS->list_records();
+
// add id to message list table if not specified
if (!strlen($attrib['id']))
$attrib['id'] = 'rcmAddressList';
-
+
// define list of cols to be displayed
- $a_show_cols = array('name', 'email');
-
- // create XHTML table
- $out = rcube_table_output($attrib, $sql_result, $a_show_cols, 'contact_id');
+ $a_show_cols = array('name');
- // set client env
- $javascript = sprintf("%s.gui_object('contactslist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
- $javascript .= sprintf("%s.set_env('current_page', %d);\n", $JS_OBJECT_NAME, $CONTACTS_LIST['page']);
- $javascript .= sprintf("%s.set_env('pagecount', %d);\n", $JS_OBJECT_NAME, ceil($rowcount/$CONFIG['pagesize']));
- $javascript .= "rcmail.set_env('newcontact', '" . rcube_label('newcontact') . "');";
- //$javascript .= sprintf("%s.set_env('contacts', %s);", $JS_OBJECT_NAME, array2js($a_js_message_arr));
+ // create XHTML table
+ $out = rcube_table_output($attrib, $result->records, $a_show_cols, $CONTACTS->primary_key);
- $OUTPUT->add_script($javascript);
+ // set client env
+ $OUTPUT->add_gui_object('contactslist', $attrib['id']);
+ $OUTPUT->set_env('current_page', (int)$CONTACTS->list_page);
+ $OUTPUT->set_env('pagecount', ceil($result->count/$CONTACTS->page_size));
$OUTPUT->include_script('list.js');
-
+
// add some labels to client
rcube_add_label('deletecontactconfirm');
-
+
return $out;
}
-
-function rcmail_js_contacts_list($sql_result, $obj_name='this')
+function rcmail_js_contacts_list($result, $prefix='')
{
- global $DB;
+ global $OUTPUT;
- $commands = '';
-
- if (!$sql_result)
- return '';
+ if (empty($result) || $result->count == 0)
+ return;
// define list of cols to be displayed
- $a_show_cols = array('name', 'email');
-
- while ($sql_arr = $DB->fetch_assoc($sql_result))
+ $a_show_cols = array('name');
+
+ while ($row = $result->next())
{
$a_row_cols = array();
-
+
// format each col
foreach ($a_show_cols as $col)
- {
- $cont = Q($sql_arr[$col]);
- $a_row_cols[$col] = $cont;
- }
-
- $commands .= sprintf("%s.add_contact_row(%s, %s);\n",
- $obj_name,
- $sql_arr['contact_id'],
- array2js($a_row_cols));
- }
+ $a_row_cols[$col] = $row[$col];
- return $commands;
+ $OUTPUT->command($prefix.'add_contact_row', $row['ID'], $a_row_cols);
+ }
}
// similar function as /steps/settings/identities.inc::rcmail_identity_frame()
function rcmail_contact_frame($attrib)
{
- global $OUTPUT, $JS_OBJECT_NAME;
+ global $OUTPUT;
if (!$attrib['id'])
$attrib['id'] = 'rcmcontactframe';
$attrib['name'] = $attrib['id'];
-
- $OUTPUT->add_script(sprintf("%s.set_env('contentframe', '%s');", $JS_OBJECT_NAME, $attrib['name']));
-
$attrib_str = create_attrib_string($attrib, array('name', 'id', 'class', 'style', 'src', 'width', 'height', 'frameborder'));
- $out = '<iframe'. $attrib_str . '></iframe>';
-
- return $out;
+
+ $OUTPUT->set_env('contentframe', $attrib['name']);
+ $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
+ return '<iframe'. $attrib_str . '></iframe>';
}
function rcmail_rowcount_display($attrib)
{
- global $OUTPUT, $JS_OBJECT_NAME;
+ global $OUTPUT;
if (!$attrib['id'])
$attrib['id'] = 'rcmcountdisplay';
- $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
+ $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
// allow the following attributes to be added to the <span> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
-
$out = '<span' . $attrib_str . '>';
$out .= rcmail_get_rowcount_text();
$out .= '</span>';
return $out;
}
-function rcmail_get_rowcount_text($max=NULL)
+function rcmail_get_rowcount_text()
{
- global $CONTACTS_LIST, $CONFIG, $DB;
+ global $CONTACTS;
- $start_row = ($CONTACTS_LIST['page']-1) * $CONFIG['pagesize'] + 1;
-
- // get nr of contacts
- if ($max===NULL)
- {
- $sql_result = $DB->query("SELECT 1 FROM ".get_table_name('contacts')."
- WHERE del<>1
- AND user_id=?",
- $_SESSION['user_id']);
-
- $max = $DB->num_rows($sql_result);
- }
-
- if ($max==0)
+ // read nr of contacts
+ $result = $CONTACTS->get_result();
+ if (!$result)
+ $result = $CONTACTS->count();
+
+ if ($result->count == 0)
$out = rcube_label('nocontactsfound');
else
- $out = rcube_label(array('name' => 'contactsfromto',
- 'vars' => array('from' => $start_row,
- 'to' => min($max, $start_row + $CONFIG['pagesize'] - 1),
- 'count' => $max)));
+ $out = rcube_label(array(
+ 'name' => 'contactsfromto',
+ 'vars' => array(
+ 'from' => $result->first + 1,
+ 'to' => min($result->count, $result->first + $CONTACTS->page_size),
+ 'count' => $result->count)
+ ));
return $out;
}
+
+
+// register UI objects
+$OUTPUT->add_handlers(array(
+ 'directorylist' => 'rcmail_directory_list',
+ 'addresslist' => 'rcmail_contacts_list',
+ 'addressframe' => 'rcmail_contact_frame',
+ 'recordscountdisplay' => 'rcmail_rowcount_display',
+ 'searchform' => 'rcmail_search_form'
+));
?>
diff --git a/program/steps/addressbook/ldapsearchform.inc b/program/steps/addressbook/ldapsearchform.inc
deleted file mode 100644
index a4e08dcdc..000000000
--- a/program/steps/addressbook/ldapsearchform.inc
+++ /dev/null
@@ -1,277 +0,0 @@
-<?php
-
-/*
- +-----------------------------------------------------------------------+
- | program/steps/addressbook/ldapsearch.inc |
- | |
- | This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
- | Licensed under the GNU GPL |
- | |
- | PURPOSE: |
- | Show an ldap search form in the addressbook |
- | |
- +-----------------------------------------------------------------------+
- | Author: Justin Randell <justin.randell@gmail.com> |
- +-----------------------------------------------------------------------+
-
- $Id$
-
-*/
-require_once 'include/rcube_ldap.inc';
-
-/**
- * draw the ldap public search form
- */
-function rcmail_ldap_public_search_form($attrib)
- {
- global $CONFIG, $JS_OBJECT_NAME, $OUTPUT;
- if (!isset($CONFIG['ldap_public']))
- {
- // no ldap servers to search
- show_message('noldapserver', 'warning');
- rcmail_overwrite_action('add');
- return false;
- }
- else
- {
- // store some information in the session
- $_SESSION['ldap_public']['server_count'] = $server_count = count($CONFIG['ldap_public']);
- $_SESSION['ldap_public']['server_names'] = $server_names = array_keys($CONFIG['ldap_public']);
- }
-
- list($form_start, $form_end) = get_form_tags($attrib);
- $out = "$form_start<table id=\"ldap_public_search_table\">\n\n";
-
- // search name field
- $search_name = new textfield(array('name' => '_ldap_public_search_name',
- 'id' => 'rcmfd_ldap_public_search_name'));
- $out .= "<tr><td class=\"title\"><label for=\"rcmfd_ldap_public_search_name\">" .
- rep_specialchars_output(rcube_label('ldappublicsearchname')) .
- "</label></td><td>" . $search_name->show() . "</td></tr>\n";
-
-
- // there's more than one server to search for, show a dropdown menu
- if ($server_count > 1)
- {
- $select_server = new select(array('name' => '_ldap_public_servers',
- 'id' => 'rcfmd_ldap_public_servers'));
-
- $select_server->add($server_names, $server_names);
-
- $out .= '<tr><td class="title"><label for="rcfmd_ldap_public_servers">' .
- rep_specialchars_output(rcube_label('ldappublicserverselect')) .
- "</label></td><td>" . $select_server->show() . "</td></tr>\n";
- }
-
- // foreach configured ldap server, set up the search fields
- for ($i = 0; $i < $server_count; $i++)
- {
- $server = $CONFIG['ldap_public'][$server_names[$i]];
-
- // only display one search fields select - js takes care of the rest
- if (!$i)
- {
- $field_name = '_ldap_public_search_field';
- $field_id = 'rcfmd_ldap_public_search_field';
-
- $search_fields = new select(array('name' => $field_name,
- 'id' => $field_id));
-
- $search_fields->add(array_keys($server['search_fields']), array_values($server['search_fields']));
- $out .= '<tr><td class="title"><label for="' . $field_id . '">' .
- rep_specialchars_output(rcube_label('ldappublicsearchfield')) .
- "</label></td><td>" . $search_fields->show() . "</td></tr>\n";
-
- $attributes = array('name' => '_ldap_public_search_type',
- 'id' => 'rcmfd_ldap_public_search_type');
-
- // if there's only one server, and it doesn't accept fuzzy searches,
- // then check and disable the check box - thanks pieter
- if ($server_count == 1 && !$server['fuzzy_search'])
- {
- $attributes['CHECKED'] = 'CHECKED';
- $attributes['disabled'] = 'disabled';
- }
-
- $search_type = new checkbox($attributes);
-
- $out .= '<tr id="ldap_fuzzy_search"><td class="title"><label for="rcmfd_ldap_public_search_type">' .
- rep_specialchars_output(rcube_label('ldappublicsearchtype')) .
- "</label></td><td>" . $search_type->show() . "</td></tr>\n";
- }
-
- if ($server_count > 1)
- {
- // store the search fields in a js array for each server
- $js = '';
- foreach ($server['search_fields'] as $search_name => $search_value)
- $js .= "['$search_name', '$search_value'], ";
-
- // store whether this server accepts fuzzy search as last item in array
- $js .= $server['fuzzy_search'] ? "'fuzzy'" : "'exact'";
- $OUTPUT->add_script("rcmail.set_env('{$server_names[$i]}_search_fields', new Array($js));");
- }
- }
-
- // add contact button label text
- $OUTPUT->add_script("rcmail.set_env('addcontact', '" . rcube_label('addcontact') . "');");
-
- $out .= "\n</table>$form_end";
- return $out;
- }
-
-/**
- * get search values and return ldap contacts
- */
-function rcmail_ldap_public_list()
- {
- // just return if we are not being called from a search form
- if (!isset($_POST['_action']))
- return null;
-
- global $CONFIG, $OUTPUT, $JS_OBJECT_NAME;
-
- // show no search name warning and exit
- if (empty($_POST['_ldap_public_search_name']) || trim($_POST['_ldap_public_search_name']) == '')
- {
- show_message('nosearchname', 'warning');
- return false;
- }
-
- // set up ldap server(s) array or bail
- if ($_SESSION['ldap_public']['server_count'] > 1)
- // show no ldap server warning and exit
- if (empty($_POST['_ldap_public_servers']))
- {
- show_message('noldappublicserver', 'warning');
- return false;
- }
- else
- $server_name = $_POST['_ldap_public_servers'];
- else if ($_SESSION['ldap_public']['server_count'] == 1)
- $server_name = $_SESSION['ldap_public']['server_names'][0];
- else
- return false;
-
- // get search parameters
- $search_value = $_POST['_ldap_public_search_name'];
- $search_field = $_POST['_ldap_public_search_field'];
-
- // only use the post var for search type if the ldap server allows 'like'
- $exact = true;
- if ($CONFIG['ldap_public'][$server_name]['fuzzy_search'])
- $exact = isset($_POST['_ldap_public_search_type']) ? true : false;
-
- // perform an ldap search
- $contacts = rcmail_ldap_contact_search($search_value,
- $search_field,
- $CONFIG['ldap_public'][$server_name],
- $exact);
-
- // if no results, show a warning and return
- if (!$contacts)
- {
- show_message('nocontactsreturned', 'warning');
- return false;
- }
-
- // add id to message list table if not specified
- if (!strlen($attrib['id']))
- $attrib['id'] = 'ldapAddressList';
-
- // define table class
- $attrib['class'] = 'records-table';
- $attrib['cellspacing'] = 0;
-
- // define list of cols to be displayed
- $a_show_cols = array('name', 'email');
-
- // create XHTML table
- $out = rcube_table_output($attrib, $contacts, $a_show_cols, 'row_id');
-
- // set client env
- $javascript = "$JS_OBJECT_NAME.gui_object('ldapcontactslist', '{$attrib['id']}');\n";
- $OUTPUT->add_script($javascript);
-
- return $out;
- }
-
-/**
- * perform search for contacts from given public ldap server
- */
-function rcmail_ldap_contact_search($search_value, $search_field, $server, $exact=true)
- {
- global $CONFIG;
-
- $attributes = array($server['name_field'], $server['mail_field']);
-
- $LDAP = new rcube_ldap();
- if ($LDAP->connect($server['hosts'], $server['port'], $server['protocol']))
- {
- $filter = "$search_field=" . ($exact ? $search_value : "*$search_value*");
- $result = $LDAP->search($server['base_dn'],
- $filter,
- $attributes,
- $server['scope'],
- $sort=null);
-
- // add any results to contact array
- if ($result['count'])
- {
- for ($n = 0; $n < $result['count']; $n++)
- {
- $contacts[$n]['name'] = $result[$n][$server['name_field']][0];
- $contacts[$n]['email'] = $result[$n][$server['mail_field']][0];
- $contacts[$n]['row_id'] = $n + 1;
- }
- }
- }
- else
- return false;
-
- // cleanup
- $LDAP->close();
-
- if (!$result['count'])
- return false;
-
- // weed out duplicate emails
- for ($n = 0; $n < $result['count']; $n++)
- for ($i = 0; $i < $result['count']; $i++)
- if ($contacts[$i]['email'] == $contacts[$n]['email'] && $i != $n)
- unset($contacts[$n]);
-
- return $contacts;
- }
-
-function get_form_tags($attrib)
- {
- global $OUTPUT, $JS_OBJECT_NAME, $EDIT_FORM, $SESS_HIDDEN_FIELD;
-
- $form_start = '';
- if (!strlen($EDIT_FORM))
- {
- $hiddenfields = new hiddenfield(array('name' => '_task', 'value' => $GLOBALS['_task']));
- $hiddenfields->add(array('name' => '_action', 'value' => 'ldappublicsearch'));
-
- if ($_framed)
- $hiddenfields->add(array('name' => '_framed', 'value' => 1));
-
- $form_start .= !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
- $form_start .= "\n$SESS_HIDDEN_FIELD\n";
- $form_start .= $hiddenfields->show();
- }
-
- $form_end = (strlen($EDIT_FORM) && !strlen($attrib['form'])) ? '</form>' : '';
- $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
-
- $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('ldappublicsearchform', '$form_name');");
-
- $EDIT_FORM = $form_name;
-
- return array($form_start, $form_end);
- }
-
-parse_template('ldappublicsearch');
-?>
diff --git a/program/steps/addressbook/list.inc b/program/steps/addressbook/list.inc
index 0aa4873b3..71b9379b1 100644
--- a/program/steps/addressbook/list.inc
+++ b/program/steps/addressbook/list.inc
@@ -1,56 +1,35 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/addressbook/list.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Send contacts list to client (as remote response) |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
-
-// count contacts for this user
-$sql_result = $DB->query("SELECT COUNT(contact_id) AS rows
- FROM ".get_table_name('contacts')."
- WHERE del<>1
- AND user_id=?",
- $_SESSION['user_id']);
-
-$sql_arr = $DB->fetch_assoc($sql_result);
-$rowcount = $sql_arr['rows'];
+// get contacts for this user
+$result = $CONTACTS->list_records();
// update message count display
-$pages = ceil($rowcount/$CONFIG['pagesize']);
-$commands = sprintf("this.set_rowcount('%s');\n", rcmail_get_rowcount_text($rowcount));
-$commands .= sprintf("this.set_env('pagecount', %d);\n", $pages);
-
-$start_row = ($CONTACTS_LIST['page']-1) * $CONFIG['pagesize'];
+$OUTPUT->set_env('pagecount', ceil($result->count / $CONTACTS->page_size));
+$OUTPUT->command('set_rowcount', rcmail_get_rowcount_text($rowcount));
-// get contacts from DB
-$sql_result = $DB->limitquery("SELECT * FROM ".get_table_name('contacts')."
- WHERE del<>1
- AND user_id=?
- ORDER BY name",
- $start_row,
- $CONFIG['pagesize'],
- $_SESSION['user_id']);
-
-$commands .= rcmail_js_contacts_list($sql_result);
+// create javascript list
+rcmail_js_contacts_list($result);
// send response
-rcube_remote_response($commands);
+$OUTPUT->send();
-exit;
?>
\ No newline at end of file
diff --git a/program/steps/addressbook/mailto.inc b/program/steps/addressbook/mailto.inc
new file mode 100644
index 000000000..ddbec30d0
--- /dev/null
+++ b/program/steps/addressbook/mailto.inc
@@ -0,0 +1,48 @@
+<?php
+
+/*
+ +-----------------------------------------------------------------------+
+ | program/steps/addressbook/mailto.inc |
+ | |
+ | This file is part of the RoundCube Webmail client |
+ | Copyright (C) 2007, RoundCube Dev. - Switzerland |
+ | Licensed under the GNU GPL |
+ | |
+ | PURPOSE: |
+ | Compose a recipient list with all selected contacts |
+ | |
+ +-----------------------------------------------------------------------+
+ | Author: Thomas Bruederli <roundcube@gmail.com> |
+ +-----------------------------------------------------------------------+
+
+ $Id: copy.inc 471 2007-02-09 21:25:50Z thomasb $
+
+*/
+
+$cid = get_input_value('_cid', RCUBE_INPUT_GET);
+$recipients = null;
+$mailto = array();
+
+if ($cid && preg_match('/^[a-z0-9\-_=]+(,[a-z0-9\-_=]+)*$/i', $cid) && $CONTACTS->ready)
+{
+ $recipients = $CONTACTS->search($CONTACTS->primary_key, $cid);
+
+ while (is_object($recipients) && ($rec = $recipients->iterate()))
+ $mailto[] = format_email_recipient($rec['email'], $rec['name']);
+}
+
+if (!empty($mailto))
+{
+ $mailto_str = join(', ', $mailto);
+ $mailto_id = substr(md5($mailto_str), 0, 16);
+ $_SESSION['mailto'][$mailto_id] = $mailto_str;
+ $OUTPUT->command('redirect', rcmail_self_url('compose', array('_mailto' => $mailto_id), 'mail'));
+}
+else
+ $OUTPUT->show_message('nocontactsfound', 'warning');
+
+
+// send response
+$OUTPUT->send();
+
+?>
\ No newline at end of file
diff --git a/program/steps/addressbook/save.inc b/program/steps/addressbook/save.inc
index a50d0388a..72e54b173 100644
--- a/program/steps/addressbook/save.inc
+++ b/program/steps/addressbook/save.inc
@@ -1,258 +1,126 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/addressbook/save.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Save a contact entry or to add a new one |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
+// cannot edit record
+if ($CONTACTS->readonly)
+{
+ $OUTPUT->show_message('contactreadonly', 'error');
+ rcmail_overwrite_action(empty($_POST['_cid']) ? 'add' : 'show');
+ return;
+}
+
// check input
-if ((empty($_POST['_name']) || empty($_POST['_email'])) && empty($_GET['_framed']))
- {
- show_message('formincomplete', 'warning');
+if ((!get_input_value('_name', RCUBE_INPUT_POST) || !get_input_value('_email', RCUBE_INPUT_POST)) && $_framed)
+{
+ $OUTPUT->show_message('formincomplete', 'warning');
rcmail_overwrite_action(empty($_POST['_cid']) ? 'add' : 'show');
return;
- }
+}
+
// setup some vars we need
$a_save_cols = array('name', 'firstname', 'surname', 'email');
-$contacts_table = get_table_name('contacts');
+$a_record = array();
+$cid = get_input_value('_cid', RCUBE_INPUT_POST);
+
+// read POST values into hash array
+foreach ($a_save_cols as $col)
+{
+ $fname = '_'.$col;
+ if (isset($_POST[$fname]))
+ $a_record[$col] = get_input_value($fname, RCUBE_INPUT_POST);
+}
// update an existing contact
-if (!empty($_POST['_cid']))
+if (!empty($cid))
+{
+ if ($CONTACTS->update($cid, $a_record))
{
- $a_write_sql = array();
-
- foreach ($a_save_cols as $col)
- {
- $fname = '_'.$col;
- if (!isset($_POST[$fname]))
- continue;
-
- $a_write_sql[] = sprintf("%s=%s",
- $DB->quoteIdentifier($col),
- $DB->quote(get_input_value($fname, RCUBE_INPUT_POST)));
- }
-
- if (sizeof($a_write_sql))
- {
- $DB->query("UPDATE $contacts_table
- SET changed=".$DB->now().", ".join(', ', $a_write_sql)."
- WHERE contact_id=?
- AND user_id=?
- AND del<>1",
- $_POST['_cid'],
- $_SESSION['user_id']);
-
- $updated = $DB->affected_rows();
- }
-
- if ($updated)
- {
if ($_framed)
- {
+ {
// define list of cols to be displayed
- $a_show_cols = array('name', 'email');
$a_js_cols = array();
-
- $sql_result = $DB->query("SELECT * FROM $contacts_table
- WHERE contact_id=?
- AND user_id=?
- AND del<>1",
- $_POST['_cid'],
- $_SESSION['user_id']);
-
- $sql_arr = $DB->fetch_assoc($sql_result);
- foreach ($a_show_cols as $col)
- $a_js_cols[] = (string)$sql_arr[$col];
+ $record = $CONTACTS->get_record($cid, true);
- // update the changed col in list
- $OUTPUT->add_script(sprintf("if(parent.%s)parent.%s.update_contact_row('%d', %s);",
- $JS_OBJECT_NAME,
- $JS_OBJECT_NAME,
- $_POST['_cid'],
- array2js($a_js_cols)));
+ foreach (array('name', 'email') as $col)
+ $a_js_cols[] = (string)$record[$col];
- }
+ // update the changed col in list
+ $OUTPUT->command('parent.update_contact_row', $cid, $a_js_cols);
+ }
// show confirmation
- show_message('successfullysaved', 'confirmation');
+ $OUTPUT->show_message('successfullysaved', 'confirmation');
rcmail_overwrite_action('show');
- }
+ }
else
- {
+ {
// show error message
- show_message('errorsaving', 'error');
+ $OUTPUT->show_message('errorsaving', 'error');
rcmail_overwrite_action('show');
- }
}
+}
// insert a new contact
else
- {
- $a_insert_cols = $a_insert_values = array();
-
+{
// check for existing contacts
- $sql = "SELECT 1 FROM $contacts_table
- WHERE user_id = {$_SESSION['user_id']}
- AND del <> '1' ";
-
- // get email and name, build sql for existing user check
- if (isset($_GET['_emails']) && isset($_GET['_names']))
- {
- $sql .= "AND email IN (";
- $emails = explode(',', get_input_value('_emails', RCUBE_INPUT_GET));
- $names = explode(',', get_input_value('_names', RCUBE_INPUT_GET));
- $count = count($emails);
- $n = 0;
- foreach ($emails as $email)
- {
- $end = (++$n == $count) ? '' : ',';
- $sql .= $DB->quote($email) . $end;
- }
- $sql .= ")";
- $ldap_form = true;
- }
- else if (isset($_POST['_email']))
- $sql .= "AND email = " . $DB->quote(get_input_value('_email', RCUBE_INPUT_POST));
-
- $sql_result = $DB->query($sql);
-
+ $existing = $CONTACTS->search('email', $a_record['email'], false);
+
// show warning message
- if ($DB->num_rows($sql_result))
- {
- show_message('contactexists', 'warning');
-
- if ($ldap_form)
- rcmail_overwrite_action('ldappublicsearch');
- else
- rcmail_overwrite_action('add');
-
+ if ($existing->count)
+ {
+ $OUTPUT->show_message('contactexists', 'warning');
+ rcmail_overwrite_action('add');
return;
- }
+ }
- if ($ldap_form)
- {
- $n = 0;
- foreach ($emails as $email)
- {
- $DB->query("INSERT INTO $contacts_table
- (user_id, name, email)
- VALUES ({$_SESSION['user_id']}," . $DB->quote($names[$n++]) . "," .
- $DB->quote($email) . ")");
- $insert_id[] = $DB->insert_id();
- }
- }
- else
- {
- foreach ($a_save_cols as $col)
- {
- $fname = '_'.$col;
- if (!isset($_POST[$fname]))
- continue;
-
- $a_insert_cols[] = $col;
- $a_insert_values[] = $DB->quote(get_input_value($fname, RCUBE_INPUT_POST));
- }
-
- if (sizeof($a_insert_cols))
- {
- $DB->query("INSERT INTO $contacts_table
- (user_id, changed, del, ".join(', ', $a_insert_cols).")
- VALUES (?, ".$DB->now().", 0, ".join(', ', $a_insert_values).")",
- $_SESSION['user_id']);
-
- $insert_id = $DB->insert_id(get_sequence_name('contacts'));
- }
- }
-
- if ($insert_id)
+ // insert record and send response
+ if ($insert_id = $CONTACTS->insert($a_record))
+ {
+ if ($_framed)
{
- if (!$ldap_form)
- {
- if ($_framed)
- {
- // add contact row or jump to the page where it should appear
- $commands = sprintf("if(parent.%s)parent.", $JS_OBJECT_NAME);
- $sql_result = $DB->query("SELECT * FROM $contacts_table
- WHERE contact_id=?
- AND user_id=?",
- $insert_id,
- $_SESSION['user_id']);
- $commands .= rcmail_js_contacts_list($sql_result, $JS_OBJECT_NAME);
-
- $commands .= sprintf("if(parent.%s)parent.%s.contact_list.select('%d');\n",
- $JS_OBJECT_NAME,
- $JS_OBJECT_NAME,
- $insert_id);
-
- // update record count display
- $commands .= sprintf("if(parent.%s)parent.%s.set_rowcount('%s');\n",
- $JS_OBJECT_NAME,
- $JS_OBJECT_NAME,
- rcmail_get_rowcount_text());
-
- $OUTPUT->add_script($commands);
- }
-
- // show confirmation
- show_message('successfullysaved', 'confirmation');
- $_GET['_cid'] = $insert_id;
- }
- else
- {
// add contact row or jump to the page where it should appear
- $commands = '';
- foreach ($insert_id as $id)
- {
- $sql_result = $DB->query("SELECT * FROM $contacts_table
- WHERE contact_id = $id
- AND user_id = {$_SESSION['user_id']}");
-
- $commands .= sprintf("if(parent.%s)parent.", $JS_OBJECT_NAME);
- $commands .= rcmail_js_contacts_list($sql_result, $JS_OBJECT_NAME);
- $last_id = $id;
- }
+ $CONTACTS->reset();
+ $result = $CONTACTS->search($CONTACTS->primary_key, $insert_id);
- // display the last insert id
- $commands .= sprintf("if(parent.%s)parent.%s.contact_list.select('%d');\n",
- $JS_OBJECT_NAME,
- $JS_OBJECT_NAME,
- $last_id);
+ rcmail_js_contacts_list($result, 'parent.');
+ $OUTPUT->command('parent.contact_list.select', $insert_id);
// update record count display
- $commands .= sprintf("if(parent.%s)parent.%s.set_rowcount('%s');\n",
- $JS_OBJECT_NAME,
- $JS_OBJECT_NAME,
- rcmail_get_rowcount_text());
-
- $OUTPUT->add_script($commands);
- rcmail_overwrite_action('ldappublicsearch');
- }
+ $CONTACTS->reset();
+ $OUTPUT->command('parent.set_rowcount', rcmail_get_rowcount_text());
+ }
// show confirmation
- show_message('successfullysaved', 'confirmation');
+ $OUTPUT->show_message('successfullysaved', 'confirmation');
rcmail_overwrite_action('show');
- }
+ $_GET['_cid'] = $insert_id;
+ }
else
- {
+ {
// show error message
- show_message('errorsaving', 'error');
+ $OUTPUT->show_message('errorsaving', 'error');
rcmail_overwrite_action('add');
- }
}
+}
?>
diff --git a/program/steps/addressbook/search.inc b/program/steps/addressbook/search.inc
new file mode 100644
index 000000000..01233a0bd
--- /dev/null
+++ b/program/steps/addressbook/search.inc
@@ -0,0 +1,53 @@
+<?php
+
+/*
+ +-----------------------------------------------------------------------+
+ | program/steps/addressbook/search.inc |
+ | |
+ | This file is part of the RoundCube Webmail client |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
+ | Licensed under the GNU GPL |
+ | |
+ | PURPOSE: |
+ | Search step for address book contacts |
+ | |
+ +-----------------------------------------------------------------------+
+ | Author: Thomas Bruederli <roundcube@gmail.com> |
+ +-----------------------------------------------------------------------+
+
+ $Id: search.inc 456 2007-01-10 12:34:33Z thomasb $
+
+*/
+
+$CONTACTS->set_page(1);
+$_SESSION['page'] = 1;
+
+$search = trim(get_input_value('_q', RCUBE_INPUT_GET));
+$search_request = md5('addr'.$search);
+
+// get contacts for this user
+$result = $CONTACTS->search(array('name','email'), $search);
+
+if ($result->count > 0)
+{
+ // save search settings in session
+ $_SESSION['search'][$search_request] = $CONTACTS->get_search_set();
+
+ // create javascript list
+ rcmail_js_contacts_list($result);
+}
+else
+{
+ $OUTPUT->show_message('nocontactsfound', 'warning');
+ $search_request = -1;
+}
+
+// update message count display
+$OUTPUT->set_env('search_request', $search_request);
+$OUTPUT->set_env('pagecount', ceil($result->count / $CONTACTS->page_size));
+$OUTPUT->command('set_rowcount', rcmail_get_rowcount_text());
+
+// send response
+$OUTPUT->send();
+
+?>
\ No newline at end of file
diff --git a/program/steps/addressbook/show.inc b/program/steps/addressbook/show.inc
index 960ea1c45..75f1e7452 100644
--- a/program/steps/addressbook/show.inc
+++ b/program/steps/addressbook/show.inc
@@ -1,80 +1,73 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/addressbook/show.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Show contact details |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-if ($_GET['_cid'] || $_POST['_cid'])
- {
- $cid = $_POST['_cid'] ? $_POST['_cid'] : $_GET['_cid'];
- $DB->query("SELECT * FROM ".get_table_name('contacts')."
- WHERE contact_id=?
- AND user_id=?
- AND del<>1",
- $cid,
- $_SESSION['user_id']);
-
- $CONTACT_RECORD = $DB->fetch_assoc();
-
- if (is_array($CONTACT_RECORD))
- $OUTPUT->add_script(sprintf("%s.set_env('cid', '%s');", $JS_OBJECT_NAME, $CONTACT_RECORD['contact_id']));
- }
-
+// read contact record
+if (($cid = get_input_value('_cid', RCUBE_INPUT_GPC)) && ($record = $CONTACTS->get_record($cid, true)))
+ $OUTPUT->set_env('cid', $record['ID']);
function rcmail_contact_details($attrib)
{
- global $CONTACT_RECORD, $JS_OBJECT_NAME;
+ global $CONTACTS, $OUTPUT;
- if (!$CONTACT_RECORD)
- return show_message('contactnotfound');
+ // check if we have a valid result
+ if (!(($result = $CONTACTS->get_result()) && ($record = $result->first())))
+ {
+ $OUTPUT->show_message('contactnotfound');
+ return false;
+ }
// a specific part is requested
if ($attrib['part'])
- return rep_specialchars_output($CONTACT_RECORD[$attrib['part']]);
-
+ return Q($record[$attrib['part']]);
// return the complete address record as table
$out = "<table>\n\n";
$a_show_cols = array('name', 'firstname', 'surname', 'email');
foreach ($a_show_cols as $col)
{
- if ($col=='email' && $CONTACT_RECORD[$col])
- $value = sprintf('<a href="#compose" onclick="%s.command(\'compose\', %d)" title="%s">%s</a>',
- $JS_OBJECT_NAME,
- $CONTACT_RECORD['contact_id'],
- rcube_label('composeto'),
- $CONTACT_RECORD[$col]);
+ if ($col=='email' && !empty($record[$col]))
+ $value = sprintf(
+ '<a href="#compose" onclick="%s.command(\'compose\', \'%s\')" title="%s">%s</a>',
+ JS_OBJECT_NAME,
+ JQ($record[$col]),
+ rcube_label('composeto'),
+ Q($record[$col]));
else
- $value = rep_specialchars_output($CONTACT_RECORD[$col]);
+ $value = Q($record[$col]);
- $title = rcube_label($col);
- $out .= sprintf("<tr><td class=\"title\">%s</td><td>%s</td></tr>\n", $title, $value);
+ $out .= sprintf("<tr><td class=\"title\">%s</td><td>%s</td></tr>\n",
+ Q(rcube_label($col)),
+ $value);
}
-
-
+
$out .= "\n</table>";
return $out;
}
-parse_template('showcontact');
+//$OUTPUT->framed = $_framed;
+$OUTPUT->add_handler('contactdetails', 'rcmail_contact_details');
+$OUTPUT->send('showcontact');
?>
\ No newline at end of file
diff --git a/program/steps/error.inc b/program/steps/error.inc
index 2eb50eb7b..dd533060a 100644
--- a/program/steps/error.inc
+++ b/program/steps/error.inc
@@ -1,127 +1,127 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/error.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Display error message page |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
// browser is not compatible with this application
if ($ERROR_CODE==409)
{
$user_agent = $GLOBALS['HTTP_SERVER_VARS']['HTTP_USER_AGENT'];
$__error_title = 'Your browser does not suit the requirements for this application';
$__error_text = <<<EOF
<i>Supported browsers:</i><br />
&raquo; &nbsp;Netscape 7+<br />
&raquo; &nbsp;Microsoft Internet Explorer 6+<br />
&raquo; &nbsp;Mozilla Firefox 1.0+<br />
&raquo; &nbsp;Opera 8.0+<br />
&raquo; &nbsp;Safari 1.2+<br />
<br />
&raquo; &nbsp;JavaScript enabled<br />
&raquo; &nbsp;Support for XMLHTTPRequest<br />
<p><i>Your configuration:</i><br />
$user_agent</p>
EOF;
}
// authorization error
else if ($ERROR_CODE==401)
{
$__error_title = "AUTHORIZATION FAILED";
$__error_text = "Could not verify that you are authorized to access this service!<br />\n".
"Please contact your server-administrator.";
}
// failed request (wrong step in URL)
else if ($ERROR_CODE==404)
{
$__error_title = "REQUEST FAILED/FILE NOT FOUND";
$request_url = htmlentities($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$__error_text = <<<EOF
The requested page was not found!<br />
Please contact your server-administrator.
<p><i>Failed request:</i><br />
http://$request_url</p>
EOF;
}
// database connection error
-else if ($ERROR_CODE==0x01f4)
+else if ($ERROR_CODE==603)
{
$__error_title = "DATABASE ERROR: CONNECTION FAILED!";
$__error_text = <<<EOF
Unable to connect to the database!<br />
Please contact your server-administrator.
EOF;
}
// system error
else
{
$__error_title = "SERVICE CURRENTLY NOT AVAILABLE!";
$__error_text = "Please contact your server-administrator.";
if (($CONFIG['debug_level'] & 4) && $ERROR_MESSAGE)
$__error_text = $ERROR_MESSAGE;
else
$__error_text = sprintf('Error No. [0x%04X]', $ERROR_CODE);
}
// compose page content
$__page_content = <<<EOF
<div>
<h3 class="error-title">$__error_title</h3>
<p class="error-text">$__error_text</p>
</div>
EOF;
if (template_exists('error'))
{
$OUTPUT->scripts = array();
$OUTPUT->script_files = array();
parse_template('error');
}
// print system error page
print <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title>RoundCube|Mail : ERROR $ERROR_CODE</title>
<link rel="stylesheet" type="text/css" href="program/style.css" />
</head>
<body>
<table border="0" cellsapcing="0" cellpadding="0" width="100%" height="80%"><tr><td align="center">
$__page_content
</td></tr></table>
</body>
</html>
EOF;
?>
\ No newline at end of file
diff --git a/program/steps/mail/addcontact.inc b/program/steps/mail/addcontact.inc
index b040581aa..484b0d4ba 100644
--- a/program/steps/mail/addcontact.inc
+++ b/program/steps/mail/addcontact.inc
@@ -1,67 +1,55 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/addcontact.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Add the submitted contact to the users address book |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
+require_once('include/rcube_contacts.inc');
-if (!empty($_GET['_address']))
- {
- $contact_arr = $IMAP->decode_address_list(get_input_value('_address', RCUBE_INPUT_GET, TRUE));
- if (sizeof($contact_arr))
- {
- $contact = $contact_arr[1];
-
- if ($contact['mailto'])
- $sql_result = $DB->query("SELECT 1 FROM ".get_table_name('contacts')."
- WHERE user_id=?
- AND email=?
- AND del<>1",
- $_SESSION['user_id'],$contact['mailto']);
-
- // contact entry with this mail address exists
- if ($sql_result && $DB->num_rows($sql_result))
- $existing_contact = TRUE;
-
- else if ($contact['mailto'])
- {
- $DB->query("INSERT INTO ".get_table_name('contacts')."
- (user_id, changed, del, name, email)
- VALUES (?, ".$DB->now().", 0, ?, ?)",
- $_SESSION['user_id'],
- $contact['name'],
- $contact['mailto']);
+$done = false;
- $added = $DB->insert_id(get_sequence_name('contacts'));
- }
- }
-
- if ($added)
- $commands = show_message('addedsuccessfully', 'confirmation');
- else if ($existing_contact)
- $commands = show_message('contactexists', 'warning');
+if (!empty($_POST['_address']))
+{
+ $CONTACTS = new rcube_contacts($DB, $_SESSION['user_id']);
+ $contact_arr = $IMAP->decode_address_list(get_input_value('_address', RCUBE_INPUT_POST, true), 1, false);
+
+ if (!empty($contact_arr[1]['mailto']))
+ {
+ $contact = array(
+ 'email' => $contact_arr[1]['mailto'],
+ 'name' => $contact_arr[1]['name']
+ );
+
+ // use email address part for name
+ if (empty($contact['name']) || $contact['name'] == $contact['email'])
+ $contact['name'] = ucfirst(preg_replace('/[\.\-]/', ' ', substr($contact['email'], 0, strpos($contact['email'], '@'))));
+
+ // check for existing contacts
+ $existing = $CONTACTS->search('email', $contact['email'], false);
+ if ($done = $existing->count)
+ $OUTPUT->show_message('contactexists', 'warning');
+ else if ($done = $CONTACTS->insert($contact))
+ $OUTPUT->show_message('addedsuccessfully', 'confirmation');
}
+}
+if (!$done)
+ $OUTPUT->show_message('errorsavingcontact', 'warning');
-if (!$commands)
- $commands = show_message('errorsavingcontact', 'warning');
-
-rcube_remote_response($commands);
-exit;
+$OUTPUT->send();
?>
\ No newline at end of file
diff --git a/program/steps/mail/check_recent.inc b/program/steps/mail/check_recent.inc
index ca35725ea..119d481ab 100644
--- a/program/steps/mail/check_recent.inc
+++ b/program/steps/mail/check_recent.inc
@@ -1,60 +1,59 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/check_recent.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Check for recent messages, in all mailboxes |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id: check_recent.inc 233 2006-06-26 17:31:20Z richs $
*/
-$REMOTE_REQUEST = TRUE;
-
$a_mailboxes = $IMAP->list_mailboxes();
foreach ($a_mailboxes as $mbox_name)
{
if ($mbox_name == $IMAP->get_mailbox_name())
{
if ($recent_count = $IMAP->messagecount(NULL, 'RECENT', TRUE))
{
$count = $IMAP->messagecount(NULL, 'ALL', TRUE);
$unread_count = $IMAP->messagecount(NULL, 'UNSEEN', TRUE);
- $commands .= sprintf("this.set_unread_count('%s', %d);\n", addslashes($mbox_name), $unread_count);
- $commands .= sprintf("this.set_env('messagecount', %d);\n", $count);
- $commands .= sprintf("this.set_rowcount('%s');\n", rcmail_get_messagecount_text($count));
- $commands .= sprintf("this.set_quota('%s');\n", $IMAP->get_quota());
+ $OUTPUT->set_env('messagecount', $count);
+ $OUTPUT->command('set_unread_count', $mbox_name, $unread_count);
+ $OUTPUT->command('set_rowcount', rcmail_get_messagecount_text());
+ $OUTPUT->command('set_quota', $IMAP->get_quota());
// add new message headers to list
$a_headers = array();
for ($i=$recent_count, $id=$count-$recent_count+1; $i>0; $i--, $id++)
{
$header = $IMAP->get_headers($id, NULL, FALSE);
if ($header->recent)
$a_headers[] = $header;
}
- $commands .= rcmail_js_message_list($a_headers, TRUE);
+ rcmail_js_message_list($a_headers, TRUE);
}
}
else
{
if ($IMAP->messagecount($mbox_name, 'RECENT'))
- $commands .= sprintf("this.set_unread_count('%s', %d);\n", addslashes($mbox_name), $IMAP->messagecount($mbox_name, 'UNSEEN'));
+ $OUTPUT->command('set_unread_count', $mbox_name, $IMAP->messagecount($mbox_name, 'UNSEEN'));
}
}
-rcube_remote_response($commands);
+$OUTPUT->send();
+
?>
diff --git a/program/steps/mail/compose.inc b/program/steps/mail/compose.inc
index 24057a224..4e73b4ba1 100644
--- a/program/steps/mail/compose.inc
+++ b/program/steps/mail/compose.inc
@@ -1,905 +1,889 @@
<?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');
require_once('lib/html2text.inc');
// define constants for message compose mode
define('RCUBE_COMPOSE_REPLY', 0x0106);
define('RCUBE_COMPOSE_FORWARD', 0x0107);
define('RCUBE_COMPOSE_DRAFT', 0x0108);
// remove an attachment
if ($_action=='remove-attachment' && preg_match('/^rcmfile([0-9]+)$/', $_GET['_file'], $regs))
{
$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);
+ $OUTPUT->command('remove_from_attachment_list', "rcmfile$id");
+ $OUTPUT->send();
exit;
}
}
$MESSAGE_FORM = NULL;
$MESSAGE = NULL;
// Nothing below is called during message composition, only at "new/forward/reply/draft" initialization or
// if a compose-ID is given (i.e. when the compose step is opened in a new window/tab).
// 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
if (!is_array($_SESSION['compose']) || $_SESSION['compose']['id'] != get_input_value('_id', RCUBE_INPUT_GET))
{
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', 'converting');
// add config parameter to client script
-$OUTPUT->add_script(sprintf("%s.set_env('draft_autosave', %d);", $JS_OBJECT_NAME, !empty($CONFIG['drafts_mbox']) ? $CONFIG['draft_autosave'] : 0));
+$OUTPUT->set_env('draft_autosave', !empty($CONFIG['drafts_mbox']) ? $CONFIG['draft_autosave'] : 0);
// get reference message and set compose mode
if ($msg_uid = get_input_value('_reply_uid', RCUBE_INPUT_GET))
$compose_mode = RCUBE_COMPOSE_REPLY;
else if ($msg_uid = get_input_value('_forward_uid', RCUBE_INPUT_GET))
$compose_mode = RCUBE_COMPOSE_FORWARD;
else if ($msg_uid = get_input_value('_draft_uid', RCUBE_INPUT_GET))
$compose_mode = RCUBE_COMPOSE_DRAFT;
if (!empty($msg_uid))
{
// similar as in program/steps/mail/show.inc
$MESSAGE = array('UID' => $msg_uid);
$MESSAGE['headers'] = &$IMAP->get_headers($msg_uid);
$MESSAGE['structure'] = &$IMAP->get_structure($msg_uid);
$MESSAGE['subject'] = $IMAP->decode_header($MESSAGE['headers']->subject);
$MESSAGE['parts'] = $IMAP->get_mime_numbers($MESSAGE['structure']);
if ($compose_mode == RCUBE_COMPOSE_REPLY)
{
$_SESSION['compose']['reply_uid'] = $msg_uid;
$_SESSION['compose']['reply_msgid'] = $MESSAGE['headers']->messageID;
$_SESSION['compose']['references'] = $MESSAGE['headers']->reference;
$_SESSION['compose']['references'] .= !empty($MESSAGE['headers']->reference) ? ' ' : '';
$_SESSION['compose']['references'] .= $MESSAGE['headers']->messageID;
if (!empty($_GET['_all']))
$MESSAGE['reply_all'] = 1;
}
else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
{
$_SESSION['compose']['forward_uid'] = $msg_uid;
}
else if ($compose_mode == RCUBE_COMPOSE_DRAFT)
{
$_SESSION['compose']['draft_uid'] = $msg_uid;
}
}
/****** compose mode functions ********/
function rcmail_compose_headers($attrib)
{
global $IMAP, $MESSAGE, $DB, $compose_mode;
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);
- }
+
+ // we have a set of recipients stored is session
+ if (($mailto_id = get_input_value('_mailto', RCUBE_INPUT_GET)) && $_SESSION['mailto'][$mailto_id])
+ $fvalue = $_SESSION['mailto'][$mailto_id];
else if (!empty($_GET['_to']))
$fvalue = get_input_value('_to', RCUBE_INPUT_GET);
case 'cc':
if (!$fname)
{
$fname = '_cc';
$header = 'cc';
}
case 'bcc':
if (!$fname)
{
$fname = '_bcc';
$header = '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 && $compose_mode == RCUBE_COMPOSE_REPLY)
{
// get recipent address(es) out of the message headers
if ($header=='to' && !empty($MESSAGE['headers']->replyto))
$fvalue = $MESSAGE['headers']->replyto;
else if ($header=='to' && !empty($MESSAGE['headers']->from))
$fvalue = $MESSAGE['headers']->from;
// add recipent of original message if reply to all
else if ($header=='cc' && !empty($MESSAGE['reply_all']))
{
if ($v = $MESSAGE['headers']->to)
$fvalue .= $v;
if ($v = $MESSAGE['headers']->cc)
$fvalue .= (!empty($fvalue) ? ', ' : '') . $v;
}
// 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 (!empty($addr_part['mailto']) && !in_array($addr_part['mailto'], $sa_recipients) && (!$MESSAGE['FROM'] || !in_array($addr_part['mailto'], $MESSAGE['FROM'])))
{
$fvalue .= (strlen($fvalue) ? ', ':'').$addr_part['string'];
$sa_recipients[] = $addr_part['mailto'];
}
}
}
}
else if ($header && $compose_mode == RCUBE_COMPOSE_DRAFT)
{
// get drafted headers
if ($header=='to' && !empty($MESSAGE['headers']->to))
$fvalue = $IMAP->decode_header($MESSAGE['headers']->to);
if ($header=='cc' && !empty($MESSAGE['headers']->cc))
$fvalue = $IMAP->decode_header($MESSAGE['headers']->cc);
if ($header=='bcc' && !empty($MESSAGE['headers']->bcc))
$fvalue = $IMAP->decode_header($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, $MESSAGE, $DB, $OUTPUT, $JS_OBJECT_NAME, $compose_mode;
+ global $IMAP, $MESSAGE, $DB, $OUTPUT, $compose_mode;
// 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 ($compose_mode == RCUBE_COMPOSE_REPLY && is_object($MESSAGE['headers']))
{
$MESSAGE['FROM'] = array();
$a_to = $IMAP->decode_address_list($MESSAGE['headers']->to);
foreach ($a_to as $addr)
{
if (!empty($addr['mailto']))
$a_recipients[] = $addr['mailto'];
}
if (!empty($MESSAGE['headers']->cc))
{
$a_cc = $IMAP->decode_address_list($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, html_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)";
+ $field_attrib['onchange'] = JS_OBJECT_NAME.".change_identity(this)";
$select_from = new select($field_attrib);
while ($sql_arr = $DB->fetch_assoc($sql_result))
{
$identity_id = $sql_arr['identity_id'];
$select_from->add(format_email_recipient($sql_arr['email'], $sql_arr['name']), $identity_id);
// add signature to array
if (!empty($sql_arr['signature']))
{
$a_signatures[$identity_id]['text'] = $sql_arr['signature'];
$a_signatures[$identity_id]['is_html'] = ($sql_arr['html_signature'] == 1) ? true : false;
if ($a_signatures[$identity_id]['is_html'])
{
$h2t = new html2text($a_signatures[$identity_id]['text'], false, false);
$plainTextPart = $h2t->get_text();
$a_signatures[$identity_id]['plain_text'] = trim($plainTextPart);
}
}
// 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 ($compose_mode == RCUBE_COMPOSE_REPLY && is_array($MESSAGE['FROM']))
$MESSAGE['FROM'][] = $sql_arr['email'];
if ($compose_mode == RCUBE_COMPOSE_DRAFT && strstr($MESSAGE['headers']->from, $sql_arr['email']))
$from_id = $sql_arr['identity_id'];
}
// overwrite identity selection with post parameter
if (isset($_POST['_from']))
$from_id = get_input_value('_from', RCUBE_INPUT_POST);
$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)));
+ $OUTPUT->set_env('signatures', $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, $MESSAGE, $JS_OBJECT_NAME, $compose_mode;
+ global $CONFIG, $OUTPUT, $MESSAGE, $compose_mode;
list($form_start, $form_end) = get_form_tags($attrib);
unset($attrib['form']);
if (empty($attrib['id']))
$attrib['id'] = 'rcmComposeMessage';
$attrib['name'] = '_message';
if ($CONFIG['htmleditor'])
$isHtml = true;
else
$isHtml = false;
$body = '';
// use posted message body
if (!empty($_POST['_message']))
{
$body = get_input_value('_message', RCUBE_INPUT_POST, TRUE);
}
// compose reply-body
else if ($compose_mode == RCUBE_COMPOSE_REPLY)
{
$hasHtml = rcmail_has_html_part($MESSAGE['parts']);
if ($hasHtml && $CONFIG['htmleditor'])
{
$body = rcmail_first_html_part($MESSAGE);
$isHtml = true;
}
else
{
$body = rcmail_first_text_part($MESSAGE);
$isHtml = false;
}
$body = rcmail_create_reply_body($body, $isHtml);
}
// forward message body inline
else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
{
$hasHtml = rcmail_has_html_part($MESSAGE['parts']);
if ($hasHtml && $CONFIG['htmleditor'])
{
$body = rcmail_first_html_part($MESSAGE);
$isHtml = true;
}
else
{
$body = rcmail_first_text_part($MESSAGE);
$isHtml = false;
}
$body = rcmail_create_forward_body($body, $isHtml);
}
else if ($compose_mode == RCUBE_COMPOSE_DRAFT)
{
$hasHtml = rcmail_has_html_part($MESSAGE['parts']);
if ($hasHtml && $CONFIG['htmleditor'])
{
$body = rcmail_first_html_part($MESSAGE);
$isHtml = true;
}
else
{
$body = rcmail_first_text_part($MESSAGE);
$isHtml = false;
}
$body = rcmail_create_draft_body($body, $isHtml);
}
$OUTPUT->include_script('tiny_mce/tiny_mce.js');
$OUTPUT->include_script("editor.js");
$OUTPUT->add_script('rcmail_editor_init("$__skin_path");');
$out = $form_start ? "$form_start\n" : '';
$saveid = new hiddenfield(array('name' => '_draft_saveid', 'value' => $compose_mode==RCUBE_COMPOSE_DRAFT ? str_replace(array('<','>'), "", $MESSAGE['headers']->messageID) : ''));
$out .= $saveid->show();
$drafttoggle = new hiddenfield(array('name' => '_draft', 'value' => 'yes'));
$out .= $drafttoggle->show();
$msgtype = new hiddenfield(array('name' => '_is_html', 'value' => ($isHtml?"1":"0")));
$out .= $msgtype->show();
// If desired, set this text area to be editable by TinyMCE
if ($isHtml)
$attrib['mce_editable'] = "true";
$textarea = new textarea($attrib);
$out .= $textarea->show($body);
$out .= $form_end ? "\n$form_end" : '';
// include GoogieSpell
if (!empty($CONFIG['enable_spellcheck']) && !$isHtml)
{
$lang_set = '';
if (!empty($CONFIG['spellcheck_languages']) && is_array($CONFIG['spellcheck_languages']))
$lang_set = "googie.setLanguages(".array2js($CONFIG['spellcheck_languages']).");\n";
$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%s".
"googie.setCurrentLanguage('%s');\n".
"googie.decorateTextarea('%s');\n".
"%s.set_env('spellcheck', googie);",
$GLOBALS['COMM_PATH'],
JQ(Q(rcube_label('checkspelling'))),
JQ(Q(rcube_label('resumeediting'))),
JQ(Q(rcube_label('close'))),
JQ(Q(rcube_label('revertto'))),
JQ(Q(rcube_label('nospellerrors'))),
$lang_set,
substr($_SESSION['user_lang'], 0, 2),
$attrib['id'],
- $JS_OBJECT_NAME), 'foot');
+ 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, $bodyIsHtml)
{
global $IMAP, $MESSAGE;
if (! $bodyIsHtml)
{
// 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
$prefix = sprintf("\n\n\nOn %s, %s wrote:\n",
$MESSAGE['headers']->date,
$IMAP->decode_header($MESSAGE['headers']->from));
// try to remove the signature
if ($sp = strrstr($body, '-- '))
{
if ($body{$sp+3}==' ' || $body{$sp+3}=="\n" || $body{$sp+3}=="\r")
$body = substr($body, 0, $sp-1);
}
$suffix = '';
}
else
{
$prefix = sprintf("<br><br>On %s, %s wrote:<br><blockquote type=\"cite\" " .
"style=\"padding-left: 5px; border-left: #1010ff 2px solid; " .
"margin-left: 5px; width: 100%%\">",
$MESSAGE['headers']->date,
$IMAP->decode_header($MESSAGE['headers']->from));
$suffix = "</blockquote>";
}
return $prefix.$body.$suffix;
}
function rcmail_create_forward_body($body, $bodyIsHtml)
{
global $IMAP, $MESSAGE;
if (! $bodyIsHtml)
{
// 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",
$MESSAGE['subject'],
$MESSAGE['headers']->date,
$IMAP->decode_header($MESSAGE['headers']->from),
$IMAP->decode_header($MESSAGE['headers']->to));
}
else
{
$prefix = sprintf(
"<br><br>-------- Original Message --------" .
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" .
"<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Subject: </th><td>%s</td></tr>" .
"<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Date: </th><td>%s</td></tr>" .
"<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">From: </th><td>%s</td></tr>" .
"<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">To: </th><td>%s</td></tr>" .
"</tbody></table><br>",
Q($MESSAGE['subject']),
Q($MESSAGE['headers']->date),
Q($IMAP->decode_header($MESSAGE['headers']->from)),
Q($IMAP->decode_header($MESSAGE['headers']->to)));
}
// add attachments
if (!isset($_SESSION['compose']['forward_attachments']) && is_array($MESSAGE['parts']))
rcmail_write_compose_attachments($MESSAGE);
return $prefix.$body;
}
function rcmail_create_draft_body($body, $bodyIsHtml)
{
global $IMAP, $MESSAGE;
// add attachments
if (!isset($_SESSION['compose']['forward_attachments']) &&
is_array($MESSAGE['parts']) && sizeof($MESSAGE['parts'])>1)
rcmail_write_compose_attachments($MESSAGE);
return $body;
}
function rcmail_write_compose_attachments(&$message)
{
global $IMAP, $CONFIG;
$temp_dir = unslashify($CONFIG['temp_dir']);
if (!is_array($_SESSION['compose']['attachments']))
$_SESSION['compose']['attachments'] = array();
foreach ($message['parts'] as $pid => $part)
{
if ($part->ctype_primary != 'message' && $part->ctype_primary != 'text' &&
($part->disposition=='attachment' || $part->disposition=='inline' || $part->headers['content-id'] ||
(empty($part->disposition) && $part->filename)))
{
$tmp_path = tempnam($temp_dir, 'rcmAttmnt');
if ($fp = fopen($tmp_path, 'w'))
{
fwrite($fp, $IMAP->get_message_part($message['UID'], $pid, $part->encoding));
fclose($fp);
$_SESSION['compose']['attachments'][] = array(
'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
'name' => $part->filename,
'path' => $tmp_path
);
}
}
}
$_SESSION['compose']['forward_attachments'] = TRUE;
}
function rcmail_compose_subject($attrib)
{
global $CONFIG, $MESSAGE, $compose_mode;
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 ($compose_mode == RCUBE_COMPOSE_REPLY)
{
if (eregi('^re:', $MESSAGE['subject']))
$subject = $MESSAGE['subject'];
else
$subject = 'Re: '.$MESSAGE['subject'];
}
// create a forward-subject
else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
{
if (eregi('^fwd:', $MESSAGE['subject']))
$subject = $MESSAGE['subject'];
else
$subject = 'Fwd: '.$MESSAGE['subject'];
}
// creeate a draft-subject
else if ($compose_mode == RCUBE_COMPOSE_DRAFT)
$subject = $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, $CONFIG;
+ global $OUTPUT, $CONFIG;
// 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" />',
$CONFIG['skin_path'],
$attrib['deleteicon'],
rcube_label('delete'));
else
$button = rcube_label('delete');
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,
+ JS_OBJECT_NAME,
$id,
Q(rcube_label('delete')),
$button,
Q($a_prop['name']));
}
- $OUTPUT->add_script(sprintf("%s.gui_object('attachmentlist', '%s');", $JS_OBJECT_NAME, $attrib['id']));
+ $OUTPUT->add_gui_object('attachmentlist', $attrib['id']);
$out .= '</ul>';
return $out;
}
function rcmail_compose_attachment_form($attrib)
{
- global $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
+ global $OUTPUT, $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');
+ $js_instance = JS_OBJECT_NAME;
$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)" />
+<input type="button" value="$label_send" class="button" onclick="$js_instance.command('send-attachment', this.form)" />
</form>
</div>
EOF;
- $OUTPUT->add_script(sprintf("%s.gui_object('uploadbox', '%s');", $JS_OBJECT_NAME, $attrib['id']));
+ $OUTPUT->add_gui_object('uploadbox', $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 rcmail_editor_selector($attrib)
{
global $CONFIG, $MESSAGE, $compose_mode;
$choices = array(
'html' => 'htmltoggle',
'plain' => 'plaintoggle'
);
// determine whether HTML or plain text should be checked
if ($CONFIG['htmleditor'])
$useHtml = true;
else
$useHtml = false;
if ($compose_mode == RCUBE_COMPOSE_REPLY ||
$compose_mode == RCUBE_COMPOSE_FORWARD ||
$compose_mode == RCUBE_COMPOSE_DRAFT)
{
$hasHtml = rcmail_has_html_part($MESSAGE['parts']);
$useHtml = ($hasHtml && $CONFIG['htmleditor']);
}
$selector = '';
$attrib['name'] = '_editorSelect';
$attrib['onchange'] = 'return rcmail_toggle_editor(this)';
foreach ($choices as $value => $text)
{
$checked = '';
if ((($value == 'html') && $useHtml) ||
(($value != 'html') && !$useHtml))
$attrib['checked'] = 'true';
else
unset($attrib['checked']);
$attrib['id'] = '_' . $value;
$rb = new radiobutton($attrib);
- $selector .= sprintf("<td>%s</td><td class=\"title\"><label for=\"%s\">%s</label></td>",
+ $selector .= sprintf("%s<label for=\"%s\">%s</label>",
$rb->show($value),
$attrib['id'],
rcube_label($text));
}
return $selector;
}
function get_form_tags($attrib)
{
- global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $MESSAGE_FORM, $SESS_HIDDEN_FIELD;
+ global $CONFIG, $OUTPUT, $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');");
+ $OUTPUT->add_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);
- }
+// register UI objects
+$OUTPUT->add_handlers(array(
+ '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',
+ 'editorselector' => 'rcmail_editor_selector',
+ 'receiptcheckbox' => 'rcmail_receipt_checkbox',
+));
/****** 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']);
+require_once('include/rcube_contacts.inc');
+
+$CONTACTS = new rcube_contacts($DB, $_SESSION['user_id']);
+$CONTACTS->set_pagesize(1000);
-if ($DB->num_rows($sql_result))
+if ($result = $CONTACTS->list_records())
{
$a_contacts = array();
- while ($sql_arr = $DB->fetch_assoc($sql_result))
+ while ($sql_arr = $result->iterate())
if ($sql_arr['email'])
$a_contacts[] = format_email_recipient($sql_arr['email'], JQ($sql_arr['name']));
- $OUTPUT->add_script(sprintf("$JS_OBJECT_NAME.set_env('contacts', %s);", array2js($a_contacts)));
+ $OUTPUT->set_env('contacts', $a_contacts);
}
parse_template('compose');
?>
diff --git a/program/steps/mail/folders.inc b/program/steps/mail/folders.inc
index 1b7007c39..a97057e2c 100644
--- a/program/steps/mail/folders.inc
+++ b/program/steps/mail/folders.inc
@@ -1,61 +1,57 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/folders.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Implement folder operations line EXPUNGE and Clear |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
$mbox_name = $IMAP->get_mailbox_name();
-
// send EXPUNGE command
if ($_action=='expunge')
- {
+{
$success = $IMAP->expunge(get_input_value('_mbox', RCUBE_INPUT_GET));
// reload message list if current mailbox
if ($success && !empty($_GET['_reload']))
- {
- rcube_remote_response('this.message_list.clear();', TRUE);
+ {
+ $OUTPUT->command('message_list.clear');
$_action = 'list';
return;
- }
+ }
else
$commands = "// expunged: $success\n";
- }
+}
// clear mailbox
else if ($_action=='purge')
- {
+{
$success = $IMAP->clear_mailbox(get_input_value('_mbox', RCUBE_INPUT_GET));
if ($success && !empty($_GET['_reload']))
- {
- $commands = "this.message_list.clear();\n";
- $commands .= "this.set_env('messagecount', 0);\n";
- $commands .= "this.set_env('pagecount', 0);\n";
- $commands .= sprintf("this.set_rowcount('%s');\n", rcmail_get_messagecount_text());
- $commands .= sprintf("this.set_unread_count('%s', 0);\n", addslashes($mbox_name));
- }
+ {
+ $OUTPUT->set_env('messagecount', 0);
+ $OUTPUT->set_env('pagecount', 0);
+ $OUTPUT->command('message_list.clear');
+ $OUTPUT->command('set_rowcount', rcmail_get_messagecount_text());
+ $OUTPUT->command('set_unread_count', $mbox_name, 0);
+ }
else
$commands = "// purged: $success";
- }
-
-
+}
-rcube_remote_response($commands);
+$OUTPUT->send($commands);
?>
\ No newline at end of file
diff --git a/program/steps/mail/func.inc b/program/steps/mail/func.inc
index a0bdf0995..7416fb5d4 100644
--- a/program/steps/mail/func.inc
+++ b/program/steps/mail/func.inc
@@ -1,1505 +1,1483 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/func.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Provide webmail functionality and GUI objects |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
require_once('lib/html2text.inc');
require_once('lib/enriched.inc');
$EMAIL_ADDRESS_PATTERN = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/i';
-if (empty($_SESSION['mbox'])){
+if (empty($_SESSION['mbox']))
$_SESSION['mbox'] = $IMAP->get_mailbox_name();
-}
// set imap properties and session vars
if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
{
$IMAP->set_mailbox($mbox);
$_SESSION['mbox'] = $mbox;
}
if (!empty($_GET['_page']))
{
$IMAP->set_page((int)$_GET['_page']);
$_SESSION['page'] = (int)$_GET['_page'];
}
// set mailbox to INBOX if not set
if (empty($_SESSION['mbox']))
$_SESSION['mbox'] = $IMAP->get_mailbox_name();
// set default sort col/order to session
if (!isset($_SESSION['sort_col']))
$_SESSION['sort_col'] = $CONFIG['message_sort_col'];
if (!isset($_SESSION['sort_order']))
$_SESSION['sort_order'] = $CONFIG['message_sort_order'];
// set message set for search result
if (!empty($_GET['_search']) && isset($_SESSION['search'][$_GET['_search']]))
$IMAP->set_search_set($_SESSION['search'][$_GET['_search']]);
// define url for getting message parts
if (strlen($_GET['_uid']))
$GET_URL = sprintf('%s&_action=get&_mbox=%s&_uid=%d', $COMM_PATH, $IMAP->get_mailbox_name(), get_input_value('_uid', RCUBE_INPUT_GET));
// set current mailbox in client environment
-$OUTPUT->add_script(sprintf("%s.set_env('mailbox', '%s');", $JS_OBJECT_NAME, $IMAP->get_mailbox_name()));
+$OUTPUT->set_env('mailbox', $IMAP->get_mailbox_name());
+//$OUTPUT->set_pagetitle(rcube_charset_convert($IMAP->get_mailbox_name(), 'UTF-7', 'UTF-8'));
if ($CONFIG['trash_mbox'])
- $OUTPUT->add_script(sprintf("%s.set_env('trash_mailbox', '%s');", $JS_OBJECT_NAME, $CONFIG['trash_mbox']));
-
+ $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
if ($CONFIG['drafts_mbox'])
- $OUTPUT->add_script(sprintf("%s.set_env('drafts_mailbox', '%s');", $JS_OBJECT_NAME, $CONFIG['drafts_mbox']));
-
+ $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
if ($CONFIG['junk_mbox'])
- $OUTPUT->add_script(sprintf("%s.set_env('junk_mailbox', '%s');", $JS_OBJECT_NAME, $CONFIG['junk_mbox']));
+ $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
+
+if (!$OUTPUT->ajax_call)
+ rcube_add_label('checkingmail');
+
// return the mailboxlist in HTML
function rcmail_mailbox_list($attrib)
{
- global $IMAP, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $COMM_PATH;
+ global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
static $s_added_script = FALSE;
static $a_mailboxes;
// add some labels to client
rcube_add_label('purgefolderconfirm');
rcube_add_label('deletemessagesconfirm');
// $mboxlist_start = rcube_timer();
$type = $attrib['type'] ? $attrib['type'] : 'ul';
$add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
array('style', 'class', 'id');
if ($type=='ul' && !$attrib['id'])
$attrib['id'] = 'rcmboxlist';
// allow the following attributes to be added to the <ul> tag
$attrib_str = create_attrib_string($attrib, $add_attrib);
$out = '<' . $type . $attrib_str . ">\n";
// add no-selection option
if ($type=='select' && $attrib['noselection'])
$out .= sprintf('<option value="0">%s</option>'."\n",
rcube_label($attrib['noselection']));
// get mailbox list
$mbox_name = $IMAP->get_mailbox_name();
// for these mailboxes we have localized labels
$special_mailboxes = array('inbox', 'sent', 'drafts', 'trash', 'junk');
// build the folders tree
if (empty($a_mailboxes))
{
// get mailbox list
$a_folders = $IMAP->list_mailboxes();
$delimiter = $IMAP->get_hierarchy_delimiter();
$a_mailboxes = array();
// rcube_print_time($mboxlist_start, 'list_mailboxes()');
foreach ($a_folders as $folder)
rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
}
// var_dump($a_mailboxes);
if ($type=='select')
$out .= rcmail_render_folder_tree_select($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
else
$out .= rcmail_render_folder_tree_html($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
// rcube_print_time($mboxlist_start, 'render_folder_tree()');
if ($type=='ul')
- $OUTPUT->add_script(sprintf("%s.gui_object('mailboxlist', '%s');", $JS_OBJECT_NAME, $attrib['id']));
+ $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
return $out . "</$type>";
}
// create a hierarchical array of the mailbox list
function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
{
$pos = strpos($folder, $delm);
if ($pos !== false)
{
$subFolders = substr($folder, $pos+1);
$currentFolder = substr($folder, 0, $pos);
}
else
{
$subFolders = false;
$currentFolder = $folder;
}
$path .= $currentFolder;
if (!isset($arrFolders[$currentFolder]))
{
$arrFolders[$currentFolder] = array('id' => $path,
'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
'folders' => array());
}
if (!empty($subFolders))
rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
}
// return html for a structured list <ul> for the mailbox tree
function rcmail_render_folder_tree_html(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
{
- global $JS_OBJECT_NAME, $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
+ global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
$idx = 0;
$out = '';
foreach ($arrFolders as $key => $folder)
{
$zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
$title = '';
$folder_lc = strtolower($folder['id']);
if (in_array($folder_lc, $special))
$foldername = rcube_label($folder_lc);
else
{
$foldername = $folder['name'];
// shorten the folder name to a given length
if ($maxlength && $maxlength>1)
{
$fname = abbrevate_string($foldername, $maxlength);
if ($fname != $foldername)
$title = ' title="'.Q($foldername).'"';
$foldername = $fname;
}
}
// add unread message count display
if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox_name)))
$foldername .= sprintf(' (%d)', $unread_count);
// make folder name safe for ids and class names
- $folder_css = $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
+ $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
+ $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
// set special class for Sent, Drafts, Trash and Junk
if ($folder['id']==$CONFIG['sent_mbox'])
$class_name = 'sent';
else if ($folder['id']==$CONFIG['drafts_mbox'])
$class_name = 'drafts';
else if ($folder['id']==$CONFIG['trash_mbox'])
$class_name = 'trash';
else if ($folder['id']==$CONFIG['junk_mbox'])
$class_name = 'junk';
$js_name = htmlspecialchars(JQ($folder['id']));
- $out .= sprintf('<li id="rcmbx%s" class="mailbox %s %s%s%s"><a href="%s&amp;_mbox=%s"'.
- ' onclick="return %s.command(\'list\',\'%s\')"'.
- ' onmouseover="return %s.focus_mailbox(\'%s\')"' .
- ' onmouseout="return %s.unfocus_mailbox(\'%s\')"' .
- ' onmouseup="return %s.mbox_mouse_up(\'%s\')"%s>%s</a>',
- $folder_css,
+ $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
+ ' onclick="return %s.command(\'list\',\'%s\',this)"'.
+ ' onmouseover="return %s.focus_folder(\'%s\')"' .
+ ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
+ ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
+ $folder_id,
$class_name,
$zebra_class,
$unread_count ? ' unread' : '',
$folder['id']==$mbox_name ? ' selected' : '',
- $COMM_PATH,
- urlencode($folder['id']),
- $JS_OBJECT_NAME,
+ Q(rcmail_self_url('', array('_mbox' => $folder['id']))),
+ JS_OBJECT_NAME,
$js_name,
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
$js_name,
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
$js_name,
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
$js_name,
$title,
Q($foldername));
if (!empty($folder['folders']))
$out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
$out .= "</li>\n";
$idx++;
}
return $out;
}
// return html for a flat list <select> for the mailbox tree
function rcmail_render_folder_tree_select(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
{
global $IMAP, $OUTPUT;
$idx = 0;
$out = '';
foreach ($arrFolders as $key=>$folder)
{
$folder_lc = strtolower($folder['id']);
if (in_array($folder_lc, $special))
$foldername = rcube_label($folder_lc);
else
{
$foldername = $folder['name'];
// shorten the folder name to a given length
if ($maxlength && $maxlength>1)
$foldername = abbrevate_string($foldername, $maxlength);
}
$out .= sprintf('<option value="%s">%s%s</option>'."\n",
htmlspecialchars($folder['id']),
str_repeat('&nbsp;', $nestLevel*4),
Q($foldername));
if (!empty($folder['folders']))
$out .= rcmail_render_folder_tree_select($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1);
$idx++;
}
return $out;
}
// return the message list as HTML table
function rcmail_message_list($attrib)
{
- global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT, $JS_OBJECT_NAME;
+ global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT;
$skin_path = $CONFIG['skin_path'];
$image_tag = '<img src="%s%s" alt="%s" border="0" />';
// check to see if we have some settings for sorting
$sort_col = $_SESSION['sort_col'];
$sort_order = $_SESSION['sort_order'];
// add some labels to client
rcube_add_label('from', 'to');
// get message headers
$a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
// add id to message list table if not specified
if (!strlen($attrib['id']))
$attrib['id'] = 'rcubemessagelist';
// 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'));
$out = '<table' . $attrib_str . ">\n";
// define list of cols to be displayed
$a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
$a_sort_cols = array('subject', 'date', 'from', 'to', 'size');
// show 'to' instead of from in sent messages
if (($IMAP->get_mailbox_name()==$CONFIG['sent_mbox'] || $IMAP->get_mailbox_name()==$CONFIG['drafts_mbox']) && ($f = array_search('from', $a_show_cols))
&& !array_search('to', $a_show_cols))
$a_show_cols[$f] = 'to';
// add col definition
$out .= '<colgroup>';
$out .= '<col class="icon" />';
foreach ($a_show_cols as $col)
$out .= sprintf('<col class="%s" />', $col);
$out .= '<col class="icon" />';
$out .= "</colgroup>\n";
// add table title
$out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
$javascript = '';
foreach ($a_show_cols as $col)
{
// get column name
$col_name = Q(rcube_label($col));
// make sort links
$sort = '';
if ($IMAP->get_capability('sort') && in_array($col, $a_sort_cols))
{
// have buttons configured
if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
{
$sort = '&nbsp;&nbsp;';
// asc link
if (!empty($attrib['sortascbutton']))
{
- $sort .= rcube_button(array('command' => 'sort',
- 'prop' => $col.'_ASC',
- 'image' => $attrib['sortascbutton'],
- 'align' => 'absmiddle',
- 'title' => 'sortasc'));
+ $sort .= $OUTPUT->button(array(
+ 'command' => 'sort',
+ 'prop' => $col.'_ASC',
+ 'image' => $attrib['sortascbutton'],
+ 'align' => 'absmiddle',
+ 'title' => 'sortasc'));
}
// desc link
if (!empty($attrib['sortdescbutton']))
{
- $sort .= rcube_button(array('command' => 'sort',
- 'prop' => $col.'_DESC',
- 'image' => $attrib['sortdescbutton'],
- 'align' => 'absmiddle',
- 'title' => 'sortdesc'));
+ $sort .= $OUTPUT->button(array(
+ 'command' => 'sort',
+ 'prop' => $col.'_DESC',
+ 'image' => $attrib['sortdescbutton'],
+ 'align' => 'absmiddle',
+ 'title' => 'sortdesc'));
}
}
// just add a link tag to the header
else
{
$col_name = sprintf('<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
$col,
rcube_label('sortby'),
$col_name);
}
}
$sort_class = $col==$sort_col ? " sorted$sort_order" : '';
// put it all together
$out .= '<td class="'.$col.$sort_class.'" id="rcmHead'.$col.'">' . "$col_name$sort</td>\n";
}
$out .= '<td class="icon">'.($attrib['attachmenticon'] ? sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '') : '')."</td>\n";
$out .= "</tr></thead>\n<tbody>\n";
// no messages in this mailbox
if (!sizeof($a_headers))
{
$out .= sprintf('<tr><td colspan="%d">%s</td></tr>',
sizeof($a_show_cols)+2,
Q(rcube_label('nomessagesfound')));
}
$a_js_message_arr = array();
// create row for each message
foreach ($a_headers as $i => $header) //while (list($i, $header) = each($a_headers))
{
$message_icon = $attach_icon = '';
$js_row_arr = array();
$zebra_class = $i%2 ? 'even' : 'odd';
// set messag attributes to javascript array
if ($header->deleted)
$js_row_arr['deleted'] = true;
if (!$header->seen)
$js_row_arr['unread'] = true;
if ($header->answered)
$js_row_arr['replied'] = true;
// set message icon
if ($attrib['deletedicon'] && $header->deleted)
$message_icon = $attrib['deletedicon'];
else if ($attrib['unreadicon'] && !$header->seen)
$message_icon = $attrib['unreadicon'];
else if ($attrib['repliedicon'] && $header->answered)
$message_icon = $attrib['repliedicon'];
else if ($attrib['messageicon'])
$message_icon = $attrib['messageicon'];
- // set attachment icon
+ // set attachment icon
if ($attrib['attachmenticon'] && preg_match("/multipart\/[mr]/i", $header->ctype))
$attach_icon = $attrib['attachmenticon'];
$out .= sprintf('<tr id="rcmrow%d" class="message%s%s %s">'."\n",
$header->uid,
$header->seen ? '' : ' unread',
$header->deleted ? ' deleted' : '',
$zebra_class);
$out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
-
+
// format each col
foreach ($a_show_cols as $col)
{
if ($col=='from' || $col=='to')
$cont = Q(rcmail_address_string($header->$col, 3, $attrib['addicon']), 'show');
else if ($col=='subject')
{
- $cont = Q($IMAP->decode_header($header->$col));
- if (!$cont) $cont = Q(rcube_label('nosubject'));
- // firefox/mozilla temporary workaround to pad subject with content so that whitespace in rows responds to drag+drop
- $cont .= '<img src="./program/blank.gif" height="5" width="1000" alt="" />';
+ $cont = Q(rcube_imap::decode_mime_string($header->$col, $header->charset));
+ if (empty($cont)) $cont = Q(rcube_label('nosubject'));
}
else if ($col=='size')
$cont = show_bytes($header->$col);
else if ($col=='date')
- $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
+ $cont = format_date($header->date);
else
$cont = Q($header->$col);
$out .= '<td class="'.$col.'">' . $cont . "</td>\n";
}
$out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '');
$out .= "</tr>\n";
if (sizeof($js_row_arr))
$a_js_message_arr[$header->uid] = $js_row_arr;
}
// complete message table
$out .= "</tbody></table>\n";
$message_count = $IMAP->messagecount();
// set client env
- $javascript .= sprintf("%s.gui_object('mailcontframe', '%s');\n", $JS_OBJECT_NAME, 'mailcontframe');
- $javascript .= sprintf("%s.gui_object('messagelist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
- $javascript .= sprintf("%s.set_env('messagecount', %d);\n", $JS_OBJECT_NAME, $message_count);
- $javascript .= sprintf("%s.set_env('current_page', %d);\n", $JS_OBJECT_NAME, $IMAP->list_page);
- $javascript .= sprintf("%s.set_env('pagecount', %d);\n", $JS_OBJECT_NAME, ceil($message_count/$IMAP->page_size));
- $javascript .= sprintf("%s.set_env('sort_col', '%s');\n", $JS_OBJECT_NAME, $sort_col);
- $javascript .= sprintf("%s.set_env('sort_order', '%s');\n", $JS_OBJECT_NAME, $sort_order);
+ $OUTPUT->add_gui_object('mailcontframe', 'mailcontframe');
+ $OUTPUT->add_gui_object('messagelist', $attrib['id']);
+ $OUTPUT->set_env('messagecount', $message_count);
+ $OUTPUT->set_env('current_page', $IMAP->list_page);
+ $OUTPUT->set_env('pagecount', ceil($message_count/$IMAP->page_size));
+ $OUTPUT->set_env('sort_col', $sort_col);
+ $OUTPUT->set_env('sort_order', $sort_order);
if ($attrib['messageicon'])
- $javascript .= sprintf("%s.set_env('messageicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['messageicon']);
+ $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
if ($attrib['deletedicon'])
- $javascript .= sprintf("%s.set_env('deletedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['deletedicon']);
+ $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
if ($attrib['unreadicon'])
- $javascript .= sprintf("%s.set_env('unreadicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['unreadicon']);
+ $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
if ($attrib['repliedicon'])
- $javascript .= sprintf("%s.set_env('repliedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['repliedicon']);
+ $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
if ($attrib['attachmenticon'])
- $javascript .= sprintf("%s.set_env('attachmenticon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['attachmenticon']);
-
- $javascript .= sprintf("%s.set_env('messages', %s);", $JS_OBJECT_NAME, array2js($a_js_message_arr));
+ $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
+
+ $OUTPUT->set_env('messages', array2js($a_js_message_arr));
- $OUTPUT->add_script($javascript);
$OUTPUT->include_script('list.js');
return $out;
}
-
-
// return javascript commands to add rows to the message list
function rcmail_js_message_list($a_headers, $insert_top=FALSE)
{
- global $CONFIG, $IMAP;
+ global $CONFIG, $IMAP, $OUTPUT;
- $commands = '';
$a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
// show 'to' instead of from in sent messages
- if (($IMAP->get_mailbox_name()==$CONFIG['sent_mbox'] || $IMAP->get_mailbox_name()==$CONFIG['drafts_mbox'])
- && ($f = array_search('from', $a_show_cols)) && !array_search('to', $a_show_cols))
+ if (($IMAP->get_mailbox_name() == $CONFIG['sent_mbox'] || $IMAP->get_mailbox_name() == $CONFIG['drafts_mbox'])
+ && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
$a_show_cols[$f] = 'to';
- $commands .= sprintf("this.set_message_coltypes(%s);\n", array2js($a_show_cols));
+ $OUTPUT->command('set_message_coltypes', $a_show_cols);
// loop through message headers
for ($n=0; $a_headers[$n]; $n++)
{
$header = $a_headers[$n];
$a_msg_cols = array();
$a_msg_flags = array();
-
+
// format each col; similar as in rcmail_message_list()
foreach ($a_show_cols as $col)
{
if ($col=='from' || $col=='to')
$cont = Q(rcmail_address_string($header->$col, 3), 'show');
else if ($col=='subject')
{
- $cont = Q($IMAP->decode_header($header->$col));
+ $cont = Q(rcube_imap::decode_mime_string($header->$col, $header->charset));
if (!$cont) $cont = Q(rcube_label('nosubject'));
}
else if ($col=='size')
$cont = show_bytes($header->$col);
else if ($col=='date')
- $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
+ $cont = format_date($header->date);
else
$cont = Q($header->$col);
$a_msg_cols[$col] = $cont;
}
$a_msg_flags['deleted'] = $header->deleted ? 1 : 0;
$a_msg_flags['unread'] = $header->seen ? 0 : 1;
$a_msg_flags['replied'] = $header->answered ? 1 : 0;
- $commands .= sprintf("this.add_message_row(%s, %s, %s, %b, %b);\n",
- $header->uid,
- array2js($a_msg_cols),
- array2js($a_msg_flags),
- preg_match("/multipart\/m/i", $header->ctype),
- $insert_top);
+ $OUTPUT->command('add_message_row',
+ $header->uid,
+ $a_msg_cols,
+ $a_msg_flags,
+ preg_match("/multipart\/m/i", $header->ctype),
+ $insert_top);
}
-
- return $commands;
}
// return an HTML iframe for loading mail content
function rcmail_messagecontent_frame($attrib)
{
- global $OUTPUT, $JS_OBJECT_NAME;
+ global $OUTPUT;
if (empty($attrib['id']))
$attrib['id'] = 'rcmailcontentwindow';
// allow the following attributes to be added to the <iframe> tag
$attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height', 'frameborder'));
$framename = $attrib['id'];
$out = sprintf('<iframe name="%s"%s></iframe>'."\n",
$framename,
$attrib_str);
- $OUTPUT->add_script("$JS_OBJECT_NAME.set_env('contentframe', '$framename');");
+ $OUTPUT->set_env('contentframe', $framename);
+ $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
return $out;
}
-// return code for search function
-function rcmail_search_form($attrib)
- {
- global $OUTPUT, $JS_OBJECT_NAME;
-
- // add some labels to client
- rcube_add_label('searching');
-
- $attrib['name'] = '_q';
-
- if (empty($attrib['id']))
- $attrib['id'] = 'rcmqsearchbox';
-
- $input_q = new textfield($attrib);
- $out = $input_q->show();
-
- $OUTPUT->add_script(sprintf("%s.gui_object('qsearchbox', '%s');",
- $JS_OBJECT_NAME,
- $attrib['id']));
-
- // add form tag around text field
- if (empty($attrib['form']))
- $out = sprintf('<form name="rcmqsearchform" action="./" '.
- 'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',
- $JS_OBJECT_NAME,
- $out);
-
- return $out;
- }
-
function rcmail_messagecount_display($attrib)
{
- global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
+ global $IMAP, $OUTPUT;
if (!$attrib['id'])
$attrib['id'] = 'rcmcountdisplay';
- $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');",
- $JS_OBJECT_NAME,
- $attrib['id']));
+ $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
// allow the following attributes to be added to the <span> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
$out = '<span' . $attrib_str . '>';
$out .= rcmail_get_messagecount_text();
$out .= '</span>';
return $out;
}
function rcmail_quota_display($attrib)
{
- global $OUTPUT, $JS_OBJECT_NAME, $COMM_PATH;
+ global $OUTPUT, $COMM_PATH;
if (!$attrib['id'])
$attrib['id'] = 'rcmquotadisplay';
- $OUTPUT->add_script(sprintf("%s.gui_object('quotadisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
+ $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
// allow the following attributes to be added to the <span> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
$out = '<span' . $attrib_str . '>';
$out .= rcmail_quota_content($attrib['display']);
$out .= '</span>';
return $out;
}
function rcmail_quota_content($display)
{
global $IMAP, $COMM_PATH;
if (!$IMAP->get_capability('QUOTA'))
$quota_text = rcube_label('unknown');
else if ($quota = $IMAP->get_quota())
{
$quota_text = sprintf("%s / %s (%.0f%%)",
show_bytes($quota["used"] * 1024),
show_bytes($quota["total"] * 1024),
$quota["percent"]);
// show quota as image (by Brett Patterson)
if ($display == 'image' && function_exists('imagegif'))
{
$attrib = array('width' => 100, 'height' => 14);
- $quota_text = sprintf('<img src="%s&amp;_action=quotaimg&amp;u=%s&amp;q=%d&amp;w=%d&amp;h=%d" width="%d" height="%d" alt="%s" title="%s / %s" />',
- $COMM_PATH,
+ $quota_text = sprintf('<img src="./bin/quotaimg.php?u=%s&amp;q=%d&amp;w=%d&amp;h=%d" width="%d" height="%d" alt="%s" title="%s / %s" />',
$quota['used'], $quota['total'],
$attrib['width'], $attrib['height'],
$attrib['width'], $attrib['height'],
$quota_text,
show_bytes($quota["used"] * 1024),
show_bytes($quota["total"] * 1024));
}
}
else
$quota_text = rcube_label('unlimited');
return $quota_text;
}
function rcmail_get_messagecount_text($count=NULL, $page=NULL)
{
global $IMAP, $MESSAGE;
if (isset($MESSAGE['index']))
{
return rcube_label(array('name' => 'messagenrof',
'vars' => array('nr' => $MESSAGE['index']+1,
'count' => $count!==NULL ? $count : $IMAP->messagecount())));
}
if ($page===NULL)
$page = $IMAP->list_page;
$start_msg = ($page-1) * $IMAP->page_size + 1;
$max = $count!==NULL ? $count : $IMAP->messagecount();
if ($max==0)
$out = rcube_label('mailboxempty');
else
$out = rcube_label(array('name' => 'messagesfromto',
'vars' => array('from' => $start_msg,
'to' => min($max, $start_msg + $IMAP->page_size - 1),
'count' => $max)));
return Q($out);
}
function rcmail_print_body($part, $safe=FALSE, $plain=FALSE)
{
- global $IMAP, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
+ global $IMAP, $REMOTE_OBJECTS;
$body = is_array($part->replaces) ? strtr($part->body, $part->replaces) : $part->body;
// convert html to text/plain
if ($part->ctype_secondary=='html' && $plain)
{
$txt = new html2text($body, false, true);
$body = $txt->get_text();
$part->ctype_secondary = 'plain';
}
// text/html
if ($part->ctype_secondary=='html')
{
// remove charset specification in HTML message
$body = preg_replace('/charset=[a-z0-9\-]+/i', '', $body);
if (!$safe) // remove remote images and scripts
{
$remote_patterns = array('/<img\s+(.*)src=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
'/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
'/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
'/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
'/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
'/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
'/<script.+<\/script>/Umis');
$remote_replaces = array('<img \\1src=\\2./program/blocked.gif\\4',
'',
'',
'',
'none',
'none',
'');
// set flag if message containes remote obejcts that where blocked
foreach ($remote_patterns as $pattern)
{
if (preg_match($pattern, $body))
{
$REMOTE_OBJECTS = TRUE;
break;
}
}
$body = preg_replace($remote_patterns, $remote_replaces, $body);
}
return Q($body, 'show', FALSE);
}
// text/enriched
if ($part->ctype_secondary=='enriched')
{
return Q(enriched_to_html($body), 'show');
}
else
{
// make links and email-addresses clickable
$convert_patterns = $convert_replaces = $replace_strings = array();
$url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
$url_chars_within = '\?\.~,!';
$convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
$convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
$convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
$convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
$convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
- $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
+ $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return ".JS_OBJECT_NAME.".command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
if ($part->ctype_parameters['format'] != 'flowed')
$body = wordwrap(trim($body), 80);
$body = preg_replace($convert_patterns, $convert_replaces, $body);
// split body into single lines
$a_lines = preg_split('/\r?\n/', $body);
$quote_level = 0;
// colorize quoted parts
for($n=0; $n<sizeof($a_lines); $n++)
{
$line = $a_lines[$n];
$quotation = '';
$q = 0;
if (preg_match('/^(>+\s*)/', $line, $regs))
{
$q = strlen(preg_replace('/\s/', '', $regs[1]));
$line = substr($line, strlen($regs[1]));
if ($q > $quote_level)
$quotation = str_repeat('<blockquote>', $q - $quote_level);
else if ($q < $quote_level)
$quotation = str_repeat("</blockquote>", $quote_level - $q);
}
else if ($quote_level > 0)
$quotation = str_repeat("</blockquote>", $quote_level);
$quote_level = $q;
$a_lines[$n] = $quotation . Q($line, 'replace', FALSE);
}
// insert the links for urls and mailtos
$body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
return "<div class=\"pre\">".$body."\n</div>";
}
}
// add a string to the replacement array and return a replacement string
function rcmail_str_replacement($str, &$rep)
{
static $count = 0;
$rep[$count] = stripslashes($str);
return "##string_replacement{".($count++)."}##";
}
function rcmail_parse_message(&$structure, $arg=array(), $recursive=FALSE)
{
global $IMAP;
static $sa_inline_objects = array();
// arguments are: (bool)$prefer_html, (string)$get_url
extract($arg);
$a_attachments = array();
$a_return_parts = array();
$out = '';
$message_ctype_primary = strtolower($structure->ctype_primary);
$message_ctype_secondary = strtolower($structure->ctype_secondary);
// show message headers
if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
{
$c = new stdClass;
$c->type = 'headers';
$c->headers = &$structure->headers;
$a_return_parts[] = $c;
}
// print body if message doesn't have multiple parts
if ($message_ctype_primary=='text')
{
$structure->type = 'content';
$a_return_parts[] = &$structure;
}
// message contains alternative parts
else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
{
// get html/plaintext parts
$plain_part = $html_part = $print_part = $related_part = NULL;
foreach ($structure->parts as $p => $sub_part)
{
$sub_ctype_primary = strtolower($sub_part->ctype_primary);
$sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
// check if sub part is
if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
$plain_part = $p;
else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
$html_part = $p;
else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
$enriched_part = $p;
else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
$related_part = $p;
}
// parse related part (alternative part could be in here)
if ($related_part!==NULL && $prefer_html)
{
list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
$a_return_parts = array_merge($a_return_parts, $parts);
$a_attachments = array_merge($a_attachments, $attachmnts);
}
// print html/plain part
else if ($html_part!==NULL && $prefer_html)
$print_part = &$structure->parts[$html_part];
else if ($enriched_part!==NULL)
$print_part = &$structure->parts[$enriched_part];
else if ($plain_part!==NULL)
$print_part = &$structure->parts[$plain_part];
// show message body
if (is_object($print_part))
{
$print_part->type = 'content';
$a_return_parts[] = $print_part;
}
// show plaintext warning
else if ($html_part!==NULL)
{
$c = new stdClass;
$c->type = 'content';
$c->body = rcube_label('htmlmessage');
$c->ctype_primary = 'text';
$c->ctype_secondary = 'plain';
$a_return_parts[] = $c;
}
// add html part as attachment
if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
{
$html_part = &$structure->parts[$html_part];
$html_part->filename = rcube_label('htmlmessage');
$html_part->mimetype = 'text/html';
$a_attachments[] = $html_part;
}
}
// message contains multiple parts
else if (is_array($structure->parts) && !empty($structure->parts))
{
for ($i=0; $i<count($structure->parts); $i++)
{
$mail_part = &$structure->parts[$i];
$primary_type = strtolower($mail_part->ctype_primary);
$secondary_type = strtolower($mail_part->ctype_secondary);
// multipart/alternative
if ($primary_type=='multipart')
{
list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
$a_return_parts = array_merge($a_return_parts, $parts);
$a_attachments = array_merge($a_attachments, $attachmnts);
}
// part text/[plain|html] OR message/delivery-status
else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html') && $mail_part->disposition!='attachment') ||
($primary_type=='message' && $secondary_type=='delivery-status'))
{
$mail_part->type = 'content';
$a_return_parts[] = $mail_part;
}
// part message/*
else if ($primary_type=='message')
{
list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
$a_return_parts = array_merge($a_return_parts, $parts);
$a_attachments = array_merge($a_attachments, $attachmnts);
}
// part is file/attachment
else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
(empty($mail_part->disposition) && $mail_part->filename))
{
// skip apple resource forks
if ($message_ctype_secondary=='appledouble' && $secondary_type=='applefile')
continue;
// part belongs to a related message
if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
{
$mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
$sa_inline_objects[] = $mail_part;
}
// is regular attachment
else
{
if (!$mail_part->filename)
$mail_part->filename = 'file_'.$mail_part->mime_id;
$a_attachments[] = $mail_part;
}
}
}
// if this was a related part try to resolve references
if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
{
$a_replaces = array();
foreach ($sa_inline_objects as $inline_object)
$a_replaces['cid:'.$inline_object->content_id] = htmlspecialchars(sprintf($get_url, $inline_object->mime_id));
// add replace array to each content part
// (will be applied later when part body is available)
for ($i=0; $i<count($a_return_parts); $i++)
{
if ($a_return_parts[$i]->type=='content')
$a_return_parts[$i]->replaces = $a_replaces;
}
}
}
// message is single part non-text
else if ($structure->filename)
$a_attachments[] = $structure;
return array($a_return_parts, $a_attachments);
}
// return table with message headers
function rcmail_message_headers($attrib, $headers=NULL)
{
global $IMAP, $OUTPUT, $MESSAGE;
static $sa_attrib;
// keep header table attrib
if (is_array($attrib) && !$sa_attrib)
$sa_attrib = $attrib;
else if (!is_array($attrib) && is_array($sa_attrib))
$attrib = $sa_attrib;
if (!isset($MESSAGE))
return FALSE;
// get associative array of headers object
if (!$headers)
$headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
-
+
$header_count = 0;
// 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'));
$out = '<table' . $attrib_str . ">\n";
// show these headers
$standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
foreach ($standard_headers as $hkey)
{
if (!$headers[$hkey])
continue;
if ($hkey=='date' && !empty($headers[$hkey]))
$header_value = format_date(strtotime($headers[$hkey]));
else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
$header_value = Q(rcmail_address_string($headers[$hkey], NULL, $attrib['addicon']), 'show');
else
- $header_value = Q($IMAP->decode_header($headers[$hkey]));
+ $header_value = Q(rcube_imap::decode_mime_string($headers[$hkey], $headers['charset']));
$out .= "\n<tr>\n";
$out .= '<td class="header-title">'.Q(rcube_label($hkey)).":&nbsp;</td>\n";
$out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
$header_count++;
}
$out .= "\n</table>\n\n";
return $header_count ? $out : '';
}
function rcmail_message_body($attrib)
{
- global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
+ global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $GET_URL, $REMOTE_OBJECTS;
if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
return '';
if (!$attrib['id'])
$attrib['id'] = 'rcmailMsgBody';
$safe_mode = (bool)$_GET['_safe'];
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
$out = '<div '. $attrib_str . ">\n";
$header_attrib = array();
foreach ($attrib as $attr => $value)
if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
$header_attrib[$regs[1]] = $value;
// this is an ecrypted message
// -> create a plaintext body with the according message
if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
{
$p = new stdClass;
$p->type = 'content';
$p->ctype_primary = 'text';
$p->ctype_secondary = 'plain';
$p->body = rcube_label('encryptedmessage');
$MESSAGE['parts'][0] = $p;
}
if ($MESSAGE['parts'])
{
foreach ($MESSAGE['parts'] as $i => $part)
{
if ($part->type=='headers')
$out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
else if ($part->type=='content')
{
if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
$part->ctype_parameters['charset'] = $MESSAGE['headers']->charset;
// fetch part if not available
if (!isset($part->body))
$part->body = $IMAP->get_message_part($MESSAGE['UID'], $part->mime_id, $part);
$body = rcmail_print_body($part, $safe_mode, !$CONFIG['prefer_html']);
$out .= '<div class="message-part">';
if ($part->ctype_secondary != 'plain')
$out .= rcmail_sanitize_html($body, $attrib['id']);
else
$out .= $body;
$out .= "</div>\n";
}
}
}
else
$out .= $MESSAGE['body'];
$ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
$ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
// list images after mail body
if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
{
foreach ($MESSAGE['attachments'] as $attach_prop)
{
if (strpos($attach_prop->mimetype, 'image/')===0)
$out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&amp;_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
htmlspecialchars($GET_URL), $attach_prop->mime_id,
$attach_prop->filename,
$attach_prop->filename);
}
}
// tell client that there are blocked remote objects
if ($REMOTE_OBJECTS && !$safe_mode)
- $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
+ $OUTPUT->set_env('blockedobjects', true);
$out .= "\n</div>";
return $out;
}
// modify a HTML message that it can be displayed inside a HTML page
function rcmail_sanitize_html($body, $container_id)
{
// remove any null-byte characters before parsing
$body = preg_replace('/\x00/', '', $body);
$last_style_pos = 0;
$body_lc = strtolower($body);
// find STYLE tags
while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
{
$pos = strpos($body_lc, '>', $pos)+1;
// replace all css definitions with #container [def]
$styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id);
$body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
$body_lc = strtolower($body);
$last_style_pos = $pos2;
}
// remove SCRIPT tags
foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
{
while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
{
$pos2 += strlen('</'.$tag.'>');
$body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
$body_lc = strtolower($body);
}
}
// replace event handlers on any object
while ($body != $prev_body)
{
$prev_body = $body;
$body = preg_replace('/(<[^!][^>]*\s)(on[^=>]+)=([^>]+>)/im', '$1__removed=$3', $body);
$body = preg_replace('/(<[^!][^>]*\shref=["\']?)(javascript:)([^>]*?>)/im', '$1null:$3', $body);
}
// resolve <base href>
$base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
if (preg_match($base_reg, $body, $regs))
{
$base_url = $regs[2];
$body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
$body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
$body = preg_replace($base_reg, '', $body);
}
// modify HTML links to open a new window if clicked
$body = preg_replace('/<a\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1');", $body);
// add comments arround html and other tags
$out = preg_replace(array('/(<\/?html[^>]*>)/i',
'/(<\/?head[^>]*>)/i',
'/(<title[^>]*>.*<\/title>)/Ui',
'/(<\/?meta[^>]*>)/i'),
'<!--\\1-->',
$body);
$out = preg_replace(array('/(<body[^>]*>)/i',
'/(<\/body>)/i'),
array('<div class="rcmBody">',
'</div>'),
$out);
// quote <? of php and xml files that are specified as text/html
$out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
return $out;
}
// parse link attributes and set correct target
function rcmail_alter_html_link($in)
{
$in = preg_replace('/=([^("|\'|\s)]+)(\s|$)/', '="\1"', $in);
$attrib = parse_attrib_string($in);
if (stristr((string)$attrib['href'], 'mailto:'))
$attrib['onclick'] = sprintf("return %s.command('compose','%s',this)",
- $GLOBALS['JS_OBJECT_NAME'],
+ JS_OBJECT_NAME,
JQ(substr($attrib['href'], 7)));
else if (!empty($attrib['href']) && $attrib['href']{0}!='#')
$attrib['target'] = '_blank';
return '<a' . create_attrib_string($attrib, array('href', 'name', 'target', 'onclick', 'id', 'class', 'style', 'title')) . '>';
}
// replace all css definitions with #container [def]
function rcmail_mod_css_styles($source, $container_id)
{
$a_css_values = array();
$last_pos = 0;
// cut out all contents between { and }
while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
{
$key = sizeof($a_css_values);
$a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
$source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
$last_pos = $pos+2;
}
// remove html commends and add #container to each tag selector.
// also replace body definition because we also stripped off the <body> tag
$styles = preg_replace(array('/(^\s*<!--)|(-->\s*$)/', '/(^\s*|,\s*|\}\s*)([a-z0-9\._][a-z0-9\.\-_]*)/im', '/<<str_replacement\[([0-9]+)\]>>/e', "/$container_id\s+body/i"),
array('', "\\1#$container_id \\2", "\$a_css_values[\\1]", "$container_id div.rcmBody"),
$source);
return $styles;
}
function rcmail_has_html_part($message_parts)
{
if (!is_array($message_parts))
return FALSE;
// check all message parts
foreach ($message_parts as $pid => $part)
{
$mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
if ($mimetype=='text/html')
{
return TRUE;
}
}
return FALSE;
}
// return first HTML part of a message
function rcmail_first_html_part($message_struct)
{
global $IMAP;
if (!is_array($message_struct['parts']))
return FALSE;
$html_part = NULL;
// check all message parts
foreach ($message_struct['parts'] as $pid => $part)
{
$mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
if ($mimetype=='text/html')
{
$html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
}
}
if ($html_part)
{
// remove special chars encoding
//$trans = array_flip(get_html_translation_table(HTML_ENTITIES));
//$html_part = strtr($html_part, $trans);
return $html_part;
}
return FALSE;
}
// return first text part of a message
function rcmail_first_text_part($message_struct)
{
global $IMAP;
if (empty($message_struct['parts']))
return $message_struct['UID'] ? $IMAP->get_body($message_struct['UID']) : false;
// check all message parts
foreach ($message_struct['parts'] as $pid => $part)
{
$mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
if ($mimetype=='text/plain')
return $IMAP->get_message_part($message_struct['UID'], $pid, $part);
else if ($mimetype=='text/html')
{
$html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
// remove special chars encoding
$trans = array_flip(get_html_translation_table(HTML_ENTITIES));
$html_part = strtr($html_part, $trans);
// create instance of html2text class
$txt = new html2text($html_part);
return $txt->get_text();
}
}
return FALSE;
}
// decode address string and re-format it as HTML links
function rcmail_address_string($input, $max=NULL, $addicon=NULL)
{
- global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
+ global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
$a_parts = $IMAP->decode_address_list($input);
if (!sizeof($a_parts))
return $input;
$c = count($a_parts);
$j = 0;
$out = '';
foreach ($a_parts as $part)
{
$j++;
if ($PRINT_MODE)
$out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
{
$out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
Q($part['mailto']),
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
JQ($part['mailto']),
Q($part['mailto']),
Q($part['name']));
if ($addicon)
$out .= sprintf('&nbsp;<a href="#add" onclick="return %s.command(\'add-contact\',\'%s\',this)" title="%s"><img src="%s%s" alt="add" border="0" /></a>',
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
urlencode($part['string']),
rcube_label('addtoaddressbook'),
$CONFIG['skin_path'],
$addicon);
}
else
{
if ($part['name'])
$out .= Q($part['name']);
if ($part['mailto'])
$out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
}
if ($c>$j)
$out .= ','.($max ? '&nbsp;' : ' ');
if ($max && $j==$max && $c>$j)
{
$out .= '...';
break;
}
}
return $out;
}
function rcmail_message_part_controls()
{
global $CONFIG, $IMAP, $MESSAGE;
if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
return '';
$part = &$MESSAGE['parts'][$_GET['_part']];
$attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
$out = '<table '. $attrib_str . ">\n";
if ($filename)
{
$out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
Q(rcube_label('filename')),
Q($part->filename),
str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
Q(rcube_label('download')));
}
if ($part->size)
$out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
Q(rcube_label('filesize')),
show_bytes($part->size));
$out .= "\n</table>";
return $out;
}
function rcmail_message_part_frame($attrib)
{
global $MESSAGE;
$part = $MESSAGE['parts'][$_GET['_part']];
$ctype_primary = strtolower($part->ctype_primary);
$attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
$attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
$out = '<iframe '. $attrib_str . "></iframe>";
return $out;
}
// clear message composing settings
function rcmail_compose_cleanup()
{
if (!isset($_SESSION['compose']))
return;
// remove attachment files from temp dir
if (is_array($_SESSION['compose']['attachments']))
foreach ($_SESSION['compose']['attachments'] as $attachment)
@unlink($attachment['path']);
unset($_SESSION['compose']);
}
-
-
+
+
+// register UI objects
+$OUTPUT->add_handlers(array(
+ 'mailboxlist' => 'rcmail_mailbox_list',
+ 'messages' => 'rcmail_message_list',
+ 'messagecountdisplay' => 'rcmail_messagecount_display',
+ 'quotadisplay' => 'rcmail_quota_display',
+ 'messageheaders' => 'rcmail_message_headers',
+ 'messagebody' => 'rcmail_message_body',
+ 'messagecontentframe' => 'rcmail_messagecontent_frame',
+ 'messagepartframe' => 'rcmail_message_part_frame',
+ 'messagepartcontrols' => 'rcmail_message_part_controls',
+ 'searchform' => 'rcmail_search_form'
+));
+
?>
\ No newline at end of file
diff --git a/program/steps/mail/getunread.inc b/program/steps/mail/getunread.inc
index ed4a5fb77..e6b3843e4 100644
--- a/program/steps/mail/getunread.inc
+++ b/program/steps/mail/getunread.inc
@@ -1,36 +1,31 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/getunread.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Check all mailboxes for unread messages and update GUI |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
-
$a_folders = $IMAP->list_mailboxes();
if (!empty($a_folders))
- {
+{
foreach ($a_folders as $mbox_row)
- {
- $commands = sprintf("this.set_unread_count('%s', %d);\n", addslashes($mbox_row), $IMAP->messagecount($mbox_row, 'UNSEEN'));
- rcube_remote_response($commands, TRUE);
- }
- }
+ $OUTPUT->command('set_unread_count', $mbox_row, $IMAP->messagecount($mbox_row, 'UNSEEN'));
+}
-exit;
+$OUTPUT->send();
?>
diff --git a/program/steps/mail/list.inc b/program/steps/mail/list.inc
index 6e0637441..162624c36 100644
--- a/program/steps/mail/list.inc
+++ b/program/steps/mail/list.inc
@@ -1,69 +1,65 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/list.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Send message list to client (as remote response) |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
$OUTPUT_TYPE = 'js';
-
// is there a sort type for this request?
if ($sort = get_input_value('_sort', RCUBE_INPUT_GET))
- {
+{
// yes, so set the sort vars
list($sort_col, $sort_order) = explode('_', $sort);
// set session vars for sort (so next page and task switch know how to sort)
$_SESSION['sort_col'] = $sort_col;
$_SESSION['sort_order'] = $sort_order;
- }
+}
else
- {
+{
// use session settings if set, defaults if not
$sort_col = isset($_SESSION['sort_col']) ? $_SESSION['sort_col'] : $CONFIG['message_sort_col'];
$sort_order = isset($_SESSION['sort_order']) ? $_SESSION['sort_order'] : $CONFIG['message_sort_order'];
- }
+}
// fetch message headers
if ($count = $IMAP->messagecount())
$a_headers = $IMAP->list_headers($mbox_name, NULL, $sort_col, $sort_order);
$unseen = $IMAP->messagecount($mbox_name, 'UNSEEN', !empty($_GET['_refresh']) ? TRUE : FALSE);
// update message count display
$pages = ceil($count/$IMAP->page_size);
-$commands = sprintf("this.set_env('messagecount', %d);\n", $count);
-$commands .= sprintf("this.set_env('pagecount', %d);\n", $pages);
-$commands .= sprintf("this.set_rowcount('%s');\n", rcmail_get_messagecount_text($count));
+$OUTPUT->set_env('messagecount', $count);
+$OUTPUT->set_env('pagecount', $pages);
+$OUTPUT->command('set_rowcount', rcmail_get_messagecount_text($count));
// update mailboxlist
-$mbox_name = $IMAP->get_mailbox_name();
-$commands .= sprintf("this.set_unread_count('%s', %d);\n", addslashes($mbox_name), $unseen);
+$OUTPUT->command('set_unread_count', $IMAP->get_mailbox_name(), $unseen);
// add message rows
if (isset($a_headers) && count($a_headers))
- $commands .= rcmail_js_message_list($a_headers);
+ rcmail_js_message_list($a_headers);
// send response
-rcube_remote_response($commands);
+$OUTPUT->send();
-exit;
?>
\ No newline at end of file
diff --git a/program/steps/mail/mark.inc b/program/steps/mail/mark.inc
index 780bf5c6e..0dd781e08 100644
--- a/program/steps/mail/mark.inc
+++ b/program/steps/mail/mark.inc
@@ -1,41 +1,41 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/mark.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Mark the submitted messages with the specified flag |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
-
-$a_flags_map = array('undelete' => 'UNDELETED',
- 'delete' => 'DELETED',
- 'read' => 'SEEN',
- 'unread' => 'UNSEEN');
+$a_flags_map = array(
+ 'undelete' => 'UNDELETED',
+ 'delete' => 'DELETED',
+ 'read' => 'SEEN',
+ 'unread' => 'UNSEEN');
if (($uids = get_input_value('_uid', RCUBE_INPUT_GET)) && ($flag = get_input_value('_flag', RCUBE_INPUT_GET)))
- {
+{
$flag = $a_flags_map[$flag] ? $a_flags_map[$flag] : strtoupper($flag);
$marked = $IMAP->set_flag($uids, $flag);
+
if ($marked != -1)
- {
+ {
$mbox_name = $IMAP->get_mailbox_name();
- $commands = sprintf("this.set_unread_count('%s', %d);\n", $mbox_name, $IMAP->messagecount($mbox_name, 'UNSEEN'));
- rcube_remote_response($commands);
- }
+ $OUTPUT->command('set_unread_count', $mbox_name, $IMAP->messagecount($mbox_name, 'UNSEEN'));
+ $OUTPUT->send();
}
+}
exit;
?>
\ No newline at end of file
diff --git a/program/steps/mail/move_del.inc b/program/steps/mail/move_del.inc
index 8d31e3aa5..fb8a0af4c 100644
--- a/program/steps/mail/move_del.inc
+++ b/program/steps/mail/move_del.inc
@@ -1,101 +1,96 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/move_del.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Move the submitted messages to a specific mailbox or delete them |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
-$REMOTE_REQUEST = TRUE;
-
// move messages
if ($_action=='moveto' && !empty($_GET['_uid']) && !empty($_GET['_target_mbox']))
- {
+{
$count = sizeof(explode(',', ($uids = get_input_value('_uid', RCUBE_INPUT_GET))));
$target = get_input_value('_target_mbox', RCUBE_INPUT_GET);
$moved = $IMAP->move_message($uids, $target, get_input_value('_mbox', RCUBE_INPUT_GET));
if (!$moved)
- {
+ {
// send error message
- $commands = "this.list_mailbox();\n";
- $commands .= show_message('errormoving', 'error');
- rcube_remote_response($commands);
+ $OUTPUT->command('list_mailbox');
+ $OUTPUT->show_message('errormoving', 'error');
+ $OUTPUT->send();
exit;
- }
}
+}
// delete messages
else if ($_action=='delete' && !empty($_GET['_uid']))
- {
+{
$count = sizeof(explode(',', ($uids = get_input_value('_uid', RCUBE_INPUT_GET))));
$del = $IMAP->delete_message($uids, get_input_value('_mbox', RCUBE_INPUT_GET));
if (!$del)
- {
+ {
// send error message
- $commands = "this.list_mailbox();\n";
- $commands .= show_message('errordeleting', 'error');
- rcube_remote_response($commands);
+ $OUTPUT->command('list_mailbox');
+ $OUTPUT->show_message('errordeleting', 'error');
+ $OUTPUT->send();
exit;
- }
}
+}
// unknown action or missing query param
else
- {
exit;
- }
// refresh saved seach set after moving some messages
if (($search_request = get_input_value('_search', RCUBE_INPUT_GPC)) && $IMAP->search_set)
$_SESSION['search'][$search_request] = $IMAP->refresh_search();
// update message count display
$msg_count = $IMAP->messagecount();
$pages = ceil($msg_count / $IMAP->page_size);
-$commands = sprintf("this.set_rowcount('%s');\n", rcmail_get_messagecount_text($msg_count));
-$commands .= sprintf("this.set_env('pagecount', %d);\n", $pages);
+$OUTPUT->set_env('pagecount', $pages);
+$OUTPUT->command('set_rowcount', rcmail_get_messagecount_text($msg_count));
// update mailboxlist
$mbox = $IMAP->get_mailbox_name();
-$commands .= sprintf("this.set_unread_count('%s', %d);\n", $mbox, $IMAP->messagecount($mbox, 'UNSEEN'));
+$OUTPUT->command('set_unread_count', $mbox, $IMAP->messagecount($mbox, 'UNSEEN'));
if ($_action=='moveto' && $target)
- $commands .= sprintf("this.set_unread_count('%s', %d);\n", $target, $IMAP->messagecount($target, 'UNSEEN'));
+ $OUTPUT->command('set_unread_count', $target, $IMAP->messagecount($target, 'UNSEEN'));
-$commands .= sprintf("this.set_quota('%s');\n", $IMAP->get_quota());
+$OUTPUT->command('set_quota', $IMAP->get_quota());
// add new rows from next page (if any)
if ($_GET['_from']!='show' && $pages>1 && $IMAP->list_page < $pages)
- {
+{
$sort_col = isset($_SESSION['sort_col']) ? $_SESSION['sort_col'] : $CONFIG['message_sort_col'];
$sort_order = isset($_SESSION['sort_order']) ? $_SESSION['sort_order'] : $CONFIG['message_sort_order'];
$a_headers = $IMAP->list_headers($mbox, NULL, $sort_col, $sort_order);
$a_headers = array_slice($a_headers, -$count, $count);
- $commands .= rcmail_js_message_list($a_headers);
- }
+ rcmail_js_message_list($a_headers);
+}
// send response
-rcube_remote_response($commands);
+$OUTPUT->send();
-exit;
?>
diff --git a/program/steps/mail/quotadisplay.inc b/program/steps/mail/quotadisplay.inc
index c96a7a7ee..accecdb91 100644
--- a/program/steps/mail/quotadisplay.inc
+++ b/program/steps/mail/quotadisplay.inc
@@ -1,29 +1,28 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/quotadisplay.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Remote call to return the quota image or text |
| |
+-----------------------------------------------------------------------+
| Author: Robin Elfrink <robin@15augustus.nl> |
+-----------------------------------------------------------------------+
$Id$
*/
$display = isset($_GET['_display']) ? $_GET['_display'] : 'text';
$id = isset($_GET['_id']) ? $_GET['_id'] : 'rcmquotadisplay';
$quota = rcmail_quota_content($display);
-$command = sprintf("this.gui_objects.%s.innerHTML = '%s';\n", $id, $quota);
-rcube_remote_response($command);
+$OUTPUT->remote_response(sprintf("this.gui_objects.%s.innerHTML = '%s';\n", $id, $quota));
exit;
?>
diff --git a/program/steps/mail/search.inc b/program/steps/mail/search.inc
index c4b843b55..bef821b40 100644
--- a/program/steps/mail/search.inc
+++ b/program/steps/mail/search.inc
@@ -1,111 +1,109 @@
<?php
/*
+-----------------------------------------------------------------------+
| steps/mail/search.inc |
| |
| Search functions for rc webmail |
| Licensed under the GNU GPL |
| |
+-----------------------------------------------------------------------+
| Author: Benjamin Smith <defitro@gmail.com> |
| Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
*/
$REMOTE_REQUEST = TRUE;
// reset list_page and old search results
$IMAP->set_page(1);
$IMAP->set_search_set(NULL);
$_SESSION['page'] = 1;
// using encodeURI with javascript "should" give us
// a correctly UTF-8 encoded query string
$imap_charset = 'UTF-8';
// get search string
-$str = get_input_value('_search', RCUBE_INPUT_GET);
+$str = get_input_value('_q', RCUBE_INPUT_GET);
$mbox = get_input_value('_mbox', RCUBE_INPUT_GET);
$search_request = md5($mbox.$str);
// Check the search string for type of search
if (preg_match("/^from:/i", $str))
{
list(,$srch) = explode(":", $str);
$subject = "HEADER FROM";
$search = trim($srch);
}
else if (preg_match("/^to:/i", $str))
{
list(,$srch) = explode(":", $str);
$subject = "HEADER TO";
$search = trim($srch);
}
else if (preg_match("/^cc:/i", $str))
{
list(,$srch) = explode(":", $str);
$subject = "HEADER CC";
$search = trim($srch);
}
else if (preg_match("/^subject:/i", $str))
{
list(,$srch) = explode(":", $str);
$subject = "HEADER SUBJECT";
$search = trim($srch);
}
else if (preg_match("/^body:/i", $str))
{
list(,$srch) = explode(":", $str);
$subject = "TEXT";
$search = trim($srch);
}
// search in subject and sender by default
else
{
$subject = array("HEADER SUBJECT", "HEADER FROM");
$search = trim($str);
}
// execute IMAP search
$result = $IMAP->search($mbox, $subject, $search, $imap_charset);
-
-$commands = '';
$count = 0;
// Make sure our $result is legit..
if (is_array($result) && $result[0] != '')
- {
+{
// Get the headers
$result_h = $IMAP->list_header_set($mbox, $result, 1, $_SESSION['sort_col'], $_SESSION['sort_order']);
- $count = count($result);
+ $count = count($result_h);
// save search results in session
if (!is_array($_SESSION['search']))
$_SESSION['search'] = array();
// Make sure we got the headers
if ($result_h != NULL)
- {
+ {
$_SESSION['search'][$search_request] = $IMAP->get_search_set();
- $commands = rcmail_js_message_list($result_h);
- $commands .= show_message('searchsuccessful', 'confirmation', array('nr' => $count));
- }
+ rcmail_js_message_list($result_h);
+ $OUTPUT->show_message('searchsuccessful', 'confirmation', array('nr' => $count));
}
+}
else
- {
- $commands = show_message('searchnomatch', 'warning');
+{
+ $OUTPUT->show_message('searchnomatch', 'warning');
$search_request = -1;
- }
+}
// update message count display
$pages = ceil($count/$IMAP->page_size);
-$commands .= sprintf("\nthis.set_env('search_request', '%s')\n", $search_request);
-$commands .= sprintf("this.set_env('messagecount', %d);\n", $count);
-$commands .= sprintf("this.set_env('pagecount', %d);\n", $pages);
-$commands .= sprintf("this.set_rowcount('%s');\n", rcmail_get_messagecount_text($count, 1));
-rcube_remote_response($commands);
+$OUTPUT->set_env('search_request', $search_request);
+$OUTPUT->set_env('messagecount', $count);
+$OUTPUT->set_env('pagecount', $pages);
+$OUTPUT->command('set_rowcount', rcmail_get_messagecount_text($count, 1));
+$OUTPUT->send();
?>
\ No newline at end of file
diff --git a/program/steps/mail/sendmail.inc b/program/steps/mail/sendmail.inc
index 4a65ee390..bc454b309 100644
--- a/program/steps/mail/sendmail.inc
+++ b/program/steps/mail/sendmail.inc
@@ -1,478 +1,465 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/sendmail.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Compose a new mail message with all headers and attachments |
| and send it using IlohaMail's SMTP methods or with PHP mail() |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
//require_once('lib/smtp.inc');
require_once('include/rcube_smtp.inc');
require_once('lib/html2text.inc');
require_once('lib/rc_mail_mime.inc');
if (!isset($_SESSION['compose']['id']))
{
rcmail_overwrite_action('list');
return;
}
/****** message sending functions ********/
function rcmail_get_identity($id)
{
- global $DB, $CHARSET, $OUTPUT;
+ global $DB, $OUTPUT;
// get identity record
$sql_result = $DB->query("SELECT *, email AS mailto
FROM ".get_table_name('identities')."
WHERE identity_id=?
AND user_id=?
AND del<>1",
$id,$_SESSION['user_id']);
if ($DB->num_rows($sql_result))
{
$sql_arr = $DB->fetch_assoc($sql_result);
$out = $sql_arr;
$name = strpos($sql_arr['name'], ",") ? '"'.$sql_arr['name'].'"' : $sql_arr['name'];
$out['string'] = sprintf('%s <%s>',
- rcube_charset_convert($name, $CHARSET, $OUTPUT->get_charset()),
+ rcube_charset_convert($name, RCMAIL_CHARSET, $OUTPUT->get_charset()),
$sql_arr['mailto']);
return $out;
}
return FALSE;
}
/**
* go from this:
* <img src=".../tiny_mce/plugins/emotions/images/smiley-cool.gif" border="0" alt="Cool" title="Cool" />
*
* to this:
*
* <IMG src="cid:smiley-cool.gif"/>
* ...
* ------part...
* Content-Type: image/gif
* Content-Transfer-Encoding: base64
* Content-ID: <smiley-cool.gif>
*/
function rcmail_attach_emoticons(&$mime_message)
{
global $CONFIG, $INSTALL_PATH;
$htmlContents = $mime_message->getHtmlBody();
// remove any null-byte characters before parsing
$body = preg_replace('/\x00/', '', $htmlContents);
$last_img_pos = 0;
$searchstr = 'program/js/tiny_mce/plugins/emotions/images/';
// keep track of added images, so they're only added once
$included_images = array();
// find emoticon image tags
while ($pos = strpos($body, $searchstr, $last_img_pos))
{
$pos2 = strpos($body, '"', $pos);
$body_pre = substr($body, 0, $pos);
$image_name = substr($body,
$pos + strlen($searchstr),
$pos2 - ($pos + strlen($searchstr)));
// sanitize image name so resulting attachment doesn't leave images dir
$image_name = preg_replace('/[^a-zA-Z0-9_\.\-]/i','',$image_name);
$body_post = substr($body, $pos2);
if (! in_array($image_name, $included_images))
{
// add the image to the MIME message
$img_file = $INSTALL_PATH . '/' . $searchstr . $image_name;
if(! $mime_message->addHTMLImage($img_file, 'image/gif', '', true, '_' . $image_name))
- {
- show_message("emoticonerror", 'error');
- }
+ $OUTPUT->show_message("emoticonerror", 'error');
+
array_push($included_images, $image_name);
}
$body = $body_pre . 'cid:_' . $image_name . $body_post;
$last_img_pos = $pos2;
}
$mime_message->setHTMLBody($body);
}
if (strlen($_POST['_draft_saveid']) > 3)
$olddraftmessageid = get_input_value('_draft_saveid', RCUBE_INPUT_POST);
$message_id = sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), rcmail_mail_domain($_SESSION['imap_host']));
$savedraft = !empty($_POST['_draft']) ? TRUE : FALSE;
// remove all scripts and act as called in frame
$OUTPUT->reset();
-$_framed = TRUE;
+$OUTPUT->framed = TRUE;
/****** check submission and compose message ********/
if (!$savedraft && empty($_POST['_to']) && empty($_POST['_subject']) && $_POST['_message'])
{
- show_message("sendingfailed", 'error');
- rcube_iframe_response();
+ $OUTPUT->show_message("sendingfailed", 'error');
+ $OUTPUT->send('iframe');
return;
}
// set default charset
$input_charset = $OUTPUT->get_charset();
$message_charset = isset($_POST['_charset']) ? $_POST['_charset'] : $input_charset;
$mailto_regexp = array('/[,;]\s*[\r\n]+/', '/[\r\n]+/', '/[,;]\s*$/m', '/;/');
$mailto_replace = array(', ', ', ', '', ',');
// replace new lines and strip ending ', '
$mailto = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_to', RCUBE_INPUT_POST, TRUE, $message_charset));
// decode address strings
$to_address_arr = $IMAP->decode_address_list($mailto);
$identity_arr = rcmail_get_identity(get_input_value('_from', RCUBE_INPUT_POST));
$from = $identity_arr['mailto'];
$first_to = is_array($to_address_arr[0]) ? $to_address_arr[0]['mailto'] : $mailto;
if (empty($identity_arr['string']))
$identity_arr['string'] = $from;
// compose headers array
$headers = array('Date' => date('D, j M Y H:i:s O'),
- 'From' => rcube_charset_convert($identity_arr['string'], $CHARSET, $message_charset),
+ 'From' => rcube_charset_convert($identity_arr['string'], RCMAIL_CHARSET, $message_charset),
'To' => $mailto);
// additional recipients
if (!empty($_POST['_cc']))
$headers['Cc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_cc', RCUBE_INPUT_POST, TRUE, $message_charset));
if (!empty($_POST['_bcc']))
$headers['Bcc'] = preg_replace($mailto_regexp, $mailto_replace, get_input_value('_bcc', RCUBE_INPUT_POST, TRUE, $message_charset));
if (!empty($identity_arr['bcc']))
$headers['Bcc'] = ($headers['Bcc'] ? $headers['Bcc'].', ' : '') . $identity_arr['bcc'];
// add subject
$headers['Subject'] = trim(get_input_value('_subject', RCUBE_INPUT_POST, FALSE, $message_charset));
if (!empty($identity_arr['organization']))
$headers['Organization'] = $identity_arr['organization'];
if (!empty($identity_arr['reply-to']))
$headers['Reply-To'] = $identity_arr['reply-to'];
if (!empty($_SESSION['compose']['reply_msgid']))
$headers['In-Reply-To'] = $_SESSION['compose']['reply_msgid'];
if (!empty($_SESSION['compose']['references']))
$headers['References'] = $_SESSION['compose']['references'];
if (!empty($_POST['_priority']))
{
$priority = (int)$_POST['_priority'];
$a_priorities = array(1=>'highest', 2=>'high', 4=>'low', 5=>'lowest');
if ($str_priority = $a_priorities[$priority])
$headers['X-Priority'] = sprintf("%d (%s)", $priority, ucfirst($str_priority));
}
if (!empty($_POST['_receipt']))
{
$headers['Return-Receipt-To'] = $identity_arr['string'];
$headers['Disposition-Notification-To'] = $identity_arr['string'];
}
// additional headers
$headers['Message-ID'] = $message_id;
$headers['X-Sender'] = $from;
if (!empty($CONFIG['useragent']))
$headers['User-Agent'] = $CONFIG['useragent'];
// fetch message body
$message_body = get_input_value('_message', RCUBE_INPUT_POST, TRUE, $message_charset);
// append generic footer to all messages
if (!empty($CONFIG['generic_message_footer']))
{
$file = realpath($CONFIG['generic_message_footer']);
if($fp = fopen($file, 'r'))
{
$content = fread($fp, filesize($file));
fclose($fp);
$message_body .= "\r\n" . rcube_charset_convert($content, 'UTF-8', $message_charset);
}
}
// try to autodetect operating system and use the correct line endings
// use the configured delimiter for headers
if (!empty($CONFIG['mail_header_delimiter']))
$header_delm = $CONFIG['mail_header_delimiter'];
else if (strtolower(substr(PHP_OS, 0, 3)=='win'))
$header_delm = "\r\n";
else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
$header_delm = "\r\n";
else
$header_delm = "\n";
$isHtmlVal = strtolower(get_input_value('_is_html', RCUBE_INPUT_POST));
$isHtml = ($isHtmlVal == "1");
// create extended PEAR::Mail_mime instance
$MAIL_MIME = new rc_mail_mime($header_delm);
// For HTML-formatted messages, construct the MIME message with both
// the HTML part and the plain-text part
if ($isHtml)
{
$MAIL_MIME->setHTMLBody($message_body);
// add a plain text version of the e-mail as an alternative part.
$h2t = new html2text($message_body);
$plainTextPart = $h2t->get_text();
$MAIL_MIME->setTXTBody($plainTextPart);
// look for "emoticon" images from TinyMCE and copy into message as attachments
rcmail_attach_emoticons($MAIL_MIME);
}
else
{
$MAIL_MIME->setTXTBody($message_body, FALSE, TRUE);
}
// add stored attachments, if any
if (is_array($_SESSION['compose']['attachments']))
foreach ($_SESSION['compose']['attachments'] as $attachment)
$MAIL_MIME->addAttachment($attachment['path'], $attachment['mimetype'], $attachment['name'], true, 'base64', 'attachment', $message_charset);
// add submitted attachments
if (is_array($_FILES['_attachments']['tmp_name']))
foreach ($_FILES['_attachments']['tmp_name'] as $i => $filepath)
$MAIL_MIME->addAttachment($filepath, $files['type'][$i], $files['name'][$i], true, 'base64', 'attachment', $message_charset);
// chose transfer encoding
$charset_7bit = array('ASCII', 'ISO-2022-JP', 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-15');
$transfer_encoding = in_array(strtoupper($message_charset), $charset_7bit) ? '7bit' : '8bit';
// encoding settings for mail composing
$message_param = array('text_encoding' => $transfer_encoding,
'html_encoding' => 'quoted-printable',
'head_encoding' => 'quoted-printable',
'head_charset' => $message_charset,
'html_charset' => $message_charset,
'text_charset' => $message_charset);
// compose message body and get headers
$msg_body = $MAIL_MIME->get($message_param);
// unset to save memory.
unset($MAIL_MIME->_parts);
// encoding subject header with mb_encode provides better results with asian characters
if ($MBSTRING && function_exists("mb_encode_mimeheader"))
{
mb_internal_encoding($message_charset);
$mb_subject = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
- mb_internal_encoding($CHARSET);
+ mb_internal_encoding(RCMAIL_CHARSET);
}
// Begin SMTP Delivery Block
if (!$savedraft) {
// send thru SMTP server using custom SMTP library
if ($CONFIG['smtp_server'])
{
// generate list of recipients
$a_recipients = array($mailto);
if (strlen($headers['Cc']))
$a_recipients[] = $headers['Cc'];
if (strlen($headers['Bcc']))
$a_recipients[] = $headers['Bcc'];
// clean Bcc from header for recipients
$send_headers = $headers;
unset($send_headers['Bcc']);
if (!empty($mb_subject))
$send_headers['Subject'] = $mb_subject;
// send message
$smtp_response = array();
$sent = smtp_mail($from, $a_recipients, $MAIL_MIME->txtHeaders($send_headers), $msg_body, $smtp_response);
// log error
if (!$sent)
- {
- raise_error(array('code' => 800,
- 'type' => 'smtp',
- 'line' => __LINE__,
- 'file' => __FILE__,
+ raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
- }
}
// send mail using PHP's mail() function
else
{
// unset some headers because they will be added by the mail() function
$headers_enc = $MAIL_MIME->headers($headers);
$headers_php = $MAIL_MIME->_headers;
unset($headers_php['To'], $headers_php['Subject']);
if (!empty($mb_subject))
$headers_enc['Subject'] = $mb_subject;
// reset stored headers and overwrite
$MAIL_MIME->_headers = array();
$header_str = $MAIL_MIME->txtHeaders($headers_php);
if (ini_get('safe_mode'))
$sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
else
$sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
}
// return to compose page if sending failed
if (!$sent)
{
- show_message("sendingfailed", 'error');
- rcube_iframe_response();
+ $OUTPUT->show_message("sendingfailed", 'error');
+ $OUTPUT->send('iframe');
return;
}
// set repliead flag
if ($_SESSION['compose']['reply_uid'])
$IMAP->set_flag($_SESSION['compose']['reply_uid'], 'ANSWERED');
} // End of SMTP Delivery Block
// Determine which folder to save message
if ($savedraft)
$store_target = 'drafts_mbox';
else
$store_target = 'sent_mbox';
if ($CONFIG[$store_target])
{
// create string of complete message headers
$header_str = $MAIL_MIME->txtHeaders($headers);
// check if mailbox exists
if (!in_array_nocase($CONFIG[$store_target], $IMAP->list_mailboxes()))
$store_folder = $IMAP->create_mailbox($CONFIG[$store_target], TRUE);
else
$store_folder = TRUE;
// add headers to message body
$msg_body = $header_str."\r\n".$msg_body;
// append message to sent box
if ($store_folder)
$saved = $IMAP->save_message($CONFIG[$store_target], $msg_body);
// raise error if saving failed
if (!$saved)
{
- raise_error(array('code' => 800,
- 'type' => 'imap',
- 'file' => __FILE__,
+ raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
'message' => "Could not save message in $CONFIG[$store_target]"), TRUE, FALSE);
- show_message('errorsaving', 'error');
- rcube_iframe_response($errorout);
+ $OUTPUT->show_message('errorsaving', 'error');
+ $OUTPUT->send('iframe');
}
if ($olddraftmessageid)
{
// delete previous saved draft
$a_deleteid = $IMAP->search($CONFIG['drafts_mbox'],'HEADER Message-ID',$olddraftmessageid);
$deleted = $IMAP->delete_message($IMAP->get_uid($a_deleteid[0],$CONFIG['drafts_mbox']),$CONFIG['drafts_mbox']);
// raise error if deletion of old draft failed
if (!$deleted)
- raise_error(array('code' => 800,
- 'type' => 'imap',
- 'file' => __FILE__,
+ raise_error(array('code' => 800, 'type' => 'imap', 'file' => __FILE__,
'message' => "Could not delete message from ".$CONFIG['drafts_mbox']), TRUE, FALSE);
}
}
if ($savedraft)
{
- // clear the "saving message" busy status, and display success
- show_message('messagesaved', 'confirmation');
-
- // update "_draft_saveid" on the page, which is used to delete a previous draft
- $frameout = "var foundid = parent.rcube_find_object('_draft_saveid', parent.document);\n";
- $frameout .= sprintf("foundid.value = '%s';\n", str_replace(array('<','>'), "", $message_id));
+ // display success
+ $OUTPUT->show_message('messagesaved', 'confirmation');
- // update the "cmp_hash" to prevent "Unsaved changes" warning
- $frameout .= sprintf("parent.%s.cmp_hash = parent.%s.compose_field_hash();\n", $JS_OBJECT_NAME, $JS_OBJECT_NAME);
+ // update "_draft_saveid" and the "cmp_hash" to prevent "Unsaved changes" warning
+ $OUTPUT->command('set_draft_id', str_replace(array('<','>'), "", $message_id));
+ $OUTPUT->command('compose_field_hash', true);
// start the auto-save timer again
- $frameout .= sprintf("parent.%s.auto_save_start();", $JS_OBJECT_NAME);
+ $OUTPUT->command('auto_save_start');
- // send html page with JS calls as response
- rcube_iframe_response($frameout);
+ $OUTPUT->send('iframe');
}
else
{
if ($CONFIG['smtp_log'])
{
- $log_entry = sprintf("[%s] User: %d on %s; Message for %s; %s\n",
- date("d-M-Y H:i:s O", mktime()),
- $_SESSION['user_id'],
- $_SERVER['REMOTE_ADDR'],
- $mailto,
- !empty($smtp_response) ? join('; ', $smtp_response) : '');
+ $log_entry = sprintf(
+ "[%s] User: %d on %s; Message for %s; %s\n",
+ date("d-M-Y H:i:s O", mktime()),
+ $_SESSION['user_id'],
+ $_SERVER['REMOTE_ADDR'],
+ $mailto,
+ !empty($smtp_response) ? join('; ', $smtp_response) : '');
if ($fp = @fopen($CONFIG['log_dir'].'/sendmail', 'a'))
{
fwrite($fp, $log_entry);
fclose($fp);
}
}
rcmail_compose_cleanup();
- rcube_iframe_response(sprintf("parent.$JS_OBJECT_NAME.sent_successfully('%s');",
- JQ(rcube_label('messagesent'))));
+ $OUTPUT->command('sent_successfully', rcube_label('messagesent'));
+ $OUTPUT->send('iframe');
}
?>
diff --git a/program/steps/mail/show.inc b/program/steps/mail/show.inc
index 19e6e56a9..6c247aea9 100644
--- a/program/steps/mail/show.inc
+++ b/program/steps/mail/show.inc
@@ -1,177 +1,180 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/show.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Display a mail message similar as a usual mail application does |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
require_once('Mail/mimeDecode.php');
$PRINT_MODE = $_action=='print' ? TRUE : FALSE;
// similar code as in program/steps/mail/get.inc
if ($_GET['_uid'])
{
$MESSAGE = array('UID' => get_input_value('_uid', RCUBE_INPUT_GET));
$MESSAGE['headers'] = $IMAP->get_headers($MESSAGE['UID']);
// go back to list if message not found (wrong UID)
if (!$MESSAGE['headers'])
{
- show_message('messageopenerror', 'error');
+ $OUTPUT->show_message('messageopenerror', 'error');
if ($_action=='preview' && template_exists('messagepreview'))
parse_template('messagepreview');
else
{
$_action = 'list';
return;
}
}
// calculate Etag for this request
$etag = md5($MESSAGE['UID'].$IMAP->get_mailbox_name().session_id().($PRINT_MODE?1:0));
// allow caching, unless remote images are present
if ((bool)get_input_value('_safe', RCUBE_INPUT_GET))
send_nocacheing_headers();
else
send_modified_header($_SESSION['login_time'], $etag);
-
- $MESSAGE['subject'] = $IMAP->decode_header($MESSAGE['headers']->subject);
+ $MESSAGE['subject'] = rcube_imap::decode_mime_string($MESSAGE['headers']->subject, $MESSAGE['headers']->charset);
+ $OUTPUT->set_pagetitle($MESSAGE['subject']);
if ($MESSAGE['structure'] = $IMAP->get_structure($MESSAGE['UID']))
list($MESSAGE['parts'], $MESSAGE['attachments']) = rcmail_parse_message(
$MESSAGE['structure'],
array('safe' => (bool)$_GET['_safe'],
'prefer_html' => $CONFIG['prefer_html'],
'get_url' => $GET_URL.'&_part=%s')
);
else
$MESSAGE['body'] = $IMAP->get_body($MESSAGE['UID']);
// mark message as read
if (!$MESSAGE['headers']->seen && $_action != 'preview')
$IMAP->set_flag($MESSAGE['UID'], 'SEEN');
// give message uid to the client
- $javascript = sprintf("%s.set_env('uid', '%s');\n", $JS_OBJECT_NAME, $MESSAGE['UID']);
- $javascript .= sprintf("%s.set_env('safemode', '%b');", $JS_OBJECT_NAME, $_GET['_safe']);
+ $OUTPUT->set_env('uid', $MESSAGE['UID']);
+ $OUTPUT->set_env('safemode', (bool)$_GET['_safe']);
$next = $prev = -1;
// get previous, first, next and last message UID
if (!($_SESSION['sort_col'] == 'date' && $_SESSION['sort_order'] == 'DESC') &&
$IMAP->get_capability('sort'))
{
// Only if we use custom sorting
$a_msg_index = $IMAP->message_index(NULL, $_SESSION['sort_col'], $_SESSION['sort_order']);
$MESSAGE['index'] = array_search((string)$MESSAGE['UID'], $a_msg_index, TRUE);
$prev = isset($a_msg_index[$MESSAGE['index']-1]) ? $a_msg_index[$MESSAGE['index']-1] : -1 ;
$first = count($a_msg_index)>0 ? $a_msg_index[0] : -1;
$next = isset($a_msg_index[$MESSAGE['index']+1]) ? $a_msg_index[$MESSAGE['index']+1] : -1 ;
$last = count($a_msg_index)>0 ? $a_msg_index[count($a_msg_index)-1] : -1;
}
else
{
// this assumes that we are sorted by date_DESC
$seq = $IMAP->get_id($MESSAGE['UID']);
$prev = $IMAP->get_uid($seq + 1);
$first = $IMAP->get_uid($IMAP->messagecount());
$next = $IMAP->get_uid($seq - 1);
$last = $IMAP->get_uid(1);
$MESSAGE['index'] = $IMAP->messagecount() - $seq;
}
if ($prev > 0)
- $javascript .= sprintf("\n%s.set_env('prev_uid', '%s');", $JS_OBJECT_NAME, $prev);
+ $OUTPUT->set_env('prev_uid', $prev);
if ($first >0)
- $javascript .= sprintf("\n%s.set_env('first_uid', '%s');", $JS_OBJECT_NAME, $first);
+ $OUTPUT->set_env('first_uid', $first);
if ($next > 0)
- $javascript .= sprintf("\n%s.set_env('next_uid', '%s');", $JS_OBJECT_NAME, $next);
+ $OUTPUT->set_env('next_uid', $next);
if ($last >0)
- $javascript .= sprintf("\n%s.set_env('last_uid', '%s');", $JS_OBJECT_NAME, $last);
-
- $OUTPUT->add_script($javascript);
+ $OUTPUT->set_env('last_uid', $last);
}
function rcmail_message_attachments($attrib)
{
- global $CONFIG, $OUTPUT, $PRINT_MODE, $MESSAGE, $GET_URL, $JS_OBJECT_NAME;
+ global $CONFIG, $OUTPUT, $PRINT_MODE, $MESSAGE, $GET_URL;
if (sizeof($MESSAGE['attachments']))
{
// allow the following attributes to be added to the <ul> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
$out = '<ul' . $attrib_str . ">\n";
foreach ($MESSAGE['attachments'] as $attach_prop)
{
if ($PRINT_MODE)
$out .= sprintf('<li>%s (%s)</li>'."\n",
$attach_prop->filename,
show_bytes($attach_prop->size));
else
$out .= sprintf('<li><a href="%s&amp;_part=%s" onclick="return %s.command(\'load-attachment\',{part:\'%s\', mimetype:\'%s\'},this)">%s</a></li>'."\n",
htmlspecialchars($GET_URL),
$attach_prop->mime_id,
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
$attach_prop->mime_id,
$attach_prop->mimetype,
$attach_prop->filename);
}
$out .= "</ul>";
return $out;
}
}
function rcmail_remote_objects_msg($attrib)
{
- global $CONFIG, $OUTPUT, $JS_OBJECT_NAME;
+ global $CONFIG, $OUTPUT;
if (!$attrib['id'])
$attrib['id'] = 'rcmremoteobjmsg';
// allow the following attributes to be added to the <div> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
$out = '<div' . $attrib_str . ">";
$out .= sprintf('%s&nbsp;<a href="#loadimages" onclick="%s.command(\'load-images\')">%s</a>',
Q(rcube_label('blockedimages')),
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
Q(rcube_label('showimages')));
$out .= '</div>';
- $OUTPUT->add_script(sprintf("%s.gui_object('remoteobjectsmsg', '%s');", $JS_OBJECT_NAME, $attrib['id']));
+ $OUTPUT->add_gui_object('remoteobjectsmsg', $attrib['id']);
return $out;
}
+$OUTPUT->add_handlers(array(
+ 'messageattachments' => 'rcmail_message_attachments',
+ 'blockedobjects' => 'rcmail_remote_objects_msg'));
+
+
if ($_action=='print' && template_exists('printmessage'))
parse_template('printmessage');
else if ($_action=='preview' && template_exists('messagepreview'))
parse_template('messagepreview');
else
parse_template('message');
?>
\ No newline at end of file
diff --git a/program/steps/mail/upload.inc b/program/steps/mail/upload.inc
index 06ed26591..a28c3e8e2 100644
--- a/program/steps/mail/upload.inc
+++ b/program/steps/mail/upload.inc
@@ -1,90 +1,85 @@
<?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;
}
// use common temp dir for file uploads
$temp_dir = unslashify($CONFIG['temp_dir']);
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);
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'],
- Q(rcube_label('delete')));
+ $button = sprintf(
+ '<img src="%s/images/icons/remove-attachment.png" alt="%s" border="0" style="padding-right:2px;vertical-align:middle" />',
+ $CONFIG['skin_path'],
+ Q(rcube_label('delete')));
else
$button = Q(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,
- Q(rcube_label('delete')),
- $button,
- Q($_FILES['_attachments']['name'][$i]));
-
- $response .= sprintf('parent.%s.add2attachment_list(\'rcmfile%d\',\'%s\');',
- $JS_OBJECT_NAME,
- $id,
- $content);
+ $content = sprintf(
+ '<a href="#delete" onclick="return %s.command(\'remove-attachment\', \'rcmfile%d\', this)" title="%s">%s</a>%s',
+ JS_OBJECT_NAME,
+ $id,
+ Q(rcube_label('delete')),
+ $button,
+ Q($_FILES['_attachments']['name'][$i]));
+
+ $OUTPUT->command('add2attachment_list', "rcmfile$id", $content);
}
else // upload failed
{
$err = $_FILES['_attachments']['error'][$i];
if ($err == UPLOAD_ERR_INI_SIZE || $err == UPLOAD_ERR_FORM_SIZE)
$msg = rcube_label(array('name' => 'filesizeerror', 'vars' => array('size' => show_bytes(parse_bytes(ini_get('upload_max_filesize'))))));
else
$msg = rcube_label('fileuploaderror');
- $response = sprintf("parent.%s.display_message('%s', 'error');", $JS_OBJECT_NAME, JQ($msg));
+ $OUTPUT->command('display_message', $msg, 'error');
}
}
// 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);
+$OUTPUT->command('show_attachment_form', false);
+$OUTPUT->command('auto_save_start', false);
+$OUTPUT->send('iframe');
?>
diff --git a/program/steps/settings/delete_identity.inc b/program/steps/settings/delete_identity.inc
index 560a2b10b..3614a3e96 100644
--- a/program/steps/settings/delete_identity.inc
+++ b/program/steps/settings/delete_identity.inc
@@ -1,51 +1,48 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/settings/delete_identity.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Delete the submitted identities (IIDs) from the database |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
if (($ids = get_input_value('_iid', RCUBE_INPUT_GET)) && preg_match('/^[0-9]+(,[0-9]+)*$/', $ids))
- {
- $DB->query("UPDATE ".get_table_name('identities')."
- SET del=1
- WHERE user_id=?
- AND identity_id IN (".$ids.")",
- $_SESSION['user_id']);
+{
+ $DB->query(
+ "UPDATE ".get_table_name('identities')."
+ SET del=1
+ WHERE user_id=?
+ AND identity_id IN (".$ids.")",
+ $_SESSION['user_id']);
$count = $DB->affected_rows();
if ($count)
- {
- $commands = show_message('deletedsuccessfully', 'confirmation');
- }
+ $OUTPUT->show_message('deletedsuccessfully', 'confirmation');
// send response
- if ($REMOTE_REQUEST)
- rcube_remote_response($commands);
- }
+ if ($OUTPUT->ajax_call)
+ $OUTPUT->send();
+}
-if ($REMOTE_REQUEST)
+if ($OUTPUT->ajax_call)
exit;
// go to identities page
-$_action = 'identities';
+rcmail_overwrite_action('identities');
-// overwrite action variable
-$OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $_action));
?>
diff --git a/program/steps/settings/edit_identity.inc b/program/steps/settings/edit_identity.inc
index 5fa531a11..51a0cd0a0 100644
--- a/program/steps/settings/edit_identity.inc
+++ b/program/steps/settings/edit_identity.inc
@@ -1,145 +1,144 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/settings/edit_identity.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Show edit form for a identity record or to add a new one |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
if (($_GET['_iid'] || $_POST['_iid']) && $_action=='edit-identity')
{
$DB->query("SELECT * FROM ".get_table_name('identities')."
WHERE identity_id=?
AND user_id=?
AND del<>1",
get_input_value('_iid', RCUBE_INPUT_GPC),
$_SESSION['user_id']);
$IDENTITY_RECORD = $DB->fetch_assoc();
if (is_array($IDENTITY_RECORD))
- $OUTPUT->add_script(sprintf("%s.set_env('iid', '%s');", $JS_OBJECT_NAME, $IDENTITY_RECORD['identity_id']));
-
- $PAGE_TITLE = rcube_label('edititem');
+ $OUTPUT->set_env('iid', $IDENTITY_RECORD['identity_id']);
+
+ $OUTPUT->set_pagetitle(rcube_label('edititem'));
}
else
- $PAGE_TITLE = rcube_label('newitem');
+ $OUTPUT->set_pagetitle(rcube_label('newitem'));
$OUTPUT->include_script('list.js');
function rcube_identity_form($attrib)
{
- global $IDENTITY_RECORD, $JS_OBJECT_NAME, $OUTPUT;
+ global $IDENTITY_RECORD, $OUTPUT;
$OUTPUT->include_script('tiny_mce/tiny_mce_src.js');
$OUTPUT->add_script("tinyMCE.init({ mode : 'specific_textareas'," .
"apply_source_formatting : true," .
"content_css : '\$__skin_path' + '/editor_content.css'," .
"popups_css : '\$__skin_path' + '/editor_popups.css'," .
"editor_css : '\$__skin_path' + '/editor_ui.css'," .
"theme : 'advanced'," .
"theme_advanced_toolbar_location : 'top'," .
"theme_advanced_toolbar_align : 'left'," .
"theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,separator,outdent,indent,charmap,hr'," .
"theme_advanced_buttons2 : 'link,unlink,code,forecolor,fontselect,fontsizeselect'," .
"theme_advanced_buttons3 : '' });");
if (!$IDENTITY_RECORD && $GLOBALS['_action']!='add-identity')
return rcube_label('notfound');
// add some labels to client
- rcube_add_label('noemailwarning');
- rcube_add_label('nonamewarning');
+ rcube_add_label('noemailwarning', 'nonamewarning');
list($form_start, $form_end) = get_form_tags($attrib, 'save-identity', array('name' => '_iid', 'value' => $IDENTITY_RECORD['identity_id']));
unset($attrib['form']);
// list of available cols
$a_show_cols = array('name' => array('type' => 'text'),
'email' => array('type' => 'text'),
'organization' => array('type' => 'text'),
'reply-to' => array('type' => 'text', 'label' => 'replyto'),
'bcc' => array('type' => 'text'),
'signature' => array('type' => 'textarea', 'size' => "40", 'rows' => "6"),
'html_signature'=>array('type' => 'checkbox', 'label' => 'htmlsignature', 'onclick' => 'return rcmail.toggle_editor(this, \'_signature\');'),
'standard' => array('type' => 'checkbox', 'label' => 'setdefault'));
// a specific part is requested
if ($attrib['part'])
{
$colprop = $a_show_cols[$attrib['part']];
if (is_array($colprop))
{
$out = $form_start;
$out .= rcmail_get_edit_field($attrib['part'], $IDENTITY_RECORD[$attrib['part']], $attrib, $colprop['type']);
return $out;
}
else
return '';
}
// return the complete edit form as table
$out = "$form_start<table>\n\n";
foreach ($a_show_cols as $col => $colprop)
{
$attrib['id'] = 'rcmfd_'.$col;
if (strlen($colprop['onclick']))
$attrib['onclick'] = $colprop['onclick'];
else
unset($attrib['onclick']);
if ($col == 'signature')
{
$attrib['size'] = $colprop['size'];
$attrib['rows'] = $colprop['rows'];
$attrib['mce_editable'] = $IDENTITY_RECORD['html_signature'] ? "true" : "false";
}
else
{
unset($attrib['size']);
unset($attrib['rows']);
unset($attrib['mce_editable']);
}
$label = strlen($colprop['label']) ? $colprop['label'] : $col;
$value = rcmail_get_edit_field($col, $IDENTITY_RECORD[$col], $attrib, $colprop['type']);
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$attrib['id'],
Q(rcube_label($label)),
$value);
}
$out .= "\n</table>$form_end";
return $out;
}
-
+$OUTPUT->add_handler('identityform', 'rcube_identity_form');
if ($_action=='add-identity' && template_exists('addidentity'))
parse_template('addidentity');
parse_template('editidentity');
?>
diff --git a/program/steps/settings/func.inc b/program/steps/settings/func.inc
index e51f6838e..91212e174 100644
--- a/program/steps/settings/func.inc
+++ b/program/steps/settings/func.inc
@@ -1,269 +1,275 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/settings/func.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Provide functionality for user's settings & preferences |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
// get user record
$sql_result = $DB->query("SELECT username, mail_host FROM ".get_table_name('users')."
WHERE user_id=?",
$_SESSION['user_id']);
if ($USER_DATA = $DB->fetch_assoc($sql_result))
- $PAGE_TITLE = sprintf('%s %s@%s', rcube_label('settingsfor'), $USER_DATA['username'], $USER_DATA['mail_host']);
+ $OUTPUT->set_pagetitle(sprintf('%s %s@%s', rcube_label('settingsfor'), $USER_DATA['username'], $USER_DATA['mail_host']));
function rcmail_user_prefs_form($attrib)
{
global $DB, $CONFIG, $sess_user_lang;
$no_override = is_array($CONFIG['dont_override']) ? array_flip($CONFIG['dont_override']) : array();
// add some labels to client
rcube_add_label('nopagesizewarning');
list($form_start, $form_end) = get_form_tags($attrib, 'save-prefs');
unset($attrib['form']);
// 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'));
// return the complete edit form as table
$out = "$form_start<table" . $attrib_str . ">\n\n";
// show language selection
if (!isset($no_override['language']))
{
$a_lang = rcube_list_languages();
asort($a_lang);
$field_id = 'rcmfd_lang';
$select_lang = new select(array('name' => '_language', 'id' => $field_id));
$select_lang->add(array_values($a_lang), array_keys($a_lang));
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('language')),
$select_lang->show($sess_user_lang));
}
// show page size selection
if (!isset($no_override['timezone']))
{
$field_id = 'rcmfd_timezone';
$select_timezone = new select(array('name' => '_timezone', 'id' => $field_id));
$select_timezone->add('(GMT -11:00) Midway Island, Samoa', '-11');
$select_timezone->add('(GMT -10:00) Hawaii', '-10');
$select_timezone->add('(GMT -9:00) Alaska', '-9');
$select_timezone->add('(GMT -8:00) Pacific Time (US/Canada)', '-8');
$select_timezone->add('(GMT -7:00) Mountain Time (US/Canada)', '-7');
$select_timezone->add('(GMT -6:00) Central Time (US/Canada), Mexico City', '-6');
$select_timezone->add('(GMT -5:00) Eastern Time (US/Canada), Bogota, Lima', '-5');
$select_timezone->add('(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz', '-4');
$select_timezone->add('(GMT -3:00) Brazil, Buenos Aires, Georgetown', '-3');
$select_timezone->add('(GMT -3:30) Nfld Time (Canada), Nfld, S. Labador', '-3.5');
$select_timezone->add('(GMT -2:00) Mid-Atlantic', '-2');
$select_timezone->add('(GMT -1:00) Azores, Cape Verde Islands', '-1');
$select_timezone->add('(GMT) Western Europe, London, Lisbon, Casablanca', '0');
$select_timezone->add('(GMT +1:00) Central European Time', '1');
$select_timezone->add('(GMT +2:00) EET: Kaliningrad, South Africa', '2');
$select_timezone->add('(GMT +3:00) Baghdad, Kuwait, Riyadh, Moscow, Nairobi', '3');
$select_timezone->add('(GMT +3:30) Tehran', '3.5');
$select_timezone->add('(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi', '4');
$select_timezone->add('(GMT +4:30) Kabul', '4.5');
$select_timezone->add('(GMT +5:00) Ekaterinburg, Islamabad, Karachi', '5');
$select_timezone->add('(GMT +5:30) Chennai, Kolkata, Mumbai, New Delhi', '5.5');
$select_timezone->add('(GMT +5:45) Kathmandu', '5.75');
$select_timezone->add('(GMT +6:00) Almaty, Dhaka, Colombo', '6');
$select_timezone->add('(GMT +7:00) Bangkok, Hanoi, Jakarta', '7');
$select_timezone->add('(GMT +8:00) Beijing, Perth, Singapore, Taipei', '8');
$select_timezone->add('(GMT +9:00) Tokyo, Seoul, Yakutsk', '9');
$select_timezone->add('(GMT +9:30) Adelaide, Darwin', '9.5');
$select_timezone->add('(GMT +10:00) EAST/AEST: Guam, Vladivostok', '10');
$select_timezone->add('(GMT +11:00) Magadan, Solomon Islands', '11');
$select_timezone->add('(GMT +12:00) Auckland, Wellington, Kamchatka', '12');
$select_timezone->add('(GMT +13:00) Tonga, Pheonix Islands', '13');
$select_timezone->add('(GMT +14:00) Kiribati', '14');
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('timezone')),
$select_timezone->show($CONFIG['timezone']));
}
// daylight savings
if (!isset($no_override['dst_active']))
{
$field_id = 'rcmfd_dst';
$input_dst = new checkbox(array('name' => '_dst_active', 'id' => $field_id, 'value' => 1));
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('dstactive')),
$input_dst->show($CONFIG['dst_active']));
}
// show page size selection
if (!isset($no_override['pagesize']))
{
$field_id = 'rcmfd_pgsize';
$input_pagesize = new textfield(array('name' => '_pagesize', 'id' => $field_id, 'size' => 5));
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('pagesize')),
$input_pagesize->show($CONFIG['pagesize']));
}
// MM: Show checkbox for toggling 'pretty dates'
if (!isset($no_override['prettydate']))
{
$field_id = 'rcmfd_prettydate';
$input_prettydate = new checkbox(array('name' => '_pretty_date', 'id' => $field_id, 'value' => 1));
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('prettydate')),
$input_prettydate->show($CONFIG['prettydate']?1:0));
}
// show checkbox for HTML/plaintext messages
if (!isset($no_override['prefer_html']))
{
$field_id = 'rcmfd_htmlmsg';
$input_pagesize = new checkbox(array('name' => '_prefer_html', 'id' => $field_id, 'value' => 1));
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('preferhtml')),
$input_pagesize->show($CONFIG['prefer_html']?1:0));
}
// Show checkbox for HTML Editor
if (!isset($no_override['htmleditor']))
{
$field_id = 'rcmfd_htmleditor';
$input_htmleditor = new checkbox(array('name' => '_htmleditor', 'id' => $field_id, 'value' => 1));
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('htmleditor')),
$input_htmleditor->show($CONFIG['htmleditor']?1:0));
}
// show config parameter for preview pane
if (!isset($no_override['preview_pane']))
{
$field_id = 'rcmfd_preview';
$input_preview = new checkbox(array('name' => '_preview_pane', 'id' => $field_id, 'value' => 1));
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('previewpane')),
$input_preview->show($CONFIG['preview_pane']?1:0));
}
if (!empty($CONFIG['drafts_mbox']) && !isset($no_override['draft_autosave']))
{
$field_id = 'rcmfd_autosave';
$select_autosave = new select(array('name' => '_draft_autosave', 'id' => $field_id));
$select_autosave->add(rcube_label('never'), 0);
foreach (array(3, 5, 10) as $i => $min)
$select_autosave->add(rcube_label(array('name' => 'everynminutes', 'vars' => array('n' => $min))), $min*60);
$out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
$field_id,
Q(rcube_label('autosavedraft')),
$select_autosave->show($CONFIG['draft_autosave']));
}
$out .= "\n</table>$form_end";
return $out;
}
function rcmail_identities_list($attrib)
{
- global $DB, $CONFIG, $OUTPUT, $JS_OBJECT_NAME;
+ global $DB, $CONFIG, $OUTPUT;
// get contacts from DB
$sql_result = $DB->query("SELECT * FROM ".get_table_name('identities')."
WHERE del<>1
AND user_id=?
ORDER BY standard DESC, name ASC",
$_SESSION['user_id']);
// add id to message list table if not specified
if (!strlen($attrib['id']))
$attrib['id'] = 'rcmIdentitiesList';
// define list of cols to be displayed
$a_show_cols = array('name', 'email', 'organization', 'reply-to');
// create XHTML table
$out = rcube_table_output($attrib, $sql_result, $a_show_cols, 'identity_id');
// set client env
- $javascript = sprintf("%s.gui_object('identitieslist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
- $OUTPUT->add_script($javascript);
+ $OUTPUT->add_gui_object('identitieslist', $attrib['id']);
return $out;
}
// similar function as in /steps/addressbook/edit.inc
function get_form_tags($attrib, $action, $add_hidden=array())
{
- global $OUTPUT, $JS_OBJECT_NAME, $EDIT_FORM, $SESS_HIDDEN_FIELD;
+ global $OUTPUT, $EDIT_FORM, $SESS_HIDDEN_FIELD;
$form_start = '';
if (!strlen($EDIT_FORM))
{
$hiddenfields = new hiddenfield(array('name' => '_task', 'value' => $GLOBALS['_task']));
$hiddenfields->add(array('name' => '_action', 'value' => $action));
if ($add_hidden)
$hiddenfields->add($add_hidden);
if ($_GET['_framed'] || $_POST['_framed'])
$hiddenfields->add(array('name' => '_framed', 'value' => 1));
$form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
$form_start .= "\n$SESS_HIDDEN_FIELD\n";
$form_start .= $hiddenfields->show();
}
$form_end = (!strlen($EDIT_FORM) && !strlen($attrib['form'])) ? '</form>' : '';
$form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
if (!strlen($EDIT_FORM))
- $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('editform', '$form_name');");
+ $OUTPUT->add_gui_object('editform', $form_name);
$EDIT_FORM = $form_name;
return array($form_start, $form_end);
}
+// register UI objects
+$OUTPUT->add_handlers(array(
+ 'userprefs' => 'rcmail_user_prefs_form',
+ 'itentitieslist' => 'rcmail_identities_list'
+));
+
+
?>
\ No newline at end of file
diff --git a/program/steps/settings/identities.inc b/program/steps/settings/identities.inc
index caaa45342..9284e525d 100644
--- a/program/steps/settings/identities.inc
+++ b/program/steps/settings/identities.inc
@@ -1,49 +1,49 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/settings/identities.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Manage identities of a user account |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
if ($USER_DATA = $DB->fetch_assoc($sql_result))
- $PAGE_TITLE = sprintf('%s (%s@%s)', rcube_label('identities'), $USER_DATA['username'], $USER_DATA['mail_host']);
+ $OUTPUT->set_pagetitle(sprintf('%s (%s@%s)', rcube_label('identities'), $USER_DATA['username'], $USER_DATA['mail_host']));
$OUTPUT->include_script('list.js');
// similar function as /steps/addressbook/func.inc::rcmail_contact_frame()
function rcmail_identity_frame($attrib)
{
- global $OUTPUT, $JS_OBJECT_NAME;
+ global $OUTPUT;
if (!$attrib['id'])
$attrib['id'] = 'rcmIdentityFrame';
$attrib['name'] = $attrib['id'];
- $OUTPUT->add_script(sprintf("%s.set_env('contentframe', '%s');", $JS_OBJECT_NAME, $attrib['name']));
+ $OUTPUT->set_env('contentframe', $attrib['name']);
$attrib_str = create_attrib_string($attrib, array('name', 'id', 'class', 'style', 'src', 'width', 'height', 'frameborder'));
$out = '<iframe'. $attrib_str . '></iframe>';
return $out;
}
-
+$OUTPUT->add_handler('identityframe', 'rcmail_identity_frame');
parse_template('identities');
?>
\ No newline at end of file
diff --git a/program/steps/settings/manage_folders.inc b/program/steps/settings/manage_folders.inc
index 8dd898d26..7499fe3d4 100644
--- a/program/steps/settings/manage_folders.inc
+++ b/program/steps/settings/manage_folders.inc
@@ -1,288 +1,282 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/settings/manage_folders.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Provide functionality to create/delete/rename folders |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
// init IMAP connection
rcmail_imap_init(TRUE);
// subscribe to one or more mailboxes
if ($_action=='subscribe')
{
if ($mboxes = get_input_value('_mboxes', RCUBE_INPUT_GET))
$IMAP->subscribe(array($mboxes));
- if ($REMOTE_REQUEST)
- rcube_remote_response('// subscribed');
+ if ($OUTPUT->ajax_call)
+ $OUTPUT->remote_response('// subscribed');
}
// unsubscribe one or more mailboxes
else if ($_action=='unsubscribe')
{
if ($mboxes = get_input_value('_mboxes', RCUBE_INPUT_GET))
$IMAP->unsubscribe(array($mboxes));
- if ($REMOTE_REQUEST)
- rcube_remote_response('// unsubscribed');
+ if ($OUTPUT->ajax_call)
+ $OUTPUT->remote_response('// unsubscribed');
}
// create a new mailbox
else if ($_action=='create-folder')
{
if (!empty($_GET['_name']))
$create = $IMAP->create_mailbox(trim(get_input_value('_name', RCUBE_INPUT_GET, FALSE, 'UTF-7')), TRUE);
- if ($create && $REMOTE_REQUEST)
+ if ($create && $OUTPUT->ajax_call)
{
- $commands = sprintf("this.add_folder_row('%s','%s')",
- JQ($create),
- JQ(rcube_charset_convert($create, 'UTF-7')));
- rcube_remote_response($commands);
+ $OUTPUT->command('add_folder_row', $create, rcube_charset_convert($create, 'UTF-7'));
+ $OUTPUT->send();
}
- else if (!$create && $REMOTE_REQUEST)
+ else if (!$create && $OUTPUT->ajax_call)
{
- $commands = show_message('errorsaving', 'error');
- rcube_remote_response($commands);
+ $OUTPUT->show_message('errorsaving', 'error');
+ $OUTPUT->remote_response();
}
else if (!$create)
- show_message('errorsaving', 'error');
+ $OUTPUT->show_message('errorsaving', 'error');
}
// rename a mailbox
else if ($_action=='rename-folder')
{
if (!empty($_GET['_folder_oldname']) && !empty($_GET['_folder_newname']))
- $rename = $IMAP->rename_mailbox(get_input_value('_folder_oldname', RCUBE_INPUT_GET), trim(get_input_value('_folder_newname', RCUBE_INPUT_GET, FALSE, 'UTF-7')));
+ $rename = $IMAP->rename_mailbox(($oldname = get_input_value('_folder_oldname', RCUBE_INPUT_GET)), trim(get_input_value('_folder_newname', RCUBE_INPUT_GET, FALSE, 'UTF-7')));
- if ($rename && $REMOTE_REQUEST)
+ if ($rename && $OUTPUT->ajax_call)
{
- $commands = sprintf("this.replace_folder_row('%s','%s','%s');\n",
- JQ(get_input_value('_folder_oldname', RCUBE_INPUT_GET)),
- JQ($rename),
- JQ(rcube_charset_convert($rename, 'UTF-7')));
-
- $commands .= "this.reset_folder_rename();\n";
-
- rcube_remote_response($commands);
+ $OUTPUT->command('replace_folder_row', $oldname, $rename, rcube_charset_convert($rename, 'UTF-7'));
+ $OUTPUT->command('reset_folder_rename');
+ $OUTPUT->send();
}
- else if (!$rename && $REMOTE_REQUEST)
+ else if (!$rename && $OUTPUT->ajax_call)
{
- $commands = "this.reset_folder_rename();\n";
- $commands .= show_message('errorsaving', 'error');
- rcube_remote_response($commands);
+ $OUTPUT->command('reset_folder_rename');
+ $OUTPUT->show_message('errorsaving', 'error');
+ $OUTPUT->send();
}
else if (!$rename)
- show_message('errorsaving', 'error');
+ $OUTPUT->show_message('errorsaving', 'error');
}
// delete an existing IMAP mailbox
else if ($_action=='delete-folder')
{
if ($mboxes = get_input_value('_mboxes', RCUBE_INPUT_GET))
$deleted = $IMAP->delete_mailbox(array($mboxes));
- if ($REMOTE_REQUEST && $deleted)
+ if ($OUTPUT->ajax_call && $deleted)
{
- $commands = sprintf("this.remove_folder_row('%s');\n", JQ(get_input_value('_mboxes', RCUBE_INPUT_GET)));
- $commands .= show_message('folderdeleted', 'confirmation');
- rcube_remote_response($commands);
+ $OUTPUT->command('remove_folder_row', get_input_value('_mboxes', RCUBE_INPUT_GET));
+ $OUTPUT->show_message('folderdeleted', 'confirmation');
+ $OUTPUT->send();
}
- else if ($REMOTE_REQUEST)
+ else if ($OUTPUT->ajax_call)
{
- $commands = show_message('errorsaving', 'error');
- rcube_remote_response($commands);
+ $OUTPUT->show_message('errorsaving', 'error');
+ $OUTPUT->send();
}
}
// build table with all folders listed by server
function rcube_subscription_form($attrib)
{
- global $IMAP, $CONFIG, $OUTPUT, $JS_OBJECT_NAME;
+ global $IMAP, $CONFIG, $OUTPUT;
list($form_start, $form_end) = get_form_tags($attrib, 'folders');
unset($attrib['form']);
if (!$attrib['id'])
$attrib['id'] = 'rcmSubscriptionlist';
// 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'));
$out = "$form_start\n<table" . $attrib_str . ">\n";
// add table header
$out .= "<thead><tr>\n";
$out .= sprintf('<td class="name">%s</td><td class="subscribed">%s</td>'.
'<td class="rename">&nbsp;</td><td class="delete">&nbsp;</td>',
rcube_label('foldername'), rcube_label('subscribed'));
$out .= "\n</tr></thead>\n<tbody>\n";
// get folders from server
$IMAP->clear_cache('mailboxes');
$a_unsubscribed = $IMAP->list_unsubscribed();
$a_subscribed = $IMAP->list_mailboxes();
$a_js_folders = array();
- $checkbox_subscribe = new checkbox(array('name' => '_subscribed[]', 'onclick' => "$JS_OBJECT_NAME.command(this.checked?'subscribe':'unsubscribe',this.value)"));
+ $checkbox_subscribe = new checkbox(array('name' => '_subscribed[]', 'onclick' => JS_OBJECT_NAME.".command(this.checked?'subscribe':'unsubscribe',this.value)"));
if (!empty($attrib['deleteicon']))
$del_button = sprintf('<img src="%s%s" alt="%s" border="0" />', $CONFIG['skin_path'], $attrib['deleteicon'], rcube_label('delete'));
else
$del_button = rcube_label('delete');
if (!empty($attrib['renameicon']))
$edit_button = sprintf('<img src="%s%s" alt="%s" border="0" />', $CONFIG['skin_path'], $attrib['renameicon'], rcube_label('rename'));
else
$del_button = rcube_label('rename');
// create list of available folders
foreach ($a_unsubscribed as $i => $folder)
{
$subscribed = in_array($folder, $a_subscribed);
$protected = ($CONFIG['protect_default_folders'] == TRUE && in_array($folder,$CONFIG['default_imap_folders']));
$zebra_class = $i%2 ? 'even' : 'odd';
$folder_js = JQ($folder);
- $folder_js_enc = JQ(rcube_charset_convert($folder, 'UTF-7'));
$folder_html = $CONFIG['protect_default_folders'] && in_array($folder, $CONFIG['default_imap_folders']) ? rcube_label(strtolower($folder)) : rcube_charset_convert($folder, 'UTF-7');
if (!$protected)
- $a_js_folders['rcmrow'.($i+1)] = array($folder_js, $folder_js_enc);
+ $a_js_folders['rcmrow'.($i+1)] = array($folder, rcube_charset_convert($folder, 'UTF-7'));
$out .= sprintf('<tr id="rcmrow%d" class="%s"><td>%s</td>',
$i+1,
$zebra_class,
Q($folder_html));
if ($protected)
$out .= '<td>&nbsp;'.($subscribed ? '&#x2022;' : '-').'</td>';
else
$out .= '<td>'.$checkbox_subscribe->show($subscribed?$folder:'', array('value' => $folder)).'</td>';
// add rename and delete buttons
if (!$protected)
$out .= sprintf('<td><a href="#rename" onclick="%s.command(\'rename-folder\',\'%s\')" title="%s">%s</a>'.
'<td><a href="#delete" onclick="%s.command(\'delete-folder\',\'%s\')" title="%s">%s</a></td>',
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
$folder_js,
rcube_label('renamefolder'),
$edit_button,
- $JS_OBJECT_NAME,
+ JS_OBJECT_NAME,
$folder_js,
rcube_label('deletefolder'),
$del_button);
else
$out .= '<td></td><td></td>';
$out .= "</tr>\n";
}
$out .= "</tbody>\n</table>";
$out .= "\n$form_end";
-
- $javascript = sprintf("%s.gui_object('subscriptionlist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
- $javascript .= sprintf("%s.set_env('subscriptionrows', %s);", $JS_OBJECT_NAME, array2js($a_js_folders));
- $OUTPUT->add_script($javascript);
+ $OUTPUT->add_gui_object('subscriptionlist', $attrib['id']);
+ $OUTPUT->set_env('subscriptionrows', $a_js_folders);
return $out;
}
function rcube_create_folder_form($attrib)
{
- global $JS_OBJECT_NAME;
-
list($form_start, $form_end) = get_form_tags($attrib, 'create-folder');
unset($attrib['form']);
// return the complete edit form as table
$out = "$form_start\n";
$input = new textfield(array('name' => '_folder_name'));
$out .= $input->show();
if (get_boolean($attrib['button']))
{
$button = new input_field(array('type' => 'button',
'value' => rcube_label('create'),
- 'onclick' => "$JS_OBJECT_NAME.command('create-folder',this.form)"));
+ 'onclick' => JS_OBJECT_NAME.".command('create-folder',this.form)"));
$out .= $button->show();
}
$out .= "\n$form_end";
return $out;
}
function rcube_rename_folder_form($attrib)
{
- global $CONFIG, $IMAP, $JS_OBJECT_NAME;
+ global $CONFIG, $IMAP;
list($form_start, $form_end) = get_form_tags($attrib, 'rename-folder');
unset($attrib['form']);
// return the complete edit form as table
$out = "$form_start\n";
$a_unsubscribed = $IMAP->list_unsubscribed();
$select_folder = new select(array('name' => '_folder_oldname', 'id' => 'rcmfd_oldfolder'));
foreach ($a_unsubscribed as $i => $folder)
{
if ($CONFIG['protect_default_folders'] == TRUE && in_array($folder,$CONFIG['default_imap_folders']))
continue;
$select_folder->add($folder);
}
$out .= $select_folder->show();
$out .= " to ";
$inputtwo = new textfield(array('name' => '_folder_newname'));
$out .= $inputtwo->show();
if (get_boolean($attrib['button']))
{
$button = new input_field(array('type' => 'button',
'value' => rcube_label('rename'),
- 'onclick' => "$JS_OBJECT_NAME.command('rename-folder',this.form)"));
+ 'onclick' => JS_OBJECT_NAME.".command('rename-folder',this.form)"));
$out .= $button->show();
}
$out .= "\n$form_end";
return $out;
}
+// register UI objects
+$OUTPUT->add_handlers(array(
+ 'foldersubscription' => 'rcube_subscription_form',
+ 'createfolder' => 'rcube_create_folder_form',
+ 'renamefolder' => 'rcube_rename_folder_form'
+));
+
// add some labels to client
rcube_add_label('deletefolderconfirm');
-
-parse_template('managefolders');
+$OUTPUT->send('managefolders');
?>
diff --git a/program/steps/settings/save_identity.inc b/program/steps/settings/save_identity.inc
index ce1c6f6b4..8079b589a 100644
--- a/program/steps/settings/save_identity.inc
+++ b/program/steps/settings/save_identity.inc
@@ -1,157 +1,157 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/settings/save_identity.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Save an identity record or to add a new one |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
$a_save_cols = array('name', 'email', 'organization', 'reply-to', 'bcc', 'standard', 'signature', 'html_signature');
$a_html_cols = array('signature');
$a_boolean_cols = array('standard', 'html_signature');
$updated = $default_id = false;
// check input
if (empty($_POST['_name']) || empty($_POST['_email']))
{
- show_message('formincomplete', 'warning');
+ $OUTPUT->show_message('formincomplete', 'warning');
rcmail_overwrite_action('edit-identitiy');
return;
}
// update an existing contact
if ($_POST['_iid'])
{
$a_write_sql = array();
foreach ($a_save_cols as $col)
{
$fname = '_'.$col;
if (isset($_POST[$fname]))
$a_write_sql[] = sprintf("%s=%s",
$DB->quoteIdentifier($col),
$DB->quote(get_input_value($fname, RCUBE_INPUT_POST, in_array($col, $a_html_cols))));
}
// set "off" values for checkboxes that were not checked, and therefore
// not included in the POST body.
foreach ($a_boolean_cols as $col)
{
$fname = '_' . $col;
if (!isset($_POST[$fname]))
$a_write_sql[] = sprintf("%s=0", $DB->quoteIdentifier($col));
}
if (sizeof($a_write_sql))
{
$DB->query(
"UPDATE ".get_table_name('identities')."
SET ".join(', ', $a_write_sql)."
WHERE identity_id=?
AND user_id=?
AND del<>1",
get_input_value('_iid', RCUBE_INPUT_POST),
$_SESSION['user_id']);
$updated = $DB->affected_rows();
}
if ($updated)
{
- show_message('successfullysaved', 'confirmation');
+ $OUTPUT->show_message('successfullysaved', 'confirmation');
if (!empty($_POST['_standard']))
$default_id = get_input_value('_iid', RCUBE_INPUT_POST);
if ($_POST['_framed'])
{
// update the changed col in list
// ...
}
}
else if ($DB->is_error())
{
// show error message
- show_message('errorsaving', 'error');
+ $OUTPUT->show_message('errorsaving', 'error');
rcmail_overwrite_action('edit-identitiy');
return;
}
}
// insert a new contact
else
{
$a_insert_cols = $a_insert_values = array();
foreach ($a_save_cols as $col)
{
$fname = '_'.$col;
if (!isset($_POST[$fname]))
continue;
$a_insert_cols[] = $DB->quoteIdentifier($col);
$a_insert_values[] = $DB->quote(get_input_value($fname, RCUBE_INPUT_POST, in_array($col, $a_html_cols)));
}
if (sizeof($a_insert_cols))
{
$DB->query("INSERT INTO ".get_table_name('identities')."
(user_id, ".join(', ', $a_insert_cols).")
VALUES (?, ".join(', ', $a_insert_values).")",
$_SESSION['user_id']);
$insert_id = $DB->insert_id(get_sequence_name('identities'));
}
if ($insert_id)
{
$_GET['_iid'] = $insert_id;
if (!empty($_POST['_standard']))
$default_id = $insert_id;
if ($_POST['_framed'])
{
// add contact row or jump to the page where it should appear
// ....
}
}
else
{
// show error message
- show_message('errorsaving', 'error');
+ $OUTPUT->show_message('errorsaving', 'error');
rcmail_overwrite_action('edit-identity');
return;
}
}
// mark all other identities as 'not-default'
if ($default_id)
$DB->query(
"UPDATE ".get_table_name('identities')."
SET ".$DB->quoteIdentifier('standard')."='0'
WHERE user_id=?
AND identity_id<>?
AND del<>1",
$_SESSION['user_id'],
$default_id);
// go to next step
-rcmail_overwrite_action($_POST['_framed'] ? 'edit-identity' : 'identities');
+rcmail_overwrite_action($_framed ? 'edit-identity' : 'identities');
?>
\ No newline at end of file
diff --git a/program/steps/settings/save_prefs.inc b/program/steps/settings/save_prefs.inc
index fd254f9f3..4945a4fff 100644
--- a/program/steps/settings/save_prefs.inc
+++ b/program/steps/settings/save_prefs.inc
@@ -1,55 +1,52 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/settings/save_prefs.inc |
| |
| This file is part of the RoundCube Webmail client |
- | Copyright (C) 2005, RoundCube Dev. - Switzerland |
+ | Copyright (C) 2005-2007, RoundCube Dev. - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Save user preferences to DB and to the current session |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
$a_user_prefs = array(
'timezone' => isset($_POST['_timezone']) ? floatval($_POST['_timezone']) : $CONFIG['timezone'],
'dst_active' => isset($_POST['_dst_active']) ? TRUE : FALSE,
'pagesize' => is_numeric($_POST['_pagesize']) ? intval($_POST['_pagesize']) : $CONFIG['pagesize'],
'prettydate' => isset($_POST['_pretty_date']) ? TRUE : FALSE,
'prefer_html' => isset($_POST['_prefer_html']) ? TRUE : FALSE,
'htmleditor' => isset($_POST['_htmleditor']) ? TRUE : FALSE,
'preview_pane' => isset($_POST['_preview_pane']) ? TRUE : FALSE,
'draft_autosave' => isset($_POST['_draft_autosave']) ? intval($_POST['_draft_autosave']) : 0
);
// don't override these parameters
foreach ((array)$CONFIG['dont_override'] as $p)
$a_user_prefs[$p] = $CONFIG[$p];
// switch UI language
if (isset($_POST['_language']))
{
$sess_user_lang = $_SESSION['user_lang'] = get_input_value('_language', RCUBE_INPUT_POST);
rcmail_set_locale($sess_user_lang);
}
if (rcmail_save_user_prefs($a_user_prefs))
- show_message('successfullysaved', 'confirmation');
+ $OUTPUT->show_message('successfullysaved', 'confirmation');
// go to next step
-$_action = 'preferences';
-
-// overwrite action variable
-$OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $_action));
+rcmail_overwrite_action('preferences');
?>
diff --git a/skins/default/addresses.css b/skins/default/addresses.css
index 0ff1b28a9..363a63477 100644
--- a/skins/default/addresses.css
+++ b/skins/default/addresses.css
@@ -1,116 +1,183 @@
/***** RoundCube|Mail address book task styles *****/
#abooktoolbar
{
position: absolute;
top: 45px;
left: 200px;
height: 35px;
}
#abooktoolbar a
{
padding-right: 10px;
}
#abookcountbar
{
position: absolute;
- top: 60px;
- left: 490px;
+ bottom: 16px;
+ left: 185px;
width: 240px;
height: 20px;
text-align: left;
}
#abookcountbar span
{
font-size: 11px;
color: #333333;
}
-
-#addresslist
+#directorylist, #addresslist
{
position: absolute;
top: 85px;
- left: 20px;
- width: 450px;
bottom: 40px;
border: 1px solid #999999;
background-color: #F9F9F9;
overflow: auto;
/* css hack for IE */
- height: expression((parseInt(document.documentElement.clientHeight)-135)+'px');
+ height: expression((parseInt(document.documentElement.clientHeight)-135)+'px');
+}
+
+#directorylist
+{
+ left: 20px;
+ width: 150px;
+}
+
+#addresslist
+{
+ left: 185px;
+ width: 340px;
+}
+
+#directorylist ul
+{
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+#directorylist ul
+{
+ font-size: 11px;
+ border-bottom: 1px solid #EBEBEB;
+}
+
+#directorylist ul li a
+{
+ display: block;
+ padding-left: 6px;
+ padding-top: 2px;
+ padding-bottom: 2px;
+ text-decoration: none;
+}
+
+#directorylist li.selected
+{
+ background-color: #929292;
+ border-bottom: 1px solid #898989;
+}
+
+#directorylist li.selected a
+{
+ color: #FFF;
+ font-weight: bold;
+}
+
+#directorylist li.droptarget
+{
+ background-color: #FFFFA6;
}
+
#contacts-table
{
width: 100%;
table-layout: fixed;
/* css hack for IE */
width: expression(document.getElementById('addresslist').clientWidth);
}
#contacts-table tbody td
{
cursor: pointer;
}
#contacts-box
{
position: absolute;
top: 85px;
- left: 490px;
- right: 40px;
+ left: 540px;
+ right: 30px;
bottom: 40px;
border: 1px solid #999999;
overflow: hidden;
/* css hack for IE */
- width: expression((parseInt(document.documentElement.clientWidth)-80-document.getElementById('addresslist').offsetWidth)+'px');
+ width: expression((parseInt(document.documentElement.clientWidth)-70-document.getElementById('addresslist').offsetWidth)+'px');
height: expression((parseInt(document.documentElement.clientHeight)-135)+'px');
}
#addressviewsplitter
{
- background-position: 6px center;
+ background-position: 4px center;
}
#addressviewsplitter .splitterLine
{
margin-left: 3px;
- width: 9px;
+ width: 6px;
}
body.iframe,
#contact-frame
{
background-color: #F9F9F9;
}
#contact-frame
{
border: none;
/* visibility: hidden; */
}
+#contact-title, #groups-title
+{
+ height: 12px !important;
+/* height: 20px; */
+ padding: 4px 5px 3px 5px;
+ border-bottom: 1px solid #999;
+ color: #333;
+ font-size: 11px;
+ font-weight: bold;
+ background-color: #EBEBEB;
+ background-image: url(images/listheader_aqua.gif);
+ white-space: nowrap;
+}
+
+#contact-title
+{
+ padding: 4px 10px 3px 10px;
+}
#contact-details
{
- padding: 15px 20px 10px 20px;
+ padding: 15px 10px 10px 10px;
}
#contact-details table td.title
{
- color: #666666;
+ color: #666;
font-weight: bold;
text-align: right;
padding-right: 10px;
}
diff --git a/skins/default/common.css b/skins/default/common.css
index b3c234f89..2ce3dffad 100755
--- a/skins/default/common.css
+++ b/skins/default/common.css
@@ -1,348 +1,426 @@
/***** RoundCube|Mail basic styles *****/
body
{
margin: 8px;
background-color: #F6F6F6; /* #EBEBEB; */
color: #000000;
}
body.iframe
{
margin: 0px;
}
body.extwin
{
margin: 10px;
}
body, td, th, span, div, p, h3
{
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
color: #000000;
}
th
{
font-weight: normal;
}
h3
{
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
font-size: 18px;
color: #000000;
}
a, a:active, a:visited
{
color: #000000;
outline: none;
}
a.button, a.button:visited, a.tab, a.tab:visited, a.axislist
{
color: #000000;
text-decoration: none;
}
a.tab
{
width: 80px;
display: block;
text-align: center;
}
hr
{
height: 1px;
background-color: #666666;
border-style: none;
}
input, textarea
{
font-size: 9pt;
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
padding: 1px;
padding-left: 3px;
padding-right: 3px;
background-color: #ffffff;
border: 1px solid #666666;
}
input[type="checkbox"],
input[type="radio"]
{
border: 0;
padding: 0;
}
input.button
{
height: 20px;
color: #333333;
font-size: 12px;
padding-left: 8px;
padding-right: 8px;
background: url(images/buttons/bg.gif) repeat-x #f0f0f0;
border: 1px solid #a4a4a4;
}
input.button:hover
{
color: black;
}
img
{
behavior: url('skins/default/pngbehavior.htc');
}
.alttext
{
font-size: 11px;
}
/** common user interface objects */
#header
{
position: absolute;
top: 10px;
left: 20px;
width: 170px;
height: 40px;
z-index: 100;
}
#taskbar
{
position: absolute;
top: 0px;
right: 0px;
width: 600px;
height: 37px;
background: url(images/taskbar.gif) top right no-repeat;
- padding: 10px 24px 10px 0px;
+ padding: 10px 14px 10px 0px;
text-align: right;
white-space: nowrap;
z-index: 2;
}
#taskbar a,
#taskbar a:active,
#taskbar a:visited
{
font-size: 11px;
color: #666666;
text-decoration: none;
padding: 6px 16px 6px 30px;
background-repeat: no-repeat;
}
#taskbar a:hover
{
color: #333333;
}
a.button-mail
{
background-image: url(images/buttons/mail.gif);
}
a.button-addressbook
{
background-image: url(images/buttons/addressbook.gif);
}
a.button-settings
{
background-image: url(images/buttons/settings.gif);
}
a.button-logout
{
background-image: url(images/buttons/logout.gif);
}
#message
{
position: absolute;
display: none;
top: -1px;
left: 200px;
right: 200px;
z-index: 5000;
opacity: 0.85;
}
#message div
{
width: 400px;
margin: 0px auto;
height: 24px;
min-height: 24px;
padding: 8px 10px 8px 46px;
}
#message div.notice,
#remote-objects-message
{
background: url(images/display/info.png) 6px 3px no-repeat;
background-color: #F7FDCB;
border: 1px solid #C2D071;
}
#message div.error,
#message div.warning
{
background: url(images/display/warning.png) 6px 3px no-repeat;
background-color: #EF9398;
border: 1px solid #DC5757;
}
#message div.confirmation
{
background: url(images/display/confirm.png) 6px 3px no-repeat;
background-color: #A6EF7B;
border: 1px solid #76C83F;
}
#message div.loading
{
background: url(images/display/loading.gif) 6px 3px no-repeat;
background-color: #EBEBEB;
border: 1px solid #CCCCCC;
}
.splitter
{
position: absolute;
padding: 2px;
background: url(images/dimple.png) center no-repeat;
}
.splitter-h
{
cursor: n-resize;
background-position: center 2px;
}
.splitter-v
{
cursor: e-resize;
background-position: 1px center;
}
.boxtitle
{
height: 12px !important;
padding: 4px 20px 3px 20px;
border-bottom: 1px solid #999;
color: #333;
font-size: 11px;
font-weight: bold;
background-color: #EBEBEB;
background-image: url(images/listheader_aqua.gif);
}
+.radios-left label
+{
+ padding-left: 0.3em;
+}
/***** common table settings ******/
table.records-table thead tr td
{
height: 20px;
padding: 0px 4px 0px 4px;
vertical-align: middle;
border-bottom: 1px solid #999999;
color: #333333;
background-color: #EBEBEB;
background-image: url(images/listheader_aqua.gif);
font-size: 11px;
font-weight: bold;
}
table.records-table tbody tr td
{
height: 16px;
padding: 2px 4px 2px 4px;
font-size: 11px;
white-space: nowrap;
border-bottom: 1px solid #EBEBEB;
overflow: hidden;
text-align: left;
}
table.records-table tr
{
background-color: #FFFFFF;
}
table.records-table tr.selected td
{
font-weight: bold;
color: #FFFFFF;
background-color: #CC3333;
}
table.records-table tr.focused td
{
- border-bottom: thin dotted;
- border-top: thin dotted;
}
table.records-table tr.unfocused td
{
font-weight: bold;
color: #FFFFFF;
background-color: #929292;
}
+/***** mac-style quicksearch field *****/
+
+#quicksearchbar
+{
+ position: absolute;
+ top: 60px;
+ right: 30px;
+ width: 182px;
+ height: 20px;
+ text-align: right;
+ background: url('images/searchfield.gif') top left no-repeat;
+}
+
+#quicksearchbar a
+{
+ position: absolute;
+ top: 3px;
+ right: 4px;
+ text-decoration: none;
+}
+
+#quicksearchbar img
+{
+ vertical-align: middle;
+}
+
+#quicksearchbox
+{
+ position: absolute;
+ top: 2px;
+ left: 20px;
+ width: 140px;
+ font-size: 11px;
+ padding: 0px;
+ border: none;
+}
+
+
+/*\*/
+html>body*#quicksearchbar[id$="quicksearchbar"]:not([class="none"]) { background-image: none; }
+html>body*#quicksearchbar[id$="quicksearchbar"]:not([class="none"]) a { top: 5px; }
+html>body*#quicksearchbar[id$="quicksearchbar"]:not([class="none"]) #quicksearchbox { width: 180px; top:0px; right: 1px; left: auto; }
+/**/
+
+
/***** roundcube webmail pre-defined classes *****/
+#rcversion
+{
+ position: absolute;
+ top: 67px;
+ left: 20px;
+ width: 160px;
+ text-align: center;
+
+ font-weight: normal;
+ font-size: x-small;
+ font-variant: small-caps;
+
+ color: #999999;
+ /*border: 1px solid #308014;
+ background-color: #b4eeb4;*/
+}
+
+#rcmdraglayer
+{
+ width: 300px;
+ border: 1px solid #999999;
+ background-color: #F9F9F9;
+ padding-left: 8px;
+ padding-right: 8px;
+ padding-top: 3px;
+ padding-bottom: 3px;
+ font-size: 11px;
+ opacity: 0.6;
+ -moz-opacity: 0.6;
+}
+
a.rcmContactAddress
{
text-decoration: none;
}
a.rcmContactAddress:hover
{
text-decoration: underline;
}
#rcmKSearchpane
{
background-color: #F9F9F9;
border: 1px solid #CCCCCC;
}
#rcmKSearchpane ul
{
margin: 0px;
padding: 2px;
list-style-image: none;
list-style-type: none;
}
#rcmKSearchpane ul li
{
height: 16px;
font-size: 11px;
padding-left: 8px;
padding-top: 2px;
padding-right: 8px;
white-space: nowrap;
}
#rcmKSearchpane ul li.selected
{
color: #ffffff;
background-color: #CC3333;
}
diff --git a/skins/default/ldapsearchform.css b/skins/default/ldapsearchform.css
deleted file mode 100644
index 9661442eb..000000000
--- a/skins/default/ldapsearchform.css
+++ /dev/null
@@ -1,54 +0,0 @@
-/***** RoundCube|Mail address book task styles *****/
-
-
-body.iframe,
-{
- background-color: #F9F9F9;
-}
-
-#ldapsearch-title
-{
- height: 12px !important;
-/* height: 20px; */
- padding: 4px 20px 3px 20px;
- border-bottom: 1px solid #999999;
- color: #333333;
- font-size: 11px;
- font-weight: bold;
- background-color: #EBEBEB;
- background-image: url(images/listheader_aqua.gif);
-}
-
-#ldapsearch-details
-{
- padding: 15px 20px 10px 20px;
-}
-
-#ldapsearch-details table td.title
-{
- color: #666666;
- font-weight: bold;
- text-align: right;
- padding-right: 10px;
-}
-
-#ldapAddressList
-{
- width: 100%;
- table-layout: fixed;
- /* css hack for IE */
- width: expression(document.getElementById('addresslist').clientWidth);
-}
-
-#ldapAddressList table
-{
- border-top: 1px solid #999999;
-}
-
-#ldap-search-results div
-{
- width: 100%;
- color: red;
- background-color: green;
-}
-
diff --git a/skins/default/mail.css b/skins/default/mail.css
index 11364baa0..67f2bbb10 100644
--- a/skins/default/mail.css
+++ b/skins/default/mail.css
@@ -1,948 +1,875 @@
/***** RoundCube|Mail mail task styles *****/
#messagetoolbar
{
position: absolute;
top: 45px;
left: 200px;
right: 250px;
height: 35px;
white-space: nowrap;
/* border: 1px solid #cccccc; */
}
#messagetoolbar a
{
padding-right: 10px;
}
#messagetoolbar select
{
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
font-size: 11px;
color: #333333;
}
#messagetoolbar select.mboxlist
{
position: absolute;
left: 375px;
top: 10px;
}
#messagetoolbar select.mboxlist option
{
padding-left: 15px;
}
#messagetoolbar select.mboxlist option[value="0"]
{
padding-left: 2px;
}
#listcontrols
{
position: absolute;
left: 200px;
bottom: 20px;
height: 16px;
width: 500px;
font-size: 11px;
}
#listcontrols a,
#listcontrols a:active,
#listcontrols a:visited,
#mailboxcontrols a,
#mailboxcontrols a:active,
#mailboxcontrols a:visited
{
color: #999999;
font-size: 11px;
text-decoration: none;
}
#listcontrols a.active,
#listcontrols a.active:active,
#listcontrols a.active:visited,
#mailboxcontrols a.active,
#mailboxcontrols a.active:active,
#mailboxcontrols a.active:visited
{
color: #CC0000;
}
#listcontrols a.active:hover,
#mailboxcontrols a.active:hover
{
text-decoration: underline;
}
#messagecountbar
{
position: absolute;
bottom: 16px;
- right: 40px;
+ right: 30px;
width: 300px;
height: 20px;
text-align: right;
white-space: nowrap;
}
#messagecountbar span
{
font-size: 11px;
color: #333333;
}
#messagepartcontainer
{
position: absolute;
top: 80px;
left: 20px;
right: 20px;
bottom: 20px;
}
#mailcontframe
{
position: absolute;
top: 85px;
left: 200px;
- right: 40px;
+ right: 30px;
bottom: 40px;
border: 1px solid #999999;
background-color: #F9F9F9;
overflow: auto;
/* css hack for IE */
- width: expression((parseInt(document.documentElement.clientWidth)-240)+'px');
+ width: expression((parseInt(document.documentElement.clientWidth)-230)+'px');
height: expression((parseInt(document.documentElement.clientHeight)-125)+'px');
}
#mailpreviewframe
{
position: absolute;
top: 305px;
left: 200px;
- right: 40px;
+ right: 30px;
bottom: 40px;
border: 1px solid #999999;
background-color: #F9F9F9;
/* css hack for IE */
- width: expression((parseInt(document.documentElement.clientWidth)-240)+'px');
+ width: expression((parseInt(document.documentElement.clientWidth)-230)+'px');
height: expression((parseInt(document.documentElement.clientHeight)-135-document.getElementById('mailcontframe').offsetHeight)+'px');
}
#messagecontframe
{
width: 100%;
height: 100%;
border: 0;
}
/*\*/
html>body*#messagecontframe
{
[height: 40%;
height: 40%;
]height: 100%;
}
/**/
#messagepartframe
{
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
width: auto;
height: auto;
border: 1px solid #999999;
background-color: #F9F9F9;
}
#partheader
{
position: absolute;
top: 10px;
left: 220px;
height: 40px;
}
#partheader table td
{
padding-left: 2px;
padding-right: 4px;
vertical-align: middle;
font-size: 11px;
}
#partheader table td.title
{
color: #666666;
font-weight: bold;
}
-#rcmdraglayer
-{
- width: 300px;
- border: 1px solid #999999;
- background-color: #F9F9F9;
- padding-left: 8px;
- padding-right: 8px;
- padding-top: 3px;
- padding-bottom: 3px;
- font-size: 11px;
- opacity: 0.6;
- -moz-opacity: 0.6;
-}
-
/** mailbox list styles */
#mailboxlist-header
{
position: absolute;
top: 85px;
left: 20px;
width: 140px !important;
/* width: 162px; */
height: 13px;
padding: 3px 10px 2px 10px;
background-color: #EBEBEB;
background-image: url(images/listheader_aqua.gif);
border: 1px solid #CCCCCC;
color: #333333;
font-size: 11px;
font-weight: bold;
}
#mailboxlist-container
{
position: absolute;
top: 105px;
left: 20px;
width: 160px;
bottom: 40px;
border: 1px solid #CCCCCC;
background-color: #F9F9F9;
overflow: auto;
/* css hack for IE */
height: expression((parseInt(document.documentElement.clientHeight)-145)+'px');
}
#mailboxlist
{
width: 100%;
height: auto;
margin: 0px;
padding: 0px;
list-style-image: none;
list-style-type: none;
overflow: hidden;
white-space: nowrap;
}
#mailboxlist li
{
/* height: 18px; */
font-size: 11px;
background: url(images/icons/folder-closed.png) no-repeat;
background-position: 10px 1px;
border-bottom: 1px solid #EBEBEB;
/* IE 5.5 margin-left: -16px; */
}
#mailboxlist li.inbox
{
background-image: url(images/icons/folder-inbox.png);
}
#mailboxlist li.drafts
{
background-image: url(images/icons/folder-drafts.png);
}
#mailboxlist li.sent
{
background-image: url(images/icons/folder-sent.png);
}
#mailboxlist li.junk
{
background-image: url(images/icons/folder-junk.png);
}
#mailboxlist li.trash
{
background-image: url(images/icons/folder-trash.png);
}
#mailboxlist li a
{
display: block;
padding-left: 32px;
padding-top: 2px;
padding-bottom: 2px;
text-decoration: none;
}
#mailboxlist li, #mailboxlist li.unread
{
/* background-image: url(images/mailbox_list.gif); */
}
#mailboxlist li.unread
{
font-weight: bold;
}
#mailboxlist li.selected
{
background-color: #929292;
border-bottom: 1px solid #898989;
}
#mailboxlist li.selected a
{
color: #FFF;
font-weight: bold;
}
#mailboxlist li.droptarget
{
background-color: #FFFFA6;
}
/* styles for nested folders */
#mailboxlist ul {
list-style: none;
padding: 0;
margin:0;
border-top: 1px solid #EBEBEB;
}
#mailboxlist ul li {
padding-left: 15px;
background-position: 25px 1px;
}
#mailboxlist li.selected li {
background-color: #F9F9F9;
}
#mailboxlist li.unread li {
font-weight: normal;
}
#mailboxlist li.unread li.unread {
font-weight: bold;
}
#mailboxlist li.selected li a{
color: black;
font-weight: normal;
}
#mailboxcontrols
{
position: absolute;
left: 20px;
width: 160px;
bottom: 20px;
height: 16px;
overflow: hidden;
font-size: 11px;
}
/** message list styles */
body.messagelist
{
margin: 0px;
background-color: #F9F9F9;
}
#messagelist
{
width: 100%;
display: table;
table-layout: fixed;
/* css hack for IE */
width: expression(document.getElementById('mailcontframe').clientWidth);
}
#messagelist thead tr td
{
height: 20px;
padding-top: 0px;
padding-bottom: 0px;
padding-left: 2px;
padding-right: 4px;
vertical-align: middle;
border-bottom: 1px solid #999999;
color: #333333;
background-color: #EBEBEB;
background-image: url(images/listheader_aqua.gif);
font-size: 11px;
font-weight: bold;
}
#messagelist thead tr td.sortedASC,
#messagelist thead tr td.sortedDESC
{
background-image: url(images/listheader_dark.gif);
}
#messagelist thead tr td.sortedASC a
{
background: url(images/sort_asc.gif) top right no-repeat;
}
#messagelist thead tr td.sortedDESC a
{
background: url(images/sort_desc.gif) top right no-repeat;
}
#messagelist thead tr td a,
#messagelist thead tr td a:hover
{
display: block;
width: auto !important;
width: 100%;
color: #333333;
text-decoration: none;
}
#messagelist tbody tr td
{
height: 16px;
padding: 2px;
padding-right: 4px;
font-size: 11px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
border-bottom: 1px solid #EBEBEB;
cursor: pointer;
}
#messagelist col
{
display: table-column;
text-align: left;
vertical-align: middle;
}
#messagelist tr td.icon
{
width: 16px;
vertical-align: middle;
}
#messagelist tr td.subject
{
overflow: hidden;
vertical-align: middle;
}
#messagelist tr td.size
{
width: 60px;
text-align: right;
vertical-align: middle;
}
#messagelist tr td.from,
#messagelist tr td.to
{
width: 180px;
vertical-align: middle;
}
#messagelist tr td.date
{
width: 118px;
vertical-align: middle;
}
#messagelist tr.message
{
background-color: #FFFFFF;
}
/*
#messagelist tr.odd
{
background-color: #F9F9F9;
}
*/
#messagelist tr.unread
{
font-weight: bold;
background-color: #FFFFFF;
}
#messagelist tr.selected td
{
font-weight: bold;
color: #FFFFFF;
background-color: #CC3333;
}
#messagelist tr.unfocused td
{
font-weight: bold;
color: #FFFFFF;
background-color: #929292;
}
#messagelist tr.selected td a.rcmContactAddress
{
color: #FFFFFF;
}
#messagelist tr.unfocused td a.rcmContactAddress
{
color: #FFFFFF;
}
#messagelist tr.deleted td a.rcmContactAddress
{
color: #CCCCCC;
}
#messagelist tr.deleted td,
#messagelist tr.deleted td a
{
color: #CCCCCC;
}
-#quicksearchbar
-{
- position: absolute;
- top: 60px;
- right: 40px;
- width: 182px;
- height: 20px;
- text-align: right;
- background: url('images/searchfield.gif') top left no-repeat;
-}
-
-#quicksearchbar a
-{
- position: absolute;
- top: 3px;
- right: 4px;
- text-decoration: none;
-}
-
-#quicksearchbar img
-{
- vertical-align: middle;
-}
-
-#quicksearchbox
-{
- position: absolute;
- top: 2px;
- left: 20px;
- width: 140px;
- font-size: 11px;
- padding: 0px;
- border: none;
-}
-
-
-/*\*/
-html>body*#quicksearchbar[id$="quicksearchbar"]:not([class="none"]) { background-image: none; }
-html>body*#quicksearchbar[id$="quicksearchbar"]:not([class="none"]) a { top: 5px; }
-html>body*#quicksearchbar[id$="quicksearchbar"]:not([class="none"]) #quicksearchbox { width: 180px; top:0px; right: 1px; left: auto; }
-/**/
-
-
-#rcversion
-{
- position: absolute;
- top: 67px;
- left: 20px;
- width: 160px;
- text-align: center;
-
- font-weight: normal;
- font-size: x-small;
- font-variant: small-caps;
-
- color: #999999;
- /*border: 1px solid #308014;
- background-color: #b4eeb4;*/
-}
#quotadisplay
{
color: #666666;
font-size: 11px;
}
#quotadisplay img
{
vertical-align: middle;
margin-left: 4px;
border: 1px solid #666666;
}
/** message view styles */
#messageframe
{
position: absolute;
- top: 95px;
+ top: 85px;
left: 200px;
- right: 40px;
+ right: 30px;
bottom: 40px;
border: 1px solid #cccccc;
background-color: #FFFFFF;
overflow: auto;
/* css hack for IE */
/* margin-bottom: 10px; */
width: expression((parseInt(document.documentElement.clientWidth)-240)+'px');
height: expression((parseInt(document.documentElement.clientHeight)-125)+'px');
}
div.messageheaderbox
{
margin: 6px 8px 0px 8px;
border: 1px solid #ccc;
}
table.headers-table
{
width: 100%;
background-color: #EBEBEB;
table-layout: fixed;
}
#messagebody table.headers-table
{
width: auto;
margin: 6px 8px;
background-color: #F4F4F4;
border: 1px solid #ccc;
}
table.headers-table tr td
{
font-size: 11px;
border-bottom:1px solid #FFFFFF;
}
table.headers-table td.header-title
{
width: 80px;
color: #666666;
font-weight: bold;
text-align: right;
white-space: nowrap;
padding-right: 4px;
}
table.headers-table tr td.subject
{
width: 95%;
font-weight: bold;
}
#attachment-list
{
margin: 0px;
padding: 0px 0px 0px 68px;
min-height: 18px;
list-style-image: none;
list-style-type: none;
background: url(images/icons/attachment.png) 52px 1px no-repeat #DFDFDF; 
}
#attachment-list:after
{
content: ".";
display: block;
height: 0;
font-size: 0;
clear: both;
visibility: hidden;
}
#attachment-list li
{
float: left;
height: 18px;
font-size: 11px;
padding: 2px 10px 0px 10px;
}
#attachment-list li a
{
text-decoration: none;
}
#attachment-list li a:hover
{
text-decoration: underline;
}
#messagebody
{
position:relative;
min-height: 300px;
padding-top: 10px;
padding-bottom: 10px;
background-color: #FFFFFF;
}
div.message-part
{
padding: 8px;
padding-top: 10px;
overflow: hidden;
}
div.message-part a
{
color: #0000CC;
}
div.message-part div.pre
{
margin: 0px;
padding: 0px;
white-space: pre;
font-family: monospace;
}
div.message-part blockquote
{
color: blue;
border-left: 2px solid blue;
border-right: 2px solid blue;
background-color: #F6F6F6;
margin: 2px 0px 2px 0px;
padding: 1px 8px 1px 10px;
}
div.message-part blockquote blockquote
{
color: green;
border-left: 2px solid green;
border-right: 2px solid green;
}
div.message-part blockquote blockquote blockquote
{
color: #990000;
border-left: 2px solid #bb0000;
border-right: 2px solid #bb0000;
}
#remote-objects-message
{
display: none;
height: 20px;
min-height: 20px;
margin: 8px 8px 0px 8px;
padding: 10px 10px 6px 46px;
}
#remote-objects-message a
{
color: #666666;
padding-left: 10px;
}
#remote-objects-message a:hover
{
color: #333333;
}
/** message compose styles */
#priority-selector
{
position: absolute;
left: 280px;
top: 10px;
}
#receipt-selector
{
position: absolute;
left: 450px;
top: 10px;
}
#compose-container
{
position: absolute;
top: 90px;
left: 200px;
right: 40px;
bottom: 40px;
padding: 0px;
margin: 0px;
/* css hack for IE */
width: expression(document.documentElement.clientWidth-240);
height: expression((parseInt(document.documentElement.clientHeight)-130)+'px');
}
/*
#compose-headers
{
position: absolute;
top: 70px;
left: 200px;
height: 84px;
border-top: 1px solid #cccccc;
overflow: auto;
}
#compose-headers td
{
padding-top: 1px;
padding-bottom: 1px;
border-right: 1px solid #cccccc;
border-bottom: 1px solid #cccccc;
}
*/
#compose-headers
{
width: 100%;
}
/*
#compose-headers td
{
width: 100%;
}
*/
#compose-headers td.top
{
vertical-align: top;
}
#compose-headers td.title,
#compose-subject td.title
{
width: 80px !important;
color: #666666;
font-size: 11px;
font-weight: bold;
padding-right: 10px;
white-space: nowrap;
}
#compose-headers td.add-button
{
width: 40px !important;
text-align: right;
vertical-align: bottom;
}
#compose-headers td.add-button a
{
color: #666666;
font-size: 11px;
text-decoration: none;
}
#compose-headers td textarea
{
width: 100%;
height: 40px;
}
#compose-headers td input
{
width: 100%;
}
#compose-cc,
#compose-bcc,
#compose-replyto
{
display: none;
}
#compose-body
{
margin-top: 5px;
margin-bottom: 10px;
width: 99%;
height: 90%;
min-height: 280px;
font-size: 9pt;
font-family: "Courier New", Courier, monospace;
}
#compose-attachments
{
position: absolute;
top: 100px;
left: 20px;
width: 160px;
}
#compose-attachments ul
{
margin: 0px;
padding: 0px;
border: 1px solid #CCCCCC;
background-color: #F9F9F9;
list-style-image: none;
list-style-type: none;
}
#compose-attachments ul li
{
height: 18px;
font-size: 11px;
padding-left: 2px;
padding-top: 2px;
padding-right: 4px;
border-bottom: 1px solid #EBEBEB;
white-space: nowrap;
overflow: hidden;
}
#attachment-title
{
background: url(images/icons/attachment.png) top left no-repeat;
padding: 0px 0px 3px 22px;
}
#attachment-form
{
position: absolute;
top: 150px;
left: 20px;
z-index: 200;
padding: 8px;
visibility: hidden;
border: 1px solid #CCCCCC;
background-color: #F9F9F9;
}
#attachment-form input.button
{
margin-top: 8px;
}
diff --git a/skins/default/print.css b/skins/default/print.css
index 5f0dbddc3..a36f87a1f 100644
--- a/skins/default/print.css
+++ b/skins/default/print.css
@@ -1,136 +1,136 @@
/***** RoundCube|Mail message print styles *****/
body
{
background-color: #ffffff;
color: #000000;
margin: 2mm;
}
body, td, th, span, div, p, h3
{
font-family: "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
font-size: 9pt;
color: #000000;
}
h3
{
font-size: 18px;
color: #000000;
}
a, a:active, a:visited
{
color: #000000;
}
#header
{
margin-left: 5mm;
margin-bottom: 3mm;
}
#messageframe
{
position: relative;
}
table.headers-table
{
table-layout: fixed;
}
table.headers-table tr td
{
font-size: 9pt;
}
table.headers-table td.header-title
{
color: #666666;
font-weight: bold;
text-align: right;
vertical-align: top;
padding-right: 4mm;
white-space: nowrap;
}
table.headers-table tr td.subject
{
width: 90%;
font-weight: bold;
}
#attachment-list
{
margin-top: 3mm;
padding-top: 3mm;
border-top: 1pt solid #cccccc;
}
#attachment-list li
{
font-size: 9pt;
}
#attachment-list li a
{
text-decoration: none;
}
#attachment-list li a:hover
{
text-decoration: underline;
}
#messagebody
{
margin-top: 5mm;
border-top: none;
}
div.message-part
{
padding: 2mm;
margin-top: 5mm;
margin-bottom: 5mm;
border-top: 1pt solid #cccccc;
}
div.message-part a
{
color: #0000CC;
}
div.message-part div.pre
{
margin: 0;
padding: 0;
white-space: pre;
- font-size: 9pt;
+ font-family: monospace;
}
div.message-part blockquote
{
color: blue;
border-left: 2px solid blue;
border-right: 2px solid blue;
background-color: #F6F6F6;
margin: 0.5em 0em 0.5em 0em;
padding: 0.25em 1em 0.25em 1em;
}
div.message-part blockquote blockquote
{
color: green;
border-left: 2px solid green;
border-right: 2px solid green;
}
div.message-part blockquote blockquote blockquote
{
color: #990000;
border-left: 2px solid #bb0000;
border-right: 2px solid #bb0000;
}
diff --git a/skins/default/templates/addcontact.html b/skins/default/templates/addcontact.html
index d4fc9cc59..e52b8c737 100644
--- a/skins/default/templates/addcontact.html
+++ b/skins/default/templates/addcontact.html
@@ -1,24 +1,25 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><roundcube:object name="pagetitle" /></title>
<roundcube:include file="/includes/links.html" />
<link rel="stylesheet" type="text/css" href="/addresses.css" />
</head>
<body class="iframe">
<div id="contact-title" class="boxtitle"><roundcube:label name="addcontact" /></div>
<div id="contact-details">
<roundcube:object name="contacteditform" size="40" />
<p><br />
<input type="button" value="<roundcube:label name="cancel" />" class="button" onclick="history.back()" />&nbsp;
<roundcube:button command="save" type="input" class="button" label="save" />
</p>
+</form>
</div>
</body>
</html>
diff --git a/skins/default/templates/addressbook.html b/skins/default/templates/addressbook.html
index e5b5a104b..c70b00c92 100644
--- a/skins/default/templates/addressbook.html
+++ b/skins/default/templates/addressbook.html
@@ -1,45 +1,53 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><roundcube:object name="pagetitle" /></title>
<roundcube:include file="/includes/links.html" />
<link rel="stylesheet" type="text/css" href="/addresses.css" />
<script type="text/javascript" src="/splitter.js"></script>
</head>
<body>
<roundcube:include file="/includes/taskbar.html" />
<roundcube:include file="/includes/header.html" />
<div id="abooktoolbar">
<roundcube:button command="add" imageSel="/images/buttons/add_contact_sel.png" imageAct="/images/buttons/add_contact_act.png" imagePas="/images/buttons/add_contact_pas.png" width="32" height="32" title="newcontact" />
<roundcube:button command="delete" imageSel="/images/buttons/delete_sel.png" imageAct="/images/buttons/delete_act.png" imagePas="/images/buttons/delete_pas.png" width="32" height="32" title="deletecontact" />
<roundcube:button command="compose" imageSel="/images/buttons/compose_sel.png" imageAct="/images/buttons/compose_act.png" imagePas="/images/buttons/compose_pas.png" width="32" height="32" title="composeto" />
<roundcube:button command="print" imageSel="/images/buttons/print_sel.png" imageAct="/images/buttons/print_act.png" imagePas="/images/buttons/print_pas.png" width="32" height="32" title="print" />
<roundcube:button command="export" imageSel="/images/buttons/download_sel.png" imageAct="/images/buttons/download_act.png" imagePas="/images/buttons/download_pas.png" width="32" height="32" title="export" />
-<roundcube:button command="ldappublicsearch" imageSel="/images/buttons/contacts_sel.png" imageAct="/images/buttons/contacts_act.png" imagePas="/images/buttons/contacts_pas.png" width="32" height="32" title="ldapsearch" />
</div>
-<div id="abookcountbar">
-<roundcube:button command="firstpage" imageSel="/images/buttons/first_sel.png" imageAct="/images/buttons/first_act.png" imagePas="/images/buttons/first_pas.png" width="11" height="11" title="firstpage" />
-<roundcube:button command="previouspage" imageSel="/images/buttons/previous_sel.png" imageAct="/images/buttons/previous_act.png" imagePas="/images/buttons/previous_pas.png" width="11" height="11" title="previouspage" />
-&nbsp;<roundcube:object name="recordsCountDisplay" />&nbsp;
-<roundcube:button command="nextpage" imageSel="/images/buttons/next_sel.png" imageAct="/images/buttons/next_act.png" imagePas="/images/buttons/next_pas.png" width="11" height="11" title="nextpage" />
-<roundcube:button command="lastpage" imageSel="/images/buttons/last_sel.png" imageAct="/images/buttons/last_act.png" imagePas="/images/buttons/last_pas.png" width="11" height="11" title="lastpage" />
+<div id="quicksearchbar">
+<roundcube:object name="searchform" type="search" results="5" id="quicksearchbox" /><roundcube:button command="reset-search" id="searchreset" image="/images/icons/reset.gif" title="resetsearch" />
+</div>
+
+<div id="directorylist">
+<div id="groups-title"><roundcube:label name="groups" /></div>
+<roundcube:object name="directorylist" id="directories-list" />
</div>
<div id="addresslist">
<roundcube:object name="addresslist" id="contacts-table" class="records-table" cellspacing="0" summary="Contacts list" />
</div>
<script type="text/javascript">
var addrviewsplit = new rcube_splitter({id:'addressviewsplitter', p1: 'addresslist', p2: 'contacts-box', orientation: 'v'});
rcmail.add_onload('addrviewsplit.init()');
</script>
<div id="contacts-box">
<roundcube:object name="addressframe" id="contact-frame" width="100%" height="100%" frameborder="0" src="/watermark.html" />
</div>
+<div id="abookcountbar">
+<roundcube:button command="firstpage" imageSel="/images/buttons/first_sel.png" imageAct="/images/buttons/first_act.png" imagePas="/images/buttons/first_pas.png" width="11" height="11" title="firstpage" />
+<roundcube:button command="previouspage" imageSel="/images/buttons/previous_sel.png" imageAct="/images/buttons/previous_act.png" imagePas="/images/buttons/previous_pas.png" width="11" height="11" title="previouspage" />
+&nbsp;<roundcube:object name="recordsCountDisplay" />&nbsp;
+<roundcube:button command="nextpage" imageSel="/images/buttons/next_sel.png" imageAct="/images/buttons/next_act.png" imagePas="/images/buttons/next_pas.png" width="11" height="11" title="nextpage" />
+<roundcube:button command="lastpage" imageSel="/images/buttons/last_sel.png" imageAct="/images/buttons/last_act.png" imagePas="/images/buttons/last_pas.png" width="11" height="11" title="lastpage" />
+</div>
+
</body>
</html>
diff --git a/skins/default/templates/compose.html b/skins/default/templates/compose.html
index 3c8348843..63d5b2c2b 100644
--- a/skins/default/templates/compose.html
+++ b/skins/default/templates/compose.html
@@ -1,147 +1,146 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><roundcube:object name="productname" /> :: <roundcube:label name="compose" /></title>
<roundcube:include file="/includes/links.html" />
<link rel="stylesheet" type="text/css" href="/mail.css" />
<link rel="stylesheet" type="text/css" href="/googiespell.css" />
<script type="text/javascript">
<!--
function rcmail_toggle_display(id)
{
var row, disp;
if (row = document.getElementById(id))
{
disp = (!row.style.display || row.style.display=='none') ? ((document.all && !window.opera) ? 'block' : 'table-row') : 'none';
row.style.display = disp;
}
return false;
}
//-->
</script>
</head>
<body>
<roundcube:include file="/includes/taskbar.html" />
<roundcube:include file="/includes/header.html" />
<form name="form" action="./" method="post">
<div id="messagetoolbar">
<!--<roundcube:button command="list" image="/images/buttons/back_act.png" imageSel="/images/buttons/back_sel.png" imageAct="/images/buttons/back_act.png" width="32" height="32" title="backtolist" />-->
<roundcube:button command="send" imageSel="/images/buttons/send_sel.png" imageAct="/images/buttons/send_act.png" imagePas="/images/buttons/send_pas.png" width="32" height="32" title="sendmessage" />
<roundcube:button command="spellcheck" imageSel="/images/buttons/spellcheck_sel.png" imageAct="/images/buttons/spellcheck_act.png" imagePas="/images/buttons/spellcheck_pas.png" width="32" height="32" title="checkspelling" />
<roundcube:button command="add-attachment" imageSel="/images/buttons/attach_sel.png" imageAct="/images/buttons/attach_act.png" imagePas="/images/buttons/attach_pas.png" width="32" height="32" title="addattachment" />
<roundcube:button command="savedraft" imageSel="/images/buttons/drafts_sel.png" imageAct="/images/buttons/drafts_act.png" imagePas="/images/buttons/drafts_pas.png" width="32" height="32" title="savemessage" />
<div id="priority-selector">
<label for="rcmcomposepriority"><roundcube:label name="priority" />:</label>&nbsp;<roundcube:object name="prioritySelector" form="form" id="rcmcomposepriority" />
</div>
<div id="receipt-selector">
<roundcube:object name="receiptCheckBox" form="form" id="rcmcomposereceipt" />&nbsp;<label for="rcmcomposereceipt"><roundcube:label name="returnreceipt" /></label>
</div>
</div>
<div id="compose-container">
<table border="0" cellspacing="0" cellpadding="1" style="width:100%; height:99%;" summary="">
<tbody>
<tr>
<td>
<table border="0" cellspacing="0" cellpadding="1" id="compose-headers" summary="">
<tbody><tr>
<td class="title"><label for="rcmcomposefrom"><roundcube:label name="from" /></label></td>
<td><roundcube:object name="composeHeaders" part="from" form="form" id="rcmcomposefrom" tabindex="1" /></td>
</tr><tr>
<td class="title top"><label for="rcmcomposeto"><roundcube:label name="to" /></label></td>
<td><roundcube:object name="composeHeaders" part="to" form="form" id="rcmcomposeto" cols="80" rows="2" tabindex="2" /></td>
<td class="add-button"><a href="#" onclick="return rcmail_toggle_display('compose-cc')">[Cc]</a><br />
<a href="#" onclick="return rcmail_toggle_display('compose-bcc')">[Bcc]</a><br /></td>
</tr><tr id="compose-cc">
<td class="title top"><label for="rcmcomposecc"><roundcube:label name="cc" /></label></td>
<td><roundcube:object name="composeHeaders" part="cc" form="form" id="rcmcomposecc" cols="80" rows="2" tabindex="3" /></td>
</tr><tr id="compose-bcc">
<td class="title top"><label for="rcmcomposebcc"><roundcube:label name="bcc" /></label></td>
<td><roundcube:object name="composeHeaders" part="bcc" form="form" id="rcmcomposebcc" cols="80" rows="2" tabindex="4" /></td>
</tr><tr id="compose-replyto">
<td class="title top"><label for="rcmcomposereplyto"><roundcube:label name="replyto" /></label></td>
<td><roundcube:object name="composeHeaders" part="replyto" form="form" id="rcmcomposereplyto" size="80" tabindex="5" /></td>
</tr><tr>
<td class="title"><label for="compose-subject"><roundcube:label name="subject" /></label></td>
<td><roundcube:object name="composeSubject" id="compose-subject" form="form" tabindex="6" /></td>
</tr>
</tbody>
</table>
</td>
</tr><tr>
<td style="width:100%; height:98%; vertical-align:top;">
<roundcube:object name="composeBody" id="compose-body" form="form" cols="80" rows="20" wrap="virtual" tabindex="7" />
-<table border="0" cellspacing="0" width="100%" summary=""><tbody><tr>
-
+<table border="0" cellspacing="0" width="100%" summary=""><tbody>
+<tr>
<td>
<roundcube:button type="input" command="send" class="button" label="sendmessage" />
<roundcube:button type="input" command="list" class="button" label="cancel" />
</td>
<td align="right">
-<roundcube:label name="charset" />:&nbsp;<roundcube:object name="charsetSelector" tabindex="8" />
+ <roundcube:label name="editortype" />:&nbsp;
+ <span class="radios-left"><roundcube:object name="editorSelector" tabindex="9" /></span>
</td>
-<td align="right">
- <roundcube:label name="editortype" />:&nbsp;</td>
-<roundcube:object name="editorSelector" tabindex="9" />
-</tr></tbody></table>
+</tr>
+</tbody></table>
</td>
</tr>
</tbody>
</table>
</div>
<div id="compose-attachments">
<div id="attachment-title"><roundcube:label name="attachments" /></div>
<roundcube:object name="composeAttachmentList" deleteIcon="/images/icons/remove-attachment.png"/ >
<p><roundcube:button command="add-attachment" imagePas="/images/buttons/add_pas.png" imageSel="/images/buttons/add_sel.png" imageAct="/images/buttons/add_act.png" width="23" height="18" title="addattachment" />
</div>
</form>
<roundcube:object name="composeAttachmentForm" id="attachment-form" />
<script type="text/javascript">
<!--
var cc_field = document.form._cc;
if (cc_field && cc_field.value!='')
rcmail_toggle_display('compose-cc');
var bcc_field = document.form._bcc;
if (bcc_field && bcc_field.value!='')
rcmail_toggle_display('compose-bcc');
//-->
</script>
</body>
</html>
diff --git a/skins/default/templates/ldappublicsearch.html b/skins/default/templates/ldappublicsearch.html
deleted file mode 100644
index d9714cb85..000000000
--- a/skins/default/templates/ldappublicsearch.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<title><roundcube:object name="pagetitle" /></title>
-<link rel="stylesheet" type="text/css" href="/common.css" />
-<link rel="stylesheet" type="text/css" href="/ldapsearchform.css" />
-</head>
-<body class="iframe">
-
-<div id="ldapsearch-title"><roundcube:label name="ldappublicsearchform" /></div>
-
-<div id="ldapsearch-details">
-<roundcube:object name="ldappublicsearch" size="40" />
-<p>
-<roundcube:button command="ldappublicsearch" type="input" class="button" label="ldappublicsearch" />
-<input type="button" value="<roundcube:label name="cancel" />" class="button" onclick="history.back()" />&nbsp;
-<br /></p>
-</div>
-
-
-<div id="ldapsearch-results">
-<roundcube:object name="ldappublicaddresslist"
- id="ldappublicaddresslist"
- cellspacing="0"
- summary="LDAP email address list" />
-</div>
-
-<roundcube:include file="/includes/ldapscripts.html" />
-
-</body>
-</html>
diff --git a/skins/default/templates/showcontact.html b/skins/default/templates/showcontact.html
index 53bc08b5c..79304578c 100644
--- a/skins/default/templates/showcontact.html
+++ b/skins/default/templates/showcontact.html
@@ -1,19 +1,19 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><roundcube:object name="pagetitle" /></title>
<roundcube:include file="/includes/links.html" />
<link rel="stylesheet" type="text/css" href="/addresses.css" />
</head>
<body class="iframe">
<div id="contact-title" class="boxtitle"><roundcube:object name="contactdetails" part="name" /></div>
<div id="contact-details">
<roundcube:object name="contactdetails" />
-<p><br /><roundcube:button command="edit" type="input" class="button" label="editcontact" /></p>
+<p><br /><roundcube:button command="edit" type="input" class="button" label="editcontact" condition="!ENV:readonly" /></p>
</div>
</body>
</html>

File Metadata

Mime Type
text/x-diff
Expires
Thu, Mar 19, 10:23 AM (1 d, 9 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
458630
Default Alt Text
(751 KB)

Event Timeline