PageRenderTime 31ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/program/include/rcube_output_html.php

https://github.com/netconstructor/roundcubemail
PHP | 1775 lines | 1127 code | 257 blank | 391 comment | 275 complexity | f80fe0f7006a457d2a559ddd642095f5 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file