PageRenderTime 61ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/system/core/Output.php

https://github.com/amant/happy_cms
PHP | 461 lines | 210 code | 75 blank | 176 comment | 37 complexity | 74b706592155c78850ce45438537572a MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP 5.1.6 or newer
  6. *
  7. * @package CodeIgniter
  8. * @author ExpressionEngine Dev Team
  9. * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
  10. * @license http://codeigniter.com/user_guide/license.html
  11. * @link http://codeigniter.com
  12. * @since Version 1.0
  13. * @filesource
  14. */
  15. // ------------------------------------------------------------------------
  16. /**
  17. * Output Class
  18. *
  19. * Responsible for sending final output to browser
  20. *
  21. * @package CodeIgniter
  22. * @subpackage Libraries
  23. * @category Output
  24. * @author ExpressionEngine Dev Team
  25. * @link http://codeigniter.com/user_guide/libraries/output.html
  26. */
  27. class CI_Output {
  28. var $final_output;
  29. var $cache_expiration = 0;
  30. var $headers = array();
  31. var $enable_profiler = FALSE;
  32. var $parse_exec_vars = TRUE; // whether or not to parse variables like {elapsed_time} and {memory_usage}
  33. var $_zlib_oc = FALSE;
  34. var $_profiler_sections = array();
  35. function __construct()
  36. {
  37. $this->_zlib_oc = @ini_get('zlib.output_compression');
  38. log_message('debug', "Output Class Initialized");
  39. }
  40. // --------------------------------------------------------------------
  41. /**
  42. * Get Output
  43. *
  44. * Returns the current output string
  45. *
  46. * @access public
  47. * @return string
  48. */
  49. function get_output()
  50. {
  51. return $this->final_output;
  52. }
  53. // --------------------------------------------------------------------
  54. /**
  55. * Set Output
  56. *
  57. * Sets the output string
  58. *
  59. * @access public
  60. * @param string
  61. * @return void
  62. */
  63. function set_output($output)
  64. {
  65. $this->final_output = $output;
  66. }
  67. // --------------------------------------------------------------------
  68. /**
  69. * Append Output
  70. *
  71. * Appends data onto the output string
  72. *
  73. * @access public
  74. * @param string
  75. * @return void
  76. */
  77. function append_output($output)
  78. {
  79. if ($this->final_output == '')
  80. {
  81. $this->final_output = $output;
  82. }
  83. else
  84. {
  85. $this->final_output .= $output;
  86. }
  87. }
  88. // --------------------------------------------------------------------
  89. /**
  90. * Set Header
  91. *
  92. * Lets you set a server header which will be outputted with the final display.
  93. *
  94. * Note: If a file is cached, headers will not be sent. We need to figure out
  95. * how to permit header data to be saved with the cache data...
  96. *
  97. * @access public
  98. * @param string
  99. * @return void
  100. */
  101. function set_header($header, $replace = TRUE)
  102. {
  103. // If zlib.output_compression is enabled it will compress the output,
  104. // but it will not modify the content-length header to compensate for
  105. // the reduction, causing the browser to hang waiting for more data.
  106. // We'll just skip content-length in those cases.
  107. if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0)
  108. {
  109. return;
  110. }
  111. $this->headers[] = array($header, $replace);
  112. }
  113. // --------------------------------------------------------------------
  114. /**
  115. * Set HTTP Status Header
  116. * moved to Common procedural functions in 1.7.2
  117. *
  118. * @access public
  119. * @param int the status code
  120. * @param string
  121. * @return void
  122. */
  123. function set_status_header($code = 200, $text = '')
  124. {
  125. set_status_header($code, $text);
  126. }
  127. // --------------------------------------------------------------------
  128. /**
  129. * Enable/disable Profiler
  130. *
  131. * @access public
  132. * @param bool
  133. * @return void
  134. */
  135. function enable_profiler($val = TRUE)
  136. {
  137. $this->enable_profiler = (is_bool($val)) ? $val : TRUE;
  138. }
  139. // --------------------------------------------------------------------
  140. /**
  141. * Set Profiler Sections
  142. *
  143. * Allows override of default / config settings for Profiler section display
  144. *
  145. * @access public
  146. * @param array
  147. * @return void
  148. */
  149. function set_profiler_sections($sections)
  150. {
  151. foreach ($sections as $section => $enable)
  152. {
  153. $this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE;
  154. }
  155. }
  156. // --------------------------------------------------------------------
  157. /**
  158. * Set Cache
  159. *
  160. * @access public
  161. * @param integer
  162. * @return void
  163. */
  164. function cache($time)
  165. {
  166. $this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time;
  167. }
  168. // --------------------------------------------------------------------
  169. /**
  170. * Display Output
  171. *
  172. * All "view" data is automatically put into this variable by the controller class:
  173. *
  174. * $this->final_output
  175. *
  176. * This function sends the finalized output data to the browser along
  177. * with any server headers and profile data. It also stops the
  178. * benchmark timer so the page rendering speed and memory usage can be shown.
  179. *
  180. * @access public
  181. * @return mixed
  182. */
  183. function _display($output = '')
  184. {
  185. // Note: We use globals because we can't use $CI =& get_instance()
  186. // since this function is sometimes called by the caching mechanism,
  187. // which happens before the CI super object is available.
  188. global $BM, $CFG;
  189. // Grab the super object if we can.
  190. if (class_exists('CI_Controller'))
  191. {
  192. $CI =& get_instance();
  193. }
  194. // --------------------------------------------------------------------
  195. // Set the output data
  196. if ($output == '')
  197. {
  198. $output =& $this->final_output;
  199. }
  200. // --------------------------------------------------------------------
  201. // Do we need to write a cache file? Only if the controller does not have its
  202. // own _output() method and we are not dealing with a cache file, which we
  203. // can determine by the existence of the $CI object above
  204. if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
  205. {
  206. $this->_write_cache($output);
  207. }
  208. // --------------------------------------------------------------------
  209. // Parse out the elapsed time and memory usage,
  210. // then swap the pseudo-variables with the data
  211. $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
  212. if ($this->parse_exec_vars === TRUE)
  213. {
  214. $memory = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB';
  215. $output = str_replace('{elapsed_time}', $elapsed, $output);
  216. $output = str_replace('{memory_usage}', $memory, $output);
  217. }
  218. // --------------------------------------------------------------------
  219. // Is compression requested?
  220. if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE)
  221. {
  222. if (extension_loaded('zlib'))
  223. {
  224. if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
  225. {
  226. ob_start('ob_gzhandler');
  227. }
  228. }
  229. }
  230. // --------------------------------------------------------------------
  231. // Are there any server headers to send?
  232. if (count($this->headers) > 0)
  233. {
  234. foreach ($this->headers as $header)
  235. {
  236. @header($header[0], $header[1]);
  237. }
  238. }
  239. // --------------------------------------------------------------------
  240. // Does the $CI object exist?
  241. // If not we know we are dealing with a cache file so we'll
  242. // simply echo out the data and exit.
  243. if ( ! isset($CI))
  244. {
  245. echo $output;
  246. log_message('debug', "Final output sent to browser");
  247. log_message('debug', "Total execution time: ".$elapsed);
  248. return TRUE;
  249. }
  250. // --------------------------------------------------------------------
  251. // Do we need to generate profile data?
  252. // If so, load the Profile class and run it.
  253. if ($this->enable_profiler == TRUE)
  254. {
  255. $CI->load->library('profiler');
  256. if ( ! empty($this->_profiler_sections))
  257. {
  258. $CI->profiler->set_sections($this->_profiler_sections);
  259. }
  260. // If the output data contains closing </body> and </html> tags
  261. // we will remove them and add them back after we insert the profile data
  262. if (preg_match("|</body>.*?</html>|is", $output))
  263. {
  264. $output = preg_replace("|</body>.*?</html>|is", '', $output);
  265. $output .= $CI->profiler->run();
  266. $output .= '</body></html>';
  267. }
  268. else
  269. {
  270. $output .= $CI->profiler->run();
  271. }
  272. }
  273. // --------------------------------------------------------------------
  274. // Does the controller contain a function named _output()?
  275. // If so send the output there. Otherwise, echo it.
  276. if (method_exists($CI, '_output'))
  277. {
  278. $CI->_output($output);
  279. }
  280. else
  281. {
  282. // Strip all spaces to from html
  283. //echo preg_replace('!\s+!', ' ', $output);
  284. /*echo preg_replace('#(?ix)(?>[^\S ]\s*|\s{2,})(?=(?:(?:[^<]++|<(?!/?(?:textarea|pre)\b))*+)(?:<(?>textarea|pre)\b|\z))#', ' ', $output);*/
  285. echo preg_replace('%(?>[^\S ]\s*| \s{2,})(?=[^<]*+(?:<(?!/?(?:textarea|pre)\b)[^<]*+)*+(?:<(?>textarea|pre)\b| \z))%Six', ' ', $output);
  286. //echo $output; // Send it to the browser!
  287. }
  288. log_message('debug', "Final output sent to browser");
  289. log_message('debug', "Total execution time: ".$elapsed);
  290. }
  291. // --------------------------------------------------------------------
  292. /**
  293. * Write a Cache File
  294. *
  295. * @access public
  296. * @return void
  297. */
  298. function _write_cache($output)
  299. {
  300. $CI =& get_instance();
  301. $path = $CI->config->item('cache_path');
  302. $cache_path = ($path == '') ? APPPATH.'cache/' : $path;
  303. if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
  304. {
  305. log_message('error', "Unable to write cache file: ".$cache_path);
  306. return;
  307. }
  308. $uri = $CI->config->item('base_url').
  309. $CI->config->item('index_page').
  310. $CI->uri->uri_string();
  311. $cache_path .= md5($uri);
  312. if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
  313. {
  314. log_message('error', "Unable to write cache file: ".$cache_path);
  315. return;
  316. }
  317. $expire = time() + ($this->cache_expiration * 60);
  318. if (flock($fp, LOCK_EX))
  319. {
  320. fwrite($fp, $expire.'TS--->'.$output);
  321. flock($fp, LOCK_UN);
  322. }
  323. else
  324. {
  325. log_message('error', "Unable to secure a file lock for file at: ".$cache_path);
  326. return;
  327. }
  328. fclose($fp);
  329. @chmod($cache_path, FILE_WRITE_MODE);
  330. log_message('debug', "Cache file written: ".$cache_path);
  331. }
  332. // --------------------------------------------------------------------
  333. /**
  334. * Update/serve a cached file
  335. *
  336. * @access public
  337. * @return void
  338. */
  339. function _display_cache(&$CFG, &$URI)
  340. {
  341. $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');
  342. // Build the file path. The file name is an MD5 hash of the full URI
  343. $uri = $CFG->item('base_url').
  344. $CFG->item('index_page').
  345. $URI->uri_string;
  346. $filepath = $cache_path.md5($uri);
  347. if ( ! @file_exists($filepath))
  348. {
  349. return FALSE;
  350. }
  351. if ( ! $fp = @fopen($filepath, FOPEN_READ))
  352. {
  353. return FALSE;
  354. }
  355. flock($fp, LOCK_SH);
  356. $cache = '';
  357. if (filesize($filepath) > 0)
  358. {
  359. $cache = fread($fp, filesize($filepath));
  360. }
  361. flock($fp, LOCK_UN);
  362. fclose($fp);
  363. // Strip out the embedded timestamp
  364. if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
  365. {
  366. return FALSE;
  367. }
  368. // Has the file expired? If so we'll delete it.
  369. if (time() >= trim(str_replace('TS--->', '', $match['1'])))
  370. {
  371. if (is_really_writable($cache_path))
  372. {
  373. @unlink($filepath);
  374. log_message('debug', "Cache file has expired. File deleted");
  375. return FALSE;
  376. }
  377. }
  378. // Display the cache
  379. $this->_display(str_replace($match['0'], '', $cache));
  380. log_message('debug', "Cache file is current. Sending it to browser.");
  381. return TRUE;
  382. }
  383. }
  384. // END Output Class
  385. /* End of file Output.php */
  386. /* Location: ./system/core/Output.php */