source: github/program/include/main.inc @ e34ae17

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

Fixed XSS vulnerability (Bug #1484109)

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