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