From 197601ef5fa2e6aaabfb6e0baaf56179f7cc1ee3 Mon Sep 17 00:00:00 2001
From: thomascube <thomas@roundcube.net>
Date: Wed, 30 Apr 2008 04:21:42 -0400
Subject: [PATCH] Next step: introduce the application class 'rcmail' and get rid of some global vars

---
 program/include/main.inc                  |  527 +-----------------
 program/steps/mail/compose.inc            |   48 -
 program/include/rcube_json_output.php     |    4 
 program/steps/mail/show.inc               |   12 
 program/include/iniset.php                |    2 
 program/steps/settings/manage_folders.inc |   12 
 index.php                                 |  142 +---
 program/include/rcube_shared.inc          |    4 
 program/steps/mail/folders.inc            |    6 
 program/steps/mail/func.inc               |    2 
 program/steps/settings/func.inc           |   15 
 CHANGELOG                                 |    4 
 program/steps/addressbook/edit.inc        |   15 
 program/steps/addressbook/save.inc        |    6 
 program/steps/settings/save_identity.inc  |    2 
 program/include/rcube_user.php            |  125 +--
 config/main.inc.php.dist                  |    2 
 program/steps/mail/sendmail.inc           |    2 
 program/include/rcube_config.php          |  152 +++++
 program/steps/settings/save_prefs.inc     |    5 
 program/steps/mail/move_del.inc           |    6 
 program/steps/settings/edit_identity.inc  |   10 
 program/include/rcube_imap.php            |    2 
 program/include/rcmail.php                |  462 ++++++++++++++++
 program/include/rcube_template.php        |   67 +
 25 files changed, 866 insertions(+), 768 deletions(-)

diff --git a/CHANGELOG b/CHANGELOG
index 22c166b..da4e14a 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -1,6 +1,10 @@
 CHANGELOG RoundCube Webmail
 ---------------------------
 
+2008/04/30 (thomasb)
+----------
+- Introduce new application class 'rcmail' and get rid of some global vars
+
 2008/04/29 (alec)
 ----------
 - improved messages list performance - patch from Justin Heesemann
diff --git a/config/main.inc.php.dist b/config/main.inc.php.dist
index 8adb4cf..25cf6da 100644
--- a/config/main.inc.php.dist
+++ b/config/main.inc.php.dist
@@ -118,7 +118,7 @@
 $rcmail_config['des_key'] = 'rcmail-!24ByteDESkey*Str';
 
 // the default locale setting
-$rcmail_config['locale_string'] = 'en';
+$rcmail_config['language'] = 'en';
 
 // use this format for short date display
 $rcmail_config['date_short'] = 'D H:i';
