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

Last change on this file since 19 was 19, checked in by roundcube, 8 years ago

Make message caching configurable

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