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

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

Changed license to GNU GPLv3+ with exceptions for skins and plugins

  • Property svn:keywords set to Id
File size: 47.3 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        return preg_replace_callback('/\$(__[a-z0-9_\-]+)/',
532            array($this, 'globals_callback'), $input);
533    }
534
535    /**
536     * Callback funtion for preg_replace_callback() in parse_with_globals()
537     */
538    private function globals_callback($matches)
539    {
540        return $GLOBALS[$matches[1]];
541    }
542
543    /**
544     * Public wrapper to dipp into template parsing.
545     *
546     * @param  string $input
547     * @return string
548     * @uses   rcube_template::parse_xml()
549     * @since  0.1-rc1
550     */
551    public function just_parse($input)
552    {
553        return $this->parse_xml($input);
554    }
555
556    /**
557     * Parse for conditional tags
558     *
559     * @param  string $input
560     * @return string
561     */
562    private function parse_conditions($input)
563    {
564        $matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>\n?/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE);
565        if ($matches && count($matches) == 4) {
566            if (preg_match('/^(else|endif)$/i', $matches[1])) {
567                return $matches[0] . $this->parse_conditions($matches[3]);
568            }
569            $attrib = parse_attrib_string($matches[2]);
570            if (isset($attrib['condition'])) {
571                $condmet = $this->check_condition($attrib['condition']);
572                $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>\n?/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
573                if ($condmet) {
574                    $result = $submatches[0];
575                    $result.= ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>\n?/Uis', '', $submatches[3], 1) : $submatches[3]);
576                }
577                else {
578                    $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
579                }
580                return $matches[0] . $this->parse_conditions($result);
581            }
582            raise_error(array(
583                'code' => 500,
584                'type' => 'php',
585                'line' => __LINE__,
586                'file' => __FILE__,
587                'message' => "Unable to parse conditional tag " . $matches[2]
588            ), true, false);
589        }
590        return $input;
591    }
592
593
594    /**
595     * Determines if a given condition is met
596     *
597     * @todo   Get rid off eval() once I understand what this does.
598     * @todo   Extend this to allow real conditions, not just "set"
599     * @param  string Condition statement
600     * @return boolean True if condition is met, False if not
601     */
602    private function check_condition($condition)
603    {
604        return eval("return (".$this->parse_expression($condition).");");
605    }
606
607
608    /**
609     * Inserts hidden field with CSRF-prevention-token into POST forms
610     */
611    private function alter_form_tag($matches)
612    {
613        $out = $matches[0];
614        $attrib  = parse_attrib_string($matches[1]);
615
616        if (strtolower($attrib['method']) == 'post') {
617            $hidden = new html_hiddenfield(array('name' => '_token', 'value' => $this->app->get_request_token()));
618            $out .= "\n" . $hidden->show();
619        }
620
621        return $out;
622    }
623
624
625    /**
626     * Parses expression and replaces variables
627     *
628     * @param  string Expression statement
629     * @return string Expression value
630     */
631    private function parse_expression($expression)
632    {
633        return preg_replace(
634            array(
635                '/session:([a-z0-9_]+)/i',
636                '/config:([a-z0-9_]+)(:([a-z0-9_]+))?/i',
637                '/env:([a-z0-9_]+)/i',
638                '/request:([a-z0-9_]+)/i',
639                '/cookie:([a-z0-9_]+)/i',
640                '/browser:([a-z0-9_]+)/i',
641                '/template:name/i',
642            ),
643            array(
644                "\$_SESSION['\\1']",
645                "\$this->app->config->get('\\1',get_boolean('\\3'))",
646                "\$this->env['\\1']",
647                "get_input_value('\\1', RCUBE_INPUT_GPC)",
648                "\$_COOKIE['\\1']",
649                "\$this->browser->{'\\1'}",
650                $this->template_name,
651            ),
652            $expression);
653    }
654
655
656    /**
657     * Search for special tags in input and replace them
658     * with the appropriate content
659     *
660     * @param  string Input string to parse
661     * @return string Altered input string
662     * @todo   Use DOM-parser to traverse template HTML
663     * @todo   Maybe a cache.
664     */
665    private function parse_xml($input)
666    {
667        return preg_replace_callback('/<roundcube:([-_a-z]+)\s+((?:[^>]|\\\\>)+)(?<!\\\\)>/Ui', array($this, 'xml_command'), $input);
668    }
669
670
671    /**
672     * Callback function for parsing an xml command tag
673     * and turn it into real html content
674     *
675     * @param  array Matches array of preg_replace_callback
676     * @return string Tag/Object content
677     */
678    private function xml_command($matches)
679    {
680        $command = strtolower($matches[1]);
681        $attrib  = parse_attrib_string($matches[2]);
682
683        // empty output if required condition is not met
684        if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
685            return '';
686        }
687
688        // execute command
689        switch ($command) {
690            // return a button
691            case 'button':
692                if ($attrib['name'] || $attrib['command']) {
693                    return $this->button($attrib);
694                }
695                break;
696
697            // show a label
698            case 'label':
699                if ($attrib['name'] || $attrib['command']) {
700                    $vars = $attrib + array('product' => $this->config['product_name']);
701                    unset($vars['name'], $vars['command']);
702                    $label = rcube_label($attrib + array('vars' => $vars));
703                    return !$attrib['noshow'] ? (get_boolean((string)$attrib['html']) ? $label : Q($label)) : '';
704                }
705                break;
706
707            // include a file
708            case 'include':
709                if (!$this->plugin_skin_path || !is_file($path = realpath($this->plugin_skin_path . $attrib['file'])))
710                    $path = realpath(($attrib['skin_path'] ? $attrib['skin_path'] : $this->config['skin_path']).$attrib['file']);
711               
712                if (is_readable($path)) {
713                    if ($this->config['skin_include_php']) {
714                        $incl = $this->include_php($path);
715                    }
716                    else {
717                      $incl = file_get_contents($path);
718                    }
719                    $incl = $this->parse_conditions($incl);
720                    return $this->parse_xml($incl);
721                }
722                break;
723
724            case 'plugin.include':
725                $hook = $this->app->plugins->exec_hook("template_plugin_include", $attrib);
726                return $hook['content'];
727                break;
728
729            // define a container block
730            case 'container':
731                if ($attrib['name'] && $attrib['id']) {
732                    $this->command('gui_container', $attrib['name'], $attrib['id']);
733                    // let plugins insert some content here
734                    $hook = $this->app->plugins->exec_hook("template_container", $attrib);
735                    return $hook['content'];
736                }
737                break;
738
739            // return code for a specific application object
740            case 'object':
741                $object = strtolower($attrib['name']);
742                $content = '';
743
744                // we are calling a class/method
745                if (($handler = $this->object_handlers[$object]) && is_array($handler)) {
746                    if ((is_object($handler[0]) && method_exists($handler[0], $handler[1])) ||
747                    (is_string($handler[0]) && class_exists($handler[0])))
748                    $content = call_user_func($handler, $attrib);
749                }
750                // execute object handler function
751                else if (function_exists($handler)) {
752                    $content = call_user_func($handler, $attrib);
753                }
754                else if ($object == 'doctype') {
755                    $content = html::doctype($attrib['value']);
756                }
757                else if ($object == 'logo') {
758                    $attrib += array('alt' => $this->xml_command(array('', 'object', 'name="productname"')));
759                    if ($this->config['skin_logo'])
760                        $attrib['src'] = $this->config['skin_logo'];
761                    $content = html::img($attrib);
762                }
763                else if ($object == 'productname') {
764                    $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'Roundcube Webmail';
765                    $content = Q($name);
766                }
767                else if ($object == 'version') {
768                    $ver = (string)RCMAIL_VERSION;
769                    if (is_file(INSTALL_PATH . '.svn/entries')) {
770                        if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
771                          $ver .= ' [SVN r'.$regs[1].']';
772                    }
773                    $content = Q($ver);
774                }
775                else if ($object == 'steptitle') {
776                  $content = Q($this->get_pagetitle());
777                }
778                else if ($object == 'pagetitle') {
779                    if (!empty($this->config['devel_mode']) && !empty($_SESSION['username']))
780                      $title = $_SESSION['username'].' :: ';
781                    else if (!empty($this->config['product_name']))
782                      $title = $this->config['product_name'].' :: ';
783                    else
784                      $title = '';
785                    $title .= $this->get_pagetitle();
786                    $content = Q($title);
787                }
788
789                // exec plugin hooks for this template object
790                $hook = $this->app->plugins->exec_hook("template_object_$object", $attrib + array('content' => $content));
791                return $hook['content'];
792
793            // return code for a specified eval expression
794            case 'exp':
795                $value = $this->parse_expression($attrib['expression']);
796                return eval("return Q($value);");
797
798            // return variable
799            case 'var':
800                $var = explode(':', $attrib['name']);
801                $name = $var[1];
802                $value = '';
803
804                switch ($var[0]) {
805                    case 'env':
806                        $value = $this->env[$name];
807                        break;
808                    case 'config':
809                        $value = $this->config[$name];
810                        if (is_array($value) && $value[$_SESSION['storage_host']]) {
811                            $value = $value[$_SESSION['storage_host']];
812                        }
813                        break;
814                    case 'request':
815                        $value = get_input_value($name, RCUBE_INPUT_GPC);
816                        break;
817                    case 'session':
818                        $value = $_SESSION[$name];
819                        break;
820                    case 'cookie':
821                        $value = htmlspecialchars($_COOKIE[$name]);
822                        break;
823                    case 'browser':
824                        $value = $this->browser->{$name};
825                        break;
826                }
827
828                if (is_array($value)) {
829                    $value = implode(', ', $value);
830                }
831
832                return Q($value);
833                break;
834        }
835        return '';
836    }
837
838    /**
839     * Include a specific file and return it's contents
840     *
841     * @param string File path
842     * @return string Contents of the processed file
843     */
844    private function include_php($file)
845    {
846        ob_start();
847        include $file;
848        $out = ob_get_contents();
849        ob_end_clean();
850
851        return $out;
852    }
853
854    /**
855     * Create and register a button
856     *
857     * @param  array Named button attributes
858     * @return string HTML button
859     * @todo   Remove all inline JS calls and use jQuery instead.
860     * @todo   Remove all sprintf()'s - they are pretty, but also slow.
861     */
862    public function button($attrib)
863    {
864        static $s_button_count = 100;
865
866        // these commands can be called directly via url
867        $a_static_commands = array('compose', 'list', 'preferences', 'folders', 'identities');
868
869        if (!($attrib['command'] || $attrib['name'])) {
870            return '';
871        }
872
873        // try to find out the button type
874        if ($attrib['type']) {
875            $attrib['type'] = strtolower($attrib['type']);
876        }
877        else {
878            $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
879        }
880
881        $command = $attrib['command'];
882
883        if ($attrib['task'])
884          $command = $attrib['task'] . '.' . $command;
885
886        if (!$attrib['image']) {
887            $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
888        }
889
890        if (!$attrib['id']) {
891            $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
892        }
893        // get localized text for labels and titles
894        if ($attrib['title']) {
895            $attrib['title'] = Q(rcube_label($attrib['title'], $attrib['domain']));
896        }
897        if ($attrib['label']) {
898            $attrib['label'] = Q(rcube_label($attrib['label'], $attrib['domain']));
899        }
900        if ($attrib['alt']) {
901            $attrib['alt'] = Q(rcube_label($attrib['alt'], $attrib['domain']));
902        }
903
904        // set title to alt attribute for IE browsers
905        if ($this->browser->ie && !$attrib['title'] && $attrib['alt']) {
906            $attrib['title'] = $attrib['alt'];
907        }
908
909        // add empty alt attribute for XHTML compatibility
910        if (!isset($attrib['alt'])) {
911            $attrib['alt'] = '';
912        }
913
914        // register button in the system
915        if ($attrib['command']) {
916            $this->add_script(sprintf(
917                "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
918                JS_OBJECT_NAME,
919                $command,
920                $attrib['id'],
921                $attrib['type'],
922                $attrib['imageact'] ? $this->abs_url($attrib['imageact']) : $attrib['classact'],
923                $attrib['imagesel'] ? $this->abs_url($attrib['imagesel']) : $attrib['classsel'],
924                $attrib['imageover'] ? $this->abs_url($attrib['imageover']) : ''
925            ));
926
927            // make valid href to specific buttons
928            if (in_array($attrib['command'], rcmail::$main_tasks)) {
929                $attrib['href'] = rcmail_url(null, null, $attrib['command']);
930                $attrib['onclick'] = sprintf("%s.switch_task('%s');return false", JS_OBJECT_NAME, $attrib['command']);
931            }
932            else if ($attrib['task'] && in_array($attrib['task'], rcmail::$main_tasks)) {
933                $attrib['href'] = rcmail_url($attrib['command'], null, $attrib['task']);
934            }
935            else if (in_array($attrib['command'], $a_static_commands)) {
936                $attrib['href'] = rcmail_url($attrib['command']);
937            }
938            else if ($attrib['command'] == 'permaurl' && !empty($this->env['permaurl'])) {
939              $attrib['href'] = $this->env['permaurl'];
940            }
941        }
942
943        // overwrite attributes
944        if (!$attrib['href']) {
945            $attrib['href'] = '#';
946        }
947        if ($attrib['task']) {
948            if ($attrib['classact'])
949                $attrib['class'] = $attrib['classact'];
950        }
951        else if ($command && !$attrib['onclick']) {
952            $attrib['onclick'] = sprintf(
953                "return %s.command('%s','%s',this)",
954                JS_OBJECT_NAME,
955                $command,
956                $attrib['prop']
957            );
958        }
959
960        $out = '';
961
962        // generate image tag
963        if ($attrib['type']=='image') {
964            $attrib_str = html::attrib_string(
965                $attrib,
966                array(
967                    'style', 'class', 'id', 'width', 'height', 'border', 'hspace',
968                    'vspace', 'align', 'alt', 'tabindex', 'title'
969                )
970            );
971            $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
972            if ($attrib['label']) {
973                $btn_content .= ' '.$attrib['label'];
974            }
975            $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'target');
976        }
977        else if ($attrib['type']=='link') {
978            $btn_content = isset($attrib['content']) ? $attrib['content'] : ($attrib['label'] ? $attrib['label'] : $attrib['command']);
979            $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style', 'tabindex', 'target');
980            if ($attrib['innerclass'])
981                $btn_content = html::span($attrib['innerclass'], $btn_content);
982        }
983        else if ($attrib['type']=='input') {
984            $attrib['type'] = 'button';
985
986            if ($attrib['label']) {
987                $attrib['value'] = $attrib['label'];
988            }
989            if ($attrib['command']) {
990              $attrib['disabled'] = 'disabled';
991            }
992
993            $out = html::tag('input', $attrib, '', array('type', 'value', 'onclick', 'id', 'class', 'style', 'tabindex', 'disabled'));
994        }
995
996        // generate html code for button
997        if ($btn_content) {
998            $attrib_str = html::attrib_string($attrib, $link_attrib);
999            $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1000        }
1001
1002        return $out;
1003    }
1004
1005
1006    /*  ************* common functions delivering gui objects **************  */
1007
1008
1009    /**
1010     * Create a form tag with the necessary hidden fields
1011     *
1012     * @param array Named tag parameters
1013     * @return string HTML code for the form
1014     */
1015    public function form_tag($attrib, $content = null)
1016    {
1017      if ($this->framed || !empty($_REQUEST['_framed'])) {
1018        $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
1019        $hidden = $hiddenfield->show();
1020      }
1021
1022      if (!$content)
1023        $attrib['noclose'] = true;
1024
1025      return html::tag('form',
1026        $attrib + array('action' => "./", 'method' => "get"),
1027        $hidden . $content,
1028        array('id','class','style','name','method','action','enctype','onsubmit'));
1029    }
1030
1031
1032    /**
1033     * Build a form tag with a unique request token
1034     *
1035     * @param array Named tag parameters including 'action' and 'task' values which will be put into hidden fields
1036     * @param string Form content
1037     * @return string HTML code for the form
1038     */
1039    public function request_form($attrib, $content = '')
1040    {
1041        $hidden = new html_hiddenfield();
1042        if ($attrib['task']) {
1043            $hidden->add(array('name' => '_task', 'value' => $attrib['task']));
1044        }
1045        if ($attrib['action']) {
1046            $hidden->add(array('name' => '_action', 'value' => $attrib['action']));
1047        }
1048
1049        unset($attrib['task'], $attrib['request']);
1050        $attrib['action'] = './';
1051
1052        // we already have a <form> tag
1053        if ($attrib['form']) {
1054            if ($this->framed || !empty($_REQUEST['_framed']))
1055                $hidden->add(array('name' => '_framed', 'value' => '1'));
1056            return $hidden->show() . $content;
1057        }
1058        else
1059            return $this->form_tag($attrib, $hidden->show() . $content);
1060    }
1061
1062
1063    /**
1064     * GUI object 'username'
1065     * Showing IMAP username of the current session
1066     *
1067     * @param array Named tag parameters (currently not used)
1068     * @return string HTML code for the gui object
1069     */
1070    public function current_username($attrib)
1071    {
1072        static $username;
1073
1074        // alread fetched
1075        if (!empty($username)) {
1076            return $username;
1077        }
1078
1079        // Current username is an e-mail address
1080        if (strpos($_SESSION['username'], '@')) {
1081            $username = $_SESSION['username'];
1082        }
1083        // get e-mail address from default identity
1084        else if ($sql_arr = $this->app->user->get_identity()) {
1085            $username = $sql_arr['email'];
1086        }
1087        else {
1088            $username = $this->app->user->get_username();
1089        }
1090
1091        return rcube_idn_to_utf8($username);
1092    }
1093
1094
1095    /**
1096     * GUI object 'loginform'
1097     * Returns code for the webmail login form
1098     *
1099     * @param array Named parameters
1100     * @return string HTML code for the gui object
1101     */
1102    private function login_form($attrib)
1103    {
1104        $default_host = $this->config['default_host'];
1105        $autocomplete = (int) $this->config['login_autocomplete'];
1106
1107        $_SESSION['temp'] = true;
1108
1109        // save original url
1110        $url = get_input_value('_url', RCUBE_INPUT_POST);
1111        if (empty($url) && !preg_match('/_(task|action)=logout/', $_SERVER['QUERY_STRING']))
1112            $url = $_SERVER['QUERY_STRING'];
1113
1114        // set atocomplete attribute
1115        $user_attrib = $autocomplete > 0 ? array() : array('autocomplete' => 'off');
1116        $host_attrib = $autocomplete > 0 ? array() : array('autocomplete' => 'off');
1117        $pass_attrib = $autocomplete > 1 ? array() : array('autocomplete' => 'off');
1118
1119        $input_task   = new html_hiddenfield(array('name' => '_task', 'value' => 'login'));
1120        $input_action = new html_hiddenfield(array('name' => '_action', 'value' => 'login'));
1121        $input_tzone  = new html_hiddenfield(array('name' => '_timezone', 'id' => 'rcmlogintz', 'value' => '_default_'));
1122        $input_dst    = new html_hiddenfield(array('name' => '_dstactive', 'id' => 'rcmlogindst', 'value' => '_default_'));
1123        $input_url    = new html_hiddenfield(array('name' => '_url', 'id' => 'rcmloginurl', 'value' => $url));
1124        $input_user   = new html_inputfield(array('name' => '_user', 'id' => 'rcmloginuser')
1125            + $attrib + $user_attrib);
1126        $input_pass   = new html_passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd')
1127            + $attrib + $pass_attrib);
1128        $input_host   = null;
1129
1130        if (is_array($default_host) && count($default_host) > 1) {
1131            $input_host = new html_select(array('name' => '_host', 'id' => 'rcmloginhost'));
1132
1133            foreach ($default_host as $key => $value) {
1134                if (!is_array($value)) {
1135                    $input_host->add($value, (is_numeric($key) ? $value : $key));
1136                }
1137                else {
1138                    $input_host = null;
1139                    break;
1140                }
1141            }
1142        }
1143        else if (is_array($default_host) && ($host = array_pop($default_host))) {
1144            $hide_host = true;
1145            $input_host = new html_hiddenfield(array(
1146                'name' => '_host', 'id' => 'rcmloginhost', 'value' => $host) + $attrib);
1147        }
1148        else if (empty($default_host)) {
1149            $input_host = new html_inputfield(array('name' => '_host', 'id' => 'rcmloginhost')
1150                + $attrib + $host_attrib);
1151        }
1152
1153        $form_name  = !empty($attrib['form']) ? $attrib['form'] : 'form';
1154        $this->add_gui_object('loginform', $form_name);
1155
1156        // create HTML table with two cols
1157        $table = new html_table(array('cols' => 2));
1158
1159        $table->add('title', html::label('rcmloginuser', Q(rcube_label('username'))));
1160        $table->add('input', $input_user->show(get_input_value('_user', RCUBE_INPUT_GPC)));
1161
1162        $table->add('title', html::label('rcmloginpwd', Q(rcube_label('password'))));
1163        $table->add('input', $input_pass->show());
1164
1165        // add host selection row
1166        if (is_object($input_host) && !$hide_host) {
1167            $table->add('title', html::label('rcmloginhost', Q(rcube_label('server'))));
1168            $table->add('input', $input_host->show(get_input_value('_host', RCUBE_INPUT_GPC)));
1169        }
1170
1171        $out  = $input_task->show();
1172        $out .= $input_action->show();
1173        $out .= $input_tzone->show();
1174        $out .= $input_dst->show();
1175        $out .= $input_url->show();
1176        $out .= $table->show();
1177
1178        if ($hide_host) {
1179            $out .= $input_host->show();
1180        }
1181
1182        // surround html output with a form tag
1183        if (empty($attrib['form'])) {
1184            $out = $this->form_tag(array('name' => $form_name, 'method' => 'post'), $out);
1185        }
1186
1187        return $out;
1188    }
1189
1190
1191    /**
1192     * GUI object 'preloader'
1193     * Loads javascript code for images preloading
1194     *
1195     * @param array Named parameters
1196     * @return void
1197     */
1198    private function preloader($attrib)
1199    {
1200        $images = preg_split('/[\s\t\n,]+/', $attrib['images'], -1, PREG_SPLIT_NO_EMPTY);
1201        $images = array_map(array($this, 'abs_url'), $images);
1202
1203        if (empty($images) || $this->app->task == 'logout')
1204            return;
1205
1206        $this->add_script('var images = ' . json_serialize($images) .';
1207            for (var i=0; i<images.length; i++) {
1208                img = new Image();
1209                img.src = images[i];
1210            }', 'docready');
1211    }
1212
1213
1214    /**
1215     * GUI object 'searchform'
1216     * Returns code for search function
1217     *
1218     * @param array Named parameters
1219     * @return string HTML code for the gui object
1220     */
1221    private function search_form($attrib)
1222    {
1223        // add some labels to client
1224        $this->add_label('searching');
1225
1226        $attrib['name'] = '_q';
1227
1228        if (empty($attrib['id'])) {
1229            $attrib['id'] = 'rcmqsearchbox';
1230        }
1231        if ($attrib['type'] == 'search' && !$this->browser->khtml) {
1232            unset($attrib['type'], $attrib['results']);
1233        }
1234
1235        $input_q = new html_inputfield($attrib);
1236        $out = $input_q->show();
1237
1238        $this->add_gui_object('qsearchbox', $attrib['id']);
1239
1240        // add form tag around text field
1241        if (empty($attrib['form'])) {
1242            $out = $this->form_tag(array(
1243                'name' => "rcmqsearchform",
1244                'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
1245                'style' => "display:inline"),
1246                $out);
1247        }
1248
1249        return $out;
1250    }
1251
1252
1253    /**
1254     * Builder for GUI object 'message'
1255     *
1256     * @param array Named tag parameters
1257     * @return string HTML code for the gui object
1258     */
1259    private function message_container($attrib)
1260    {
1261        if (isset($attrib['id']) === false) {
1262            $attrib['id'] = 'rcmMessageContainer';
1263        }
1264
1265        $this->add_gui_object('message', $attrib['id']);
1266        return html::div($attrib, "");
1267    }
1268
1269
1270    /**
1271     * GUI object 'charsetselector'
1272     *
1273     * @param array Named parameters for the select tag
1274     * @return string HTML code for the gui object
1275     */
1276    function charset_selector($attrib)
1277    {
1278        // pass the following attributes to the form class
1279        $field_attrib = array('name' => '_charset');
1280        foreach ($attrib as $attr => $value) {
1281            if (in_array($attr, array('id', 'name', 'class', 'style', 'size', 'tabindex'))) {
1282                $field_attrib[$attr] = $value;
1283            }
1284        }
1285
1286        $charsets = array(
1287            'UTF-8'        => 'UTF-8 ('.rcube_label('unicode').')',
1288            'US-ASCII'     => 'ASCII ('.rcube_label('english').')',
1289            'ISO-8859-1'   => 'ISO-8859-1 ('.rcube_label('westerneuropean').')',
1290            'ISO-8859-2'   => 'ISO-8859-2 ('.rcube_label('easterneuropean').')',
1291            'ISO-8859-4'   => 'ISO-8859-4 ('.rcube_label('baltic').')',
1292            'ISO-8859-5'   => 'ISO-8859-5 ('.rcube_label('cyrillic').')',
1293            'ISO-8859-6'   => 'ISO-8859-6 ('.rcube_label('arabic').')',
1294            'ISO-8859-7'   => 'ISO-8859-7 ('.rcube_label('greek').')',
1295            'ISO-8859-8'   => 'ISO-8859-8 ('.rcube_label('hebrew').')',
1296            'ISO-8859-9'   => 'ISO-8859-9 ('.rcube_label('turkish').')',
1297            'ISO-8859-10'   => 'ISO-8859-10 ('.rcube_label('nordic').')',
1298            'ISO-8859-11'   => 'ISO-8859-11 ('.rcube_label('thai').')',
1299            'ISO-8859-13'   => 'ISO-8859-13 ('.rcube_label('baltic').')',
1300            'ISO-8859-14'   => 'ISO-8859-14 ('.rcube_label('celtic').')',
1301            'ISO-8859-15'   => 'ISO-8859-15 ('.rcube_label('westerneuropean').')',
1302            'ISO-8859-16'   => 'ISO-8859-16 ('.rcube_label('southeasterneuropean').')',
1303            'WINDOWS-1250' => 'Windows-1250 ('.rcube_label('easterneuropean').')',
1304            'WINDOWS-1251' => 'Windows-1251 ('.rcube_label('cyrillic').')',
1305            'WINDOWS-1252' => 'Windows-1252 ('.rcube_label('westerneuropean').')',
1306            'WINDOWS-1253' => 'Windows-1253 ('.rcube_label('greek').')',
1307            'WINDOWS-1254' => 'Windows-1254 ('.rcube_label('turkish').')',
1308            'WINDOWS-1255' => 'Windows-1255 ('.rcube_label('hebrew').')',
1309            'WINDOWS-1256' => 'Windows-1256 ('.rcube_label('arabic').')',
1310            'WINDOWS-1257' => 'Windows-1257 ('.rcube_label('baltic').')',
1311            'WINDOWS-1258' => 'Windows-1258 ('.rcube_label('vietnamese').')',
1312            'ISO-2022-JP'  => 'ISO-2022-JP ('.rcube_label('japanese').')',
1313            'ISO-2022-KR'  => 'ISO-2022-KR ('.rcube_label('korean').')',
1314            'ISO-2022-CN'  => 'ISO-2022-CN ('.rcube_label('chinese').')',
1315            'EUC-JP'       => 'EUC-JP ('.rcube_label('japanese').')',
1316            'EUC-KR'       => 'EUC-KR ('.rcube_label('korean').')',
1317            'EUC-CN'       => 'EUC-CN ('.rcube_label('chinese').')',
1318            'BIG5'         => 'BIG5 ('.rcube_label('chinese').')',
1319            'GB2312'       => 'GB2312 ('.rcube_label('chinese').')',
1320        );
1321
1322        if (!empty($_POST['_charset']))
1323                $set = $_POST['_charset'];
1324            else if (!empty($attrib['selected']))
1325                $set = $attrib['selected'];
1326            else
1327                $set = $this->get_charset();
1328
1329            $set = strtoupper($set);
1330            if (!isset($charsets[$set]))
1331                $charsets[$set] = $set;
1332
1333        $select = new html_select($field_attrib);
1334        $select->add(array_values($charsets), array_keys($charsets));
1335
1336        return $select->show($set);
1337    }
1338
1339    /**
1340     * Include content from config/about.<LANG>.html if available
1341     */
1342    private function about_content($attrib)
1343    {
1344        $content = '';
1345        $filenames = array(
1346            'about.' . $_SESSION['language'] . '.html',
1347            'about.' . substr($_SESSION['language'], 0, 2) . '.html',
1348            'about.html',
1349        );
1350        foreach ($filenames as $file) {
1351            $fn = RCMAIL_CONFIG_DIR . '/' . $file;
1352            if (is_readable($fn)) {
1353                $content = file_get_contents($fn);
1354                $content = $this->parse_conditions($content);
1355                $content = $this->parse_xml($content);
1356                break;
1357            }
1358        }
1359
1360        return $content;
1361    }
1362
1363}  // end class rcube_template
1364
1365
Note: See TracBrowser for help on using the repository browser.