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 foreach ($this->js_commands as $i => $args)
317 $method = array_shift($args);
318 foreach ($args as $i => $arg)
319 $args[$i] = json_serialize($arg);
321 $parent = $this->framed || preg_match('/^parent\./', $method);
324 $this->ajax_call ? 'this' : ($parent ? 'parent.' : '') . JS_OBJECT_NAME,
325 preg_replace('/^parent\./', '', $method),
329 // add command to set page title
330 if ($this->ajax_call && !empty($this->pagetitle))
332 "this.set_pagetitle('%s');\n",
333 JQ((!empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '') . $this->pagetitle)
340 * Make URLs starting with a slash point to skin directory
343 function abs_url($str)
345 return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
350 /***** Template parsing methods *****/
353 * Replace all strings ($varname)
354 * with the content of the according global variable.
357 function parse_with_globals($input)
359 $GLOBALS['__comm_path'] = urlencode($GLOBALS['COMM_PATH']);
360 return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
365 * Parse for conditional tags
368 function parse_conditions($input)
370 if (($matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE)) && count($matches)==4)
372 if (preg_match('/^(else|endif)$/i', $matches[1]))
373 return $matches[0] . $this->parse_conditions($matches[3]);
376 $attrib = parse_attrib_string($matches[2]);
377 if (isset($attrib['condition']))
379 $condmet = $this->check_condition($attrib['condition']);
380 $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
383 $result = $submatches[0] . ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>/Uis', '', $submatches[3], 1) : $submatches[3]);
385 $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
387 return $matches[0] . $this->parse_conditions($result);
391 raise_error(array('code' => 500, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__,
392 'message' => "Unable to parse conditional tag " . $matches[2]), TRUE, FALSE);
402 * Determines if a given condition is met
404 * @return True if condition is valid, False is not
407 function check_condition($condition)
409 $condition = preg_replace(
410 array('/session:([a-z0-9_]+)/i', '/config:([a-z0-9_]+)/i', '/env:([a-z0-9_]+)/i', '/request:([a-z0-9_]+)/ie'),
411 array("\$_SESSION['\\1']", "\$this->config['\\1']", "\$this->env['\\1']", "get_input_value('\\1', RCUBE_INPUT_GPC)"),
414 return @eval("return (".$condition.");");
419 * Search for special tags in input and replace them
420 * with the appropriate content
422 * @param string Input string to parse
423 * @return Altered input string
426 function parse_xml($input)
428 return preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "\$this->xml_command('\\1', '\\2')", $input);
433 * Convert a xml command tag into real content
435 * @param string Tag command: object,button,label, etc.
436 * @param string Attribute string
437 * @return Tag/Object content string
440 function xml_command($command, $str_attrib, $add_attrib=array())
442 $command = strtolower($command);
443 $attrib = parse_attrib_string($str_attrib) + $add_attrib;
445 // empty output if required condition is not met
446 if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition']))
454 if ($attrib['command'])
455 return $this->button($attrib);
460 if ($attrib['name'] || $attrib['command'])
461 return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
466 $path = realpath($this->config['skin_path'].$attrib['file']);
469 if ($this->config['skin_include_php'])
470 $incl = $this->include_php($path);
471 else if ($fp = @fopen($path, 'r'))
473 $incl = fread($fp, filesize($path));
476 return $this->parse_xml($incl);
480 // return code for a specific application object
482 $object = strtolower($attrib['name']);
484 // execute object handler function
485 if ($this->object_handlers[$object] && function_exists($this->object_handlers[$object]))
486 return call_user_func($this->object_handlers[$object], $attrib);
488 else if ($object=='productname')
490 $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
493 else if ($object=='version')
495 return (string)RCMAIL_VERSION;
497 else if ($object=='pagetitle')
500 $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
502 if (!empty($this->pagetitle))
503 $title .= $this->pagetitle;
504 else if ($task == 'login')
505 $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $this->config['product_name'])));
507 $title .= ucfirst($task);
516 $var = explode(':', $attrib['name']);
523 $value = $this->env[$name];
526 $value = $this->config[$name];
527 if (is_array($value) && $value[$_SESSION['imap_host']])
528 $value = $value[$_SESSION['imap_host']];
531 $value = get_input_value($name, RCUBE_INPUT_GPC);
534 $value = $_SESSION[$name];
538 if (is_array($value))
539 $value = join(", ", $value);
549 * Include a specific file and return it's contents
551 * @param string File path
552 * @return string Contents of the processed file
554 function include_php($file)
558 $out = ob_get_contents();
566 * Create and register a button
568 * @param array Button attributes
569 * @return HTML button
572 function button($attrib)
574 global $CONFIG, $OUTPUT, $BROWSER, $MAIN_TASKS;
575 static $sa_buttons = array();
576 static $s_button_count = 100;
578 // these commands can be called directly via url
579 $a_static_commands = array('compose', 'list');
581 $skin_path = $this->config['skin_path'];
583 if (!($attrib['command'] || $attrib['name']))
586 // try to find out the button type
588 $attrib['type'] = strtolower($attrib['type']);
590 $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
592 $command = $attrib['command'];
594 // take the button from the stack
595 if($attrib['name'] && $sa_buttons[$attrib['name']])
596 $attrib = $sa_buttons[$attrib['name']];
598 // add button to button stack
599 else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class'])
601 if (!$attrib['name'])
602 $attrib['name'] = $command;
604 if (!$attrib['image'])
605 $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
607 $sa_buttons[$attrib['name']] = $attrib;
610 // get saved button for this command/name
611 else if ($command && $sa_buttons[$command])
612 $attrib = $sa_buttons[$command];
618 // set border to 0 because of the link arround the button
619 if ($attrib['type']=='image' && !isset($attrib['border']))
620 $attrib['border'] = 0;
623 $attrib['id'] = sprintf('rcmbtn%d', $s_button_count++);
625 // get localized text for labels and titles
626 if ($attrib['title'])
627 $attrib['title'] = Q(rcube_label($attrib['title']));
628 if ($attrib['label'])
629 $attrib['label'] = Q(rcube_label($attrib['label']));
632 $attrib['alt'] = Q(rcube_label($attrib['alt']));
634 // set title to alt attribute for IE browsers
635 if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
637 $attrib['alt'] = $attrib['title'];
638 unset($attrib['title']);
641 // add empty alt attribute for XHTML compatibility
642 if (!isset($attrib['alt']))
646 // register button in the system
647 if ($attrib['command'])
649 $this->add_script(sprintf(
650 "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
655 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
656 $attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
657 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : '')
660 // make valid href to specific buttons
661 if (in_array($attrib['command'], $MAIN_TASKS))
662 $attrib['href'] = Q(rcmail_url(null, null, $attrib['command']));
663 else if (in_array($attrib['command'], $a_static_commands))
664 $attrib['href'] = Q(rcmail_url($attrib['command']));
667 // overwrite attributes
668 if (!$attrib['href'])
669 $attrib['href'] = '#';
672 $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", JS_OBJECT_NAME, $command, $attrib['prop']);
674 if ($command && $attrib['imageover'])
676 $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
677 $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
680 if ($command && $attrib['imagesel'])
682 $attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
683 $attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
688 // generate image tag
689 if ($attrib['type']=='image')
691 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
692 $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
693 $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
694 if ($attrib['label'])
695 $btn_content .= ' '.$attrib['label'];
697 $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
699 else if ($attrib['type']=='link')
701 $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
702 $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
704 else if ($attrib['type']=='input')
706 $attrib['type'] = 'button';
708 if ($attrib['label'])
709 $attrib['value'] = $attrib['label'];
711 $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
712 $out = sprintf('<input%s disabled="disabled" />', $attrib_str);
715 // generate html code for button
718 $attrib_str = create_attrib_string($attrib, $link_attrib);
719 $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
725 } // end class rcmail_template
729 // ************** common functions delivering gui objects **************
733 * Builder for GUI object 'message'
735 * @param array Named tag parameters
736 * @return string HTML code for the gui object
738 function rcmail_message_container($attrib)
743 $attrib['id'] = 'rcmMessageContainer';
745 // allow the following attributes to be added to the <table> tag
746 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
747 $out = '<div' . $attrib_str . "></div>";
749 $OUTPUT->add_gui_object('message', $attrib['id']);
756 * GUI object 'username'
757 * Showing IMAP username of the current session
759 * @param array Named tag parameters (currently not used)
760 * @return string HTML code for the gui object
762 function rcmail_current_username($attrib)
768 if (!empty($s_username))
771 // get e-mail address form default identity
772 $sql_result = $DB->query(
773 "SELECT email AS mailto
774 FROM ".get_table_name('identities')."
778 $_SESSION['user_id']);
780 if ($DB->num_rows($sql_result))
782 $sql_arr = $DB->fetch_assoc($sql_result);
783 $s_username = $sql_arr['mailto'];
785 else if (strstr($_SESSION['username'], '@'))
786 $s_username = $_SESSION['username'];
788 $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
795 * GUI object 'loginform'
796 * Returns code for the webmail login form
798 * @param array Named parameters
799 * @return string HTML code for the gui object
801 function rcmail_login_form($attrib)
803 global $CONFIG, $OUTPUT, $SESS_HIDDEN_FIELD;
806 $labels['user'] = rcube_label('username');
807 $labels['pass'] = rcube_label('password');
808 $labels['host'] = rcube_label('server');
810 $input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30) + $attrib);
811 $input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30) + $attrib);
812 $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
815 $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
816 $fields['pass'] = $input_pass->show();
817 $fields['action'] = $input_action->show();
819 if (is_array($CONFIG['default_host']))
821 $select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
823 foreach ($CONFIG['default_host'] as $key => $value)
825 if (!is_array($value))
826 $select_host->add($value, (is_numeric($key) ? $value : $key));
834 $fields['host'] = isset($select_host) ? $select_host->show($_POST['_host']) : null;
836 else if (!strlen($CONFIG['default_host']))
838 $input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
839 $fields['host'] = $input_host->show($_POST['_host']);
842 $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
843 $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
844 $form_end = !strlen($attrib['form']) ? '</form>' : '';
851 <td class="title"><label for="rcmloginhost">$labels[host]</label></td>
852 <td>$fields[host]</td>
856 $OUTPUT->add_gui_object('loginform', $form_name);
864 <td class="title"><label for="rcmloginuser">$labels[user]</label></td>
865 <td>$fields[user]</td>
869 <td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
870 <td>$fields[pass]</td>
881 * GUI object 'charsetselector'
883 * @param array Named parameters for the select tag
884 * @return string HTML code for the gui object
886 function rcmail_charset_selector($attrib)
890 // pass the following attributes to the form class
891 $field_attrib = array('name' => '_charset');
892 foreach ($attrib as $attr => $value)
893 if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
894 $field_attrib[$attr] = $value;
897 'US-ASCII' => 'ASCII (English)',
898 'EUC-JP' => 'EUC-JP (Japanese)',
899 'EUC-KR' => 'EUC-KR (Korean)',
900 'BIG5' => 'BIG5 (Chinese)',
901 'GB2312' => 'GB2312 (Chinese)',
902 'ISO-2022-JP' => 'ISO-2022-JP (Japanese)',
903 'ISO-8859-1' => 'ISO-8859-1 (Latin-1)',
904 'ISO-8859-2' => 'ISO-8895-2 (Central European)',
905 'ISO-8859-7' => 'ISO-8859-7 (Greek)',
906 'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
907 'Windows-1251' => 'Windows-1251 (Cyrillic)',
908 'Windows-1252' => 'Windows-1252 (Western)',
909 'Windows-1255' => 'Windows-1255 (Hebrew)',
910 'Windows-1256' => 'Windows-1256 (Arabic)',
911 'Windows-1257' => 'Windows-1257 (Baltic)',
915 $select = new select($field_attrib);
916 $select->add(array_values($charsets), array_keys($charsets));
918 $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
919 return $select->show($set);
924 * GUI object 'searchform'
925 * Returns code for search function
927 * @param array Named parameters
928 * @return string HTML code for the gui object
930 function rcmail_search_form($attrib)
934 // add some labels to client
935 rcube_add_label('searching');
937 $attrib['name'] = '_q';
939 if (empty($attrib['id']))
940 $attrib['id'] = 'rcmqsearchbox';
942 $input_q = new textfield($attrib);
943 $out = $input_q->show();
945 $OUTPUT->add_gui_object('qsearchbox', $attrib['id']);
947 // add form tag around text field
948 if (empty($attrib['form']))
950 '<form name="rcmqsearchform" action="./" '.
951 'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',