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_shared.inc |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com> |
17 +-----------------------------------------------------------------------+
23 require_once('include/rcube_shared.inc');
26 class rcmail_template extends rcube_html_page
31 var $ajax_call = false;
34 var $js_env = array();
35 var $js_commands = array();
36 var $object_handlers = array();
40 function __construct(&$config, $task)
42 parent::__construct();
45 $this->config = $config;
46 $this->ajax_call = !empty($_GET['_remote']) || !empty($_POST['_remote']);
48 // add common javascripts
49 if (!$this->ajax_call)
51 $javascript = "var ".JS_OBJECT_NAME." = new rcube_webmail();";
53 // don't wait for page onload. Call init at the bottom of the page (delayed)
54 $javascript_foot = "if (window.call_init)\n call_init('".JS_OBJECT_NAME."');";
56 $this->add_script($javascript, 'head_top');
57 $this->add_script($javascript_foot, 'foot');
58 $this->scripts_path = 'program/js/';
59 $this->include_script('common.js');
60 $this->include_script('app.js');
64 // PHP 4 compatibility
65 function rcmail_template(&$config, $task)
67 $this->__construct($config, $task);
72 * Set environment variable
74 function set_env($name, $value, $addtojs=true)
76 $this->env[$name] = $value;
77 if ($addtojs || isset($this->js_env[$name]))
78 $this->js_env[$name] = $value;
83 * Set page title variable
85 function set_pagetitle($title)
87 $this->pagetitle = $title;
92 * Register a template object handler
94 * @param string Object name
95 * @param string Function name to call
97 function add_handler($obj, $func)
99 $this->object_handlers[$obj] = $func;
103 * Register a list of template object handlers
105 * @param array Hash array with object=>handler pairs
107 function add_handlers($arr)
109 $this->object_handlers = array_merge($this->object_handlers, $arr);
113 * Register a GUI object to the client script
115 * @param string Object name
116 * @param string Object ID
118 function add_gui_object($obj, $id)
120 $this->add_script(JS_OBJECT_NAME.".gui_object('$obj', '$id');");
125 * Call a client method
127 * @param string Method to call
128 * @param ... Additional arguments
132 $this->js_commands[] = func_get_args();
137 * Invoke display_message command
139 function show_message($message, $type='notice', $vars=NULL)
143 rcube_label(array('name' => $message, 'vars' => $vars)),
149 * Delete all stored env variables and commands
153 $this->env = array();
154 $this->js_env = array();
155 $this->js_commands = array();
156 $this->object_handlers = array();
161 * Send the request output to the client.
162 * This will either parse a skin tempalte or send an AJAX response
164 * @param string Template name
165 * @param boolean True if script should terminate (default)
167 function send($templ=null, $exit=true)
169 if ($this->ajax_call)
170 $this->remote_response('', !$exit);
171 else if ($templ != 'iframe')
172 $this->parse($templ, false);
175 $this->framed = $templ == 'iframe' ? true : $this->framed;
185 * Send an AJAX response with executable JS code
187 * @param string Additional JS code
188 * @param boolean True if output buffer should be flushed
190 function remote_response($add='', $flush=false)
192 static $s_header_sent = FALSE;
196 $s_header_sent = TRUE;
197 send_nocacheing_headers();
198 header('Content-Type: application/x-javascript; charset='.RCMAIL_CHARSET);
199 print '/** ajax response ['.date('d/M/Y h:i:s O')."] **/\n";
202 // unset default env vars
203 unset($this->js_env['task'], $this->js_env['action'], $this->js_env['comm_path']);
205 // send response code
206 print rcube_charset_convert($this->get_js_commands() . $add, RCMAIL_CHARSET, $this->get_charset());
208 if ($flush) // flush the output buffer
216 function write($template='')
218 // write all env variables to client
219 $js = $this->framed ? "if(window.parent) {\n" : '';
220 $js .= $this->get_js_commands() . ($this->framed ? ' }' : '');
221 $this->add_script($js, 'head_top');
224 parent::write($template, $this->config['skin_path']);
229 * Parse a specific skin template and deliver to stdout
231 * @param string Template name
232 * @param boolean Exit script
234 function parse($name='main', $exit=true)
236 $skin_path = $this->config['skin_path'];
238 // read template file
240 $path = "$skin_path/templates/$name.html";
242 if($fp = @fopen($path, 'r'))
244 $templ = fread($fp, filesize($path));
254 'message' => "Error loading template for '$name'"), TRUE, TRUE);
258 // parse for specialtags
259 $output = $this->parse_xml($this->parse_conditions($templ));
262 if ($this->config['debug_level'] & 8)
263 $this->add_footer('<div style="position:absolute;top:5px;left:5px;width:400px;padding:0.2em;background:white;opacity:0.8;z-index:9000">
264 <a href="#toggle" onclick="con=document.getElementById(\'dbgconsole\');con.style.display=(con.style.display==\'none\'?\'block\':\'none\');return false">console</a>
265 <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>');
267 $this->write(trim($this->parse_with_globals($output)), $skin_path);
275 * Return executable javascript code for all registered commands
278 function get_js_commands()
282 $out .= ($this->ajax_call ? 'this' : JS_OBJECT_NAME) . '.set_env('.json_serialize($this->js_env).");\n";
284 foreach ($this->js_commands as $i => $args)
286 $method = array_shift($args);
287 foreach ($args as $i => $arg)
288 $args[$i] = json_serialize($arg);
290 $parent = $this->framed || preg_match('/^parent\./', $method);
293 $this->ajax_call ? 'this' : ($parent ? 'parent.' : '') . JS_OBJECT_NAME,
294 preg_replace('/^parent\./', '', $method),
302 * Make URLs starting with a slash point to skin directory
304 function abs_url($str)
306 return preg_replace('/^\//', $this->config['skin_path'].'/', $str);
311 /***** Template parsing methods *****/
314 * Replace all strings ($varname) with the content
315 * of the according global variable.
317 function parse_with_globals($input)
319 $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
320 return preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
325 * Parse for conditional tags
327 function parse_conditions($input)
329 if (($matches = preg_split('/<roundcube:(if|elseif|else|endif)\s+([^>]+)>/is', $input, 2, PREG_SPLIT_DELIM_CAPTURE)) && count($matches)==4)
331 if (preg_match('/^(else|endif)$/i', $matches[1]))
332 return $matches[0] . $this->parse_conditions($matches[3]);
335 $attrib = parse_attrib_string($matches[2]);
336 if (isset($attrib['condition']))
338 $condmet = $this->check_condition($attrib['condition']);
339 $submatches = preg_split('/<roundcube:(elseif|else|endif)\s+([^>]+)>/is', $matches[3], 2, PREG_SPLIT_DELIM_CAPTURE);
342 $result = $submatches[0] . ($submatches[1] != 'endif' ? preg_replace('/.*<roundcube:endif\s+[^>]+>/Uis', '', $submatches[3], 1) : $submatches[3]);
344 $result = "<roundcube:$submatches[1] $submatches[2]>" . $submatches[3];
346 return $matches[0] . $this->parse_conditions($result);
350 raise_error(array('code' => 500, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__,
351 'message' => "Unable to parse conditional tag " . $matches[2]), TRUE, FALSE);
361 * Determines if a given condition is met
363 * @return True if condition is valid, False is not
365 function check_condition($condition)
367 $condition = preg_replace(
368 array('/session:([a-z0-9_]+)/i', '/config:([a-z0-9_]+)/i', '/env:([a-z0-9_]+)/i', '/request:([a-z0-9_]+)/ie'),
369 array("\$_SESSION['\\1']", "\$this->config['\\1']", "\$this->env['\\1']", "get_input_value('\\1', RCUBE_INPUT_GPC)"),
372 return @eval("return (".$condition.");");
377 * Search for special tags in input and replace them
378 * with the appropriate content
380 * @param string Input string to parse
381 * @return Altered input string
383 function parse_xml($input)
385 return preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "\$this->xml_command('\\1', '\\2')", $input);
390 * Convert a xml command tag into real content
392 * @param string Tag command: object,button,label, etc.
393 * @param string Attribute string
394 * @return Tag/Object content string
396 function xml_command($command, $str_attrib, $add_attrib=array())
398 $command = strtolower($command);
399 $attrib = parse_attrib_string($str_attrib) + $add_attrib;
401 // empty output if required condition is not met
402 if (!empty($attrib['condition']) && !$this->check_condition($attrib['condition']))
410 if ($attrib['command'])
411 return $this->button($attrib);
416 if ($attrib['name'] || $attrib['command'])
417 return Q(rcube_label($attrib + array('vars' => array('product' => $this->config['product_name']))));
422 $path = realpath($this->config['skin_path'].$attrib['file']);
423 if ($fp = @fopen($path, 'r'))
425 $incl = fread($fp, filesize($path));
427 return $this->parse_xml($incl);
431 // return code for a specific application object
433 $object = strtolower($attrib['name']);
435 // execute object handler function
436 if ($this->object_handlers[$object] && function_exists($this->object_handlers[$object]))
437 return call_user_func($this->object_handlers[$object], $attrib);
439 else if ($object=='productname')
441 $name = !empty($this->config['product_name']) ? $this->config['product_name'] : 'RoundCube Webmail';
444 else if ($object=='version')
446 return (string)RCMAIL_VERSION;
448 else if ($object=='pagetitle')
451 $title = !empty($this->config['product_name']) ? $this->config['product_name'].' :: ' : '';
453 if (!empty($this->pagetitle))
454 $title .= $this->pagetitle;
455 else if ($task == 'login')
456 $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $this->config['product_name'])));
458 $title .= ucfirst($task);
471 * Create and register a button
473 * @param array Button attributes
474 * @return HTML button
476 function button($attrib)
478 global $CONFIG, $OUTPUT, $BROWSER, $MAIN_TASKS;
479 static $sa_buttons = array();
480 static $s_button_count = 100;
482 // these commands can be called directly via url
483 $a_static_commands = array('compose', 'list');
485 $skin_path = $this->config['skin_path'];
487 if (!($attrib['command'] || $attrib['name']))
490 // try to find out the button type
492 $attrib['type'] = strtolower($attrib['type']);
494 $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $attrib['imageact']) ? 'image' : 'link';
496 $command = $attrib['command'];
498 // take the button from the stack
499 if($attrib['name'] && $sa_buttons[$attrib['name']])
500 $attrib = $sa_buttons[$attrib['name']];
502 // add button to button stack
503 else if($attrib['image'] || $attrib['imageact'] || $attrib['imagepas'] || $attrib['class'])
505 if (!$attrib['name'])
506 $attrib['name'] = $command;
508 if (!$attrib['image'])
509 $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
511 $sa_buttons[$attrib['name']] = $attrib;
514 // get saved button for this command/name
515 else if ($command && $sa_buttons[$command])
516 $attrib = $sa_buttons[$command];
522 // set border to 0 because of the link arround the button
523 if ($attrib['type']=='image' && !isset($attrib['border']))
524 $attrib['border'] = 0;
527 $attrib['id'] = sprintf('rcmbtn%d', $s_button_count++);
529 // get localized text for labels and titles
530 if ($attrib['title'])
531 $attrib['title'] = Q(rcube_label($attrib['title']));
532 if ($attrib['label'])
533 $attrib['label'] = Q(rcube_label($attrib['label']));
536 $attrib['alt'] = Q(rcube_label($attrib['alt']));
538 // set title to alt attribute for IE browsers
539 if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
541 $attrib['alt'] = $attrib['title'];
542 unset($attrib['title']);
545 // add empty alt attribute for XHTML compatibility
546 if (!isset($attrib['alt']))
550 // register button in the system
551 if ($attrib['command'])
553 $this->add_script(sprintf(
554 "%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
559 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
560 $attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
561 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : '')
564 // make valid href to specific buttons
565 if (in_array($attrib['command'], $MAIN_TASKS))
566 $attrib['href'] = Q(rcmail_url(null, null, $attrib['command']));
567 else if (in_array($attrib['command'], $a_static_commands))
568 $attrib['href'] = Q(rcmail_url($attrib['command']));
571 // overwrite attributes
572 if (!$attrib['href'])
573 $attrib['href'] = '#';
576 $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", JS_OBJECT_NAME, $command, $attrib['prop']);
578 if ($command && $attrib['imageover'])
580 $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
581 $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
584 if ($command && $attrib['imagesel'])
586 $attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
587 $attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", JS_OBJECT_NAME, $command, $attrib['id']);
592 // generate image tag
593 if ($attrib['type']=='image')
595 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
596 $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
597 $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
598 if ($attrib['label'])
599 $btn_content .= ' '.$attrib['label'];
601 $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
603 else if ($attrib['type']=='link')
605 $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
606 $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
608 else if ($attrib['type']=='input')
610 $attrib['type'] = 'button';
612 if ($attrib['label'])
613 $attrib['value'] = $attrib['label'];
615 $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
616 $out = sprintf('<input%s disabled />', $attrib_str);
619 // generate html code for button
622 $attrib_str = create_attrib_string($attrib, $link_attrib);
623 $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);