4 +-----------------------------------------------------------------------+
5 | program/include/rcube_template.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2006-2008, RoundCube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Class to handle HTML page output using a skin template. |
13 | Extends rcube_html_page class from rcube_shared.inc |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
17 +-----------------------------------------------------------------------+
25 * Class to create HTML page output using a skin template
29 * @uses rcube_html_page
31 class rcube_template extends rcube_html_page
39 var $js_env = array();
40 var $js_commands = array();
41 var $object_handlers = array();
43 public $ajax_call = false;
48 * @todo Use jQuery's $(document).ready() here.
49 * @todo Replace $this->config with the real rcube_config object
51 public function __construct($task, $framed = false)
53 parent::__construct();
55 $this->app = rcmail::get_instance();
56 $this->config = $this->app->config->all();
58 //$this->framed = $framed;
61 // add common javascripts
62 $javascript = 'var '.JS_OBJECT_NAME.' = new rcube_webmail();';
64 // don't wait for page onload. Call init at the bottom of the page (delayed)
65 $javascript_foot = "if (window.call_init)\n call_init('".JS_OBJECT_NAME."');";
67 $this->add_script($javascript, 'head_top');
68 $this->add_script($javascript_foot, 'foot');
69 $this->scripts_path = 'program/js/';
70 $this->include_script('common.js');
71 $this->include_script('app.js');
73 // register common UI objects
74 $this->add_handlers(array(
75 'loginform' => array($this, 'login_form'),
76 'username' => array($this, 'current_username'),
77 'message' => array($this, 'message_container'),
78 'charsetselector' => array($this, 'charset_selector'),
83 * Set environment variable
85 * @param string Property name
86 * @param mixed Property value
87 * @param boolean True if this property should be added to client environment
89 public function set_env($name, $value, $addtojs = true)
91 $this->env[$name] = $value;
92 if ($addtojs || isset($this->js_env[$name])) {
93 $this->js_env[$name] = $value;
99 * Set page title variable
101 public function set_pagetitle($title)
103 $this->pagetitle = $title;
108 * Register a template object handler
110 * @param string Object name
111 * @param string Function name to call
114 public function add_handler($obj, $func)
116 $this->object_handlers[$obj] = $func;
120 * Register a list of template object handlers
122 * @param array Hash array with object=>handler pairs
125 public function add_handlers($arr)
127 $this->object_handlers = array_merge($this->object_handlers, $arr);
131 * Register a GUI object to the client script
133 * @param string Object name
134 * @param string Object ID
137 public function add_gui_object($obj, $id)
139 $this->add_script(JS_OBJECT_NAME.".gui_object('$obj', '$id');");
143 * Call a client method
145 * @param string Method to call
146 * @param ... Additional arguments
148 public function command()
150 $this->js_commands[] = func_get_args();
155 * Add a localized label to the client environment
157 public function add_label()
159 $arg_list = func_get_args();
160 foreach ($arg_list as $i => $name) {
161 $this->command('add_label', $name, rcube_label($name));
167 * Invoke display_message command
169 * @param string Message to display
170 * @param string Message type [notice|confirm|error]
171 * @param array Key-value pairs to be replaced in localized text
172 * @uses self::command()
174 public function show_message($message, $type='notice', $vars=NULL)
178 rcube_label(array('name' => $message, 'vars' => $vars)),
184 * Delete all stored env variables and commands
187 * @uses rcube_html::reset()
189 * @uses self::$js_env
190 * @uses self::$js_commands
191 * @uses self::$object_handlers
193 public public function reset()
195 $this->env = array();
196 $this->js_env = array();
197 $this->js_commands = array();
198 $this->object_handlers = array();
204 * Send the request output to the client.
205 * This will either parse a skin tempalte or send an AJAX response
207 * @param string Template name
208 * @param boolean True if script should terminate (default)
210 public function send($templ = null, $exit = true)
212 if ($templ != 'iframe') {
213 $this->parse($templ, false);
216 $this->framed = $templ == 'iframe' ? true : $this->framed;
226 * Process template and write to stdOut
228 * @param string HTML template
229 * @see rcube_html_page::write()
232 public function write($template = '')
234 // unlock interface after iframe load
236 array_unshift($this->js_commands, array('set_busy', false));
238 // write all env variables to client
239 $js = $this->framed ? "if(window.parent) {\n" : '';
240 $js .= $this->get_js_commands() . ($this->framed ? ' }' : '');
241 $this->add_script($js, 'head_top');
244 parent::write($template, $this->config['skin_path']);
248 * Parse a specific skin template and deliver to stdout
250 * Either returns nothing, or exists hard (exit();)
252 * @param string Template name
253 * @param boolean Exit script
255 * @link http://php.net/manual/en/function.exit.php
257 private function parse($name = 'main', $exit = true)
259 $skin_path = $this->config['skin_path'];
261 // read template file
263 $path = "$skin_path/templates/$name.html";
265 if (($fp = fopen($path, 'r')) === false) {
269 $message.= ob_get_contents();
276 'message' => 'Error loading template for '.$name.': '.$message
280 $templ = fread($fp, filesize($path));
283 // parse for specialtags
284 $output = $this->parse_conditions($templ);
285 $output = $this->parse_xml($output);
288 if ($this->config['debug_level'] & 8) {
289 $this->add_footer('<div style="position:absolute;top:5px;left:5px;width:400px;padding:0.2em;background:white;opacity:0.8;z-index:9000">
290 <a href="#toggle" onclick="con=document.getElementById(\'dbgconsole\');con.style.display=(con.style.display==\'none\'?\'block\':\'none\');return false">console</a>
291 <form action="/" name="debugform"><textarea name="console" id="dbgconsole" rows="20" cols="40" wrap="off" style="display:none;width:400px;border:none;font-size:x-small"></textarea></form></div>'
294 $output = $this->parse_with_globals($output);
295 $this->write(trim($output), $skin_path);
303 * Return executable javascript code for all registered commands
305 * @return string $out
307 private function get_js_commands()
310 if (!$this->framed && !empty($this->js_env)) {
311 $out .= JS_OBJECT_NAME . '.set_env('.json_serialize($this->js_env).");\n";
313 foreach ($this->js_commands as $i => $args) {
314 $method = array_shift($args);
315 foreach ($args as $i => $arg) {
316 $args[$i] = json_serialize($arg);
318 $parent = $this->framed || preg_match('/^parent\./', $method);
321 ($parent ? 'parent.' : '') . JS_OBJECT_NAME,
322 preg_replace('/^parent\./', '', $method),
326 // add command to set page title
327 if ($this->ajax_call && !empty($this->pagetitle)) {
329 "this.set_pagetitle('%s');\n",
330 JQ((!empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '') . $this->pagetitle)
337 * Make URLs starting with a slash point to skin directory
339 * @param string Input string
342 public function abs_url($str)
344 return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
348 /***** Template parsing methods *****/
351 * Replace all strings ($varname)
352 * with the content of the according global variable.
354 private function parse_with_globals($input)
356 $GLOBALS['__comm_path'] = Q($this->app->comm_path);
357 return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
361 * Public wrapper to dipp into template parsing.
363 * @param string $input
365 * @uses rcube_template::parse_xml()
368 public function just_parse($input)
370 return $this->parse_xml($input);
374 * Parse for conditional tags
376 * @param string $input
379 private function parse_conditions($input)
381 $matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE);
382 if ($matches && count($matches) == 4) {
383 if (preg_match('/^(else|endif)$/i', $matches[1])) {
384 return $matches[0] . $this->parse_conditions($matches[3]);
386 $attrib = parse_attrib_string($matches[2]);
387 if (isset($attrib['condition'])) {
388 $condmet = $this->check_condition($attrib['condition']);
389 $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
391 $result = $submatches[0];
392 $result.= ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>/Uis', '', $submatches[3], 1) : $submatches[3]);
395 $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
397 return $matches[0] . $this->parse_conditions($result);
404 'message' => "Unable to parse conditional tag " . $matches[2]
412 * Determines if a given condition is met
414 * @todo Get rid off eval() once I understand what this does.
415 * @todo Extend this to allow real conditions, not just "set"
416 * @param string Condition statement
417 * @return boolean True if condition is met, False is not
419 private function check_condition($condition)
421 $condition = preg_replace(
423 '/session:([a-z0-9_]+)/i',
424 '/config:([a-z0-9_]+)/i',
425 '/env:([a-z0-9_]+)/i',
426 '/request:([a-z0-9_]+)/ie'
430 "\$this->config['\\1']",
431 "\$this->env['\\1']",
432 "get_input_value('\\1', RCUVE_INPUT_GPC)"
436 return eval("return (".$condition.");");
441 * Search for special tags in input and replace them
442 * with the appropriate content
444 * @param string Input string to parse
445 * @return string Altered input string
446 * @todo Maybe a cache.
448 private function parse_xml($input)
450 return preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "\$this->xml_command('\\1', '\\2')", $input);
455 * Convert a xml command tag into real content
457 * @param string Tag command: object,button,label, etc.
458 * @param string Attribute string
459 * @return string Tag/Object content
461 private function xml_command($command, $str_attrib, $add_attrib = array())
463 $command = strtolower($command);
464 $attrib = parse_attrib_string($str_attrib) + $add_attrib;
466 // empty output if required condition is not met
467 if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition'])) {
475 if ($attrib['name'] || $attrib['command']) {
476 return $this->button($attrib);
482 if ($attrib['name'] || $attrib['command']) {
483 return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
489 $path = realpath($this->config['skin_path'].$attrib['file']);
490 if ($fsize = filesize($path)) {
491 if ($this->config['skin_include_php']) {
492 $incl = $this->include_php($path);
494 else if ($fp = fopen($path, 'r')) {
495 $incl = fread($fp, $fsize);
498 return $this->parse_xml($incl);
502 case 'plugin.include':
503 //rcube::tfk_debug(var_export($this->config['skin_path'], true));
504 $path = realpath($this->config['skin_path'].$attrib['file']);
506 //rcube::tfk_debug("Does not exist:");
507 //rcube::tfk_debug($this->config['skin_path']);
508 //rcube::tfk_debug($attrib['file']);
509 //rcube::tfk_debug($path);
511 $incl = file_get_contents($path);
513 return $this->parse_xml($incl);
517 // return code for a specific application object
519 $object = strtolower($attrib['name']);
521 // we are calling a class/method
522 if (($handler = $this->object_handlers[$object]) && is_array($handler)) {
523 if ((is_object($handler[0]) && method_exists($handler[0], $handler[1])) ||
524 (is_string($handler[0]) && class_exists($handler[0])))
525 return call_user_func($handler, $attrib);
527 else if (function_exists($handler)) {
528 // execute object handler function
529 return call_user_func($handler, $attrib);
532 if ($object=='productname') {
533 $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
536 if ($object=='version') {
537 $ver = (string)RCMAIL_VERSION;
538 if (is_file(INSTALL_PATH . '.svn/entries')) {
539 if (preg_match('/Revision:\s(\d+)/', @shell_exec('svn info'), $regs))
540 $ver .= ' [SVN r'.$regs[1].']';
544 if ($object=='pagetitle') {
546 $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
548 if (!empty($this->pagetitle)) {
549 $title .= $this->pagetitle;
551 else if ($task == 'login') {
552 $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $this->config['product_name'])));
555 $title .= ucfirst($task);
564 $var = explode(':', $attrib['name']);
570 $value = $this->env[$name];
573 $value = $this->config[$name];
574 if (is_array($value) && $value[$_SESSION['imap_host']]) {
575 $value = $value[$_SESSION['imap_host']];
579 $value = get_input_value($name, RCUBE_INPUT_GPC);
582 $value = $_SESSION[$name];
586 if (is_array($value)) {
587 $value = implode(', ', $value);
597 * Include a specific file and return it's contents
599 * @param string File path
600 * @return string Contents of the processed file
602 private function include_php($file)
606 $out = ob_get_contents();
613 * Create and register a button
615 * @param array Named button attributes
616 * @return string HTML button
617 * @todo Remove all inline JS calls and use jQuery instead.
618 * @todo Remove all sprintf()'s - they are pretty, but also slow.
620 private function button($attrib)
622 static $sa_buttons = array();
623 static $s_button_count = 100;
625 // these commands can be called directly via url
626 $a_static_commands = array('compose', 'list');
628 if (!($attrib['command'] || $attrib['name'])) {
632 $browser = new rcube_browser();
634 // try to find out the button type
635 if ($attrib['type']) {
636 $attrib['type'] = strtolower($attrib['type']);
639 $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
641 $command = $attrib['command'];
643 // take the button from the stack
644 if ($attrib['name'] && $sa_buttons[$attrib['name']]) {
645 $attrib = $sa_buttons[$attrib['name']];
647 else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class']) {
648 // add button to button stack
649 if (!$attrib['name']) {
650 $attrib['name'] = $command;
652 if (!$attrib['image']) {
653 $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
655 $sa_buttons[$attrib['name']] = $attrib;
657 else if ($command && $sa_buttons[$command]) {
658 // get saved button for this command/name
659 $attrib = $sa_buttons[$command];
662 // set border to 0 because of the link arround the button
663 if ($attrib['type']=='image' && !isset($attrib['border'])) {
664 $attrib['border'] = 0;
666 if (!$attrib['id']) {
667 $attrib['id'] = sprintf('rcmbtn%d', $s_button_count++);
669 // get localized text for labels and titles
670 if ($attrib['title']) {
671 $attrib['title'] = Q(rcube_label($attrib['title']));
673 if ($attrib['label']) {
674 $attrib['label'] = Q(rcube_label($attrib['label']));
676 if ($attrib['alt']) {
677 $attrib['alt'] = Q(rcube_label($attrib['alt']));
679 // set title to alt attribute for IE browsers
680 if ($browser->ie && $attrib['title'] && !$attrib['alt']) {
681 $attrib['alt'] = $attrib['title'];
682 unset($attrib['title']);
685 // add empty alt attribute for XHTML compatibility
686 if (!isset($attrib['alt'])) {
690 // register button in the system
691 if ($attrib['command']) {
692 $this->add_script(sprintf(
693 "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
698 $attrib['imageact'] ? $this->abs_url($attrib['imageact']) : $attrib['classact'],
699 $attrib['imagesel'] ? $this->abs_url($attrib['imagesel']) : $attrib['classsel'],
700 $attrib['imageover'] ? $this->abs_url($attrib['imageover']) : ''
703 // make valid href to specific buttons
704 if (in_array($attrib['command'], rcmail::$main_tasks)) {
705 $attrib['href'] = Q(rcmail_url(null, null, $attrib['command']));
707 else if (in_array($attrib['command'], $a_static_commands)) {
708 $attrib['href'] = Q(rcmail_url($attrib['command']));
712 // overwrite attributes
713 if (!$attrib['href']) {
714 $attrib['href'] = '#';
717 $attrib['onclick'] = sprintf(
718 "return %s.command('%s','%s',this)",
724 if ($command && $attrib['imageover']) {
725 $attrib['onmouseover'] = sprintf(
726 "return %s.button_over('%s','%s')",
731 $attrib['onmouseout'] = sprintf(
732 "return %s.button_out('%s','%s')",
739 if ($command && $attrib['imagesel']) {
740 $attrib['onmousedown'] = sprintf(
741 "return %s.button_sel('%s','%s')",
746 $attrib['onmouseup'] = sprintf(
747 "return %s.button_out('%s','%s')",
756 // generate image tag
757 if ($attrib['type']=='image') {
758 $attrib_str = html::attrib_string(
761 'style', 'class', 'id', 'width',
762 'height', 'border', 'hspace',
763 'vspace', 'align', 'alt',
766 $btn_content = sprintf('<img src="%s"%s />', $this->abs_url($attrib['image']), $attrib_str);
767 if ($attrib['label']) {
768 $btn_content .= ' '.$attrib['label'];
770 $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
772 else if ($attrib['type']=='link') {
773 $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
774 $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
776 else if ($attrib['type']=='input') {
777 $attrib['type'] = 'button';
779 if ($attrib['label']) {
780 $attrib['value'] = $attrib['label'];
783 $attrib_str = html::attrib_string(
786 'type', 'value', 'onclick',
787 'id', 'class', 'style'
790 $out = sprintf('<input%s disabled="disabled" />', $attrib_str);
793 // generate html code for button
795 $attrib_str = html::attrib_string($attrib, $link_attrib);
796 $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
803 /* ************* common functions delivering gui objects ************** */
807 * Create a form tag with the necessary hidden fields
809 * @param array Named tag parameters
810 * @return string HTML code for the form
812 public function form_tag($attrib, $content = null)
815 $hiddenfield = new html_hiddenfield(array('name' => '_framed', 'value' => '1'));
816 $hidden = $hiddenfield->show();
820 $attrib['noclose'] = true;
822 return html::tag('form',
823 $attrib + array('action' => "./", 'method' => "get"),
829 * GUI object 'username'
830 * Showing IMAP username of the current session
832 * @param array Named tag parameters (currently not used)
833 * @return string HTML code for the gui object
835 public function current_username($attrib)
840 if (!empty($username)) {
844 // get e-mail address form default identity
845 if ($sql_arr = $this->app->user->get_identity()) {
846 $username = $sql_arr['email'];
849 $username = $this->app->user->get_username();
857 * GUI object 'loginform'
858 * Returns code for the webmail login form
860 * @param array Named parameters
861 * @return string HTML code for the gui object
863 private function login_form($attrib)
865 $default_host = $this->config['default_host'];
867 $_SESSION['temp'] = true;
869 $input_user = new html_inputfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30, 'autocomplete' => 'off'));
870 $input_pass = new html_passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
871 $input_action = new html_hiddenfield(array('name' => '_action', 'value' => 'login'));
874 if (is_array($default_host)) {
875 $input_host = new html_select(array('name' => '_host', 'id' => 'rcmloginhost'));
877 foreach ($default_host as $key => $value) {
878 if (!is_array($value)) {
879 $input_host->add($value, (is_numeric($key) ? $value : $key));
887 else if (!strlen($default_host)) {
888 $input_host = new html_inputfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
891 $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
892 $this->add_gui_object('loginform', $form_name);
894 // create HTML table with two cols
895 $table = new html_table(array('cols' => 2));
897 $table->add('title', html::label('rcmloginuser', Q(rcube_label('username'))));
898 $table->add(null, $input_user->show(get_input_value('_user', RCUVE_INPUT_POST)));
900 $table->add('title', html::label('rcmloginpwd', Q(rcube_label('password'))));
901 $table->add(null, $input_pass->show());
903 // add host selection row
904 if (is_object($input_host)) {
905 $table->add('title', html::label('rcmloginhost', Q(rcube_label('server'))));
906 $table->add(null, $input_host->show(get_input_value('_host', RCUVE_INPUT_POST)));
909 $out = $input_action->show();
910 $out .= $table->show();
912 // surround html output with a form tag
913 if (empty($attrib['form'])) {
914 $out = $this->form_tag(array('name' => $form_name, 'method' => "post"), $out);
922 * GUI object 'searchform'
923 * Returns code for search function
925 * @param array Named parameters
926 * @return string HTML code for the gui object
928 private function search_form($attrib)
930 // add some labels to client
931 $this->add_label('searching');
933 $attrib['name'] = '_q';
935 if (empty($attrib['id'])) {
936 $attrib['id'] = 'rcmqsearchbox';
938 $input_q = new html_inputfield($attrib);
939 $out = $input_q->show();
941 $this->add_gui_object('qsearchbox', $attrib['id']);
943 // add form tag around text field
944 if (empty($attrib['form'])) {
945 $out = $this->form_tag(array(
946 'name' => "rcmqsearchform",
947 'onsubmit' => JS_OBJECT_NAME . ".command('search');return false;",
948 'style' => "display:inline"),
957 * Builder for GUI object 'message'
959 * @param array Named tag parameters
960 * @return string HTML code for the gui object
962 private function message_container($attrib)
964 if (isset($attrib['id']) === false) {
965 $attrib['id'] = 'rcmMessageContainer';
968 $this->add_gui_object('message', $attrib['id']);
969 return html::div($attrib, "");
974 * GUI object 'charsetselector'
976 * @param array Named parameters for the select tag
977 * @return string HTML code for the gui object
979 static function charset_selector($attrib)
981 // pass the following attributes to the form class
982 $field_attrib = array('name' => '_charset');
983 foreach ($attrib as $attr => $value) {
984 if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex'))) {
985 $field_attrib[$attr] = $value;
989 'US-ASCII' => 'ASCII (English)',
990 'EUC-JP' => 'EUC-JP (Japanese)',
991 'EUC-KR' => 'EUC-KR (Korean)',
992 'BIG5' => 'BIG5 (Chinese)',
993 'GB2312' => 'GB2312 (Chinese)',
994 'ISO-2022-JP' => 'ISO-2022-JP (Japanese)',
995 'ISO-8859-1' => 'ISO-8859-1 (Latin-1)',
996 'ISO-8859-2' => 'ISO-8895-2 (Central European)',
997 'ISO-8859-7' => 'ISO-8859-7 (Greek)',
998 'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
999 'Windows-1251' => 'Windows-1251 (Cyrillic)',
1000 'Windows-1252' => 'Windows-1252 (Western)',
1001 'Windows-1255' => 'Windows-1255 (Hebrew)',
1002 'Windows-1256' => 'Windows-1256 (Arabic)',
1003 'Windows-1257' => 'Windows-1257 (Baltic)',
1007 $select = new html_select($field_attrib);
1008 $select->add(array_values($charsets), array_keys($charsets));
1010 $set = $_POST['_charset'] ? $_POST['_charset'] : $this->get_charset();
1011 return $select->show($set);
1014 } // end class rcube_template