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

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