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

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