PageRenderTime 56ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/system/core/Output.php

https://bitbucket.org/hlevine/myclientbase-south-african-version
PHP | 574 lines | 245 code | 90 blank | 239 comment | 41 complexity | 8c24ef6d59783980cd3019bf7a861cf5 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, GPL-2.0
  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. /**
  29. * Current output string
  30. *
  31. * @var string
  32. * @access protected
  33. */
  34. protected $final_output;
  35. /**
  36. * Cache expiration time
  37. *
  38. * @var int
  39. * @access protected
  40. */
  41. protected $cache_expiration = 0;
  42. /**
  43. * List of server headers
  44. *
  45. * @var array
  46. * @access protected
  47. */
  48. protected $headers = array();
  49. /**
  50. * List of mime types
  51. *
  52. * @var array
  53. * @access protected
  54. */
  55. protected $mime_types = array();
  56. /**
  57. * Determines wether profiler is enabled
  58. *
  59. * @var book
  60. * @access protected
  61. */
  62. protected $enable_profiler = FALSE;
  63. /**
  64. * Determines if output compression is enabled
  65. *
  66. * @var bool
  67. * @access protected
  68. */
  69. protected $_zlib_oc = FALSE;
  70. /**
  71. * List of profiler sections
  72. *
  73. * @var array
  74. * @access protected
  75. */
  76. protected $_profiler_sections = array();
  77. /**
  78. * Whether or not to parse variables like {elapsed_time} and {memory_usage}
  79. *
  80. * @var bool
  81. * @access protected
  82. */
  83. protected $parse_exec_vars = TRUE;
  84. /**
  85. * Constructor
  86. *
  87. */
  88. function __construct()
  89. {
  90. $this->_zlib_oc = @ini_get('zlib.output_compression');
  91. // Get mime types for later
  92. if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
  93. {
  94. include APPPATH.'config/'.ENVIRONMENT.'/mimes.php';
  95. }
  96. else
  97. {
  98. include APPPATH.'config/mimes.php';
  99. }
  100. $this->mime_types = $mimes;
  101. log_message('debug', "Output Class Initialized");
  102. }
  103. // --------------------------------------------------------------------
  104. /**
  105. * Get Output
  106. *
  107. * Returns the current output string
  108. *
  109. * @access public
  110. * @return string
  111. */
  112. function get_output()
  113. {
  114. return $this->final_output;
  115. }
  116. // --------------------------------------------------------------------
  117. /**
  118. * Set Output
  119. *
  120. * Sets the output string
  121. *
  122. * @access public
  123. * @param string
  124. * @return void
  125. */
  126. function set_output($output)
  127. {
  128. $this->final_output = $output;
  129. return $this;
  130. }
  131. // --------------------------------------------------------------------
  132. /**
  133. * Append Output
  134. *
  135. * Appends data onto the output string
  136. *
  137. * @access public
  138. * @param string
  139. * @return void
  140. */
  141. function append_output($output)
  142. {
  143. if ($this->final_output == '')
  144. {
  145. $this->final_output = $output;
  146. }
  147. else
  148. {
  149. $this->final_output .= $output;
  150. }
  151. return $this;
  152. }
  153. // --------------------------------------------------------------------
  154. /**
  155. * Set Header
  156. *
  157. * Lets you set a server header which will be outputted with the final display.
  158. *
  159. * Note: If a file is cached, headers will not be sent. We need to figure out
  160. * how to permit header data to be saved with the cache data...
  161. *
  162. * @access public
  163. * @param string
  164. * @param bool
  165. * @return void
  166. */
  167. function set_header($header, $replace = TRUE)
  168. {
  169. // If zlib.output_compression is enabled it will compress the output,
  170. // but it will not modify the content-length header to compensate for
  171. // the reduction, causing the browser to hang waiting for more data.
  172. // We'll just skip content-length in those cases.
  173. if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) == 0)
  174. {
  175. return;
  176. }
  177. $this->headers[] = array($header, $replace);
  178. return $this;
  179. }
  180. // --------------------------------------------------------------------
  181. /**
  182. * Set Content Type Header
  183. *
  184. * @access public
  185. * @param string extension of the file we're outputting
  186. * @return void
  187. */
  188. function set_content_type($mime_type)
  189. {
  190. if (strpos($mime_type, '/') === FALSE)
  191. {
  192. $extension = ltrim($mime_type, '.');
  193. // Is this extension supported?
  194. if (isset($this->mime_types[$extension]))
  195. {
  196. $mime_type =& $this->mime_types[$extension];
  197. if (is_array($mime_type))
  198. {
  199. $mime_type = current($mime_type);
  200. }
  201. }
  202. }
  203. $header = 'Content-Type: '.$mime_type;
  204. $this->headers[] = array($header, TRUE);
  205. return $this;
  206. }
  207. // --------------------------------------------------------------------
  208. /**
  209. * Set HTTP Status Header
  210. * moved to Common procedural functions in 1.7.2
  211. *
  212. * @access public
  213. * @param int the status code
  214. * @param string
  215. * @return void
  216. */
  217. function set_status_header($code = 200, $text = '')
  218. {
  219. set_status_header($code, $text);
  220. return $this;
  221. }
  222. // --------------------------------------------------------------------
  223. /**
  224. * Enable/disable Profiler
  225. *
  226. * @access public
  227. * @param bool
  228. * @return void
  229. */
  230. function enable_profiler($val = TRUE)
  231. {
  232. $this->enable_profiler = (is_bool($val)) ? $val : TRUE;
  233. return $this;
  234. }
  235. // --------------------------------------------------------------------
  236. /**
  237. * Set Profiler Sections
  238. *
  239. * Allows override of default / config settings for Profiler section display
  240. *
  241. * @access public
  242. * @param array
  243. * @return void
  244. */
  245. function set_profiler_sections($sections)
  246. {
  247. foreach ($sections as $section => $enable)
  248. {
  249. $this->_profiler_sections[$section] = ($enable !== FALSE) ? TRUE : FALSE;
  250. }
  251. return $this;
  252. }
  253. // --------------------------------------------------------------------
  254. /**
  255. * Set Cache
  256. *
  257. * @access public
  258. * @param integer
  259. * @return void
  260. */
  261. function cache($time)
  262. {
  263. $this->cache_expiration = ( ! is_numeric($time)) ? 0 : $time;
  264. return $this;
  265. }
  266. // --------------------------------------------------------------------
  267. /**
  268. * Display Output
  269. *
  270. * All "view" data is automatically put into this variable by the controller class:
  271. *
  272. * $this->final_output
  273. *
  274. * This function sends the finalized output data to the browser along
  275. * with any server headers and profile data. It also stops the
  276. * benchmark timer so the page rendering speed and memory usage can be shown.
  277. *
  278. * @access public
  279. * @param string
  280. * @return mixed
  281. */
  282. function _display($output = '')
  283. {
  284. // Note: We use globals because we can't use $CI =& get_instance()
  285. // since this function is sometimes called by the caching mechanism,
  286. // which happens before the CI super object is available.
  287. global $BM, $CFG;
  288. // Grab the super object if we can.
  289. if (class_exists('CI_Controller'))
  290. {
  291. $CI =& get_instance();
  292. }
  293. // --------------------------------------------------------------------
  294. // Set the output data
  295. if ($output == '')
  296. {
  297. $output =& $this->final_output;
  298. }
  299. // --------------------------------------------------------------------
  300. // Do we need to write a cache file? Only if the controller does not have its
  301. // own _output() method and we are not dealing with a cache file, which we
  302. // can determine by the existence of the $CI object above
  303. if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
  304. {
  305. $this->_write_cache($output);
  306. }
  307. // --------------------------------------------------------------------
  308. // Parse out the elapsed time and memory usage,
  309. // then swap the pseudo-variables with the data
  310. $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
  311. if ($this->parse_exec_vars === TRUE)
  312. {
  313. $memory = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB';
  314. $output = str_replace('{elapsed_time}', $elapsed, $output);
  315. $output = str_replace('{memory_usage}', $memory, $output);
  316. }
  317. // --------------------------------------------------------------------
  318. // Is compression requested?
  319. if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE)
  320. {
  321. if (extension_loaded('zlib'))
  322. {
  323. if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
  324. {
  325. ob_start('ob_gzhandler');
  326. }
  327. }
  328. }
  329. // --------------------------------------------------------------------
  330. // Are there any server headers to send?
  331. if (count($this->headers) > 0)
  332. {
  333. foreach ($this->headers as $header)
  334. {
  335. @header($header[0], $header[1]);
  336. }
  337. }
  338. // --------------------------------------------------------------------
  339. // Does the $CI object exist?
  340. // If not we know we are dealing with a cache file so we'll
  341. // simply echo out the data and exit.
  342. if ( ! isset($CI))
  343. {
  344. echo $output;
  345. log_message('debug', "Final output sent to browser");
  346. log_message('debug', "Total execution time: ".$elapsed);
  347. return TRUE;
  348. }
  349. // --------------------------------------------------------------------
  350. // Do we need to generate profile data?
  351. // If so, load the Profile class and run it.
  352. if ($this->enable_profiler == TRUE)
  353. {
  354. $CI->load->library('profiler');
  355. if ( ! empty($this->_profiler_sections))
  356. {
  357. $CI->profiler->set_sections($this->_profiler_sections);
  358. }
  359. // If the output data contains closing </body> and </html> tags
  360. // we will remove them and add them back after we insert the profile data
  361. if (preg_match("|</body>.*?</html>|is", $output))
  362. {
  363. $output = preg_replace("|</body>.*?</html>|is", '', $output);
  364. $output .= $CI->profiler->run();
  365. $output .= '</body></html>';
  366. }
  367. else
  368. {
  369. $output .= $CI->profiler->run();
  370. }
  371. }
  372. // --------------------------------------------------------------------
  373. // Does the controller contain a function named _output()?
  374. // If so send the output there. Otherwise, echo it.
  375. if (method_exists($CI, '_output'))
  376. {
  377. $CI->_output($output);
  378. }
  379. else
  380. {
  381. echo $output; // Send it to the browser!
  382. }
  383. log_message('debug', "Final output sent to browser");
  384. log_message('debug', "Total execution time: ".$elapsed);
  385. }
  386. // --------------------------------------------------------------------
  387. /**
  388. * Write a Cache File
  389. *
  390. * @access public
  391. * @param string
  392. * @return void
  393. */
  394. function _write_cache($output)
  395. {
  396. $CI =& get_instance();
  397. $path = $CI->config->item('cache_path');
  398. $cache_path = ($path == '') ? APPPATH.'cache/' : $path;
  399. if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
  400. {
  401. log_message('error', "Unable to write cache file: ".$cache_path);
  402. return;
  403. }
  404. $uri = $CI->config->item('base_url').
  405. $CI->config->item('index_page').
  406. $CI->uri->uri_string();
  407. $cache_path .= md5($uri);
  408. if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
  409. {
  410. log_message('error', "Unable to write cache file: ".$cache_path);
  411. return;
  412. }
  413. $expire = time() + ($this->cache_expiration * 60);
  414. if (flock($fp, LOCK_EX))
  415. {
  416. fwrite($fp, $expire.'TS--->'.$output);
  417. flock($fp, LOCK_UN);
  418. }
  419. else
  420. {
  421. log_message('error', "Unable to secure a file lock for file at: ".$cache_path);
  422. return;
  423. }
  424. fclose($fp);
  425. @chmod($cache_path, FILE_WRITE_MODE);
  426. log_message('debug', "Cache file written: ".$cache_path);
  427. }
  428. // --------------------------------------------------------------------
  429. /**
  430. * Update/serve a cached file
  431. *
  432. * @access public
  433. * @param object config class
  434. * @param object uri class
  435. * @return void
  436. */
  437. function _display_cache(&$CFG, &$URI)
  438. {
  439. $cache_path = ($CFG->item('cache_path') == '') ? APPPATH.'cache/' : $CFG->item('cache_path');
  440. // Build the file path. The file name is an MD5 hash of the full URI
  441. $uri = $CFG->item('base_url').
  442. $CFG->item('index_page').
  443. $URI->uri_string;
  444. $filepath = $cache_path.md5($uri);
  445. if ( ! @file_exists($filepath))
  446. {
  447. return FALSE;
  448. }
  449. if ( ! $fp = @fopen($filepath, FOPEN_READ))
  450. {
  451. return FALSE;
  452. }
  453. flock($fp, LOCK_SH);
  454. $cache = '';
  455. if (filesize($filepath) > 0)
  456. {
  457. $cache = fread($fp, filesize($filepath));
  458. }
  459. flock($fp, LOCK_UN);
  460. fclose($fp);
  461. // Strip out the embedded timestamp
  462. if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
  463. {
  464. return FALSE;
  465. }
  466. // Has the file expired? If so we'll delete it.
  467. if (time() >= trim(str_replace('TS--->', '', $match['1'])))
  468. {
  469. if (is_really_writable($cache_path))
  470. {
  471. @unlink($filepath);
  472. log_message('debug', "Cache file has expired. File deleted");
  473. return FALSE;
  474. }
  475. }
  476. // Display the cache
  477. $this->_display(str_replace($match['0'], '', $cache));
  478. log_message('debug', "Cache file is current. Sending it to browser.");
  479. return TRUE;
  480. }
  481. }
  482. // END Output Class
  483. /* End of file Output.php */
  484. /* Location: ./system/core/Output.php */