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

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

Define containers in GUI templates + support external 'commands'

  • Property svn:executable set to *
File size: 34.8 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.2.6/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->add_script(sprintf(
583                  "%s.gui_container('%s', '%s');",
584                  JS_OBJECT_NAME,
585                  $attrib['name'],
586                  $attrib['id']));
587                break;
588
589            // return code for a specific application object
590            case 'object':
591                $object = strtolower($attrib['name']);
592
593                // we are calling a class/method
594                if (($handler = $this->object_handlers[$object]) && is_array($handler)) {
595                    if ((is_object($handler[0]) && method_exists($handler[0], $handler[1])) ||
596                    (is_string($handler[0]) && class_exists($handler[0])))
597                    return call_user_func($handler, $attrib);
598                }
599                else if (function_exists($handler)) {
600                    // execute object handler function
601                    return call_user_func($handler, $attrib);
602                }
603
604                if ($object=='productname') {
605                    $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
606                    return Q($name);
607                }
608                if ($object=='version') {
609                    $ver = (string)RCMAIL_VERSION;
610                    if (is_file(INSTALL_PATH . '.svn/entries')) {
611                        if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
612                          $ver .= ' [SVN r'.$regs[1].']';
613                    }
614                    return $ver;
615                }
616                if ($object=='steptitle') {
617                  return Q($this->get_pagetitle());
618                }
619                if ($object=='pagetitle') {
620                    $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
621                    $title .= $this->get_pagetitle();
622                    return Q($title);
623                }
624                break;
625
626            // return code for a specified eval expression
627            case 'exp':
628                $value = $this->parse_expression($attrib['expression']);
629                return eval("return Q($value);");
630           
631            // return variable
632            case 'var':
633                $var = explode(':', $attrib['name']);
634                $name = $var[1];
635                $value = '';
636
637                switch ($var[0]) {
638                    case 'env':
639                        $value = $this->env[$name];
640                        break;
641                    case 'config':
642                        $value = $this->config[$name];
643                        if (is_array($value) && $value[$_SESSION['imap_host']]) {
644                            $value = $value[$_SESSION['imap_host']];
645                        }
646                        break;
647                    case 'request':
648                        $value = get_input_value($name, RCUBE_INPUT_GPC);
649                        break;
650                    case 'session':
651                        $value = $_SESSION[$name];
652                        break;
653                    case 'cookie':
654                        $value = htmlspecialchars($_COOKIE[$name]);
655                        break;
656                }
657
658                if (is_array($value)) {
659                    $value = implode(', ', $value);
660                }
661
662                return Q($value);
663                break;
664        }
665        return '';
666    }
667
668    /**
669     * Include a specific file and return it's contents
670     *
671     * @param string File path
672     * @return string Contents of the processed file
673     */
674    private function include_php($file)
675    {
676        ob_start();
677        include $file;
678        $out = ob_get_contents();
679        ob_end_clean();
680
681        return $out;
682    }
683
684    /**
685     * Create and register a button
686     *
687     * @param  array Named button attributes
688     * @return string HTML button
689     * @todo   Remove all inline JS calls and use jQuery instead.
690     * @todo   Remove all sprintf()'s - they are pretty, but also slow.
691     */
692    public function button($attrib)
693    {
694        static $sa_buttons = array();
695        static $s_button_count = 100;
696
697        // these commands can be called directly via url
698        $a_static_commands = array('compose', 'list');
699
700        if (!($attrib['command'] || $attrib['name'])) {
701            return '';
702        }
703
704        // try to find out the button type
705        if ($attrib['type']) {
706            $attrib['type'] = strtolower($attrib['type']);
707        }
708        else {
709            $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
710        }
711        $command = $attrib['command'];
712
713        // take the button from the stack
714        if ($attrib['name'] && $sa_buttons[$attrib['name']]) {
715            $attrib = $sa_buttons[$attrib['name']];
716        }
717        else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class']) {
718            // add button to button stack
719            if (!$attrib['name']) {
720                $attrib['name'] = $command;
721            }
722            if (!$attrib['image']) {
723                $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
724            }
725            $sa_buttons[$attrib['name']] = $attrib;
726        }
727        else if ($command && $sa_buttons[$command]) {
728            // get saved button for this command/name
729            $attrib = $sa_buttons[$command];
730        }
731
732        if (!$attrib['id']) {
733            $attrib['id'] =  sprintf('rcmbtn%d', $s_button_count++);
734        }
735        // get localized text for labels and titles
736        if ($attrib['title']) {
737            $attrib['title'] = Q(rcube_label($attrib['title']));
738        }
739        if ($attrib['label']) {
740            $attrib['label'] = Q(rcube_label($attrib['label']));
741        }
742        if ($attrib['alt']) {
743            $attrib['alt'] = Q(rcube_label($attrib['alt']));
744        }
745        // set title to alt attribute for IE browsers
746        if ($this->browser->ie && $attrib['title'] && !$attrib['alt']) {
747            $attrib['alt'] = $attrib['title'];
748            unset($attrib['title']);
749        }
750
751        // add empty alt attribute for XHTML compatibility
752        if (!isset($attrib['alt'])) {
753            $attrib['alt'] = '';
754        }
755
756        // register button in the system
757        if ($attrib['command']) {
758            $this->add_script(sprintf(
759                "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
760                JS_OBJECT_NAME,
761                $command,
762                $attrib['id'],
763                $attrib['type'],
764                $attrib['imageact'] ? $this->abs_url($attrib['imageact']) : $attrib['classact'],
765                $attrib['imagesel'] ? $this->abs_url($attrib['imagesel']) : $attrib['classsel'],
766                $attrib['imageover'] ? $this->abs_url($attrib['imageover']) : ''
767            ));
768
769            // make valid href to specific buttons
770            if (in_array($attrib['command'], rcmail::$main_tasks)) {
771                $attrib['href'] = rcmail_url(null, null, $attrib['command']);
772            }
773            else if (in_array($attrib['command'], $a_static_commands)) {
774                $attrib['href'] = rcmail_url($attrib['command']);
775            }
776            else if ($attrib['command'] == 'permaurl' && !empty($this->env['permaurl'])) {
777                $attrib['href'] = $this->env['permaurl'];
778            }
779        }
780
781        // overwrite attributes
782        if (!$attrib['href']) {
783            $attrib['href'] = '#';
784        }
785        if ($command) {
786            $attrib['onclick'] = sprintf(
787                "return %s.command('%s','%s',this)",
788                JS_OBJECT_NAME,
789                $command,
790                $attrib['prop']
791            );
792        }
793        if ($command && $attrib['imageover']) {
794            $attrib['onmouseover'] = sprintf(
795                "return %s.button_over('%s','%s')",
796                JS_OBJECT_NAME,
797                $command,
798                $attrib['id']
799            );
800            $attrib['onmouseout'] = sprintf(
801                "return %s.button_out('%s','%s')",
802                JS_OBJECT_NAME,
803                $command,
804                $attrib['id']
805            );
806        }
807
808        if ($command && $attrib['imagesel']) {
809            $attrib['onmousedown'] = sprintf(
810                "return %s.button_sel('%s','%s')",
811                JS_OBJECT_NAME,
812                $command,
813                $attrib['id']
814            );
815            $attrib['onmouseup'] = sprintf(
816                "return %s.button_out('%s','%s')",
817                JS_OBJECT_NAME,
818                $command,
819                $attrib['id']
820            );
821        }
822
823        $out = '';
824
825        // generate image tag
826        if ($attrib['type']=='image') {
827            $attrib_str = html::attrib_string(
828                $attrib,
829                array(
830                    'style', 'class', 'id', 'width',
831                    'height', 'border', 'hspace',
832                    'vspace', 'align', 'alt', 'tabindex'
833                )
834            );
835            $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
836            if ($attrib['label']) {
837                $btn_content .= ' '.$attrib['label'];
838            }
839            $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title', 'target');
840        }
841        else if ($attrib['type']=='link') {
842            $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
843            $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style', 'tabindex', 'target');
844        }
845        else if ($attrib['type']=='input') {
846            $attrib['type'] = 'button';
847
848            if ($attrib['label']) {
849                $attrib['value'] = $attrib['label'];
850            }
851
852            $attrib_str = html::attrib_string(
853                $attrib,
854                array(
855                    'type', 'value', 'onclick',
856                    'id', 'class', 'style', 'tabindex'
857                )
858            );
859            $out = sprintf('<input%s disabled="disabled" />', $attrib_str);
860        }
861
862        // generate html code for button
863        if ($btn_content) {
864            $attrib_str = html::attrib_string($attrib, $link_attrib);
865            $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
866        }
867
868        return $out;
869    }
870
871
872    /*  ************* common functions delivering gui objects **************  */
873
874
875    /**
876     * Create a form tag with the necessary hidden fields
877     *
878     * @param array Named tag parameters
879     * @return string HTML code for the form
880     */
881    public function form_tag($attrib, $content = null)
882    {
883      if ($this->framed) {
884        $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
885        $hidden = $hiddenfield->show();
886      }
887     
888      if (!$content)
889        $attrib['noclose'] = true;
890     
891      return html::tag('form',
892        $attrib + array('action' => "./", 'method' => "get"),
893        $hidden . $content);
894    }
895
896
897    /**
898     * GUI object 'username'
899     * Showing IMAP username of the current session
900     *
901     * @param array Named tag parameters (currently not used)
902     * @return string HTML code for the gui object
903     */
904    public function current_username($attrib)
905    {
906        static $username;
907
908        // alread fetched
909        if (!empty($username)) {
910            return $username;
911        }
912
913        // get e-mail address form default identity
914        if ($sql_arr = $this->app->user->get_identity()) {
915            $username = $sql_arr['email'];
916        }
917        else {
918            $username = $this->app->user->get_username();
919        }
920
921        return $username;
922    }
923
924
925    /**
926     * GUI object 'loginform'
927     * Returns code for the webmail login form
928     *
929     * @param array Named parameters
930     * @return string HTML code for the gui object
931     */
932    private function login_form($attrib)
933    {
934        $default_host = $this->config['default_host'];
935
936        $_SESSION['temp'] = true;
937
938        $input_user   = new html_inputfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30) + $attrib);
939        $input_pass   = new html_passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30) + $attrib);
940        $input_action = new html_hiddenfield(array('name' => '_action', 'value' => 'login'));
941        $input_tzone  = new html_hiddenfield(array('name' => '_timezone', 'id' => 'rcmlogintz', 'value' => '_default_'));
942        $input_host   = null;
943
944        if (is_array($default_host)) {
945            $input_host = new html_select(array('name' => '_host', 'id' => 'rcmloginhost'));
946
947            foreach ($default_host as $key => $value) {
948                if (!is_array($value)) {
949                    $input_host->add($value, (is_numeric($key) ? $value : $key));
950                }
951                else {
952                    $input_host = null;
953                    break;
954                }
955            }
956        }
957        else if (empty($default_host)) {
958            $input_host = new html_inputfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
959        }
960
961        $form_name  = !empty($attrib['form']) ? $attrib['form'] : 'form';
962        $this->add_gui_object('loginform', $form_name);
963
964        // create HTML table with two cols
965        $table = new html_table(array('cols' => 2));
966
967        $table->add('title', html::label('rcmloginuser', Q(rcube_label('username'))));
968        $table->add(null, $input_user->show(get_input_value('_user', RCUBE_INPUT_POST)));
969
970        $table->add('title', html::label('rcmloginpwd', Q(rcube_label('password'))));
971        $table->add(null, $input_pass->show());
972
973        // add host selection row
974        if (is_object($input_host)) {
975            $table->add('title', html::label('rcmloginhost', Q(rcube_label('server'))));
976            $table->add(null, $input_host->show(get_input_value('_host', RCUBE_INPUT_POST)));
977        }
978
979        $out = $input_action->show();
980        $out .= $input_tzone->show();
981        $out .= $table->show();
982
983        // surround html output with a form tag
984        if (empty($attrib['form'])) {
985            $out = $this->form_tag(array('name' => $form_name, 'method' => "post"), $out);
986        }
987
988        return $out;
989    }
990
991
992    /**
993     * GUI object 'searchform'
994     * Returns code for search function
995     *
996     * @param array Named parameters
997     * @return string HTML code for the gui object
998     */
999    private function search_form($attrib)
1000    {
1001        // add some labels to client
1002        $this->add_label('searching');
1003
1004        $attrib['name'] = '_q';
1005
1006        if (empty($attrib['id'])) {
1007            $attrib['id'] = 'rcmqsearchbox';
1008        }
1009        if ($attrib['type'] == 'search' && !$this->browser->khtml) {
1010          unset($attrib['type'], $attrib['results']);
1011        }
1012       
1013        $input_q = new html_inputfield($attrib);
1014        $out = $input_q->show();
1015
1016        $this->add_gui_object('qsearchbox', $attrib['id']);
1017
1018        // add form tag around text field
1019        if (empty($attrib['form'])) {
1020            $out = $this->form_tag(array(
1021                'name' => "rcmqsearchform",
1022                'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
1023                'style' => "display:inline"),
1024              $out);
1025        }
1026
1027        return $out;
1028    }
1029
1030
1031    /**
1032     * Builder for GUI object 'message'
1033     *
1034     * @param array Named tag parameters
1035     * @return string HTML code for the gui object
1036     */
1037    private function message_container($attrib)
1038    {
1039        if (isset($attrib['id']) === false) {
1040            $attrib['id'] = 'rcmMessageContainer';
1041        }
1042
1043        $this->add_gui_object('message', $attrib['id']);
1044        return html::div($attrib, "");
1045    }
1046
1047
1048    /**
1049     * GUI object 'charsetselector'
1050     *
1051     * @param array Named parameters for the select tag
1052     * @return string HTML code for the gui object
1053     */
1054    static function charset_selector($attrib)
1055    {
1056        // pass the following attributes to the form class
1057        $field_attrib = array('name' => '_charset');
1058        foreach ($attrib as $attr => $value) {
1059            if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex'))) {
1060                $field_attrib[$attr] = $value;
1061            }
1062        }
1063        $charsets = array(
1064            'US-ASCII'     => 'ASCII (English)',
1065            'EUC-JP'       => 'EUC-JP (Japanese)',
1066            'EUC-KR'       => 'EUC-KR (Korean)',
1067            'BIG5'         => 'BIG5 (Chinese)',
1068            'GB2312'       => 'GB2312 (Chinese)',
1069            'ISO-2022-JP'  => 'ISO-2022-JP (Japanese)',
1070            'ISO-8859-1'   => 'ISO-8859-1 (Latin-1)',
1071            'ISO-8859-2'   => 'ISO-8895-2 (Central European)',
1072            'ISO-8859-7'   => 'ISO-8859-7 (Greek)',
1073            'ISO-8859-9'   => 'ISO-8859-9 (Turkish)',
1074            'Windows-1251' => 'Windows-1251 (Cyrillic)',
1075            'Windows-1252' => 'Windows-1252 (Western)',
1076            'Windows-1255' => 'Windows-1255 (Hebrew)',
1077            'Windows-1256' => 'Windows-1256 (Arabic)',
1078            'Windows-1257' => 'Windows-1257 (Baltic)',
1079            'UTF-8'        => 'UTF-8'
1080            );
1081
1082            $select = new html_select($field_attrib);
1083            $select->add(array_values($charsets), array_keys($charsets));
1084
1085            $set = $_POST['_charset'] ? $_POST['_charset'] : $this->get_charset();
1086            return $select->show($set);
1087    }
1088
1089}  // end class rcube_template
1090
1091
Note: See TracBrowser for help on using the repository browser.