Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F9785344
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Size
193 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/CHANGELOG b/CHANGELOG
index 6ead1dc24..5cb09012e 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,305 +1,312 @@
CHANGELOG RoundCube Webmail
---------------------------
+2006/07/19 (thomasb)
+----------
+- Correct entity encoding of link urls (HTML validity)
+- Moved back button in compose step (Ticket #)
+- Added absolute URLs to several buttons (for "open in new window")
+
+
2006/07/18 (thomasb)
----------
- Fixed password with spaces issue (Bug #1364122)
- Replaced _auth hash with second cookie (Ticket #1483811)
- Don't use get_input_value() for passwords (Bug #1468895)
- Made password encryption key configurable
- Minor bugfixes with charset encoding
- Added <label> tags to forms (Ticket #1483810)
2006/07/07 (thomasb)
----------
- Fixed INSTALL_PATH bug #1425663
2006/07/03 (richs)
----------
- Fixed compatibility with in-body email addresses containing "+" (Bug #1483836)
- Updated French localizations (Ticket #1483862)
- Incoming messages can now be moved to Drafts, edited, saved, then moved back (Feature #1436191)
- Added Firefox workaround when clicking whitespace to drag messages (Bug #1483857)
- Corrected Dutch and Italian localizations (Ticket #1483851 and #1483848)
- Enabled 'Empty' (purge) command for Junk mailbox (defined in main.inc.php)
2006/06/30 (richs)
----------
- Fixed empty INBOX compatibility bug (Patch #1443200)
- Temporarily fixed French "compact" localization (Patch #1483862)
- Fixed "Select All" not working with Delete interface button (Bug #1332434)
- Fixed messsage list column compatibility with Konqueror (Bug #1395711)
- Fixed "unread count" in window title when count changed (Bug #1483812)
- Fixed DB error when deleting from message table (Patch #1483835)
2006/06/29 (richs)
----------
- Added ability to remove attachments (Feature #1436721)
- Default folders are now auto-created on first login (Feature #1471594)
- Fixed compatibility with folder apostrophes (e.g.: Joe's Folder) (Bug #1429458)
- Corrected Italian localizations
- Tweaked rename-folder form to clear after a rename
2006/06/26 (richs)
----------
- Added button to immediately check for new messages
- New message checking now displays status "Checking for new messages..."
- New message checking now looks for unread messages in all mailboxes (Feature #1326401)
- Task buttons now respond to clicks by darkening (as in other applications)
- Fixed "Sender" column changing to "Recipient" for "Sent" and "Drafts" message lists
- Added ability to sort messages by "Size"
- Added ability to rename folders (Feature #1326396)
- Added 'protect_default_folders' option to main.inc.php to prevent renames/deletes/unsubscribes of default folders
- Corrected 5 typos of "INSTLL" to "INSTALL" in program/include/main.inc
2006/06/25
----------
- Changed behavior to include host-specific configuration (Bug #1483849)
- Assume ISO-8859-1 encoding of mail messages by default (Patch #1483839)
- Fixed spell checker to work with the new URL at google.com
- Some memory and security optimizations sendmail.inc
- Updated UGRADING description
2006/06/19
----------
- Added Drafts support (Feature #1326839) (richs)
2006/06/02
----------
- Updated Estonian localization and moved from ee to et
- Added Bulgarian localization
2006/05/25
----------
- Finalized GoogieSpell integration
2006/05/18
----------
- Added Arabic and Armenian localizations
- Updated Russian localization
- Removed MDB2 classes from repository. Install them seperately if used.
- Updated MDB2 wrapper class contributed by Lukas Kahwe Smith
- Allow & in e-mail addresses
2006/05/05
----------
- Fixed typos in function rcube_button() (Bugs #1473198 and #1473201)
- Check for zlib.output_compression before using ob_gzhandler (Bug #1471069)
- Casting date parts in iil_StrToTime() to avoid warnings (Bug #1482140)
- Corrected INSTALL description (Bug #1476106)
- Added charset to javascript HTTP headers
- Fixed Opera bug with CC and BCC fields (Bug #1474576)
- Changed login page title regarding product name (Bug #1476413)
- Pimped search function
- Applied attachment viewing/forwarding patches by Andrew Fladmark
- Applied prev/next patch by Leonard Bouchet
- Applied patches by Mark Bucciarelli
- Applied patch for requesting receipts by Salvatore Ansani
- Integrated GoogieSpell as suggested by phil (styling is not perfect yet, localization is missing)
2006/04/13
----------
- Added Slovenian localization
- Updated Portuguese localization
- Fixed parent.location problem for compose-links
- Added sort order saving patch by Jacob Brunson
- Added gzip compression support
2006/04/02
----------
- Added Lithuanian localization
- Improved search function
- Added version string as template object
- Load host-specific configuration file (see config/main.inc.php)
- New config parameter adding domain to user names for login
- Strip tags on _auth, _action, _task parameters
- Corrected labels for next/previous page buttons in address book
2006/03/23
----------
- Auto-detect mail header delimiters
- Regard daylight savings
- Localized quota display
- Started implementing search function
2006/03/20
----------
- Avoid error message when saving an unchanged identity (Bug #1429510)
- Fixed hard-coded cols selection for sent folder (Bug #1354586)
- Enable some HTML links for use with "open in new window" or "save target"
- Check meta-key instead of ctrl on Macs
- Ignore double clicks when holding down a modifier key
- Fixed reloading of the login page
- Fixed typo in compose template (Bug #1446852)
- Added compose button to message read step (Request #1433288)
- New config parameter for persistent database connections (Bug #1431817)
2006/03/14
----------
- Don't remove internal HTML tags in plaintext messages
- Improved error handling in DB connection failure
2006/02/22
----------
- Updated localizations
- Fixed bug #1435989
2006/02/19
----------
- Updated localizations
- Applied patch of Anders Karlsson
- Applied patch of Jacob Brunson
- Applied patch for virtuser_query by Robin Elfrink
- Added support for References header (patch by Auke)
- Added support for mbstring module by Tadashi Jokagi
- Added function for automatic remove of slashes on GET and POST vars
if magic_quotes is enabled
2006/02/05
----------
- Added Slovak, Hungarian, Bosnian and Croation translation
- Fixed bug when inserting signatures with !?&
- Chopping message headers before inserting into the message cache table
(to avoid bugs in Postgres)
- Allow one-char domains in e-mail addresses
- Make product name in page title configurable
- Make username available as skin object
- Added session_write_close() in rcube_db class destructor to avoid problems
in PHP 5.0.5
- Use move_uploaded_file() instead of copy() for a more secure handling of
uploaded attachments
- Additional config parameter to show/hide deleted messages
- Added periodic request for checking new mails (Request #1307821)
- Added EXPUNGE command
- Optimized loading time for mail interface
- Changed to full UTF-8 support
- Additional timezones (Patch #1389912)
- Added LDAP public search (experimental)
- Applied patch for correct ctrl/shift behavior for message selection (Bug #1326364)
- Casting to strings when adding empty headers to message cache (Bug #1406026)
- Skip sender-address as recipient when Reply-to-all
- Fixes in utf8-class
- Added patch for Quota display by Aury Fink Filho <nuny@aury.com.br>
- Added garbage collector for message cache
- Added patches for BCC headers
2005/12/16
----------
- Added Turkish and Simplified Chinese translation
- Use virtusertable to resolve e-mail addresses at login
- Configurable mail_domain used to compose correct e-mail addresses
on first login
2005/12/03
----------
- Added Finnish, Romanian, Polish, Czech, British, Norwegian, Greek, Russian,
Estonian and Chinese translation
- Get IMAP server capabilities in array
- Check for NAMESPACE capability before sending command
- Set default user language from config 'locale_string'
- Added sorting patch for message list
- Make default sort col/order configurable
- Fixed XSS in address book and identities
- Added more XSS protection (Bug #1308236)
- Added tab indexes for compose form
- Added 'changed' col to contacts table
- Support for 160-bit session hashes
- Added input check for contacts and identities (Patch #1346523)
- Added messages/warning to compose step (Patch #1323895)
- Added favicon to the default skin
- Fixed Bug #1334337 as far as possible
- Added Reply-To-All functionality (Request #1326395, Patch #1349777)
- Redesign of client side AJAX code (enable multi threading)
- Added keep-alive signal every minute
- Make logs dir configurable
- Added support for SMTPS
- Decode attachment file names
- Make delimiter for message headers configurable
- Add generic footer to sent messages
- Choose the rigt identity when replying
- Remove signature when replying (Request #1333167)
- Signatures for each identity
- Select charset when composing message
- Complete re-design of the caching mechanism
2005/08/11
----------
- Write list header to client even if list is empty
- Add functions "select all", "select none" to message list
- Improved filter for HTML messages to remove potentially malicious tags
(script, iframe, object) and event handlers.
- Buttons for next/previous message in view mode
- Add new created contact to list and show confirmation status
- Added folder management (subscribe/create/delete)
- Log message sending (SMTP log)
- Grant access for Camino browser
- Added German translation
2005/10/20
----------
- Added Swedish, Latvian, Portuguese and Catalan translation
- Make SMTP auth method configurable
- Make mailboxlist scrollable (Bug #1326372)
- Fixed SSL support
- Improved support for Courier IMAP (root folder and delimiter issues)
- Moved taskbar from bottom to top
- Added 'session_lifetime' parameter
- Fixed wrong unread count when deleting message (Bug #1332434)
- Srip tags when creating a new folder (Bug #1332084)
- Translate HTML tags in message headers (Bug #1330134)
- Correction in German translation (Bug #1329434)
- Display folder names with special chars correctly (Bug #1330157)
2005/10/07
----------
- Added French, Italian, Spanish, Danish, Dutch translation
- Clarified license (Bug #1305966)
- Fixed PHP warnings (Bug #1299403)
- Fixed english translation (Bug #1295406)
- Fixed bug #1290833: Last character of email not seen
- Fixed bug #1292199 when creating new user
- Allow more browsers (Bug #1285101)
- Added setting for showing pretty dates
- Added support for SQLite database
- Make use of message caching configurable
- Also add attachments when forwarding a message
- Long folder names will not flow over message list (Bug #1267232)
- Show nested mailboxes hieracically
- Enable IMAPS by host
2005/08/20
----------
- Improved cacheing of mailbox messagecount
- Fixed javascript bug when creating a new message folder
- Fixed javascript bugs #1260990 and #1260992: folder selection
- Make Trash folder configurable
- Auto create folders Inbox, Sent and Trash (if configured)
- Support for IMAP root folder
- Added support fot text/enriched messages
- Make list of special mailboxes configurable
diff --git a/program/include/main.inc b/program/include/main.inc
index ef2ecbfe8..e77df19e3 100644
--- a/program/include/main.inc
+++ b/program/include/main.inc
@@ -1,1790 +1,1795 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/main.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, RoundCube Dev, - Switzerland |
| Licensed under the GNU GPL |
| |
| PURPOSE: |
| Provide basic functions for the webmail package |
| |
+-----------------------------------------------------------------------+
| Author: Thomas Bruederli <roundcube@gmail.com> |
+-----------------------------------------------------------------------+
$Id$
*/
require_once('lib/des.inc');
require_once('lib/utf7.inc');
require_once('lib/utf8.class.php');
// define constannts for input reading
define('RCUBE_INPUT_GET', 0x0101);
define('RCUBE_INPUT_POST', 0x0102);
define('RCUBE_INPUT_GPC', 0x0103);
// register session and connect to server
function rcmail_startup($task='mail')
{
global $sess_id, $sess_auth, $sess_user_lang;
global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
// check client
$BROWSER = rcube_browser();
// load config file
include_once('config/main.inc.php');
$CONFIG = is_array($rcmail_config) ? $rcmail_config : array();
// load host-specific configuration
rcmail_load_host_config($CONFIG);
$CONFIG['skin_path'] = $CONFIG['skin_path'] ? unslashify($CONFIG['skin_path']) : 'skins/default';
// load db conf
include_once('config/db.inc.php');
$CONFIG = array_merge($CONFIG, $rcmail_config);
if (empty($CONFIG['log_dir']))
$CONFIG['log_dir'] = $INSTALL_PATH.'logs';
else
$CONFIG['log_dir'] = unslashify($CONFIG['log_dir']);
// set PHP error logging according to config
if ($CONFIG['debug_level'] & 1)
{
ini_set('log_errors', 1);
ini_set('error_log', $CONFIG['log_dir'].'/errors');
}
if ($CONFIG['debug_level'] & 4)
ini_set('display_errors', 1);
else
ini_set('display_errors', 0);
// set session garbage collecting time according to session_lifetime
if (!empty($CONFIG['session_lifetime']))
ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']+2)*60);
// prepare DB connection
require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
$DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
$DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
$DB->db_connect('w');
// we can use the database for storing session data
if (!$DB->is_error())
include_once('include/session.inc');
// init session
session_start();
$sess_id = session_id();
// create session and set session vars
if (!isset($_SESSION['auth_time']))
{
$_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
$_SESSION['auth_time'] = mktime();
setcookie('sessauth', rcmail_auth_hash($sess_id, $_SESSION['auth_time']));
}
// set session vars global
$sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
// overwrite config with user preferences
if (is_array($_SESSION['user_prefs']))
$CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
// reset some session parameters when changing task
if ($_SESSION['task'] != $task)
unset($_SESSION['page']);
// set current task to session
$_SESSION['task'] = $task;
// create IMAP object
if ($task=='mail')
rcmail_imap_init();
// set localization
if ($CONFIG['locale_string'])
setlocale(LC_ALL, $CONFIG['locale_string']);
else if ($sess_user_lang)
setlocale(LC_ALL, $sess_user_lang);
register_shutdown_function('rcmail_shutdown');
}
// load a host-specific config file if configured
function rcmail_load_host_config(&$config)
{
$fname = NULL;
if (is_array($config['include_host_config']))
$fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
else if (!empty($config['include_host_config']))
$fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
if ($fname && is_file('config/'.$fname))
{
include('config/'.$fname);
$config = array_merge($config, $rcmail_config);
}
}
// create authorization hash
function rcmail_auth_hash($sess_id, $ts)
{
global $CONFIG;
$auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
$sess_id,
$ts,
$CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
$_SERVER['HTTP_USER_AGENT']);
if (function_exists('sha1'))
return sha1($auth_string);
else
return md5($auth_string);
}
// compare the auth hash sent by the client with the local session credentials
function rcmail_authenticate_session()
{
$now = mktime();
$valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']));
// renew auth cookie every 5 minutes
if (!$valid || ($now-$_SESSION['auth_time'] > 300))
{
$_SESSION['auth_time'] = $now;
setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
}
return $valid;
}
// create IMAP object and connect to server
function rcmail_imap_init($connect=FALSE)
{
global $CONFIG, $DB, $IMAP;
$IMAP = new rcube_imap($DB);
$IMAP->debug_level = $CONFIG['debug_level'];
$IMAP->skip_deleted = $CONFIG['skip_deleted'];
// connect with stored session data
if ($connect)
{
if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
show_message('imaperror', 'error');
rcmail_set_imap_prop();
}
// enable caching of imap data
if ($CONFIG['enable_caching']===TRUE)
$IMAP->set_caching(TRUE);
if (is_array($CONFIG['default_imap_folders']))
$IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
// 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 (!empty($_SESSION['mbox']))
$IMAP->set_mailbox($_SESSION['mbox']);
if (isset($_SESSION['page']))
$IMAP->set_page($_SESSION['page']);
}
// do these things on script shutdown
function rcmail_shutdown()
{
global $IMAP;
if (is_object($IMAP))
{
$IMAP->close();
$IMAP->write_cache();
}
// before closing the database connection, write session data
session_write_close();
}
// destroy session data and remove cookie
function rcmail_kill_session()
{
// save user preferences
$a_user_prefs = $_SESSION['user_prefs'];
if (!is_array($a_user_prefs))
$a_user_prefs = array();
if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
(isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
{
$a_user_prefs['message_sort_col'] = $_SESSION['sort_col'];
$a_user_prefs['message_sort_order'] = $_SESSION['sort_order'];
rcmail_save_user_prefs($a_user_prefs);
}
$_SESSION = array();
session_destroy();
}
// return correct name for a specific database table
function get_table_name($table)
{
global $CONFIG;
// return table name if configured
$config_key = 'db_table_'.$table;
if (strlen($CONFIG[$config_key]))
return $CONFIG[$config_key];
return $table;
}
// return correct name for a specific database sequence
// (used for Postres only)
function get_sequence_name($sequence)
{
global $CONFIG;
// return table name if configured
$config_key = 'db_sequence_'.$sequence;
if (strlen($CONFIG[$config_key]))
return $CONFIG[$config_key];
return $table;
}
// check the given string and returns language properties
function rcube_language_prop($lang, $prop='lang')
{
global $INSTALL_PATH;
static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
if (empty($rcube_languages))
@include($INSTALL_PATH.'program/localization/index.inc');
// check if we have an alias for that language
if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
$lang = $rcube_language_aliases[$lang];
// try the first two chars
if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
{
$lang = substr($lang, 0, 2);
$lang = rcube_language_prop($lang);
}
if (!isset($rcube_languages[$lang]))
$lang = 'en_US';
// language has special charset configured
if (isset($rcube_charsets[$lang]))
$charset = $rcube_charsets[$lang];
else
$charset = 'UTF-8';
if ($prop=='charset')
return $charset;
else
return $lang;
}
// init output object for GUI and add common scripts
function load_gui()
{
global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
// init output page
$OUTPUT = new rcube_html_page();
// add common javascripts
$javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
$javascript .= "$JS_OBJECT_NAME.set_env('comm_path', '$COMM_PATH');\n";
if (isset($CONFIG['javascript_config'] )){
foreach ($CONFIG['javascript_config'] as $js_config_var){
$javascript .= "$JS_OBJECT_NAME.set_env('$js_config_var', '" . $CONFIG[$js_config_var] . "');\n";
}
}
if (!empty($GLOBALS['_framed']))
$javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
$OUTPUT->add_script($javascript);
$OUTPUT->include_script('common.js');
$OUTPUT->include_script('app.js');
$OUTPUT->scripts_path = 'program/js/';
// set locale setting
rcmail_set_locale($sess_user_lang);
// set user-selected charset
if (!empty($CONFIG['charset']))
$OUTPUT->set_charset($CONFIG['charset']);
// add some basic label to client
rcube_add_label('loading','checkingmail');
}
// set localization charset based on the given language
function rcmail_set_locale($lang)
{
global $OUTPUT, $MBSTRING, $MBSTRING_ENCODING;
static $s_mbstring_loaded = NULL;
// settings for mbstring module (by Tadashi Jokagi)
if ($s_mbstring_loaded===NULL)
{
if ($s_mbstring_loaded = extension_loaded("mbstring"))
{
$MBSTRING = TRUE;
if (function_exists("mb_mbstring_encodings"))
$MBSTRING_ENCODING = mb_mbstring_encodings();
else
$MBSTRING_ENCODING = array("ISO-8859-1", "UTF-7", "UTF7-IMAP", "UTF-8",
"ISO-2022-JP", "EUC-JP", "EUCJP-WIN",
"SJIS", "SJIS-WIN");
$MBSTRING_ENCODING = array_map("strtoupper", $MBSTRING_ENCODING);
if (in_array("SJIS", $MBSTRING_ENCODING))
$MBSTRING_ENCODING[] = "SHIFT_JIS";
}
else
{
$MBSTRING = FALSE;
$MBSTRING_ENCODING = array();
}
}
if ($MBSTRING && function_exists("mb_language"))
{
if (!@mb_language(strtok($lang, "_")))
$MBSTRING = FALSE; // unsupport language
}
$OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
}
// perfom login to the IMAP server and to the webmail service
function rcmail_login($user, $pass, $host=NULL)
{
global $CONFIG, $IMAP, $DB, $sess_user_lang;
$user_id = NULL;
if (!$host)
$host = $CONFIG['default_host'];
// parse $host URL
$a_host = parse_url($host);
if ($a_host['host'])
{
$host = $a_host['host'];
$imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
$imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
}
else
$imap_port = $CONFIG['default_port'];
/* Modify username with domain if required
Inspired by Marco <P0L0_notspam_binware.org>
*/
// Check if we need to add domain
if ($CONFIG['username_domain'] && !strstr($user, '@'))
{
if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
$user .= '@'.$CONFIG['username_domain'][$host];
else if (!empty($CONFIG['username_domain']))
$user .= '@'.$CONFIG['username_domain'];
}
// query if user already registered
$sql_result = $DB->query("SELECT user_id, username, language, preferences
FROM ".get_table_name('users')."
WHERE mail_host=? AND (username=? OR alias=?)",
$host,
$user,
$user);
// user already registered -> overwrite username
if ($sql_arr = $DB->fetch_assoc($sql_result))
{
$user_id = $sql_arr['user_id'];
$user = $sql_arr['username'];
}
// try to resolve email address from virtuser table
if (!empty($CONFIG['virtuser_file']) && strstr($user, '@'))
$user = rcmail_email2user($user);
// exit if IMAP login failed
if (!($imap_login = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
return FALSE;
// user already registered
if ($user_id && !empty($sql_arr))
{
// get user prefs
if (strlen($sql_arr['preferences']))
{
$user_prefs = unserialize($sql_arr['preferences']);
$_SESSION['user_prefs'] = $user_prefs;
array_merge($CONFIG, $user_prefs);
}
// set user specific language
if (strlen($sql_arr['language']))
$sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
// update user's record
$DB->query("UPDATE ".get_table_name('users')."
SET last_login=now()
WHERE user_id=?",
$user_id);
}
// create new system user
else if ($CONFIG['auto_create_user'])
{
$user_id = rcmail_create_user($user, $host);
}
if ($user_id)
{
$_SESSION['user_id'] = $user_id;
$_SESSION['imap_host'] = $host;
$_SESSION['imap_port'] = $imap_port;
$_SESSION['imap_ssl'] = $imap_ssl;
$_SESSION['username'] = $user;
$_SESSION['user_lang'] = $sess_user_lang;
$_SESSION['password'] = encrypt_passwd($pass);
// force reloading complete list of subscribed mailboxes
$IMAP->clear_cache('mailboxes');
return TRUE;
}
return FALSE;
}
// create new entry in users and identities table
function rcmail_create_user($user, $host)
{
global $DB, $CONFIG, $IMAP;
$user_email = '';
// try to resolve user in virtusertable
if (!empty($CONFIG['virtuser_file']) && strstr($user, '@')==FALSE)
$user_email = rcmail_user2email($user);
$DB->query("INSERT INTO ".get_table_name('users')."
(created, last_login, username, mail_host, alias, language)
VALUES (now(), now(), ?, ?, ?, ?)",
$user,
$host,
$user_email,
$_SESSION['user_lang']);
if ($user_id = $DB->insert_id(get_sequence_name('users')))
{
if (is_array($CONFIG['mail_domain']) && isset($CONFIG['mail_domain'][$host]))
$mail_domain = $CONFIG['mail_domain'][$host];
else if (!empty($CONFIG['mail_domain']))
$mail_domain = $CONFIG['mail_domain'];
else
$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']));
if ($sql_arr = $DB->fetch_array($sql_result))
$user_email = $sql_arr[0];
}
// also create new identity records
$DB->query("INSERT INTO ".get_table_name('identities')."
(user_id, del, standard, name, email)
VALUES (?, 0, 1, ?, ?)",
$user_id,
$user_name,
$user_email);
// get existing mailboxes
$a_mailboxes = $IMAP->list_mailboxes();
}
else
{
raise_error(array('code' => 500,
'type' => 'php',
'line' => __LINE__,
'file' => __FILE__,
'message' => "Failed to create new user"), TRUE, FALSE);
}
return $user_id;
}
// load virtuser table in array
function rcmail_getvirtualfile()
{
global $CONFIG;
if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
return FALSE;
// read file
$a_lines = file($CONFIG['virtuser_file']);
return $a_lines;
}
// find matches of the given pattern in virtuser table
function rcmail_findinvirtual($pattern)
{
$result = array();
$virtual = rcmail_getvirtualfile();
if ($virtual==FALSE)
return $result;
// check each line for matches
foreach ($virtual as $line)
{
$line = trim($line);
if (empty($line) || $line{0}=='#')
continue;
if (eregi($pattern, $line))
$result[] = $line;
}
return $result;
}
// resolve username with virtuser table
function rcmail_email2user($email)
{
$user = $email;
$r = rcmail_findinvirtual("^$email");
for ($i=0; $i<count($r); $i++)
{
$data = $r[$i];
$arr = preg_split('/\s+/', $data);
if(count($arr)>0)
{
$user = trim($arr[count($arr)-1]);
break;
}
}
return $user;
}
// resolve e-mail address with virtuser table
function rcmail_user2email($user)
{
$email = "";
$r = rcmail_findinvirtual("$user$");
for ($i=0; $i<count($r); $i++)
{
$data=$r[$i];
$arr = preg_split('/\s+/', $data);
if (count($arr)>0)
{
$email = trim($arr[0]);
break;
}
}
return $email;
}
function rcmail_save_user_prefs($a_user_prefs)
{
global $DB, $CONFIG, $sess_user_lang;
$DB->query("UPDATE ".get_table_name('users')."
SET preferences=?,
language=?
WHERE user_id=?",
serialize($a_user_prefs),
$sess_user_lang,
$_SESSION['user_id']);
if ($DB->affected_rows())
{
$_SESSION['user_prefs'] = $a_user_prefs;
$CONFIG = array_merge($CONFIG, $a_user_prefs);
return TRUE;
}
return FALSE;
}
// overwrite action variable
function rcmail_overwrite_action($action)
{
global $OUTPUT, $JS_OBJECT_NAME;
$GLOBALS['_action'] = $action;
$OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $action));
}
function show_message($message, $type='notice', $vars=NULL)
{
global $OUTPUT, $JS_OBJECT_NAME, $REMOTE_REQUEST;
$framed = $GLOBALS['_framed'];
$command = sprintf("display_message('%s', '%s');",
addslashes(rep_specialchars_output(rcube_label(array('name' => $message, 'vars' => $vars)))),
$type);
if ($REMOTE_REQUEST)
return 'this.'.$command;
else
$OUTPUT->add_script(sprintf("%s%s.%s",
$framed ? sprintf('if(parent.%s)parent.', $JS_OBJECT_NAME) : '',
$JS_OBJECT_NAME,
$command));
// console(rcube_label($message));
}
function console($msg, $type=1)
{
if ($GLOBALS['REMOTE_REQUEST'])
print "// $msg\n";
else
{
print $msg;
print "\n<hr>\n";
}
}
// encrypt IMAP password using DES encryption
function encrypt_passwd($pass)
{
$cypher = des(get_des_key(), $pass, 1, 0, NULL);
return base64_encode($cypher);
}
// decrypt IMAP password using DES encryption
function decrypt_passwd($cypher)
{
$pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
return preg_replace('/\x00/', '', $pass);
}
// return a 24 byte key for the DES encryption
function get_des_key()
{
$key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
$len = strlen($key);
// make sure the key is exactly 24 chars long
if ($len<24)
$key .= str_repeat('_', 24-$len);
else if ($len>24)
substr($key, 0, 24);
return $key;
}
// send correct response on a remote request
function rcube_remote_response($js_code, $flush=FALSE)
{
global $OUTPUT, $CHARSET;
static $s_header_sent = FALSE;
if (!$s_header_sent)
{
$s_header_sent = TRUE;
send_nocacheing_headers();
header('Content-Type: application/x-javascript; charset='.$CHARSET);
print '/** remote response ['.date('d/M/Y h:i:s O')."] **/\n";
}
// send response code
print rcube_charset_convert($js_code, $CHARSET, $OUTPUT->get_charset());
if ($flush) // flush the output buffer
flush();
else // terminate script
exit;
}
// read directory program/localization/ and return a list of available languages
function rcube_list_languages()
{
global $CONFIG, $INSTALL_PATH;
static $sa_languages = array();
if (!sizeof($sa_languages))
{
@include($INSTALL_PATH.'program/localization/index.inc');
if ($dh = @opendir($INSTALL_PATH.'program/localization'))
{
while (($name = readdir($dh)) !== false)
{
if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
continue;
if ($label = $rcube_languages[$name])
$sa_languages[$name] = $label ? $label : $name;
}
closedir($dh);
}
}
return $sa_languages;
}
// add a localized label to the client environment
function rcube_add_label()
{
global $OUTPUT, $JS_OBJECT_NAME;
$arg_list = func_get_args();
foreach ($arg_list as $i => $name)
$OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
$JS_OBJECT_NAME,
$name,
rep_specialchars_output(rcube_label($name), 'js')));
}
// remove temp files of a session
function rcmail_clear_session_temp($sess_id)
{
global $CONFIG;
$temp_dir = slashify($CONFIG['temp_dir']);
$cache_dir = $temp_dir.$sess_id;
if (is_dir($cache_dir))
{
clear_directory($cache_dir);
rmdir($cache_dir);
}
}
// remove all expired message cache records
function rcmail_message_cache_gc()
{
global $DB, $CONFIG;
// no cache lifetime configured
if (empty($CONFIG['message_cache_lifetime']))
return;
// get target timestamp
$ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
$DB->query("DELETE FROM ".get_table_name('messages')."
WHERE created < ".$DB->fromunixtime($ts));
}
// convert a string from one charset to another
// this function is not complete and not tested well
function rcube_charset_convert($str, $from, $to=NULL)
{
global $MBSTRING, $MBSTRING_ENCODING;
$from = strtoupper($from);
$to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
if ($from==$to)
return $str;
// convert charset using mbstring module
if ($MBSTRING)
{
$to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
$from = $from=="UTF-7" ? "UTF7-IMAP": $from;
if (in_array($to, $MBSTRING_ENCODING) && in_array($from, $MBSTRING_ENCODING))
return mb_convert_encoding($str, $to, $from);
}
// convert charset using iconv module
if (function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7')
return iconv($from, $to, $str);
$conv = new utf8();
// convert string to UTF-8
if ($from=='UTF-7')
$str = rcube_charset_convert(UTF7DecodeString($str), 'ISO-8859-1');
else if ($from=='ISO-8859-1' && function_exists('utf8_encode'))
$str = utf8_encode($str);
else if ($from!='UTF-8')
{
$conv->loadCharset($from);
$str = $conv->strToUtf8($str);
}
// encode string for output
if ($to=='UTF-7')
return UTF7EncodeString($str);
else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
return utf8_decode($str);
else if ($to!='UTF-8')
{
$conv->loadCharset($to);
return $conv->utf8ToStr($str);
}
// return UTF-8 string
return $str;
}
// replace specials characters to a specific encoding type
function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
{
global $OUTPUT_TYPE, $OUTPUT;
static $html_encode_arr, $js_rep_table, $rtf_rep_table, $xml_rep_table;
if (!$enctype)
$enctype = $GLOBALS['OUTPUT_TYPE'];
// convert nbsps back to normal spaces if not html
if ($enctype!='html')
$str = str_replace(chr(160), ' ', $str);
// encode for plaintext
if ($enctype=='text')
return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
// encode for HTML output
if ($enctype=='html')
{
if (!$html_encode_arr)
{
$html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
unset($html_encode_arr['?']);
unset($html_encode_arr['&']);
}
$ltpos = strpos($str, '<');
$encode_arr = $html_encode_arr;
// don't replace quotes and html tags
if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
{
unset($encode_arr['"']);
unset($encode_arr['<']);
unset($encode_arr['>']);
}
else if ($mode=='remove')
$str = strip_tags($str);
$out = strtr($str, $encode_arr);
return $newlines ? nl2br($out) : $out;
}
if ($enctype=='url')
return rawurlencode($str);
// if the replace tables for RTF, XML and JS are not yet defined
if (!$js_rep_table)
{
$js_rep_table = $rtf_rep_table = $xml_rep_table = array();
$xml_rep_table['&'] = '&';
for ($c=160; $c<256; $c++) // can be increased to support more charsets
{
$hex = dechex($c);
$rtf_rep_table[Chr($c)] = "\\'$hex";
$xml_rep_table[Chr($c)] = "&#$c;";
if ($OUTPUT->get_charset()=='ISO-8859-1')
$js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
}
$js_rep_table['"'] = sprintf("\u%s%s", str_repeat('0', 4-strlen(dechex(34))), dechex(34));
$xml_rep_table['"'] = '"';
}
// encode for RTF
if ($enctype=='xml')
return strtr($str, $xml_rep_table);
// encode for javascript use
if ($enctype=='js')
{
if ($OUTPUT->get_charset()!='UTF-8')
$str = rcube_charset_convert($str, $GLOBALS['CHARSET'], $OUTPUT->get_charset());
return preg_replace(array("/\r\n/", '/"/', "/([^\\\])'/"), array('\n', '\"', "$1\'"), strtr($str, $js_rep_table));
}
// encode for RTF
if ($enctype=='rtf')
return preg_replace("/\r\n/", "\par ", strtr($str, $rtf_rep_table));
// no encoding given -> return original string
return $str;
}
/**
* Read input value and convert it for internal use
* Performs stripslashes() and charset conversion if necessary
*
* @param string Field name to read
* @param int Source to get value from (GPC)
* @param boolean Allow HTML tags in field value
* @param string Charset to convert into
* @return string Field value or NULL if not available
*/
function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
{
global $OUTPUT;
$value = NULL;
if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
$value = $_GET[$fname];
else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
$value = $_POST[$fname];
else if ($source==RCUBE_INPUT_GPC)
{
if (isset($_POST[$fname]))
$value = $_POST[$fname];
else if (isset($_GET[$fname]))
$value = $_GET[$fname];
else if (isset($_COOKIE[$fname]))
$value = $_COOKIE[$fname];
}
// strip slashes if magic_quotes enabled
if ((bool)get_magic_quotes_gpc())
$value = stripslashes($value);
// remove HTML tags if not allowed
if (!$allow_html)
$value = strip_tags($value);
// convert to internal charset
if (is_object($OUTPUT))
return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
else
return $value;
}
// ************** template parsing and gui functions **************
// return boolean if a specific template exists
function template_exists($name)
{
global $CONFIG, $OUTPUT;
$skin_path = $CONFIG['skin_path'];
// check template file
return is_file("$skin_path/templates/$name.html");
}
// get page template an replace variable
// similar function as used in nexImage
function parse_template($name='main', $exit=TRUE)
{
global $CONFIG, $OUTPUT;
$skin_path = $CONFIG['skin_path'];
// read template file
$templ = '';
$path = "$skin_path/templates/$name.html";
if($fp = @fopen($path, 'r'))
{
$templ = fread($fp, filesize($path));
fclose($fp);
}
else
{
raise_error(array('code' => 500,
'type' => 'php',
'line' => __LINE__,
'file' => __FILE__,
'message' => "Error loading template for '$name'"), TRUE, TRUE);
return FALSE;
}
// parse for specialtags
$output = parse_rcube_xml($templ);
$OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
if ($exit)
exit;
}
// replace all strings ($varname) with the content of the according global variable
function parse_with_globals($input)
{
$GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
$output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
return $output;
}
function parse_rcube_xml($input)
{
$output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
return $output;
}
function rcube_xml_command($command, $str_attrib, $a_attrib=NULL)
{
global $IMAP, $CONFIG, $OUTPUT;
$attrib = array();
$command = strtolower($command);
preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str_attrib), $regs, PREG_SET_ORDER);
// convert attributes to an associative array (name => value)
if ($regs)
foreach ($regs as $attr)
$attrib[strtolower($attr[1])] = $attr[2];
else if ($a_attrib)
$attrib = $a_attrib;
// execute command
switch ($command)
{
// return a button
case 'button':
if ($attrib['command'])
return rcube_button($attrib);
break;
// show a label
case 'label':
if ($attrib['name'] || $attrib['command'])
return rep_specialchars_output(rcube_label($attrib));
break;
// create a menu item
case 'menu':
if ($attrib['command'] && $attrib['group'])
rcube_menu($attrib);
break;
// include a file
case 'include':
$path = realpath($CONFIG['skin_path'].$attrib['file']);
if($fp = @fopen($path, 'r'))
{
$incl = fread($fp, filesize($path));
fclose($fp);
return parse_rcube_xml($incl);
}
break;
// return code for a specific application object
case 'object':
$object = strtolower($attrib['name']);
$object_handlers = array(
// GENERAL
'loginform' => 'rcmail_login_form',
'username' => 'rcmail_current_username',
// MAIL
'mailboxlist' => 'rcmail_mailbox_list',
'message' => 'rcmail_message_container',
'messages' => 'rcmail_message_list',
'messagecountdisplay' => 'rcmail_messagecount_display',
'quotadisplay' => 'rcmail_quota_display',
'messageheaders' => 'rcmail_message_headers',
'messagebody' => 'rcmail_message_body',
'messageattachments' => 'rcmail_message_attachments',
'blockedobjects' => 'rcmail_remote_objects_msg',
'messagecontentframe' => 'rcmail_messagecontent_frame',
'messagepartframe' => 'rcmail_message_part_frame',
'messagepartcontrols' => 'rcmail_message_part_controls',
'composeheaders' => 'rcmail_compose_headers',
'composesubject' => 'rcmail_compose_subject',
'composebody' => 'rcmail_compose_body',
'composeattachmentlist' => 'rcmail_compose_attachment_list',
'composeattachmentform' => 'rcmail_compose_attachment_form',
'composeattachment' => 'rcmail_compose_attachment_field',
'priorityselector' => 'rcmail_priority_selector',
'charsetselector' => 'rcmail_charset_selector',
'searchform' => 'rcmail_search_form',
'receiptcheckbox' => 'rcmail_receipt_checkbox',
// ADDRESS BOOK
'addresslist' => 'rcmail_contacts_list',
'addressframe' => 'rcmail_contact_frame',
'recordscountdisplay' => 'rcmail_rowcount_display',
'contactdetails' => 'rcmail_contact_details',
'contacteditform' => 'rcmail_contact_editform',
'ldappublicsearch' => 'rcmail_ldap_public_search_form',
'ldappublicaddresslist' => 'rcmail_ldap_public_list',
// USER SETTINGS
'userprefs' => 'rcmail_user_prefs_form',
'itentitieslist' => 'rcmail_identities_list',
'identityframe' => 'rcmail_identity_frame',
'identityform' => 'rcube_identity_form',
'foldersubscription' => 'rcube_subscription_form',
'createfolder' => 'rcube_create_folder_form',
'renamefolder' => 'rcube_rename_folder_form',
'composebody' => 'rcmail_compose_body'
);
// execute object handler function
if ($object_handlers[$object] && function_exists($object_handlers[$object]))
return call_user_func($object_handlers[$object], $attrib);
else if ($object=='productname')
{
$name = !empty($CONFIG['product_name']) ? $CONFIG['product_name'] : 'RoundCube Webmail';
return rep_specialchars_output($name, 'html', 'all');
}
else if ($object=='version')
{
return (string)RCMAIL_VERSION;
}
else if ($object=='pagetitle')
{
$task = $GLOBALS['_task'];
$title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
if ($task=='login')
$title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $CONFIG['product_name'])));
else if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
$title .= $GLOBALS['MESSAGE']['subject'];
else if (isset($GLOBALS['PAGE_TITLE']))
$title .= $GLOBALS['PAGE_TITLE'];
else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
$title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
else
$title .= ucfirst($task);
return rep_specialchars_output($title, 'html', 'all');
}
break;
}
return '';
}
// create and register a button
function rcube_button($attrib)
{
global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER, $COMM_PATH, $MAIN_TASKS;
static $sa_buttons = array();
static $s_button_count = 100;
+ // these commands can be called directly via url
+ $a_static_commands = array('compose', 'list');
+
$skin_path = $CONFIG['skin_path'];
if (!($attrib['command'] || $attrib['name']))
return '';
// try to find out the button type
if ($attrib['type'])
$attrib['type'] = strtolower($attrib['type']);
else
$attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imageact']) ? 'image' : 'link';
$command = $attrib['command'];
// take the button from the stack
if($attrib['name'] && $sa_buttons[$attrib['name']])
$attrib = $sa_buttons[$attrib['name']];
// add button to button stack
else if($attrib['image'] || $arg['imageact'] || $attrib['imagepas'] || $attrib['class'])
{
if(!$attrib['name'])
$attrib['name'] = $command;
if (!$attrib['image'])
$attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
$sa_buttons[$attrib['name']] = $attrib;
}
// get saved button for this command/name
else if ($command && $sa_buttons[$command])
$attrib = $sa_buttons[$command];
//else
// return '';
// set border to 0 because of the link arround the button
if ($attrib['type']=='image' && !isset($attrib['border']))
$attrib['border'] = 0;
if (!$attrib['id'])
$attrib['id'] = sprintf('rcmbtn%d', $s_button_count++);
// get localized text for labels and titles
if ($attrib['title'])
$attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
if ($attrib['label'])
$attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
if ($attrib['alt'])
$attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
// set title to alt attribute for IE browsers
if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
{
$attrib['alt'] = $attrib['title'];
unset($attrib['title']);
}
// add empty alt attribute for XHTML compatibility
if (!isset($attrib['alt']))
$attrib['alt'] = '';
// register button in the system
if ($attrib['command'])
{
$OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
$JS_OBJECT_NAME,
$command,
$attrib['id'],
$attrib['type'],
$attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
$attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
$attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
- // make valid href to task buttons
+ // make valid href to specific buttons
if (in_array($attrib['command'], $MAIN_TASKS))
- $attrib['href'] = ereg_replace('_task=[a-z]+', '_task='.$attrib['command'], $COMM_PATH);
+ $attrib['href'] = htmlentities(ereg_replace('_task=[a-z]+', '_task='.$attrib['command'], $COMM_PATH));
+ else if (in_array($attrib['command'], $a_static_commands))
+ $attrib['href'] = htmlentities($COMM_PATH.'&_action='.$attrib['command']);
}
// overwrite attributes
if (!$attrib['href'])
$attrib['href'] = '#';
if ($command)
$attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
if ($command && $attrib['imageover'])
{
$attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
$attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
}
if ($command && $attrib['imagesel'])
{
$attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
$attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
}
$out = '';
// generate image tag
if ($attrib['type']=='image')
{
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
$img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
$btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
if ($attrib['label'])
$btn_content .= ' '.$attrib['label'];
$link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
}
else if ($attrib['type']=='link')
{
$btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
$link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
}
else if ($attrib['type']=='input')
{
$attrib['type'] = 'button';
if ($attrib['label'])
$attrib['value'] = $attrib['label'];
$attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
$out = sprintf('<input%s disabled />', $attrib_str);
}
// generate html code for button
if ($btn_content)
{
$attrib_str = create_attrib_string($attrib, $link_attrib);
$out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
}
return $out;
}
function rcube_menu($attrib)
{
return '';
}
function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
{
global $DB;
// allow the following attributes to be added to the <table> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
$table = '<table' . $attrib_str . ">\n";
// add table title
$table .= "<thead><tr>\n";
foreach ($a_show_cols as $col)
$table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
$table .= "</tr></thead>\n<tbody>\n";
$c = 0;
if (!is_array($table_data))
{
while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
{
$zebra_class = $c%2 ? 'even' : 'odd';
$table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
// format each col
foreach ($a_show_cols as $col)
{
$cont = rep_specialchars_output($sql_arr[$col]);
$table .= '<td class="'.$col.'">' . $cont . "</td>\n";
}
$table .= "</tr>\n";
$c++;
}
}
else
{
foreach ($table_data as $row_data)
{
$zebra_class = $c%2 ? 'even' : 'odd';
$table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
// format each col
foreach ($a_show_cols as $col)
{
$cont = rep_specialchars_output($row_data[$col]);
$table .= '<td class="'.$col.'">' . $cont . "</td>\n";
}
$table .= "</tr>\n";
$c++;
}
}
// complete message table
$table .= "</tbody></table>\n";
return $table;
}
function rcmail_get_edit_field($col, $value, $attrib, $type='text')
{
$fname = '_'.$col;
$attrib['name'] = $fname;
if ($type=='checkbox')
{
$attrib['value'] = '1';
$input = new checkbox($attrib);
}
else if ($type=='textarea')
{
$attrib['cols'] = $attrib['size'];
$input = new textarea($attrib);
}
else
$input = new textfield($attrib);
// use value from post
if (!empty($_POST[$fname]))
$value = $_POST[$fname];
$out = $input->show($value);
return $out;
}
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, $attrib[$a]);
return $attrib_str;
}
function format_date($date, $format=NULL)
{
global $CONFIG, $sess_user_lang;
$ts = NULL;
if (is_numeric($date))
$ts = $date;
else if (!empty($date))
$ts = @strtotime($date);
if (empty($ts))
return '';
// get user's timezone
$tz = $CONFIG['timezone'];
if ($CONFIG['dst_active'])
$tz++;
// convert time to user's timezone
$timestamp = $ts - date('Z', $ts) + ($tz * 3600);
// get current timestamp in user's timezone
$now = time(); // local time
$now -= (int)date('Z'); // make GMT time
$now += ($tz * 3600); // user's time
$now_date = getdate();
$today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
$week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
// define date format depending on current time
if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
$format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
else if (!$format)
$format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
// parse format string manually in order to provide localized weekday and month names
// an alternative would be to convert the date() format string to fit with strftime()
$out = '';
for($i=0; $i<strlen($format); $i++)
{
if ($format{$i}=='\\') // skip escape chars
continue;
// write char "as-is"
if ($format{$i}==' ' || $format{$i-1}=='\\')
$out .= $format{$i};
// weekday (short)
else if ($format{$i}=='D')
$out .= rcube_label(strtolower(date('D', $timestamp)));
// weekday long
else if ($format{$i}=='l')
$out .= rcube_label(strtolower(date('l', $timestamp)));
// month name (short)
else if ($format{$i}=='M')
$out .= rcube_label(strtolower(date('M', $timestamp)));
// month name (long)
else if ($format{$i}=='F')
$out .= rcube_label(strtolower(date('F', $timestamp)));
else
$out .= date($format{$i}, $timestamp);
}
return $out;
}
// ************** functions delivering gui objects **************
function rcmail_message_container($attrib)
{
global $OUTPUT, $JS_OBJECT_NAME;
if (!$attrib['id'])
$attrib['id'] = 'rcmMessageContainer';
// allow the following attributes to be added to the <table> tag
$attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
$out = '<div' . $attrib_str . "></div>";
$OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
return $out;
}
// return the IMAP username of the current session
function rcmail_current_username($attrib)
{
global $DB;
static $s_username;
// alread fetched
if (!empty($s_username))
return $s_username;
// get e-mail address form default identity
$sql_result = $DB->query("SELECT email AS mailto
FROM ".get_table_name('identities')."
WHERE user_id=?
AND standard=1
AND del<>1",
$_SESSION['user_id']);
if ($DB->num_rows($sql_result))
{
$sql_arr = $DB->fetch_assoc($sql_result);
$s_username = $sql_arr['mailto'];
}
else if (strstr($_SESSION['username'], '@'))
$s_username = $_SESSION['username'];
else
$s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
return $s_username;
}
// return code for the webmail login form
function rcmail_login_form($attrib)
{
global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
$labels = array();
$labels['user'] = rcube_label('username');
$labels['pass'] = rcube_label('password');
$labels['host'] = rcube_label('server');
$input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30));
$input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
$input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
$fields = array();
$fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
$fields['pass'] = $input_pass->show();
$fields['action'] = $input_action->show();
if (is_array($CONFIG['default_host']))
{
$select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
foreach ($CONFIG['default_host'] as $key => $value)
$select_host->add($value, (is_numeric($key) ? $value : $key));
$fields['host'] = $select_host->show($_POST['_host']);
}
else if (!strlen($CONFIG['default_host']))
{
$input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
$fields['host'] = $input_host->show($_POST['_host']);
}
$form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
$form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
$form_end = !strlen($attrib['form']) ? '</form>' : '';
if ($fields['host'])
$form_host = <<<EOF
</tr><tr>
<td class="title"><label for="rcmloginhost">$labels[host]</label></td>
<td>$fields[host]</td>
EOF;
$OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
$out = <<<EOF
$form_start
$SESS_HIDDEN_FIELD
$fields[action]
<table><tr>
<td class="title"><label for="rcmloginuser">$labels[user]</label></td>
<td>$fields[user]</td>
</tr><tr>
<td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
<td>$fields[pass]</td>
$form_host
</tr></table>
$form_end
EOF;
return $out;
}
function rcmail_charset_selector($attrib)
{
global $OUTPUT;
// pass the following attributes to the form class
$field_attrib = array('name' => '_charset');
foreach ($attrib as $attr => $value)
if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
$field_attrib[$attr] = $value;
$charsets = array(
'US-ASCII' => 'ASCII (English)',
'EUC-JP' => 'EUC-JP (Japanese)',
'EUC-KR' => 'EUC-KR (Korean)',
'BIG5' => 'BIG5 (Chinese)',
'GB2312' => 'GB2312 (Chinese)',
'ISO-2022-JP' => 'ISO-2022-JP (Japanese)',
'ISO-8859-1' => 'ISO-8859-1 (Latin-1)',
'ISO-8859-2' => 'ISO-8895-2 (Central European)',
'ISO-8859-7' => 'ISO-8859-7 (Greek)',
'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
'Windows-1251' => 'Windows-1251 (Cyrillic)',
'Windows-1252' => 'Windows-1252 (Western)',
'Windows-1255' => 'Windows-1255 (Hebrew)',
'Windows-1256' => 'Windows-1256 (Arabic)',
'Windows-1257' => 'Windows-1257 (Baltic)',
'UTF-8' => 'UTF-8'
);
$select = new select($field_attrib);
$select->add(array_values($charsets), array_keys($charsets));
$set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
return $select->show($set);
}
/****** debugging function ********/
function rcube_timer()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function rcube_print_time($timer, $label='Timer')
{
static $print_count = 0;
$print_count++;
$now = rcube_timer();
$diff = $now-$timer;
if (empty($label))
$label = 'Timer '.$print_count;
console(sprintf("%s: %0.4f sec", $label, $diff));
}
?>
diff --git a/program/include/rcube_imap.inc b/program/include/rcube_imap.inc
index bc12eac06..177d05a62 100644
--- a/program/include/rcube_imap.inc
+++ b/program/include/rcube_imap.inc
@@ -1,2134 +1,2116 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/include/rcube_imap.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, 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');
require_once('lib/utf7.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.26
* @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', 'drafts', 'sent', 'junk', 'trash');
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 $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 account namespace
if ($this->conn)
{
$this->_parse_capability($this->conn->capability);
iil_C_NameSpace($this->conn);
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 = array();
// add mailbox names lower case
foreach ($arr as $mbox_row)
$this->default_folders[] = strtolower($mbox_row);
// add inbox if not included
if (!in_array('inbox', $this->default_folders))
array_unshift($arr, 'inbox');
}
}
/**
* 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;
}
/**
* 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;
}
// 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();
// create Default folders if they do not exist
global $CONFIG;
foreach ($CONFIG['default_imap_folders'] as $folder)
{
if (!in_array_nocase($folder, $a_folders))
{
$this->create_mailbox($folder, TRUE);
$this->subscribe($folder);
}
}
$a_folders = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox($root), $filter);
$a_mailbox_cache = 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;
$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();
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);
-
- /*
- if ($page=='all')
- {
- $begin = 0;
- $end = $max;
- }
- else if (!$this->get_capability('sort') && $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;
- */
-
+
+ // mailbox is empty
+ if ($begin >= $end)
+ return array();
+
//console("fetch headers $start_msg to ".($start_msg+$this->page_size)." (msg $begin to $end)");
$headers_sorted = FALSE;
$cache_key = $mailbox.'.msg';
$cache_status = $this->check_cache_status($mailbox, $cache_key);
//console("Cache status = $cache_status");
// 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;
}
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' : '')))
{
//console("$mailbox: ".join(',', $msg_index));
$msgs = $msg_index[$begin];
for ($i=$begin+1; $i < $end; $i++)
$msgs = $msgs.','.$msg_index[$i];
$sorted = TRUE;
}
else
{
- $msgs = sprintf("%d:%d", $begin+1, $end);
+ $msgs = sprintf("%d:%d", $begin+1, $end);
$sorted = FALSE;
}
// cache is dirty, sync it
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);
}
// 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
$this->clear_message_cache($cache_key, $max);
// 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)
// $a_msg_headers = iil_SortHeaders($a_msg_headers, $this->sort_field, $this->sort_order);
if (!$headers_sorted && $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
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)
{
// console("$id / $uid: OK");
unset($cache_index[$id]);
continue;
}
// message in cache but in wrong position
if (in_array((string)$uid, $cache_index, TRUE))
{
// console("$id / $uid: Moved");
unset($cache_index[$id]);
}
// other message at this position
if (isset($cache_index[$id]))
{
// console("$id / $uid: Delete");
$this->remove_message_cache($cache_key, $id);
unset($cache_index[$id]);
}
// console("$id / $uid: Add");
// 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)
{
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
if ($str && $criteria)
{
$criteria = 'CHARSET UTF-8 '.$criteria.' "'.UTF7EncodeString($str).'"';
return $this->_search_index($mailbox, $criteria);
}
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;
}
function get_headers($id, $mbox_name=NULL, $is_uid=TRUE)
{
$mailbox = $mbox_name ? $this->_mod_mailbox($mbox_name) : $this->mailbox;
// get cached headers
if ($is_uid && ($headers = $this->get_cached_message($mailbox.'.msg', $id)))
return $headers;
$msg_id = $is_uid ? $this->_uid2id($id) : $id;
$headers = iil_C_FetchHeader($this->conn, $mailbox, $msg_id);
// write headers cache
if ($headers)
$this->add_message_cache($mailbox.'.msg', $msg_id, $headers);
return $headers;
}
function get_body($uid, $part=1)
{
if (!($msg_id = $this->_uid2id($uid)))
return FALSE;
$structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
$structure = iml_GetRawStructureArray($structure_str);
$body = iil_C_FetchPartBody($this->conn, $this->mailbox, $msg_id, $part);
$encoding = iml_GetPartEncodingCode($structure, $part);
if ($encoding==3) $body = $this->mime_decode($body, 'base64');
else if ($encoding==4) $body = $this->mime_decode($body, 'quoted-printable');
return $body;
}
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;
}
// set message flag to one or several messages
// possible flags are: SEEN, UNDELETED, DELETED, RECENT, ANSWERED, DRAFT
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);
$moved = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
// 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);
}
// 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 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)
{
$index = array_search($uid, $a_cache_index);
$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
* --------------------------------*/
// return an array with all folders available in IMAP server
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'))
{
$result = iil_C_GetQuota($this->conn);
if ($result["total"])
return sprintf("%.2fMB / %.2fMB (%.0f%%)", $result["used"] / 1000.0, $result["total"] / 1000.0, $result["percent"]);
}
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
function create_mailbox($name, $subscribe=FALSE)
{
$result = FALSE;
// replace backslashes
$name = preg_replace('/[\\\]+/', '-', $name);
$name_enc = UTF7EncodeString($name);
// reduce mailbox name to 100 chars
$name_enc = substr($name_enc, 0, 100);
$abs_name = $this->_mod_mailbox($name_enc);
$a_mailbox_cache = $this->get_cache('mailboxes');
if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
$result = iil_C_CreateFolder($this->conn, $abs_name);
// update mailboxlist cache
if ($result && $subscribe)
$this->subscribe($name_enc);
return $result ? $name : FALSE;
}
// set a new name to an existing mailbox
function rename_mailbox($mbox_name, $new_name, $subscribe=TRUE)
{
$result = FALSE;
// replace backslashes
$name = preg_replace('/[\\\]+/', '-', $new_name);
$name_enc = UTF7EncodeString($new_name);
// reduce mailbox name to 100 chars
$name_enc = substr($name_enc, 0, 100);
$abs_name = $this->_mod_mailbox($name_enc);
$a_mailbox_cache = $this->get_cache('mailboxes');
if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
$result = iil_C_RenameFolder($this->conn, $mbox_name, $abs_name);
// update mailboxlist cache
if ($result && $subscribe)
$this->unsubscribe($mbox_name);
$this->subscribe($name_enc);
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;
}
/* --------------------------------
* 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=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 (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, $body=FALSE)
{
if (!$this->caching_enabled)
return FALSE;
$internal_key = '__single_msg';
if ($this->caching_enabled && (!isset($this->cache[$internal_key][$uid]) || $body))
{
$sql_select = "idx, uid, headers";
if ($body)
$sql_select .= ", body";
$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))
{
$headers = unserialize($sql_arr['headers']);
if (is_object($headers) && !empty($sql_arr['body']))
$headers->body = $sql_arr['body'];
$this->cache[$internal_key][$uid] = $headers;
}
}
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)
{
if (!$key || !is_object($headers) || empty($headers->uid))
return;
$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)
VALUES (?, 0, ?, 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));
}
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)
{
$a = $this->_parse_address_list($input);
$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']));
$string = $name!==$address ? sprintf('%s <%s>', strpos($name, ',')!==FALSE ? '"'.$name.'"' : $name, $address) : $address;
$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)
{
$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);
return $out;
}
// no encoding information, defaults to what is specified in the class header
return rcube_charset_convert($input, '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($this->root_ns) && $this->root_ns == $mbox_name) || ($mbox_name == 'INBOX' && $mode == 'in'))
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))!==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, $mbox_name);
}
function get_uid($id,$mbox_name=NULL)
{
return $this->_id2uid($id, $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);
}
}
function _parse_address_list($str)
{
$a = $this->_explode_quoted_string(',', $str);
$result = array();
foreach ($a as $key => $val)
{
$val = str_replace("\"<", "\" <", $val);
$sub_a = $this->_explode_quoted_string(' ', $val);
foreach ($sub_a as $k => $v)
{
if ((strpos($v, '@') > 0) && (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'];
$result[$key]['name'] = $this->decode_header($result[$key]['name']);
}
return $result;
}
function _explode_quoted_string($delimiter, $string)
{
$quotes = explode("\"", $string);
foreach ($quotes as $key => $val)
if (($key % 2) == 1)
$quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
$string = implode("\"", $quotes);
$result = explode($delimiter, $string);
foreach ($result as $key => $val)
$result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
return $result;
}
}
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/lib/imap.inc b/program/lib/imap.inc
index b8f3dea39..70abdc40e 100644
--- a/program/lib/imap.inc
+++ b/program/lib/imap.inc
@@ -1,2110 +1,2110 @@
<?php
/////////////////////////////////////////////////////////
//
// Iloha IMAP Library (IIL)
//
// (C)Copyright 2002 Ryo Chijiiwa <Ryo@IlohaMail.org>
//
// This file is part of IlohaMail. IlohaMail is free software released
// under the GPL license. See enclosed file COPYING for details, or
// see http://www.fsf.org/copyleft/gpl.html
//
/////////////////////////////////////////////////////////
/********************************************************
FILE: include/imap.inc
PURPOSE:
Provide alternative IMAP library that doesn't rely on the standard
C-Client based version. This allows IlohaMail to function regardless
of whether or not the PHP build it's running on has IMAP functionality
built-in.
USEAGE:
Function containing "_C_" in name require connection handler to be
passed as one of the parameters. To obtain connection handler, use
iil_Connect()
VERSION:
IlohaMail-0.9-20050415
CHANGES:
File altered by Thomas Bruederli <roundcube@gmail.com>
to fit enhanced equirements by the RoundCube Webmail:
- Added list of server capabilites and check these before invoking commands
- Added junk flag to iilBasicHeader
- Enhanced error reporting on fsockopen()
- Additional parameter for SORT command
- Removed Call-time pass-by-reference because deprecated
- Parse charset from content-type in iil_C_FetchHeaders()
- Enhanced heaer sorting
- Pass message as reference in iil_C_Append (to save memory)
- Added BCC and REFERENCE to the list of headers to fetch in iil_C_FetchHeaders()
- Leave messageID unchanged in iil_C_FetchHeaders()
- Avoid stripslahes in iil_Connect()
- Added patch to iil_SortHeaders() by Richard Green
- Removed <br> from error messages (better for logging)
- Added patch to iil_C_Sort() enabling UID SORT commands
- Added function iil_C_ID2UID()
- Casting date parts in iil_StrToTime() to avoid mktime() warnings
- Removed some debuggers (echo ...)
********************************************************/
// changed path to work within roundcube webmail
include_once("lib/icl_commons.inc");
if (!$IMAP_USE_HEADER_DATE) $IMAP_USE_INTERNAL_DATE = true;
$IMAP_MONTHS=array("Jan"=>1,"Feb"=>2,"Mar"=>3,"Apr"=>4,"May"=>5,"Jun"=>6,"Jul"=>7,"Aug"=>8,"Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12);
$IMAP_SERVER_TZ = date('Z');
$iil_error;
$iil_errornum;
$iil_selected;
class iilConnection{
var $fp;
var $error;
var $errorNum;
var $selected;
var $message;
var $host;
var $cache;
var $uid_cache;
var $do_cache;
var $exists;
var $recent;
var $rootdir;
var $delimiter;
var $capability = array();
}
class iilBasicHeader{
var $id;
var $uid;
var $subject;
var $from;
var $to;
var $cc;
var $replyto;
var $in_reply_to;
var $date;
var $messageID;
var $size;
var $encoding;
var $ctype;
var $flags;
var $timestamp;
var $f;
var $seen;
var $deleted;
var $recent;
var $answered;
var $junk;
var $internaldate;
var $is_reply;
}
class iilThreadHeader{
var $id;
var $sbj;
var $irt;
var $mid;
}
function iil_xor($string, $string2){
$result = "";
$size = strlen($string);
for ($i=0; $i<$size; $i++) $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
return $result;
}
function iil_ReadLine($fp, $size){
$line="";
if ($fp){
do{
$buffer = fgets($fp, 2048);
$line.=$buffer;
}while($buffer[strlen($buffer)-1]!="\n");
}
return $line;
}
function iil_MultLine($fp, $line){
$line = chop($line);
if (ereg('\{[0-9]+\}$', $line)){
$out = "";
preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
$bytes = $a[2][0];
while(strlen($out)<$bytes){
$out.=chop(iil_ReadLine($fp, 1024));
}
$line = $a[1][0]."\"$out\"";
}
return $line;
}
function iil_ReadBytes($fp, $bytes){
$data = "";
$len = 0;
do{
$data.=fread($fp, $bytes-$len);
$len = strlen($data);
}while($len<$bytes);
return $data;
}
function iil_ReadReply($fp){
do{
$line = chop(trim(iil_ReadLine($fp, 1024)));
}while($line[0]=="*");
return $line;
}
function iil_ParseResult($string){
$a=explode(" ", $string);
if (count($a) > 2){
if (strcasecmp($a[1], "OK")==0) return 0;
else if (strcasecmp($a[1], "NO")==0) return -1;
else if (strcasecmp($a[1], "BAD")==0) return -2;
}else return -3;
}
// check if $string starts with $match
function iil_StartsWith($string, $match){
$len = strlen($match);
if ($len==0) return false;
if (strncmp($string, $match, $len)==0) return true;
else return false;
}
function iil_StartsWithI($string, $match){
$len = strlen($match);
if ($len==0) return false;
if (strncasecmp($string, $match, $len)==0) return true;
else return false;
}
function iil_C_Authenticate(&$conn, $user, $pass, $encChallenge){
// initialize ipad, opad
for ($i=0;$i<64;$i++){
$ipad.=chr(0x36);
$opad.=chr(0x5C);
}
// pad $pass so it's 64 bytes
$padLen = 64 - strlen($pass);
for ($i=0;$i<$padLen;$i++) $pass .= chr(0);
// generate hash
$hash = md5(iil_xor($pass,$opad).pack("H*",md5(iil_xor($pass, $ipad).base64_decode($encChallenge))));
// generate reply
$reply = base64_encode($user." ".$hash);
// send result, get reply
fputs($conn->fp, $reply."\r\n");
$line = iil_ReadLine($conn->fp, 1024);
// process result
if (iil_ParseResult($line)==0){
$conn->error .= "";
$conn->errorNum = 0;
return $conn->fp;
}else{
$conn->error .= 'Authentication for '.$user.' failed (AUTH): "'.htmlspecialchars($line)."\"";
$conn->errorNum = -2;
return false;
}
}
function iil_C_Login(&$conn, $user, $password){
fputs($conn->fp, "a001 LOGIN $user \"$password\"\r\n");
do{
$line = iil_ReadReply($conn->fp);
}while(!iil_StartsWith($line, "a001 "));
$a=explode(" ", $line);
if (strcmp($a[1],"OK")==0){
$result=$conn->fp;
$conn->error.="";
$conn->errorNum = 0;
}else{
$result=false;
fclose($conn->fp);
$conn->error .= 'Authentication for '.$user.' failed (LOGIN): "'.htmlspecialchars($line)."\"";
$conn->errorNum = -2;
}
return $result;
}
function iil_ParseNamespace2($str, &$i, $len=0, $l){
if (!$l) $str = str_replace("NIL", "()", $str);
if (!$len) $len = strlen($str);
$data = array();
$in_quotes = false;
$elem = 0;
for($i;$i<$len;$i++){
$c = (string)$str[$i];
if ($c=='(' && !$in_quotes){
$i++;
$data[$elem] = iil_ParseNamespace2($str, $i, $len, $l++);
$elem++;
}else if ($c==')' && !$in_quotes) return $data;
else if ($c=="\\"){
$i++;
if ($in_quotes) $data[$elem].=$c.$str[$i];
}else if ($c=='"'){
$in_quotes = !$in_quotes;
if (!$in_quotes) $elem++;
}else if ($in_quotes){
$data[$elem].=$c;
}
}
return $data;
}
function iil_C_NameSpace(&$conn){
global $my_prefs;
if (!in_array('NAMESPACE', $conn->capability))
return false;
if ($my_prefs["rootdir"]) return true;
fputs($conn->fp, "ns1 NAMESPACE\r\n");
do{
$line = iil_ReadLine($conn->fp, 1024);
if (iil_StartsWith($line, "* NAMESPACE")){
$i = 0;
$data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
}
}while(!iil_StartsWith($line, "ns1"));
if (!is_array($data)) return false;
$user_space_data = $data[0];
if (!is_array($user_space_data)) return false;
$first_userspace = $user_space_data[0];
if (count($first_userspace)!=2) return false;
$conn->rootdir = $first_userspace[0];
$conn->delimiter = $first_userspace[1];
$my_prefs["rootdir"] = substr($conn->rootdir, 0, -1);
return true;
}
function iil_Connect($host, $user, $password){
global $iil_error, $iil_errornum;
global $ICL_SSL, $ICL_PORT;
global $IMAP_NO_CACHE;
global $my_prefs, $IMAP_USE_INTERNAL_DATE;
$iil_error = "";
$iil_errornum = 0;
//strip slashes
// $user = stripslashes($user);
// $password = stripslashes($password);
//set auth method
$auth_method = "plain";
if (func_num_args() >= 4){
$auth_array = func_get_arg(3);
if (is_array($auth_array)) $auth_method = $auth_array["imap"];
if (empty($auth_method)) $auth_method = "plain";
}
$message = "INITIAL: $auth_method\n";
$result = false;
//initialize connection
$conn = new iilConnection;
$conn->error="";
$conn->errorNum=0;
$conn->selected="";
$conn->user = $user;
$conn->host = $host;
$conn->cache = array();
$conn->do_cache = (function_exists("cache_write")&&!$IMAP_NO_CACHE);
$conn->cache_dirty = array();
if ($my_prefs['sort_field']=='INTERNALDATE') $IMAP_USE_INTERNAL_DATE = true;
else if ($my_prefs['sort_field']=='DATE') $IMAP_USE_INTERNAL_DATE = false;
//echo '<!-- conn sort_field: '.$my_prefs['sort_field'].' //-->';
//check input
if (empty($host)) $iil_error .= "Invalid host\n";
if (empty($user)) $iil_error .= "Invalid user\n";
if (empty($password)) $iil_error .= "Invalid password\n";
if (!empty($iil_error)) return false;
if (!$ICL_PORT) $ICL_PORT = 143;
//check for SSL
if ($ICL_SSL){
$host = "ssl://".$host;
}
//open socket connection
$conn->fp = @fsockopen($host, $ICL_PORT, $errno, $errstr, 10);
if (!$conn->fp){
$iil_error = "Could not connect to $host at port $ICL_PORT: $errstr";
$iil_errornum = -1;
return false;
}
$iil_error.="Socket connection established\r\n";
$line=iil_ReadLine($conn->fp, 300);
if (strcasecmp($auth_method, "check")==0){
//check for supported auth methods
//default to plain text auth
$auth_method = "plain";
//check for CRAM-MD5
fputs($conn->fp, "cp01 CAPABILITY\r\n");
do{
$line = trim(chop(iil_ReadLine($conn->fp, 100)));
$conn->message.="$line\n";
$a = explode(" ", $line);
if ($line[0]=="*"){
while ( list($k, $w) = each($a) ){
if ($w!='*' && $w!='CAPABILITY')
$conn->capability[] = $w;
if ((strcasecmp($w, "AUTH=CRAM_MD5")==0)||
(strcasecmp($w, "AUTH=CRAM-MD5")==0)){
$auth_method = "auth";
}
}
}
}while($a[0]!="cp01");
}
if (strcasecmp($auth_method, "auth")==0){
$conn->message.="Trying CRAM-MD5\n";
//do CRAM-MD5 authentication
fputs($conn->fp, "a000 AUTHENTICATE CRAM-MD5\r\n");
$line = trim(chop(iil_ReadLine($conn->fp, 1024)));
$conn->message.="$line\n";
if ($line[0]=="+"){
$conn->message.='Got challenge: '.htmlspecialchars($line)."\n";
//got a challenge string, try CRAM-5
$result = iil_C_Authenticate($conn, $user, $password, substr($line,2));
$conn->message.= "Tried CRAM-MD5: $result \n";
}else{
$conn->message.='No challenge ('.htmlspecialchars($line)."), try plain\n";
$auth = "plain";
}
}
if ((!$result)||(strcasecmp($auth, "plain")==0)){
//do plain text auth
$result = iil_C_Login($conn, $user, $password);
$conn->message.="Tried PLAIN: $result \n";
}
$conn->message .= $auth;
if ($result){
iil_C_Namespace($conn);
return $conn;
}else{
$iil_error = $conn->error;
$iil_errornum = $conn->errorNum;
return false;
}
}
function iil_Close(&$conn){
iil_C_WriteCache($conn);
if (@fputs($conn->fp, "I LOGOUT\r\n")){
fgets($conn->fp, 1024);
fclose($conn->fp);
$conn->fp = false;
}
}
function iil_ClearCache($user, $host){
}
function iil_C_WriteCache(&$conn){
//echo "<!-- doing iil_C_WriteCache //-->\n";
if (!$conn->do_cache) return false;
if (is_array($conn->cache)){
while(list($folder,$data)=each($conn->cache)){
if ($folder && is_array($data) && $conn->cache_dirty[$folder]){
$key = $folder.".imap";
$result = cache_write($conn->user, $conn->host, $key, $data, true);
//echo "<!-- writing $key $data: $result //-->\n";
}
}
}
}
function iil_C_EnableCache(&$conn){
$conn->do_cache = true;
}
function iil_C_DisableCache(&$conn){
$conn->do_cache = false;
}
function iil_C_LoadCache(&$conn, $folder){
if (!$conn->do_cache) return false;
$key = $folder.".imap";
if (!is_array($conn->cache[$folder])){
$conn->cache[$folder] = cache_read($conn->user, $conn->host, $key);
$conn->cache_dirty[$folder] = false;
}
}
function iil_C_ExpireCachedItems(&$conn, $folder, $message_set){
if (!$conn->do_cache) return; //caching disabled
if (!is_array($conn->cache[$folder])) return; //cache not initialized|empty
if (count($conn->cache[$folder])==0) return; //cache not initialized|empty
$uids = iil_C_FetchHeaderIndex($conn, $folder, $message_set, "UID");
$num_removed = 0;
if (is_array($uids)){
//echo "<!-- unsetting: ".implode(",",$uids)." //-->\n";
while(list($n,$uid)=each($uids)){
unset($conn->cache[$folder][$uid]);
//$conn->cache[$folder][$uid] = false;
//$num_removed++;
}
$conn->cache_dirty[$folder] = true;
//echo '<!--'."\n";
//print_r($conn->cache);
//echo "\n".'//-->'."\n";
}else{
echo "<!-- failed to get uids: $message_set //-->\n";
}
/*
if ($num_removed>0){
$new_cache;
reset($conn->cache[$folder]);
while(list($uid,$item)=each($conn->cache[$folder])){
if ($item) $new_cache[$uid] = $conn->cache[$folder][$uid];
}
$conn->cache[$folder] = $new_cache;
}
*/
}
function iil_ExplodeQuotedString($delimiter, $string){
$quotes=explode("\"", $string);
while ( list($key, $val) = each($quotes))
if (($key % 2) == 1)
$quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
$string=implode("\"", $quotes);
$result=explode($delimiter, $string);
while ( list($key, $val) = each($result) )
$result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
return $result;
}
function iil_CheckForRecent($host, $user, $password, $mailbox){
if (empty($mailbox)) $mailbox="INBOX";
$conn=iil_Connect($host, $user, $password, "plain");
$fp = $conn->fp;
if ($fp){
fputs($fp, "a002 EXAMINE \"$mailbox\"\r\n");
do{
$line=chop(iil_ReadLine($fp, 300));
$a=explode(" ", $line);
if (($a[0]=="*") && (strcasecmp($a[2], "RECENT")==0)) $result=(int)$a[1];
}while (!iil_StartsWith($a[0],"a002"));
fputs($fp, "a003 LOGOUT\r\n");
fclose($fp);
}else $result=-2;
return $result;
}
function iil_C_Select(&$conn, $mailbox){
$fp = $conn->fp;
if (empty($mailbox)) return false;
if (strcmp($conn->selected, $mailbox)==0) return true;
iil_C_LoadCache($conn, $mailbox);
if (fputs($fp, "sel1 SELECT \"$mailbox\"\r\n")){
do{
$line=chop(iil_ReadLine($fp, 300));
$a=explode(" ", $line);
if (count($a) == 3){
if (strcasecmp($a[2], "EXISTS")==0) $conn->exists=(int)$a[1];
if (strcasecmp($a[2], "RECENT")==0) $conn->recent=(int)$a[1];
}
}while (!iil_StartsWith($line, "sel1"));
$a=explode(" ", $line);
if (strcasecmp($a[1],"OK")==0){
$conn->selected = $mailbox;
return true;
}else return false;
}else{
return false;
}
}
function iil_C_CheckForRecent(&$conn, $mailbox){
if (empty($mailbox)) $mailbox="INBOX";
iil_C_Select($conn, $mailbox);
if ($conn->selected==$mailbox) return $conn->recent;
else return false;
}
function iil_C_CountMessages(&$conn, $mailbox, $refresh=false){
if ($refresh) $conn->selected="";
iil_C_Select($conn, $mailbox);
if ($conn->selected==$mailbox) return $conn->exists;
else return false;
}
function iil_SplitHeaderLine($string){
$pos=strpos($string, ":");
if ($pos>0){
$res[0]=substr($string, 0, $pos);
$res[1]=trim(substr($string, $pos+1));
return $res;
}else{
return $string;
}
}
function iil_StrToTime($str){
global $IMAP_MONTHS,$IMAP_SERVER_TZ;
if ($str) $time1 = strtotime($str);
if ($time1 && $time1!=-1) return $time1-$IMAP_SERVER_TZ;
//echo '<!--'.$str.'//-->';
//replace double spaces with single space
$str = trim($str);
$str = str_replace(" ", " ", $str);
//strip off day of week
$pos=strpos($str, " ");
if (!is_numeric(substr($str, 0, $pos))) $str = substr($str, $pos+1);
//explode, take good parts
$a=explode(" ",$str);
//$month_a=array("Jan"=>1,"Feb"=>2,"Mar"=>3,"Apr"=>4,"May"=>5,"Jun"=>6,"Jul"=>7,"Aug"=>8,"Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12);
$month_str=$a[1];
$month=$IMAP_MONTHS[$month_str];
$day=(int)$a[0];
$year=(int)$a[2];
$time=$a[3];
$tz_str = $a[4];
$tz = substr($tz_str, 0, 3);
$ta = explode(":",$time);
$hour=(int)$ta[0]-(int)$tz;
$minute=(int)$ta[1];
$second=(int)$ta[2];
//make UNIX timestamp
$time2 = mktime($hour, $minute, $second, $month, $day, $year);
//echo '<!--'.$time1.' '.$time2.' //-->'."\n";
return $time2;
}
function iil_C_Sort(&$conn, $mailbox, $field, $add='', $is_uid=FALSE, $encoding='US-ASCII'){
/* Do "SELECT" command */
if (!iil_C_Select($conn, $mailbox)) return false;
$field = strtoupper($field);
if ($field=='INTERNALDATE') $field='ARRIVAL';
$fields = array('ARRIVAL'=>1,'CC'=>1,'DATE'=>1,'FROM'=>1,'SIZE'=>1,'SUBJECT'=>1,'TO'=>1);
if (!$fields[$field])
return false;
$is_uid = $is_uid ? 'UID ' : '';
if (!empty($add))
$add = " $add";
$fp = $conn->fp;
$command = 's '. $is_uid .'SORT ('.$field.') '.$encoding.' ALL'."$add\r\n";
$line = $data = '';
if (!fputs($fp, $command)) return false;
do{
$line = chop(iil_ReadLine($fp, 1024));
if (iil_StartsWith($line, '* SORT')) $data.=($data?' ':'').substr($line,7);
}while($line[0]!='s');
if (empty($data)){
$conn->error = $line;
return false;
}
$out = explode(' ',$data);
return $out;
}
function iil_C_FetchHeaderIndex(&$conn, $mailbox, $message_set, $index_field, $normalize=true){
global $IMAP_USE_INTERNAL_DATE;
$c=0;
$result=array();
$fp = $conn->fp;
if (empty($index_field)) $index_field="DATE";
$index_field = strtoupper($index_field);
if ((empty($message_set)) || ($message_set == "1:0")) return array();
//$fields_a["DATE"] = ($IMAP_USE_INTERNAL_DATE?6:1);
$fields_a['DATE'] = 1;
$fields_a['INTERNALDATE'] = 6;
$fields_a['FROM'] = 1;
$fields_a['REPLY-TO'] = 1;
$fields_a['SENDER'] = 1;
$fields_a['TO'] = 1;
$fields_a['SUBJECT'] = 1;
$fields_a['UID'] = 2;
$fields_a['SIZE'] = 2;
$fields_a['SEEN'] = 3;
$fields_a['RECENT'] = 4;
$fields_a['DELETED'] = 5;
$mode=$fields_a[$index_field];
if (!($mode > 0)) return false;
/* Do "SELECT" command */
if (!iil_C_Select($conn, $mailbox)) return false;
/* FETCH date,from,subject headers */
if ($mode==1){
$key="fhi".($c++);
$request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)])\r\n";
if (!fputs($fp, $request)) return false;
do{
$line=chop(iil_ReadLine($fp, 200));
$a=explode(" ", $line);
if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[strlen($line)-1]!=")")){
$id=$a[1];
$str=$line=chop(iil_ReadLine($fp, 300));
while($line[0]!=")"){ //caution, this line works only in this particular case
$line=chop(iil_ReadLine($fp, 300));
if ($line[0]!=")"){
if (ord($line[0]) <= 32){ //continuation from previous header line
$str.=" ".trim($line);
}
if ((ord($line[0]) > 32) || (strlen($line[0]) == 0)){
list($field, $string) = iil_SplitHeaderLine($str);
if (strcasecmp($field, "date")==0){
$result[$id]=iil_StrToTime($string);
}else{
$result[$id] = str_replace("\"", "", $string);
if ($normalize) $result[$id]=strtoupper($result[$id]);
}
$str=$line;
}
}
}
}
/*
$end_pos = strlen($line)-1;
if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[$end_pos]=="}")){
$id = $a[1];
$pos = strrpos($line, "{")+1;
$bytes = (int)substr($line, $pos, $end_pos-$pos);
$received = 0;
do{
$line = iil_ReadLine($fp, 0);
$received+=strlen($line);
$line = chop($line);
if ($received>$bytes) break;
else if (!$line) continue;
list($field,$string)=explode(": ", $line);
if (strcasecmp($field, "date")==0)
$result[$id] = iil_StrToTime($string);
else if ($index_field!="DATE")
$result[$id]=strtoupper(str_replace("\"", "", $string));
}while($line[0]!=")");
}else{
//one line response, not expected so ignore
}
*/
}while(!iil_StartsWith($line, $key));
}else if ($mode==6){
$key="fhi".($c++);
$request = $key." FETCH $message_set (INTERNALDATE)\r\n";
if (!fputs($fp, $request)) return false;
do{
$line=chop(iil_ReadLine($fp, 200));
if ($line[0]=="*"){
//original: "* 10 FETCH (INTERNALDATE "31-Jul-2002 09:18:02 -0500")"
$paren_pos = strpos($line, "(");
$foo = substr($line, 0, $paren_pos);
$a = explode(" ", $foo);
$id = $a[1];
$open_pos = strpos($line, "\"") + 1;
$close_pos = strrpos($line, "\"");
if ($open_pos && $close_pos){
$len = $close_pos - $open_pos;
$time_str = substr($line, $open_pos, $len);
$result[$id] = strtotime($time_str);
}
}else{
$a = explode(" ", $line);
}
}while(!iil_StartsWith($a[0], $key));
}else{
if ($mode >= 3) $field_name="FLAGS";
else if ($index_field=="SIZE") $field_name="RFC822.SIZE";
else $field_name=$index_field;
/* FETCH uid, size, flags */
$key="fhi".($c++);
$request=$key." FETCH $message_set ($field_name)\r\n";
if (!fputs($fp, $request)) return false;
do{
$line=chop(iil_ReadLine($fp, 200));
$a = explode(" ", $line);
if (($line[0]=="*") && ($a[2]=="FETCH")){
$line=str_replace("(", "", $line);
$line=str_replace(")", "", $line);
$a=explode(" ", $line);
$id=$a[1];
if (isset($result[$id])) continue; //if we already got the data, skip forward
if ($a[3]!=$field_name) continue; //make sure it's returning what we requested
/* Caution, bad assumptions, next several lines */
if ($mode==2) $result[$id]=$a[4];
else{
$haystack=strtoupper($line);
$result[$id]=(strpos($haystack, $index_field) > 0 ? "F" : "N");
}
}
}while(!iil_StartsWith($line, $key));
}
//check number of elements...
list($start_mid,$end_mid)=explode(':',$message_set);
if (is_numeric($start_mid) && is_numeric($end_mid)){
//count how many we should have
$should_have = $end_mid - $start_mid +1;
//if we have less, try and fill in the "gaps"
if (count($result)<$should_have){
for($i=$start_mid;$i<=$end_mid;$i++) if (!isset($result[$i])) $result[$i] = '';
}
}
return $result;
}
function iil_CompressMessageSet($message_set){
//given a comma delimited list of independent mid's,
//compresses by grouping sequences together
//if less than 255 bytes long, let's not bother
if (strlen($message_set)<255) return $message_set;
//see if it's already been compress
if (strpos($message_set,':')!==false) return $message_set;
//separate, then sort
$ids = explode(',',$message_set);
sort($ids);
$result = array();
$start = $prev = $ids[0];
foreach($ids as $id){
$incr = $id - $prev;
if ($incr>1){ //found a gap
if ($start==$prev) $result[] = $prev; //push single id
else $result[] = $start.':'.$prev; //push sequence as start_id:end_id
$start = $id; //start of new sequence
}
$prev = $id;
}
//handle the last sequence/id
if ($start==$prev) $result[] = $prev;
else $result[] = $start.':'.$prev;
//return as comma separated string
return implode(',',$result);
}
function iil_C_UIDsToMIDs(&$conn, $mailbox, $uids){
if (!is_array($uids) || count($uids)==0) return array();
return iil_C_Search($conn, $mailbox, "UID ".implode(",", $uids));
}
function iil_C_UIDToMID(&$conn, $mailbox, $uid){
$result = iil_C_UIDsToMIDs($conn, $mailbox, array($uid));
if (count($result)==1) return $result[0];
else return false;
}
function iil_C_FetchUIDs(&$conn,$mailbox){
global $clock;
$num = iil_C_CountMessages($conn, $mailbox);
if ($num==0) return array();
$message_set = '1'.($num>1?':'.$num:'');
//if cache not enabled, just call iil_C_FetchHeaderIndex on 'UID' field
if (!$conn->do_cache)
return iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
//otherwise, let's check cache first
$key = $mailbox.'.uids';
$cache_good = true;
if ($conn->uid_cache) $data = $conn->uid_cache;
else $data = cache_read($conn->user, $conn->host, $key);
//was anything cached at all?
if ($data===false) $cache_good = -1;
//make sure number of messages were the same
if ($cache_good>0 && $data['n']!=$num) $cache_good = -2;
//if everything's okay so far...
if ($cache_good>0){
//check UIDs of highest mid with current and cached
$temp = iil_C_Search($conn, $mailbox, 'UID '.$data['d'][$num]);
if (!$temp || !is_array($temp) || $temp[0]!=$num) $cache_good=-3;
}
//if cached data's good, return it
if ($cache_good>0){
return $data['d'];
}
//otherwise, we need to fetch it
$data = array('n'=>$num,'d'=>array());
$data['d'] = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, 'UID');
cache_write($conn->user, $conn->host, $key, $data);
$conn->uid_cache = $data;
return $data['d'];
}
function iil_SortThreadHeaders($headers, $index_a, $uids){
asort($index_a);
$result = array();
foreach($index_a as $mid=>$foobar){
$uid = $uids[$mid];
$result[$uid] = $headers[$uid];
}
return $result;
}
function iil_C_FetchThreadHeaders(&$conn, $mailbox, $message_set){
global $clock;
global $index_a;
if (empty($message_set)) return false;
$result = array();
$uids = iil_C_FetchUIDs($conn, $mailbox);
$debug = false;
/* Get cached records where possible */
if ($conn->do_cache){
$cached = cache_read($conn->user, $conn->host, $mailbox.'.thhd');
if ($cached && is_array($uids) && count($uids)>0){
$needed_set = "";
foreach($uids as $id=>$uid){
if ($cached[$uid]){
$result[$uid] = $cached[$uid];
$result[$uid]->id = $id;
}else $needed_set.=($needed_set?",":"").$id;
}
if ($needed_set) $message_set = $needed_set;
else $message_set = '';
}
}
$message_set = iil_CompressMessageSet($message_set);
if ($debug) echo "Still need: ".$message_set;
/* if we're missing any, get them */
if ($message_set){
/* FETCH date,from,subject headers */
$key="fh";
$fp = $conn->fp;
$request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS (SUBJECT MESSAGE-ID IN-REPLY-TO)])\r\n";
$mid_to_id = array();
if (!fputs($fp, $request)) return false;
do{
$line = chop(iil_ReadLine($fp, 1024));
if ($debug) echo $line."\n";
if (ereg('\{[0-9]+\}$', $line)){
$a = explode(" ", $line);
$new = array();
$new_thhd = new iilThreadHeader;
$new_thhd->id = $a[1];
do{
$line=chop(iil_ReadLine($fp, 1024),"\r\n");
if (iil_StartsWithI($line,'Message-ID:') || (iil_StartsWithI($line,'In-Reply-To:')) || (iil_StartsWithI($line,'SUBJECT:'))){
$pos = strpos($line, ":");
$field_name = substr($line, 0, $pos);
$field_val = substr($line, $pos+1);
$new[strtoupper($field_name)] = trim($field_val);
}else if (ereg('^[[:space:]]', $line)){
$new[strtoupper($field_name)].= trim($line);
}
}while($line[0]!=')');
$new_thhd->sbj = $new['SUBJECT'];
$new_thhd->mid = substr($new['MESSAGE-ID'], 1, -1);
$new_thhd->irt = substr($new['IN-REPLY-TO'], 1, -1);
$result[$uids[$new_thhd->id]] = $new_thhd;
}
}while(!iil_StartsWith($line, "fh"));
}
/* sort headers */
if (is_array($index_a)){
$result = iil_SortThreadHeaders($result, $index_a, $uids);
}
/* write new set to cache */
if ($conn->do_cache){
if (count($result)!=count($cached))
cache_write($conn->user, $conn->host, $mailbox.'.thhd', $result);
}
//echo 'iil_FetchThreadHeaders:'."\n";
//print_r($result);
return $result;
}
function iil_C_BuildThreads2(&$conn, $mailbox, $message_set, &$clock){
global $index_a;
if (empty($message_set)) return false;
$result=array();
$roots=array();
$root_mids = array();
$sub_mids = array();
$strays = array();
$messages = array();
$fp = $conn->fp;
$debug = false;
$sbj_filter_pat = '[a-zA-Z]{2,3}(\[[0-9]*\])?:([[:space:]]*)';
/* Do "SELECT" command */
if (!iil_C_Select($conn, $mailbox)) return false;
/* FETCH date,from,subject headers */
$mid_to_id = array();
$messages = array();
$headers = iil_C_FetchThreadHeaders($conn, $mailbox, $message_set);
if ($clock) $clock->register('fetched headers');
if ($debug) print_r($headers);
/* go through header records */
foreach($headers as $header){
//$id = $header['i'];
//$new = array('id'=>$id, 'MESSAGE-ID'=>$header['m'],
// 'IN-REPLY-TO'=>$header['r'], 'SUBJECT'=>$header['s']);
$id = $header->id;
$new = array('id'=>$id, 'MESSAGE-ID'=>$header->mid,
'IN-REPLY-TO'=>$header->irt, 'SUBJECT'=>$header->sbj);
/* add to message-id -> mid lookup table */
$mid_to_id[$new['MESSAGE-ID']] = $id;
/* if no subject, use message-id */
if (empty($new['SUBJECT'])) $new['SUBJECT'] = $new['MESSAGE-ID'];
/* if subject contains 'RE:' or has in-reply-to header, it's a reply */
$sbj_pre ='';
$has_re = false;
if (eregi($sbj_filter_pat, $new['SUBJECT'])) $has_re = true;
if ($has_re||$new['IN-REPLY-TO']) $sbj_pre = 'RE:';
/* strip out 're:', 'fw:' etc */
if ($has_re) $sbj = ereg_replace($sbj_filter_pat,'', $new['SUBJECT']);
else $sbj = $new['SUBJECT'];
$new['SUBJECT'] = $sbj_pre.$sbj;
/* if subject not a known thread-root, add to list */
if ($debug) echo $id.' '.$new['SUBJECT']."\t".$new['MESSAGE-ID']."\n";
$root_id = $roots[$sbj];
if ($root_id && ($has_re || !$root_in_root[$root_id])){
if ($debug) echo "\tfound root: $root_id\n";
$sub_mids[$new['MESSAGE-ID']] = $root_id;
$result[$root_id][] = $id;
}else if (!isset($roots[$sbj])||(!$has_re&&$root_in_root[$root_id])){
/* try to use In-Reply-To header to find root
unless subject contains 'Re:' */
if ($has_re&&$new['IN-REPLY-TO']){
if ($debug) echo "\tlooking: ".$new['IN-REPLY-TO']."\n";
//reply to known message?
$temp = $sub_mids[$new['IN-REPLY-TO']];
if ($temp){
//found it, root:=parent's root
if ($debug) echo "\tfound parent: ".$new['SUBJECT']."\n";
$result[$temp][] = $id;
$sub_mids[$new['MESSAGE-ID']] = $temp;
$sbj = '';
}else{
//if we can't find referenced parent, it's a "stray"
$strays[$id] = $new['IN-REPLY-TO'];
}
}
//add subject as root
if ($sbj){
if ($debug) echo "\t added to root\n";
$roots[$sbj] = $id;
$root_in_root[$id] = !$has_re;
$sub_mids[$new['MESSAGE-ID']] = $id;
$result[$id] = array($id);
}
if ($debug) echo $new['MESSAGE-ID']."\t".$sbj."\n";
}
}
//now that we've gone through all the messages,
//go back and try and link up the stray threads
if (count($strays)>0){
foreach($strays as $id=>$irt){
$root_id = $sub_mids[$irt];
if (!$root_id || $root_id==$id) continue;
$result[$root_id] = array_merge($result[$root_id],$result[$id]);
unset($result[$id]);
}
}
if ($clock) $clock->register('data prepped');
if ($debug) print_r($roots);
//print_r($result);
return $result;
}
function iil_SortThreads(&$tree, $index, $sort_order='ASC'){
if (!is_array($tree) || !is_array($index)) return false;
//create an id to position lookup table
$i = 0;
foreach($index as $id=>$val){
$i++;
$index[$id] = $i;
}
$max = $i+1;
//for each tree, set array key to position
$itree = array();
foreach($tree as $id=>$node){
if (count($tree[$id])<=1){
//for "threads" with only one message, key is position of that message
$n = $index[$id];
$itree[$n] = array($n=>$id);
}else{
//for "threads" with multiple messages,
$min = $max;
$new_a = array();
foreach($tree[$id] as $mid){
$new_a[$index[$mid]] = $mid; //create new sub-array mapping position to id
$pos = $index[$mid];
if ($pos&&$pos<$min) $min = $index[$mid]; //find smallest position
}
$n = $min; //smallest position of child is thread position
//assign smallest position to root level key
//set children array to one created above
ksort($new_a);
$itree[$n] = $new_a;
}
}
//sort by key, this basically sorts all threads
ksort($itree);
$i=0;
$out=array();
foreach($itree as $k=>$node){
$out[$i] = $itree[$k];
$i++;
}
//return
return $out;
}
function iil_IndexThreads(&$tree){
/* creates array mapping mid to thread id */
if (!is_array($tree)) return false;
$t_index = array();
foreach($tree as $pos=>$kids){
foreach($kids as $kid) $t_index[$kid] = $pos;
}
return $t_index;
}
function iil_C_FetchHeaders(&$conn, $mailbox, $message_set){
global $IMAP_USE_INTERNAL_DATE;
$c=0;
$result=array();
$fp = $conn->fp;
if (empty($message_set)) return array();
/* Do "SELECT" command */
if (!iil_C_Select($conn, $mailbox)){
$conn->error = "Couldn't select $mailbox";
return false;
}
/* Get cached records where possible */
if ($conn->do_cache){
$uids = iil_C_FetchHeaderIndex($conn, $mailbox, $message_set, "UID");
if (is_array($uids) && count($conn->cache[$mailbox]>0)){
$needed_set = "";
while(list($id,$uid)=each($uids)){
if ($conn->cache[$mailbox][$uid]){
$result[$id] = $conn->cache[$mailbox][$uid];
$result[$id]->id = $id;
}else $needed_set.=($needed_set?",":"").$id;
}
//echo "<!-- iil_C_FetchHeader\nMessage Set: $message_set\nNeeded Set:$needed_set\n//-->\n";
if ($needed_set) $message_set = iil_CompressMessageSet($needed_set);
else return $result;
}
}
/* FETCH date,from,subject headers */
$key="fh".($c++);
$request=$key." FETCH $message_set (BODY.PEEK[HEADER.FIELDS (DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID REFERENCE)])\r\n";
if (!fputs($fp, $request)) return false;
do{
$line=chop(iil_ReadLine($fp, 200));
$a=explode(" ", $line);
if (($line[0]=="*") && ($a[2]=="FETCH")){
$id=$a[1];
$result[$id]=new iilBasicHeader;
$result[$id]->id = $id;
$result[$id]->subject = "";
/*
Start parsing headers. The problem is, some header "lines" take up multiple lines.
So, we'll read ahead, and if the one we're reading now is a valid header, we'll
process the previous line. Otherwise, we'll keep adding the strings until we come
to the next valid header line.
*/
$i = 0;
$lines = array();
do{
$line = chop(iil_ReadLine($fp, 300),"\r\n");
if (ord($line[0])<=32) $lines[$i].=(empty($lines[$i])?"":"\n").trim(chop($line));
else{
$i++;
$lines[$i] = trim(chop($line));
}
}while($line[0]!=")" && strncmp($line, $key, strlen($key))); // patch from "Maksim Rubis" <siburny@hotmail.com>
if(strncmp($line, $key, strlen($key)))
{
//process header, fill iilBasicHeader obj.
// initialize
if (is_array($headers)){
reset($headers);
while ( list($k, $bar) = each($headers) ) $headers[$k] = "";
}
// create array with header field:data
$headers = array();
while ( list($lines_key, $str) = each($lines) ){
list($field, $string) = iil_SplitHeaderLine($str);
$field = strtolower($field);
$headers[$field] = $string;
}
$result[$id]->date = $headers["date"];
$result[$id]->timestamp = iil_StrToTime($headers["date"]);
$result[$id]->from = $headers["from"];
$result[$id]->to = str_replace("\n", " ", $headers["to"]);
$result[$id]->subject = str_replace("\n", "", $headers["subject"]);
$result[$id]->replyto = str_replace("\n", " ", $headers["reply-to"]);
$result[$id]->cc = str_replace("\n", " ", $headers["cc"]);
$result[$id]->bcc = str_replace("\n", " ", $headers["bcc"]);
$result[$id]->encoding = str_replace("\n", " ", $headers["content-transfer-encoding"]);
$result[$id]->ctype = str_replace("\n", " ", $headers["content-type"]);
$result[$id]->in_reply_to = ereg_replace("[\n<>]",'', $headers['in-reply-to']);
$result[$id]->reference = $headers["reference"];
list($result[$id]->ctype, $ctype_add) = explode(";", $headers["content-type"]);
if (preg_match('/charset="?([a-z0-9\-]+)"?/i', $ctype_add, $regs))
$result[$id]->charset = $regs[1];
$messageID = $headers["message-id"];
if (!$messageID) "mid:".$id;
$result[$id]->messageID = $messageID;
}
else {
$a=explode(" ", $line);
}
}
}while(strcmp($a[0], $key)!=0);
/*
FETCH uid, size, flags
Sample reply line: "* 3 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen \Deleted))"
*/
$command_key="fh".($c++);
$request= $command_key." FETCH $message_set (UID RFC822.SIZE FLAGS INTERNALDATE)\r\n";
if (!fputs($fp, $request)) return false;
do{
$line=chop(iil_ReadLine($fp, 200));
//$a = explode(" ", $line);
//if (($line[0]=="*") && ($a[2]=="FETCH")){
if ($line[0]=="*"){
//echo "<!-- $line //-->\n";
//get outter most parens
$open_pos = strpos($line, "(") + 1;
$close_pos = strrpos($line, ")");
if ($open_pos && $close_pos){
//extract ID from pre-paren
$pre_str = substr($line, 0, $open_pos);
$pre_a = explode(" ", $line);
$id = $pre_a[1];
//get data
$len = $close_pos - $open_pos;
$str = substr($line, $open_pos, $len);
//swap parents with quotes, then explode
$str = eregi_replace("[()]", "\"", $str);
$a = iil_ExplodeQuotedString(" ", $str);
//did we get the right number of replies?
$parts_count = count($a);
if ($parts_count>=8){
for ($i=0;$i<$parts_count;$i=$i+2){
if (strcasecmp($a[$i],"UID")==0) $result[$id]->uid=$a[$i+1];
else if (strcasecmp($a[$i],"RFC822.SIZE")==0) $result[$id]->size=$a[$i+1];
else if (strcasecmp($a[$i],"INTERNALDATE")==0) $time_str = $a[$i+1];
else if (strcasecmp($a[$i],"FLAGS")==0) $flags_str = $a[$i+1];
}
// process flags
$flags_str = eregi_replace('[\\\"]', "", $flags_str);
$flags_a = explode(" ", $flags_str);
//echo "<!-- ID: $id FLAGS: ".implode(",", $flags_a)." //-->\n";
$result[$id]->seen = false;
$result[$id]->recent = false;
$result[$id]->deleted = false;
$result[$id]->answered = false;
if (is_array($flags_a)){
reset($flags_a);
while (list($key,$val)=each($flags_a)){
if (strcasecmp($val,"Seen")==0) $result[$id]->seen = true;
else if (strcasecmp($val, "Deleted")==0) $result[$id]->deleted=true;
else if (strcasecmp($val, "Recent")==0) $result[$id]->recent = true;
else if (strcasecmp($val, "Answered")==0) $result[$id]->answered = true;
}
$result[$id]->flags=$flags_str;
}
// if time is gmt...
$time_str = str_replace('GMT','+0000',$time_str);
//get timezone
$time_str = substr($time_str, 0, -1);
$time_zone_str = substr($time_str, -5); //extract timezone
$time_str = substr($time_str, 1, -6); //remove quotes
$time_zone = (float)substr($time_zone_str, 1, 2); //get first two digits
if ($time_zone_str[3]!='0') $time_zone += 0.5; //handle half hour offset
if ($time_zone_str[0]=="-") $time_zone = $time_zone * -1.0; //minus?
$result[$id]->internaldate = $time_str;
if ($IMAP_USE_INTERNAL_DATE){
//calculate timestamp
$timestamp = strtotime($time_str); //return's server's time
$na_timestamp = $timestamp;
$timestamp -= $time_zone * 3600; //compensate for tz, get GMT
$result[$id]->timestamp = $timestamp;
}
if ($conn->do_cache){
$uid = $result[$id]->uid;
$conn->cache[$mailbox][$uid] = $result[$id];
$conn->cache_dirty[$mailbox] = true;
}
//echo "<!-- ID: $id : $time_str -- local: $na_timestamp (".date("F j, Y, g:i a", $na_timestamp).") tz: $time_zone -- GMT: ".$timestamp." (".date("F j, Y, g:i a", $timestamp).") //-->\n";
}else{
//echo "<!-- ERROR: $id : $str //-->\n";
}
}
}
}while(strpos($line, $command_key)===false);
return $result;
}
function iil_C_FetchHeader(&$conn, $mailbox, $id){
$fp = $conn->fp;
$a=iil_C_FetchHeaders($conn, $mailbox, $id);
if (is_array($a)) return $a[$id];
else return false;
}
function iil_SortHeaders($a, $field, $flag){
if (empty($field)) $field="uid";
$field=strtolower($field);
if ($field=="date"||$field=='internaldate') $field="timestamp";
if (empty($flag)) $flag="ASC";
$flag=strtoupper($flag);
$stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ',"\"") : array("\"");
$c=count($a);
if ($c>0){
/*
Strategy:
First, we'll create an "index" array.
Then, we'll use sort() on that array,
and use that to sort the main array.
*/
// create "index" array
$index=array();
reset($a);
while (list($key, $val)=each($a)){
if ($field=="timestamp"){
$data = @strtotime($val->date);
if ($data == false)
$data = $val->timestamp;
}
else {
$data = $val->$field;
if (is_string($data))
$data=strtoupper(str_replace($stripArr, "", $data));
}
$index[$key]=$data;
}
// sort index
$i=0;
if ($flag=="ASC") asort($index);
else arsort($index);
// form new array based on index
$result=array();
reset($index);
while (list($key, $val)=each($index)){
$result[$key]=$a[$key];
$i++;
}
}
return $result;
}
function iil_C_Expunge(&$conn, $mailbox){
$fp = $conn->fp;
if (iil_C_Select($conn, $mailbox)){
$c=0;
fputs($fp, "exp1 EXPUNGE\r\n");
do{
$line=chop(iil_ReadLine($fp, 100));
if ($line[0]=="*") $c++;
}while (!iil_StartsWith($line, "exp1"));
if (iil_ParseResult($line) == 0){
$conn->selected = ""; //state has changed, need to reselect
//$conn->exists-=$c;
return $c;
}else{
$conn->error = $line;
return -1;
}
}
return -1;
}
function iil_C_ModFlag(&$conn, $mailbox, $messages, $flag, $mod){
if ($mod!="+" && $mod!="-") return -1;
$fp = $conn->fp;
$flags=array(
"SEEN"=>"\\Seen",
"DELETED"=>"\\Deleted",
"RECENT"=>"\\Recent",
"ANSWERED"=>"\\Answered",
"DRAFT"=>"\\Draft",
"FLAGGED"=>"\\Flagged"
);
$flag=strtoupper($flag);
$flag=$flags[$flag];
if (iil_C_Select($conn, $mailbox)){
$c=0;
fputs($fp, "flg STORE $messages ".$mod."FLAGS (".$flag.")\r\n");
do{
$line=chop(iil_ReadLine($fp, 100));
if ($line[0]=="*") $c++;
}while (!iil_StartsWith($line, "flg"));
if (iil_ParseResult($line) == 0){
iil_C_ExpireCachedItems($conn, $mailbox, $messages);
return $c;
}else{
$conn->error = $line;
return -1;
}
}else{
$conn->error = "Select failed";
return -1;
}
}
function iil_C_Flag(&$conn, $mailbox, $messages, $flag){
return iil_C_ModFlag($conn, $mailbox, $messages, $flag, "+");
}
function iil_C_Unflag(&$conn, $mailbox, $messages, $flag){
return iil_C_ModFlag($conn, $mailbox, $messages, $flag, "-");
}
function iil_C_Delete(&$conn, $mailbox, $messages){
return iil_C_ModFlag($conn, $mailbox, $messages, "DELETED", "+");
}
function iil_C_Undelete(&$conn, $mailbox, $messages){
return iil_C_ModFlag($conn, $mailbox, $messages, "DELETED", "-");
}
function iil_C_Unseen(&$conn, $mailbox, $messages){
return iil_C_ModFlag($conn, $mailbox, $messages, "SEEN", "-");
}
function iil_C_Copy(&$conn, $messages, $from, $to){
$fp = $conn->fp;
if (empty($from) || empty($to)) return -1;
if (iil_C_Select($conn, $from)){
$c=0;
fputs($fp, "cpy1 COPY $messages \"$to\"\r\n");
$line=iil_ReadReply($fp);
return iil_ParseResult($line);
}else{
return -1;
}
}
function iil_FormatSearchDate($month, $day, $year){
$month = (int)$month;
$months=array(
1=>"Jan", 2=>"Feb", 3=>"Mar", 4=>"Apr",
5=>"May", 6=>"Jun", 7=>"Jul", 8=>"Aug",
9=>"Sep", 10=>"Oct", 11=>"Nov", 12=>"Dec"
);
return $day."-".$months[$month]."-".$year;
}
function iil_C_CountUnseen(&$conn, $folder){
$index = iil_C_Search($conn, $folder, "ALL UNSEEN");
if (is_array($index)){
$str = implode(",", $index);
if (empty($str)) return false;
else return count($index);
}else return false;
}
function iil_C_UID2ID(&$conn, $folder, $uid){
if ($uid > 0){
$id_a = iil_C_Search($conn, $folder, "UID $uid");
if (is_array($id_a)){
$count = count($id_a);
if ($count > 1) return false;
else return $id_a[0];
}
}
return false;
}
function iil_C_ID2UID(&$conn, $folder, $id){
$fp = $conn->fp;
$result=-1;
if ($id > 0) {
if (iil_C_Select($conn, $folder)){
$key = "FUID";
if (fputs($fp, "$key FETCH $id (UID)\r\n")){
do{
$line=chop(iil_ReadLine($fp, 1024));
if (eregi("^\* $id FETCH \(UID (.*)\)", $line, $r)){
$result = $r[1];
}
} while (!preg_match("/^$key/", $line));
}
}
}
return $result;
}
function iil_C_Search(&$conn, $folder, $criteria){
$fp = $conn->fp;
if (iil_C_Select($conn, $folder)){
$c=0;
$query = "srch1 SEARCH ".chop($criteria)."\r\n";
fputs($fp, $query);
do{
$line=trim(chop(iil_ReadLine($fp, 10000)));
if (eregi("^\* SEARCH", $line)){
$str = trim(substr($line, 8));
$messages = explode(" ", $str);
}
}while(!iil_StartsWith($line, "srch1"));
$result_code=iil_ParseResult($line);
if ($result_code==0) return $messages;
else{
$conn->error = "iil_C_Search: ".$line."\n";
return false;
}
}else{
$conn->error = "iil_C_Search: Couldn't select \"$folder\"\n";
return false;
}
}
function iil_C_Move(&$conn, $messages, $from, $to){
$fp = $conn->fp;
if (!$from || !$to) return -1;
$r=iil_C_Copy($conn, $messages, $from,$to);
if ($r==0){
return iil_C_Delete($conn, $from, $messages);
}else{
return $r;
}
}
function iil_C_GetHierarchyDelimiter(&$conn){
if ($conn->delimiter) return $conn->delimiter;
$fp = $conn->fp;
$delimiter = false;
//try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
if (!fputs($fp, "ghd LIST \"\" \"\"\r\n")) return false;
do{
$line=iil_ReadLine($fp, 500);
if ($line[0]=="*"){
$line = rtrim($line);
$a=iil_ExplodeQuotedString(" ", $line);
if ($a[0]=="*") $delimiter = str_replace("\"", "", $a[count($a)-2]);
}
}while (!iil_StartsWith($line, "ghd"));
if (strlen($delimiter)>0) return $delimiter;
//if that fails, try namespace extension
//try to fetch namespace data
fputs($conn->fp, "ns1 NAMESPACE\r\n");
do{
$line = iil_ReadLine($conn->fp, 1024);
if (iil_StartsWith($line, "* NAMESPACE")){
$i = 0;
$data = iil_ParseNamespace2(substr($line,11), $i, 0, 0);
}
}while(!iil_StartsWith($line, "ns1"));
if (!is_array($data)) return false;
//extract user space data (opposed to global/shared space)
$user_space_data = $data[0];
if (!is_array($user_space_data)) return false;
//get first element
$first_userspace = $user_space_data[0];
if (!is_array($first_userspace)) return false;
//extract delimiter
$delimiter = $first_userspace[1];
return $delimiter;
}
function iil_C_ListMailboxes(&$conn, $ref, $mailbox){
global $IGNORE_FOLDERS;
$ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
$fp = $conn->fp;
if (empty($mailbox)) $mailbox="*";
if (empty($ref) && $conn->rootdir) $ref = $conn->rootdir;
// send command
if (!fputs($fp, "lmb LIST \"".$ref."\" \"$mailbox\"\r\n")) return false;
$i=0;
// get folder list
do{
$line=iil_ReadLine($fp, 500);
$line=iil_MultLine($fp, $line);
$a = explode(" ", $line);
if (($line[0]=="*") && ($a[1]=="LIST")){
$line = rtrim($line);
// split one line
$a=iil_ExplodeQuotedString(" ", $line);
// last string is folder name
$folder = str_replace("\"", "", $a[count($a)-1]);
if (empty($ignore) || (!empty($ignore) && !eregi($ignore, $folder))) $folders[$i] = $folder;
// second from last is delimiter
$delim = str_replace("\"", "", $a[count($a)-2]);
// is it a container?
$i++;
}
}while (!iil_StartsWith($line, "lmb"));
if (is_array($folders)){
if (!empty($ref)){
// if rootdir was specified, make sure it's the first element
// some IMAP servers (i.e. Courier) won't return it
if ($ref[strlen($ref)-1]==$delim) $ref = substr($ref, 0, strlen($ref)-1);
if ($folders[0]!=$ref) array_unshift($folders, $ref);
}
return $folders;
}else if (iil_ParseResult($line)==0){
return array('INBOX');
}else{
$conn->error = $line;
return false;
}
}
function iil_C_ListSubscribed(&$conn, $ref, $mailbox){
global $IGNORE_FOLDERS;
$ignore = $IGNORE_FOLDERS[strtolower($conn->host)];
$fp = $conn->fp;
if (empty($mailbox)) $mailbox = "*";
if (empty($ref) && $conn->rootdir) $ref = $conn->rootdir;
$folders = array();
// send command
if (!fputs($fp, "lsb LSUB \"".$ref."\" \"".$mailbox."\"\r\n")){
$conn->error = "Couldn't send LSUB command\n";
return false;
}
$i=0;
// get folder list
do{
$line=iil_ReadLine($fp, 500);
$line=iil_MultLine($fp, $line);
$a = explode(" ", $line);
- if (($line[0]=="*") && ($a[1]=="LSUB")){
+ if (($line[0]=="*") && ($a[1]=="LSUB" || $a[1]=="LIST")){
$line = rtrim($line);
// split one line
$a=iil_ExplodeQuotedString(" ", $line);
// last string is folder name
//$folder = UTF7DecodeString(str_replace("\"", "", $a[count($a)-1]));
$folder = str_replace("\"", "", $a[count($a)-1]);
if ((!in_array($folder, $folders)) && (empty($ignore) || (!empty($ignore) && !eregi($ignore, $folder)))) $folders[$i] = $folder;
// second from last is delimiter
$delim = str_replace("\"", "", $a[count($a)-2]);
// is it a container?
$i++;
}
}while (!iil_StartsWith($line, "lsb"));
if (is_array($folders)){
if (!empty($ref)){
// if rootdir was specified, make sure it's the first element
// some IMAP servers (i.e. Courier) won't return it
if ($ref[strlen($ref)-1]==$delim) $ref = substr($ref, 0, strlen($ref)-1);
if ($folders[0]!=$ref) array_unshift($folders, $ref);
}
return $folders;
}else{
$conn->error = $line;
return false;
}
}
function iil_C_Subscribe(&$conn, $folder){
$fp = $conn->fp;
$query = "sub1 SUBSCRIBE \"".$folder."\"\r\n";
fputs($fp, $query);
$line=trim(chop(iil_ReadLine($fp, 10000)));
return iil_ParseResult($line);
}
function iil_C_UnSubscribe(&$conn, $folder){
$fp = $conn->fp;
$query = "usub1 UNSUBSCRIBE \"".$folder."\"\r\n";
fputs($fp, $query);
$line=trim(chop(iil_ReadLine($fp, 10000)));
return iil_ParseResult($line);
}
function iil_C_FetchPartHeader(&$conn, $mailbox, $id, $part){
$fp = $conn->fp;
$result=false;
if (($part==0)||(empty($part))) $part="HEADER";
else $part.=".MIME";
if (iil_C_Select($conn, $mailbox)){
$key="fh".($c++);
$request=$key." FETCH $id (BODY.PEEK[$part])\r\n";
if (!fputs($fp, $request)) return false;
do{
$line=chop(iil_ReadLine($fp, 200));
$a=explode(" ", $line);
if (($line[0]=="*") && ($a[2]=="FETCH") && ($line[strlen($line)-1]!=")")){
$line=iil_ReadLine($fp, 300);
while(chop($line)!=")"){
$result.=$line;
$line=iil_ReadLine($fp, 300);
}
}
}while(strcmp($a[0], $key)!=0);
}
return $result;
}
function iil_C_HandlePartBody(&$conn, $mailbox, $id, $part, $mode){
/* modes:
1: return string
2: print
3: base64 and print
*/
$fp = $conn->fp;
$result=false;
if (($part==0)||(empty($part))) $part="TEXT";
if (iil_C_Select($conn, $mailbox)){
$reply_key="* ".$id;
// format request
$key="ftch".($c++)." ";
$request=$key."FETCH $id (BODY.PEEK[$part])\r\n";
// send request
if (!fputs($fp, $request)) return false;
// receive reply line
do{
$line = chop(iil_ReadLine($fp, 1000));
$a = explode(" ", $line);
}while ($a[2]!="FETCH");
$len = strlen($line);
if ($line[$len-1] == ")"){
//one line response, get everything between first and last quotes
$from = strpos($line, "\"") + 1;
$to = strrpos($line, "\"");
$len = $to - $from;
if ($mode==1) $result = substr($line, $from, $len);
else if ($mode==2) echo substr($line, $from, $len);
else if ($mode==3) echo base64_decode(substr($line, $from, $len));
}else if ($line[$len-1] == "}"){
//multi-line request, find sizes of content and receive that many bytes
$from = strpos($line, "{") + 1;
$to = strrpos($line, "}");
$len = $to - $from;
$sizeStr = substr($line, $from, $len);
$bytes = (int)$sizeStr;
$received = 0;
while ($received < $bytes){
$remaining = $bytes - $received;
$line = iil_ReadLine($fp, 1024);
$len = strlen($line);
if ($len > $remaining) substr($line, 0, $remaining);
$received += strlen($line);
if ($mode==1) $result .= chop($line)."\n";
else if ($mode==2){ echo chop($line)."\n"; flush(); }
else if ($mode==3){ echo base64_decode($line); flush(); }
}
}
// read in anything up until 'til last line
do{
$line = iil_ReadLine($fp, 1024);
}while(!iil_StartsWith($line, $key));
if ($result){
$result = chop($result);
return $result; // substr($result, 0, strlen($result)-1);
}else return false;
}else{
echo "Select failed.";
}
if ($mode==1) return $result;
else return $received;
}
function iil_C_FetchPartBody(&$conn, $mailbox, $id, $part){
return iil_C_HandlePartBody($conn, $mailbox, $id, $part, 1);
}
function iil_C_PrintPartBody(&$conn, $mailbox, $id, $part){
iil_C_HandlePartBody($conn, $mailbox, $id, $part, 2);
}
function iil_C_PrintBase64Body(&$conn, $mailbox, $id, $part){
iil_C_HandlePartBody($conn, $mailbox, $id, $part, 3);
}
function iil_C_CreateFolder(&$conn, $folder){
$fp = $conn->fp;
if (fputs($fp, "c CREATE \"".$folder."\"\r\n")){
do{
$line=iil_ReadLine($fp, 300);
}while($line[0]!="c");
$conn->error = $line;
return (iil_ParseResult($line)==0);
}else{
return false;
}
}
function iil_C_RenameFolder(&$conn, $from, $to){
$fp = $conn->fp;
if (fputs($fp, "r RENAME \"".$from."\" \"".$to."\"\r\n")){
do{
$line=iil_ReadLine($fp, 300);
}while($line[0]!="r");
return (iil_ParseResult($line)==0);
}else{
return false;
}
}
function iil_C_DeleteFolder(&$conn, $folder){
$fp = $conn->fp;
if (fputs($fp, "d DELETE \"".$folder."\"\r\n")){
do{
$line=iil_ReadLine($fp, 300);
}while($line[0]!="d");
return (iil_ParseResult($line)==0);
}else{
$conn->error = "Couldn't send command\n";
return false;
}
}
function iil_C_Append(&$conn, $folder, &$message){
if (!$folder) return false;
$fp = $conn->fp;
$message = str_replace("\r", "", $message);
$message = str_replace("\n", "\r\n", $message);
$len = strlen($message);
if (!$len) return false;
$request="A APPEND \"".$folder."\" (\\Seen) {".$len."}\r\n";
if (fputs($fp, $request)){
$line=iil_ReadLine($fp, 100);
$sent = fwrite($fp, $message."\r\n");
flush();
do{
$line=iil_ReadLine($fp, 1000);
}while($line[0]!="A");
$result = (iil_ParseResult($line)==0);
if (!$result) $conn->error .= $line."\n";
return $result;
}else{
$conn->error .= "Couldn't send command \"$request\"\n";
return false;
}
}
function iil_C_AppendFromFile(&$conn, $folder, $path){
if (!$folder) return false;
//open message file
$in_fp = false;
if (file_exists(realpath($path))) $in_fp = fopen($path, "r");
if (!$in_fp){
$conn->error .= "Couldn't open $path for reading\n";
return false;
}
$fp = $conn->fp;
$len = filesize($path);
if (!$len) return false;
//send APPEND command
$request="A APPEND \"".$folder."\" (\\Seen) {".$len."}\r\n";
$bytes_sent = 0;
if (fputs($fp, $request)){
$line=iil_ReadLine($fp, 100);
//send file
while(!feof($in_fp)){
$buffer = fgets($in_fp, 4096);
$bytes_sent += strlen($buffer);
fputs($fp, $buffer);
}
fclose($in_fp);
fputs($fp, "\r\n");
//read response
do{
$line=iil_ReadLine($fp, 1000);
}while($line[0]!="A");
$result = (iil_ParseResult($line)==0);
if (!$result) $conn->error .= $line."\n";
return $result;
}else{
$conn->error .= "Couldn't send command \"$request\"\n";
return false;
}
}
function iil_C_FetchStructureString(&$conn, $folder, $id){
$fp = $conn->fp;
$result=false;
if (iil_C_Select($conn, $folder)){
$key = "F1247";
if (fputs($fp, "$key FETCH $id (BODYSTRUCTURE)\r\n")){
do{
$line=chop(iil_ReadLine($fp, 5000));
if ($line[0]=="*"){
if (ereg("\}$", $line)){
preg_match('/(.+)\{([0-9]+)\}/', $line, $match);
$result = $match[1];
do{
$line = chop(iil_ReadLine($fp, 100));
if (!preg_match("/^$key/", $line)) $result .= $line;
else $done = true;
}while(!$done);
}else{
$result = $line;
}
list($pre, $post) = explode("BODYSTRUCTURE ", $result);
$result = substr($post, 0, strlen($post)-1); //truncate last ')' and return
}
}while (!preg_match("/^$key/",$line));
}
}
return $result;
}
function iil_C_PrintSource(&$conn, $folder, $id, $part){
$header = iil_C_FetchPartHeader($conn, $folder, $id, $part);
//echo str_replace("\r", "", $header);
echo $header;
echo iil_C_PrintPartBody($conn, $folder, $id, $part);
}
function iil_C_GetQuota(&$conn){
/*
b GETQUOTAROOT "INBOX"
* QUOTAROOT INBOX user/rchijiiwa1
* QUOTA user/rchijiiwa1 (STORAGE 654 9765)
b OK Completed
*/
$fp = $conn->fp;
$result=false;
$quota_line = "";
//get line containing quota info
if (fputs($fp, "QUOT1 GETQUOTAROOT \"INBOX\"\r\n")){
do{
$line=chop(iil_ReadLine($fp, 5000));
if (iil_StartsWith($line, "* QUOTA ")) $quota_line = $line;
}while(!iil_StartsWith($line, "QUOT1"));
}
//return false if not found, parse if found
if (!empty($quota_line)){
$quota_line = eregi_replace("[()]", "", $quota_line);
$parts = explode(" ", $quota_line);
$storage_part = array_search("STORAGE", $parts);
if ($storage_part>0){
$result = array();
$used = $parts[$storage_part+1];
$total = $parts[$storage_part+2];
$result["used"] = $used;
$result["total"] = (empty($total)?"??":$total);
$result["percent"] = (empty($total)?"??":round(($used/$total)*100));
$result["free"] = 100 - $result["percent"];
}
}
return $result;
}
function iil_C_ClearFolder(&$conn, $folder){
$num_in_trash = iil_C_CountMessages($conn, $folder);
if ($num_in_trash > 0) iil_C_Delete($conn, $folder, "1:".$num_in_trash);
return (iil_C_Expunge($conn, $folder) >= 0);
}
?>
diff --git a/program/steps/mail/show.inc b/program/steps/mail/show.inc
index 27fc44b3f..26a3d3312 100644
--- a/program/steps/mail/show.inc
+++ b/program/steps/mail/show.inc
@@ -1,178 +1,178 @@
<?php
/*
+-----------------------------------------------------------------------+
| program/steps/mail/show.inc |
| |
| This file is part of the RoundCube Webmail client |
| Copyright (C) 2005, 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();
$MESSAGE['headers'] = $IMAP->get_headers($_GET['_uid']);
$MESSAGE['source'] = rcmail_message_source($_GET['_uid']);
// go back to list if message not found (wrong UID)
if (!$MESSAGE['headers'] || !$MESSAGE['source'])
{
$_action = 'list';
return;
}
$mmd = new Mail_mimeDecode($MESSAGE['source']);
$MESSAGE['structure'] = $mmd->decode(array('include_bodies' => TRUE,
'decode_headers' => FALSE,
'decode_bodies' => FALSE));
$mmd->getMimeNumbers($MESSAGE['structure']);
$MESSAGE['subject'] = $IMAP->decode_header($MESSAGE['structure']->headers['subject']);
if ($MESSAGE['structure'])
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($_GET['_uid']);
// mark message as read
if (!$MESSAGE['headers']->seen)
$IMAP->set_flag($_GET['_uid'], 'SEEN');
// give message uid to the client
$javascript = sprintf("%s.set_env('uid', '%s');\n", $JS_OBJECT_NAME, $_GET['_uid']);
$javascript .= sprintf("%s.set_env('safemode', '%b');", $JS_OBJECT_NAME, $_GET['_safe']);
$next = $prev = -1;
// get previous and next 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)$_GET['_uid'], $a_msg_index, TRUE);
$prev = isset($a_msg_index[$MESSAGE['index']-1]) ? $a_msg_index[$MESSAGE['index']-1] : -1 ;
$next = isset($a_msg_index[$MESSAGE['index']+1]) ? $a_msg_index[$MESSAGE['index']+1] : -1 ;
} else {
// this assumes that we are sorted by date_DESC
$seq = $IMAP->get_id($_GET['_uid']);
$prev = $IMAP->get_uid($seq + 1);
$next = $IMAP->get_uid($seq - 1);
$MESSAGE['index'] = $IMAP->messagecount() - $seq;
}
if ($prev > 0)
$javascript .= sprintf("\n%s.set_env('prev_uid', '%s');", $JS_OBJECT_NAME, $prev);
if ($next > 0)
$javascript .= sprintf("\n%s.set_env('next_uid', '%s');", $JS_OBJECT_NAME, $next);
$OUTPUT->add_script($javascript);
}
function rcmail_message_attachments($attrib)
{
global $CONFIG, $OUTPUT, $PRINT_MODE, $MESSAGE, $GET_URL, $JS_OBJECT_NAME;
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&_part=%s" onclick="return %s.command(\'load-attachment\',{part:\'%s\', mimetype:\'%s\'},this)">%s</a></li>'."\n",
- $GET_URL,
+ $out .= sprintf('<li><a href="%s&_part=%s" onclick="return %s.command(\'load-attachment\',{part:\'%s\', mimetype:\'%s\'},this)">%s</a></li>'."\n",
+ htmlentities($GET_URL),
$attach_prop['part_id'],
$JS_OBJECT_NAME,
$attach_prop['part_id'],
$attach_prop['mimetype'],
$attach_prop['filename']);
}
$out .= "</ul>";
return $out;
}
}
// return an HTML iframe for loading mail content
function rcmail_messagecontent_frame($attrib)
{
global $COMM_PATH, $OUTPUT, $GET_URL, $JS_OBJECT_NAME;
// allow the following attributes to be added to the <iframe> tag
$attrib_str = create_attrib_string($attrib);
$framename = 'rcmailcontentwindow';
$out = sprintf('<iframe src="%s" name="%s"%s>%s</iframe>'."\n",
$GET_URL,
$framename,
$attrib_str,
rcube_label('loading'));
$OUTPUT->add_script("$JS_OBJECT_NAME.set_env('contentframe', '$framename');");
return $out;
}
function rcmail_remote_objects_msg($attrib)
{
global $CONFIG, $OUTPUT, $JS_OBJECT_NAME;
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 .= rep_specialchars_output(sprintf('%s <a href="#loadimages" onclick="%s.command(\'load-images\')" title="%s">%s</a>',
rcube_label('blockedimages'),
$JS_OBJECT_NAME,
rcube_label('showimages'),
rcube_label('showimages')));
$out .= '</div>';
$OUTPUT->add_script(sprintf("%s.gui_object('remoteobjectsmsg', '%s');", $JS_OBJECT_NAME, $attrib['id']));
return $out;
}
if ($_action=='print')
parse_template('printmessage');
else
parse_template('message');
?>
\ No newline at end of file
diff --git a/skins/default/templates/compose.html b/skins/default/templates/compose.html
index e5db5a59b..a65dcb772 100644
--- a/skins/default/templates/compose.html
+++ b/skins/default/templates/compose.html
@@ -1,142 +1,153 @@
<!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;
}
function rcmail_auto_save()
{
rcmail.command('savedraft','',this);
self.setTimeout('rcmail_auto_save()',300000);
}
self.setTimeout('rcmail_auto_save()',300000);
//-->
</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="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="contacts" imageSel="/images/buttons/contacts_sel.png" imageAct="/images/buttons/contacts_act.png" imagePas="/images/buttons/contacts_pas.png" width="32" height="32" title="addressbook" />-->
<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> <roundcube:object name="prioritySelector" form="form" id="rcmcomposepriority" />
</div>
<div id="receipt-selector">
<roundcube:object name="receiptCheckBox" form="form" id="rcmcomposereceipt" /> <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:100%;" summary=""><tr>
+<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=""><tr>
+<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><roundcube:object name="composeAttachment" size="20" /></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></table>
+</tr>
+</tbody>
+</table>
</td>
</tr><tr>
<td style="width:100%; height:95%; vertical-align:top;">
-<roundcube:object name="composeBody" id="compose-body" form="form" cols="80" rows="20" wrap="virtual" tabindex="7" /><br />
+<roundcube:object name="composeBody" id="compose-body" form="form" cols="80" rows="20" wrap="virtual" tabindex="7" />
+</td>
+
+</tr><tr>
+
+<td>
+
+<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" />: <roundcube:object name="charsetSelector" tabindex="8" />
</td>
-</tr></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');
//-->
</script>
-<!--
-<div id="attachment-form">
-<roundcube:object name="composeAttachment" size="20" /><br />
-<input type="button" value="<roundcube:label name='close' />" onclick="rcmail_show_attachment_form(0)" />
-<input type="button" value="<roundcube:label name='send' />" onclick="rcmail.command('send-attachment', this)" />
-</div>
--->
</body>
</html>
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Mon, Aug 17, 11:59 AM (1 d, 1 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1261438
Default Alt Text
(193 KB)
Attached To
Mode
R3 roundcubemail
Attached
Detach File
Event Timeline
Log In to Comment