source: github/program/include/main.inc @ f3b6599

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

Added patches for default language and sorting function

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