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