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