source: github/program/include/rcube_template.php @ ff73e02

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