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