thomascube
2005-11-08 583f1c8d80c42195d0ee41f30a885e13d777b79f
commit | author | age
4e17e6 1 <?php
T 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                      |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 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
22 require_once('lib/des.inc');
23
24
25 // register session and connect to server
26 function rcmail_startup($task='mail')
27   {
28   global $sess_id, $sess_auth, $sess_user_lang;
29   global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
30
31   // check client
32   $BROWSER = rcube_browser();
de2e1e 33
4e17e6 34   // load config file
T 35   include_once('config/main.inc.php');
36   $CONFIG = is_array($rcmail_config) ? $rcmail_config : array();
37   $CONFIG['skin_path'] = $CONFIG['skin_path'] ? preg_replace('/\/$/', '', $CONFIG['skin_path']) : 'skins/default';
38
39   // load db conf
40   include_once('config/db.inc.php');
41   $CONFIG = array_merge($CONFIG, $rcmail_config);
42
43
44   // set PHP error logging according to config
45   if ($CONFIG['debug_level'] & 1)
46     {
47     ini_set('log_errors', 1);
48     ini_set('error_log', $INSTALL_PATH.'logs/errors');  
49     }
50   if ($CONFIG['debug_level'] & 4)
51     ini_set('display_errors', 1);
52   else
53     ini_set('display_errors', 0);
7902df 54   
T 55   // set session garbage collecting time according to session_lifetime
56   if (!empty($CONFIG['session_lifetime']))
57     ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']+2)*60);
4e17e6 58
T 59
60   // prepare DB connection
f45ec7 61   require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
S 62   
1676e1 63   $DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr']);
42b113 64   $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
4e17e6 65
T 66   // we can use the database for storing session data
36df57 67   // session queries do not work with MDB2
T 68   if ($CONFIG['db_backend']!='mdb2' && is_object($DB) && $DB->db_provider!='sqlite')
4e17e6 69     include_once('include/session.inc');
T 70
71
72   // init session
73   session_start();
74   $sess_id = session_id();
75   
76   // create session and set session vars
77   if (!$_SESSION['client_id'])
78     {
79     $_SESSION['client_id'] = $sess_id;
f3b659 80     $_SESSION['user_lang'] = substr($CONFIG['locale_string'], 0, 2);
4e17e6 81     $_SESSION['auth_time'] = mktime();
T 82     $_SESSION['auth'] = rcmail_auth_hash($sess_id, $_SESSION['auth_time']);
83     unset($GLOBALS['_auth']);
84     }
85
86   // set session vars global
87   $sess_auth = $_SESSION['auth'];
88   $sess_user_lang = $_SESSION['user_lang'];
89
90
91   // overwrite config with user preferences
92   if (is_array($_SESSION['user_prefs']))
93     $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
94
95
96   // reset some session parameters when changing task
97   if ($_SESSION['task'] != $task)
98     unset($_SESSION['page']);
99
100   // set current task to session
101   $_SESSION['task'] = $task;
102
103
104   // create IMAP object
105   if ($task=='mail')
106     rcmail_imap_init();
107
108
109   // set localization
110   if ($CONFIG['locale_string'])
111     setlocale(LC_ALL, $CONFIG['locale_string']);
112   else if ($sess_user_lang)
113     setlocale(LC_ALL, $sess_user_lang);
114
115
116   register_shutdown_function('rcmail_shutdown');
117   }
118   
119
120 // create authorization hash
121 function rcmail_auth_hash($sess_id, $ts)
122   {
123   global $CONFIG;
124   
125   $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
126                          $sess_id,
127                          $ts,
128                          $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
129                          $_SERVER['HTTP_USER_AGENT']);
130   
131   if (function_exists('sha1'))
132     return sha1($auth_string);
133   else
134     return md5($auth_string);
135   }
136
137
138
139 // create IMAP object and connect to server
140 function rcmail_imap_init($connect=FALSE)
141   {
142   global $CONFIG, $IMAP;
6dc026 143
4e17e6 144   $IMAP = new rcube_imap();
T 145
7902df 146   // connect with stored session data
T 147   if ($connect)
148     {
149     if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
150       show_message('imaperror', 'error');
151       
152     rcmail_set_imap_prop();
153     }
154
6dc026 155   // enable caching of imap data
T 156   if ($CONFIG['enable_caching']===TRUE)
157     $IMAP->set_caching(TRUE);
158
4e17e6 159   if (is_array($CONFIG['default_imap_folders']))
T 160     $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
161
162   // set pagesize from config
163   if (isset($CONFIG['pagesize']))
164     $IMAP->set_pagesize($CONFIG['pagesize']);
7902df 165   }
4e17e6 166
T 167
7902df 168 // set root dir and last stored mailbox
T 169 // this must be done AFTER connecting to the server
170 function rcmail_set_imap_prop()
171   {
172   global $CONFIG, $IMAP;
173
174   // set root dir from config
175   if (strlen($CONFIG['imap_root']))
176     $IMAP->set_rootdir($CONFIG['imap_root']);
177
178   if (strlen($_SESSION['mbox']))
179     $IMAP->set_mailbox($_SESSION['mbox']);
180     
181   if (isset($_SESSION['page']))
182     $IMAP->set_page($_SESSION['page']);
4e17e6 183   }
T 184
185
186 // do these things on script shutdown
187 function rcmail_shutdown()
188   {
189   global $IMAP;
190   
191   if (is_object($IMAP))
192     {
193     $IMAP->close();
194     $IMAP->write_cache();
195     }
196   }
197
198
199 // destroy session data and remove cookie
200 function rcmail_kill_session()
201   {
202 /* $sess_name = session_name();
203   if (isset($_COOKIE[$sess_name]))
204    setcookie($sess_name, '', time()-42000, '/');
205 */
206   $_SESSION = array();
207   session_destroy();
208   }
209
210
211 // return correct name for a specific database table
212 function get_table_name($table)
213   {
214   global $CONFIG;
215   
216   // return table name if configured
217   $config_key = 'db_table_'.$table;
218
219   if (strlen($CONFIG[$config_key]))
220     return $CONFIG[$config_key];
221   
222   return $table;
223   }
224
225
226
227 // init output object for GUI and add common scripts
228 function load_gui()
229   {
7cc38e 230   global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
4e17e6 231
T 232   // init output page
233   $OUTPUT = new rcube_html_page();
234   
235   // add common javascripts
236   $javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
237   $javascript .= "$JS_OBJECT_NAME.set_env('comm_path', '$COMM_PATH');\n";
238
597170 239   if (!empty($GLOBALS['_framed']))
4e17e6 240     $javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
7cc38e 241     
4e17e6 242   $OUTPUT->add_script($javascript);
T 243   $OUTPUT->include_script('program/js/common.js');
7cc38e 244   $OUTPUT->include_script('program/js/app.js');
T 245
246   // set user-selected charset
247   if ($CONFIG['charset'])
248     $OUTPUT->set_charset($CONFIG['charset']);
249   else
250     rcmail_set_locale($sess_user_lang);
10a699 251   
T 252   // add some basic label to client
253   rcube_add_label('loading');
4e17e6 254   }  
7cc38e 255
T 256
257 // set localization charset based on the given language
258 function rcmail_set_locale($lang)
259   {
260   global $OUTPUT, $INSTLL_PATH;
261   static $rcube_charsets;
262
263   if (!$rcube_charsets)
264     @include($INSTLL_PATH.'program/localization/index.inc');
265
266   if (isset($rcube_charsets[$lang]))
267     $OUTPUT->set_charset($rcube_charsets[$lang]);
268   else
269     $OUTPUT->set_charset('ISO-8859-1');
270   }
4e17e6 271
T 272
273 // perfom login to the IMAP server and to the webmail service
274 function rcmail_login($user, $pass, $host=NULL)
275   {
276   global $CONFIG, $IMAP, $DB, $sess_user_lang;
42b113 277   $user_id = NULL;
4e17e6 278   
T 279   if (!$host)
280     $host = $CONFIG['default_host'];
281
f619de 282   // parse $host URL
T 283   $a_host = parse_url($host);
284   if ($a_host['host'])
285     {
286     $host = $a_host['host'];
287     $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
288     $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
289     }
290
4e17e6 291   // query if user already registered
d7cb77 292   $sql_result = $DB->query("SELECT user_id, username, language, preferences
S 293                             FROM ".get_table_name('users')."
294                             WHERE  mail_host=? AND (username=? OR alias=?)",
295                             $host,
296                             $user,
297                             $user);
4e17e6 298
42b113 299   // user already registered -> overwrite username
4e17e6 300   if ($sql_arr = $DB->fetch_assoc($sql_result))
T 301     {
302     $user_id = $sql_arr['user_id'];
42b113 303     $user = $sql_arr['username'];
T 304     }
305
306   // exit if IMAP login failed
307   if (!($imap_login  = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
308     return FALSE;
309
310   // user already registered
311   if ($user_id && !empty($sql_arr))
312     {
4e17e6 313     // get user prefs
T 314     if (strlen($sql_arr['preferences']))
315       {
316       $user_prefs = unserialize($sql_arr['preferences']);
317       $_SESSION['user_prefs'] = $user_prefs;
318       array_merge($CONFIG, $user_prefs);
319       }
320
f3b659 321
4e17e6 322     // set user specific language
T 323     if (strlen($sql_arr['language']))
324       $sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
f3b659 325       
4e17e6 326     // update user's record
d7cb77 327     $DB->query("UPDATE ".get_table_name('users')."
667737 328                 SET    last_login=now()
d7cb77 329                 WHERE  user_id=?",
S 330                 $user_id);
4e17e6 331     }
T 332   // create new system user
333   else if ($CONFIG['auto_create_user'])
334     {
335     $user_id = rcmail_create_user($user, $host);
336     }
337
338   if ($user_id)
339     {
340     $_SESSION['user_id']   = $user_id;
341     $_SESSION['imap_host'] = $host;
7902df 342     $_SESSION['imap_port'] = $imap_port;
T 343     $_SESSION['imap_ssl']  = $imap_ssl;
4e17e6 344     $_SESSION['username']  = $user;
f3b659 345     $_SESSION['user_lang'] = $sess_user_lang;
4e17e6 346     $_SESSION['password']  = encrypt_passwd($pass);
T 347
348     // force reloading complete list of subscribed mailboxes    
349     $IMAP->clear_cache('mailboxes');
350
351     return TRUE;
352     }
353
354   return FALSE;
355   }
356
357
358 // create new entry in users and identities table
359 function rcmail_create_user($user, $host)
360   {
361   global $DB, $CONFIG, $IMAP;
f3b659 362   
d7cb77 363   $DB->query("INSERT INTO ".get_table_name('users')."
S 364               (created, last_login, username, mail_host, language)
667737 365               VALUES (now(), now(), ?, ?, ?)",
d7cb77 366               $user,
S 367               $host,
368               $_SESSION['user_lang']);
4e17e6 369
d7cb77 370   if ($user_id = $DB->insert_id('user_ids'))
4e17e6 371     {
52c1f2 372     $user_email = strstr($user, '@') ? $user : sprintf('%s@%s', $user, $host);
T 373     $user_name = $user!=$user_email ? $user : '';
374     
4e17e6 375     // also create a new identity record
d7cb77 376     $DB->query("INSERT INTO ".get_table_name('identities')."
S 377                 (user_id, `default`, name, email)
378                 VALUES (?, '1', ?, ?)",
379                 $user_id,
380                 $user_name,
381                 $user_email);
4e17e6 382                        
T 383     // get existing mailboxes
384     $a_mailboxes = $IMAP->list_mailboxes();
385     
386     // check if the configured mailbox for sent messages exists
387     if ($CONFIG['sent_mbox'] && !in_array_nocase($CONFIG['sent_mbox'], $a_mailboxes))
388       $IMAP->create_mailbox($CONFIG['sent_mbox'], TRUE);
389
390     // check if the configured mailbox for sent messages exists
391     if ($CONFIG['trash_mbox'] && !in_array_nocase($CONFIG['trash_mbox'], $a_mailboxes))
392       $IMAP->create_mailbox($CONFIG['trash_mbox'], TRUE);
42b113 393     }
T 394   else
395     {
396     raise_error(array('code' => 500,
397                       'type' => 'php',
398                       'line' => __LINE__,
399                       'file' => __FILE__,
400                       'message' => "Failed to create new user"), TRUE, FALSE);
4e17e6 401     }
T 402     
403   return $user_id;
404   }
405
406
10a699 407 // overwrite action variable  
T 408 function rcmail_overwrite_action($action)
409   {
410   global $OUTPUT, $JS_OBJECT_NAME;
411   $GLOBALS['_action'] = $action;
412
413   $OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $action));  
414   }
415
416
4e17e6 417 function show_message($message, $type='notice')
T 418   {
419   global $OUTPUT, $JS_OBJECT_NAME, $REMOTE_REQUEST;
420
597170 421   $framed = $GLOBALS['_framed'];
4e17e6 422   $command = sprintf("display_message('%s', '%s');",
T 423                      addslashes(rep_specialchars_output(rcube_label($message))),
424                      $type);
425                      
426   if ($REMOTE_REQUEST)
427     return 'this.'.$command;
428   
429   else
430     $OUTPUT->add_script(sprintf("%s%s.%s",
431                                 $framed ? sprintf('if(parent.%s)parent.', $JS_OBJECT_NAME) : '',
432                                 $JS_OBJECT_NAME,
433                                 $command));
434   
435   // console(rcube_label($message));
436   }
437
438
439 function console($msg, $type=1)
440   {
520c36 441   if ($GLOBALS['REMOTE_REQUEST'])
T 442     print "// $msg\n";
443   else
444     {
445     print $msg;
446     print "\n<hr>\n";
447     }
4e17e6 448   }
T 449
450
451 function encrypt_passwd($pass)
452   {
453   $cypher = des('rcmail?24BitPwDkeyF**ECB', $pass, 1, 0, NULL);
454   return base64_encode($cypher);
455   }
456
457
458 function decrypt_passwd($cypher)
459   {
460   $pass = des('rcmail?24BitPwDkeyF**ECB', base64_decode($cypher), 0, 0, NULL);
461   return trim($pass);
462   }
463
464
465 // send correct response on a remote request
466 function rcube_remote_response($js_code)
467   {
468   send_nocacheing_headers();
469   //header('Content-Type: text/javascript');
470   header('Content-Type: application/x-javascript');
471
472   print '/** remote response ['.date('d/M/Y h:i:s O')."] **/\n";
473   print $js_code;
474   exit;
475   }
476
477
9fee0e 478 // read directory program/localization/ and return a list of available languages
T 479 function rcube_list_languages()
480   {
481   global $CONFIG, $INSTALL_PATH;
482   static $sa_languages = array();
483
484   if (!sizeof($sa_languages))
485     {
7cc38e 486     @include($INSTLL_PATH.'program/localization/index.inc');
9fee0e 487
T 488     if ($dh = @opendir($INSTLL_PATH.'program/localization'))
489       {
490       while (($name = readdir($dh)) !== false)
491         {
492         if ($name{0}=='.' || !is_dir($INSTLL_PATH.'program/localization/'.$name))
493           continue;
494
495         if ($label = $rcube_languages[$name])
496           $sa_languages[$name] = $label ? $label : $name;
497         }
498       closedir($dh);
499       }
500     }
501
502   return $sa_languages;
503   }
504
4e17e6 505
10a699 506 // add a localized label to the client environment
T 507 function rcube_add_label()
508   {
509   global $OUTPUT, $JS_OBJECT_NAME;
510   
511   $arg_list = func_get_args();
512   foreach ($arg_list as $i => $name)
513     $OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
514                                 $JS_OBJECT_NAME,
515                                 $name,
516                                 rep_specialchars_output(rcube_label($name), 'js')));  
517   }
518
519
4e17e6 520
T 521 // ************** template parsing and gui functions **************
522
523
524 // return boolean if a specific template exists
525 function template_exists($name)
526   {
527   global $CONFIG, $OUTPUT;
528   $skin_path = $CONFIG['skin_path'];
529
530   // check template file
531   return is_file("$skin_path/templates/$name.html");
532   }
533
534
535 // get page template an replace variable
536 // similar function as used in nexImage
537 function parse_template($name='main', $exit=TRUE)
538   {
539   global $CONFIG, $OUTPUT;
540   $skin_path = $CONFIG['skin_path'];
541
542   // read template file
543   $templ = '';
544   $path = "$skin_path/templates/$name.html";
545
546   if($fp = @fopen($path, 'r'))
547     {
548     $templ = fread($fp, filesize($path));
549     fclose($fp);
550     }
551   else
552     {
553     raise_error(array('code' => 500,
554                       'type' => 'php',
555                       'line' => __LINE__,
556                       'file' => __FILE__,
557                       'message' => "Error loading template for '$name'"), TRUE, TRUE);
558     return FALSE;
559     }
560
561
562   // parse for specialtags
563   $output = parse_rcube_xml($templ);
564   
565   $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
566
567   if ($exit)
568     exit;
569   }
570
571
572
573 // replace all strings ($varname) with the content of the according global variable
574 function parse_with_globals($input)
575   {
b595c9 576   $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
4e17e6 577   $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
T 578   return $output;
579   }
580
581
582
583 function parse_rcube_xml($input)
584   {
585   $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
586   return $output;
587   }
588
589
590 function rcube_xml_command($command, $str_attrib, $a_attrib=NULL)
591   {
592   global $IMAP, $CONFIG;
593   
594   $attrib = array();
595   $command = strtolower($command);
596
597   preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str_attrib), $regs, PREG_SET_ORDER);
598
599   // convert attributes to an associative array (name => value)
600   if ($regs)
601     foreach ($regs as $attr)
602       $attrib[strtolower($attr[1])] = $attr[2];
603   else if ($a_attrib)
604     $attrib = $a_attrib;
605
606   // execute command
607   switch ($command)
608     {
609     // return a button
610     case 'button':
611       if ($attrib['command'])
612         return rcube_button($attrib);
613       break;
614
615     // show a label
616     case 'label':
617       if ($attrib['name'] || $attrib['command'])
7dd801 618         return rep_specialchars_output(rcube_label($attrib));
4e17e6 619       break;
T 620
621     // create a menu item
622     case 'menu':
623       if ($attrib['command'] && $attrib['group'])
624         rcube_menu($attrib);
625       break;
626
627     // include a file 
628     case 'include':
629       $path = realpath($CONFIG['skin_path'].$attrib['file']);
630       
631       if($fp = @fopen($path, 'r'))
632         {
633         $incl = fread($fp, filesize($path));
634         fclose($fp);        
635         return parse_rcube_xml($incl);
636         }
637       break;
638
639     // return code for a specific application object
640     case 'object':
641       $object = strtolower($attrib['name']);
642
643       if ($object=='loginform')
644         return rcmail_login_form($attrib);
645
646       else if ($object=='message')
647         return rcmail_message_container($attrib);
648
649       // MAIL
650       else if ($object=='mailboxlist' && function_exists('rcmail_mailbox_list'))
651         return rcmail_mailbox_list($attrib);
652         
653       else if ($object=='messages' && function_exists('rcmail_message_list'))
654         return rcmail_message_list($attrib);
655
656       else if ($object=='messagecountdisplay' && function_exists('rcmail_messagecount_display'))
657         return rcmail_messagecount_display($attrib);
658
659       else if ($object=='messageheaders' && function_exists('rcmail_message_headers'))
660         return rcmail_message_headers($attrib);
661
662       else if ($object=='messageattachments' && function_exists('rcmail_message_attachments'))
663         return rcmail_message_attachments($attrib);
664
665       else if ($object=='messagebody' && function_exists('rcmail_message_body'))
666         return rcmail_message_body($attrib);
667         
668       else if ($object=='blockedobjects' && function_exists('rcmail_remote_objects_msg'))
669         return rcmail_remote_objects_msg($attrib);
670
671       else if ($object=='messagecontentframe' && function_exists('rcmail_messagecontent_frame'))
672         return rcmail_messagecontent_frame($attrib);
673
674       else if ($object=='messagepartframe' && function_exists('rcmail_message_part_frame'))
675         return rcmail_message_part_frame($attrib);
676
677       else if ($object=='messagepartcontrols' && function_exists('rcmail_message_part_controls'))
678         return rcmail_message_part_controls($attrib);
679
680       else if ($object=='composeheaders' && function_exists('rcmail_compose_headers'))
681         return rcmail_compose_headers($attrib);
682
683       else if ($object=='composesubject' && function_exists('rcmail_compose_subject'))
684         return rcmail_compose_subject($attrib);
685
686       else if ($object=='composebody' && function_exists('rcmail_compose_body'))
687         return rcmail_compose_body($attrib);
688
689       else if ($object=='composeattachmentlist' && function_exists('rcmail_compose_attachment_list'))
690         return rcmail_compose_attachment_list($attrib);
691
692       else if ($object=='composeattachmentform' && function_exists('rcmail_compose_attachment_form'))
693         return rcmail_compose_attachment_form($attrib);
694
695       else if ($object=='composeattachment' && function_exists('rcmail_compose_attachment_field'))
696         return rcmail_compose_attachment_field($attrib);
697
698       else if ($object=='priorityselector' && function_exists('rcmail_priority_selector'))
699         return rcmail_priority_selector($attrib);
700         
701       else if ($object=='priorityselector' && function_exists('rcmail_priority_selector'))
702         return rcmail_priority_selector($attrib);
703
704
705       // ADDRESS BOOK
706       else if ($object=='addresslist' && function_exists('rcmail_contacts_list'))
707         return rcmail_contacts_list($attrib);
708
709       else if ($object=='addressframe' && function_exists('rcmail_contact_frame'))
710         return rcmail_contact_frame($attrib);
711
712       else if ($object=='recordscountdisplay' && function_exists('rcmail_rowcount_display'))
713         return rcmail_rowcount_display($attrib);
714         
715       else if ($object=='contactdetails' && function_exists('rcmail_contact_details'))
716         return rcmail_contact_details($attrib);
717
718       else if ($object=='contacteditform' && function_exists('rcmail_contact_editform'))
719         return rcmail_contact_editform($attrib);
720
721
722       // USER SETTINGS
723       else if ($object=='userprefs' && function_exists('rcmail_user_prefs_form'))
724         return rcmail_user_prefs_form($attrib);
725
726       else if ($object=='itentitieslist' && function_exists('rcmail_identities_list'))
727         return rcmail_identities_list($attrib);
728
729       else if ($object=='identityframe' && function_exists('rcmail_identity_frame'))
730         return rcmail_identity_frame($attrib);
731
732       else if ($object=='identityform' && function_exists('rcube_identity_form'))
733         return rcube_identity_form($attrib);
734
735       else if ($object=='foldersubscription' && function_exists('rcube_subscription_form'))
736         return rcube_subscription_form($attrib);
737
738       else if ($object=='createfolder' && function_exists('rcube_create_folder_form'))
739         return rcube_create_folder_form($attrib);
740
741
742       else if ($object=='pagetitle')
743         {
744         $task = $GLOBALS['_task'];
745         if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
746           return rep_specialchars_output("RoundCube|Mail :: ".$GLOBALS['MESSAGE']['subject']);
747         else if (isset($GLOBALS['PAGE_TITLE']))
748           return rep_specialchars_output("RoundCube|Mail :: ".$GLOBALS['PAGE_TITLE']);
749         else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
a95e0e 750           return "RoundCube|Mail :: ".rep_specialchars_output(UTF7DecodeString($mbox_name), 'html', 'all');
4e17e6 751         else
T 752           return "RoundCube|Mail :: $task";
753         }
754
755       else if ($object=='about')
756         return '';
757
758       break;
759     }
760
761   return '';
762   }
763
764
765 // create and register a button
766 function rcube_button($attrib)
767   {
14eafe 768   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER;
4e17e6 769   static $sa_buttons = array();
T 770   static $s_button_count = 100;
771   
772   $skin_path = $CONFIG['skin_path'];
773   
774   if (!($attrib['command'] || $attrib['name']))
775     return '';
776
777   // try to find out the button type
778   if ($attrib['type'])
779     $attrib['type'] = strtolower($attrib['type']);
780   else
781     $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imagect']) ? 'image' : 'link';
782   
783   
784   $command = $attrib['command'];
785   
786   // take the button from the stack
787   if($attrib['name'] && $sa_buttons[$attrib['name']])
788     $attrib = $sa_buttons[$attrib['name']];
789
790   // add button to button stack
791   else if($attrib['image'] || $arg['imagect'] || $attrib['imagepas'] || $attrib['class'])
792     {
793     if(!$attrib['name'])
794       $attrib['name'] = $command;
795
796     if (!$attrib['image'])
797       $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
798
799     $sa_buttons[$attrib['name']] = $attrib;
800     }
801
802   // get saved button for this command/name
803   else if ($command && $sa_buttons[$command])
804     $attrib = $sa_buttons[$command];
805
806   //else
807   //  return '';
808
809
810   // set border to 0 because of the link arround the button
811   if ($attrib['type']=='image' && !isset($attrib['border']))
812     $attrib['border'] = 0;
813     
814   if (!$attrib['id'])
815     $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
816
817   // get localized text for labels and titles
818   if ($attrib['title'])
819     $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
820   if ($attrib['label'])
821     $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
822
823   if ($attrib['alt'])
824     $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
14eafe 825
T 826   // set title to alt attribute for IE browsers
827   if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
828     {
829     $attrib['alt'] = $attrib['title'];
830     unset($attrib['title']);
831     }
832
4e17e6 833   // add empty alt attribute for XHTML compatibility
T 834   if (!isset($attrib['alt']))
835     $attrib['alt'] = '';
836
837
838   // register button in the system
839   if ($attrib['command'])
840     $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
841                                 $JS_OBJECT_NAME,
842                                 $command,
843                                 $attrib['id'],
844                                 $attrib['type'],
845                                 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
846                                 $attirb['imagesel'] ? $skin_path.$attirb['imagesel'] : $attrib['classsel'],
847                                 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
848
849   // overwrite attributes
850   if (!$attrib['href'])
851     $attrib['href'] = '#';
852
853   if ($command)
854     $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
855     
856   if ($command && $attrib['imageover'])
857     {
858     $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
859     $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
860     }
861
862
863   $out = '';
864
865   // generate image tag
866   if ($attrib['type']=='image')
867     {
868     $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'alt'));
869     $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
870     $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
871     if ($attrib['label'])
872       $btn_content .= ' '.$attrib['label'];
873     
874     $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'title');
875     }
876   else if ($attrib['type']=='link')
877     {
878     $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
879     $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
880     }
881   else if ($attrib['type']=='input')
882     {
883     $attrib['type'] = 'button';
884     
885     if ($attrib['label'])
886       $attrib['value'] = $attrib['label'];
887       
888     $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
889     $out = sprintf('<input%s disabled />', $attrib_str);
890     }
891
892   // generate html code for button
893   if ($btn_content)
894     {
895     $attrib_str = create_attrib_string($attrib, $link_attrib);
896     $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
897     }
898
899   return $out;
900   }
901
902
903 function rcube_menu($attrib)
904   {
905   
906   return '';
907   }
908
909
910
911 function rcube_table_output($attrib, $sql_result, $a_show_cols, $id_col)
912   {
913   global $DB;
914   
915   // allow the following attributes to be added to the <table> tag
916   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
917   
918   $table = '<table' . $attrib_str . ">\n";
919     
920   // add table title
921   $table .= "<thead><tr>\n";
922
923   foreach ($a_show_cols as $col)
1038d5 924     $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
4e17e6 925
T 926   $table .= "</tr></thead>\n<tbody>\n";
927   
928   $c = 0;
929   while ($sql_result && ($sql_arr = $DB->fetch_assoc($sql_result)))
930     {
931     $zebra_class = $c%2 ? 'even' : 'odd';
932
933     $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
934
935     // format each col
936     foreach ($a_show_cols as $col)
937       {
938       $cont = rep_specialchars_output($sql_arr[$col]);
939       $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
940       }
941
942     $table .= "</tr>\n";
943     $c++;
944     }
945
946   // complete message table
947   $table .= "</tbody></table>\n";
948   
949   return $table;
950   }
951
952
953
954 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
955   {
956   $fname = '_'.$col;
957   $attrib['name'] = $fname;
958   
959   if ($type=='checkbox')
960     {
961     $attrib['value'] = '1';
962     $input = new checkbox($attrib);
963     }
964   else if ($type=='textarea')
965     {
966     $attrib['cols'] = $attrib['size'];
967     $input = new textarea($attrib);
968     }
969   else
970     $input = new textfield($attrib);
971
972   // use value from post
597170 973   if (!empty($_POST[$fname]))
4e17e6 974     $value = $_POST[$fname];
T 975
976   $out = $input->show($value);
977          
978   return $out;
979   }
980
981
982 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
983   {
984   // allow the following attributes to be added to the <iframe> tag
985   $attrib_str = '';
986   foreach ($allowed_attribs as $a)
987     if (isset($attrib[$a]))
988       $attrib_str .= sprintf(' %s="%s"', $a, $attrib[$a]);
989
990   return $attrib_str;
991   }
992
993
994
995 function format_date($date, $format=NULL)
996   {
997   global $CONFIG, $sess_user_lang;
998   
999   if (is_numeric($date))
1000     $ts = $date;
b076a4 1001   else if (!empty($date))
4e17e6 1002     $ts = strtotime($date);
b076a4 1003   else
T 1004     return '';
4e17e6 1005
T 1006   // convert time to user's timezone
1007   $timestamp = $ts - date('Z', $ts) + ($CONFIG['timezone'] * 3600);
1008   
1009   // get current timestamp in user's timezone
1010   $now = time();  // local time
1011   $now -= (int)date('Z'); // make GMT time
1012   $now += ($CONFIG['timezone'] * 3600); // user's time
1013
1014   $day_secs = 60*((int)date('H', $now)*60 + (int)date('i', $now));
1015   $week_secs = 60 * 60 * 24 * 7;
1016   $diff = $now - $timestamp;
1017
30233b 1018   // define date format depending on current time  
T 1019   if ($CONFIG['prettydate'] && !$format && $diff < $day_secs)
4e17e6 1020     return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
30233b 1021   else if ($CONFIG['prettydate'] && !$format && $diff < $week_secs)
4e17e6 1022     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 1023   else if (!$format)
1024     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1025
1026
1027   // parse format string manually in order to provide localized weekday and month names
1028   // an alternative would be to convert the date() format string to fit with strftime()
1029   $out = '';
1030   for($i=0; $i<strlen($format); $i++)
1031     {
1032     if ($format{$i}=='\\')  // skip escape chars
1033       continue;
1034     
1035     // write char "as-is"
1036     if ($format{$i}==' ' || $format{$i-1}=='\\')
1037       $out .= $format{$i};
1038     // weekday (short)
1039     else if ($format{$i}=='D')
1040       $out .= rcube_label(strtolower(date('D', $timestamp)));
1041     // weekday long
1042     else if ($format{$i}=='l')
1043       $out .= rcube_label(strtolower(date('l', $timestamp)));
1044     // month name (short)
1045     else if ($format{$i}=='M')
1046       $out .= rcube_label(strtolower(date('M', $timestamp)));
1047     // month name (long)
1048     else if ($format{$i}=='F')
1049       $out .= rcube_label(strtolower(date('F', $timestamp)));
1050     else
1051       $out .= date($format{$i}, $timestamp);
1052     }
1053   
1054   return $out;
1055   }
1056
1057
1058 // ************** functions delivering gui objects **************
1059
1060
1061
1062 function rcmail_message_container($attrib)
1063   {
1064   global $OUTPUT, $JS_OBJECT_NAME;
1065
1066   if (!$attrib['id'])
1067     $attrib['id'] = 'rcmMessageContainer';
1068
1069   // allow the following attributes to be added to the <table> tag
1070   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1071   $out = '<div' . $attrib_str . "></div>";
1072   
1073   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1074   
1075   return $out;
1076   }
1077
1078
1079 // return code for the webmail login form
1080 function rcmail_login_form($attrib)
1081   {
1082   global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1083   
1084   $labels = array();
1085   $labels['user'] = rcube_label('username');
1086   $labels['pass'] = rcube_label('password');
1087   $labels['host'] = rcube_label('server');
1088   
1089   $input_user = new textfield(array('name' => '_user', 'size' => 30));
1090   $input_pass = new passwordfield(array('name' => '_pass', 'size' => 30));
1091   $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
1092     
1093   $fields = array();
1094   $fields['user'] = $input_user->show($_POST['_user']);
1095   $fields['pass'] = $input_pass->show();
1096   $fields['action'] = $input_action->show();
1097   
1098   if (is_array($CONFIG['default_host']))
1099     {
1100     $select_host = new select(array('name' => '_host'));
42b113 1101     
T 1102     foreach ($CONFIG['default_host'] as $key => $value)
1103       $select_host->add($value, (is_numeric($key) ? $value : $key));
1104       
4e17e6 1105     $fields['host'] = $select_host->show($_POST['_host']);
T 1106     }
1107   else if (!strlen($CONFIG['default_host']))
1108     {
1109     $input_host = new textfield(array('name' => '_host', 'size' => 30));
1110     $fields['host'] = $input_host->show($_POST['_host']);
1111     }
1112
1113   $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1114   $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1115   $form_end = !strlen($attrib['form']) ? '</form>' : '';
1116   
1117   if ($fields['host'])
1118     $form_host = <<<EOF
1119     
1120 </tr><tr>
1121
1122 <td class="title">$labels[host]</td>
1123 <td>$fields[host]</td>
1124
1125 EOF;
1126
1127   $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1128   
1129   $out = <<<EOF
1130 $form_start
1131 $SESS_HIDDEN_FIELD
1132 $fields[action]
1133 <table><tr>
1134
1135 <td class="title">$labels[user]</td>
1136 <td>$fields[user]</td>
1137
1138 </tr><tr>
1139
1140 <td class="title">$labels[pass]</td>
1141 <td>$fields[pass]</td>
1142 $form_host
1143 </tr></table>
1144 $form_end
1145 EOF;
1146
1147   return $out;
1148   }
1149
1150
1151 ?>