source: github/program/include/main.inc @ 078adf9

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 078adf9 was 078adf9, checked in by thomascube <thomas@…>, 7 years ago

Improved usability (Ticket #1483807) and HTML validity; applied patch #1328032; fixed bug #1443200

  • Property mode set to 100644
File size: 49.2 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/main.inc                                              |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005, RoundCube Dev, - Switzerland                      |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Provide basic functions for the webmail package                     |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22require_once('lib/des.inc');
23require_once('lib/utf7.inc');
24require_once('lib/utf8.class.php');
25
26
27// define constannts for input reading
28define('RCUBE_INPUT_GET', 0x0101);
29define('RCUBE_INPUT_POST', 0x0102);
30define('RCUBE_INPUT_GPC', 0x0103);
31
32
33// register session and connect to server
34function rcmail_startup($task='mail')
35  {
36  global $sess_id, $sess_auth, $sess_user_lang;
37  global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
38
39  // check client
40  $BROWSER = rcube_browser();
41
42  // load config file
43  include_once('config/main.inc.php');
44  $CONFIG = is_array($rcmail_config) ? $rcmail_config : array();
45 
46  // load host-specific configuration
47  rcmail_load_host_config($CONFIG);
48 
49  $CONFIG['skin_path'] = $CONFIG['skin_path'] ? unslashify($CONFIG['skin_path']) : 'skins/default';
50
51  // load db conf
52  include_once('config/db.inc.php');
53  $CONFIG = array_merge($CONFIG, $rcmail_config);
54
55  if (empty($CONFIG['log_dir']))
56    $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
57  else
58    $CONFIG['log_dir'] = unslashify($CONFIG['log_dir']);
59
60  // set PHP error logging according to config
61  if ($CONFIG['debug_level'] & 1)
62    {
63    ini_set('log_errors', 1);
64    ini_set('error_log', $CONFIG['log_dir'].'/errors');
65    }
66  if ($CONFIG['debug_level'] & 4)
67    ini_set('display_errors', 1);
68  else
69    ini_set('display_errors', 0);
70
71
72  // set session garbage collecting time according to session_lifetime
73  if (!empty($CONFIG['session_lifetime']))
74    ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']+2)*60);
75
76
77  // prepare DB connection
78  require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
79 
80  $DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
81  $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
82  $DB->db_connect('w');
83   
84  // we can use the database for storing session data
85  if (!$DB->is_error())
86    include_once('include/session.inc');
87
88  // init session
89  session_start();
90  $sess_id = session_id();
91
92  // create session and set session vars
93  if (!isset($_SESSION['auth_time']))
94    {
95    $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
96    $_SESSION['auth_time'] = mktime();
97    setcookie('sessauth', rcmail_auth_hash($sess_id, $_SESSION['auth_time']));
98    }
99
100  // set session vars global
101  $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
102
103
104  // overwrite config with user preferences
105  if (is_array($_SESSION['user_prefs']))
106    $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
107
108
109  // reset some session parameters when changing task
110  if ($_SESSION['task'] != $task)
111    unset($_SESSION['page']);
112
113  // set current task to session
114  $_SESSION['task'] = $task;
115
116  // create IMAP object
117  if ($task=='mail')
118    rcmail_imap_init();
119
120
121  // set localization
122  if ($CONFIG['locale_string'])
123    setlocale(LC_ALL, $CONFIG['locale_string']);
124  else if ($sess_user_lang)
125    setlocale(LC_ALL, $sess_user_lang);
126
127
128  register_shutdown_function('rcmail_shutdown');
129  }
130
131
132// load a host-specific config file if configured
133function rcmail_load_host_config(&$config)
134  {
135  $fname = NULL;
136 
137  if (is_array($config['include_host_config']))
138    $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
139  else if (!empty($config['include_host_config']))
140    $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
141
142   if ($fname && is_file('config/'.$fname))
143     {
144     include('config/'.$fname);
145     $config = array_merge($config, $rcmail_config);
146     }
147  }
148
149
150// create authorization hash
151function rcmail_auth_hash($sess_id, $ts)
152  {
153  global $CONFIG;
154 
155  $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
156                         $sess_id,
157                         $ts,
158                         $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
159                         $_SERVER['HTTP_USER_AGENT']);
160 
161  if (function_exists('sha1'))
162    return sha1($auth_string);
163  else
164    return md5($auth_string);
165  }
166
167
168// compare the auth hash sent by the client with the local session credentials
169function rcmail_authenticate_session()
170  {
171  $now = mktime();
172  $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']));
173 
174  // renew auth cookie every 5 minutes
175  if (!$valid || ($now-$_SESSION['auth_time'] > 300))
176    {
177    $_SESSION['auth_time'] = $now;
178    setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
179    }
180   
181  return $valid;
182  }
183
184
185// create IMAP object and connect to server
186function rcmail_imap_init($connect=FALSE)
187  {
188  global $CONFIG, $DB, $IMAP;
189
190  $IMAP = new rcube_imap($DB);
191  $IMAP->debug_level = $CONFIG['debug_level'];
192  $IMAP->skip_deleted = $CONFIG['skip_deleted'];
193
194
195  // connect with stored session data
196  if ($connect)
197    {
198    if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
199      show_message('imaperror', 'error');
200     
201    rcmail_set_imap_prop();
202    }
203
204  // enable caching of imap data
205  if ($CONFIG['enable_caching']===TRUE)
206    $IMAP->set_caching(TRUE);
207
208  if (is_array($CONFIG['default_imap_folders']))
209    $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
210
211  // set pagesize from config
212  if (isset($CONFIG['pagesize']))
213    $IMAP->set_pagesize($CONFIG['pagesize']);
214  }
215
216
217// set root dir and last stored mailbox
218// this must be done AFTER connecting to the server
219function rcmail_set_imap_prop()
220  {
221  global $CONFIG, $IMAP;
222
223  // set root dir from config
224  if (!empty($CONFIG['imap_root']))
225    $IMAP->set_rootdir($CONFIG['imap_root']);
226
227  if (!empty($_SESSION['mbox']))
228    $IMAP->set_mailbox($_SESSION['mbox']);
229  if (isset($_SESSION['page']))
230    $IMAP->set_page($_SESSION['page']);
231  }
232
233
234// do these things on script shutdown
235function rcmail_shutdown()
236  {
237  global $IMAP;
238 
239  if (is_object($IMAP))
240    {
241    $IMAP->close();
242    $IMAP->write_cache();
243    }
244   
245  // before closing the database connection, write session data
246  session_write_close();
247  }
248
249
250// destroy session data and remove cookie
251function rcmail_kill_session()
252  {
253  // save user preferences
254  $a_user_prefs = $_SESSION['user_prefs'];
255  if (!is_array($a_user_prefs))
256    $a_user_prefs = array();
257   
258  if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
259      (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
260    {
261    $a_user_prefs['message_sort_col'] = $_SESSION['sort_col'];
262    $a_user_prefs['message_sort_order'] = $_SESSION['sort_order'];
263    rcmail_save_user_prefs($a_user_prefs);
264    }
265
266  $_SESSION = array();
267  session_destroy();
268  }
269
270
271// return correct name for a specific database table
272function get_table_name($table)
273  {
274  global $CONFIG;
275 
276  // return table name if configured
277  $config_key = 'db_table_'.$table;
278
279  if (strlen($CONFIG[$config_key]))
280    return $CONFIG[$config_key];
281 
282  return $table;
283  }
284
285
286// return correct name for a specific database sequence
287// (used for Postres only)
288function get_sequence_name($sequence)
289  {
290  global $CONFIG;
291 
292  // return table name if configured
293  $config_key = 'db_sequence_'.$sequence;
294
295  if (strlen($CONFIG[$config_key]))
296    return $CONFIG[$config_key];
297 
298  return $table;
299  }
300
301
302// check the given string and returns language properties
303function rcube_language_prop($lang, $prop='lang')
304  {
305  global $INSTALL_PATH;
306  static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
307
308  if (empty($rcube_languages))
309    @include($INSTALL_PATH.'program/localization/index.inc');
310   
311  // check if we have an alias for that language
312  if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
313    $lang = $rcube_language_aliases[$lang];
314   
315  // try the first two chars
316  if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
317    {
318    $lang = substr($lang, 0, 2);
319    $lang = rcube_language_prop($lang);
320    }
321
322  if (!isset($rcube_languages[$lang]))
323    $lang = 'en_US';
324
325  // language has special charset configured
326  if (isset($rcube_charsets[$lang]))
327    $charset = $rcube_charsets[$lang];
328  else
329    $charset = 'UTF-8';   
330
331
332  if ($prop=='charset')
333    return $charset;
334  else
335    return $lang;
336  }
337 
338
339// init output object for GUI and add common scripts
340function load_gui()
341  {
342  global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
343
344  // init output page
345  $OUTPUT = new rcube_html_page();
346 
347  // add common javascripts
348  $javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
349  $javascript .= "$JS_OBJECT_NAME.set_env('comm_path', '$COMM_PATH');\n";
350
351  if (isset($CONFIG['javascript_config'] )){
352    foreach ($CONFIG['javascript_config'] as $js_config_var){
353      $javascript .= "$JS_OBJECT_NAME.set_env('$js_config_var', '" . $CONFIG[$js_config_var] . "');\n";
354    }
355  }
356 
357  if (!empty($GLOBALS['_framed']))
358    $javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
359   
360  $OUTPUT->add_script($javascript);
361  $OUTPUT->include_script('common.js');
362  $OUTPUT->include_script('app.js');
363  $OUTPUT->scripts_path = 'program/js/';
364
365  // set locale setting
366  rcmail_set_locale($sess_user_lang);
367
368  // set user-selected charset
369  if (!empty($CONFIG['charset']))
370    $OUTPUT->set_charset($CONFIG['charset']);
371
372  // add some basic label to client
373  rcube_add_label('loading','checkingmail');
374  }
375
376
377// set localization charset based on the given language
378function rcmail_set_locale($lang)
379  {
380  global $OUTPUT, $MBSTRING, $MBSTRING_ENCODING;
381  static $s_mbstring_loaded = NULL;
382 
383  // settings for mbstring module (by Tadashi Jokagi)
384  if ($s_mbstring_loaded===NULL)
385    {
386    if ($s_mbstring_loaded = extension_loaded("mbstring"))
387      {
388      $MBSTRING = TRUE;
389      if (function_exists("mb_mbstring_encodings"))
390        $MBSTRING_ENCODING = mb_mbstring_encodings();
391      else
392        $MBSTRING_ENCODING = array("ISO-8859-1", "UTF-7", "UTF7-IMAP", "UTF-8",
393                                   "ISO-2022-JP", "EUC-JP", "EUCJP-WIN",
394                                   "SJIS", "SJIS-WIN");
395
396       $MBSTRING_ENCODING = array_map("strtoupper", $MBSTRING_ENCODING);
397       if (in_array("SJIS", $MBSTRING_ENCODING))
398         $MBSTRING_ENCODING[] = "SHIFT_JIS";
399       }
400     else
401      {
402      $MBSTRING = FALSE;
403      $MBSTRING_ENCODING = array();
404      }
405    }
406
407  if ($MBSTRING && function_exists("mb_language"))
408    {
409    if (!@mb_language(strtok($lang, "_")))
410      $MBSTRING = FALSE;   //  unsupport language
411    }
412
413  $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
414  }
415
416
417// perfom login to the IMAP server and to the webmail service
418function rcmail_login($user, $pass, $host=NULL)
419  {
420  global $CONFIG, $IMAP, $DB, $sess_user_lang;
421  $user_id = NULL;
422 
423  if (!$host)
424    $host = $CONFIG['default_host'];
425
426  // parse $host URL
427  $a_host = parse_url($host);
428  if ($a_host['host'])
429    {
430    $host = $a_host['host'];
431    $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
432    $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
433    }
434  else
435    $imap_port = $CONFIG['default_port'];
436
437
438  /* Modify username with domain if required 
439     Inspired by Marco <P0L0_notspam_binware.org>
440  */
441  // Check if we need to add domain
442  if ($CONFIG['username_domain'] && !strstr($user, '@'))
443    {
444    if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
445      $user .= '@'.$CONFIG['username_domain'][$host];
446    else if (!empty($CONFIG['username_domain']))
447      $user .= '@'.$CONFIG['username_domain'];   
448    }
449
450
451  // query if user already registered
452  $sql_result = $DB->query("SELECT user_id, username, language, preferences
453                            FROM ".get_table_name('users')."
454                            WHERE  mail_host=? AND (username=? OR alias=?)",
455                            $host,
456                            $user,
457                            $user);
458
459  // user already registered -> overwrite username
460  if ($sql_arr = $DB->fetch_assoc($sql_result))
461    {
462    $user_id = $sql_arr['user_id'];
463    $user = $sql_arr['username'];
464    }
465
466  // try to resolve email address from virtuser table   
467  if (!empty($CONFIG['virtuser_file']) && strstr($user, '@'))
468    $user = rcmail_email2user($user);
469
470
471  // exit if IMAP login failed
472  if (!($imap_login  = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
473    return FALSE;
474
475  // user already registered
476  if ($user_id && !empty($sql_arr))
477    {
478    // get user prefs
479    if (strlen($sql_arr['preferences']))
480      {
481      $user_prefs = unserialize($sql_arr['preferences']);
482      $_SESSION['user_prefs'] = $user_prefs;
483      array_merge($CONFIG, $user_prefs);
484      }
485
486
487    // set user specific language
488    if (strlen($sql_arr['language']))
489      $sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
490     
491    // update user's record
492    $DB->query("UPDATE ".get_table_name('users')."
493                SET    last_login=now()
494                WHERE  user_id=?",
495                $user_id);
496    }
497  // create new system user
498  else if ($CONFIG['auto_create_user'])
499    {
500    $user_id = rcmail_create_user($user, $host);
501    }
502
503  if ($user_id)
504    {
505    $_SESSION['user_id']   = $user_id;
506    $_SESSION['imap_host'] = $host;
507    $_SESSION['imap_port'] = $imap_port;
508    $_SESSION['imap_ssl']  = $imap_ssl;
509    $_SESSION['username']  = $user;
510    $_SESSION['user_lang'] = $sess_user_lang;
511    $_SESSION['password']  = encrypt_passwd($pass);
512
513    // force reloading complete list of subscribed mailboxes   
514    $IMAP->clear_cache('mailboxes');
515
516    return TRUE;
517    }
518
519  return FALSE;
520  }
521
522
523// create new entry in users and identities table
524function rcmail_create_user($user, $host)
525  {
526  global $DB, $CONFIG, $IMAP;
527
528  $user_email = '';
529
530  // try to resolve user in virtusertable
531  if (!empty($CONFIG['virtuser_file']) && strstr($user, '@')==FALSE)
532    $user_email = rcmail_user2email($user);
533
534  $DB->query("INSERT INTO ".get_table_name('users')."
535              (created, last_login, username, mail_host, alias, language)
536              VALUES (now(), now(), ?, ?, ?, ?)",
537              $user,
538              $host,
539              $user_email,
540                      $_SESSION['user_lang']);
541
542  if ($user_id = $DB->insert_id(get_sequence_name('users')))
543    {
544    if (is_array($CONFIG['mail_domain']) && isset($CONFIG['mail_domain'][$host]))
545      $mail_domain = $CONFIG['mail_domain'][$host];
546    else if (!empty($CONFIG['mail_domain']))
547      $mail_domain = $CONFIG['mail_domain'];
548    else
549      $mail_domain = $host;
550   
551    if ($user_email=='')
552      $user_email = strstr($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
553
554    $user_name = $user!=$user_email ? $user : '';
555
556    // try to resolve the e-mail address from the virtuser table
557        if (!empty($CONFIG['virtuser_query']))
558          {
559      $sql_result = $DB->query(preg_replace('/%u/', $user, $CONFIG['virtuser_query']));
560      if ($sql_arr = $DB->fetch_array($sql_result))
561        $user_email = $sql_arr[0];
562      }
563
564    // also create new identity records
565    $DB->query("INSERT INTO ".get_table_name('identities')."
566                (user_id, del, standard, name, email)
567                VALUES (?, 0, 1, ?, ?)",
568                $user_id,
569                $user_name,
570                $user_email);
571
572                       
573    // get existing mailboxes
574    $a_mailboxes = $IMAP->list_mailboxes();
575    }
576  else
577    {
578    raise_error(array('code' => 500,
579                      'type' => 'php',
580                      'line' => __LINE__,
581                      'file' => __FILE__,
582                      'message' => "Failed to create new user"), TRUE, FALSE);
583    }
584   
585  return $user_id;
586  }
587
588
589// load virtuser table in array
590function rcmail_getvirtualfile()
591  {
592  global $CONFIG;
593  if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
594    return FALSE;
595 
596  // read file
597  $a_lines = file($CONFIG['virtuser_file']);
598  return $a_lines;
599  }
600
601
602// find matches of the given pattern in virtuser table
603function rcmail_findinvirtual($pattern)
604  {
605  $result = array();
606  $virtual = rcmail_getvirtualfile();
607  if ($virtual==FALSE)
608    return $result;
609
610  // check each line for matches
611  foreach ($virtual as $line)
612    {
613    $line = trim($line);
614    if (empty($line) || $line{0}=='#')
615      continue;
616     
617    if (eregi($pattern, $line))
618      $result[] = $line;
619    }
620
621  return $result;
622  }
623
624
625// resolve username with virtuser table
626function rcmail_email2user($email)
627  {
628  $user = $email;
629  $r = rcmail_findinvirtual("^$email");
630
631  for ($i=0; $i<count($r); $i++)
632    {
633    $data = $r[$i];
634    $arr = preg_split('/\s+/', $data);
635    if(count($arr)>0)
636      {
637      $user = trim($arr[count($arr)-1]);
638      break;
639      }
640    }
641
642  return $user;
643  }
644
645
646// resolve e-mail address with virtuser table
647function rcmail_user2email($user)
648  {
649  $email = "";
650  $r = rcmail_findinvirtual("$user$");
651
652  for ($i=0; $i<count($r); $i++)
653    {
654    $data=$r[$i];
655    $arr = preg_split('/\s+/', $data);
656    if (count($arr)>0)
657      {
658      $email = trim($arr[0]);
659      break;
660      }
661    }
662
663  return $email;
664  }
665
666
667function rcmail_save_user_prefs($a_user_prefs)
668  {
669  global $DB, $CONFIG, $sess_user_lang;
670 
671  $DB->query("UPDATE ".get_table_name('users')."
672              SET    preferences=?,
673                     language=?
674              WHERE  user_id=?",
675              serialize($a_user_prefs),
676              $sess_user_lang,
677              $_SESSION['user_id']);
678
679  if ($DB->affected_rows())
680    {
681    $_SESSION['user_prefs'] = $a_user_prefs; 
682    $CONFIG = array_merge($CONFIG, $a_user_prefs);
683    return TRUE;
684    }
685   
686  return FALSE;
687  }
688
689
690// overwrite action variable 
691function rcmail_overwrite_action($action)
692  {
693  global $OUTPUT, $JS_OBJECT_NAME;
694  $GLOBALS['_action'] = $action;
695
696  $OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $action)); 
697  }
698
699
700function show_message($message, $type='notice', $vars=NULL)
701  {
702  global $OUTPUT, $JS_OBJECT_NAME, $REMOTE_REQUEST;
703 
704  $framed = $GLOBALS['_framed'];
705  $command = sprintf("display_message('%s', '%s');",
706                     addslashes(rep_specialchars_output(rcube_label(array('name' => $message, 'vars' => $vars)))),
707                     $type);
708                     
709  if ($REMOTE_REQUEST)
710    return 'this.'.$command;
711 
712  else
713    $OUTPUT->add_script(sprintf("%s%s.%s",
714                                $framed ? sprintf('if(parent.%s)parent.', $JS_OBJECT_NAME) : '',
715                                $JS_OBJECT_NAME,
716                                $command));
717 
718  // console(rcube_label($message));
719  }
720
721
722function console($msg, $type=1)
723  {
724  if ($GLOBALS['REMOTE_REQUEST'])
725    print "// $msg\n";
726  else
727    {
728    print $msg;
729    print "\n<hr>\n";
730    }
731  }
732
733
734// encrypt IMAP password using DES encryption
735function encrypt_passwd($pass)
736  {
737  $cypher = des(get_des_key(), $pass, 1, 0, NULL);
738  return base64_encode($cypher);
739  }
740
741
742// decrypt IMAP password using DES encryption
743function decrypt_passwd($cypher)
744  {
745  $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
746  return preg_replace('/\x00/', '', $pass);
747  }
748
749
750// return a 24 byte key for the DES encryption
751function get_des_key()
752  {
753  $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
754  $len = strlen($key);
755 
756  // make sure the key is exactly 24 chars long
757  if ($len<24)
758    $key .= str_repeat('_', 24-$len);
759  else if ($len>24)
760    substr($key, 0, 24);
761 
762  return $key;
763  }
764
765
766// send correct response on a remote request
767function rcube_remote_response($js_code, $flush=FALSE)
768  {
769  global $OUTPUT, $CHARSET;
770  static $s_header_sent = FALSE;
771 
772  if (!$s_header_sent)
773    {
774    $s_header_sent = TRUE;
775    send_nocacheing_headers();
776    header('Content-Type: application/x-javascript; charset='.$CHARSET);
777    print '/** remote response ['.date('d/M/Y h:i:s O')."] **/\n";
778    }
779
780  // send response code
781  print rcube_charset_convert($js_code, $CHARSET, $OUTPUT->get_charset());
782
783  if ($flush)  // flush the output buffer
784    flush();
785  else         // terminate script
786    exit;
787  }
788
789
790// read directory program/localization/ and return a list of available languages
791function rcube_list_languages()
792  {
793  global $CONFIG, $INSTALL_PATH;
794  static $sa_languages = array();
795
796  if (!sizeof($sa_languages))
797    {
798    @include($INSTALL_PATH.'program/localization/index.inc');
799
800    if ($dh = @opendir($INSTALL_PATH.'program/localization'))
801      {
802      while (($name = readdir($dh)) !== false)
803        {
804        if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
805          continue;
806
807        if ($label = $rcube_languages[$name])
808          $sa_languages[$name] = $label ? $label : $name;
809        }
810      closedir($dh);
811      }
812    }
813  return $sa_languages;
814  }
815
816
817// add a localized label to the client environment
818function rcube_add_label()
819  {
820  global $OUTPUT, $JS_OBJECT_NAME;
821 
822  $arg_list = func_get_args();
823  foreach ($arg_list as $i => $name)
824    $OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
825                                $JS_OBJECT_NAME,
826                                $name,
827                                rep_specialchars_output(rcube_label($name), 'js'))); 
828  }
829
830
831// remove temp files of a session
832function rcmail_clear_session_temp($sess_id)
833  {
834  global $CONFIG;
835
836  $temp_dir = slashify($CONFIG['temp_dir']);
837  $cache_dir = $temp_dir.$sess_id;
838
839  if (is_dir($cache_dir))
840    {
841    clear_directory($cache_dir);
842    rmdir($cache_dir);
843    } 
844  }
845
846
847// remove all expired message cache records
848function rcmail_message_cache_gc()
849  {
850  global $DB, $CONFIG;
851 
852  // no cache lifetime configured
853  if (empty($CONFIG['message_cache_lifetime']))
854    return;
855 
856  // get target timestamp
857  $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
858 
859  $DB->query("DELETE FROM ".get_table_name('messages')."
860             WHERE  created < ".$DB->fromunixtime($ts));
861  }
862
863
864// convert a string from one charset to another
865// this function is not complete and not tested well
866function rcube_charset_convert($str, $from, $to=NULL)
867  {
868  global $MBSTRING, $MBSTRING_ENCODING;
869
870  $from = strtoupper($from);
871  $to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
872
873  if ($from==$to)
874    return $str;
875   
876  // convert charset using mbstring module 
877  if ($MBSTRING)
878    {
879    $to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
880    $from = $from=="UTF-7" ? "UTF7-IMAP": $from;
881   
882    if (in_array($to, $MBSTRING_ENCODING) && in_array($from, $MBSTRING_ENCODING))
883      return mb_convert_encoding($str, $to, $from);
884    }
885
886  // convert charset using iconv module 
887  if (function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7')
888    return iconv($from, $to, $str);
889
890  $conv = new utf8();
891
892  // convert string to UTF-8
893  if ($from=='UTF-7')
894    $str = rcube_charset_convert(UTF7DecodeString($str), 'ISO-8859-1');
895  else if ($from=='ISO-8859-1' && function_exists('utf8_encode'))
896    $str = utf8_encode($str);
897  else if ($from!='UTF-8')
898    {
899    $conv->loadCharset($from);
900    $str = $conv->strToUtf8($str);
901    }
902
903  // encode string for output
904  if ($to=='UTF-7')
905    return UTF7EncodeString($str);
906  else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
907    return utf8_decode($str);
908  else if ($to!='UTF-8')
909    {
910    $conv->loadCharset($to);
911    return $conv->utf8ToStr($str);
912    }
913
914  // return UTF-8 string
915  return $str;
916  }
917
918
919
920// replace specials characters to a specific encoding type
921function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
922  {
923  global $OUTPUT_TYPE, $OUTPUT;
924  static $html_encode_arr, $js_rep_table, $rtf_rep_table, $xml_rep_table;
925
926  if (!$enctype)
927    $enctype = $GLOBALS['OUTPUT_TYPE'];
928
929  // convert nbsps back to normal spaces if not html
930  if ($enctype!='html')
931    $str = str_replace(chr(160), ' ', $str);
932
933  // encode for plaintext
934  if ($enctype=='text')
935    return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
936
937  // encode for HTML output
938  if ($enctype=='html')
939    {
940    if (!$html_encode_arr)
941      {
942      $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);       
943      unset($html_encode_arr['?']);
944      unset($html_encode_arr['&']);
945      }
946
947    $ltpos = strpos($str, '<');
948    $encode_arr = $html_encode_arr;
949
950    // don't replace quotes and html tags
951    if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
952      {
953      unset($encode_arr['"']);
954      unset($encode_arr['<']);
955      unset($encode_arr['>']);
956      }
957    else if ($mode=='remove')
958      $str = strip_tags($str);
959     
960    $out = strtr($str, $encode_arr);
961     
962    return $newlines ? nl2br($out) : $out;
963    }
964
965
966  if ($enctype=='url')
967    return rawurlencode($str);
968
969
970  // if the replace tables for RTF, XML and JS are not yet defined
971  if (!$js_rep_table)
972    {
973    $js_rep_table = $rtf_rep_table = $xml_rep_table = array();
974    $xml_rep_table['&'] = '&amp;';
975
976    for ($c=160; $c<256; $c++)  // can be increased to support more charsets
977      {
978      $hex = dechex($c);
979      $rtf_rep_table[Chr($c)] = "\\'$hex";
980      $xml_rep_table[Chr($c)] = "&#$c;";
981     
982      if ($OUTPUT->get_charset()=='ISO-8859-1')
983        $js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
984      }
985
986    $js_rep_table['"'] = sprintf("\u%s%s", str_repeat('0', 4-strlen(dechex(34))), dechex(34));
987    $xml_rep_table['"'] = '&quot;';
988    }
989
990  // encode for RTF
991  if ($enctype=='xml')
992    return strtr($str, $xml_rep_table);
993
994  // encode for javascript use
995  if ($enctype=='js')
996    {
997    if ($OUTPUT->get_charset()!='UTF-8')
998      $str = rcube_charset_convert($str, $GLOBALS['CHARSET'], $OUTPUT->get_charset());
999     
1000    return preg_replace(array("/\r\n/", '/"/', "/([^\\\])'/"), array('\n', '\"', "$1\'"), strtr($str, $js_rep_table));
1001    }
1002
1003  // encode for RTF
1004  if ($enctype=='rtf')
1005    return preg_replace("/\r\n/", "\par ", strtr($str, $rtf_rep_table));
1006
1007  // no encoding given -> return original string
1008  return $str;
1009  }
1010
1011
1012/**
1013 * Read input value and convert it for internal use
1014 * Performs stripslashes() and charset conversion if necessary
1015 *
1016 * @param  string   Field name to read
1017 * @param  int      Source to get value from (GPC)
1018 * @param  boolean  Allow HTML tags in field value
1019 * @param  string   Charset to convert into
1020 * @return string   Field value or NULL if not available
1021 */
1022function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1023  {
1024  global $OUTPUT;
1025  $value = NULL;
1026 
1027  if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1028    $value = $_GET[$fname];
1029  else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1030    $value = $_POST[$fname];
1031  else if ($source==RCUBE_INPUT_GPC)
1032    {
1033    if (isset($_POST[$fname]))
1034      $value = $_POST[$fname];
1035    else if (isset($_GET[$fname]))
1036      $value = $_GET[$fname];
1037    else if (isset($_COOKIE[$fname]))
1038      $value = $_COOKIE[$fname];
1039    }
1040 
1041  // strip slashes if magic_quotes enabled
1042  if ((bool)get_magic_quotes_gpc())
1043    $value = stripslashes($value);
1044
1045  // remove HTML tags if not allowed   
1046  if (!$allow_html)
1047    $value = strip_tags($value);
1048 
1049  // convert to internal charset
1050  if (is_object($OUTPUT))
1051    return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1052  else
1053    return $value;
1054  }
1055
1056
1057
1058
1059// ************** template parsing and gui functions **************
1060
1061
1062// return boolean if a specific template exists
1063function template_exists($name)
1064  {
1065  global $CONFIG, $OUTPUT;
1066  $skin_path = $CONFIG['skin_path'];
1067
1068  // check template file
1069  return is_file("$skin_path/templates/$name.html");
1070  }
1071
1072
1073// get page template an replace variable
1074// similar function as used in nexImage
1075function parse_template($name='main', $exit=TRUE)
1076  {
1077  global $CONFIG, $OUTPUT;
1078  $skin_path = $CONFIG['skin_path'];
1079
1080  // read template file
1081  $templ = '';
1082  $path = "$skin_path/templates/$name.html";
1083
1084  if($fp = @fopen($path, 'r'))
1085    {
1086    $templ = fread($fp, filesize($path));
1087    fclose($fp);
1088    }
1089  else
1090    {
1091    raise_error(array('code' => 500,
1092                      'type' => 'php',
1093                      'line' => __LINE__,
1094                      'file' => __FILE__,
1095                      'message' => "Error loading template for '$name'"), TRUE, TRUE);
1096    return FALSE;
1097    }
1098
1099
1100  // parse for specialtags
1101  $output = parse_rcube_xml($templ);
1102 
1103  $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
1104
1105  if ($exit)
1106    exit;
1107  }
1108
1109
1110
1111// replace all strings ($varname) with the content of the according global variable
1112function parse_with_globals($input)
1113  {
1114  $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
1115  $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
1116  return $output;
1117  }
1118
1119
1120
1121function parse_rcube_xml($input)
1122  {
1123  $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
1124  return $output;
1125  }
1126
1127
1128function rcube_xml_command($command, $str_attrib, $a_attrib=NULL)
1129  {
1130  global $IMAP, $CONFIG, $OUTPUT;
1131 
1132  $attrib = array();
1133  $command = strtolower($command);
1134
1135  preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str_attrib), $regs, PREG_SET_ORDER);
1136
1137  // convert attributes to an associative array (name => value)
1138  if ($regs)
1139    foreach ($regs as $attr)
1140      $attrib[strtolower($attr[1])] = $attr[2];
1141  else if ($a_attrib)
1142    $attrib = $a_attrib;
1143
1144  // execute command
1145  switch ($command)
1146    {
1147    // return a button
1148    case 'button':
1149      if ($attrib['command'])
1150        return rcube_button($attrib);
1151      break;
1152
1153    // show a label
1154    case 'label':
1155      if ($attrib['name'] || $attrib['command'])
1156        return rep_specialchars_output(rcube_label($attrib));
1157      break;
1158
1159    // create a menu item
1160    case 'menu':
1161      if ($attrib['command'] && $attrib['group'])
1162        rcube_menu($attrib);
1163      break;
1164
1165    // include a file
1166    case 'include':
1167      $path = realpath($CONFIG['skin_path'].$attrib['file']);
1168     
1169      if($fp = @fopen($path, 'r'))
1170        {
1171        $incl = fread($fp, filesize($path));
1172        fclose($fp);       
1173        return parse_rcube_xml($incl);
1174        }
1175      break;
1176
1177    // return code for a specific application object
1178    case 'object':
1179      $object = strtolower($attrib['name']);
1180
1181      $object_handlers = array(
1182        // GENERAL
1183        'loginform' => 'rcmail_login_form',
1184        'username'  => 'rcmail_current_username',
1185       
1186        // MAIL
1187        'mailboxlist' => 'rcmail_mailbox_list',
1188        'message' => 'rcmail_message_container',
1189        'messages' => 'rcmail_message_list',
1190        'messagecountdisplay' => 'rcmail_messagecount_display',
1191        'quotadisplay' => 'rcmail_quota_display',
1192        'messageheaders' => 'rcmail_message_headers',
1193        'messagebody' => 'rcmail_message_body',
1194        'messageattachments' => 'rcmail_message_attachments',
1195        'blockedobjects' => 'rcmail_remote_objects_msg',
1196        'messagecontentframe' => 'rcmail_messagecontent_frame',
1197        'messagepartframe' => 'rcmail_message_part_frame',
1198        'messagepartcontrols' => 'rcmail_message_part_controls',
1199        'composeheaders' => 'rcmail_compose_headers',
1200        'composesubject' => 'rcmail_compose_subject',
1201        'composebody' => 'rcmail_compose_body',
1202        'composeattachmentlist' => 'rcmail_compose_attachment_list',
1203        'composeattachmentform' => 'rcmail_compose_attachment_form',
1204        'composeattachment' => 'rcmail_compose_attachment_field',
1205        'priorityselector' => 'rcmail_priority_selector',
1206        'charsetselector' => 'rcmail_charset_selector',
1207        'searchform' => 'rcmail_search_form',
1208        'receiptcheckbox' => 'rcmail_receipt_checkbox',
1209       
1210        // ADDRESS BOOK
1211        'addresslist' => 'rcmail_contacts_list',
1212        'addressframe' => 'rcmail_contact_frame',
1213        'recordscountdisplay' => 'rcmail_rowcount_display',
1214        'contactdetails' => 'rcmail_contact_details',
1215        'contacteditform' => 'rcmail_contact_editform',
1216        'ldappublicsearch' => 'rcmail_ldap_public_search_form',
1217        'ldappublicaddresslist' => 'rcmail_ldap_public_list',
1218
1219        // USER SETTINGS
1220        'userprefs' => 'rcmail_user_prefs_form',
1221        'itentitieslist' => 'rcmail_identities_list',
1222        'identityframe' => 'rcmail_identity_frame',
1223        'identityform' => 'rcube_identity_form',
1224        'foldersubscription' => 'rcube_subscription_form',
1225        'createfolder' => 'rcube_create_folder_form',
1226        'renamefolder' => 'rcube_rename_folder_form',
1227        'composebody' => 'rcmail_compose_body'
1228      );
1229
1230     
1231      // execute object handler function
1232      if ($object_handlers[$object] && function_exists($object_handlers[$object]))
1233        return call_user_func($object_handlers[$object], $attrib);
1234       
1235      else if ($object=='productname')
1236        {
1237        $name = !empty($CONFIG['product_name']) ? $CONFIG['product_name'] : 'RoundCube Webmail';
1238        return rep_specialchars_output($name, 'html', 'all');
1239        }
1240      else if ($object=='version')
1241        {
1242        return (string)RCMAIL_VERSION;
1243        }
1244      else if ($object=='pagetitle')
1245        {
1246        $task = $GLOBALS['_task'];
1247        $title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
1248       
1249        if ($task=='login')
1250          $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $CONFIG['product_name'])));
1251        else if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
1252          $title .= $GLOBALS['MESSAGE']['subject'];
1253        else if (isset($GLOBALS['PAGE_TITLE']))
1254          $title .= $GLOBALS['PAGE_TITLE'];
1255        else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
1256          $title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
1257        else
1258          $title .= ucfirst($task);
1259         
1260        return rep_specialchars_output($title, 'html', 'all');
1261        }
1262
1263      break;
1264    }
1265
1266  return '';
1267  }
1268
1269
1270// create and register a button
1271function rcube_button($attrib)
1272  {
1273  global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER, $COMM_PATH, $MAIN_TASKS;
1274  static $sa_buttons = array();
1275  static $s_button_count = 100;
1276 
1277  // these commands can be called directly via url
1278  $a_static_commands = array('compose', 'list');
1279 
1280  $skin_path = $CONFIG['skin_path'];
1281 
1282  if (!($attrib['command'] || $attrib['name']))
1283    return '';
1284
1285  // try to find out the button type
1286  if ($attrib['type'])
1287    $attrib['type'] = strtolower($attrib['type']);
1288  else
1289    $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imageact']) ? 'image' : 'link';
1290 
1291 
1292  $command = $attrib['command'];
1293 
1294  // take the button from the stack
1295  if($attrib['name'] && $sa_buttons[$attrib['name']])
1296    $attrib = $sa_buttons[$attrib['name']];
1297
1298  // add button to button stack
1299  else if($attrib['image'] || $arg['imageact'] || $attrib['imagepas'] || $attrib['class'])
1300    {
1301    if(!$attrib['name'])
1302      $attrib['name'] = $command;
1303
1304    if (!$attrib['image'])
1305      $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1306
1307    $sa_buttons[$attrib['name']] = $attrib;
1308    }
1309
1310  // get saved button for this command/name
1311  else if ($command && $sa_buttons[$command])
1312    $attrib = $sa_buttons[$command];
1313
1314  //else
1315  //  return '';
1316
1317
1318  // set border to 0 because of the link arround the button
1319  if ($attrib['type']=='image' && !isset($attrib['border']))
1320    $attrib['border'] = 0;
1321   
1322  if (!$attrib['id'])
1323    $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
1324
1325  // get localized text for labels and titles
1326  if ($attrib['title'])
1327    $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
1328  if ($attrib['label'])
1329    $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
1330
1331  if ($attrib['alt'])
1332    $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
1333
1334  // set title to alt attribute for IE browsers
1335  if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
1336    {
1337    $attrib['alt'] = $attrib['title'];
1338    unset($attrib['title']);
1339    }
1340
1341  // add empty alt attribute for XHTML compatibility
1342  if (!isset($attrib['alt']))
1343    $attrib['alt'] = '';
1344
1345
1346  // register button in the system
1347  if ($attrib['command'])
1348    {
1349    $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
1350                                $JS_OBJECT_NAME,
1351                                $command,
1352                                $attrib['id'],
1353                                $attrib['type'],
1354                                $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
1355                                $attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
1356                                $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
1357
1358    // make valid href to specific buttons
1359    if (in_array($attrib['command'], $MAIN_TASKS))
1360      $attrib['href'] = htmlentities(ereg_replace('_task=[a-z]+', '_task='.$attrib['command'], $COMM_PATH));
1361    else if (in_array($attrib['command'], $a_static_commands))
1362      $attrib['href'] = htmlentities($COMM_PATH.'&_action='.$attrib['command']);
1363    }
1364
1365  // overwrite attributes
1366  if (!$attrib['href'])
1367    $attrib['href'] = '#';
1368
1369  if ($command)
1370    $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
1371   
1372  if ($command && $attrib['imageover'])
1373    {
1374    $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1375    $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1376    }
1377
1378  if ($command && $attrib['imagesel'])
1379    {
1380    $attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1381    $attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1382    }
1383
1384  $out = '';
1385
1386  // generate image tag
1387  if ($attrib['type']=='image')
1388    {
1389    $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
1390    $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
1391    $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
1392    if ($attrib['label'])
1393      $btn_content .= ' '.$attrib['label'];
1394   
1395    $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
1396    }
1397  else if ($attrib['type']=='link')
1398    {
1399    $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
1400    $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
1401    }
1402  else if ($attrib['type']=='input')
1403    {
1404    $attrib['type'] = 'button';
1405   
1406    if ($attrib['label'])
1407      $attrib['value'] = $attrib['label'];
1408     
1409    $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
1410    $out = sprintf('<input%s disabled />', $attrib_str);
1411    }
1412
1413  // generate html code for button
1414  if ($btn_content)
1415    {
1416    $attrib_str = create_attrib_string($attrib, $link_attrib);
1417    $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1418    }
1419
1420  return $out;
1421  }
1422
1423
1424function rcube_menu($attrib)
1425  {
1426 
1427  return '';
1428  }
1429
1430
1431
1432function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1433  {
1434  global $DB;
1435 
1436  // allow the following attributes to be added to the <table> tag
1437  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1438 
1439  $table = '<table' . $attrib_str . ">\n";
1440   
1441  // add table title
1442  $table .= "<thead><tr>\n";
1443
1444  foreach ($a_show_cols as $col)
1445    $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
1446
1447  $table .= "</tr></thead>\n<tbody>\n";
1448 
1449  $c = 0;
1450
1451  if (!is_array($table_data))
1452    {
1453    while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1454      {
1455      $zebra_class = $c%2 ? 'even' : 'odd';
1456
1457      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1458
1459      // format each col
1460      foreach ($a_show_cols as $col)
1461        {
1462        $cont = rep_specialchars_output($sql_arr[$col]);
1463            $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1464        }
1465
1466      $table .= "</tr>\n";
1467      $c++;
1468      }
1469    }
1470  else
1471    {
1472    foreach ($table_data as $row_data)
1473      {
1474      $zebra_class = $c%2 ? 'even' : 'odd';
1475
1476      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1477
1478      // format each col
1479      foreach ($a_show_cols as $col)
1480        {
1481        $cont = rep_specialchars_output($row_data[$col]);
1482            $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1483        }
1484
1485      $table .= "</tr>\n";
1486      $c++;
1487      }
1488    }
1489
1490  // complete message table
1491  $table .= "</tbody></table>\n";
1492 
1493  return $table;
1494  }
1495
1496
1497
1498function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1499  {
1500  $fname = '_'.$col;
1501  $attrib['name'] = $fname;
1502 
1503  if ($type=='checkbox')
1504    {
1505    $attrib['value'] = '1';
1506    $input = new checkbox($attrib);
1507    }
1508  else if ($type=='textarea')
1509    {
1510    $attrib['cols'] = $attrib['size'];
1511    $input = new textarea($attrib);
1512    }
1513  else
1514    $input = new textfield($attrib);
1515
1516  // use value from post
1517  if (!empty($_POST[$fname]))
1518    $value = $_POST[$fname];
1519
1520  $out = $input->show($value);
1521         
1522  return $out;
1523  }
1524
1525
1526function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1527  {
1528  // allow the following attributes to be added to the <iframe> tag
1529  $attrib_str = '';
1530  foreach ($allowed_attribs as $a)
1531    if (isset($attrib[$a]))
1532      $attrib_str .= sprintf(' %s="%s"', $a, $attrib[$a]);
1533
1534  return $attrib_str;
1535  }
1536
1537
1538
1539function format_date($date, $format=NULL)
1540  {
1541  global $CONFIG, $sess_user_lang;
1542 
1543  $ts = NULL;
1544 
1545  if (is_numeric($date))
1546    $ts = $date;
1547  else if (!empty($date))
1548    $ts = @strtotime($date);
1549   
1550  if (empty($ts))
1551    return '';
1552   
1553  // get user's timezone
1554  $tz = $CONFIG['timezone'];
1555  if ($CONFIG['dst_active'])
1556    $tz++;
1557
1558  // convert time to user's timezone
1559  $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1560 
1561  // get current timestamp in user's timezone
1562  $now = time();  // local time
1563  $now -= (int)date('Z'); // make GMT time
1564  $now += ($tz * 3600); // user's time
1565  $now_date = getdate();
1566
1567  $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1568  $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1569
1570  // define date format depending on current time 
1571  if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
1572    return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
1573  else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
1574    $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1575  else if (!$format)
1576    $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1577
1578
1579  // parse format string manually in order to provide localized weekday and month names
1580  // an alternative would be to convert the date() format string to fit with strftime()
1581  $out = '';
1582  for($i=0; $i<strlen($format); $i++)
1583    {
1584    if ($format{$i}=='\\')  // skip escape chars
1585      continue;
1586   
1587    // write char "as-is"
1588    if ($format{$i}==' ' || $format{$i-1}=='\\')
1589      $out .= $format{$i};
1590    // weekday (short)
1591    else if ($format{$i}=='D')
1592      $out .= rcube_label(strtolower(date('D', $timestamp)));
1593    // weekday long
1594    else if ($format{$i}=='l')
1595      $out .= rcube_label(strtolower(date('l', $timestamp)));
1596    // month name (short)
1597    else if ($format{$i}=='M')
1598      $out .= rcube_label(strtolower(date('M', $timestamp)));
1599    // month name (long)
1600    else if ($format{$i}=='F')
1601      $out .= rcube_label(strtolower(date('F', $timestamp)));
1602    else
1603      $out .= date($format{$i}, $timestamp);
1604    }
1605 
1606  return $out;
1607  }
1608
1609
1610// ************** functions delivering gui objects **************
1611
1612
1613
1614function rcmail_message_container($attrib)
1615  {
1616  global $OUTPUT, $JS_OBJECT_NAME;
1617
1618  if (!$attrib['id'])
1619    $attrib['id'] = 'rcmMessageContainer';
1620
1621  // allow the following attributes to be added to the <table> tag
1622  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1623  $out = '<div' . $attrib_str . "></div>";
1624 
1625  $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1626 
1627  return $out;
1628  }
1629
1630
1631// return the IMAP username of the current session
1632function rcmail_current_username($attrib)
1633  {
1634  global $DB;
1635  static $s_username;
1636
1637  // alread fetched 
1638  if (!empty($s_username))
1639    return $s_username;
1640
1641  // get e-mail address form default identity
1642  $sql_result = $DB->query("SELECT email AS mailto
1643                            FROM ".get_table_name('identities')."
1644                            WHERE  user_id=?
1645                            AND    standard=1
1646                            AND    del<>1",
1647                            $_SESSION['user_id']);
1648                                   
1649  if ($DB->num_rows($sql_result))
1650    {
1651    $sql_arr = $DB->fetch_assoc($sql_result);
1652    $s_username = $sql_arr['mailto'];
1653    }
1654  else if (strstr($_SESSION['username'], '@'))
1655    $s_username = $_SESSION['username'];
1656  else
1657    $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1658
1659  return $s_username;
1660  }
1661
1662
1663// return code for the webmail login form
1664function rcmail_login_form($attrib)
1665  {
1666  global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1667 
1668  $labels = array();
1669  $labels['user'] = rcube_label('username');
1670  $labels['pass'] = rcube_label('password');
1671  $labels['host'] = rcube_label('server');
1672 
1673  $input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30));
1674  $input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
1675  $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
1676   
1677  $fields = array();
1678  $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
1679  $fields['pass'] = $input_pass->show();
1680  $fields['action'] = $input_action->show();
1681 
1682  if (is_array($CONFIG['default_host']))
1683    {
1684    $select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
1685   
1686    foreach ($CONFIG['default_host'] as $key => $value)
1687      $select_host->add($value, (is_numeric($key) ? $value : $key));
1688     
1689    $fields['host'] = $select_host->show($_POST['_host']);
1690    }
1691  else if (!strlen($CONFIG['default_host']))
1692    {
1693        $input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
1694        $fields['host'] = $input_host->show($_POST['_host']);
1695    }
1696
1697  $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1698  $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1699  $form_end = !strlen($attrib['form']) ? '</form>' : '';
1700 
1701  if ($fields['host'])
1702    $form_host = <<<EOF
1703   
1704</tr><tr>
1705
1706<td class="title"><label for="rcmloginhost">$labels[host]</label></td>
1707<td>$fields[host]</td>
1708
1709EOF;
1710
1711  $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1712 
1713  $out = <<<EOF
1714$form_start
1715$SESS_HIDDEN_FIELD
1716$fields[action]
1717<table><tr>
1718
1719<td class="title"><label for="rcmloginuser">$labels[user]</label></td>
1720<td>$fields[user]</td>
1721
1722</tr><tr>
1723
1724<td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
1725<td>$fields[pass]</td>
1726$form_host
1727</tr></table>
1728$form_end
1729EOF;
1730
1731  return $out;
1732  }
1733
1734
1735function rcmail_charset_selector($attrib)
1736  {
1737  global $OUTPUT;
1738 
1739  // pass the following attributes to the form class
1740  $field_attrib = array('name' => '_charset');
1741  foreach ($attrib as $attr => $value)
1742    if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1743      $field_attrib[$attr] = $value;
1744     
1745  $charsets = array(
1746    'US-ASCII'     => 'ASCII (English)',
1747    'EUC-JP'       => 'EUC-JP (Japanese)',
1748    'EUC-KR'       => 'EUC-KR (Korean)',
1749    'BIG5'         => 'BIG5 (Chinese)',
1750    'GB2312'       => 'GB2312 (Chinese)',
1751    'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1752    'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
1753    'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1754    'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1755    'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1756    'Windows-1251' => 'Windows-1251 (Cyrillic)',
1757    'Windows-1252' => 'Windows-1252 (Western)',
1758    'Windows-1255' => 'Windows-1255 (Hebrew)',
1759    'Windows-1256' => 'Windows-1256 (Arabic)',
1760    'Windows-1257' => 'Windows-1257 (Baltic)',
1761    'UTF-8'        => 'UTF-8'
1762    );
1763
1764  $select = new select($field_attrib);
1765  $select->add(array_values($charsets), array_keys($charsets));
1766 
1767  $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
1768  return $select->show($set);
1769  }
1770
1771
1772/****** debugging function ********/
1773
1774function rcube_timer()
1775  {
1776  list($usec, $sec) = explode(" ", microtime());
1777  return ((float)$usec + (float)$sec);
1778  }
1779 
1780
1781function rcube_print_time($timer, $label='Timer')
1782  {
1783  static $print_count = 0;
1784 
1785  $print_count++;
1786  $now = rcube_timer();
1787  $diff = $now-$timer;
1788 
1789  if (empty($label))
1790    $label = 'Timer '.$print_count;
1791 
1792  console(sprintf("%s: %0.4f sec", $label, $diff));
1793  }
1794
1795?>
Note: See TracBrowser for help on using the repository browser.