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

Last change on this file since 1796 was 1796, checked in by thomasb, 5 years ago

Redesign of the identities settings + add config option to disable multiple identities

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