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

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