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