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