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