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

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