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

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