source: github/program/include/rcube_template.php @ f94e442

HEADcourier-fixdev-browser-capabilitiespdorelease-0.8
Last change on this file since f94e442 was f94e442, checked in by thomascube <thomas@…>, 18 months ago

Add more classes and options to HTML elements for better styleability

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