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

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

Minor bugfixes and SMTP support

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