source: github/program/include/rcube_template.php @ c9e9fe1

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since c9e9fe1 was c9e9fe1, checked in by alecpl <alec@…>, 4 years ago
  • Property mode set to 100755
File size: 38.9 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 ($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
333        // call super method
334        parent::write($template, $this->config['skin_path']);
335    }
336
337    /**
338     * Parse a specific skin template and deliver to stdout
339     *
340     * Either returns nothing, or exists hard (exit();)
341     *
342     * @param  string  Template name
343     * @param  boolean Exit script
344     * @return void
345     * @link   http://php.net/manual/en/function.exit.php
346     */
347    private function parse($name = 'main', $exit = true)
348    {
349        $skin_path = $this->config['skin_path'];
350        $plugin = false;
351       
352        $temp = explode(".", $name, 2);
353        if (count($temp) > 1) {
354            $plugin = $temp[0];
355            $name = $temp[1];
356            $skin_dir = $plugin . '/skins/' . $this->config['skin'];
357            $skin_path = $this->app->plugins->dir . $skin_dir;
358            if (!is_dir($skin_path)) {  // fallback to default skin
359                $skin_dir = $plugin . '/skins/default';
360                $skin_path = $this->app->plugins->dir . $skin_dir;
361            }
362        }
363       
364        $path = "$skin_path/templates/$name.html";
365
366        // read template file
367        if (($templ = @file_get_contents($path)) === false) {
368            raise_error(array(
369                'code' => 501,
370                'type' => 'php',
371                'line' => __LINE__,
372                'file' => __FILE__,
373                'message' => 'Error loading template for '.$name
374                ), true, true);
375            return false;
376        }
377       
378        // replace all path references to plugins/... with the configured plugins dir
379        // and /this/ to the current plugin skin directory
380        if ($plugin) {
381            $templ = preg_replace(array('/\bplugins\//', '/(["\']?)\/this\//'), array($this->app->plugins->url, '\\1'.$this->app->plugins->url.$skin_dir.'/'), $templ);
382        }
383
384        // parse for specialtags
385        $output = $this->parse_conditions($templ);
386        $output = $this->parse_xml($output);
387       
388        // trigger generic hook where plugins can put additional content to the page
389        $hook = $this->app->plugins->exec_hook("render_page", array('template' => $name, 'content' => $output));
390
391        // add debug console
392        if ($this->config['debug_level'] & 8) {
393            $this->add_footer('<div id="console" style="position:absolute;top:5px;left:5px;width:405px;padding:2px;background:white;z-index:9000;">
394                <a href="#toggle" onclick="con=document.getElementById(\'dbgconsole\');con.style.display=(con.style.display==\'none\'?\'block\':\'none\');return false">console</a>
395                <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>'
396            );
397        }
398       
399        $output = $this->parse_with_globals($hook['content']);
400        $this->write(trim($output));
401        if ($exit) {
402            exit;
403        }
404    }
405
406
407    /**
408     * Return executable javascript code for all registered commands
409     *
410     * @return string $out
411     */
412    private function get_js_commands()
413    {
414        $out = '';
415        if (!$this->framed && !empty($this->js_env)) {
416            $out .= JS_OBJECT_NAME . '.set_env('.json_serialize($this->js_env).");\n";
417        }
418        foreach ($this->js_commands as $i => $args) {
419            $method = array_shift($args);
420            foreach ($args as $i => $arg) {
421                $args[$i] = json_serialize($arg);
422            }
423            $parent = $this->framed || preg_match('/^parent\./', $method);
424            $out .= sprintf(
425                "%s.%s(%s);\n",
426                ($parent ? 'if(window.parent && parent.'.JS_OBJECT_NAME.') parent.' : '') . JS_OBJECT_NAME,
427                preg_replace('/^parent\./', '', $method),
428                implode(',', $args)
429            );
430        }
431       
432        return $out;
433    }
434
435    /**
436     * Make URLs starting with a slash point to skin directory
437     *
438     * @param  string Input string
439     * @return string
440     */
441    public function abs_url($str)
442    {
443        return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
444    }
445
446
447    /*****  Template parsing methods  *****/
448
449    /**
450     * Replace all strings ($varname)
451     * with the content of the according global variable.
452     */
453    private function parse_with_globals($input)
454    {
455        $GLOBALS['__version'] = Q(RCMAIL_VERSION);
456        $GLOBALS['__comm_path'] = Q($this->app->comm_path);
457        return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
458    }
459
460    /**
461     * Public wrapper to dipp into template parsing.
462     *
463     * @param  string $input
464     * @return string
465     * @uses   rcube_template::parse_xml()
466     * @since  0.1-rc1
467     */
468    public function just_parse($input)
469    {
470        return $this->parse_xml($input);
471    }
472
473    /**
474     * Parse for conditional tags
475     *
476     * @param  string $input
477     * @return string
478     */
479    private function parse_conditions($input)
480    {
481        $matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE);
482        if ($matches && count($matches) == 4) {
483            if (preg_match('/^(else|endif)$/i', $matches[1])) {
484                return $matches[0] . $this->parse_conditions($matches[3]);
485            }
486            $attrib = parse_attrib_string($matches[2]);
487            if (isset($attrib['condition'])) {
488                $condmet = $this->check_condition($attrib['condition']);
489                $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
490                if ($condmet) {
491                    $result = $submatches[0];
492                    $result.= ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>/Uis', '', $submatches[3], 1) : $submatches[3]);
493                }
494                else {
495                    $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
496                }
497                return $matches[0] . $this->parse_conditions($result);
498            }
499            raise_error(array(
500                'code' => 500,
501                'type' => 'php',
502                'line' => __LINE__,
503                'file' => __FILE__,
504                'message' => "Unable to parse conditional tag " . $matches[2]
505            ), true, false);
506        }
507        return $input;
508    }
509
510
511    /**
512     * Determines if a given condition is met
513     *
514     * @todo   Get rid off eval() once I understand what this does.
515     * @todo   Extend this to allow real conditions, not just "set"
516     * @param  string Condition statement
517     * @return boolean True if condition is met, False if not
518     */
519    private function check_condition($condition)
520    {
521        return eval("return (".$this->parse_expression($condition).");");
522    }
523   
524   
525    /**
526     *
527     */
528    private function alter_form_tag($matches)
529    {
530        $out = $matches[0];
531        $attrib  = parse_attrib_string($matches[1]);
532     
533        if (strtolower($attrib['method']) == 'post') {
534            $hidden = new html_hiddenfield(array('name' => '_token', 'value' => $this->app->get_request_token()));
535            $out .= "\n" . $hidden->show();
536        }
537     
538        return $out;
539    }
540
541
542    /**
543     * Parses expression and replaces variables
544     *
545     * @param  string Expression statement
546     * @return string Expression statement
547     */
548    private function parse_expression($expression)
549    {
550        return preg_replace(
551            array(
552                '/session:([a-z0-9_]+)/i',
553                '/config:([a-z0-9_]+)(:([a-z0-9_]+))?/i',
554                '/env:([a-z0-9_]+)/i',
555                '/request:([a-z0-9_]+)/i',
556                '/cookie:([a-z0-9_]+)/i',
557                '/browser:([a-z0-9_]+)/i'
558            ),
559            array(
560                "\$_SESSION['\\1']",
561                "\$this->app->config->get('\\1',get_boolean('\\3'))",
562                "\$this->env['\\1']",
563                "get_input_value('\\1', RCUBE_INPUT_GPC)",
564                "\$_COOKIE['\\1']",
565                "\$this->browser->{'\\1'}"
566            ),
567            $expression);
568    }
569
570
571    /**
572     * Search for special tags in input and replace them
573     * with the appropriate content
574     *
575     * @param  string Input string to parse
576     * @return string Altered input string
577     * @todo   Use DOM-parser to traverse template HTML
578     * @todo   Maybe a cache.
579     */
580    private function parse_xml($input)
581    {
582        return preg_replace_callback('/<roundcube:([-_a-z]+)\s+([^>]+)>/Ui', array($this, 'xml_command'), $input);
583    }
584
585
586    /**
587     * Callback function for parsing an xml command tag
588     * and turn it into real html content
589     *
590     * @param  array Matches array of preg_replace_callback
591     * @return string Tag/Object content
592     */
593    private function xml_command($matches)
594    {
595        $command = strtolower($matches[1]);
596        $attrib  = parse_attrib_string($matches[2]);
597
598        // empty output if required condition is not met
599        if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
600            return '';
601        }
602
603        // execute command
604        switch ($command) {
605            // return a button
606            case 'button':
607                if ($attrib['name'] || $attrib['command']) {
608                    return $this->button($attrib);
609                }
610                break;
611
612            // show a label
613            case 'label':
614                if ($attrib['name'] || $attrib['command']) {
615                    return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
616                }
617                break;
618
619            // include a file
620            case 'include':
621                $path = realpath($this->config['skin_path'].$attrib['file']);
622                if (is_readable($path)) {
623                    if ($this->config['skin_include_php']) {
624                        $incl = $this->include_php($path);
625                    }
626                    else {
627                      $incl = file_get_contents($path);
628                    }
629                    $incl = $this->parse_conditions($incl);
630                    return $this->parse_xml($incl);
631                }
632                break;
633
634            case 'plugin.include':
635                $hook = $this->app->plugins->exec_hook("template_plugin_include", $attrib);
636                return $hook['content'];
637                break;
638           
639            // define a container block
640            case 'container':
641                if ($attrib['name'] && $attrib['id']) {
642                    $this->command('gui_container', $attrib['name'], $attrib['id']);
643                    // let plugins insert some content here
644                    $hook = $this->app->plugins->exec_hook("template_container", $attrib);
645                    return $hook['content'];
646                }
647                break;
648
649            // return code for a specific application object
650            case 'object':
651                $object = strtolower($attrib['name']);
652                $content = '';
653
654                // we are calling a class/method
655                if (($handler = $this->object_handlers[$object]) && is_array($handler)) {
656                    if ((is_object($handler[0]) && method_exists($handler[0], $handler[1])) ||
657                    (is_string($handler[0]) && class_exists($handler[0])))
658                    $content = call_user_func($handler, $attrib);
659                }
660                // execute object handler function
661                else if (function_exists($handler)) {
662                    $content = call_user_func($handler, $attrib);
663                }
664                else if ($object == 'productname') {
665                    $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
666                    $content = Q($name);
667                }
668                else if ($object == 'version') {
669                    $ver = (string)RCMAIL_VERSION;
670                    if (is_file(INSTALL_PATH . '.svn/entries')) {
671                        if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
672                          $ver .= ' [SVN r'.$regs[1].']';
673                    }
674                    $content = Q($ver);
675                }
676                else if ($object == 'steptitle') {
677                  $content = Q($this->get_pagetitle());
678                }
679                else if ($object == 'pagetitle') {
680                    $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
681                    $title .= $this->get_pagetitle();
682                    $content = Q($title);
683                }
684               
685                // exec plugin hooks for this template object
686                $hook = $this->app->plugins->exec_hook("template_object_$object", $attrib + array('content' => $content));
687                return $hook['content'];
688
689            // return code for a specified eval expression
690            case 'exp':
691                $value = $this->parse_expression($attrib['expression']);
692                return eval("return Q($value);");
693           
694            // return variable
695            case 'var':
696                $var = explode(':', $attrib['name']);
697                $name = $var[1];
698                $value = '';
699
700                switch ($var[0]) {
701                    case 'env':
702                        $value = $this->env[$name];
703                        break;
704                    case 'config':
705                        $value = $this->config[$name];
706                        if (is_array($value) && $value[$_SESSION['imap_host']]) {
707                            $value = $value[$_SESSION['imap_host']];
708                        }
709                        break;
710                    case 'request':
711                        $value = get_input_value($name, RCUBE_INPUT_GPC);
712                        break;
713                    case 'session':
714                        $value = $_SESSION[$name];
715                        break;
716                    case 'cookie':
717                        $value = htmlspecialchars($_COOKIE[$name]);
718                        break;
719                    case 'browser':
720                        $value = $this->browser->{$name};
721                        break;
722                }
723
724                if (is_array($value)) {
725                    $value = implode(', ', $value);
726                }
727
728                return Q($value);
729                break;
730        }
731        return '';
732    }
733
734    /**
735     * Include a specific file and return it's contents
736     *
737     * @param string File path
738     * @return string Contents of the processed file
739     */
740    private function include_php($file)
741    {
742        ob_start();
743        include $file;
744        $out = ob_get_contents();
745        ob_end_clean();
746
747        return $out;
748    }
749
750    /**
751     * Create and register a button
752     *
753     * @param  array Named button attributes
754     * @return string HTML button
755     * @todo   Remove all inline JS calls and use jQuery instead.
756     * @todo   Remove all sprintf()'s - they are pretty, but also slow.
757     */
758    public function button($attrib)
759    {
760        static $sa_buttons = array();
761        static $s_button_count = 100;
762
763        // these commands can be called directly via url
764        $a_static_commands = array('compose', 'list', 'preferences', 'folders', 'identities');
765
766        if (!($attrib['command'] || $attrib['name'])) {
767            return '';
768        }
769
770        // try to find out the button type
771        if ($attrib['type']) {
772            $attrib['type'] = strtolower($attrib['type']);
773        }
774        else {
775            $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
776        }
777        $command = $attrib['command'];
778
779        // take the button from the stack
780        if ($attrib['name'] && $sa_buttons[$attrib['name']]) {
781            $attrib = $sa_buttons[$attrib['name']];
782        }
783        else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class']) {
784            // add button to button stack
785            if (!$attrib['name']) {
786                $attrib['name'] = $command;
787            }
788            if (!$attrib['image']) {
789                $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
790            }
791            $sa_buttons[$attrib['name']] = $attrib;
792        }
793        else if ($command && $sa_buttons[$command]) {
794            // get saved button for this command/name
795            $attrib = $sa_buttons[$command];
796        }
797
798        if (!$attrib['id']) {
799            $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
800        }
801        // get localized text for labels and titles
802        if ($attrib['title']) {
803            $attrib['title'] = Q(rcube_label($attrib['title'], $attrib['domain']));
804        }
805        if ($attrib['label']) {
806            $attrib['label'] = Q(rcube_label($attrib['label'], $attrib['domain']));
807        }
808        if ($attrib['alt']) {
809            $attrib['alt'] = Q(rcube_label($attrib['alt'], $attrib['domain']));
810        }
811
812        // set title to alt attribute for IE browsers
813        if ($this->browser->ie && !$attrib['title'] && $attrib['alt']) {
814            $attrib['title'] = $attrib['alt'];
815        }
816
817        // add empty alt attribute for XHTML compatibility
818        if (!isset($attrib['alt'])) {
819            $attrib['alt'] = '';
820        }
821
822        // register button in the system
823        if ($attrib['command']) {
824            $this->add_script(sprintf(
825                "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
826                JS_OBJECT_NAME,
827                $command,
828                $attrib['id'],
829                $attrib['type'],
830                $attrib['imageact'] ? $this->abs_url($attrib['imageact']) : $attrib['classact'],
831                $attrib['imagesel'] ? $this->abs_url($attrib['imagesel']) : $attrib['classsel'],
832                $attrib['imageover'] ? $this->abs_url($attrib['imageover']) : ''
833            ));
834
835            // make valid href to specific buttons
836            if (in_array($attrib['command'], rcmail::$main_tasks)) {
837                $attrib['href'] = rcmail_url(null, null, $attrib['command']);
838            }
839            else if (in_array($attrib['command'], $a_static_commands)) {
840                $attrib['href'] = rcmail_url($attrib['command']);
841            }
842            else if ($attrib['command'] == 'permaurl' && !empty($this->env['permaurl'])) {
843                $attrib['href'] = $this->env['permaurl'];
844            }
845        }
846
847        // overwrite attributes
848        if (!$attrib['href']) {
849            $attrib['href'] = '#';
850        }
851        if ($command) {
852            $attrib['onclick'] = sprintf(
853                "return %s.command('%s','%s',this)",
854                JS_OBJECT_NAME,
855                $command,
856                $attrib['prop']
857            );
858        }
859        if ($command && $attrib['imageover']) {
860            $attrib['onmouseover'] = sprintf(
861                "return %s.button_over('%s','%s')",
862                JS_OBJECT_NAME,
863                $command,
864                $attrib['id']
865            );
866            $attrib['onmouseout'] = sprintf(
867                "return %s.button_out('%s','%s')",
868                JS_OBJECT_NAME,
869                $command,
870                $attrib['id']
871            );
872        }
873
874        if ($command && $attrib['imagesel']) {
875            $attrib['onmousedown'] = sprintf(
876                "return %s.button_sel('%s','%s')",
877                JS_OBJECT_NAME,
878                $command,
879                $attrib['id']
880            );
881            $attrib['onmouseup'] = sprintf(
882                "return %s.button_out('%s','%s')",
883                JS_OBJECT_NAME,
884                $command,
885                $attrib['id']
886            );
887        }
888
889        $out = '';
890
891        // generate image tag
892        if ($attrib['type']=='image') {
893            $attrib_str = html::attrib_string(
894                $attrib,
895                array(
896                    'style', 'class', 'id', 'width', 'height', 'border', 'hspace',
897                    'vspace', 'align', 'alt', 'tabindex', 'title'
898                )
899            );
900            $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
901            if ($attrib['label']) {
902                $btn_content .= ' '.$attrib['label'];
903            }
904            $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'target');
905        }
906        else if ($attrib['type']=='link') {
907            $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
908            $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style', 'tabindex', 'target');
909        }
910        else if ($attrib['type']=='input') {
911            $attrib['type'] = 'button';
912
913            if ($attrib['label']) {
914                $attrib['value'] = $attrib['label'];
915            }
916
917            $attrib_str = html::attrib_string(
918                $attrib,
919                array(
920                    'type', 'value', 'onclick', 'id', 'class', 'style', 'tabindex'
921                )
922            );
923            $out = sprintf('<input%s disabled="disabled" />', $attrib_str);
924        }
925
926        // generate html code for button
927        if ($btn_content) {
928            $attrib_str = html::attrib_string($attrib, $link_attrib);
929            $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
930        }
931
932        return $out;
933    }
934
935
936    /*  ************* common functions delivering gui objects **************  */
937
938
939    /**
940     * Create a form tag with the necessary hidden fields
941     *
942     * @param array Named tag parameters
943     * @return string HTML code for the form
944     */
945    public function form_tag($attrib, $content = null)
946    {
947      if ($this->framed || !empty($_REQUEST['_framed'])) {
948        $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
949        $hidden = $hiddenfield->show();
950      }
951     
952      if (!$content)
953        $attrib['noclose'] = true;
954     
955      return html::tag('form',
956        $attrib + array('action' => "./", 'method' => "get"),
957        $hidden . $content,
958        array('id','class','style','name','method','action','enctype','onsubmit'));
959    }
960   
961   
962    /**
963     * Build a form tag with a unique request token
964     *
965     * @param array Named tag parameters including 'action' and 'task' values which will be put into hidden fields
966     * @param string Form content
967     * @return string HTML code for the form
968     */
969    public function request_form($attrib, $content = '')
970    {
971        $hidden = new html_hiddenfield();
972        if ($attrib['task']) {
973            $hidden->add(array('name' => '_task', 'value' => $attrib['task']));
974        }
975        if ($attrib['action']) {
976            $hidden->add(array('name' => '_action', 'value' => $attrib['action']));
977        }
978     
979        unset($attrib['task'], $attrib['request']);
980        $attrib['action'] = './';
981     
982        // we already have a <form> tag
983        if ($attrib['form'])
984            return $hidden->show() . $content;
985        else
986            return $this->form_tag($attrib, $hidden->show() . $content);
987    }
988
989
990    /**
991     * GUI object 'username'
992     * Showing IMAP username of the current session
993     *
994     * @param array Named tag parameters (currently not used)
995     * @return string HTML code for the gui object
996     */
997    public function current_username($attrib)
998    {
999        static $username;
1000
1001        // alread fetched
1002        if (!empty($username)) {
1003            return $username;
1004        }
1005
1006        // get e-mail address form default identity
1007        if ($sql_arr = $this->app->user->get_identity()) {
1008            $username = $sql_arr['email'];
1009        }
1010        else {
1011            $username = $this->app->user->get_username();
1012        }
1013
1014        return $username;
1015    }
1016
1017
1018    /**
1019     * GUI object 'loginform'
1020     * Returns code for the webmail login form
1021     *
1022     * @param array Named parameters
1023     * @return string HTML code for the gui object
1024     */
1025    private function login_form($attrib)
1026    {
1027        $default_host = $this->config['default_host'];
1028
1029        $_SESSION['temp'] = true;
1030       
1031        // save original url
1032        $url = get_input_value('_url', RCUBE_INPUT_POST);
1033        if (empty($url) && !preg_match('/_(task|action)=logout/', $_SERVER['QUERY_STRING']))
1034            $url = $_SERVER['QUERY_STRING'];
1035
1036        $input_user   = new html_inputfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30) + $attrib);
1037        $input_pass   = new html_passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30) + $attrib);
1038        $input_action = new html_hiddenfield(array('name' => '_action', 'value' => 'login'));
1039        $input_tzone  = new html_hiddenfield(array('name' => '_timezone', 'id' => 'rcmlogintz', 'value' => '_default_'));
1040        $input_url    = new html_hiddenfield(array('name' => '_url', 'id' => 'rcmloginurl', 'value' => $url));
1041        $input_host   = null;
1042
1043        if (is_array($default_host)) {
1044            $input_host = new html_select(array('name' => '_host', 'id' => 'rcmloginhost'));
1045
1046            foreach ($default_host as $key => $value) {
1047                if (!is_array($value)) {
1048                    $input_host->add($value, (is_numeric($key) ? $value : $key));
1049                }
1050                else {
1051                    $input_host = null;
1052                    break;
1053                }
1054            }
1055        }
1056        else if (empty($default_host)) {
1057            $input_host = new html_inputfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
1058        }
1059
1060        $form_name  = !empty($attrib['form']) ? $attrib['form'] : 'form';
1061        $this->add_gui_object('loginform', $form_name);
1062
1063        // create HTML table with two cols
1064        $table = new html_table(array('cols' => 2));
1065
1066        $table->add('title', html::label('rcmloginuser', Q(rcube_label('username'))));
1067        $table->add(null, $input_user->show(get_input_value('_user', RCUBE_INPUT_POST)));
1068
1069        $table->add('title', html::label('rcmloginpwd', Q(rcube_label('password'))));
1070        $table->add(null, $input_pass->show());
1071
1072        // add host selection row
1073        if (is_object($input_host)) {
1074            $table->add('title', html::label('rcmloginhost', Q(rcube_label('server'))));
1075            $table->add(null, $input_host->show(get_input_value('_host', RCUBE_INPUT_POST)));
1076        }
1077
1078        $out = $input_action->show();
1079        $out .= $input_tzone->show();
1080        $out .= $input_url->show();
1081        $out .= $table->show();
1082
1083        // surround html output with a form tag
1084        if (empty($attrib['form'])) {
1085            $out = $this->form_tag(array('name' => $form_name, 'method' => "post"), $out);
1086        }
1087
1088        return $out;
1089    }
1090
1091
1092    /**
1093     * GUI object 'searchform'
1094     * Returns code for search function
1095     *
1096     * @param array Named parameters
1097     * @return string HTML code for the gui object
1098     */
1099    private function search_form($attrib)
1100    {
1101        // add some labels to client
1102        $this->add_label('searching');
1103
1104        $attrib['name'] = '_q';
1105
1106        if (empty($attrib['id'])) {
1107            $attrib['id'] = 'rcmqsearchbox';
1108        }
1109        if ($attrib['type'] == 'search' && !$this->browser->khtml) {
1110          unset($attrib['type'], $attrib['results']);
1111        }
1112       
1113        $input_q = new html_inputfield($attrib);
1114        $out = $input_q->show();
1115
1116        $this->add_gui_object('qsearchbox', $attrib['id']);
1117
1118        // add form tag around text field
1119        if (empty($attrib['form'])) {
1120            $out = $this->form_tag(array(
1121                'name' => "rcmqsearchform",
1122                'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
1123                'style' => "display:inline"),
1124              $out);
1125        }
1126
1127        return $out;
1128    }
1129
1130
1131    /**
1132     * Builder for GUI object 'message'
1133     *
1134     * @param array Named tag parameters
1135     * @return string HTML code for the gui object
1136     */
1137    private function message_container($attrib)
1138    {
1139        if (isset($attrib['id']) === false) {
1140            $attrib['id'] = 'rcmMessageContainer';
1141        }
1142
1143        $this->add_gui_object('message', $attrib['id']);
1144        return html::div($attrib, "");
1145    }
1146
1147
1148    /**
1149     * GUI object 'charsetselector'
1150     *
1151     * @param array Named parameters for the select tag
1152     * @return string HTML code for the gui object
1153     */
1154    static function charset_selector($attrib)
1155    {
1156        // pass the following attributes to the form class
1157        $field_attrib = array('name' => '_charset');
1158        foreach ($attrib as $attr => $value) {
1159            if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex'))) {
1160                $field_attrib[$attr] = $value;
1161            }
1162        }
1163        $charsets = array(
1164            'US-ASCII'     => 'ASCII (English)',
1165            'EUC-JP'       => 'EUC-JP (Japanese)',
1166            'EUC-KR'       => 'EUC-KR (Korean)',
1167            'BIG5'         => 'BIG5 (Chinese)',
1168            'GB2312'       => 'GB2312 (Chinese)',
1169            'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1170            'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
1171            'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1172            'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1173            'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1174            'Windows-1251' => 'Windows-1251 (Cyrillic)',
1175            'Windows-1252' => 'Windows-1252 (Western)',
1176            'Windows-1255' => 'Windows-1255 (Hebrew)',
1177            'Windows-1256' => 'Windows-1256 (Arabic)',
1178            'Windows-1257' => 'Windows-1257 (Baltic)',
1179            'UTF-8'        => 'UTF-8'
1180            );
1181
1182            $select = new html_select($field_attrib);
1183            $select->add(array_values($charsets), array_keys($charsets));
1184
1185            $set = $_POST['_charset'] ? $_POST['_charset'] : $this->get_charset();
1186            return $select->show($set);
1187    }
1188
1189}  // end class rcube_template
1190
1191
Note: See TracBrowser for help on using the repository browser.