Aleksander Machniak
2014-04-15 5be6dcf0e2234b22391ad4f654efddd0ba7c0e92
commit | author | age
47124c 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
60226a 5  | program/include/rcmail_output_html.php                                |
47124c 6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
0301d9 8  | Copyright (C) 2006-2013, The Roundcube Dev Team                       |
7fe381 9  |                                                                       |
T 10  | Licensed under the GNU General Public License version 3 or            |
11  | any later version with exceptions for skins & plugins.                |
12  | See the README file for a full license statement.                     |
47124c 13  |                                                                       |
T 14  | PURPOSE:                                                              |
15  |   Class to handle HTML page output using a skin template.             |
16  |                                                                       |
17  +-----------------------------------------------------------------------+
18  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
19  +-----------------------------------------------------------------------+
041c93 20 */
47124c 21
T 22
23 /**
24  * Class to create HTML page output using a skin template
25  *
9ba496 26  * @package Webmail
9ab346 27  * @subpackage View
47124c 28  */
60226a 29 class rcmail_output_html extends rcmail_output
47124c 30 {
c8a21d 31     public $type = 'html';
0c2596 32
A 33     protected $message = null;
34     protected $js_env = array();
35     protected $js_labels = array();
36     protected $js_commands = array();
8fa22e 37     protected $skin_paths = array();
0c2596 38     protected $template_name;
A 39     protected $scripts_path = '';
40     protected $script_files = array();
41     protected $css_files = array();
42     protected $scripts = array();
43     protected $default_template = "<html>\n<head><title></title></head>\n<body></body>\n</html>";
44     protected $header = '';
45     protected $footer = '';
46     protected $body = '';
47     protected $base_path = '';
538e64 48     protected $devel_mode = false;
47124c 49
7fcb56 50     // deprecated names of templates used before 0.5
0c2596 51     protected $deprecated_templates = array(
A 52         'contact'      => 'showcontact',
53         'contactadd'   => 'addcontact',
54         'contactedit'  => 'editcontact',
7fcb56 55         'identityedit' => 'editidentity',
T 56         'messageprint' => 'printmessage',
57     );
58
47124c 59     /**
T 60      * Constructor
61      *
197601 62      * @todo   Replace $this->config with the real rcube_config object
47124c 63      */
0c2596 64     public function __construct($task = null, $framed = false)
47124c 65     {
T 66         parent::__construct();
538e64 67
AM 68         $this->devel_mode = $this->config->get('devel_mode');
47124c 69
197601 70         //$this->framed = $framed;
83a763 71         $this->set_env('task', $task);
0c2596 72         $this->set_env('x_frame_options', $this->config->get('x_frame_options', 'sameorigin'));
3863a9 73         $this->set_env('standard_windows', (bool) $this->config->get('standard_windows'));
47124c 74
ae7027 75         // add cookie info
AM 76         $this->set_env('cookie_domain', ini_get('session.cookie_domain'));
77         $this->set_env('cookie_path', ini_get('session.cookie_path'));
39b905 78         $this->set_env('cookie_secure', filter_var(ini_get('session.cookie_secure'), FILTER_VALIDATE_BOOLEAN));
ae7027 79
423065 80         // load the correct skin (in case user-defined)
740875 81         $skin = $this->config->get('skin');
AM 82         $this->set_skin($skin);
83         $this->set_env('skin', $skin);
e58df3 84
271efe 85         if (!empty($_REQUEST['_extwin']))
0301d9 86             $this->set_env('extwin', 1);
d30460 87         if ($this->framed || !empty($_REQUEST['_framed']))
0301d9 88             $this->set_env('framed', 1);
271efe 89
47124c 90         // add common javascripts
60226a 91         $this->add_script('var '.self::JS_OBJECT_NAME.' = new rcube_webmail();', 'head_top');
47124c 92
T 93         // don't wait for page onload. Call init at the bottom of the page (delayed)
60226a 94         $this->add_script(self::JS_OBJECT_NAME.'.init();', 'docready');
47124c 95
T 96         $this->scripts_path = 'program/js/';
79275b 97         $this->include_script('jquery.min.js');
47124c 98         $this->include_script('common.js');
T 99         $this->include_script('app.js');
100
101         // register common UI objects
102         $this->add_handlers(array(
103             'loginform'       => array($this, 'login_form'),
8e211a 104             'preloader'       => array($this, 'preloader'),
47124c 105             'username'        => array($this, 'current_username'),
T 106             'message'         => array($this, 'message_container'),
107             'charsetselector' => array($this, 'charset_selector'),
1a0f60 108             'aboutcontent'    => array($this, 'about_content'),
47124c 109         ));
T 110     }
111
112     /**
113      * Set environment variable
114      *
115      * @param string Property name
116      * @param mixed Property value
117      * @param boolean True if this property should be added to client environment
118      */
119     public function set_env($name, $value, $addtojs = true)
120     {
121         $this->env[$name] = $value;
0301d9 122
47124c 123         if ($addtojs || isset($this->js_env[$name])) {
T 124             $this->js_env[$name] = $value;
125         }
126     }
f645ce 127
T 128     /**
129      * Getter for the current page title
130      *
131      * @return string The page title
132      */
0c2596 133     protected function get_pagetitle()
f645ce 134     {
T 135         if (!empty($this->pagetitle)) {
136             $title = $this->pagetitle;
137         }
138         else if ($this->env['task'] == 'login') {
0c2596 139             $title = $this->app->gettext(array(
A 140                 'name' => 'welcome',
141                 'vars' => array('product' => $this->config->get('product_name')
142             )));
f645ce 143         }
T 144         else {
145             $title = ucfirst($this->env['task']);
146         }
ad334a 147
f645ce 148         return $title;
T 149     }
0c2596 150
e58df3 151     /**
A 152      * Set skin
153      */
154     public function set_skin($skin)
155     {
62c791 156         $valid = false;
b7addf 157         $path  = RCUBE_INSTALL_PATH . 'skins/';
ad334a 158
b7addf 159         if (!empty($skin) && is_dir($path . $skin) && is_readable($path . $skin)) {
AM 160             $skin_path = 'skins/' . $skin;
161             $valid     = true;
62c791 162         }
T 163         else {
0c2596 164             $skin_path = $this->config->get('skin_path');
A 165             if (!$skin_path) {
aff970 166                 $skin_path = 'skins/' . rcube_config::DEFAULT_SKIN;
0c2596 167             }
62c791 168             $valid = !$skin;
T 169         }
423065 170
0c2596 171         $this->config->set('skin_path', $skin_path);
1730cf 172         $this->base_path = $skin_path;
ad334a 173
8fa22e 174         // register skin path(s)
TB 175         $this->skin_paths = array();
176         $this->load_skin($skin_path);
177
62c791 178         return $valid;
8fa22e 179     }
TB 180
181     /**
182      * Helper method to recursively read skin meta files and register search paths
183      */
184     private function load_skin($skin_path)
185     {
186         $this->skin_paths[] = $skin_path;
187
188         // read meta file and check for dependecies
b7addf 189         $meta = @file_get_contents(RCUBE_INSTALL_PATH . $skin_path . '/meta.json');
AM 190         $meta = @json_decode($meta, true);
191         if ($meta['extends']) {
192             $path = RCUBE_INSTALL_PATH . 'skins/';
193             if (is_dir($path . $meta['extends']) && is_readable($path . $meta['extends'])) {
194                 $this->load_skin('skins/' . $meta['extends']);
195             }
8fa22e 196         }
e58df3 197     }
fc7b5b 198
T 199     /**
e58df3 200      * Check if a specific template exists
A 201      *
202      * @param string Template name
203      * @return boolean True if template exists
204      */
205     public function template_exists($name)
206     {
8fa22e 207         foreach ($this->skin_paths as $skin_path) {
b7addf 208             $filename = RCUBE_INSTALL_PATH . $skin_path . '/templates/' . $name . '.html';
AM 209             if ((is_file($filename) && is_readable($filename))
210                 || ($this->deprecated_templates[$name] && $this->template_exists($this->deprecated_templates[$name]))
211             ) {
212                 return true;
213             }
8fa22e 214         }
47124c 215
b7addf 216         return false;
AM 217     }
47124c 218
T 219     /**
28de39 220      * Find the given file in the current skin path stack
TB 221      *
222      * @param string File name/path to resolve (starting with /)
223      * @param string Reference to the base path of the matching skin
224      * @param string Additional path to search in
225      * @return mixed Relative path to the requested file or False if not found
226      */
bc53e2 227     public function get_skin_file($file, &$skin_path = null, $add_path = null)
28de39 228     {
TB 229         $skin_paths = $this->skin_paths;
230         if ($add_path)
231             array_unshift($skin_paths, $add_path);
232
233         foreach ($skin_paths as $skin_path) {
234             $path = realpath($skin_path . $file);
235             if (is_file($path)) {
236                 return $skin_path . $file;
237             }
238         }
239
240         return false;
241     }
242
243     /**
47124c 244      * Register a GUI object to the client script
T 245      *
246      * @param  string Object name
247      * @param  string Object ID
248      * @return void
249      */
250     public function add_gui_object($obj, $id)
251     {
60226a 252         $this->add_script(self::JS_OBJECT_NAME.".gui_object('$obj', '$id');");
47124c 253     }
T 254
255     /**
256      * Call a client method
257      *
258      * @param string Method to call
259      * @param ... Additional arguments
260      */
261     public function command()
262     {
0e99d3 263         $cmd = func_get_args();
f66383 264         if (strpos($cmd[0], 'plugin.') !== false)
T 265           $this->js_commands[] = array('triggerEvent', $cmd[0], $cmd[1]);
266         else
0e99d3 267           $this->js_commands[] = $cmd;
47124c 268     }
T 269
270     /**
271      * Add a localized label to the client environment
272      */
273     public function add_label()
274     {
cc97ea 275         $args = func_get_args();
T 276         if (count($args) == 1 && is_array($args[0]))
277           $args = $args[0];
ad334a 278
cc97ea 279         foreach ($args as $name) {
0c2596 280             $this->js_labels[$name] = $this->app->gettext($name);
47124c 281         }
T 282     }
283
284     /**
285      * Invoke display_message command
286      *
7f5a84 287      * @param string  $message  Message to display
A 288      * @param string  $type     Message type [notice|confirm|error]
289      * @param array   $vars     Key-value pairs to be replaced in localized text
290      * @param boolean $override Override last set message
291      * @param int     $timeout  Message display time in seconds
47124c 292      * @uses self::command()
T 293      */
7f5a84 294     public function show_message($message, $type='notice', $vars=null, $override=true, $timeout=0)
47124c 295     {
69f18a 296         if ($override || !$this->message) {
0c2596 297             if ($this->app->text_exists($message)) {
8dd172 298                 if (!empty($vars))
A 299                     $vars = array_map('Q', $vars);
0c2596 300                 $msgtext = $this->app->gettext(array('name' => $message, 'vars' => $vars));
8dd172 301             }
A 302             else
303                 $msgtext = $message;
304
69f18a 305             $this->message = $message;
7f5a84 306             $this->command('display_message', $msgtext, $type, $timeout * 1000);
69f18a 307         }
47124c 308     }
T 309
310     /**
311      * Delete all stored env variables and commands
4d1fe2 312      *
AM 313      * @param bool $all Reset all env variables (including internal)
47124c 314      */
4d1fe2 315     public function reset($all = false)
47124c 316     {
e46d06 317         $framed = $this->framed;
4d1fe2 318         $env = $all ? null : array_intersect_key($this->env, array('extwin'=>1, 'framed'=>1));
d30460 319
0c2596 320         parent::reset();
d30460 321
TB 322         // let some env variables survive
323         $this->env = $this->js_env = $env;
e46d06 324         $this->framed = $framed || $this->env['framed'];
4d1fe2 325         $this->js_labels    = array();
AM 326         $this->js_commands  = array();
0c2596 327         $this->script_files = array();
A 328         $this->scripts      = array();
329         $this->header       = '';
330         $this->footer       = '';
331         $this->body         = '';
e46d06 332
TB 333         // load defaults
334         if (!$all) {
335             $this->__construct();
336         }
47124c 337     }
0c2596 338
47124c 339     /**
c719f3 340      * Redirect to a certain url
T 341      *
0c2596 342      * @param mixed $p     Either a string with the action or url parameters as key-value pairs
A 343      * @param int   $delay Delay in seconds
c719f3 344      */
0c2596 345     public function redirect($p = array(), $delay = 1)
c719f3 346     {
271efe 347         if ($this->env['extwin'])
TB 348             $p['extwin'] = 1;
c719f3 349         $location = $this->app->url($p);
T 350         header('Location: ' . $location);
351         exit;
352     }
353
354     /**
47124c 355      * Send the request output to the client.
T 356      * This will either parse a skin tempalte or send an AJAX response
357      *
358      * @param string  Template name
359      * @param boolean True if script should terminate (default)
360      */
361     public function send($templ = null, $exit = true)
362     {
363         if ($templ != 'iframe') {
a366a3 364             // prevent from endless loops
f78dab 365             if ($exit != 'recur' && $this->app->plugins->is_processing('render_page')) {
0c2596 366                 rcube::raise_error(array('code' => 505, 'type' => 'php',
030db5 367                   'file' => __FILE__, 'line' => __LINE__,
T 368                   'message' => 'Recursion alert: ignoring output->send()'), true, false);
a366a3 369                 return;
T 370             }
47124c 371             $this->parse($templ, false);
T 372         }
373         else {
4d1fe2 374             $this->framed = true;
47124c 375             $this->write();
T 376         }
377
c6514e 378         // set output asap
T 379         ob_flush();
380         flush();
ad334a 381
c6514e 382         if ($exit) {
47124c 383             exit;
T 384         }
385     }
0c2596 386
47124c 387     /**
T 388      * Process template and write to stdOut
389      *
0c2596 390      * @param string $template HTML template content
47124c 391      */
T 392     public function write($template = '')
393     {
394         // unlock interface after iframe load
5bfa44 395         $unlock = preg_replace('/[^a-z0-9]/i', '', $_REQUEST['_unlock']);
47124c 396         if ($this->framed) {
72e24b 397             array_unshift($this->js_commands, array('iframe_loaded', $unlock));
ad334a 398         }
A 399         else if ($unlock) {
400             array_unshift($this->js_commands, array('hide_message', $unlock));
47124c 401         }
ef27a6 402
49dac9 403         if (!empty($this->script_files))
T 404           $this->set_env('request_token', $this->app->get_request_token());
ef27a6 405
47124c 406         // write all env variables to client
4d1fe2 407         if ($commands = $this->get_js_commands()) {
AM 408             $js = $this->framed ? "if (window.parent) {\n" : '';
409             $js .= $commands . ($this->framed ? ' }' : '');
410             $this->add_script($js, 'head_top');
411         }
ad334a 412
c170bf 413         // send clickjacking protection headers
T 414         $iframe = $this->framed || !empty($_REQUEST['_framed']);
415         if (!headers_sent() && ($xframe = $this->app->config->get('x_frame_options', 'sameorigin')))
416             header('X-Frame-Options: ' . ($iframe && $xframe == 'deny' ? 'sameorigin' : $xframe));
47124c 417
T 418         // call super method
0c2596 419         $this->_write($template, $this->config->get('skin_path'));
47124c 420     }
T 421
422     /**
c739c7 423      * Parse a specific skin template and deliver to stdout (or return)
47124c 424      *
T 425      * @param  string  Template name
426      * @param  boolean Exit script
c739c7 427      * @param  boolean Don't write to stdout, return parsed content instead
A 428      *
47124c 429      * @link   http://php.net/manual/en/function.exit.php
T 430      */
c739c7 431     function parse($name = 'main', $exit = true, $write = true)
47124c 432     {
ca18a9 433         $plugin    = false;
A 434         $realname  = $name;
8fa22e 435         $this->template_name = $realname;
8e99ff 436
8fa22e 437         $temp = explode('.', $name, 2);
e7008c 438         if (count($temp) > 1) {
ca18a9 439             $plugin    = $temp[0];
A 440             $name      = $temp[1];
0c2596 441             $skin_dir  = $plugin . '/skins/' . $this->config->get('skin');
ca18a9 442
8fa22e 443             // apply skin search escalation list to plugin directory
TB 444             $plugin_skin_paths = array();
445             foreach ($this->skin_paths as $skin_path) {
28de39 446                 $plugin_skin_paths[] = $this->app->plugins->url . $plugin . '/' . $skin_path;
8fa22e 447             }
TB 448
449             // add fallback to default skin
450             if (is_dir($this->app->plugins->dir . $plugin . '/skins/default')) {
20d50d 451                 $skin_dir = $plugin . '/skins/default';
28de39 452                 $plugin_skin_paths[] = $this->app->plugins->url . $skin_dir;
8fa22e 453             }
TB 454
455             // add plugin skin paths to search list
456             $this->skin_paths = array_merge($plugin_skin_paths, $this->skin_paths);
457         }
458
459         // find skin template
460         $path = false;
461         foreach ($this->skin_paths as $skin_path) {
462             $path = "$skin_path/templates/$name.html";
463
464             // fallback to deprecated template names
465             if (!is_readable($path) && $this->deprecated_templates[$realname]) {
466                 $path = "$skin_path/templates/" . $this->deprecated_templates[$realname] . ".html";
bc66f7 467
TB 468                 if (is_readable($path)) {
469                     rcube::raise_error(array(
470                         'code' => 502, 'type' => 'php',
471                         'file' => __FILE__, 'line' => __LINE__,
472                         'message' => "Using deprecated template '" . $this->deprecated_templates[$realname]
473                             . "' in $skin_path/templates. Please rename to '$realname'"),
474                         true, false);
475                 }
8fa22e 476             }
TB 477
478             if (is_readable($path)) {
479                 $this->config->set('skin_path', $skin_path);
3806f1 480                 $this->base_path = preg_replace('!plugins/\w+/!', '', $skin_path);  // set base_path to core skin directory (not plugin's skin)
44e3bf 481                 $skin_dir = preg_replace('!^plugins/!', '', $skin_path);
8fa22e 482                 break;
TB 483             }
484             else {
485                 $path = false;
20d50d 486             }
e7008c 487         }
ad334a 488
ff73e0 489         // read template file
8fa22e 490         if (!$path || ($templ = @file_get_contents($path)) === false) {
0c2596 491             rcube::raise_error(array(
47124c 492                 'code' => 501,
T 493                 'type' => 'php',
494                 'line' => __LINE__,
495                 'file' => __FILE__,
ca18a9 496                 'message' => 'Error loading template for '.$realname
397cf7 497                 ), true, $write);
47124c 498             return false;
T 499         }
ad334a 500
66f68e 501         // replace all path references to plugins/... with the configured plugins dir
T 502         // and /this/ to the current plugin skin directory
e7008c 503         if ($plugin) {
20d50d 504             $templ = preg_replace(array('/\bplugins\//', '/(["\']?)\/this\//'), array($this->app->plugins->url, '\\1'.$this->app->plugins->url.$skin_dir.'/'), $templ);
e7008c 505         }
47124c 506
T 507         // parse for specialtags
508         $output = $this->parse_conditions($templ);
509         $output = $this->parse_xml($output);
ad334a 510
742d61 511         // trigger generic hook where plugins can put additional content to the page
ca18a9 512         $hook = $this->app->plugins->exec_hook("render_page", array('template' => $realname, 'content' => $output));
47124c 513
e4a4ca 514         // save some memory
A 515         $output = $hook['content'];
516         unset($hook['content']);
517
5172ac 518         // make sure all <form> tags have a valid request token
T 519         $output = preg_replace_callback('/<form\s+([^>]+)>/Ui', array($this, 'alter_form_tag'), $output);
520         $this->footer = preg_replace_callback('/<form\s+([^>]+)>/Ui', array($this, 'alter_form_tag'), $this->footer);
521
5be6dc 522         if (!$write) {
c739c7 523             return $output;
47124c 524         }
ad334a 525
5be6dc 526         $this->write(trim($output));
AM 527
47124c 528         if ($exit) {
T 529             exit;
530         }
531     }
532
533     /**
534      * Return executable javascript code for all registered commands
535      *
536      * @return string $out
537      */
0c2596 538     protected function get_js_commands()
47124c 539     {
T 540         $out = '';
541         if (!$this->framed && !empty($this->js_env)) {
60226a 542             $out .= self::JS_OBJECT_NAME . '.set_env('.self::json_serialize($this->js_env).");\n";
47124c 543         }
4dcd43 544         if (!empty($this->js_labels)) {
T 545             $this->command('add_label', $this->js_labels);
546         }
47124c 547         foreach ($this->js_commands as $i => $args) {
T 548             $method = array_shift($args);
549             foreach ($args as $i => $arg) {
0c2596 550                 $args[$i] = self::json_serialize($arg);
47124c 551             }
T 552             $parent = $this->framed || preg_match('/^parent\./', $method);
553             $out .= sprintf(
554                 "%s.%s(%s);\n",
60226a 555                 ($parent ? 'if(window.parent && parent.'.self::JS_OBJECT_NAME.') parent.' : '') . self::JS_OBJECT_NAME,
cc97ea 556                 preg_replace('/^parent\./', '', $method),
T 557                 implode(',', $args)
47124c 558             );
T 559         }
ad334a 560
47124c 561         return $out;
T 562     }
563
564     /**
565      * Make URLs starting with a slash point to skin directory
566      *
567      * @param  string Input string
28de39 568      * @param  boolean True if URL should be resolved using the current skin path stack
47124c 569      * @return string
T 570      */
28de39 571     public function abs_url($str, $search_path = false)
47124c 572     {
28de39 573         if ($str[0] == '/') {
TB 574             if ($search_path && ($file_url = $this->get_skin_file($str, $skin_path)))
575                 return $file_url;
576
8fa22e 577             return $this->base_path . $str;
28de39 578         }
2aa2b3 579         else
A 580             return $str;
0c2596 581     }
A 582
583     /**
584      * Show error page and terminate script execution
585      *
586      * @param int    $code     Error code
587      * @param string $message  Error message
588      */
589     public function raise_error($code, $message)
590     {
591         global $__page_content, $ERROR_CODE, $ERROR_MESSAGE;
592
593         $ERROR_CODE    = $code;
594         $ERROR_MESSAGE = $message;
595
9be2f4 596         include RCUBE_INSTALL_PATH . 'program/steps/utils/error.inc';
0c2596 597         exit;
47124c 598     }
T 599
600
601     /*****  Template parsing methods  *****/
602
603     /**
604      * Replace all strings ($varname)
605      * with the content of the according global variable.
606      */
0c2596 607     protected function parse_with_globals($input)
47124c 608     {
0c2596 609         $GLOBALS['__version']   = html::quote(RCMAIL_VERSION);
A 610         $GLOBALS['__comm_path'] = html::quote($this->app->comm_path);
8fa22e 611         $GLOBALS['__skin_path'] = html::quote($this->base_path);
0c2596 612
5740c0 613         return preg_replace_callback('/\$(__[a-z0-9_\-]+)/',
0c2596 614             array($this, 'globals_callback'), $input);
5740c0 615     }
0c2596 616
5740c0 617     /**
A 618      * Callback funtion for preg_replace_callback() in parse_with_globals()
619      */
0c2596 620     protected function globals_callback($matches)
5740c0 621     {
A 622         return $GLOBALS[$matches[1]];
8fa22e 623     }
TB 624
625     /**
626      * Correct absolute paths in images and other tags
627      * add timestamp to .js and .css filename
628      */
629     protected function fix_paths($output)
630     {
631         return preg_replace_callback(
632             '!(src|href|background)=(["\']?)([a-z0-9/_.-]+)(["\'\s>])!i',
633             array($this, 'file_callback'), $output);
634     }
635
636     /**
637      * Callback function for preg_replace_callback in write()
638      *
639      * @return string Parsed string
640      */
641     protected function file_callback($matches)
642     {
643         $file = $matches[3];
76f4f7 644         $file = preg_replace('!^/this/!', '/', $file);
8fa22e 645
TB 646         // correct absolute paths
647         if ($file[0] == '/') {
648             $file = $this->base_path . $file;
649         }
650
651         // add file modification timestamp
538e64 652         if (preg_match('/\.(js|css)$/', $file, $m)) {
c562a3 653             $file = $this->file_mod($file);
8fa22e 654         }
TB 655
656         return $matches[1] . '=' . $matches[2] . $file . $matches[4];
c562a3 657     }
AM 658
659     /**
660      * Modify file by adding mtime indicator
661      */
662     protected function file_mod($file)
663     {
664         $fs  = false;
665         $ext = substr($file, strrpos($file, '.') + 1);
666
667         // use minified file if exists (not in development mode)
668         if (!$this->devel_mode && !preg_match('/\.min\.' . $ext . '$/', $file)) {
669             $minified_file = substr($file, 0, strlen($ext) * -1) . 'min.' . $ext;
670             if ($fs = @filemtime($minified_file)) {
671                 return $minified_file . '?s=' . $fs;
672             }
673         }
674
675         if ($fs = @filemtime($file)) {
676             $file .= '?s=' . $fs;
677         }
678
679         return $file;
47124c 680     }
0c2596 681
47124c 682     /**
T 683      * Public wrapper to dipp into template parsing.
684      *
685      * @param  string $input
686      * @return string
a7e8eb 687      * @uses   rcmail_output_html::parse_xml()
47124c 688      * @since  0.1-rc1
T 689      */
690     public function just_parse($input)
691     {
b01d84 692         $input = $this->parse_conditions($input);
AM 693         $input = $this->parse_xml($input);
694
695         return $input;
47124c 696     }
0c2596 697
47124c 698     /**
T 699      * Parse for conditional tags
700      *
701      * @param  string $input
702      * @return string
703      */
0c2596 704     protected function parse_conditions($input)
47124c 705     {
84581e 706         $matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>\n?/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE);
47124c 707         if ($matches && count($matches) == 4) {
T 708             if (preg_match('/^(else|endif)$/i', $matches[1])) {
709                 return $matches[0] . $this->parse_conditions($matches[3]);
710             }
0c2596 711             $attrib = html::parse_attrib_string($matches[2]);
47124c 712             if (isset($attrib['condition'])) {
T 713                 $condmet = $this->check_condition($attrib['condition']);
84581e 714                 $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>\n?/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
47124c 715                 if ($condmet) {
T 716                     $result = $submatches[0];
84581e 717                     $result.= ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>\n?/Uis', '', $submatches[3], 1) : $submatches[3]);
47124c 718                 }
T 719                 else {
720                     $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
721                 }
722                 return $matches[0] . $this->parse_conditions($result);
723             }
0c2596 724             rcube::raise_error(array(
47124c 725                 'code' => 500,
T 726                 'type' => 'php',
727                 'line' => __LINE__,
728                 'file' => __FILE__,
729                 'message' => "Unable to parse conditional tag " . $matches[2]
730             ), true, false);
731         }
732         return $input;
733     }
734
735     /**
736      * Determines if a given condition is met
737      *
738      * @todo   Extend this to allow real conditions, not just "set"
739      * @param  string Condition statement
8e1d4a 740      * @return boolean True if condition is met, False if not
47124c 741      */
0c2596 742     protected function check_condition($condition)
47124c 743     {
029d18 744         return $this->eval_expression($condition);
549933 745     }
ad334a 746
549933 747     /**
2eb794 748      * Inserts hidden field with CSRF-prevention-token into POST forms
549933 749      */
0c2596 750     protected function alter_form_tag($matches)
549933 751     {
0c2596 752         $out    = $matches[0];
A 753         $attrib = html::parse_attrib_string($matches[1]);
ad334a 754
549933 755         if (strtolower($attrib['method']) == 'post') {
T 756             $hidden = new html_hiddenfield(array('name' => '_token', 'value' => $this->app->get_request_token()));
757             $out .= "\n" . $hidden->show();
758         }
ad334a 759
549933 760         return $out;
8e1d4a 761     }
A 762
763     /**
58e3a5 764      * Parse & evaluate a given expression and return its result.
f790b4 765      *
AM 766      * @param string Expression statement
767      *
768      * @return mixed Expression result
8e1d4a 769      */
f790b4 770     protected function eval_expression ($expression)
AM 771     {
58e3a5 772         $expression = preg_replace(
47124c 773             array(
T 774                 '/session:([a-z0-9_]+)/i',
f645ce 775                 '/config:([a-z0-9_]+)(:([a-z0-9_]+))?/i',
40353f 776                 '/env:([a-z0-9_]+)/i',
A 777                 '/request:([a-z0-9_]+)/i',
778                 '/cookie:([a-z0-9_]+)/i',
8e99ff 779                 '/browser:([a-z0-9_]+)/i',
A 780                 '/template:name/i',
47124c 781             ),
T 782             array(
783                 "\$_SESSION['\\1']",
d67485 784                 "\$app->config->get('\\1',rcube_utils::get_boolean('\\3'))",
AW 785                 "\$env['\\1']",
1aceb9 786                 "rcube_utils::get_input_value('\\1', rcube_utils::INPUT_GPC)",
a17fe6 787                 "\$_COOKIE['\\1']",
d67485 788                 "\$browser->{'\\1'}",
8e99ff 789                 $this->template_name,
47124c 790             ),
58e3a5 791             $expression
AW 792         );
f790b4 793
d67485 794         $fn = create_function('$app,$browser,$env', "return ($expression);");
f790b4 795         if (!$fn) {
58e3a5 796             rcube::raise_error(array(
AW 797                 'code' => 505,
798                 'type' => 'php',
799                 'file' => __FILE__,
800                 'line' => __LINE__,
801                 'message' => "Expression parse error on: ($expression)"), true, false);
f790b4 802
AM 803             return null;
58e3a5 804         }
f790b4 805
d67485 806         return $fn($this->app, $this->browser, $this->env);
47124c 807     }
T 808
809     /**
810      * Search for special tags in input and replace them
811      * with the appropriate content
812      *
813      * @param  string Input string to parse
814      * @return string Altered input string
06655a 815      * @todo   Use DOM-parser to traverse template HTML
47124c 816      * @todo   Maybe a cache.
T 817      */
0c2596 818     protected function parse_xml($input)
47124c 819     {
6af593 820         return preg_replace_callback('/<roundcube:([-_a-z]+)\s+((?:[^>]|\\\\>)+)(?<!\\\\)>/Ui', array($this, 'xml_command'), $input);
6f488b 821     }
A 822
823     /**
cc97ea 824      * Callback function for parsing an xml command tag
T 825      * and turn it into real html content
47124c 826      *
cc97ea 827      * @param  array Matches array of preg_replace_callback
47124c 828      * @return string Tag/Object content
T 829      */
0c2596 830     protected function xml_command($matches)
47124c 831     {
cc97ea 832         $command = strtolower($matches[1]);
0c2596 833         $attrib  = html::parse_attrib_string($matches[2]);
47124c 834
T 835         // empty output if required condition is not met
836         if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
837             return '';
838         }
839
840         // execute command
841         switch ($command) {
842             // return a button
843             case 'button':
875a48 844                 if ($attrib['name'] || $attrib['command']) {
47124c 845                     return $this->button($attrib);
T 846                 }
847                 break;
848
b7d33e 849             // frame
AM 850             case 'frame':
851                 return $this->frame($attrib);
852                 break;
853
47124c 854             // show a label
T 855             case 'label':
8fa22e 856                 if ($attrib['expression'])
fe245e 857                     $attrib['name'] = $this->eval_expression($attrib['expression']);
8fa22e 858
47124c 859                 if ($attrib['name'] || $attrib['command']) {
0d80fa 860                     // @FIXME: 'noshow' is useless, remove?
AM 861                     if ($attrib['noshow']) {
862                         return '';
863                     }
864
0c2596 865                     $vars = $attrib + array('product' => $this->config->get('product_name'));
c87806 866                     unset($vars['name'], $vars['command']);
0d80fa 867
AM 868                     $label   = $this->app->gettext($attrib + array('vars' => $vars));
f707fe 869                     $quoting = !empty($attrib['quoting']) ? strtolower($attrib['quoting']) : (rcube_utils::get_boolean((string)$attrib['html']) ? 'no' : '');
0d80fa 870
fa8f6e 871                     switch ($quoting) {
TB 872                         case 'no':
0d80fa 873                         case 'raw':
AM 874                             break;
fa8f6e 875                         case 'javascript':
0d80fa 876                         case 'js':
10da75 877                             $label = rcube::JQ($label);
0d80fa 878                             break;
AM 879                         default:
880                             $label = html::quote($label);
881                             break;
fa8f6e 882                     }
0d80fa 883
AM 884                     return $label;
47124c 885                 }
T 886                 break;
887
888             // include a file
889             case 'include':
8fa22e 890                 $old_base_path = $this->base_path;
175739 891                 if (!empty($attrib['skin_path'])) $attrib['skinpath'] = $attrib['skin_path'];
19b0d4 892                 if ($path = $this->get_skin_file($attrib['file'], $skin_path, $attrib['skinpath'])) {
2a0d3f 893                     $this->base_path = preg_replace('!plugins/\w+/!', '', $skin_path);  // set base_path to core skin directory (not plugin's skin)
28de39 894                     $path = realpath($path);
8fa22e 895                 }
0c2596 896
ff73e0 897                 if (is_readable($path)) {
0c2596 898                     if ($this->config->get('skin_include_php')) {
47124c 899                         $incl = $this->include_php($path);
T 900                     }
ff73e0 901                     else {
cc97ea 902                       $incl = file_get_contents($path);
T 903                     }
b4f7c6 904                     $incl = $this->parse_conditions($incl);
8fa22e 905                     $incl = $this->parse_xml($incl);
TB 906                     $incl = $this->fix_paths($incl);
907                     $this->base_path = $old_base_path;
908                     return $incl;
47124c 909                 }
T 910                 break;
911
912             case 'plugin.include':
cc97ea 913                 $hook = $this->app->plugins->exec_hook("template_plugin_include", $attrib);
T 914                 return $hook['content'];
ad334a 915
cc97ea 916             // define a container block
T 917             case 'container':
918                 if ($attrib['name'] && $attrib['id']) {
919                     $this->command('gui_container', $attrib['name'], $attrib['id']);
920                     // let plugins insert some content here
921                     $hook = $this->app->plugins->exec_hook("template_container", $attrib);
922                     return $hook['content'];
47124c 923                 }
T 924                 break;
925
926             // return code for a specific application object
927             case 'object':
928                 $object = strtolower($attrib['name']);
cc97ea 929                 $content = '';
47124c 930
T 931                 // we are calling a class/method
932                 if (($handler = $this->object_handlers[$object]) && is_array($handler)) {
933                     if ((is_object($handler[0]) && method_exists($handler[0], $handler[1])) ||
934                     (is_string($handler[0]) && class_exists($handler[0])))
cc97ea 935                     $content = call_user_func($handler, $attrib);
47124c 936                 }
cc97ea 937                 // execute object handler function
47124c 938                 else if (function_exists($handler)) {
cc97ea 939                     $content = call_user_func($handler, $attrib);
47124c 940                 }
f23073 941                 else if ($object == 'doctype') {
T 942                     $content = html::doctype($attrib['value']);
943                 }
ae39c4 944                 else if ($object == 'logo') {
T 945                     $attrib += array('alt' => $this->xml_command(array('', 'object', 'name="productname"')));
a77504 946
fb4474 947                     if ($logo = $this->config->get('skin_logo')) {
P 948                         if (is_array($logo)) {
949                             if ($template_logo = $logo[$this->template_name]) {
950                                 $attrib['src'] = $template_logo;
951                             }
952                             elseif ($template_logo = $logo['*']) {
953                                 $attrib['src'] = $template_logo;
954                             }
955                         }
956                         else {
957                             $attrib['src'] = $logo;
958                         }
a77504 959                     }
P 960
ae39c4 961                     $content = html::img($attrib);
T 962                 }
cc97ea 963                 else if ($object == 'productname') {
0c2596 964                     $name = $this->config->get('product_name', 'Roundcube Webmail');
A 965                     $content = html::quote($name);
47124c 966                 }
cc97ea 967                 else if ($object == 'version') {
c8fb2b 968                     $ver = (string)RCMAIL_VERSION;
9be2f4 969                     if (is_file(RCUBE_INSTALL_PATH . '.svn/entries')) {
c8fb2b 970                         if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
T 971                           $ver .= ' [SVN r'.$regs[1].']';
972                     }
9be2f4 973                     else if (is_file(RCUBE_INSTALL_PATH . '.git/index')) {
914c3e 974                         if (preg_match('/Date:\s+([^\n]+)/', @shell_exec('git log -1'), $regs)) {
AM 975                             if ($date = date('Ymd.Hi', strtotime($regs[1]))) {
976                                 $ver .= ' [GIT '.$date.']';
977                             }
978                         }
979                     }
0c2596 980                     $content = html::quote($ver);
47124c 981                 }
cc97ea 982                 else if ($object == 'steptitle') {
0c2596 983                   $content = html::quote($this->get_pagetitle());
f645ce 984                 }
cc97ea 985                 else if ($object == 'pagetitle') {
538e64 986                     if ($this->devel_mode && !empty($_SESSION['username']))
0c2596 987                         $title = $_SESSION['username'].' :: ';
A 988                     else if ($prod_name = $this->config->get('product_name'))
989                         $title = $prod_name . ' :: ';
159763 990                     else
0c2596 991                         $title = '';
f645ce 992                     $title .= $this->get_pagetitle();
0c2596 993                     $content = html::quote($title);
47124c 994                 }
ad334a 995
cc97ea 996                 // exec plugin hooks for this template object
T 997                 $hook = $this->app->plugins->exec_hook("template_object_$object", $attrib + array('content' => $content));
998                 return $hook['content'];
8e1d4a 999
A 1000             // return code for a specified eval expression
1001             case 'exp':
f790b4 1002                 return html::quote($this->eval_expression($attrib['expression']));
ad334a 1003
47124c 1004             // return variable
T 1005             case 'var':
1006                 $var = explode(':', $attrib['name']);
1007                 $name = $var[1];
1008                 $value = '';
1009
1010                 switch ($var[0]) {
1011                     case 'env':
1012                         $value = $this->env[$name];
1013                         break;
1014                     case 'config':
0c2596 1015                         $value = $this->config->get($name);
c321a9 1016                         if (is_array($value) && $value[$_SESSION['storage_host']]) {
T 1017                             $value = $value[$_SESSION['storage_host']];
47124c 1018                         }
T 1019                         break;
1020                     case 'request':
1aceb9 1021                         $value = rcube_utils::get_input_value($name, rcube_utils::INPUT_GPC);
47124c 1022                         break;
T 1023                     case 'session':
1024                         $value = $_SESSION[$name];
1025                         break;
d4273b 1026                     case 'cookie':
A 1027                         $value = htmlspecialchars($_COOKIE[$name]);
1028                         break;
a17fe6 1029                     case 'browser':
A 1030                         $value = $this->browser->{$name};
1031                         break;
47124c 1032                 }
T 1033
1034                 if (is_array($value)) {
1035                     $value = implode(', ', $value);
1036                 }
1037
0c2596 1038                 return html::quote($value);
deb2b8 1039
TB 1040             case 'form':
1041                 return $this->form_tag($attrib);
47124c 1042         }
T 1043         return '';
1044     }
0c2596 1045
47124c 1046     /**
T 1047      * Include a specific file and return it's contents
1048      *
1049      * @param string File path
1050      * @return string Contents of the processed file
1051      */
0c2596 1052     protected function include_php($file)
47124c 1053     {
T 1054         ob_start();
1055         include $file;
1056         $out = ob_get_contents();
1057         ob_end_clean();
1058
1059         return $out;
1060     }
1061
1062     /**
1063      * Create and register a button
1064      *
1065      * @param  array Named button attributes
1066      * @return string HTML button
1067      * @todo   Remove all inline JS calls and use jQuery instead.
1068      * @todo   Remove all sprintf()'s - they are pretty, but also slow.
1069      */
ed132e 1070     public function button($attrib)
47124c 1071     {
T 1072         static $s_button_count = 100;
1073
1074         // these commands can be called directly via url
cc97ea 1075         $a_static_commands = array('compose', 'list', 'preferences', 'folders', 'identities');
47124c 1076
c49c35 1077         if (!($attrib['command'] || $attrib['name'] || $attrib['href'])) {
47124c 1078             return '';
T 1079         }
ae0c82 1080
47124c 1081         // try to find out the button type
T 1082         if ($attrib['type']) {
1083             $attrib['type'] = strtolower($attrib['type']);
1084         }
1085         else {
1086             $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
1087         }
e9b5a6 1088
47124c 1089         $command = $attrib['command'];
T 1090
e9b5a6 1091         if ($attrib['task'])
T 1092           $command = $attrib['task'] . '.' . $command;
ad334a 1093
af3cf8 1094         if (!$attrib['image']) {
T 1095             $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1096         }
47124c 1097
T 1098         if (!$attrib['id']) {
1099             $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
1100         }
1101         // get localized text for labels and titles
1102         if ($attrib['title']) {
0c2596 1103             $attrib['title'] = html::quote($this->app->gettext($attrib['title'], $attrib['domain']));
47124c 1104         }
T 1105         if ($attrib['label']) {
0c2596 1106             $attrib['label'] = html::quote($this->app->gettext($attrib['label'], $attrib['domain']));
47124c 1107         }
T 1108         if ($attrib['alt']) {
0c2596 1109             $attrib['alt'] = html::quote($this->app->gettext($attrib['alt'], $attrib['domain']));
47124c 1110         }
9b2ccd 1111
47124c 1112         // set title to alt attribute for IE browsers
c9e9fe 1113         if ($this->browser->ie && !$attrib['title'] && $attrib['alt']) {
A 1114             $attrib['title'] = $attrib['alt'];
47124c 1115         }
T 1116
1117         // add empty alt attribute for XHTML compatibility
1118         if (!isset($attrib['alt'])) {
1119             $attrib['alt'] = '';
1120         }
1121
1122         // register button in the system
1123         if ($attrib['command']) {
1124             $this->add_script(sprintf(
1125                 "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
60226a 1126                 self::JS_OBJECT_NAME,
47124c 1127                 $command,
T 1128                 $attrib['id'],
1129                 $attrib['type'],
ae0c82 1130                 $attrib['imageact'] ? $this->abs_url($attrib['imageact']) : $attrib['classact'],
A 1131                 $attrib['imagesel'] ? $this->abs_url($attrib['imagesel']) : $attrib['classsel'],
1132                 $attrib['imageover'] ? $this->abs_url($attrib['imageover']) : ''
47124c 1133             ));
T 1134
1135             // make valid href to specific buttons
197601 1136             if (in_array($attrib['command'], rcmail::$main_tasks)) {
0c2596 1137                 $attrib['href']    = $this->app->url(array('task' => $attrib['command']));
60226a 1138                 $attrib['onclick'] = sprintf("return %s.command('switch-task','%s',this,event)", self::JS_OBJECT_NAME, $attrib['command']);
47124c 1139             }
e9b5a6 1140             else if ($attrib['task'] && in_array($attrib['task'], rcmail::$main_tasks)) {
0c2596 1141                 $attrib['href'] = $this->app->url(array('action' => $attrib['command'], 'task' => $attrib['task']));
e9b5a6 1142             }
47124c 1143             else if (in_array($attrib['command'], $a_static_commands)) {
0c2596 1144                 $attrib['href'] = $this->app->url(array('action' => $attrib['command']));
a25d39 1145             }
271efe 1146             else if (($attrib['command'] == 'permaurl' || $attrib['command'] == 'extwin') && !empty($this->env['permaurl'])) {
29f977 1147               $attrib['href'] = $this->env['permaurl'];
T 1148             }
47124c 1149         }
T 1150
1151         // overwrite attributes
1152         if (!$attrib['href']) {
1153             $attrib['href'] = '#';
1154         }
e9b5a6 1155         if ($attrib['task']) {
T 1156             if ($attrib['classact'])
1157                 $attrib['class'] = $attrib['classact'];
1158         }
1159         else if ($command && !$attrib['onclick']) {
47124c 1160             $attrib['onclick'] = sprintf(
c28161 1161                 "return %s.command('%s','%s',this,event)",
60226a 1162                 self::JS_OBJECT_NAME,
47124c 1163                 $command,
T 1164                 $attrib['prop']
1165             );
1166         }
1167
1168         $out = '';
1169
1170         // generate image tag
0c2596 1171         if ($attrib['type'] == 'image') {
47124c 1172             $attrib_str = html::attrib_string(
T 1173                 $attrib,
1174                 array(
c9e9fe 1175                     'style', 'class', 'id', 'width', 'height', 'border', 'hspace',
A 1176                     'vspace', 'align', 'alt', 'tabindex', 'title'
47124c 1177                 )
T 1178             );
ae0c82 1179             $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
47124c 1180             if ($attrib['label']) {
T 1181                 $btn_content .= ' '.$attrib['label'];
1182             }
c9e9fe 1183             $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'target');
47124c 1184         }
0c2596 1185         else if ($attrib['type'] == 'link') {
356a67 1186             $btn_content = isset($attrib['content']) ? $attrib['content'] : ($attrib['label'] ? $attrib['label'] : $attrib['command']);
59cdb4 1187             $link_attrib = array_merge(html::$common_attrib, array('href', 'onclick', 'tabindex', 'target'));
5587b3 1188             if ($attrib['innerclass'])
T 1189                 $btn_content = html::span($attrib['innerclass'], $btn_content);
47124c 1190         }
0c2596 1191         else if ($attrib['type'] == 'input') {
47124c 1192             $attrib['type'] = 'button';
T 1193
1194             if ($attrib['label']) {
1195                 $attrib['value'] = $attrib['label'];
1196             }
f94e44 1197             if ($attrib['command']) {
T 1198               $attrib['disabled'] = 'disabled';
1199             }
47124c 1200
ce6433 1201             $out = html::tag('input', $attrib, null, array('type', 'value', 'onclick', 'id', 'class', 'style', 'tabindex', 'disabled'));
47124c 1202         }
T 1203
1204         // generate html code for button
1205         if ($btn_content) {
5e8da2 1206             $attrib_str = html::attrib_string($attrib, array_merge($link_attrib, array('data-*')));
47124c 1207             $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
T 1208         }
1209
bc2c43 1210         if ($attrib['wrapper']) {
AM 1211             $out = html::tag($attrib['wrapper'], null, $out);
47124c 1212         }
T 1213
1214         return $out;
0c2596 1215     }
A 1216
1217     /**
1218      * Link an external script file
1219      *
1220      * @param string File URL
1221      * @param string Target position [head|foot]
1222      */
1223     public function include_script($file, $position='head')
1224     {
1225         if (!preg_match('|^https?://|i', $file) && $file[0] != '/') {
c562a3 1226             $file = $this->file_mod($this->scripts_path . $file);
0c2596 1227         }
A 1228
1229         if (!is_array($this->script_files[$position])) {
1230             $this->script_files[$position] = array();
1231         }
1232
e46d06 1233         if (!in_array($file, $this->script_files[$position])) {
TB 1234             $this->script_files[$position][] = $file;
1235         }
0c2596 1236     }
A 1237
1238     /**
1239      * Add inline javascript code
1240      *
1241      * @param string JS code snippet
1242      * @param string Target position [head|head_top|foot]
1243      */
1244     public function add_script($script, $position='head')
1245     {
1246         if (!isset($this->scripts[$position])) {
1247             $this->scripts[$position] = "\n" . rtrim($script);
1248         }
1249         else {
1250             $this->scripts[$position] .= "\n" . rtrim($script);
1251         }
1252     }
1253
1254     /**
1255      * Link an external css file
1256      *
1257      * @param string File URL
1258      */
1259     public function include_css($file)
1260     {
1261         $this->css_files[] = $file;
1262     }
1263
1264     /**
1265      * Add HTML code to the page header
1266      *
1267      * @param string $str HTML code
1268      */
1269     public function add_header($str)
1270     {
1271         $this->header .= "\n" . $str;
1272     }
1273
1274     /**
1275      * Add HTML code to the page footer
1276      * To be added right befor </body>
1277      *
1278      * @param string $str HTML code
1279      */
1280     public function add_footer($str)
1281     {
1282         $this->footer .= "\n" . $str;
1283     }
1284
1285     /**
1286      * Process template and write to stdOut
1287      *
1288      * @param string HTML template
1289      * @param string Base for absolute paths
1290      */
1291     public function _write($templ = '', $base_path = '')
1292     {
e2f90d 1293         $output = trim($templ);
AM 1294
1295         if (empty($output)) {
1296             $output   = $this->default_template;
1297             $is_empty = true;
1298         }
0c2596 1299
A 1300         // set default page title
1301         if (empty($this->pagetitle)) {
1302             $this->pagetitle = 'Roundcube Mail';
1303         }
1304
1305         // replace specialchars in content
1306         $page_title  = html::quote($this->pagetitle);
1307         $page_header = '';
1308         $page_footer = '';
1309
1310         // include meta tag with charset
1311         if (!empty($this->charset)) {
1312             if (!headers_sent()) {
1313                 header('Content-Type: text/html; charset=' . $this->charset);
1314             }
1315             $page_header = '<meta http-equiv="content-type"';
1316             $page_header.= ' content="text/html; charset=';
1317             $page_header.= $this->charset . '" />'."\n";
1318         }
1319
1320         // definition of the code to be placed in the document header and footer
1321         if (is_array($this->script_files['head'])) {
1322             foreach ($this->script_files['head'] as $file) {
1323                 $page_header .= html::script($file);
1324             }
1325         }
1326
1327         $head_script = $this->scripts['head_top'] . $this->scripts['head'];
1328         if (!empty($head_script)) {
1329             $page_header .= html::script(array(), $head_script);
1330         }
1331
1332         if (!empty($this->header)) {
1333             $page_header .= $this->header;
1334         }
1335
1336         // put docready commands into page footer
1337         if (!empty($this->scripts['docready'])) {
1338             $this->add_script('$(document).ready(function(){ ' . $this->scripts['docready'] . "\n});", 'foot');
1339         }
1340
1341         if (is_array($this->script_files['foot'])) {
1342             foreach ($this->script_files['foot'] as $file) {
1343                 $page_footer .= html::script($file);
1344             }
1345         }
1346
1347         if (!empty($this->footer)) {
1348             $page_footer .= $this->footer . "\n";
1349         }
1350
1351         if (!empty($this->scripts['foot'])) {
1352             $page_footer .= html::script(array(), $this->scripts['foot']);
1353         }
1354
1355         // find page header
1356         if ($hpos = stripos($output, '</head>')) {
1357             $page_header .= "\n";
1358         }
1359         else {
1360             if (!is_numeric($hpos)) {
1361                 $hpos = stripos($output, '<body');
1362             }
1363             if (!is_numeric($hpos) && ($hpos = stripos($output, '<html'))) {
1364                 while ($output[$hpos] != '>') {
1365                     $hpos++;
1366                 }
1367                 $hpos++;
1368             }
1369             $page_header = "<head>\n<title>$page_title</title>\n$page_header\n</head>\n";
1370         }
1371
1372         // add page hader
1373         if ($hpos) {
1374             $output = substr_replace($output, $page_header, $hpos, 0);
1375         }
1376         else {
1377             $output = $page_header . $output;
1378         }
1379
1380         // add page footer
1381         if (($fpos = strripos($output, '</body>')) || ($fpos = strripos($output, '</html>'))) {
1382             $output = substr_replace($output, $page_footer."\n", $fpos, 0);
1383         }
1384         else {
1385             $output .= "\n".$page_footer;
1386         }
1387
1388         // add css files in head, before scripts, for speed up with parallel downloads
e2f90d 1389         if (!empty($this->css_files) && !$is_empty
AM 1390             && (($pos = stripos($output, '<script ')) || ($pos = stripos($output, '</head>')))
0c2596 1391         ) {
A 1392             $css = '';
1393             foreach ($this->css_files as $file) {
1394                 $css .= html::tag('link', array('rel' => 'stylesheet',
1395                     'type' => 'text/css', 'href' => $file, 'nl' => true));
1396             }
1397             $output = substr_replace($output, $css, $pos, 0);
1398         }
1399
2a0d3f 1400         $output = $this->parse_with_globals($this->fix_paths($output));
TB 1401
0c2596 1402         // trigger hook with final HTML content to be sent
be98df 1403         $hook = $this->app->plugins->exec_hook("send_page", array('content' => $output));
0c2596 1404         if (!$hook['abort']) {
a92beb 1405             if ($this->charset != RCUBE_CHARSET) {
AM 1406                 echo rcube_charset::convert($hook['content'], RCUBE_CHARSET, $this->charset);
0c2596 1407             }
A 1408             else {
1409                 echo $hook['content'];
1410             }
1411         }
47124c 1412     }
T 1413
b7d33e 1414     /**
AM 1415      * Returns iframe object, registers some related env variables
1416      *
1417      * @param array $attrib HTML attributes
28de39 1418      * @param boolean $is_contentframe Register this iframe as the 'contentframe' gui object
b7d33e 1419      * @return string IFRAME element
AM 1420      */
28de39 1421     public function frame($attrib, $is_contentframe = false)
b7d33e 1422     {
28de39 1423         static $idcount = 0;
TB 1424
b7d33e 1425         if (!$attrib['id']) {
28de39 1426             $attrib['id'] = 'rcmframe' . ++$idcount;
b7d33e 1427         }
AM 1428
28de39 1429         $attrib['name'] = $attrib['id'];
TB 1430         $attrib['src'] = $attrib['src'] ? $this->abs_url($attrib['src'], true) : 'program/resources/blank.gif';
b7d33e 1431
28de39 1432         // register as 'contentframe' object
e0f7b9 1433         if ($is_contentframe || $attrib['contentframe']) {
AM 1434             $this->set_env('contentframe', $attrib['contentframe'] ? $attrib['contentframe'] : $attrib['name']);
28de39 1435             $this->set_env('blankpage', $attrib['src']);
TB 1436         }
b7d33e 1437
AM 1438         return html::iframe($attrib);
1439     }
1440
1441
47124c 1442     /*  ************* common functions delivering gui objects **************  */
T 1443
1444     /**
197601 1445      * Create a form tag with the necessary hidden fields
T 1446      *
1447      * @param array Named tag parameters
1448      * @return string HTML code for the form
1449      */
1450     public function form_tag($attrib, $content = null)
1451     {
57f0c8 1452       if ($this->framed || !empty($_REQUEST['_framed'])) {
197601 1453         $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
T 1454         $hidden = $hiddenfield->show();
1455       }
271efe 1456       if ($this->env['extwin']) {
TB 1457         $hiddenfield = new html_hiddenfield(array('name' => '_extwin', 'value' => '1'));
1458         $hidden = $hiddenfield->show();
1459       }
ad334a 1460
197601 1461       if (!$content)
T 1462         $attrib['noclose'] = true;
ad334a 1463
197601 1464       return html::tag('form',
deb2b8 1465         $attrib + array('action' => $this->app->comm_path, 'method' => "get"),
57f0c8 1466         $hidden . $content,
T 1467         array('id','class','style','name','method','action','enctype','onsubmit'));
1468     }
ad334a 1469
57f0c8 1470     /**
T 1471      * Build a form tag with a unique request token
1472      *
1473      * @param array Named tag parameters including 'action' and 'task' values which will be put into hidden fields
1474      * @param string Form content
1475      * @return string HTML code for the form
1476      */
747797 1477     public function request_form($attrib, $content = '')
57f0c8 1478     {
T 1479         $hidden = new html_hiddenfield();
1480         if ($attrib['task']) {
1481             $hidden->add(array('name' => '_task', 'value' => $attrib['task']));
1482         }
1483         if ($attrib['action']) {
1484             $hidden->add(array('name' => '_action', 'value' => $attrib['action']));
1485         }
ad334a 1486
57f0c8 1487         unset($attrib['task'], $attrib['request']);
T 1488         $attrib['action'] = './';
ad334a 1489
57f0c8 1490         // we already have a <form> tag
0501b6 1491         if ($attrib['form']) {
T 1492             if ($this->framed || !empty($_REQUEST['_framed']))
1493                 $hidden->add(array('name' => '_framed', 'value' => '1'));
57f0c8 1494             return $hidden->show() . $content;
0501b6 1495         }
57f0c8 1496         else
T 1497             return $this->form_tag($attrib, $hidden->show() . $content);
197601 1498     }
T 1499
1500     /**
47124c 1501      * GUI object 'username'
T 1502      * Showing IMAP username of the current session
1503      *
1504      * @param array Named tag parameters (currently not used)
1505      * @return string HTML code for the gui object
1506      */
197601 1507     public function current_username($attrib)
47124c 1508     {
T 1509         static $username;
1510
1511         // alread fetched
1512         if (!empty($username)) {
1513             return $username;
1514         }
1515
e99991 1516         // Current username is an e-mail address
A 1517         if (strpos($_SESSION['username'], '@')) {
1518             $username = $_SESSION['username'];
1519         }
929a50 1520         // get e-mail address from default identity
e99991 1521         else if ($sql_arr = $this->app->user->get_identity()) {
7e9cec 1522             $username = $sql_arr['email'];
47124c 1523         }
T 1524         else {
7e9cec 1525             $username = $this->app->user->get_username();
47124c 1526         }
T 1527
1aceb9 1528         return rcube_utils::idn_to_utf8($username);
47124c 1529     }
T 1530
1531     /**
1532      * GUI object 'loginform'
1533      * Returns code for the webmail login form
1534      *
1535      * @param array Named parameters
1536      * @return string HTML code for the gui object
1537      */
0c2596 1538     protected function login_form($attrib)
47124c 1539     {
0c2596 1540         $default_host = $this->config->get('default_host');
A 1541         $autocomplete = (int) $this->config->get('login_autocomplete');
47124c 1542
T 1543         $_SESSION['temp'] = true;
ad334a 1544
cc97ea 1545         // save original url
1aceb9 1546         $url = rcube_utils::get_input_value('_url', rcube_utils::INPUT_POST);
3a2b27 1547         if (empty($url) && !preg_match('/_(task|action)=logout/', $_SERVER['QUERY_STRING']))
cc97ea 1548             $url = $_SERVER['QUERY_STRING'];
47124c 1549
b8dc3e 1550         // Disable autocapitalization on iPad/iPhone (#1488609)
AM 1551         $attrib['autocapitalize'] = 'off';
1552
1cca4f 1553         // set atocomplete attribute
A 1554         $user_attrib = $autocomplete > 0 ? array() : array('autocomplete' => 'off');
1555         $host_attrib = $autocomplete > 0 ? array() : array('autocomplete' => 'off');
1556         $pass_attrib = $autocomplete > 1 ? array() : array('autocomplete' => 'off');
1557
c3be8e 1558         $input_task   = new html_hiddenfield(array('name' => '_task', 'value' => 'login'));
47124c 1559         $input_action = new html_hiddenfield(array('name' => '_action', 'value' => 'login'));
c8ae24 1560         $input_tzone  = new html_hiddenfield(array('name' => '_timezone', 'id' => 'rcmlogintz', 'value' => '_default_'));
cc97ea 1561         $input_url    = new html_hiddenfield(array('name' => '_url', 'id' => 'rcmloginurl', 'value' => $url));
8df6bb 1562         $input_user   = new html_inputfield(array('name' => '_user', 'id' => 'rcmloginuser', 'required' => 'required')
1cca4f 1563             + $attrib + $user_attrib);
8df6bb 1564         $input_pass   = new html_passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'required' => 'required')
1cca4f 1565             + $attrib + $pass_attrib);
47124c 1566         $input_host   = null;
T 1567
f3e101 1568         if (is_array($default_host) && count($default_host) > 1) {
47124c 1569             $input_host = new html_select(array('name' => '_host', 'id' => 'rcmloginhost'));
T 1570
1571             foreach ($default_host as $key => $value) {
1572                 if (!is_array($value)) {
1573                     $input_host->add($value, (is_numeric($key) ? $value : $key));
1574                 }
1575                 else {
1576                     $input_host = null;
1577                     break;
1578                 }
1579             }
f3e101 1580         }
6ff0c3 1581         else if (is_array($default_host) && ($host = key($default_host)) !== null) {
f3e101 1582             $hide_host = true;
A 1583             $input_host = new html_hiddenfield(array(
6ff0c3 1584                 'name' => '_host', 'id' => 'rcmloginhost', 'value' => is_numeric($host) ? $default_host[$host] : $host) + $attrib);
47124c 1585         }
e3e597 1586         else if (empty($default_host)) {
1cca4f 1587             $input_host = new html_inputfield(array('name' => '_host', 'id' => 'rcmloginhost')
A 1588                 + $attrib + $host_attrib);
47124c 1589         }
T 1590
1591         $form_name  = !empty($attrib['form']) ? $attrib['form'] : 'form';
1592         $this->add_gui_object('loginform', $form_name);
1593
1594         // create HTML table with two cols
1595         $table = new html_table(array('cols' => 2));
1596
0c2596 1597         $table->add('title', html::label('rcmloginuser', html::quote($this->app->gettext('username'))));
1aceb9 1598         $table->add('input', $input_user->show(rcube_utils::get_input_value('_user', rcube_utils::INPUT_GPC)));
47124c 1599
0c2596 1600         $table->add('title', html::label('rcmloginpwd', html::quote($this->app->gettext('password'))));
497013 1601         $table->add('input', $input_pass->show());
47124c 1602
T 1603         // add host selection row
f3e101 1604         if (is_object($input_host) && !$hide_host) {
0c2596 1605             $table->add('title', html::label('rcmloginhost', html::quote($this->app->gettext('server'))));
1aceb9 1606             $table->add('input', $input_host->show(rcube_utils::get_input_value('_host', rcube_utils::INPUT_GPC)));
47124c 1607         }
T 1608
c3be8e 1609         $out  = $input_task->show();
T 1610         $out .= $input_action->show();
c8ae24 1611         $out .= $input_tzone->show();
cc97ea 1612         $out .= $input_url->show();
47124c 1613         $out .= $table->show();
ad334a 1614
f3e101 1615         if ($hide_host) {
A 1616             $out .= $input_host->show();
1617         }
47124c 1618
904fec 1619         if (rcube_utils::get_boolean($attrib['submit'])) {
AM 1620             $submit = new html_inputfield(array('type' => 'submit', 'id' => 'rcmloginsubmit',
1621                 'class' => 'button mainaction', 'value' => $this->app->gettext('login')));
1622             $out .= html::p('formbuttons', $submit->show());
1623         }
1624
47124c 1625         // surround html output with a form tag
T 1626         if (empty($attrib['form'])) {
f3e101 1627             $out = $this->form_tag(array('name' => $form_name, 'method' => 'post'), $out);
47124c 1628         }
T 1629
086b15 1630         // include script for timezone detection
TB 1631         $this->include_script('jstz.min.js');
1632
47124c 1633         return $out;
T 1634     }
1635
1636     /**
8e211a 1637      * GUI object 'preloader'
A 1638      * Loads javascript code for images preloading
1639      *
1640      * @param array Named parameters
1641      * @return void
1642      */
0c2596 1643     protected function preloader($attrib)
8e211a 1644     {
A 1645         $images = preg_split('/[\s\t\n,]+/', $attrib['images'], -1, PREG_SPLIT_NO_EMPTY);
1646         $images = array_map(array($this, 'abs_url'), $images);
1647
1648         if (empty($images) || $this->app->task == 'logout')
1649             return;
1650
0c2596 1651         $this->add_script('var images = ' . self::json_serialize($images) .';
8e211a 1652             for (var i=0; i<images.length; i++) {
A 1653                 img = new Image();
1654                 img.src = images[i];
044d66 1655             }', 'docready');
8e211a 1656     }
A 1657
1658     /**
47124c 1659      * GUI object 'searchform'
T 1660      * Returns code for search function
1661      *
1662      * @param array Named parameters
1663      * @return string HTML code for the gui object
1664      */
0c2596 1665     protected function search_form($attrib)
47124c 1666     {
T 1667         // add some labels to client
1668         $this->add_label('searching');
1669
1670         $attrib['name'] = '_q';
1671
1672         if (empty($attrib['id'])) {
1673             $attrib['id'] = 'rcmqsearchbox';
1674         }
a3f149 1675         if ($attrib['type'] == 'search' && !$this->browser->khtml) {
2eb794 1676             unset($attrib['type'], $attrib['results']);
a3f149 1677         }
ad334a 1678
47124c 1679         $input_q = new html_inputfield($attrib);
T 1680         $out = $input_q->show();
1681
1682         $this->add_gui_object('qsearchbox', $attrib['id']);
1683
1684         // add form tag around text field
1685         if (empty($attrib['form'])) {
197601 1686             $out = $this->form_tag(array(
904fec 1687                 'name'     => "rcmqsearchform",
60226a 1688                 'onsubmit' => self::JS_OBJECT_NAME . ".command('search'); return false",
904fec 1689                 'style'    => "display:inline"),
2eb794 1690                 $out);
47124c 1691         }
T 1692
1693         return $out;
1694     }
1695
1696     /**
1697      * Builder for GUI object 'message'
1698      *
1699      * @param array Named tag parameters
1700      * @return string HTML code for the gui object
1701      */
0c2596 1702     protected function message_container($attrib)
47124c 1703     {
T 1704         if (isset($attrib['id']) === false) {
1705             $attrib['id'] = 'rcmMessageContainer';
1706         }
1707
1708         $this->add_gui_object('message', $attrib['id']);
0c2596 1709
A 1710         return html::div($attrib, '');
47124c 1711     }
T 1712
1713     /**
1714      * GUI object 'charsetselector'
1715      *
1716      * @param array Named parameters for the select tag
1717      * @return string HTML code for the gui object
1718      */
0c2596 1719     public function charset_selector($attrib)
47124c 1720     {
T 1721         // pass the following attributes to the form class
1722         $field_attrib = array('name' => '_charset');
1723         foreach ($attrib as $attr => $value) {
e55ab0 1724             if (in_array($attr, array('id', 'name', 'class', 'style', 'size', 'tabindex'))) {
47124c 1725                 $field_attrib[$attr] = $value;
T 1726             }
1727         }
e55ab0 1728
47124c 1729         $charsets = array(
0c2596 1730             'UTF-8'        => 'UTF-8 ('.$this->app->gettext('unicode').')',
A 1731             'US-ASCII'     => 'ASCII ('.$this->app->gettext('english').')',
1732             'ISO-8859-1'   => 'ISO-8859-1 ('.$this->app->gettext('westerneuropean').')',
1733             'ISO-8859-2'   => 'ISO-8859-2 ('.$this->app->gettext('easterneuropean').')',
1734             'ISO-8859-4'   => 'ISO-8859-4 ('.$this->app->gettext('baltic').')',
1735             'ISO-8859-5'   => 'ISO-8859-5 ('.$this->app->gettext('cyrillic').')',
1736             'ISO-8859-6'   => 'ISO-8859-6 ('.$this->app->gettext('arabic').')',
1737             'ISO-8859-7'   => 'ISO-8859-7 ('.$this->app->gettext('greek').')',
1738             'ISO-8859-8'   => 'ISO-8859-8 ('.$this->app->gettext('hebrew').')',
1739             'ISO-8859-9'   => 'ISO-8859-9 ('.$this->app->gettext('turkish').')',
1740             'ISO-8859-10'   => 'ISO-8859-10 ('.$this->app->gettext('nordic').')',
1741             'ISO-8859-11'   => 'ISO-8859-11 ('.$this->app->gettext('thai').')',
1742             'ISO-8859-13'   => 'ISO-8859-13 ('.$this->app->gettext('baltic').')',
1743             'ISO-8859-14'   => 'ISO-8859-14 ('.$this->app->gettext('celtic').')',
1744             'ISO-8859-15'   => 'ISO-8859-15 ('.$this->app->gettext('westerneuropean').')',
1745             'ISO-8859-16'   => 'ISO-8859-16 ('.$this->app->gettext('southeasterneuropean').')',
1746             'WINDOWS-1250' => 'Windows-1250 ('.$this->app->gettext('easterneuropean').')',
1747             'WINDOWS-1251' => 'Windows-1251 ('.$this->app->gettext('cyrillic').')',
1748             'WINDOWS-1252' => 'Windows-1252 ('.$this->app->gettext('westerneuropean').')',
1749             'WINDOWS-1253' => 'Windows-1253 ('.$this->app->gettext('greek').')',
1750             'WINDOWS-1254' => 'Windows-1254 ('.$this->app->gettext('turkish').')',
1751             'WINDOWS-1255' => 'Windows-1255 ('.$this->app->gettext('hebrew').')',
1752             'WINDOWS-1256' => 'Windows-1256 ('.$this->app->gettext('arabic').')',
1753             'WINDOWS-1257' => 'Windows-1257 ('.$this->app->gettext('baltic').')',
1754             'WINDOWS-1258' => 'Windows-1258 ('.$this->app->gettext('vietnamese').')',
1755             'ISO-2022-JP'  => 'ISO-2022-JP ('.$this->app->gettext('japanese').')',
1756             'ISO-2022-KR'  => 'ISO-2022-KR ('.$this->app->gettext('korean').')',
1757             'ISO-2022-CN'  => 'ISO-2022-CN ('.$this->app->gettext('chinese').')',
1758             'EUC-JP'       => 'EUC-JP ('.$this->app->gettext('japanese').')',
1759             'EUC-KR'       => 'EUC-KR ('.$this->app->gettext('korean').')',
1760             'EUC-CN'       => 'EUC-CN ('.$this->app->gettext('chinese').')',
1761             'BIG5'         => 'BIG5 ('.$this->app->gettext('chinese').')',
1762             'GB2312'       => 'GB2312 ('.$this->app->gettext('chinese').')',
e55ab0 1763         );
47124c 1764
089e53 1765         if (!empty($_POST['_charset'])) {
AM 1766             $set = $_POST['_charset'];
1767         }
1768         else if (!empty($attrib['selected'])) {
1769             $set = $attrib['selected'];
1770         }
1771         else {
1772             $set = $this->get_charset();
1773         }
47124c 1774
089e53 1775         $set = strtoupper($set);
AM 1776         if (!isset($charsets[$set])) {
1777             $charsets[$set] = $set;
1778         }
e55ab0 1779
A 1780         $select = new html_select($field_attrib);
1781         $select->add(array_values($charsets), array_keys($charsets));
1782
1783         return $select->show($set);
47124c 1784     }
T 1785
1a0f60 1786     /**
T 1787      * Include content from config/about.<LANG>.html if available
1788      */
0c2596 1789     protected function about_content($attrib)
1a0f60 1790     {
T 1791         $content = '';
1792         $filenames = array(
1793             'about.' . $_SESSION['language'] . '.html',
1794             'about.' . substr($_SESSION['language'], 0, 2) . '.html',
1795             'about.html',
1796         );
1797         foreach ($filenames as $file) {
592668 1798             $fn = RCUBE_CONFIG_DIR . $file;
1a0f60 1799             if (is_readable($fn)) {
T 1800                 $content = file_get_contents($fn);
1801                 $content = $this->parse_conditions($content);
1802                 $content = $this->parse_xml($content);
1803                 break;
1804             }
1805         }
1806
1807         return $content;
1808     }
1809
0c2596 1810 }