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