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

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