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