source: subversion/trunk/roundcubemail/program/include/main.inc @ 508

Last change on this file since 508 was 508, checked in by thomasb, 6 years ago

Correctly format dates in future

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