source: github/program/include/rcube_template.php @ 57f0c81

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 57f0c81 was 57f0c81, checked in by thomascube <thomas@…>, 4 years ago

Use request tokens to protect POST requests from CSFR

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