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

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

SMTPS support and minor bugfixes

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