source: subversion/trunk/roundcubemail/program/include/rcube_template.php @ 5838

Last change on this file since 5838 was 5838, checked in by thomasb, 16 months ago

Fix special vars replacement in templates

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