source: github/program/include/main.inc @ 36df57c

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 36df57c was 36df57c, checked in by thomascube <thomas@…>, 8 years ago

Edited MDB2 support

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