diff --git a/index.php b/index.php
index aa8d8bb..3d4a160 100644
--- a/index.php
+++ b/index.php
@@ -2,7 +2,7 @@
 /*
  +-----------------------------------------------------------------------+
  | RoundCube Webmail IMAP Client                                         |
- | Version 0.1-20080328                                                  |
+ | Version 0.1-20080430                                                  |
  |                                                                       |
  | Copyright (C) 2005-2008, RoundCube Dev. - Switzerland                 |
  | Licensed under the GNU GPL                                            |
@@ -45,20 +45,9 @@
 
 // define global vars
 $OUTPUT_TYPE = 'html';
-$MAIN_TASKS = array('mail','settings','addressbook','logout');
-
-// catch some url/post parameters
-$_task = strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC));
-$_action = strip_quotes(get_input_value('_action', RCUBE_INPUT_GPC));
-$_framed = (!empty($_GET['_framed']) || !empty($_POST['_framed']));
-
-// use main task if empty or invalid value
-if (empty($_task) || !in_array($_task, $MAIN_TASKS))
-  $_task = 'mail';
-
 
 // set output buffering
-if ($_action != 'get' && $_action != 'viewsource') {
+if ($RCMAIL->action != 'get' && $RCMAIL->action != 'viewsource') {
   // use gzip compression if supported
   if (function_exists('ob_gzhandler')
       && !ini_get('zlib.output_compression')
@@ -71,28 +60,11 @@
 }
 
 
-// start session with requested task
-rcmail_startup($_task);
-
-// set session related variables
-$COMM_PATH = sprintf('./?_task=%s', $_task);
-$SESS_HIDDEN_FIELD = '';
-
-
-// add framed parameter
-if ($_framed) {
-  $COMM_PATH .= '&_framed=1';
-  $SESS_HIDDEN_FIELD .= "\n".'<input type="hidden" name="_framed" value="1" />';
-}
-
+// init application and start session with requested task
+$RCMAIL = rcmail::get_instance();
 
 // init output class
-if (!empty($_GET['_remote']) || !empty($_POST['_remote'])) {
-  rcmail_init_json();
-}
-else {
-  rcmail_load_gui();
-}
+$OUTPUT = (!empty($_GET['_remote']) || !empty($_POST['_remote'])) ? $RCMAIL->init_json() : $RCMAIL->load_gui((!empty($_GET['_framed']) || !empty($_POST['_framed'])));
 
 
 // check DB connections and exit on failure
@@ -105,12 +77,12 @@
 
 
 // error steps
-if ($_action=='error' && !empty($_GET['_code'])) {
+if ($RCMAIL->action=='error' && !empty($_GET['_code'])) {
   raise_error(array('code' => hexdec($_GET['_code'])), FALSE, TRUE);
 }
 
 // try to log in
-if ($_action=='login' && $_task=='mail') {
+if ($RCMAIL->action=='login' && $RCMAIL->task=='mail') {
   $host = rcmail_autoselect_host();
   
   // check if client supports cookies
@@ -118,7 +90,7 @@
     $OUTPUT->show_message("cookiesdisabled", 'warning');
   }
   else if ($_SESSION['temp'] && !empty($_POST['_user']) && isset($_POST['_pass']) &&
-           rcmail_login(trim(get_input_value('_user', RCUBE_INPUT_POST), ' '),
+           $RCMAIL->login(trim(get_input_value('_user', RCUBE_INPUT_POST), ' '),
               get_input_value('_pass', RCUBE_INPUT_POST, true, 'ISO-8859-1'), $host)) {
     // create new session ID
     unset($_SESSION['temp']);
@@ -128,7 +100,7 @@
     rcmail_authenticate_session();
 
     // send redirect
-    header("Location: $COMM_PATH");
+    header("Location: {$RCMAIL->comm_path}");
     exit;
   }
   else {
@@ -138,14 +110,14 @@
 }
 
 // end session
-else if (($_task=='logout' || $_action=='logout') && isset($_SESSION['user_id'])) {
+else if (($RCMAIL->task=='logout' || $RCMAIL->action=='logout') && isset($_SESSION['user_id'])) {
   $OUTPUT->show_message('loggedout');
   rcmail_logout_actions();
   rcmail_kill_session();
 }
 
 // check session and auth cookie
-else if ($_action != 'login' && $_SESSION['user_id'] && $_action != 'send') {
+else if ($RCMAIL->action != 'login' && $_SESSION['user_id'] && $RCMAIL->action != 'send') {
   if (!rcmail_authenticate_session()) {
     $OUTPUT->show_message('sessionerror', 'error');
     rcmail_kill_session();
@@ -154,24 +126,24 @@
 
 
 // log in to imap server
-if (!empty($USER->ID) && $_task=='mail') {
+if (!empty($RCMAIL->user->ID) && $RCMAIL->task == 'mail') {
   $conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl']);
   if (!$conn) {
     $OUTPUT->show_message($IMAP->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
     rcmail_kill_session();
   }
   else {
-    rcmail_set_imap_prop();
+    $RCMAIL->set_imap_prop();
   }
 }
 
 
 // not logged in -> set task to 'login
-if (empty($USER->ID)) {
+if (empty($RCMAIL->user->ID)) {
   if ($OUTPUT->ajax_call)
     $OUTPUT->remote_response("setTimeout(\"location.href='\"+this.env.comm_path+\"'\", 2000);");
   
-  $_task = 'login';
+  $RCMAIL->task = 'login';
 }
 
 
@@ -184,16 +156,8 @@
 }
 
 
-// set task and action to client
-$OUTPUT->set_env('task', $_task);
-if (!empty($_action)) {
-  $OUTPUT->set_env('action', $_action);
-}
-
-
-
 // not logged in -> show login page
-if (empty($USER->ID)) {
+if (empty($RCMAIL->user->ID)) {
   // check if installer is still active
   if ($CONFIG['enable_installer'] && is_readable('./installer/index.php')) {
     $OUTPUT->add_footer(html::div(array('style' => "background:#ef9398; border:2px solid #dc5757; padding:0.5em; margin:2em auto; width:50em"),
@@ -213,65 +177,65 @@
 
 
 // handle keep-alive signal
-if ($_action=='keep-alive') {
+if ($RCMAIL->action=='keep-alive') {
   $OUTPUT->reset();
   $OUTPUT->send('');
   exit;
 }
 
 // include task specific files
-if ($_task=='mail') {
+if ($RCMAIL->task=='mail') {
   include_once('program/steps/mail/func.inc');
   
-  if ($_action=='show' || $_action=='preview' || $_action=='print')
+  if ($RCMAIL->action=='show' || $RCMAIL->action=='preview' || $RCMAIL->action=='print')
     include('program/steps/mail/show.inc');
 
-  if ($_action=='get')
+  if ($RCMAIL->action=='get')
     include('program/steps/mail/get.inc');
 
-  if ($_action=='moveto' || $_action=='delete')
+  if ($RCMAIL->action=='moveto' || $RCMAIL->action=='delete')
     include('program/steps/mail/move_del.inc');
 
-  if ($_action=='mark')
+  if ($RCMAIL->action=='mark')
     include('program/steps/mail/mark.inc');
 
-  if ($_action=='viewsource')
+  if ($RCMAIL->action=='viewsource')
     include('program/steps/mail/viewsource.inc');
 
-  if ($_action=='sendmdn')
+  if ($RCMAIL->action=='sendmdn')
     include('program/steps/mail/sendmdn.inc');
 
-  if ($_action=='send')
+  if ($RCMAIL->action=='send')
     include('program/steps/mail/sendmail.inc');
 
-  if ($_action=='upload')
+  if ($RCMAIL->action=='upload')
     include('program/steps/mail/upload.inc');
 
-  if ($_action=='compose' || $_action=='remove-attachment' || $_action=='display-attachment')
+  if ($RCMAIL->action=='compose' || $RCMAIL->action=='remove-attachment' || $RCMAIL->action=='display-attachment')
     include('program/steps/mail/compose.inc');
 
-  if ($_action=='addcontact')
+  if ($RCMAIL->action=='addcontact')
     include('program/steps/mail/addcontact.inc');
 
-  if ($_action=='expunge' || $_action=='purge')
+  if ($RCMAIL->action=='expunge' || $RCMAIL->action=='purge')
     include('program/steps/mail/folders.inc');
 
-  if ($_action=='check-recent')
+  if ($RCMAIL->action=='check-recent')
     include('program/steps/mail/check_recent.inc');
 
-  if ($_action=='getunread')
+  if ($RCMAIL->action=='getunread')
     include('program/steps/mail/getunread.inc');
     
-  if ($_action=='list' && isset($_REQUEST['_remote']))
+  if ($RCMAIL->action=='list' && isset($_REQUEST['_remote']))
     include('program/steps/mail/list.inc');
 
-   if ($_action=='search')
+   if ($RCMAIL->action=='search')
      include('program/steps/mail/search.inc');
      
-  if ($_action=='spell')
+  if ($RCMAIL->action=='spell')
     include('program/steps/mail/spell.inc');
 
-  if ($_action=='rss')
+  if ($RCMAIL->action=='rss')
     include('program/steps/mail/rss.inc');
     
   // make sure the message count is refreshed
@@ -280,62 +244,62 @@
 
 
 // include task specific files
-if ($_task=='addressbook') {
+if ($RCMAIL->task=='addressbook') {
   include_once('program/steps/addressbook/func.inc');
 
-  if ($_action=='save')
+  if ($RCMAIL->action=='save')
     include('program/steps/addressbook/save.inc');
   
-  if ($_action=='edit' || $_action=='add')
+  if ($RCMAIL->action=='edit' || $RCMAIL->action=='add')
     include('program/steps/addressbook/edit.inc');
   
-  if ($_action=='delete')
+  if ($RCMAIL->action=='delete')
     include('program/steps/addressbook/delete.inc');
 
-  if ($_action=='show')
+  if ($RCMAIL->action=='show')
     include('program/steps/addressbook/show.inc');  
 
-  if ($_action=='list' && $_REQUEST['_remote'])
+  if ($RCMAIL->action=='list' && $_REQUEST['_remote'])
     include('program/steps/addressbook/list.inc');
 
-  if ($_action=='search')
+  if ($RCMAIL->action=='search')
     include('program/steps/addressbook/search.inc');
 
-  if ($_action=='copy')
+  if ($RCMAIL->action=='copy')
     include('program/steps/addressbook/copy.inc');
 
-  if ($_action=='mailto')
+  if ($RCMAIL->action=='mailto')
     include('program/steps/addressbook/mailto.inc');
 }
 
 
 // include task specific files
-if ($_task=='settings') {
+if ($RCMAIL->task=='settings') {
   include_once('program/steps/settings/func.inc');
 
-  if ($_action=='save-identity')
+  if ($RCMAIL->action=='save-identity')
     include('program/steps/settings/save_identity.inc');
 
-  if ($_action=='add-identity' || $_action=='edit-identity')
+  if ($RCMAIL->action=='add-identity' || $RCMAIL->action=='edit-identity')
     include('program/steps/settings/edit_identity.inc');
 
-  if ($_action=='delete-identity')
+  if ($RCMAIL->action=='delete-identity')
     include('program/steps/settings/delete_identity.inc');
   
-  if ($_action=='identities')
+  if ($RCMAIL->action=='identities')
     include('program/steps/settings/identities.inc');  
 
-  if ($_action=='save-prefs')
+  if ($RCMAIL->action=='save-prefs')
     include('program/steps/settings/save_prefs.inc');  
 
-  if ($_action=='folders' || $_action=='subscribe' || $_action=='unsubscribe' ||
-      $_action=='create-folder' || $_action=='rename-folder' || $_action=='delete-folder')
+  if ($RCMAIL->action=='folders' || $RCMAIL->action=='subscribe' || $RCMAIL->action=='unsubscribe' ||
+      $RCMAIL->action=='create-folder' || $RCMAIL->action=='rename-folder' || $RCMAIL->action=='delete-folder')
     include('program/steps/settings/manage_folders.inc');
 }
 
 
 // parse main template
-$OUTPUT->send($_task);
+$OUTPUT->send($RCMAIL->task);
 
 
 // if we arrive here, something went wrong
diff --git a/program/include/iniset.php b/program/include/iniset.php
index 926b282..5072d63 100755
--- a/program/include/iniset.php
+++ b/program/include/iniset.php
@@ -2,7 +2,7 @@
 
 /*
  +-----------------------------------------------------------------------+
- | program/include/iniset.inc                                            |
+ | program/include/iniset.php                                            |
  |                                                                       |
  | This file is part of the RoundCube Webmail client                     |
  | Copyright (C) 2008, RoundCube Dev, - Switzerland                      |
diff --git a/program/include/main.inc b/program/include/main.inc
index 853ca68..e152150 100644
--- a/program/include/main.inc
+++ b/program/include/main.inc
@@ -40,153 +40,6 @@
 
 
 /**
- * Initial startup function
- * to register session, create database and imap connections
- *
- * @param string Current task
- */
-function rcmail_startup($task='mail')
-  {
-  global $sess_id, $sess_user_lang;
-  global $CONFIG, $OUTPUT, $IMAP, $DB, $USER;
-
-  // start output buffering, we don't need any output yet, 
-  // it'll be cleared after reading of config files, etc.
-  ob_start();
-
-  // load configuration
-  $CONFIG = rcmail_load_config();
-
-  // set session domain
-  if (isset($CONFIG['session_domain']) && !empty($CONFIG['session_domain'])) {
-    ini_set('session.cookie_domain', $CONFIG['session_domain']);
-  }
-
-  // set session garbage collecting time according to session_lifetime
-  if (!empty($CONFIG['session_lifetime']))
-    ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
-
-  // prepare DB connection
-  $dbwrapper = empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend'];
-  $dbclass = "rcube_" . $dbwrapper;
-  
-  $DB = new $dbclass($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
-  $DB->sqlite_initials = INSTALL_PATH.'SQL/sqlite.initial.sql';
-  $DB->set_debug((bool)$CONFIG['sql_debug']);
-  $DB->db_connect('w');
-
-  // use database for storing session data
-  include_once('include/session.inc');
-
-  // clear output buffer
-  ob_end_clean();
-
-  // init session
-  session_start();
-  $sess_id = session_id();
-
-  // create session and set session vars
-  if (!isset($_SESSION['auth_time']))
-    {
-    $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
-    $_SESSION['auth_time'] = time();
-    $_SESSION['temp'] = true;
-    }
-
-  // set session vars global
-  $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
-
-  // create user object
-  $USER = new rcube_user($_SESSION['user_id']);
-
-  // overwrite config with user preferences
-  $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
-
-  // reset some session parameters when changing task
-  if ($_SESSION['task'] != $task)
-    unset($_SESSION['page']);
-
-  // set current task to session
-  $_SESSION['task'] = $task;
-
-  // create IMAP object
-  if ($task=='mail')
-    rcmail_imap_init();
-
-  // set localization
-  if ($CONFIG['locale_string'])
-    setlocale(LC_ALL, $CONFIG['locale_string']);
-  else if ($sess_user_lang)
-    setlocale(LC_ALL, $sess_user_lang);
-
-  register_shutdown_function('rcmail_shutdown');
-  }
-
-
-/**
- * Load roundcube configuration array
- *
- * @return array Named configuration parameters
- */
-function rcmail_load_config()
-  {
-  // load config file
-  include_once('config/main.inc.php');
-  $conf = is_array($rcmail_config) ? $rcmail_config : array();
-
-  // load host-specific configuration
-  rcmail_load_host_config($conf);
-
-  $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
-
-  // load db conf
-  include_once('config/db.inc.php');
-  $conf = array_merge($conf, $rcmail_config);
-
-  if (empty($conf['log_dir']))
-    $conf['log_dir'] = INSTALL_PATH.'logs';
-  else
-    $conf['log_dir'] = unslashify($conf['log_dir']);
-
-  // set PHP error logging according to config
-  if ($conf['debug_level'] & 1)
-    {
-    ini_set('log_errors', 1);
-    ini_set('error_log', $conf['log_dir'].'/errors');
-    }
-  if ($conf['debug_level'] & 4)
-    ini_set('display_errors', 1);
-  else
-    ini_set('display_errors', 0);
-
-  return $conf;
-  }
-
-
-/**
- * Load a host-specific config file if configured
- * This will merge the host specific configuration with the given one
- *
- * @param array Global configuration parameters
- */
-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 unique authorization hash
  *
  * @param string Session ID
@@ -246,84 +99,6 @@
   }
 
 
