]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_template.php
Imported Upstream version 0.3
[roundcube.git] / program / include / rcube_template.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_template.php                                    |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2006-2009, RoundCube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Class to handle HTML page output using a skin template.             |
13  |   Extends rcube_html_page class from rcube_shared.inc                 |
14  |                                                                       |
15  +-----------------------------------------------------------------------+
16  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17  +-----------------------------------------------------------------------+
18
19  $Id$
20
21  */
22
23
24 /**
25  * Class to create HTML page output using a skin template
26  *
27  * @package View
28  * @todo Documentation
29  * @uses rcube_html_page
30  */
31 class rcube_template extends rcube_html_page
32 {
33     var $app;
34     var $config;
35     var $framed = false;
36     var $pagetitle = '';
37     var $message = null;
38     var $env = array();
39     var $js_env = array();
40     var $js_commands = array();
41     var $object_handlers = array();
42
43     public $type = 'html';
44     public $ajax_call = false;
45
46     /**
47      * Constructor
48      *
49      * @todo   Use jQuery's $(document).ready() here.
50      * @todo   Replace $this->config with the real rcube_config object
51      */
52     public function __construct($task, $framed = false)
53     {
54         parent::__construct();
55
56         $this->app = rcmail::get_instance();
57         $this->config = $this->app->config->all();
58         $this->browser = new rcube_browser();
59         
60         //$this->framed = $framed;
61         $this->set_env('task', $task);
62         $this->set_env('request_token', $this->app->get_request_token());
63
64         // load the correct skin (in case user-defined)
65         $this->set_skin($this->config['skin']);
66
67         // add common javascripts
68         $javascript = 'var '.JS_OBJECT_NAME.' = new rcube_webmail();';
69
70         // don't wait for page onload. Call init at the bottom of the page (delayed)
71         $javascript_foot = '$(document).ready(function(){ '.JS_OBJECT_NAME.'.init(); });';
72
73         $this->add_script($javascript, 'head_top');
74         $this->add_script($javascript_foot, 'foot');
75         $this->scripts_path = 'program/js/';
76         $this->include_script('jquery-1.3.min.js');
77         $this->include_script('common.js');
78         $this->include_script('app.js');
79
80         // register common UI objects
81         $this->add_handlers(array(
82             'loginform'       => array($this, 'login_form'),
83             'username'        => array($this, 'current_username'),
84             'message'         => array($this, 'message_container'),
85             'charsetselector' => array($this, 'charset_selector'),
86         ));
87     }
88
89     /**
90      * Set environment variable
91      *
92      * @param string Property name
93      * @param mixed Property value
94      * @param boolean True if this property should be added to client environment
95      */
96     public function set_env($name, $value, $addtojs = true)
97     {
98         $this->env[$name] = $value;
99         if ($addtojs || isset($this->js_env[$name])) {
100             $this->js_env[$name] = $value;
101         }
102     }
103
104
105     /**
106      * Set page title variable
107      */
108     public function set_pagetitle($title)
109     {
110         $this->pagetitle = $title;
111     }
112
113
114     /**
115      * Getter for the current page title
116      *
117      * @return string The page title
118      */
119     public function get_pagetitle()
120     {
121         if (!empty($this->pagetitle)) {
122             $title = $this->pagetitle;
123         }
124         else if ($this->env['task'] == 'login') {
125             $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $this->config['product_name'])));
126         }
127         else {
128             $title = ucfirst($this->env['task']);
129         }
130         
131         return $title;
132     }
133
134
135     /**
136      * Set skin
137      */
138     public function set_skin($skin)
139     {
140         if (!empty($skin) && is_dir('skins/'.$skin) && is_readable('skins/'.$skin))
141             $skin_path = 'skins/'.$skin;
142         else
143             $skin_path = $this->config['skin_path'] ? $this->config['skin_path'] : 'skins/default';
144
145         $this->app->config->set('skin_path', $skin_path);
146         $this->config['skin_path'] = $skin_path;
147     }
148
149     /**
150      * Check if a specific template exists
151      *
152      * @param string Template name
153      * @return boolean True if template exists
154      */
155     public function template_exists($name)
156     {
157         $filename = $this->config['skin_path'] . '/templates/' . $name . '.html';
158
159         return (is_file($filename) && is_readable($filename));
160     }
161
162     /**
163      * Register a template object handler
164      *
165      * @param  string Object name
166      * @param  string Function name to call
167      * @return void
168      */
169     public function add_handler($obj, $func)
170     {
171         $this->object_handlers[$obj] = $func;
172     }
173
174     /**
175      * Register a list of template object handlers
176      *
177      * @param  array Hash array with object=>handler pairs
178      * @return void
179      */
180     public function add_handlers($arr)
181     {
182         $this->object_handlers = array_merge($this->object_handlers, $arr);
183     }
184
185     /**
186      * Register a GUI object to the client script
187      *
188      * @param  string Object name
189      * @param  string Object ID
190      * @return void
191      */
192     public function add_gui_object($obj, $id)
193     {
194         $this->add_script(JS_OBJECT_NAME.".gui_object('$obj', '$id');");
195     }
196
197     /**
198      * Call a client method
199      *
200      * @param string Method to call
201      * @param ... Additional arguments
202      */
203     public function command()
204     {
205         $cmd = func_get_args();
206         if (strpos($cmd[0], 'plugin.') === false)
207           $this->js_commands[] = $cmd;
208     }
209
210
211     /**
212      * Add a localized label to the client environment
213      */
214     public function add_label()
215     {
216         $args = func_get_args();
217         if (count($args) == 1 && is_array($args[0]))
218           $args = $args[0];
219         
220         foreach ($args as $name) {
221             $this->command('add_label', $name, rcube_label($name));
222         }
223     }
224
225
226     /**
227      * Invoke display_message command
228      *
229      * @param string Message to display
230      * @param string Message type [notice|confirm|error]
231      * @param array Key-value pairs to be replaced in localized text
232      * @param boolean Override last set message
233      * @uses self::command()
234      */
235     public function show_message($message, $type='notice', $vars=null, $override=true)
236     {
237         if ($override || !$this->message) {
238             $this->message = $message;
239             $this->command(
240                 'display_message',
241                 rcube_label(array('name' => $message, 'vars' => $vars)),
242                 $type);
243         }
244     }
245
246
247     /**
248      * Delete all stored env variables and commands
249      *
250      * @return void
251      * @uses   rcube_html::reset()
252      * @uses   self::$env
253      * @uses   self::$js_env
254      * @uses   self::$js_commands
255      * @uses   self::$object_handlers
256      */
257     public function reset()
258     {
259         $this->env = array();
260         $this->js_env = array();
261         $this->js_commands = array();
262         $this->object_handlers = array();
263         parent::reset();
264     }
265
266
267     /**
268      * Redirect to a certain url
269      *
270      * @param mixed Either a string with the action or url parameters as key-value pairs
271      * @see rcmail::url()
272      */
273     public function redirect($p = array())
274     {
275         $location = $this->app->url($p);
276         header('Location: ' . $location);
277         exit;
278     }
279
280
281     /**
282      * Send the request output to the client.
283      * This will either parse a skin tempalte or send an AJAX response
284      *
285      * @param string  Template name
286      * @param boolean True if script should terminate (default)
287      */
288     public function send($templ = null, $exit = true)
289     {
290         if ($templ != 'iframe') {
291             // prevent from endless loops
292             if ($exit != 'recur' && $this->app->plugins->is_processing('render_page')) {
293                 raise_error(array('code' => 505, 'type' => 'php', 'message' => 'Recursion alert: ignoring output->send()'), true, false);
294                 return;
295             }
296             $this->parse($templ, false);
297         }
298         else {
299             $this->framed = $templ == 'iframe' ? true : $this->framed;
300             $this->write();
301         }
302
303         // set output asap
304         ob_flush();
305         flush();
306         
307         if ($exit) {
308             exit;
309         }
310     }
311
312     /**
313      * Process template and write to stdOut
314      *
315      * @param string HTML template
316      * @see rcube_html_page::write()
317      * @override
318      */
319     public function write($template = '')
320     {
321         // unlock interface after iframe load
322         if ($this->framed) {
323             array_unshift($this->js_commands, array('set_busy', false));
324         }
325         // write all env variables to client
326         $js = $this->framed ? "if(window.parent) {\n" : '';
327         $js .= $this->get_js_commands() . ($this->framed ? ' }' : '');
328         $this->add_script($js, 'head_top');
329         
330         // make sure all <form> tags have a valid request token
331         $template = preg_replace_callback('/<form\s+([^>]+)>/Ui', array($this, 'alter_form_tag'), $template);
332         $this->footer = preg_replace_callback('/<form\s+([^>]+)>/Ui', array($this, 'alter_form_tag'), $this->footer);
333
334         // call super method
335         parent::write($template, $this->config['skin_path']);
336     }
337
338     /**
339      * Parse a specific skin template and deliver to stdout
340      *
341      * Either returns nothing, or exists hard (exit();)
342      *
343      * @param  string  Template name
344      * @param  boolean Exit script
345      * @return void
346      * @link   http://php.net/manual/en/function.exit.php
347      */
348     private function parse($name = 'main', $exit = true)
349     {
350         $skin_path = $this->config['skin_path'];
351         $plugin = false;
352         
353         $temp = explode(".", $name, 2);
354         if (count($temp) > 1) {
355             $plugin = $temp[0];
356             $name = $temp[1];
357             $skin_dir = $plugin . '/skins/' . $this->config['skin'];
358             $skin_path = $this->app->plugins->dir . $skin_dir;
359             if (!is_dir($skin_path)) {  // fallback to default skin
360                 $skin_dir = $plugin . '/skins/default';
361                 $skin_path = $this->app->plugins->dir . $skin_dir;
362             }
363         }
364         
365         $path = "$skin_path/templates/$name.html";
366
367         // read template file
368         if (($templ = @file_get_contents($path)) === false) {
369             raise_error(array(
370                 'code' => 501,
371                 'type' => 'php',
372                 'line' => __LINE__,
373                 'file' => __FILE__,
374                 'message' => 'Error loading template for '.$name
375                 ), true, true);
376             return false;
377         }
378         
379         // replace all path references to plugins/... with the configured plugins dir
380         // and /this/ to the current plugin skin directory
381         if ($plugin) {
382             $templ = preg_replace(array('/\bplugins\//', '/(["\']?)\/this\//'), array($this->app->plugins->url, '\\1'.$this->app->plugins->url.$skin_dir.'/'), $templ);
383         }
384
385         // parse for specialtags
386         $output = $this->parse_conditions($templ);
387         $output = $this->parse_xml($output);
388         
389         // trigger generic hook where plugins can put additional content to the page
390         $hook = $this->app->plugins->exec_hook("render_page", array('template' => $name, 'content' => $output));
391
392         // add debug console
393         if ($this->config['debug_level'] & 8) {
394             $this->add_footer('<div id="console" style="position:absolute;top:5px;left:5px;width:405px;padding:2px;background:white;z-index:9000;">
395                 <a href="#toggle" onclick="con=document.getElementById(\'dbgconsole\');con.style.display=(con.style.display==\'none\'?\'block\':\'none\');return false">console</a>
396                 <form action="/" name="debugform" style="display:inline"><textarea name="console" id="dbgconsole" rows="20" cols="40" wrap="off" style="display:none;width:400px;border:none;font-size:x-small" spellcheck="false"></textarea></form></div>'
397             );
398         }
399         
400         $output = $this->parse_with_globals($hook['content']);
401         $this->write(trim($output));
402         if ($exit) {
403             exit;
404         }
405     }
406
407
408     /**
409      * Return executable javascript code for all registered commands
410      *
411      * @return string $out
412      */
413     private function get_js_commands()
414     {
415         $out = '';
416         if (!$this->framed && !empty($this->js_env)) {
417             $out .= JS_OBJECT_NAME . '.set_env('.json_serialize($this->js_env).");\n";
418         }
419         foreach ($this->js_commands as $i => $args) {
420             $method = array_shift($args);
421             foreach ($args as $i => $arg) {
422                 $args[$i] = json_serialize($arg);
423             }
424             $parent = $this->framed || preg_match('/^parent\./', $method);
425             $out .= sprintf(
426                 "%s.%s(%s);\n",
427                 ($parent ? 'if(window.parent && parent.'.JS_OBJECT_NAME.') parent.' : '') . JS_OBJECT_NAME,
428                 preg_replace('/^parent\./', '', $method),
429                 implode(',', $args)
430             );
431         }
432         
433         return $out;
434     }
435
436     /**
437      * Make URLs starting with a slash point to skin directory
438      *
439      * @param  string Input string
440      * @return string
441      */
442     public function abs_url($str)
443     {
444         return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
445     }
446
447
448     /*****  Template parsing methods  *****/
449
450     /**
451      * Replace all strings ($varname)
452      * with the content of the according global variable.
453      */
454     private function parse_with_globals($input)
455     {
456         $GLOBALS['__version'] = Q(RCMAIL_VERSION);
457         $GLOBALS['__comm_path'] = Q($this->app->comm_path);
458         return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
459     }
460
461     /**
462      * Public wrapper to dipp into template parsing.
463      *
464      * @param  string $input
465      * @return string
466      * @uses   rcube_template::parse_xml()
467      * @since  0.1-rc1
468      */
469     public function just_parse($input)
470     {
471         return $this->parse_xml($input);
472     }
473
474     /**
475      * Parse for conditional tags
476      *
477      * @param  string $input
478      * @return string
479      */
480     private function parse_conditions($input)
481     {
482         $matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE);
483         if ($matches && count($matches) == 4) {
484             if (preg_match('/^(else|endif)$/i', $matches[1])) {
485                 return $matches[0] . $this->parse_conditions($matches[3]);
486             }
487             $attrib = parse_attrib_string($matches[2]);
488             if (isset($attrib['condition'])) {
489                 $condmet = $this->check_condition($attrib['condition']);
490                 $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
491                 if ($condmet) {
492                     $result = $submatches[0];
493                     $result.= ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>/Uis', '', $submatches[3], 1) : $submatches[3]);
494                 }
495                 else {
496                     $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
497                 }
498                 return $matches[0] . $this->parse_conditions($result);
499             }
500             raise_error(array(
501                 'code' => 500,
502                 'type' => 'php',
503                 'line' => __LINE__,
504                 'file' => __FILE__,
505                 'message' => "Unable to parse conditional tag " . $matches[2]
506             ), true, false);
507         }
508         return $input;
509     }
510
511
512     /**
513      * Determines if a given condition is met
514      *
515      * @todo   Get rid off eval() once I understand what this does.
516      * @todo   Extend this to allow real conditions, not just "set"
517      * @param  string Condition statement
518      * @return boolean True if condition is met, False if not
519      */
520     private function check_condition($condition)
521     {
522         return eval("return (".$this->parse_expression($condition).");");
523     }
524     
525     
526     /**
527      *
528      */
529     private function alter_form_tag($matches)
530     {
531         $out = $matches[0];
532         $attrib  = parse_attrib_string($matches[1]);
533       
534         if (strtolower($attrib['method']) == 'post') {
535             $hidden = new html_hiddenfield(array('name' => '_token', 'value' => $this->app->get_request_token()));
536             $out .= "\n" . $hidden->show();
537         }
538       
539         return $out;
540     }
541
542
543     /**
544      * Parses expression and replaces variables
545      *
546      * @param  string Expression statement
547      * @return string Expression statement
548      */
549     private function parse_expression($expression)
550     {
551         return preg_replace(
552             array(
553                 '/session:([a-z0-9_]+)/i',
554                 '/config:([a-z0-9_]+)(:([a-z0-9_]+))?/i',
555                 '/env:([a-z0-9_]+)/i',
556                 '/request:([a-z0-9_]+)/i',
557                 '/cookie:([a-z0-9_]+)/i',
558                 '/browser:([a-z0-9_]+)/i'
559             ),
560             array(
561                 "\$_SESSION['\\1']",
562                 "\$this->app->config->get('\\1',get_boolean('\\3'))",
563                 "\$this->env['\\1']",
564                 "get_input_value('\\1', RCUBE_INPUT_GPC)",
565                 "\$_COOKIE['\\1']",
566                 "\$this->browser->{'\\1'}"
567             ),
568             $expression);
569     }
570
571
572     /**
573      * Search for special tags in input and replace them
574      * with the appropriate content
575      *
576      * @param  string Input string to parse
577      * @return string Altered input string
578      * @todo   Use DOM-parser to traverse template HTML
579      * @todo   Maybe a cache.
580      */
581     private function parse_xml($input)
582     {
583         return preg_replace_callback('/<roundcube:([-_a-z]+)\s+([^>]+)>/Ui', array($this, 'xml_command'), $input);
584     }
585
586
587     /**
588      * Callback function for parsing an xml command tag
589      * and turn it into real html content
590      *
591      * @param  array Matches array of preg_replace_callback
592      * @return string Tag/Object content
593      */
594     private function xml_command($matches)
595     {
596         $command = strtolower($matches[1]);
597         $attrib  = parse_attrib_string($matches[2]);
598
599         // empty output if required condition is not met
600         if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
601             return '';
602         }
603
604         // execute command
605         switch ($command) {
606             // return a button
607             case 'button':
608                 if ($attrib['name'] || $attrib['command']) {
609                     return $this->button($attrib);
610                 }
611                 break;
612
613             // show a label
614             case 'label':
615                 if ($attrib['name'] || $attrib['command']) {
616                     return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
617                 }
618                 break;
619
620             // include a file
621             case 'include':
622                 $path = realpath($this->config['skin_path'].$attrib['file']);
623                 if (is_readable($path)) {
624                     if ($this->config['skin_include_php']) {
625                         $incl = $this->include_php($path);
626                     }
627                     else {
628                       $incl = file_get_contents($path);
629                     }
630                     $incl = $this->parse_conditions($incl);
631                     return $this->parse_xml($incl);
632                 }
633                 break;
634
635             case 'plugin.include':
636                 $hook = $this->app->plugins->exec_hook("template_plugin_include", $attrib);
637                 return $hook['content'];
638                 break;
639             
640             // define a container block
641             case 'container':
642                 if ($attrib['name'] && $attrib['id']) {
643                     $this->command('gui_container', $attrib['name'], $attrib['id']);
644                     // let plugins insert some content here
645                     $hook = $this->app->plugins->exec_hook("template_container", $attrib);
646                     return $hook['content'];
647                 }
648                 break;
649
650             // return code for a specific application object
651             case 'object':
652                 $object = strtolower($attrib['name']);
653                 $content = '';
654
655                 // we are calling a class/method
656                 if (($handler = $this->object_handlers[$object]) && is_array($handler)) {
657                     if ((is_object($handler[0]) && method_exists($handler[0], $handler[1])) ||
658                     (is_string($handler[0]) && class_exists($handler[0])))
659                     $content = call_user_func($handler, $attrib);
660                 }
661                 // execute object handler function
662                 else if (function_exists($handler)) {
663                     $content = call_user_func($handler, $attrib);
664                 }
665                 else if ($object == 'productname') {
666                     $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
667                     $content = Q($name);
668                 }
669                 else if ($object == 'version') {
670                     $ver = (string)RCMAIL_VERSION;
671                     if (is_file(INSTALL_PATH . '.svn/entries')) {
672                         if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
673                           $ver .= ' [SVN r'.$regs[1].']';
674                     }
675                     $content = Q($ver);
676                 }
677                 else if ($object == 'steptitle') {
678                   $content = Q($this->get_pagetitle());
679                 }
680                 else if ($object == 'pagetitle') {
681                     $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
682                     $title .= $this->get_pagetitle();
683                     $content = Q($title);
684                 }
685                 
686                 // exec plugin hooks for this template object
687                 $hook = $this->app->plugins->exec_hook("template_object_$object", $attrib + array('content' => $content));
688                 return $hook['content'];
689
690             // return code for a specified eval expression
691             case 'exp':
692                 $value = $this->parse_expression($attrib['expression']);
693                 return eval("return Q($value);");
694             
695             // return variable
696             case 'var':
697                 $var = explode(':', $attrib['name']);
698                 $name = $var[1];
699                 $value = '';
700
701                 switch ($var[0]) {
702                     case 'env':
703                         $value = $this->env[$name];
704                         break;
705                     case 'config':
706                         $value = $this->config[$name];
707                         if (is_array($value) && $value[$_SESSION['imap_host']]) {
708                             $value = $value[$_SESSION['imap_host']];
709                         }
710                         break;
711                     case 'request':
712                         $value = get_input_value($name, RCUBE_INPUT_GPC);
713                         break;
714                     case 'session':
715                         $value = $_SESSION[$name];
716                         break;
717                     case 'cookie':
718                         $value = htmlspecialchars($_COOKIE[$name]);
719                         break;
720                     case 'browser':
721                         $value = $this->browser->{$name};
722                         break;
723                 }
724
725                 if (is_array($value)) {
726                     $value = implode(', ', $value);
727                 }
728
729                 return Q($value);
730                 break;
731         }
732         return '';
733     }
734
735     /**
736      * Include a specific file and return it's contents
737      *
738      * @param string File path
739      * @return string Contents of the processed file
740      */
741     private function include_php($file)
742     {
743         ob_start();
744         include $file;
745         $out = ob_get_contents();
746         ob_end_clean();
747
748         return $out;
749     }
750
751     /**
752      * Create and register a button
753      *
754      * @param  array Named button attributes
755      * @return string HTML button
756      * @todo   Remove all inline JS calls and use jQuery instead.
757      * @todo   Remove all sprintf()'s - they are pretty, but also slow.
758      */
759     public function button($attrib)
760     {
761         static $sa_buttons = array();
762         static $s_button_count = 100;
763
764         // these commands can be called directly via url
765         $a_static_commands = array('compose', 'list', 'preferences', 'folders', 'identities');
766
767         if (!($attrib['command'] || $attrib['name'])) {
768             return '';
769         }
770
771         // try to find out the button type
772         if ($attrib['type']) {
773             $attrib['type'] = strtolower($attrib['type']);
774         }
775         else {
776             $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
777         }
778         $command = $attrib['command'];
779
780         // take the button from the stack
781         if ($attrib['name'] && $sa_buttons[$attrib['name']]) {
782             $attrib = $sa_buttons[$attrib['name']];
783         }
784         else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class']) {
785             // add button to button stack
786             if (!$attrib['name']) {
787                 $attrib['name'] = $command;
788             }
789             if (!$attrib['image']) {
790                 $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
791             }
792             $sa_buttons[$attrib['name']] = $attrib;
793         }
794         else if ($command && $sa_buttons[$command]) {
795             // get saved button for this command/name
796             $attrib = $sa_buttons[$command];
797         }
798
799         if (!$attrib['id']) {
800             $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
801         }
802         // get localized text for labels and titles
803         if ($attrib['title']) {
804             $attrib['title'] = Q(rcube_label($attrib['title'], $attrib['domain']));
805         }
806         if ($attrib['label']) {
807             $attrib['label'] = Q(rcube_label($attrib['label'], $attrib['domain']));
808         }
809         if ($attrib['alt']) {
810             $attrib['alt'] = Q(rcube_label($attrib['alt'], $attrib['domain']));
811         }
812
813         // set title to alt attribute for IE browsers
814         if ($this->browser->ie && !$attrib['title'] && $attrib['alt']) {
815             $attrib['title'] = $attrib['alt'];
816         }
817
818         // add empty alt attribute for XHTML compatibility
819         if (!isset($attrib['alt'])) {
820             $attrib['alt'] = '';
821         }
822
823         // register button in the system
824         if ($attrib['command']) {
825             $this->add_script(sprintf(
826                 "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
827                 JS_OBJECT_NAME,
828                 $command,
829                 $attrib['id'],
830                 $attrib['type'],
831                 $attrib['imageact'] ? $this->abs_url($attrib['imageact']) : $attrib['classact'],
832                 $attrib['imagesel'] ? $this->abs_url($attrib['imagesel']) : $attrib['classsel'],
833                 $attrib['imageover'] ? $this->abs_url($attrib['imageover']) : ''
834             ));
835
836             // make valid href to specific buttons
837             if (in_array($attrib['command'], rcmail::$main_tasks)) {
838                 $attrib['href'] = rcmail_url(null, null, $attrib['command']);
839             }
840             else if (in_array($attrib['command'], $a_static_commands)) {
841                 $attrib['href'] = rcmail_url($attrib['command']);
842             }
843             else if ($attrib['command'] == 'permaurl' && !empty($this->env['permaurl'])) {
844               $attrib['href'] = $this->env['permaurl'];
845             }
846         }
847
848         // overwrite attributes
849         if (!$attrib['href']) {
850             $attrib['href'] = '#';
851         }
852         if ($command) {
853             $attrib['onclick'] = sprintf(
854                 "return %s.command('%s','%s',this)",
855                 JS_OBJECT_NAME,
856                 $command,
857                 $attrib['prop']
858             );
859         }
860
861         $out = '';
862
863         // generate image tag
864         if ($attrib['type']=='image') {
865             $attrib_str = html::attrib_string(
866                 $attrib,
867                 array(
868                     'style', 'class', 'id', 'width', 'height', 'border', 'hspace',
869                     'vspace', 'align', 'alt', 'tabindex', 'title'
870                 )
871             );
872             $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
873             if ($attrib['label']) {
874                 $btn_content .= ' '.$attrib['label'];
875             }
876             $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'target');
877         }
878         else if ($attrib['type']=='link') {
879             $btn_content = isset($attrib['content']) ? $attrib['content'] : ($attrib['label'] ? $attrib['label'] : $attrib['command']);
880             $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style', 'tabindex', 'target');
881         }
882         else if ($attrib['type']=='input') {
883             $attrib['type'] = 'button';
884
885             if ($attrib['label']) {
886                 $attrib['value'] = $attrib['label'];
887             }
888
889             $attrib_str = html::attrib_string(
890                 $attrib,
891                 array(
892                     'type', 'value', 'onclick', 'id', 'class', 'style', 'tabindex'
893                 )
894             );
895             $out = sprintf('<input%s disabled="disabled" />', $attrib_str);
896         }
897
898         // generate html code for button
899         if ($btn_content) {
900             $attrib_str = html::attrib_string($attrib, $link_attrib);
901             $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
902         }
903
904         return $out;
905     }
906
907
908     /*  ************* common functions delivering gui objects **************  */
909
910
911     /**
912      * Create a form tag with the necessary hidden fields
913      *
914      * @param array Named tag parameters
915      * @return string HTML code for the form
916      */
917     public function form_tag($attrib, $content = null)
918     {
919       if ($this->framed || !empty($_REQUEST['_framed'])) {
920         $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
921         $hidden = $hiddenfield->show();
922       }
923       
924       if (!$content)
925         $attrib['noclose'] = true;
926       
927       return html::tag('form',
928         $attrib + array('action' => "./", 'method' => "get"),
929         $hidden . $content,
930         array('id','class','style','name','method','action','enctype','onsubmit'));
931     }
932     
933     
934     /**
935      * Build a form tag with a unique request token
936      *
937      * @param array Named tag parameters including 'action' and 'task' values which will be put into hidden fields
938      * @param string Form content
939      * @return string HTML code for the form
940      */
941     public function request_form($attrib, $content = '')
942     {
943         $hidden = new html_hiddenfield();
944         if ($attrib['task']) {
945             $hidden->add(array('name' => '_task', 'value' => $attrib['task']));
946         }
947         if ($attrib['action']) {
948             $hidden->add(array('name' => '_action', 'value' => $attrib['action']));
949         }
950       
951         unset($attrib['task'], $attrib['request']);
952         $attrib['action'] = './';
953       
954         // we already have a <form> tag
955         if ($attrib['form'])
956             return $hidden->show() . $content;
957         else
958             return $this->form_tag($attrib, $hidden->show() . $content);
959     }
960
961
962     /**
963      * GUI object 'username'
964      * Showing IMAP username of the current session
965      *
966      * @param array Named tag parameters (currently not used)
967      * @return string HTML code for the gui object
968      */
969     public function current_username($attrib)
970     {
971         static $username;
972
973         // alread fetched
974         if (!empty($username)) {
975             return $username;
976         }
977
978         // get e-mail address form default identity
979         if ($sql_arr = $this->app->user->get_identity()) {
980             $username = $sql_arr['email'];
981         }
982         else {
983             $username = $this->app->user->get_username();
984         }
985
986         return $username;
987     }
988
989
990     /**
991      * GUI object 'loginform'
992      * Returns code for the webmail login form
993      *
994      * @param array Named parameters
995      * @return string HTML code for the gui object
996      */
997     private function login_form($attrib)
998     {
999         $default_host = $this->config['default_host'];
1000
1001         $_SESSION['temp'] = true;
1002         
1003         // save original url
1004         $url = get_input_value('_url', RCUBE_INPUT_POST);
1005         if (empty($url) && !preg_match('/_(task|action)=logout/', $_SERVER['QUERY_STRING']))
1006             $url = $_SERVER['QUERY_STRING'];
1007
1008         $input_user   = new html_inputfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30) + $attrib);
1009         $input_pass   = new html_passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30) + $attrib);
1010         $input_action = new html_hiddenfield(array('name' => '_action', 'value' => 'login'));
1011         $input_tzone  = new html_hiddenfield(array('name' => '_timezone', 'id' => 'rcmlogintz', 'value' => '_default_'));
1012         $input_url    = new html_hiddenfield(array('name' => '_url', 'id' => 'rcmloginurl', 'value' => $url));
1013         $input_host   = null;
1014
1015         if (is_array($default_host)) {
1016             $input_host = new html_select(array('name' => '_host', 'id' => 'rcmloginhost'));
1017
1018             foreach ($default_host as $key => $value) {
1019                 if (!is_array($value)) {
1020                     $input_host->add($value, (is_numeric($key) ? $value : $key));
1021                 }
1022                 else {
1023                     $input_host = null;
1024                     break;
1025                 }
1026             }
1027         }
1028         else if (empty($default_host)) {
1029             $input_host = new html_inputfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
1030         }
1031
1032         $form_name  = !empty($attrib['form']) ? $attrib['form'] : 'form';
1033         $this->add_gui_object('loginform', $form_name);
1034
1035         // create HTML table with two cols
1036         $table = new html_table(array('cols' => 2));
1037
1038         $table->add('title', html::label('rcmloginuser', Q(rcube_label('username'))));
1039         $table->add(null, $input_user->show(get_input_value('_user', RCUBE_INPUT_POST)));
1040
1041         $table->add('title', html::label('rcmloginpwd', Q(rcube_label('password'))));
1042         $table->add(null, $input_pass->show());
1043
1044         // add host selection row
1045         if (is_object($input_host)) {
1046             $table->add('title', html::label('rcmloginhost', Q(rcube_label('server'))));
1047             $table->add(null, $input_host->show(get_input_value('_host', RCUBE_INPUT_POST)));
1048         }
1049
1050         $out = $input_action->show();
1051         $out .= $input_tzone->show();
1052         $out .= $input_url->show();
1053         $out .= $table->show();
1054
1055         // surround html output with a form tag
1056         if (empty($attrib['form'])) {
1057             $out = $this->form_tag(array('name' => $form_name, 'method' => "post"), $out);
1058         }
1059
1060         return $out;
1061     }
1062
1063
1064     /**
1065      * GUI object 'searchform'
1066      * Returns code for search function
1067      *
1068      * @param array Named parameters
1069      * @return string HTML code for the gui object
1070      */
1071     private function search_form($attrib)
1072     {
1073         // add some labels to client
1074         $this->add_label('searching');
1075
1076         $attrib['name'] = '_q';
1077
1078         if (empty($attrib['id'])) {
1079             $attrib['id'] = 'rcmqsearchbox';
1080         }
1081         if ($attrib['type'] == 'search' && !$this->browser->khtml) {
1082           unset($attrib['type'], $attrib['results']);
1083         }
1084         
1085         $input_q = new html_inputfield($attrib);
1086         $out = $input_q->show();
1087
1088         $this->add_gui_object('qsearchbox', $attrib['id']);
1089
1090         // add form tag around text field
1091         if (empty($attrib['form'])) {
1092             $out = $this->form_tag(array(
1093                 'name' => "rcmqsearchform",
1094                 'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
1095                 'style' => "display:inline"),
1096               $out);
1097         }
1098
1099         return $out;
1100     }
1101
1102
1103     /**
1104      * Builder for GUI object 'message'
1105      *
1106      * @param array Named tag parameters
1107      * @return string HTML code for the gui object
1108      */
1109     private function message_container($attrib)
1110     {
1111         if (isset($attrib['id']) === false) {
1112             $attrib['id'] = 'rcmMessageContainer';
1113         }
1114
1115         $this->add_gui_object('message', $attrib['id']);
1116         return html::div($attrib, "");
1117     }
1118
1119
1120     /**
1121      * GUI object 'charsetselector'
1122      *
1123      * @param array Named parameters for the select tag
1124      * @return string HTML code for the gui object
1125      */
1126     static function charset_selector($attrib)
1127     {
1128         // pass the following attributes to the form class
1129         $field_attrib = array('name' => '_charset');
1130         foreach ($attrib as $attr => $value) {
1131             if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex'))) {
1132                 $field_attrib[$attr] = $value;
1133             }
1134         }
1135         $charsets = array(
1136             'US-ASCII'     => 'ASCII (English)',
1137             'EUC-JP'       => 'EUC-JP (Japanese)',
1138             'EUC-KR'       => 'EUC-KR (Korean)',
1139             'BIG5'         => 'BIG5 (Chinese)',
1140             'GB2312'       => 'GB2312 (Chinese)',
1141             'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1142             'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
1143             'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1144             'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1145             'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1146             'Windows-1251' => 'Windows-1251 (Cyrillic)',
1147             'Windows-1252' => 'Windows-1252 (Western)',
1148             'Windows-1255' => 'Windows-1255 (Hebrew)',
1149             'Windows-1256' => 'Windows-1256 (Arabic)',
1150             'Windows-1257' => 'Windows-1257 (Baltic)',
1151             'UTF-8'        => 'UTF-8'
1152             );
1153
1154             $select = new html_select($field_attrib);
1155             $select->add(array_values($charsets), array_keys($charsets));
1156
1157             $set = $_POST['_charset'] ? $_POST['_charset'] : $this->get_charset();
1158             return $select->show($set);
1159     }
1160
1161 }  // end class rcube_template
1162
1163