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