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