source: github/program/include/main.inc @ 58e3602a

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

Bugfixes for encoding and sending with attachments

  • Property mode set to 100644
File size: 41.3 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
701// convert a string from one charset to another
702// this function is not complete and not tested well
703function rcube_charset_convert($str, $from, $to=NULL)
704  {
705  $from = strtoupper($from);
706  $to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
707 
708  if ($from==$to)
709    return $str;
710   
711  // convert charset using iconv module 
712  if (0 && function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7') {
713    return iconv($from, $to, $str);
714    }
715
716  $conv = new utf8();
717
718  // convert string to UTF-8
719  if ($from=='UTF-7')
720    $str = rcube_charset_convert(UTF7DecodeString($str), 'ISO-8859-1');
721  else if ($from=='ISO-8859-1' && function_exists('utf8_encode'))
722    $str = utf8_encode($str);
723  else if ($from!='UTF-8')
724    {
725    $conv->loadCharset($from);
726    $str = $conv->strToUtf8($str);
727    }
728
729  // encode string for output
730  if ($to=='UTF-7')
731    return UTF7EncodeString($str);
732  else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
733    return utf8_decode($str);
734  else if ($to!='UTF-8')
735    {
736    $conv->loadCharset($to);
737    return $conv->utf8ToStr($str);
738    }
739
740  // return UTF-8 string
741  return $str;
742  }
743
744
745
746// replace specials characters to a specific encoding type
747function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
748  {
749  global $OUTPUT_TYPE, $OUTPUT;
750  static $html_encode_arr, $js_rep_table, $rtf_rep_table, $xml_rep_table;
751
752  if (!$enctype)
753    $enctype = $GLOBALS['OUTPUT_TYPE'];
754
755  // convert nbsps back to normal spaces if not html
756  if ($enctype!='html')
757    $str = str_replace(chr(160), ' ', $str);
758
759  // encode for plaintext
760  if ($enctype=='text')
761    return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
762
763  // encode for HTML output
764  if ($enctype=='html')
765    {
766    if (!$html_encode_arr)
767      {
768      $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);       
769      unset($html_encode_arr['?']);
770      unset($html_encode_arr['&']);
771      }
772
773    $ltpos = strpos($str, '<');
774    $encode_arr = $html_encode_arr;
775
776    // don't replace quotes and html tags
777    if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
778      {
779      unset($encode_arr['"']);
780      unset($encode_arr['<']);
781      unset($encode_arr['>']);
782      }
783    else if ($mode=='remove')
784      $str = strip_tags($str);
785     
786    $out = strtr($str, $encode_arr);
787     
788    return $newlines ? nl2br($out) : $out;
789    }
790
791
792  if ($enctype=='url')
793    return rawurlencode($str);
794
795
796  // if the replace tables for RTF, XML and JS are not yet defined
797  if (!$js_rep_table)
798    {
799    $js_rep_table = $rtf_rep_table = $xml_rep_table = array();
800
801    for ($c=160; $c<256; $c++)  // can be increased to support more charsets
802      {
803      $hex = dechex($c);
804      $rtf_rep_table[Chr($c)] = "\\'$hex";
805      $xml_rep_table[Chr($c)] = "&#$c;";
806     
807      if ($OUTPUT->get_charset()=='ISO-8859-1')
808        $js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
809      }
810
811    $js_rep_table['"'] = sprintf("\u%s%s", str_repeat('0', 4-strlen(dechex(34))), dechex(34));
812    $xml_rep_table['"'] = '&quot;';
813    }
814
815  // encode for RTF
816  if ($enctype=='xml')
817    return strtr($str, $xml_rep_table);
818
819  // encode for javascript use
820  if ($enctype=='js')
821    return preg_replace(array("/\r\n/", '/"/', "/([^\\\])'/"), array('\n', '\"', "$1\'"), strtr($str, $js_rep_table));
822
823  // encode for RTF
824  if ($enctype=='rtf')
825    return preg_replace("/\r\n/", "\par ", strtr($str, $rtf_rep_table));
826
827  // no encoding given -> return original string
828  return $str;
829  }
830
831
832
833// ************** template parsing and gui functions **************
834
835
836// return boolean if a specific template exists
837function template_exists($name)
838  {
839  global $CONFIG, $OUTPUT;
840  $skin_path = $CONFIG['skin_path'];
841
842  // check template file
843  return is_file("$skin_path/templates/$name.html");
844  }
845
846
847// get page template an replace variable
848// similar function as used in nexImage
849function parse_template($name='main', $exit=TRUE)
850  {
851  global $CONFIG, $OUTPUT;
852  $skin_path = $CONFIG['skin_path'];
853
854  // read template file
855  $templ = '';
856  $path = "$skin_path/templates/$name.html";
857
858  if($fp = @fopen($path, 'r'))
859    {
860    $templ = fread($fp, filesize($path));
861    fclose($fp);
862    }
863  else
864    {
865    raise_error(array('code' => 500,
866                      'type' => 'php',
867                      'line' => __LINE__,
868                      'file' => __FILE__,
869                      'message' => "Error loading template for '$name'"), TRUE, TRUE);
870    return FALSE;
871    }
872
873
874  // parse for specialtags
875  $output = parse_rcube_xml($templ);
876 
877  $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
878
879  if ($exit)
880    exit;
881  }
882
883
884
885// replace all strings ($varname) with the content of the according global variable
886function parse_with_globals($input)
887  {
888  $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
889  $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
890  return $output;
891  }
892
893
894
895function parse_rcube_xml($input)
896  {
897  $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
898  return $output;
899  }
900
901
902function rcube_xml_command($command, $str_attrib, $a_attrib=NULL)
903  {
904  global $IMAP, $CONFIG, $OUTPUT;
905 
906  $attrib = array();
907  $command = strtolower($command);
908
909  preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str_attrib), $regs, PREG_SET_ORDER);
910
911  // convert attributes to an associative array (name => value)
912  if ($regs)
913    foreach ($regs as $attr)
914      $attrib[strtolower($attr[1])] = $attr[2];
915  else if ($a_attrib)
916    $attrib = $a_attrib;
917
918  // execute command
919  switch ($command)
920    {
921    // return a button
922    case 'button':
923      if ($attrib['command'])
924        return rcube_button($attrib);
925      break;
926
927    // show a label
928    case 'label':
929      if ($attrib['name'] || $attrib['command'])
930        return rep_specialchars_output(rcube_label($attrib));
931      break;
932
933    // create a menu item
934    case 'menu':
935      if ($attrib['command'] && $attrib['group'])
936        rcube_menu($attrib);
937      break;
938
939    // include a file
940    case 'include':
941      $path = realpath($CONFIG['skin_path'].$attrib['file']);
942     
943      if($fp = @fopen($path, 'r'))
944        {
945        $incl = fread($fp, filesize($path));
946        fclose($fp);       
947        return parse_rcube_xml($incl);
948        }
949      break;
950
951    // return code for a specific application object
952    case 'object':
953      $object = strtolower($attrib['name']);
954
955      $object_handlers = array(
956        // GENERAL
957        'loginform' => 'rcmail_login_form',
958        'username'  => 'rcmail_current_username',
959       
960        // MAIL
961        'mailboxlist' => 'rcmail_mailbox_list',
962        'message' => 'rcmail_message_container',
963        'messages' => 'rcmail_message_list',
964        'messagecountdisplay' => 'rcmail_messagecount_display',
965        'quotadisplay' => 'rcmail_quota_display',
966        'messageheaders' => 'rcmail_message_headers',
967        'messagebody' => 'rcmail_message_body',
968        'messageattachments' => 'rcmail_message_attachments',
969        'blockedobjects' => 'rcmail_remote_objects_msg',
970        'messagecontentframe' => 'rcmail_messagecontent_frame',
971        'messagepartframe' => 'rcmail_message_part_frame',
972        'messagepartcontrols' => 'rcmail_message_part_controls',
973        'composeheaders' => 'rcmail_compose_headers',
974        'composesubject' => 'rcmail_compose_subject',
975        'composebody' => 'rcmail_compose_body',
976        'composeattachmentlist' => 'rcmail_compose_attachment_list',
977        'composeattachmentform' => 'rcmail_compose_attachment_form',
978        'composeattachment' => 'rcmail_compose_attachment_field',
979        'priorityselector' => 'rcmail_priority_selector',
980        'charsetselector' => 'rcmail_charset_selector',
981       
982        // ADDRESS BOOK
983        'addresslist' => 'rcmail_contacts_list',
984        'addressframe' => 'rcmail_contact_frame',
985        'recordscountdisplay' => 'rcmail_rowcount_display',
986        'contactdetails' => 'rcmail_contact_details',
987        'contacteditform' => 'rcmail_contact_editform',
988        'ldappublicsearch' => 'rcmail_ldap_public_search_form',
989        'ldappublicaddresslist' => 'rcmail_ldap_public_list',
990
991        // USER SETTINGS
992        'userprefs' => 'rcmail_user_prefs_form',
993        'itentitieslist' => 'rcmail_identities_list',
994        'identityframe' => 'rcmail_identity_frame',
995        'identityform' => 'rcube_identity_form',
996        'foldersubscription' => 'rcube_subscription_form',
997        'createfolder' => 'rcube_create_folder_form',
998        'composebody' => 'rcmail_compose_body'
999      );
1000
1001     
1002      // execute object handler function
1003      if ($object_handlers[$object] && function_exists($object_handlers[$object]))
1004        return call_user_func($object_handlers[$object], $attrib);
1005
1006      else if ($object=='pagetitle')
1007        {
1008        $task = $GLOBALS['_task'];
1009        $title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
1010       
1011        if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
1012          $title .= $GLOBALS['MESSAGE']['subject'];
1013        else if (isset($GLOBALS['PAGE_TITLE']))
1014          $title .= $GLOBALS['PAGE_TITLE'];
1015        else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
1016          $title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
1017        else
1018          $title .= $task;
1019         
1020        return rep_specialchars_output($title, 'html', 'all');
1021        }
1022
1023      break;
1024    }
1025
1026  return '';
1027  }
1028
1029
1030// create and register a button
1031function rcube_button($attrib)
1032  {
1033  global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER;
1034  static $sa_buttons = array();
1035  static $s_button_count = 100;
1036 
1037  $skin_path = $CONFIG['skin_path'];
1038 
1039  if (!($attrib['command'] || $attrib['name']))
1040    return '';
1041
1042  // try to find out the button type
1043  if ($attrib['type'])
1044    $attrib['type'] = strtolower($attrib['type']);
1045  else
1046    $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imagect']) ? 'image' : 'link';
1047 
1048 
1049  $command = $attrib['command'];
1050 
1051  // take the button from the stack
1052  if($attrib['name'] && $sa_buttons[$attrib['name']])
1053    $attrib = $sa_buttons[$attrib['name']];
1054
1055  // add button to button stack
1056  else if($attrib['image'] || $arg['imagect'] || $attrib['imagepas'] || $attrib['class'])
1057    {
1058    if(!$attrib['name'])
1059      $attrib['name'] = $command;
1060
1061    if (!$attrib['image'])
1062      $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1063
1064    $sa_buttons[$attrib['name']] = $attrib;
1065    }
1066
1067  // get saved button for this command/name
1068  else if ($command && $sa_buttons[$command])
1069    $attrib = $sa_buttons[$command];
1070
1071  //else
1072  //  return '';
1073
1074
1075  // set border to 0 because of the link arround the button
1076  if ($attrib['type']=='image' && !isset($attrib['border']))
1077    $attrib['border'] = 0;
1078   
1079  if (!$attrib['id'])
1080    $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
1081
1082  // get localized text for labels and titles
1083  if ($attrib['title'])
1084    $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
1085  if ($attrib['label'])
1086    $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
1087
1088  if ($attrib['alt'])
1089    $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
1090
1091  // set title to alt attribute for IE browsers
1092  if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
1093    {
1094    $attrib['alt'] = $attrib['title'];
1095    unset($attrib['title']);
1096    }
1097
1098  // add empty alt attribute for XHTML compatibility
1099  if (!isset($attrib['alt']))
1100    $attrib['alt'] = '';
1101
1102
1103  // register button in the system
1104  if ($attrib['command'])
1105    $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
1106                                $JS_OBJECT_NAME,
1107                                $command,
1108                                $attrib['id'],
1109                                $attrib['type'],
1110                                $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
1111                                $attirb['imagesel'] ? $skin_path.$attirb['imagesel'] : $attrib['classsel'],
1112                                $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
1113
1114  // overwrite attributes
1115  if (!$attrib['href'])
1116    $attrib['href'] = '#';
1117
1118  if ($command)
1119    $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
1120   
1121  if ($command && $attrib['imageover'])
1122    {
1123    $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1124    $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1125    }
1126
1127
1128  $out = '';
1129
1130  // generate image tag
1131  if ($attrib['type']=='image')
1132    {
1133    $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
1134    $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
1135    $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
1136    if ($attrib['label'])
1137      $btn_content .= ' '.$attrib['label'];
1138   
1139    $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'title');
1140    }
1141  else if ($attrib['type']=='link')
1142    {
1143    $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
1144    $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
1145    }
1146  else if ($attrib['type']=='input')
1147    {
1148    $attrib['type'] = 'button';
1149   
1150    if ($attrib['label'])
1151      $attrib['value'] = $attrib['label'];
1152     
1153    $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
1154    $out = sprintf('<input%s disabled />', $attrib_str);
1155    }
1156
1157  // generate html code for button
1158  if ($btn_content)
1159    {
1160    $attrib_str = create_attrib_string($attrib, $link_attrib);
1161    $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1162    }
1163
1164  return $out;
1165  }
1166
1167
1168function rcube_menu($attrib)
1169  {
1170 
1171  return '';
1172  }
1173
1174
1175
1176function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1177  {
1178  global $DB;
1179 
1180  // allow the following attributes to be added to the <table> tag
1181  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1182 
1183  $table = '<table' . $attrib_str . ">\n";
1184   
1185  // add table title
1186  $table .= "<thead><tr>\n";
1187
1188  foreach ($a_show_cols as $col)
1189    $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
1190
1191  $table .= "</tr></thead>\n<tbody>\n";
1192 
1193  $c = 0;
1194
1195  if (!is_array($table_data))
1196    {
1197    while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1198      {
1199      $zebra_class = $c%2 ? 'even' : 'odd';
1200
1201      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1202
1203      // format each col
1204      foreach ($a_show_cols as $col)
1205        {
1206        $cont = rep_specialchars_output($sql_arr[$col]);
1207            $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1208        }
1209
1210      $table .= "</tr>\n";
1211      $c++;
1212      }
1213    }
1214  else
1215    {
1216    foreach ($table_data as $row_data)
1217      {
1218      $zebra_class = $c%2 ? 'even' : 'odd';
1219
1220      $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1221
1222      // format each col
1223      foreach ($a_show_cols as $col)
1224        {
1225        $cont = rep_specialchars_output($row_data[$col]);
1226            $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1227        }
1228
1229      $table .= "</tr>\n";
1230      $c++;
1231      }
1232    }
1233
1234  // complete message table
1235  $table .= "</tbody></table>\n";
1236 
1237  return $table;
1238  }
1239
1240
1241
1242function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1243  {
1244  $fname = '_'.$col;
1245  $attrib['name'] = $fname;
1246 
1247  if ($type=='checkbox')
1248    {
1249    $attrib['value'] = '1';
1250    $input = new checkbox($attrib);
1251    }
1252  else if ($type=='textarea')
1253    {
1254    $attrib['cols'] = $attrib['size'];
1255    $input = new textarea($attrib);
1256    }
1257  else
1258    $input = new textfield($attrib);
1259
1260  // use value from post
1261  if (!empty($_POST[$fname]))
1262    $value = $_POST[$fname];
1263
1264  $out = $input->show($value);
1265         
1266  return $out;
1267  }
1268
1269
1270function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1271  {
1272  // allow the following attributes to be added to the <iframe> tag
1273  $attrib_str = '';
1274  foreach ($allowed_attribs as $a)
1275    if (isset($attrib[$a]))
1276      $attrib_str .= sprintf(' %s="%s"', $a, $attrib[$a]);
1277
1278  return $attrib_str;
1279  }
1280
1281
1282
1283function format_date($date, $format=NULL)
1284  {
1285  global $CONFIG, $sess_user_lang;
1286 
1287  if (is_numeric($date))
1288    $ts = $date;
1289  else if (!empty($date))
1290    $ts = strtotime($date);
1291  else
1292    return '';
1293
1294  // convert time to user's timezone
1295  $timestamp = $ts - date('Z', $ts) + ($CONFIG['timezone'] * 3600);
1296 
1297  // get current timestamp in user's timezone
1298  $now = time();  // local time
1299  $now -= (int)date('Z'); // make GMT time
1300  $now += ($CONFIG['timezone'] * 3600); // user's time
1301  $now_date = getdate();
1302
1303  //$day_secs = 60*((int)date('H', $now)*60 + (int)date('i', $now));
1304  //$week_secs = 60 * 60 * 24 * 7;
1305  //$diff = $now - $timestamp;
1306  $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1307  $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1308
1309  // define date format depending on current time 
1310  if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
1311    return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
1312  else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
1313    $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1314  else if (!$format)
1315    $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1316
1317
1318  // parse format string manually in order to provide localized weekday and month names
1319  // an alternative would be to convert the date() format string to fit with strftime()
1320  $out = '';
1321  for($i=0; $i<strlen($format); $i++)
1322    {
1323    if ($format{$i}=='\\')  // skip escape chars
1324      continue;
1325   
1326    // write char "as-is"
1327    if ($format{$i}==' ' || $format{$i-1}=='\\')
1328      $out .= $format{$i};
1329    // weekday (short)
1330    else if ($format{$i}=='D')
1331      $out .= rcube_label(strtolower(date('D', $timestamp)));
1332    // weekday long
1333    else if ($format{$i}=='l')
1334      $out .= rcube_label(strtolower(date('l', $timestamp)));
1335    // month name (short)
1336    else if ($format{$i}=='M')
1337      $out .= rcube_label(strtolower(date('M', $timestamp)));
1338    // month name (long)
1339    else if ($format{$i}=='F')
1340      $out .= rcube_label(strtolower(date('F', $timestamp)));
1341    else
1342      $out .= date($format{$i}, $timestamp);
1343    }
1344 
1345  return $out;
1346  }
1347
1348
1349// ************** functions delivering gui objects **************
1350
1351
1352
1353function rcmail_message_container($attrib)
1354  {
1355  global $OUTPUT, $JS_OBJECT_NAME;
1356
1357  if (!$attrib['id'])
1358    $attrib['id'] = 'rcmMessageContainer';
1359
1360  // allow the following attributes to be added to the <table> tag
1361  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1362  $out = '<div' . $attrib_str . "></div>";
1363 
1364  $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1365 
1366  return $out;
1367  }
1368
1369
1370// return the IMAP username of the current session
1371function rcmail_current_username($attrib)
1372  {
1373  global $DB;
1374  static $s_username;
1375
1376  // alread fetched 
1377  if (!empty($s_username))
1378    return $s_username;
1379
1380  // get e-mail address form default identity
1381  $sql_result = $DB->query("SELECT email AS mailto
1382                            FROM ".get_table_name('identities')."
1383                            WHERE  user_id=?
1384                            AND    standard=1
1385                            AND    del<>1",
1386                            $_SESSION['user_id']);
1387                                   
1388  if ($DB->num_rows($sql_result))
1389    {
1390    $sql_arr = $DB->fetch_assoc($sql_result);
1391    $s_username = $sql_arr['mailto'];
1392    }
1393  else if (strstr($_SESSION['username'], '@'))
1394    $s_username = $_SESSION['username'];
1395  else
1396    $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1397
1398  return $s_username;
1399  }
1400
1401
1402// return code for the webmail login form
1403function rcmail_login_form($attrib)
1404  {
1405  global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1406 
1407  $labels = array();
1408  $labels['user'] = rcube_label('username');
1409  $labels['pass'] = rcube_label('password');
1410  $labels['host'] = rcube_label('server');
1411 
1412  $input_user = new textfield(array('name' => '_user', 'size' => 30));
1413  $input_pass = new passwordfield(array('name' => '_pass', 'size' => 30));
1414  $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
1415   
1416  $fields = array();
1417  $fields['user'] = $input_user->show($_POST['_user']);
1418  $fields['pass'] = $input_pass->show();
1419  $fields['action'] = $input_action->show();
1420 
1421  if (is_array($CONFIG['default_host']))
1422    {
1423    $select_host = new select(array('name' => '_host'));
1424   
1425    foreach ($CONFIG['default_host'] as $key => $value)
1426      $select_host->add($value, (is_numeric($key) ? $value : $key));
1427     
1428    $fields['host'] = $select_host->show($_POST['_host']);
1429    }
1430  else if (!strlen($CONFIG['default_host']))
1431    {
1432        $input_host = new textfield(array('name' => '_host', 'size' => 30));
1433        $fields['host'] = $input_host->show($_POST['_host']);
1434    }
1435
1436  $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1437  $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1438  $form_end = !strlen($attrib['form']) ? '</form>' : '';
1439 
1440  if ($fields['host'])
1441    $form_host = <<<EOF
1442   
1443</tr><tr>
1444
1445<td class="title">$labels[host]</td>
1446<td>$fields[host]</td>
1447
1448EOF;
1449
1450  $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1451 
1452  $out = <<<EOF
1453$form_start
1454$SESS_HIDDEN_FIELD
1455$fields[action]
1456<table><tr>
1457
1458<td class="title">$labels[user]</td>
1459<td>$fields[user]</td>
1460
1461</tr><tr>
1462
1463<td class="title">$labels[pass]</td>
1464<td>$fields[pass]</td>
1465$form_host
1466</tr></table>
1467$form_end
1468EOF;
1469
1470  return $out;
1471  }
1472
1473
1474
1475function rcmail_charset_selector($attrib)
1476  {
1477  // pass the following attributes to the form class
1478  $field_attrib = array('name' => '_charset');
1479  foreach ($attrib as $attr => $value)
1480    if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1481      $field_attrib[$attr] = $value;
1482     
1483  $charsets = array(
1484    'US-ASCII'     => 'ASCII (English)',
1485    'X-EUC-JP'     => 'EUC-JP (Japanese)',
1486    'EUC-KR'       => 'EUC-KR (Korean)',
1487    'BIG5'         => 'BIG5 (Chinese)',
1488    'GB2312'       => 'GB2312 (Chinese)',
1489    'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
1490    'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1491    'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1492    'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1493    'Windows-1251' => 'Windows-1251 (Cyrillic)',
1494    'Windows-1252' => 'Windows-1252 (Western)',
1495    'Windows-1255' => 'Windows-1255 (Hebrew)',
1496    'Windows-1256' => 'Windows-1256 (Arabic)',
1497    'Windows-1257' => 'Windows-1257 (Baltic)',
1498    'UTF-8'        => 'UTF-8'
1499    );
1500
1501  $select = new select($field_attrib);
1502  $select->add(array_values($charsets), array_keys($charsets));
1503 
1504  $set = $_POST['_charset'] ? $_POST['_charset'] : $GLOBALS['CHARSET'];
1505  return $select->show($set);
1506  }
1507
1508
1509function rcube_timer()
1510  {
1511  list($usec, $sec) = explode(" ", microtime());
1512  return ((float)$usec + (float)$sec);
1513  }
1514 
1515
1516function rcube_print_time($timer, $label='Timer')
1517  {
1518  static $print_count = 0;
1519 
1520  $print_count++;
1521  $now = rcube_timer();
1522  $diff = $now-$timer;
1523 
1524  if (empty($label))
1525    $label = 'Timer '.$print_count;
1526 
1527  console(sprintf("%s: %0.4f sec", $label, $diff));
1528  }
1529
1530?>
Note: See TracBrowser for help on using the repository browser.