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

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

Added message cache garbage collector

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