source: subversion/branches/devel-api/program/include/rcube_template.php @ 2285

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

Allow plugins to add stylesheets + use common event interface with event 'init' to start plugin scripts

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