4 +-----------------------------------------------------------------------+
5 | program/include/rcmail_template.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2007, 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_html.inc |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
17 +-----------------------------------------------------------------------+
25 * Classes and functions for HTML output
30 require_once('include/rcube_html.inc');
34 * Class to create HTML page output using a skin template
36 class rcmail_template extends rcube_html_page
41 var $ajax_call = false;
44 var $js_env = array();
45 var $js_commands = array();
46 var $object_handlers = array();
52 * @param array Configuration array
53 * @param string Current task
55 function __construct(&$config, $task)
58 $this->config = $config;
59 $this->ajax_call = !empty($_GET['_remote']) || !empty($_POST['_remote']);
61 // add common javascripts
62 if (!$this->ajax_call)
64 $javascript = "var ".JS_OBJECT_NAME." = new rcube_webmail();";
66 // don't wait for page onload. Call init at the bottom of the page (delayed)
67 $javascript_foot = "if (window.call_init)\n call_init('".JS_OBJECT_NAME."');";
69 $this->add_script($javascript, 'head_top');
70 $this->add_script($javascript_foot, 'foot');
71 $this->scripts_path = 'program/js/';
72 $this->include_script('common.js');
73 $this->include_script('app.js');
79 * @see rcmail_template::__construct()
81 function rcmail_template(&$config, $task)
83 $this->__construct($config, $task);
88 * Set environment variable
90 * @param string Property name
91 * @param mixed Property value
92 * @param boolean True if this property should be added to client environment
94 function set_env($name, $value, $addtojs=true)
96 $this->env[$name] = $value;
97 if ($addtojs || isset($this->js_env[$name]))
98 $this->js_env[$name] = $value;
103 * Set page title variable
105 function set_pagetitle($title)
107 $this->pagetitle = $title;
112 * Register a template object handler
114 * @param string Object name
115 * @param string Function name to call
117 function add_handler($obj, $func)
119 $this->object_handlers[$obj] = $func;
123 * Register a list of template object handlers
125 * @param array Hash array with object=>handler pairs
127 function add_handlers($arr)
129 $this->object_handlers = array_merge($this->object_handlers, $arr);
133 * Register a GUI object to the client script
135 * @param string Object name
136 * @param string Object ID
138 function add_gui_object($obj, $id)
140 $this->add_script(JS_OBJECT_NAME.".gui_object('$obj', '$id');");
145 * Call a client method
147 * @param string Method to call
148 * @param ... Additional arguments
152 $this->js_commands[] = func_get_args();
157 * Invoke display_message command
159 * @param string Message to display
160 * @param string Message type [notice|confirm|error]
161 * @param array Key-value pairs to be replaced in localized text
163 function show_message($message, $type='notice', $vars=NULL)
167 rcube_label(array('name' => $message, 'vars' => $vars)),
173 * Delete all stored env variables and commands
177 $this->env = array();
178 $this->js_env = array();
179 $this->js_commands = array();
180 $this->object_handlers = array();
185 * Send the request output to the client.
186 * This will either parse a skin tempalte or send an AJAX response
188 * @param string Template name
189 * @param boolean True if script should terminate (default)
191 function send($templ=null, $exit=true)
193 if ($this->ajax_call)
194 $this->remote_response('', !$exit);
195 else if ($templ != 'iframe')
196 $this->parse($templ, false);
199 $this->framed = $templ == 'iframe' ? true : $this->framed;
209 * Send an AJAX response with executable JS code
211 * @param string Additional JS code
212 * @param boolean True if output buffer should be flushed
214 function remote_response($add='', $flush=false)
216 static $s_header_sent = FALSE;
220 $s_header_sent = TRUE;
221 send_nocacheing_headers();
222 header('Content-Type: application/x-javascript; charset='.RCMAIL_CHARSET);
223 print '/** ajax response ['.date('d/M/Y h:i:s O')."] **/\n";
226 // unset default env vars
227 unset($this->js_env['task'], $this->js_env['action'], $this->js_env['comm_path']);
229 // send response code
230 print rcube_charset_convert($this->get_js_commands() . $add, RCMAIL_CHARSET, $this->get_charset());
232 if ($flush) // flush the output buffer
238 * Process template and write to stdOut
240 * @param string HTML template
241 * @see rcube_html_page::write()
243 function write($template='')
245 // unlock interface after iframe load
247 array_unshift($this->js_commands, array('set_busy', false));
249 // write all env variables to client
250 $js = $this->framed ? "if(window.parent) {\n" : '';
251 $js .= $this->get_js_commands() . ($this->framed ? ' }' : '');
252 $this->add_script($js, 'head_top');
255 parent::write($template, $this->config['skin_path']);
260 * Parse a specific skin template and deliver to stdout
262 * @param string Template name
263 * @param boolean Exit script
265 function parse($name='main', $exit=true)
267 $skin_path = $this->config['skin_path'];
269 // read template file
271 $path = "$skin_path/templates/$name.html";
273 if($fp = @fopen($path, 'r'))
275 $templ = fread($fp, filesize($path));
285 'message' => "Error loading template for '$name'"), TRUE, TRUE);
289 // parse for specialtags
290 $output = $this->parse_xml($this->parse_conditions($templ));
293 if ($this->config['debug_level'] & 8)
294 $this->add_footer('<div style="position:absolute;top:5px;left:5px;width:400px;padding:0.2em;background:white;opacity:0.8;z-index:9000">
295 <a href="#toggle" onclick="con=document.getElementById(\'dbgconsole\');con.style.display=(con.style.display==\'none\'?\'block\':\'none\');return false">console</a>
296 <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>');
298 $this->write(trim($this->parse_with_globals($output)), $skin_path);
306 * Return executable javascript code for all registered commands
309 function get_js_commands()
312 if (!$this->framed && !empty($this->js_env))
313 $out .= ($this->ajax_call ? 'this' : JS_OBJECT_NAME) . '.set_env('.json_serialize($this->js_env).");\n";
315 // add command to set page title
316 if ($this->ajax_call && !empty($this->pagetitle))
318 "this.set_pagetitle('%s');\n",
319 JQ((!empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '') . $this->pagetitle)
322 foreach ($this->js_commands as $i => $args)
324 $method = array_shift($args);
325 foreach ($args as $i => $arg)
326 $args[$i] = json_serialize($arg);
328 $parent = $this->framed || preg_match('/^parent\./', $method);
331 $this->ajax_call ? 'this' : ($parent ? 'parent.' : '') . JS_OBJECT_NAME,
332 preg_replace('/^parent\./', '', $method),
342 * Make URLs starting with a slash point to skin directory
345 function abs_url($str)
347 return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
352 /***** Template parsing methods *****/
355 * Replace all strings ($varname)
356 * with the content of the according global variable.
359 function parse_with_globals($input)
361 $GLOBALS['__comm_path'] = Q($GLOBALS['COMM_PATH']);
362 return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
367 * Parse for conditional tags
370 function parse_conditions($input)
372 if (($matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE)) && count($matches)==4)
374 if (preg_match('/^(else|endif)$/i', $matches[1]))
375 return $matches[0] . $this->parse_conditions($matches[3]);
378 $attrib = parse_attrib_string($matches[2]);
379 if (isset($attrib['condition']))
381 $condmet = $this->check_condition($attrib['condition']);
382 $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
385 $result = $submatches[0] . ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>/Uis', '', $submatches[3], 1) : $submatches[3]);
387 $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
389 return $matches[0] . $this->parse_conditions($result);
393 raise_error(array('code' => 500, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__,
394 'message' => "Unable to parse conditional tag " . $matches[2]), TRUE, FALSE);
404 * Determines if a given condition is met
406 * @return True if condition is valid, False is not
409 function check_condition($condition)
411 $condition = preg_replace(
412 array('/session:([a-z0-9_]+)/i', '/config:([a-z0-9_]+)/i', '/env:([a-z0-9_]+)/i', '/request:([a-z0-9_]+)/ie'),
413 array("\$_SESSION['\\1']", "\$this->config['\\1']", "\$this->env['\\1']", "get_input_value('\\1', RCUBE_INPUT_GPC)"),
416 return @eval("return (".$condition.");");
421 * Search for special tags in input and replace them
422 * with the appropriate content
424 * @param string Input string to parse
425 * @return Altered input string
428 function parse_xml($input)
430 return preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "\$this->xml_command('\\1', '\\2')", $input);
435 * Convert a xml command tag into real content
437 * @param string Tag command: object,button,label, etc.
438 * @param string Attribute string
439 * @return Tag/Object content string
442 function xml_command($command, $str_attrib, $add_attrib=array())
444 $command = strtolower($command);
445 $attrib = parse_attrib_string($str_attrib) + $add_attrib;
447 // empty output if required condition is not met
448 if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition']))
456 return $this->button($attrib);
461 if ($attrib['name'] || $attrib['command'])
462 return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
467 $path = realpath($this->config['skin_path'].$attrib['file']);
470 if ($this->config['skin_include_php'])
471 $incl = $this->include_php($path);
472 else if ($fp = @fopen($path, 'r'))
474 $incl = fread($fp, filesize($path));
477 return $this->parse_xml($incl);
481 // return code for a specific application object
483 $object = strtolower($attrib['name']);
485 // execute object handler function
486 if ($this->object_handlers[$object] && function_exists($this->object_handlers[$object]))
487 return call_user_func($this->object_handlers[$object], $attrib);
489 else if ($object=='productname')
491 $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
494 else if ($object=='version')
496 return (string)RCMAIL_VERSION;
498 else if ($object=='pagetitle')
501 $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
503 if (!empty($this->pagetitle))
504 $title .= $this->pagetitle;
505 else if ($task == 'login')
506 $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $this->config['product_name'])));
508 $title .= ucfirst($task);
517 $var = explode(':', $attrib['name']);
524 $value = $this->env[$name];
527 $value = $this->config[$name];
528 if (is_array($value) && $value[$_SESSION['imap_host']])
529 $value = $value[$_SESSION['imap_host']];
532 $value = get_input_value($name, RCUBE_INPUT_GPC);
535 $value = $_SESSION[$name];
539 if (is_array($value))
540 $value = join(", ", $value);
550 * Include a specific file and return it's contents
552 * @param string File path
553 * @return string Contents of the processed file
555 function include_php($file)
559 $out = ob_get_contents();
567 * Create and register a button
569 * @param array Button attributes
570 * @return HTML button
573 function button($attrib)
575 global $CONFIG, $OUTPUT, $BROWSER, $MAIN_TASKS;
576 static $sa_buttons = array();
577 static $s_button_count = 100;
579 // these commands can be called directly via url
580 $a_static_commands = array('compose', 'list');
582 $skin_path = $this->config['skin_path'];
584 if (!($attrib['command'] || $attrib['name'] || $attrib['onclick']))
587 // try to find out the button type
589 $attrib['type'] = strtolower($attrib['type']);
591 $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
593 $command = $attrib['command'];
595 // take the button from the stack
596 if($attrib['name'] && $sa_buttons[$attrib['name']])
597 $attrib = $sa_buttons[$attrib['name']];
599 // add button to button stack
600 else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class'])
602 if (!$attrib['name'])
603 $attrib['name'] = $command;
605 if (!$attrib['image'])
606 $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
608 $sa_buttons[$attrib['name']] = $attrib;
611 // get saved button for this command/name
612 else if ($command && $sa_buttons[$command])
613 $attrib = $sa_buttons[$command];
619 // set border to 0 because of the link arround the button
620 if ($attrib['type']=='image' && !isset($attrib['border']))
621 $attrib['border'] = 0;
624 $attrib['id'] = sprintf('rcmbtn%d', $s_button_count++);
626 // get localized text for labels and titles
627 if ($attrib['title'])
628 $attrib['title'] = Q(rcube_label($attrib['title']));
629 if ($attrib['label'])
630 $attrib['label'] = Q(rcube_label($attrib['label']));
633 $attrib['alt'] = Q(rcube_label($attrib['alt']));
635 // set title to alt attribute for IE browsers
636 if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
638 $attrib['alt'] = $attrib['title'];
639 unset($attrib['title']);
642 // add empty alt attribute for XHTML compatibility
643 if (!isset($attrib['alt']))
647 // register button in the system
648 if ($attrib['command'])
650 $this->add_script(sprintf(
651 "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
656 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
657 $attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
658 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : '')
661 // make valid href to specific buttons
662 if (in_array($attrib['command'], $MAIN_TASKS))
663 $attrib['href'] = Q(rcmail_url(null, null, $attrib['command']));
664 else if (in_array($attrib['command'], $a_static_commands))
665 $attrib['href'] = Q(rcmail_url($attrib['command']));
668 // overwrite attributes
669 if (!$attrib['href'])
670 $attrib['href'] = '#';
673 $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", JS_OBJECT_NAME, $command, $attrib['prop']);
675 if ($command && $attrib['imageover'])
677 $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
678 $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
681 if ($command && $attrib['imagesel'])
683 $attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
684 $attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
689 // generate image tag
690 if ($attrib['type']=='image')
692 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
693 $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
694 $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
695 if ($attrib['label'])
696 $btn_content .= ' '.$attrib['label'];
698 $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
700 else if ($attrib['type']=='link')
702 $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
703 $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
705 else if ($attrib['type']=='input')
707 $attrib['type'] = 'button';
709 if ($attrib['label'])
710 $attrib['value'] = $attrib['label'];
712 $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
713 $out = sprintf('<input%s disabled="disabled" />', $attrib_str);
716 // generate html code for button
719 $attrib_str = create_attrib_string($attrib, $link_attrib);
720 $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
726 } // end class rcmail_template
730 // ************** common functions delivering gui objects **************
734 * Builder for GUI object 'message'
736 * @param array Named tag parameters
737 * @return string HTML code for the gui object
739 function rcmail_message_container($attrib)
744 $attrib['id'] = 'rcmMessageContainer';
746 // allow the following attributes to be added to the <table> tag
747 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
748 $out = '<div' . $attrib_str . "></div>";
750 $OUTPUT->add_gui_object('message', $attrib['id']);
757 * GUI object 'username'
758 * Showing IMAP username of the current session
760 * @param array Named tag parameters (currently not used)
761 * @return string HTML code for the gui object
763 function rcmail_current_username($attrib)
769 if (!empty($s_username))
772 if ($sql_arr = $USER->get_identity())
773 $s_username = $sql_arr['email'];
774 else if (strstr($_SESSION['username'], '@'))
775 $s_username = $_SESSION['username'];
777 $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
784 * GUI object 'loginform'
785 * Returns code for the webmail login form
787 * @param array Named parameters
788 * @return string HTML code for the gui object
790 function rcmail_login_form($attrib)
792 global $CONFIG, $OUTPUT, $SESS_HIDDEN_FIELD;
795 $labels['user'] = rcube_label('username');
796 $labels['pass'] = rcube_label('password');
797 $labels['host'] = rcube_label('server');
799 $input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30) + $attrib);
800 $input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30) + $attrib);
801 $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
804 $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
805 $fields['pass'] = $input_pass->show();
806 $fields['action'] = $input_action->show();
808 if (is_array($CONFIG['default_host']))
810 $select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
812 foreach ($CONFIG['default_host'] as $key => $value)
814 if (!is_array($value))
815 $select_host->add($value, (is_numeric($key) ? $value : $key));
823 $fields['host'] = isset($select_host) ? $select_host->show(get_input_value('_host', RCUBE_INPUT_POST)) : null;
825 else if (!strlen($CONFIG['default_host']))
827 $input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
828 $fields['host'] = $input_host->show(get_input_value('_host', RCUBE_INPUT_POST));
831 $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
832 $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
833 $form_end = !strlen($attrib['form']) ? '</form>' : '';
840 <td class="title"><label for="rcmloginhost">$labels[host]</label></td>
841 <td>$fields[host]</td>
845 $OUTPUT->add_gui_object('loginform', $form_name);
853 <td class="title"><label for="rcmloginuser">$labels[user]</label></td>
854 <td>$fields[user]</td>
858 <td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
859 <td>$fields[pass]</td>
870 * GUI object 'charsetselector'
872 * @param array Named parameters for the select tag
873 * @return string HTML code for the gui object
875 function rcmail_charset_selector($attrib)
879 // pass the following attributes to the form class
880 $field_attrib = array('name' => '_charset');
881 foreach ($attrib as $attr => $value)
882 if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
883 $field_attrib[$attr] = $value;
886 'US-ASCII' => 'ASCII (English)',
887 'EUC-JP' => 'EUC-JP (Japanese)',
888 'EUC-KR' => 'EUC-KR (Korean)',
889 'BIG5' => 'BIG5 (Chinese)',
890 'GB2312' => 'GB2312 (Chinese)',
891 'ISO-2022-JP' => 'ISO-2022-JP (Japanese)',
892 'ISO-8859-1' => 'ISO-8859-1 (Latin-1)',
893 'ISO-8859-2' => 'ISO-8895-2 (Central European)',
894 'ISO-8859-7' => 'ISO-8859-7 (Greek)',
895 'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
896 'Windows-1251' => 'Windows-1251 (Cyrillic)',
897 'Windows-1252' => 'Windows-1252 (Western)',
898 'Windows-1255' => 'Windows-1255 (Hebrew)',
899 'Windows-1256' => 'Windows-1256 (Arabic)',
900 'Windows-1257' => 'Windows-1257 (Baltic)',
904 $select = new select($field_attrib);
905 $select->add(array_values($charsets), array_keys($charsets));
907 $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
908 return $select->show($set);
913 * GUI object 'searchform'
914 * Returns code for search function
916 * @param array Named parameters
917 * @return string HTML code for the gui object
919 function rcmail_search_form($attrib)
923 // add some labels to client
924 rcube_add_label('searching');
926 $attrib['name'] = '_q';
928 if (empty($attrib['id']))
929 $attrib['id'] = 'rcmqsearchbox';
931 $input_q = new textfield($attrib);
932 $out = $input_q->show();
934 $OUTPUT->add_gui_object('qsearchbox', $attrib['id']);
936 // add form tag around text field
937 if (empty($attrib['form']))
939 '<form name="rcmqsearchform" action="./" '.
940 'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',