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