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

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

Add link to open message in new window + tweaked some header styles

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