-/**
- * Create global IMAP object and connect to server
- *
- * @param boolean True if connection should be established
- */
-function rcmail_imap_init($connect=FALSE)
-  {
-  global $CONFIG, $DB, $IMAP, $OUTPUT;
-
-  $IMAP = new rcube_imap($DB);
-  $IMAP->debug_level = $CONFIG['debug_level'];
-  $IMAP->skip_deleted = $CONFIG['skip_deleted'];
-
-
-  // connect with stored session data
-  if ($connect)
-    {
-    if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
-      $OUTPUT->show_message('imaperror', 'error');
-      
-    rcmail_set_imap_prop();
-    }
-
-  // enable caching of imap data
-  if ($CONFIG['enable_caching']===TRUE)
-    $IMAP->set_caching(TRUE);
-
-  // set pagesize from config
-  if (isset($CONFIG['pagesize']))
-    $IMAP->set_pagesize($CONFIG['pagesize']);
-  }
-
-
-/**
- * Set root dir and last stored mailbox
- * This must be done AFTER connecting to the server!
- */
-function rcmail_set_imap_prop()
-  {
-  global $CONFIG, $IMAP;
-  
-  if (!empty($CONFIG['default_charset']))
-    $IMAP->set_charset($CONFIG['default_charset']);
-
-  // set root dir from config
-  if (!empty($CONFIG['imap_root']))
-    $IMAP->set_rootdir($CONFIG['imap_root']);
-
-  if (is_array($CONFIG['default_imap_folders']))
-    $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
-
-  if (!empty($_SESSION['mbox']))
-    $IMAP->set_mailbox($_SESSION['mbox']);
-  if (isset($_SESSION['page']))
-    $IMAP->set_page($_SESSION['page']);
-  }
-
-
-/**
- * Do these things on script shutdown
- */
-function rcmail_shutdown()
-  {
-  global $IMAP, $CONTACTS;
-  
-  if (is_object($IMAP))
-    {
-    $IMAP->close();
-    $IMAP->write_cache();
-    }
-    
-  if (is_object($CONTACTS))
-    $CONTACTS->close();
-    
-  // before closing the database connection, write session data
-  session_write_close();
-  }
-
 
 /**
  * Destroy session data and remove cookie
@@ -339,17 +114,18 @@
     $USER->save_prefs($a_user_prefs);
     }
 
-  $_SESSION = array('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
+  $_SESSION = array('language' => $USER->language, 'auth_time' => time(), 'temp' => true);
   setcookie('sessauth', '-del-', time()-60);
   $USER->reset();
   }
+
 
 /**
  * Do server side actions on logout
  */
 function rcmail_logout_actions()
   {
-  global $CONFIG, $IMAP;
+  global $CONFIG, $IMAP, $RCMAIL;
 
   // on logout action we're not connected to imap server  
   if (($CONFIG['logout_purge'] && !empty($CONFIG['trash_mbox'])) 
@@ -358,7 +134,7 @@
       if (!rcmail_authenticate_session())
         return;
 
-      rcmail_imap_init(true);
+      $RCMAIL->imap_init(true);
     }
 
   if ($CONFIG['logout_purge'] && !empty($CONFIG['trash_mbox']))
@@ -411,114 +187,6 @@
 
 
 /**
- * Check the given string and returns language properties
- *
- * @param string Language code
- * @param string Peropert name
- * @return string Property value
- */
-function rcube_language_prop($lang, $prop='lang')
-  {
-  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.
- * This will instantiate a rcmail_template object and set
- * environment vars according to the current session and configuration
- */
-function rcmail_load_gui()
-{
-  global $CONFIG, $OUTPUT, $sess_user_lang;
-
-  // init output page
-  $OUTPUT = new rcube_template($CONFIG, $GLOBALS['_task']);
-  $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
-
-  foreach (array('flag_for_deletion') as $js_config_var)
-    $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
-
-  if (!empty($GLOBALS['_framed']))
-    $OUTPUT->set_env('framed', true);
-
-  // set locale setting
-  rcmail_set_locale($sess_user_lang);
-
-  // set user-selected charset
-  if (!empty($CONFIG['charset']))
-    $OUTPUT->set_charset($CONFIG['charset']);
-    
-  // add some basic label to client
-  $OUTPUT->add_label('loading');
-}
-
-/**
- * Create an output object for JSON responses
- */
-function rcmail_init_json()
-{
-  global $CONFIG, $OUTPUT;
-  
-  // init output object
-  $OUTPUT = new rcube_json_output($CONFIG, $GLOBALS['_task']);
-
-  // set locale setting
-  rcmail_set_locale($sess_user_lang);
-}
-
-/**
- * Set localization charset based on the given language.
- * This also creates a global property for mbstring usage.
- */
-function rcmail_set_locale($lang)
-  {
-  global $OUTPUT, $MBSTRING;
-  static $s_mbstring_loaded = NULL;
-  
-  // settings for mbstring module (by Tadashi Jokagi)
-  if (is_null($s_mbstring_loaded)) 
-    $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring"); 
-  else
-    $MBSTRING = $s_mbstring_loaded = FALSE;
-  
-  if ($MBSTRING)
-    mb_internal_encoding(RCMAIL_CHARSET);
-
-  $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
-  }
-
-
-/**
  * Auto-select IMAP host based on the posted login information
  *
  * @return string Selected IMAP host
@@ -547,149 +215,6 @@
     }
   
   return $host;
-  }
-
-
-/**
- * Perfom login to the IMAP server and to the webmail service.
- * This will also create a new user entry if auto_create_user is configured.
- *
- * @param string IMAP user name
- * @param string IMAP password
- * @param string IMAP host
- * @return boolean True on success, False on failure
- */
-function rcmail_login($user, $pass, $host=NULL)
-  {
-  global $CONFIG, $IMAP, $DB, $USER, $sess_user_lang;
-  $user_id = NULL;
-  
-  if (!$host)
-    $host = $CONFIG['default_host'];
-
-  // Validate that selected host is in the list of configured hosts
-  if (is_array($CONFIG['default_host']))
-    {
-    $allowed = FALSE;
-    foreach ($CONFIG['default_host'] as $key => $host_allowed)
-      {
-      if (!is_numeric($key))
-        $host_allowed = $key;
-      if ($host == $host_allowed)
-        {
-        $allowed = TRUE;
-        break;
-        }
-      }
-    if (!$allowed)
-      return FALSE;
-    }
-  else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
-    return FALSE;
-
-  // parse $host URL
-  $a_host = parse_url($host);
-  if ($a_host['host'])
-    {
-    $host = $a_host['host'];
-    $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
-    $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
-    }
-  else
-    $imap_port = $CONFIG['default_port'];
-
-
-  /* Modify username with domain if required  
-     Inspired by Marco <P0L0_notspam_binware.org>
-  */
-  // Check if we need to add domain
-  if (!empty($CONFIG['username_domain']) && !strpos($user, '@'))
-    {
-    if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
-      $user .= '@'.$CONFIG['username_domain'][$host];
-    else if (is_string($CONFIG['username_domain']))
-      $user .= '@'.$CONFIG['username_domain'];
-    }
-
-  // try to resolve email address from virtuser table    
-  if (!empty($CONFIG['virtuser_file']) && strpos($user, '@'))
-    $user = rcube_user::email2user($user);
-
-  // lowercase username if it's an e-mail address (#1484473)
-  if (strpos($user, '@'))
-    $user = strtolower($user);
-
-  // query if user already registered
-  if ($existing = rcube_user::query($user, $host))
-    $USER = $existing;
-
-  // user already registered -> overwrite username
-  if ($USER->ID)
-    {
-    $user_id = $USER->ID;
-    $user = $USER->data['username'];
-    }
-
-  // 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)
-    {
-    // get user prefs
-    $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
-
-    // set user specific language
-    if (!empty($USER->data['language']))
-      $sess_user_lang = $_SESSION['user_lang'] = $USER->data['language'];
-      
-    // update user's record
-    $USER->touch();
-    }
-  // create new system user
-  else if ($CONFIG['auto_create_user'])
-    {
-    if ($created = rcube_user::create($user, $host))
-    {
-      $USER = $created;
-      
-      // get existing mailboxes
-      $a_mailboxes = $IMAP->list_mailboxes();
-    }
-    }
-  else
-    {
-    raise_error(array(
-      'code' => 600,
-      'type' => 'php',
-      'file' => "config/main.inc.php",
-      'message' => "Acces denied for new user $user. 'auto_create_user' is disabled"
-      ), true, false);
-    }
-
-  if ($USER->ID)
-    {
-    $_SESSION['user_id']   = $USER->ID;
-    $_SESSION['username']  = $USER->data['username'];
-    $_SESSION['imap_host'] = $host;
-    $_SESSION['imap_port'] = $imap_port;
-    $_SESSION['imap_ssl']  = $imap_ssl;
-    $_SESSION['user_lang'] = $sess_user_lang;
-    $_SESSION['password']  = encrypt_passwd($pass);
-    $_SESSION['login_time'] = mktime();
-
-    // force reloading complete list of subscribed mailboxes
-    rcmail_set_imap_prop();
-    $IMAP->clear_cache('mailboxes');
-
-    if ($CONFIG['create_default_folders'])
-        $IMAP->create_default_folders();
-
-    return TRUE;
-    }
-
-  return FALSE;
   }
 
 
@@ -745,9 +270,9 @@
  */
 function rcmail_overwrite_action($action)
   {
-  global $OUTPUT;
-  $GLOBALS['_action'] = $action;
-  $OUTPUT->set_env('action', $action);
+  $app = rcmail::get_instance();
+  $app->action = $action;
+  $app->output->set_env('action', $action);
   }
 
 
@@ -761,12 +286,13 @@
  */
 function rcmail_url($action, $p=array(), $task=null)
 {
-  global $MAIN_TASKS, $COMM_PATH;
-  $qstring = '';
-  $base = $COMM_PATH;
+  $app = rcmail::get_instance();
   
-  if ($task && in_array($task, $MAIN_TASKS))
-    $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
+  $qstring = '';
+  $base = $app->comm_path;
+  
+  if ($task && in_array($task, rcmail::$main_tasks))
+    $base = ereg_replace('_task=[a-z]+', '_task='.$task, $app->comm_path);
   
   if (is_array($p))
     foreach ($p as $key => $val)
@@ -964,8 +490,7 @@
  */
 function rcube_charset_convert($str, $from, $to=NULL)
   {
-  global $MBSTRING;
-  static $convert_warning = false;
+  static $mbstring_loaded = null, $convert_warning = false;
 
   $from = strtoupper($from);
   $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
@@ -989,8 +514,14 @@
     return iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
     }
 
-  // convert charset using mbstring module  
-  if ($MBSTRING)
+  // settings for mbstring module (by Tadashi Jokagi)
+  if (is_null($mbstring_loaded)) {
+    if ($mbstring_loaded = extension_loaded("mbstring"))
+      mb_internal_encoding(RCMAIL_CHARSET);
+  }
+
+  // convert charset using mbstring module
+  if ($mbstring_loaded)
     {
     $aliases['UTF-7'] = 'UTF7-IMAP';
     $aliases['WINDOWS-1257'] = 'ISO-8859-13';
@@ -1059,7 +590,7 @@
  */
 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
   {
-  global $OUTPUT_TYPE, $OUTPUT;
+  global $OUTPUT;
   static $html_encode_arr = false;
   static $js_rep_table = false;
   static $xml_rep_table = false;
@@ -1513,7 +1044,7 @@
  */
 function format_date($date, $format=NULL)
   {
-  global $CONFIG, $sess_user_lang;
+  global $CONFIG;
   
   $ts = NULL;
 
@@ -1524,11 +1055,11 @@
     while (($ts = @strtotime($date))===false)
       {
         // if we have a date in non-rfc format
-	// remove token from the end and try again
+        // remove token from the end and try again
         $d = explode(' ', $date);
-	array_pop($d);
-	if (!$d) break;
-	$date = implode(' ', $d);
+        array_pop($d);
+        if (!$d) break;
+        $date = implode(' ', $d);
       }
     }
 
@@ -1627,7 +1158,7 @@
 
   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
     write_log('console', $msg);
-  else if ($GLOBALS['REMOTE_REQUEST'])
+  else if ($GLOBALS['OUTPUT']->ajax_call)
     print "/*\n $msg \n*/\n";
   else
     {
diff --git a/program/include/rcmail.php b/program/include/rcmail.php
new file mode 100644
index 0000000..27ff182
--- /dev/null
+++ b/program/include/rcmail.php
@@ -0,0 +1,462 @@
+<?php
+
+/*
+ +-----------------------------------------------------------------------+
+ | program/include/rcmail.php                                            |
+ |                                                                       |
+ | This file is part of the RoundCube Webmail client                     |
+ | Copyright (C) 2008, RoundCube Dev. - Switzerland                      |
+ | Licensed under the GNU GPL                                            |
+ |                                                                       |
+ | PURPOSE:                                                              |
+ |   Application class providing core functions and holding              |
+ |   instances of all 'global' objects like db- and imap-connections     |
+ +-----------------------------------------------------------------------+
+ | Author: Thomas Bruederli <roundcube@gmail.com>                        |
+ +-----------------------------------------------------------------------+
+
+ $Id: rcube_browser.php 328 2006-08-30 17:41:21Z thomasb $
+
+*/
+
+
+/**
+ * Application class of RoundCube Webmail
+ * implemented as singleton
+ *
+ * @package Core
+ */
+class rcmail
+{
+  static public $main_tasks = array('mail','settings','addressbook','logout');
+  
+  static private $instance;
+  
+  public $config;
+  public $user;
+  public $db;
+  public $imap;
+  public $output;
+  public $task = 'mail';
+  public $action = '';
+  public $comm_path = './';
+  
+  private $texts;
+  
+  
+  /**
+   * This implements the 'singleton' design pattern
+   *
+   * @return object qvert The one and only instance
+   */
+  static function get_instance()
+  {
+    if (!self::$instance) {
+      self::$instance = new rcmail();
+      self::$instance->startup();  // init AFTER object was linked with self::$instance
+    }
+
+    return self::$instance;
+  }
+  
+  
+  /**
+   * Private constructor
+   *
+   * @todo Remove global $CONFIG
+   */
+  private function __construct()
+  {
+    // load configuration
+    $this->config = new rcube_config();
+    $GLOBALS['CONFIG'] = $this->config->all();
+    
+    register_shutdown_function(array($this, 'shutdown'));
+  }
+  
+  
+  /**
+   * Initial startup function
+   * to register session, create database and imap connections
+   *
+   * @todo Remove global vars $DB, $USER
+   */
+  private function startup()
+  {
+    $config_all = $this->config->all();
+
+    // set task and action properties
+    $this->set_task(strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC)));
+    $this->action = strip_quotes(get_input_value('_action', RCUBE_INPUT_GPC));
+
+    // connect to database
+    $GLOBALS['DB'] = $this->get_dbh();
+
+    // use database for storing session data
+    include_once('include/session.inc');
+
+    // set session domain
+    if (!empty($config_all['session_domain'])) {
+      ini_set('session.cookie_domain', $config_all['session_domain']);
+    }
+    // set session garbage collecting time according to session_lifetime
+    if (!empty($config_all['session_lifetime'])) {
+      ini_set('session.gc_maxlifetime', ($config_all['session_lifetime']) * 120);
+    }
+
+    // start PHP session
+    session_start();
+
+    // set initial session vars
+    if (!isset($_SESSION['auth_time'])) {
+      $_SESSION['auth_time'] = time();
+      $_SESSION['temp'] = true;
+    }
+
+
+    // create user object
+    $this->set_user(new rcube_user($_SESSION['user_id']));
+
+    // reset some session parameters when changing task
+    if ($_SESSION['task'] != $this->task)
+      unset($_SESSION['page']);
+
+    // set current task to session
+    $_SESSION['task'] = $this->task;
+
+    // create IMAP object
+    if ($this->task == 'mail')
+      $this->imap_init();
+  }
+  
+  
+  /**
+   * Setter for application task
+   *
+   * @param string Task to set
+   */
+  public function set_task($task)
+  {
+    if (!in_array($task, self::$main_tasks))
+      $task = 'mail';
+    
+    $this->task = $task;
+    $this->comm_path = './?_task=' . $task;
+    
+    if ($this->output)
+      $this->output->set_env('task', $task);
+  }
+  
+  
+  /**
+   * Setter for system user object
+   *
+   * @param object rcube_user Current user instance
+   */
+  public function set_user($user)
+  {
+    if (is_object($user)) {
+      $this->user = $user;
+      $GLOBALS['USER'] = $this->user;
+      
+      // overwrite config with user preferences
+      $this->config->merge((array)$this->user->get_prefs());
+    }
+    
+    $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language'));
+    
+    // set localization
+    setlocale(LC_ALL, $_SESSION['language']);
+  }
+  
+  
+  /**
+   * Check the given string and return a valid language code
+   *
+   * @param string Language code
+   * @return string Valid language code
+   */
+  private function language_prop($lang)
+  {
+    static $rcube_languages, $rcube_language_aliases;
+
+    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 = $this->language_prop(substr($lang, 0, 2));
+    }
+
+    if (!isset($rcube_languages[$lang])) {
+      $lang = 'en_US';
+    }
+
+    return $lang;
+  }
+  
+  
+  /**
+   * Get the current database connection
+   *
+   * @return object rcube_db  Database connection object
+   */
+  public function get_dbh()
+  {
+    if (!$this->db) {
+      $dbclass = "rcube_" . $this->config->get('db_backend', 'mdb2');
+      $config_all = $this->config->all();
+
+      $this->db = new $dbclass($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
+      $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
+      $this->db->set_debug((bool)$config_all['sql_debug']);
+      $this->db->db_connect('w');
+    }
+
+    return $this->db;
+  }
+  
+  
+  /**
+   * Init output object for GUI and add common scripts.
+   * This will instantiate a rcmail_template object and set
+   * environment vars according to the current session and configuration
+   */
+  public function load_gui($framed = false)
+  {
+    // init output page
+    $this->output = new rcube_template($this->task, $framed);
+
+    foreach (array('flag_for_deletion') as $js_config_var) {
+      $this->output->set_env($js_config_var, $this->config->get($js_config_var));
+    }
+
+    if ($framed) {
+      $this->comm_path .= '&_framed=1';
+      $this->output->set_env('framed', true);
+    }
+
+    $this->output->set_env('task', $this->task);
+    $this->output->set_env('action', $this->action);
+    $this->output->set_env('comm_path', $this->comm_path);
+    $this->output->set_charset($this->config->get('charset', RCMAIL_CHARSET));
+
+    // add some basic label to client
+    $this->output->add_label('loading');
+    
+    return $this->output;
+  }
+  
+  
+  /**
+   * Create an output object for JSON responses
+   */
+  public function init_json()
+  {
+    $this->output = new rcube_json_output($this->task);
+    
+    return $this->output;
+  }
+  
+  
+  /**
+   * Create global IMAP object and connect to server
+   *
+   * @param boolean True if connection should be established
+   * @todo Remove global $IMAP
+   */
+  function imap_init($connect = false)
+  {
+    $this->imap = new rcube_imap($this->db);
+    $this->imap->debug_level = $this->config->get('debug_level');
+    $this->imap->skip_deleted = $this->config->get('skip_deleted');
+
+    // connect with stored session data
+    if ($connect && $_SESSION['imap_host']) {
+      if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
+        ; #$OUTPUT->show_message('imaperror', 'error');
+
+      $this->set_imap_prop();
+    }
+
+    // enable caching of imap data
+    if ($this->config->get('enable_caching')) {
+      $this->imap->set_caching(true);
+    }
+
+    // set pagesize from config
+    $this->imap->set_pagesize($this->config->get('pagesize', 50));
+    
+    // set global object for backward compatibility
+    $GLOBALS['IMAP'] = $this->imap;
+  }
+
+
+  /**
+   * Perfom login to the IMAP server and to the webmail service.
+   * This will also create a new user entry if auto_create_user is configured.
+   *
+   * @param string IMAP user name
+   * @param string IMAP password
+   * @param string IMAP host
+   * @return boolean True on success, False on failure
+   */
+  function login($username, $pass, $host=NULL)
+  {
+    $user = NULL;
+    $config = $this->config->all();
+
+    if (!$host)
+      $host = $config['default_host'];
+
+    // Validate that selected host is in the list of configured hosts
+    if (is_array($config['default_host'])) {
+      $allowed = false;
+      foreach ($config['default_host'] as $key => $host_allowed) {
+        if (!is_numeric($key))
+          $host_allowed = $key;
+        if ($host == $host_allowed) {
+          $allowed = true;
+          break;
+        }
+      }
+      if (!$allowed)
+        return false;
+      }
+    else if (!empty($config['default_host']) && $host != $config['default_host'])
+      return false;
+
+    // parse $host URL
+    $a_host = parse_url($host);
+    if ($a_host['host']) {
+      $host = $a_host['host'];
+      $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
+      $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $config['default_port']);
+    }
+    else
+      $imap_port = $config['default_port'];
+
+
+    /* Modify username with domain if required  
+       Inspired by Marco <P0L0_notspam_binware.org>
+    */
+    // Check if we need to add domain
+    if (!empty($config['username_domain']) && !strpos($username, '@')) {
+      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
+        $username .= '@'.$config['username_domain'][$host];
+      else if (is_string($config['username_domain']))
+        $username .= '@'.$config['username_domain'];
+    }
+
+    // try to resolve email address from virtuser table    
+    if (!empty($config['virtuser_file']) && strpos($username, '@'))
+      $username = rcube_user::email2user($username);
+
+    // lowercase username if it's an e-mail address (#1484473)
+    if (strpos($username, '@'))
+      $username = strtolower($username);
+
+    // user already registered -> overwrite username
+    if ($user = rcube_user::query($username, $host))
+      $username = $user->data['username'];
+
+    // exit if IMAP login failed
+    if (!($imap_login  = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl)))
+      return false;
+
+    // user already registered -> update user's record
+    if (is_object($user)) {
+      $user->touch();
+    }
+    // create new system user
+    else if ($config['auto_create_user']) {
+      if ($created = rcube_user::create($username, $host)) {
+        $user = $created;
+
+        // get existing mailboxes (but why?)
+        // $a_mailboxes = $this->imap->list_mailboxes();
+      }
+    }
+    else {
+      raise_error(array(
+        'code' => 600,
+        'type' => 'php',
+        'file' => "config/main.inc.php",
+        'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
+        ), true, false);
+    }
+
+    // login succeeded
+    if (is_object($user) && $user->ID) {
+      $this->set_user($user);
+
+      // set session vars
+      $_SESSION['user_id']   = $user->ID;
+      $_SESSION['username']  = $user->data['username'];
+      $_SESSION['imap_host'] = $host;
+      $_SESSION['imap_port'] = $imap_port;
+      $_SESSION['imap_ssl']  = $imap_ssl;
+      $_SESSION['password']  = encrypt_passwd($pass);
+      $_SESSION['login_time'] = mktime();
+
+      // force reloading complete list of subscribed mailboxes
+      $this->set_imap_prop();
+      $this->imap->clear_cache('mailboxes');
+
+      if ($config['create_default_folders'])
+          $this->imap->create_default_folders();
+
+      return true;
+    }
+
+    return false;
+  }
+
+
+  /**
+   * Set root dir and last stored mailbox
+   * This must be done AFTER connecting to the server!
+   */
+  public function set_imap_prop()
+  {
+    $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
+
+    // set root dir from config
+    if ($imap_root = $this->config->get('imap_root')) {
+      $this->imap->set_rootdir($imap_root);
+    }
+    if ($default_folders = $this->config->get('default_imap_folders')) {
+      $this->imap->set_default_mailboxes($default_folders);
+    }
+    if (!empty($_SESSION['mbox'])) {
+      $this->imap->set_mailbox($_SESSION['mbox']);
+    }
+    if (isset($_SESSION['page'])) {
+      $this->imap->set_page($_SESSION['page']);
+    }
+  }
+
+  
+  public function shutdown()
+  {
+    if (is_object($this->imap)) {
+      $this->imap->close();
+      $this->imap->write_cache();
+    }
+
+    if (is_object($this->contacts))
+      $this->contacts->close();
+
+    // before closing the database connection, write session data
+    session_write_close();
+  }
+  
+}
+
+
diff --git a/program/include/rcube_config.php b/program/include/rcube_config.php
new file mode 100644
index 0000000..541767a
--- /dev/null
+++ b/program/include/rcube_config.php
@@ -0,0 +1,152 @@
+<?php
+
+/*
+ +-----------------------------------------------------------------------+
+ | program/include/rcube_config.php                                      |
+ |                                                                       |
+ | This file is part of the RoundCube Webmail client                     |
+ | Copyright (C) 2008, RoundCube Dev. - Switzerland                      |
+ | Licensed under the GNU GPL                                            |
+ |                                                                       |
+ | PURPOSE:                                                              |
+ |   Class to read configuration settings                                |
+ |                                                                       |
+ +-----------------------------------------------------------------------+
+ | Author: Thomas Bruederli <roundcube@gmail.com>                        |
+ +-----------------------------------------------------------------------+
+
+ $Id: $
+
+*/
+
+/**
+ * Configuration class for RoundCube
+ *
+ * @package Core
+ */
+class rcube_config
+{
+  private $prop = array();
+
+
+  /**
+   * Object constructor
+   */
+  public function __construct()
+  {
+    $this->load();
+  }
+
+
+  /**
+   * Load config from local config file
+   */
+  private function load()
+  {
+    // start output buffering, we don't need any output yet, 
+    // it'll be cleared after reading of config files, etc.
+    ob_start();
+    
+    // load main config file
+    include_once(INSTALL_PATH . 'config/main.inc.php');
+    $this->prop = (array)$rcmail_config;
+
+    // load database config
+    include_once(INSTALL_PATH . 'config/db.inc.php');
+    $this->prop += (array)$rcmail_config;
+
+    // fix paths
+    $this->prop['skin_path'] = $this->prop['skin_path'] ? unslashify($this->prop['skin_path']) : 'skins/default';
+    $this->prop['log_dir'] = $this->prop['log_dir'] ? unslashify($this->prop['log_dir']) : INSTALL_PATH . 'logs';
+    
+    // handle aliases
+    if (isset($this->prop['locale_string']) && empty($this->prop['language']))
+      $this->prop['language'] = $this->prop['locale_string'];
+
+    // set PHP error logging according to config
+    if ($this->prop['debug_level'] & 1) {
+      ini_set('log_errors', 1);
+      ini_set('error_log', $this->prop['log_dir'] . '/errors');
+    }
+    if ($this->prop['debug_level'] & 4) {
+      ini_set('display_errors', 1);
+    }
+    else {
+      ini_set('display_errors', 0);
+    }
+    
+    // clear output buffer
+    ob_end_clean();
+  }
+  
+  
+  /**
+   * Load a host-specific config file if configured
+   * This will merge the host specific configuration with the given one
+   */
+  private function load_host_config()
+  {
+    $fname = null;
+
+    if (is_array($this->prop['include_host_config'])) {
+      $fname = $this->prop['include_host_config'][$_SERVER['HTTP_HOST']];
+    }
+    else if (!empty($this->prop['include_host_config'])) {
+      $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
+    }
+
+    if ($fname && is_file(INSTALL_PATH . 'config/' . $fname)) {
+      include(INSTALL_PATH . 'config/' . $fname);
+      $this->prop = array_merge($this->prop, (array)$rcmail_config);
+    }
+  }
+  
+  
+  /**
+   * Getter for a specific config parameter
+   *
+   * @param  string Parameter name
+   * @param  mixed  Default value if not set
+   * @return mixed  The requested config value
+   */
+  public function get($name, $def = null)
+  {
+    return isset($this->prop[$name]) ? $this->prop[$name] : $def;
+  }
+  
+  
+  /**
+   * Setter for a config parameter
+   *
+   * @param string Parameter name
+   * @param mixed  Parameter value
+   */
+  public function set($name, $value)
+  {
+    $this->prop[$name] = $value;
+  }
+  
+  
+  /**
+   * Override config options with the given values (eg. user prefs)
+   *
+   * @param array Hash array with config props to merge over
+   */
+  public function merge($prefs)
+  {
+    $this->prop = array_merge($this->prop, $prefs);
+  }
+  
+  
+  /**
+   * Getter for all config options
+   *
+   * @return array  Hash array containg all config properties
+   */
+  public function all()
+  {
+    return $this->prop;
+  }
+  
+}
+
diff --git a/program/include/rcube_imap.php b/program/include/rcube_imap.php
index 2c6d142..4ac033a 100644
--- a/program/include/rcube_imap.php
+++ b/program/include/rcube_imap.php
@@ -465,7 +465,7 @@
     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      
+    // RECENT count is fetched a bit different
     if ($mode == 'RECENT')
        $count = iil_C_CheckForRecent($this->conn, $mailbox);
 
diff --git a/program/include/rcube_json_output.php b/program/include/rcube_json_output.php
index 802da24..19a4543 100644
--- a/program/include/rcube_json_output.php
+++ b/program/include/rcube_json_output.php
@@ -41,10 +41,10 @@
     /**
      * Constructor
      */
-    public function __construct(&$config, $task)
+    public function __construct($task)
     {
         $this->task   = $task;
-        $this->config = $config;
+        $this->config = rcmail::get_instance()->config;
     }
     
     
diff --git a/program/include/rcube_shared.inc b/program/include/rcube_shared.inc
index eed9662..03525b3 100644
--- a/program/include/rcube_shared.inc
+++ b/program/include/rcube_shared.inc
@@ -91,9 +91,11 @@
  */
 function rcube_label($attrib)
 {
-  global $sess_user_lang, $OUTPUT;
+  global $OUTPUT;
   static $sa_text_data = false;
   static $s_language, $utf8_decode;
+  
+  $sess_user_lang = $_SESSION['language'];
 
   // extract attributes
   if (is_string($attrib))
diff --git a/program/include/rcube_template.php b/program/include/rcube_template.php
index a76e378..df6c3cc 100755
--- a/program/include/rcube_template.php
+++ b/program/include/rcube_template.php
@@ -30,6 +30,7 @@
  */
 class rcube_template extends rcube_html_page
 {
+    var $app;
     var $config;
     var $task = '';
     var $framed = false;
@@ -45,13 +46,17 @@
      * Constructor
      *
      * @todo   Use jQuery's $(document).ready() here.
+     * @todo   Replace $this->config with the real rcube_config object
      */
-    public function __construct(&$config, $task)
+    public function __construct($task, $framed = false)
     {
         parent::__construct();
 
+        $this->app = rcmail::get_instance();
+        $this->config = $this->app->config->all();
+        
+        //$this->framed = $framed;
         $this->task = $task;
-        $this->config = $config;
 
         // add common javascripts
         $javascript = 'var '.JS_OBJECT_NAME.' = new rcube_webmail();';
@@ -348,7 +353,7 @@
      */
     private function parse_with_globals($input)
     {
-        $GLOBALS['__comm_path'] = Q($GLOBALS['COMM_PATH']);
+        $GLOBALS['__comm_path'] = Q($this->app->comm_path);
         return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
     }
 
@@ -609,7 +614,6 @@
      */
     private function button($attrib)
     {
-        global $CONFIG, $OUTPUT, $MAIN_TASKS;
         static $sa_buttons = array();
         static $s_button_count = 100;
 
@@ -692,7 +696,7 @@
             ));
 
             // make valid href to specific buttons
-            if (in_array($attrib['command'], $MAIN_TASKS)) {
+            if (in_array($attrib['command'], rcmail::$main_tasks)) {
                 $attrib['href'] = Q(rcmail_url(null, null, $attrib['command']));
             }
             else if (in_array($attrib['command'], $a_static_commands)) {
@@ -795,13 +799,35 @@
 
 
     /**
+     * Create a form tag with the necessary hidden fields
+     *
+     * @param array Named tag parameters
+     * @return string HTML code for the form
+     */
+    public function form_tag($attrib, $content = null)
+    {
+      if ($this->framed) {
+        $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
+        $hidden = $hiddenfield->show();
+      }
+      
+      if (!$content)
+        $attrib['noclose'] = true;
+      
+      return html::tag('form',
+        $attrib + array('action' => "./", 'method' => "get"),
+        $hidden . $content);
+    }
+
+
+    /**
      * GUI object 'username'
      * Showing IMAP username of the current session
      *
      * @param array Named tag parameters (currently not used)
      * @return string HTML code for the gui object
      */
-    static function current_username($attrib)
+    public function current_username($attrib)
     {
         global $USER;
         static $username;
@@ -835,8 +861,7 @@
      */
     private function login_form($attrib)
     {
-        global $CONFIG, $SESS_HIDDEN_FIELD;
-        $default_host = $CONFIG['default_host'];
+        $default_host = $this->config['default_host'];
 
         $_SESSION['temp'] = true;
 
@@ -880,20 +905,12 @@
             $table->add(null, $input_host->show(get_input_value('_host', RCUVE_INPUT_POST)));
         }
 
-        $out = $SESS_HIDDEN_FIELD;
-        $out .= $input_action->show();
+        $out = $input_action->show();
         $out .= $table->show();
 
         // surround html output with a form tag
         if (empty($attrib['form'])) {
-            $out = html::tag(
-                'form',
-                array(
-                    'name' => $form_name,
-                    'action' => "./",
-                    'method' => "post"
-                ),
-            $out);
+            $out = $this->form_tag(array('name' => $form_name, 'method' => "post"), $out);
         }
 
         return $out;
@@ -924,15 +941,11 @@
 
         // add form tag around text field
         if (empty($attrib['form'])) {
-            $out = html::tag(
-                'form',
-                array(
-                    'name' => "rcmqsearchform",
-                    'action' => "./",
-                    'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
-                    'style' => "display:inline",
-                ),
-            $out);
+            $out = $this->form_tag(array(
+                'name' => "rcmqsearchform",
+                'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
+                'style' => "display:inline"),
+              $out);
         }
 
         return $out;
diff --git a/program/include/rcube_user.php b/program/include/rcube_user.php
index e748758..e125f63 100644
--- a/program/include/rcube_user.php
+++ b/program/include/rcube_user.php
@@ -29,8 +29,11 @@
  */
 class rcube_user
 {
-  var $ID = null;
-  var $data = null;
+  public $ID = null;
+  public $data = null;
+  public $language = 'en_US';
+  
+  private $db = null;
   
   
   /**
@@ -40,18 +43,19 @@
    */
   function __construct($id = null, $sql_arr = null)
   {
-    global $DB;
+    $this->db = rcmail::get_instance()->get_dbh();
     
     if ($id && !$sql_arr)
     {
-      $sql_result = $DB->query("SELECT * FROM ".get_table_name('users')." WHERE  user_id=?", $id);
-      $sql_arr = $DB->fetch_assoc($sql_result);
+      $sql_result = $this->db->query("SELECT * FROM ".get_table_name('users')." WHERE  user_id=?", $id);
+      $sql_arr = $this->db->fetch_assoc($sql_result);
     }
     
     if (!empty($sql_arr))
     {
       $this->ID = $sql_arr['user_id'];
       $this->data = $sql_arr;
+      $this->language = $sql_arr['language'];
     }
   }
 
@@ -85,7 +89,7 @@
   function get_prefs()
   {
     if ($this->ID && $this->data['preferences'])
-      return unserialize($this->data['preferences']);
+      return array('language' => $this->language) + unserialize($this->data['preferences']);
     else
       return array();
   }
@@ -99,26 +103,26 @@
    */
   function save_prefs($a_user_prefs)
   {
-    global $DB, $CONFIG, $sess_user_lang;
-    
     if (!$this->ID)
       return false;
 
     // merge (partial) prefs array with existing settings
     $a_user_prefs += (array)$this->get_prefs();
+    unset($a_user_prefs['language']);
 
-    $DB->query(
+    $this->db->query(
       "UPDATE ".get_table_name('users')."
        SET    preferences=?,
               language=?
        WHERE  user_id=?",
       serialize($a_user_prefs),
-      $sess_user_lang,
+      $_SESSION['language'],
       $this->ID);
 
-    if ($DB->affected_rows())
+    $this->language = $_SESSION['language'];
+    if ($this->db->affected_rows())
     {
-      $CONFIG = array_merge($CONFIG, $a_user_prefs);
+      rcmail::get_instance()->config->merge($a_user_prefs);
       return true;
     }
 
@@ -134,10 +138,8 @@
    */
   function get_identity($id = null)
   {
-    global $DB;
-    
     $sql_result = $this->list_identities($id ? sprintf('AND identity_id=%d', $id) : '');
-    return $DB->fetch_assoc($sql_result);
+    return $this->db->fetch_assoc($sql_result);
   }
   
   
@@ -148,15 +150,13 @@
    */
   function list_identities($sql_add = '')
   {
-    global $DB;
-    
     // get contacts from DB
-    $sql_result = $DB->query(
+    $sql_result = $this->db->query(
       "SELECT * FROM ".get_table_name('identities')."
        WHERE  del<>1
        AND    user_id=?
        $sql_add
-       ORDER BY ".$DB->quoteIdentifier('standard')." DESC, name ASC",
+       ORDER BY ".$this->db->quoteIdentifier('standard')." DESC, name ASC",
       $this->ID);
     
     return $sql_result;
@@ -172,8 +172,6 @@
    */
   function update_identity($iid, $data)
   {
-    global $DB;
-    
     if (!$this->ID)
       return false;
     
@@ -182,11 +180,11 @@
     foreach ((array)$data as $col => $value)
     {
       $write_sql[] = sprintf("%s=%s",
-        $DB->quoteIdentifier($col),
-        $DB->quote($value));
+        $this->db->quoteIdentifier($col),
+        $this->db->quote($value));
     }
     
-    $DB->query(
+    $this->db->query(
       "UPDATE ".get_table_name('identities')."
        SET ".join(', ', $write_sql)."
        WHERE  identity_id=?
@@ -195,7 +193,7 @@
       $iid,
       $this->ID);
     
-    return $DB->affected_rows();
+    return $this->db->affected_rows();
   }
   
   
@@ -207,25 +205,23 @@
    */
   function insert_identity($data)
   {
-    global $DB;
-    
     if (!$this->ID)
       return false;
 
     $insert_cols = $insert_values = array();
     foreach ((array)$data as $col => $value)
     {
-      $insert_cols[] = $DB->quoteIdentifier($col);
-      $insert_values[] = $DB->quote($value);
+      $insert_cols[] = $this->db->quoteIdentifier($col);
+      $insert_values[] = $this->db->quote($value);
     }
 
-    $DB->query(
+    $this->db->query(
       "INSERT INTO ".get_table_name('identities')."
         (user_id, ".join(', ', $insert_cols).")
        VALUES (?, ".join(', ', $insert_values).")",
       $this->ID);
 
-    return $DB->insert_id(get_sequence_name('identities'));
+    return $this->db->insert_id(get_sequence_name('identities'));
   }
   
   
@@ -237,24 +233,22 @@
    */
   function delete_identity($iid)
   {
-    global $DB;
-    
     if (!$this->ID)
       return false;
 
     if (!$this->ID || $this->ID == '')
       return false;
 
-    $sql_result = $DB->query("SELECT count(*) AS ident_count FROM " .
+    $sql_result = $this->db->query("SELECT count(*) AS ident_count FROM " .
       get_table_name('identities') .
       " WHERE user_id = ? AND del <> 1",
       $this->ID);
 
-    $sql_arr = $DB->fetch_assoc($sql_result);
+    $sql_arr = $this->db->fetch_assoc($sql_result);
     if ($sql_arr['ident_count'] <= 1)
       return false;
     
-    $DB->query(
+    $this->db->query(
       "UPDATE ".get_table_name('identities')."
        SET    del=1
        WHERE  user_id=?
@@ -262,7 +256,7 @@
       $this->ID,
       $iid);
 
-    return $DB->affected_rows();
+    return $this->db->affected_rows();
   }
   
   
@@ -273,13 +267,11 @@
    */
   function set_default($iid)
   {
-    global $DB;
-    
     if ($this->ID && $iid)
     {
-      $DB->query(
+      $this->db->query(
         "UPDATE ".get_table_name('identities')."
-         SET ".$DB->quoteIdentifier('standard')."='0'
+         SET ".$this->db->quoteIdentifier('standard')."='0'
          WHERE  user_id=?
          AND    identity_id<>?
          AND    del<>1",
@@ -294,13 +286,11 @@
    */
   function touch()
   {
-    global $DB;
-    
     if ($this->ID)
     {
-      $DB->query(
+      $this->db->query(
         "UPDATE ".get_table_name('users')."
-         SET    last_login=".$DB->now()."
+         SET    last_login=".$this->db->now()."
          WHERE  user_id=?",
         $this->ID);
     }
@@ -323,14 +313,13 @@
    * @param string IMAP user name
    * @param string IMAP host name
    * @return object rcube_user New user instance
-   * @static
    */
-  function query($user, $host)
+  static function query($user, $host)
   {
-    global $DB;
+    $dbh = rcmail::get_instance()->get_dbh();
     
     // query if user already registered
-    $sql_result = $DB->query(
+    $sql_result = $dbh->query(
       "SELECT * FROM ".get_table_name('users')."
        WHERE  mail_host=? AND (username=? OR alias=?)",
       $host,
@@ -338,7 +327,7 @@
       $user);
       
     // user already registered -> overwrite username
-    if ($sql_arr = $DB->fetch_assoc($sql_result))
+    if ($sql_arr = $dbh->fetch_assoc($sql_result))
       return new rcube_user($sql_arr['user_id'], $sql_arr);
     else
       return false;
@@ -351,28 +340,27 @@
    * @param string IMAP user name
    * @param string IMAP host
    * @return object rcube_user New user instance
-   * @static
    */
-  function create($user, $host)
+  static function create($user, $host)
   {
-    global $DB, $CONFIG;
-    
     $user_email = '';
+    $rcmail = rcmail::get_instance();
+    $dbh = $rcmail->get_dbh();
 
     // try to resolve user in virtusertable
-    if (!empty($CONFIG['virtuser_file']) && !strpos($user, '@'))
+    if ($rcmail->config->get('virtuser_file') && !strpos($user, '@'))
       $user_email = rcube_user::user2email($user);
 
-    $DB->query(
+    $dbh->query(
       "INSERT INTO ".get_table_name('users')."
         (created, last_login, username, mail_host, alias, language)
-       VALUES (".$DB->now().", ".$DB->now().", ?, ?, ?, ?)",
+       VALUES (".$dbh->now().", ".$dbh->now().", ?, ?, ?, ?)",
       strip_newlines($user),
       strip_newlines($host),
       strip_newlines($user_email),
-      $_SESSION['user_lang']);
+      $_SESSION['language']);
 
-    if ($user_id = $DB->insert_id(get_sequence_name('users')))
+    if ($user_id = $dbh->insert_id(get_sequence_name('users')))
     {
       $mail_domain = rcmail_mail_domain($host);
 
@@ -382,13 +370,13 @@
       $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/', $DB->escapeSimple($user), $CONFIG['virtuser_query']))) &&
-          ($DB->num_rows()>0))
+      if ($virtuser_query = $rcmail->config->get('virtuser_query') &&
+          ($sql_result = $dbh->query(preg_replace('/%u/', $dbh->escapeSimple($user), $virtuser_query))) &&
+          ($dbh->num_rows() > 0))
       {
-        while ($sql_arr = $DB->fetch_array($sql_result))
+        while ($sql_arr = $dbh->fetch_array($sql_result))
         {
-          $DB->query(
+          $dbh->query(
             "INSERT INTO ".get_table_name('identities')."
               (user_id, del, standard, name, email)
              VALUES (?, 0, 1, ?, ?)",
@@ -400,7 +388,7 @@
       else
       {
         // also create new identity records
-        $DB->query(
+        $dbh->query(
           "INSERT INTO ".get_table_name('identities')."
             (user_id, del, standard, name, email)
            VALUES (?, 0, 1, ?, ?)",
@@ -428,9 +416,8 @@
    *
    * @param string E-mail address to resolve
    * @return string Resolved IMAP username
-   * @static
    */
-  function email2user($email)
+  static function email2user($email)
   {
     $user = $email;
     $r = rcmail_findinvirtual("^$email");
@@ -455,9 +442,8 @@
    *
    * @param string User name
    * @return string Resolved e-mail address
-   * @static
    */
-  function user2email($user)
+  static function user2email($user)
   {
     $email = "";
     $r = rcmail_findinvirtual("$user$");
@@ -479,4 +465,3 @@
 }
 
 
-?>
diff --git a/program/steps/addressbook/edit.inc b/program/steps/addressbook/edit.inc
index e3218a3..64eab86 100644
--- a/program/steps/addressbook/edit.inc
+++ b/program/steps/addressbook/edit.inc
@@ -33,10 +33,10 @@
 
 function rcmail_contact_editform($attrib)
 {
-  global $CONTACTS, $OUTPUT;
+  global $RCMAIL, $CONTACTS, $OUTPUT;
 
   // check if we have a valid result
-  if ($GLOBALS['_action'] != 'add' && !(($result = $CONTACTS->get_result()) && ($record = $result->first())))
+  if ($RCMAIL->action != 'add' && !(($result = $CONTACTS->get_result()) && ($record = $result->first())))
   {
     $OUTPUT->show_message('contactnotfound');
     return false;
@@ -83,20 +83,19 @@
 // similar function as in /steps/settings/edit_identity.inc
 function get_form_tags($attrib)
   {
-  global $CONTACTS, $OUTPUT, $EDIT_FORM, $SESS_HIDDEN_FIELD;  
+  global $CONTACTS, $EDIT_FORM, $RCMAIL;
 
   $result = $CONTACTS->get_result();
   $form_start = '';
   if (!strlen($EDIT_FORM))
     {
-    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $GLOBALS['_task']));
+    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
     $hiddenfields->add(array('name' => '_action', 'value' => 'save', 'source' => get_input_value('_source', RCUBE_INPUT_GPC)));
     
     if (($result = $CONTACTS->get_result()) && ($record = $result->first()))
       $hiddenfields->add(array('name' => '_cid', 'value' => $record['ID']));
     
-    $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
-    $form_start .= "\n$SESS_HIDDEN_FIELD\n";
+    $form_start = !strlen($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
     $form_start .= $hiddenfields->show();
     }
     
@@ -104,11 +103,11 @@
   $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
   
   if (!strlen($EDIT_FORM))
-    $OUTPUT->add_gui_object('editform', $form_name);
+    $RCMAIL->output->add_gui_object('editform', $form_name);
   
   $EDIT_FORM = $form_name;
 
-  return array($form_start, $form_end);  
+  return array($form_start, $form_end); 
   }
 
 
diff --git a/program/steps/addressbook/save.inc b/program/steps/addressbook/save.inc
index c16d472..94a0d58 100644
--- a/program/steps/addressbook/save.inc
+++ b/program/steps/addressbook/save.inc
@@ -28,7 +28,7 @@
 }
 
 // check input
-if ((!get_input_value('_name', RCUBE_INPUT_POST) || !get_input_value('_email', RCUBE_INPUT_POST)) && $_framed)
+if ((!get_input_value('_name', RCUBE_INPUT_POST) || !get_input_value('_email', RCUBE_INPUT_POST)) && $OUTPUT->action)
 {
   $OUTPUT->show_message('formincomplete', 'warning');
   rcmail_overwrite_action(empty($_POST['_cid']) ? 'add' : 'show');
@@ -54,7 +54,7 @@
 {
   if ($CONTACTS->update($cid, $a_record))
   {
-    if ($_framed)
+    if ($OUTPUT->action)
     {
       // define list of cols to be displayed
       $a_js_cols = array();
@@ -96,7 +96,7 @@
   // insert record and send response
   if ($insert_id = $CONTACTS->insert($a_record))
   {
-    if ($_framed)
+    if ($OUTPUT->action)
     {
       // add contact row or jump to the page where it should appear
       $CONTACTS->reset();
diff --git a/program/steps/mail/compose.inc b/program/steps/mail/compose.inc
index 1189c99..d8ade67 100644
--- a/program/steps/mail/compose.inc
+++ b/program/steps/mail/compose.inc
@@ -26,7 +26,7 @@
 
 
 // remove an attachment
-if ($_action=='remove-attachment' && preg_match('/^rcmfile([0-9]+)$/', $_POST['_file'], $regs))
+if ($RCMAIL->action=='remove-attachment' && preg_match('/^rcmfile([0-9]+)$/', $_POST['_file'], $regs))
 {
   $id = $regs[1];
   if (is_array($_SESSION['compose']['attachments'][$id]))
@@ -39,7 +39,7 @@
   }
 }
 
-if ($_action=='display-attachment' && preg_match('/^rcmfile([0-9]+)$/', $_GET['_file'], $regs))
+if ($RCMAIL->action=='display-attachment' && preg_match('/^rcmfile([0-9]+)$/', $_GET['_file'], $regs))
 {
   $id = $regs[1];
   if (is_array($_SESSION['compose']['attachments'][$id]))
@@ -337,7 +337,7 @@
 
 function rcmail_compose_body($attrib)
 {
-  global $CONFIG, $OUTPUT, $MESSAGE, $compose_mode;
+  global $RCMAIL, $CONFIG, $OUTPUT, $MESSAGE, $compose_mode;
   
   list($form_start, $form_end) = get_form_tags($attrib);
   unset($attrib['form']);
@@ -410,7 +410,7 @@
     $body = rcmail_create_draft_body($body, $isHtml);
     }
 
-  $tinylang = substr($_SESSION['user_lang'], 0, 2); 
+  $tinylang = substr($_SESSION['language'], 0, 2);
   if (!file_exists('program/js/tiny_mce/langs/'.$tinylang.'.js'))
     { 
     $tinylang = 'en'; 
@@ -455,14 +455,14 @@
       "googie.setCurrentLanguage('%s');\n".
       "googie.decorateTextarea('%s');\n".
       "%s.set_env('spellcheck', googie);",
-      $GLOBALS['COMM_PATH'],
+      $RCMAIL->comm_path,
       JQ(Q(rcube_label('checkspelling'))),
       JQ(Q(rcube_label('resumeediting'))),
       JQ(Q(rcube_label('close'))),
       JQ(Q(rcube_label('revertto'))),
       JQ(Q(rcube_label('nospellerrors'))),
       $lang_set,
-      substr($_SESSION['user_lang'], 0, 2),
+      substr($_SESSION['language'], 0, 2),
       $attrib['id'],
       JS_OBJECT_NAME), 'foot');
 
@@ -704,30 +704,21 @@
 
 function rcmail_compose_attachment_form($attrib)
 {
-  global $OUTPUT, $SESS_HIDDEN_FIELD;
+  global $OUTPUT;
 
   // add ID if not given
   if (!$attrib['id'])
     $attrib['id'] = 'rcmUploadbox';
   
-  // allow the following attributes to be added to the <div> tag
-  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style'));
-  $input_field = rcmail_compose_attachment_field(array());
-  $label_send = rcube_label('upload');
-  $label_close = rcube_label('close');
-  $js_instance = JS_OBJECT_NAME;
+  $button = new html_inputfield(array('type' => "button", 'class' => "button"));
   
-  $out = <<<EOF
-<div$attrib_str>
-<form action="./" method="post" enctype="multipart/form-data">
-$SESS_HIDDEN_FIELD
-$input_field<br />
-<input type="button" value="$label_close" class="button" onclick="document.getElementById('$attrib[id]').style.visibility='hidden'" />
-<input type="button" value="$label_send" class="button" onclick="$js_instance.command('send-attachment', this.form)" />
-</form>
-</div>
-EOF;
-
+  $out = html::div($attrib,
+    $OUTPUT->form_tag(array('name' => "form", 'method' => "post")) .
+    rcmail_compose_attachment_field(array()) . html::br() .
+    $button->show(rcube_label('close'), array('onclick' => "document.getElementById('$attrib[id]').style.visibility='hidden'")) .
+    $button->show(rcube_label('upload'), array('onclick' => JS_OBJECT_NAME . ".command('send-attachment', this.form)"))
+  );
+  
   
   $OUTPUT->add_gui_object('uploadbox', $attrib['id']);
   return $out;
@@ -843,16 +834,15 @@
 
 function get_form_tags($attrib)
 {
-  global $CONFIG, $OUTPUT, $MESSAGE_FORM, $SESS_HIDDEN_FIELD;  
+  global $RCMAIL, $MESSAGE_FORM;
 
   $form_start = '';
   if (!strlen($MESSAGE_FORM))
   {
-    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $GLOBALS['_task']));
+    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
     $hiddenfields->add(array('name' => '_action', 'value' => 'send'));
 
-    $form_start = empty($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
-    $form_start .= "\n$SESS_HIDDEN_FIELD\n";
+    $form_start = empty($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
     $form_start .= $hiddenfields->show();
   }
     
@@ -860,7 +850,7 @@
   $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
   
   if (!strlen($MESSAGE_FORM))
-    $OUTPUT->add_gui_object('messageform', $form_name);
+    $RCMAIL->output->add_gui_object('messageform', $form_name);
   
   $MESSAGE_FORM = $form_name;
 
diff --git a/program/steps/mail/folders.inc b/program/steps/mail/folders.inc
index b84398f..69f3c0e 100644
--- a/program/steps/mail/folders.inc
+++ b/program/steps/mail/folders.inc
@@ -21,7 +21,7 @@
 $mbox_name = $IMAP->get_mailbox_name();
 
 // send EXPUNGE command
-if ($_action=='expunge' && ($mbox = get_input_value('_mbox', RCUBE_INPUT_POST)))
+if ($RCMAIL->action=='expunge' && ($mbox = get_input_value('_mbox', RCUBE_INPUT_POST)))
 {
   $success = $IMAP->expunge($mbox);
 
@@ -29,7 +29,7 @@
   if ($success && !empty($_REQUEST['_reload']))
   {
     $OUTPUT->command('message_list.clear');
-    $_action = 'list';
+    $RCMAIL->action = 'list';
     return;
   }
   else
@@ -37,7 +37,7 @@
 }
 
 // clear mailbox
-else if ($_action=='purge' && ($mbox = get_input_value('_mbox', RCUBE_INPUT_POST)))
+else if ($RCMAIL->action=='purge' && ($mbox = get_input_value('_mbox', RCUBE_INPUT_POST)))
 {
   // we should only be purging trash and junk
   if($mbox == $CONFIG['trash_mbox'] || $mbox == $CONFIG['junk_mbox']) 
diff --git a/program/steps/mail/func.inc b/program/steps/mail/func.inc
index 8abda6c..9a81a00 100644
--- a/program/steps/mail/func.inc
+++ b/program/steps/mail/func.inc
@@ -74,7 +74,7 @@
   rcube_add_label('checkingmail', 'deletemessage', 'movemessagetotrash', 'movingmessage');
 
 // set page title
-if (empty($_action) || $_action == 'list')
+if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
   $OUTPUT->set_pagetitle(rcmail_localize_foldername($IMAP->get_mailbox_name()));
 
 
diff --git a/program/steps/mail/move_del.inc b/program/steps/mail/move_del.inc
index 131ad2e..dad3ce7 100644
--- a/program/steps/mail/move_del.inc
+++ b/program/steps/mail/move_del.inc
@@ -24,7 +24,7 @@
 $old_pages = ceil($old_count / $IMAP->page_size);
 
 // move messages
-if ($_action=='moveto' && !empty($_POST['_uid']) && !empty($_POST['_target_mbox']))
+if ($RCMAIL->action=='moveto' && !empty($_POST['_uid']) && !empty($_POST['_target_mbox']))
 {
   $count = sizeof(explode(',', ($uids = get_input_value('_uid', RCUBE_INPUT_POST))));
   $target = get_input_value('_target_mbox', RCUBE_INPUT_POST);
@@ -41,7 +41,7 @@
 }
 
 // delete messages 
-else if ($_action=='delete' && !empty($_POST['_uid']))
+else if ($RCMAIL->action=='delete' && !empty($_POST['_uid']))
 {
   $count = sizeof(explode(',', ($uids = get_input_value('_uid', RCUBE_INPUT_POST))));
   $del = $IMAP->delete_message($uids, get_input_value('_mbox', RCUBE_INPUT_POST));
@@ -89,7 +89,7 @@
 $mbox = $IMAP->get_mailbox_name();
 $OUTPUT->command('set_unread_count', $mbox, $IMAP->messagecount($mbox, 'UNSEEN'), ($mbox == 'INBOX'));
 
-if ($_action=='moveto' && $target)
+if ($RCMAIL->action=='moveto' && $target)
   $OUTPUT->command('set_unread_count', $target, $IMAP->messagecount($target, 'UNSEEN'));
 
 $OUTPUT->command('set_quota', rcmail_quota_content($IMAP->get_quota()));
diff --git a/program/steps/mail/sendmail.inc b/program/steps/mail/sendmail.inc
index 2281a97..72ef9f4 100644
--- a/program/steps/mail/sendmail.inc
+++ b/program/steps/mail/sendmail.inc
@@ -313,7 +313,7 @@
 ));
 
 // encoding subject header with mb_encode provides better results with asian characters
-if ($MBSTRING && function_exists("mb_encode_mimeheader"))
+if (function_exists("mb_encode_mimeheader"))
 {
   mb_internal_encoding($message_charset);
   $headers['Subject'] = mb_encode_mimeheader($headers['Subject'], $message_charset, 'Q');
diff --git a/program/steps/mail/show.inc b/program/steps/mail/show.inc
index a530184..8062f45 100644
--- a/program/steps/mail/show.inc
+++ b/program/steps/mail/show.inc
@@ -19,7 +19,7 @@
 
 */
 
-$PRINT_MODE = $_action=='print' ? TRUE : FALSE;
+$PRINT_MODE = $RCMAIL->action=='print' ? TRUE : FALSE;
 
 // similar code as in program/steps/mail/get.inc
 if ($_GET['_uid'])
@@ -35,11 +35,11 @@
   if (!$MESSAGE['headers'])
     {
     $OUTPUT->show_message('messageopenerror', 'error');
-    if ($_action=='preview' && template_exists('messagepreview'))
+    if ($RCMAIL->action=='preview' && template_exists('messagepreview'))
         $OUTPUT->send('messagepreview');
     else
       {
-      $_action = 'list';
+      $RCMAIL->action = 'list';
       return;
       }
     }
@@ -78,7 +78,7 @@
   if (!$MESSAGE['headers']->seen)
   {
     $marked = $IMAP->set_flag($MESSAGE['UID'], 'SEEN');
-    if($_action == 'preview' && $marked != -1)
+    if($RCMAIL->action == 'preview' && $marked != -1)
     {
       $OUTPUT->command('set_unread_count_from_preview', $mbox_name, $IMAP->messagecount($mbox_name, 'UNSEEN'), ($mbox_name == 'INBOX'));
       $OUTPUT->command('mark_as_read_from_preview', $MESSAGE['UID']);
@@ -203,9 +203,9 @@
   'blockedobjects' => 'rcmail_remote_objects_msg'));
 
 
-if ($_action=='print' && template_exists('printmessage'))
+if ($RCMAIL->action=='print' && template_exists('printmessage'))
   $OUTPUT->send('printmessage');
-else if ($_action=='preview' && template_exists('messagepreview'))
+else if ($RCMAIL->action=='preview' && template_exists('messagepreview'))
     $OUTPUT->send('messagepreview');
 else
   $OUTPUT->send('message');
diff --git a/program/steps/settings/edit_identity.inc b/program/steps/settings/edit_identity.inc
index 2dec5b2..0f849f1 100644
--- a/program/steps/settings/edit_identity.inc
+++ b/program/steps/settings/edit_identity.inc
@@ -19,7 +19,7 @@
 
 */
 
-if (($_GET['_iid'] || $_POST['_iid']) && $_action=='edit-identity')
+if (($_GET['_iid'] || $_POST['_iid']) && $RCMAIL->action=='edit-identity')
   {
   $IDENTITY_RECORD = $USER->get_identity(get_input_value('_iid', RCUBE_INPUT_GPC));
   
@@ -37,9 +37,9 @@
 
 function rcube_identity_form($attrib)
   {
-  global $IDENTITY_RECORD, $OUTPUT;
+  global $IDENTITY_RECORD, $RCMAIL, $OUTPUT;
 
-  $tinylang = substr($_SESSION['user_lang'], 0, 2);
+  $tinylang = substr($_SESSION['language'], 0, 2);
   if (!file_exists('program/js/tiny_mce/langs/'.$tinylang.'.js'))
     {
       $tinylang = 'en';
@@ -58,7 +58,7 @@
                                     "theme_advanced_buttons2 : 'link,unlink,code,forecolor,fontselect,fontsizeselect'," .
                                     "theme_advanced_buttons3 : '' });");
 
-  if (!$IDENTITY_RECORD && $GLOBALS['_action']!='add-identity')
+  if (!$IDENTITY_RECORD && $RCMAIL->action != 'add-identity')
     return rcube_label('notfound');
 
   // add some labels to client
@@ -138,7 +138,7 @@
 
 $OUTPUT->add_handler('identityform', 'rcube_identity_form');
 
-if ($_action=='add-identity' && template_exists('addidentity'))
+if ($RCMAIL->action=='add-identity' && template_exists('addidentity'))
   $OUTPUT->send('addidentity');
 
 $OUTPUT->send('editidentity');
diff --git a/program/steps/settings/func.inc b/program/steps/settings/func.inc
index bf889a5..09ae6cf 100644
--- a/program/steps/settings/func.inc
+++ b/program/steps/settings/func.inc
@@ -27,7 +27,7 @@
 
 function rcmail_user_prefs_form($attrib)
   {
-  global $DB, $CONFIG, $sess_user_lang;
+  global $DB, $CONFIG;
 
   $no_override = is_array($CONFIG['dont_override']) ? array_flip($CONFIG['dont_override']) : array();
 
@@ -56,7 +56,7 @@
     $out .= sprintf("<tr><td class=\"title\"><label for=\"%s\">%s</label></td><td>%s</td></tr>\n",
                     $field_id,
                     Q(rcube_label('language')),
-                    $select_lang->show($sess_user_lang));
+                    $select_lang->show($_SESSION['language']));
     }
 
 
@@ -251,19 +251,18 @@
 // similar function as in /steps/addressbook/edit.inc
 function get_form_tags($attrib, $action, $add_hidden=array())
   {
-  global $OUTPUT, $EDIT_FORM, $SESS_HIDDEN_FIELD;  
+  global $EDIT_FORM, $RCMAIL;
 
   $form_start = '';
   if (!strlen($EDIT_FORM))
     {
-    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $GLOBALS['_task']));
+    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
     $hiddenfields->add(array('name' => '_action', 'value' => $action));
     
     if ($add_hidden)
       $hiddenfields->add($add_hidden);
     
-    $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
-    $form_start .= "\n$SESS_HIDDEN_FIELD\n";
+    $form_start = !strlen($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
     $form_start .= $hiddenfields->show();
     }
     
@@ -271,11 +270,11 @@
   $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
 
   if (!strlen($EDIT_FORM))
-    $OUTPUT->add_gui_object('editform', $form_name);
+    $RCMAIL->output->add_gui_object('editform', $form_name);
   
   $EDIT_FORM = $form_name;
 
-  return array($form_start, $form_end);  
+  return array($form_start, $form_end);
   }
 
 
diff --git a/program/steps/settings/manage_folders.inc b/program/steps/settings/manage_folders.inc
index a00ff9f..49f9491 100644
--- a/program/steps/settings/manage_folders.inc
+++ b/program/steps/settings/manage_folders.inc
@@ -20,10 +20,10 @@
 */
 
 // init IMAP connection
-rcmail_imap_init(TRUE);
+$RCMAIL->imap_init(true);
 
 // subscribe to one or more mailboxes
-if ($_action=='subscribe')
+if ($RCMAIL->action=='subscribe')
   {
   if ($mbox = get_input_value('_mbox', RCUBE_INPUT_POST))
     $IMAP->subscribe(array($mbox));
@@ -33,7 +33,7 @@
   }
 
 // unsubscribe one or more mailboxes
-else if ($_action=='unsubscribe')
+else if ($RCMAIL->action=='unsubscribe')
   {
   if ($mbox = get_input_value('_mbox', RCUBE_INPUT_POST))
     $IMAP->unsubscribe(array($mbox));
@@ -43,7 +43,7 @@
   }
 
 // create a new mailbox
-else if ($_action=='create-folder')
+else if ($RCMAIL->action=='create-folder')
   {
   if (!empty($_POST['_name']))
     $create = $IMAP->create_mailbox(trim(get_input_value('_name', RCUBE_INPUT_POST, FALSE, 'UTF-7')), TRUE);
@@ -62,7 +62,7 @@
   }
 
 // rename a mailbox
-else if ($_action=='rename-folder')
+else if ($RCMAIL->action=='rename-folder')
   {
   if (!empty($_POST['_folder_oldname']) && !empty($_POST['_folder_newname']))
     $rename = $IMAP->rename_mailbox(($oldname = get_input_value('_folder_oldname', RCUBE_INPUT_POST)), trim(get_input_value('_folder_newname', RCUBE_INPUT_POST, FALSE, 'UTF-7')));
@@ -97,7 +97,7 @@
   }
 
 // delete an existing IMAP mailbox
-else if ($_action=='delete-folder')
+else if ($RCMAIL->action=='delete-folder')
   {
   $a_mboxes = array_merge($IMAP->list_mailboxes(), $IMAP->list_unsubscribed());
   $delimiter = $IMAP->get_hierarchy_delimiter();
diff --git a/program/steps/settings/save_identity.inc b/program/steps/settings/save_identity.inc
index 2c2a55e..4a7b4fb 100644
--- a/program/steps/settings/save_identity.inc
+++ b/program/steps/settings/save_identity.inc
@@ -107,6 +107,6 @@
   $USER->set_default($default_id);
 
 // go to next step
-rcmail_overwrite_action($_framed ? 'edit-identity' : 'identities');
+rcmail_overwrite_action($OUTPUT->action ? 'edit-identity' : 'identities');
 
 ?>
\ No newline at end of file
diff --git a/program/steps/settings/save_prefs.inc b/program/steps/settings/save_prefs.inc
index 9ee30a6..8025ad8 100644
--- a/program/steps/settings/save_prefs.inc
+++ b/program/steps/settings/save_prefs.inc
@@ -39,10 +39,7 @@
 
 // switch UI language
 if (isset($_POST['_language']))
-  {
-  $sess_user_lang = $_SESSION['user_lang'] = get_input_value('_language', RCUBE_INPUT_POST);
-  rcmail_set_locale($sess_user_lang);
-  }
+  $_SESSION['language'] = get_input_value('_language', RCUBE_INPUT_POST);
 
 // force min size
 if ($a_user_prefs['pagesize'] < 1)

--
Gitblit v1.9.1