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