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

Last change on this file since 2519 was 2519, checked in by thomasb, 4 years ago

Fix URLs to plugin skin directory

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