blob: e7d559a1d6ae0d5e071df1b9ed42df78670edb5e [file] [log] [blame]
Michael Dodge362b8002013-01-04 23:18:39 -07001<?php
2/**
3 * CodeIgniter
4 *
Andrey Andreevfe9309d2015-01-09 17:48:58 +02005 * An open source application development framework for PHP
Michael Dodge362b8002013-01-04 23:18:39 -07006 *
Andrey Andreevbdb96ca2014-10-28 00:13:31 +02007 * This content is released under the MIT License (MIT)
Michael Dodge362b8002013-01-04 23:18:39 -07008 *
Andrey Andreevfe9309d2015-01-09 17:48:58 +02009 * Copyright (c) 2014 - 2015, British Columbia Institute of Technology
Michael Dodge362b8002013-01-04 23:18:39 -070010 *
Andrey Andreevbdb96ca2014-10-28 00:13:31 +020011 * Permission is hereby granted, free of charge, to any person obtaining a copy
12 * of this software and associated documentation files (the "Software"), to deal
13 * in the Software without restriction, including without limitation the rights
14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 * copies of the Software, and to permit persons to whom the Software is
16 * furnished to do so, subject to the following conditions:
Michael Dodge362b8002013-01-04 23:18:39 -070017 *
Andrey Andreevbdb96ca2014-10-28 00:13:31 +020018 * The above copyright notice and this permission notice shall be included in
19 * all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 * THE SOFTWARE.
28 *
29 * @package CodeIgniter
30 * @author EllisLab Dev Team
darwinel871754a2014-02-11 17:34:57 +010031 * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
Andrey Andreevfe9309d2015-01-09 17:48:58 +020032 * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
Andrey Andreevbdb96ca2014-10-28 00:13:31 +020033 * @license http://opensource.org/licenses/MIT MIT License
34 * @link http://codeigniter.com
35 * @since Version 1.0.0
Michael Dodge362b8002013-01-04 23:18:39 -070036 * @filesource
37 */
38defined('BASEPATH') OR exit('No direct script access allowed');
39
40/**
41 * Output Class
42 *
43 * Responsible for sending final output to the browser.
44 *
45 * @package CodeIgniter
46 * @subpackage Libraries
47 * @category Output
48 * @author EllisLab Dev Team
49 * @link http://codeigniter.com/user_guide/libraries/output.html
50 */
51class CI_Output {
52
53 /**
54 * Final output string
55 *
56 * @var string
57 */
58 public $final_output;
59
60 /**
61 * Cache expiration time
62 *
63 * @var int
64 */
65 public $cache_expiration = 0;
66
67 /**
68 * List of server headers
69 *
70 * @var array
71 */
Andrey Andreev155ee722014-01-10 15:50:54 +020072 public $headers = array();
Michael Dodge362b8002013-01-04 23:18:39 -070073
74 /**
75 * List of mime types
76 *
77 * @var array
78 */
Andrey Andreev155ee722014-01-10 15:50:54 +020079 public $mimes = array();
Michael Dodge362b8002013-01-04 23:18:39 -070080
81 /**
82 * Mime-type for the current page
83 *
84 * @var string
85 */
Andrey Andreev155ee722014-01-10 15:50:54 +020086 protected $mime_type = 'text/html';
Michael Dodge362b8002013-01-04 23:18:39 -070087
88 /**
89 * Enable Profiler flag
90 *
91 * @var bool
92 */
93 public $enable_profiler = FALSE;
94
95 /**
Andrey Andreev155ee722014-01-10 15:50:54 +020096 * php.ini zlib.output_compression flag
Michael Dodge362b8002013-01-04 23:18:39 -070097 *
98 * @var bool
99 */
Andrey Andreev155ee722014-01-10 15:50:54 +0200100 protected $_zlib_oc = FALSE;
101
102 /**
103 * CI output compression flag
104 *
105 * @var bool
106 */
107 protected $_compress_output = FALSE;
Michael Dodge362b8002013-01-04 23:18:39 -0700108
109 /**
110 * List of profiler sections
111 *
112 * @var array
113 */
Eric Roberts3e6b5822013-01-17 18:30:25 -0600114 protected $_profiler_sections = array();
Michael Dodge362b8002013-01-04 23:18:39 -0700115
116 /**
117 * Parse markers flag
118 *
119 * Whether or not to parse variables like {elapsed_time} and {memory_usage}.
120 *
121 * @var bool
122 */
Andrey Andreev155ee722014-01-10 15:50:54 +0200123 public $parse_exec_vars = TRUE;
Michael Dodge362b8002013-01-04 23:18:39 -0700124
125 /**
126 * Class constructor
127 *
128 * Determines whether zLib output compression will be used.
129 *
130 * @return void
131 */
132 public function __construct()
133 {
Andrey Andreevf6274742014-02-20 18:05:58 +0200134 $this->_zlib_oc = (bool) ini_get('zlib.output_compression');
Andrey Andreev155ee722014-01-10 15:50:54 +0200135 $this->_compress_output = (
136 $this->_zlib_oc === FALSE
Andrey Andreev9916bfc2014-01-10 16:21:07 +0200137 && config_item('compress_output') === TRUE
Andrey Andreev155ee722014-01-10 15:50:54 +0200138 && extension_loaded('zlib')
139 );
Michael Dodge362b8002013-01-04 23:18:39 -0700140
141 // Get mime types for later
142 $this->mimes =& get_mimes();
143
Andrey Andreev90726b82015-01-20 12:39:22 +0200144 log_message('info', 'Output Class Initialized');
Michael Dodge362b8002013-01-04 23:18:39 -0700145 }
146
147 // --------------------------------------------------------------------
148
149 /**
150 * Get Output
151 *
152 * Returns the current output string.
153 *
154 * @return string
155 */
156 public function get_output()
157 {
158 return $this->final_output;
159 }
160
161 // --------------------------------------------------------------------
162
163 /**
164 * Set Output
165 *
166 * Sets the output string.
167 *
168 * @param string $output Output data
169 * @return CI_Output
170 */
171 public function set_output($output)
172 {
173 $this->final_output = $output;
174 return $this;
175 }
176
177 // --------------------------------------------------------------------
178
179 /**
180 * Append Output
181 *
182 * Appends data onto the output string.
183 *
184 * @param string $output Data to append
185 * @return CI_Output
186 */
187 public function append_output($output)
188 {
Andrey Andreev2ab4ffb2014-02-24 16:15:09 +0200189 $this->final_output .= $output;
Michael Dodge362b8002013-01-04 23:18:39 -0700190 return $this;
191 }
192
193 // --------------------------------------------------------------------
194
195 /**
196 * Set Header
197 *
198 * Lets you set a server header which will be sent with the final output.
199 *
200 * Note: If a file is cached, headers will not be sent.
201 * @todo We need to figure out how to permit headers to be cached.
202 *
203 * @param string $header Header
204 * @param bool $replace Whether to replace the old header value, if already set
205 * @return CI_Output
206 */
207 public function set_header($header, $replace = TRUE)
208 {
209 // If zlib.output_compression is enabled it will compress the output,
210 // but it will not modify the content-length header to compensate for
211 // the reduction, causing the browser to hang waiting for more data.
212 // We'll just skip content-length in those cases.
213 if ($this->_zlib_oc && strncasecmp($header, 'content-length', 14) === 0)
214 {
215 return $this;
216 }
217
218 $this->headers[] = array($header, $replace);
219 return $this;
220 }
221
222 // --------------------------------------------------------------------
223
224 /**
225 * Set Content-Type Header
226 *
227 * @param string $mime_type Extension of the file we're outputting
228 * @param string $charset Character set (default: NULL)
229 * @return CI_Output
230 */
231 public function set_content_type($mime_type, $charset = NULL)
232 {
233 if (strpos($mime_type, '/') === FALSE)
234 {
235 $extension = ltrim($mime_type, '.');
236
237 // Is this extension supported?
238 if (isset($this->mimes[$extension]))
239 {
240 $mime_type =& $this->mimes[$extension];
241
242 if (is_array($mime_type))
243 {
244 $mime_type = current($mime_type);
245 }
246 }
247 }
248
249 $this->mime_type = $mime_type;
250
251 if (empty($charset))
252 {
253 $charset = config_item('charset');
254 }
255
256 $header = 'Content-Type: '.$mime_type
vlakoffd5ce5082014-04-25 10:13:04 +0200257 .(empty($charset) ? '' : '; charset='.$charset);
Michael Dodge362b8002013-01-04 23:18:39 -0700258
259 $this->headers[] = array($header, TRUE);
260 return $this;
261 }
262
263 // --------------------------------------------------------------------
264
265 /**
266 * Get Current Content-Type Header
267 *
268 * @return string 'text/html', if not already set
269 */
270 public function get_content_type()
271 {
272 for ($i = 0, $c = count($this->headers); $i < $c; $i++)
273 {
274 if (sscanf($this->headers[$i][0], 'Content-Type: %[^;]', $content_type) === 1)
275 {
276 return $content_type;
277 }
278 }
279
280 return 'text/html';
281 }
282
283 // --------------------------------------------------------------------
284
285 /**
286 * Get Header
287 *
288 * @param string $header_name
289 * @return string
290 */
291 public function get_header($header)
292 {
293 // Combine headers already sent with our batched headers
294 $headers = array_merge(
295 // We only need [x][0] from our multi-dimensional array
296 array_map('array_shift', $this->headers),
297 headers_list()
298 );
299
300 if (empty($headers) OR empty($header))
301 {
302 return NULL;
303 }
304
305 for ($i = 0, $c = count($headers); $i < $c; $i++)
306 {
307 if (strncasecmp($header, $headers[$i], $l = strlen($header)) === 0)
308 {
309 return trim(substr($headers[$i], $l+1));
310 }
311 }
312
313 return NULL;
314 }
315
316 // --------------------------------------------------------------------
317
318 /**
319 * Set HTTP Status Header
320 *
321 * As of version 1.7.2, this is an alias for common function
322 * set_status_header().
323 *
324 * @param int $code Status code (default: 200)
325 * @param string $text Optional message
326 * @return CI_Output
327 */
328 public function set_status_header($code = 200, $text = '')
329 {
330 set_status_header($code, $text);
331 return $this;
332 }
333
334 // --------------------------------------------------------------------
335
336 /**
337 * Enable/disable Profiler
338 *
339 * @param bool $val TRUE to enable or FALSE to disable
340 * @return CI_Output
341 */
342 public function enable_profiler($val = TRUE)
343 {
344 $this->enable_profiler = is_bool($val) ? $val : TRUE;
345 return $this;
346 }
347
348 // --------------------------------------------------------------------
349
350 /**
351 * Set Profiler Sections
352 *
353 * Allows override of default/config settings for
354 * Profiler section display.
355 *
356 * @param array $sections Profiler sections
357 * @return CI_Output
358 */
359 public function set_profiler_sections($sections)
360 {
361 if (isset($sections['query_toggle_count']))
362 {
363 $this->_profiler_sections['query_toggle_count'] = (int) $sections['query_toggle_count'];
364 unset($sections['query_toggle_count']);
365 }
366
367 foreach ($sections as $section => $enable)
368 {
369 $this->_profiler_sections[$section] = ($enable !== FALSE);
370 }
371
372 return $this;
373 }
374
375 // --------------------------------------------------------------------
376
377 /**
378 * Set Cache
379 *
380 * @param int $time Cache expiration time in seconds
381 * @return CI_Output
382 */
383 public function cache($time)
384 {
385 $this->cache_expiration = is_numeric($time) ? $time : 0;
386 return $this;
387 }
388
389 // --------------------------------------------------------------------
390
391 /**
392 * Display Output
393 *
natepizzle21432ab2015-02-03 16:25:42 -0600394 * Processes and sends finalized output data to the browser along
Michael Dodge362b8002013-01-04 23:18:39 -0700395 * with any server headers and profile data. It also stops benchmark
396 * timers so the page rendering speed and memory usage can be shown.
397 *
398 * Note: All "view" data is automatically put into $this->final_output
399 * by controller class.
400 *
401 * @uses CI_Output::$final_output
402 * @param string $output Output data override
403 * @return void
404 */
405 public function _display($output = '')
406 {
Andrey Andreevc26b9eb2014-02-24 11:31:36 +0200407 // Note: We use load_class() because we can't use $CI =& get_instance()
Michael Dodge362b8002013-01-04 23:18:39 -0700408 // since this function is sometimes called by the caching mechanism,
409 // which happens before the CI super object is available.
Andrey Andreevc26b9eb2014-02-24 11:31:36 +0200410 $BM =& load_class('Benchmark', 'core');
411 $CFG =& load_class('Config', 'core');
Michael Dodge362b8002013-01-04 23:18:39 -0700412
413 // Grab the super object if we can.
Andrey Andreev49e68de2013-02-21 16:30:55 +0200414 if (class_exists('CI_Controller', FALSE))
Michael Dodge362b8002013-01-04 23:18:39 -0700415 {
416 $CI =& get_instance();
417 }
418
419 // --------------------------------------------------------------------
420
421 // Set the output data
422 if ($output === '')
423 {
424 $output =& $this->final_output;
425 }
426
427 // --------------------------------------------------------------------
428
Michael Dodge362b8002013-01-04 23:18:39 -0700429 // Do we need to write a cache file? Only if the controller does not have its
430 // own _output() method and we are not dealing with a cache file, which we
431 // can determine by the existence of the $CI object above
432 if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
433 {
434 $this->_write_cache($output);
435 }
436
437 // --------------------------------------------------------------------
438
439 // Parse out the elapsed time and memory usage,
440 // then swap the pseudo-variables with the data
441
442 $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
443
444 if ($this->parse_exec_vars === TRUE)
445 {
446 $memory = round(memory_get_usage() / 1024 / 1024, 2).'MB';
Michael Dodge362b8002013-01-04 23:18:39 -0700447 $output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);
448 }
449
450 // --------------------------------------------------------------------
451
452 // Is compression requested?
Andrey Andreev155ee722014-01-10 15:50:54 +0200453 if (isset($CI) // This means that we're not serving a cache file, if we were, it would already be compressed
454 && $this->_compress_output === TRUE
Michael Dodge362b8002013-01-04 23:18:39 -0700455 && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
456 {
457 ob_start('ob_gzhandler');
458 }
459
460 // --------------------------------------------------------------------
461
462 // Are there any server headers to send?
463 if (count($this->headers) > 0)
464 {
465 foreach ($this->headers as $header)
466 {
467 @header($header[0], $header[1]);
468 }
469 }
470
471 // --------------------------------------------------------------------
472
473 // Does the $CI object exist?
474 // If not we know we are dealing with a cache file so we'll
475 // simply echo out the data and exit.
476 if ( ! isset($CI))
477 {
Andrey Andreev155ee722014-01-10 15:50:54 +0200478 if ($this->_compress_output === TRUE)
479 {
480 if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
481 {
482 header('Content-Encoding: gzip');
483 header('Content-Length: '.strlen($output));
484 }
485 else
486 {
487 // User agent doesn't support gzip compression,
488 // so we'll have to decompress our cache
489 $output = gzinflate(substr($output, 10, -8));
490 }
491 }
492
Michael Dodge362b8002013-01-04 23:18:39 -0700493 echo $output;
Andrey Andreev90726b82015-01-20 12:39:22 +0200494 log_message('info', 'Final output sent to browser');
Michael Dodge362b8002013-01-04 23:18:39 -0700495 log_message('debug', 'Total execution time: '.$elapsed);
496 return;
497 }
498
499 // --------------------------------------------------------------------
500
501 // Do we need to generate profile data?
502 // If so, load the Profile class and run it.
503 if ($this->enable_profiler === TRUE)
504 {
505 $CI->load->library('profiler');
506 if ( ! empty($this->_profiler_sections))
507 {
508 $CI->profiler->set_sections($this->_profiler_sections);
509 }
510
511 // If the output data contains closing </body> and </html> tags
512 // we will remove them and add them back after we insert the profile data
513 $output = preg_replace('|</body>.*?</html>|is', '', $output, -1, $count).$CI->profiler->run();
514 if ($count > 0)
515 {
516 $output .= '</body></html>';
517 }
518 }
519
520 // Does the controller contain a function named _output()?
521 // If so send the output there. Otherwise, echo it.
522 if (method_exists($CI, '_output'))
523 {
524 $CI->_output($output);
525 }
526 else
527 {
528 echo $output; // Send it to the browser!
529 }
530
Andrey Andreev90726b82015-01-20 12:39:22 +0200531 log_message('info', 'Final output sent to browser');
Michael Dodge362b8002013-01-04 23:18:39 -0700532 log_message('debug', 'Total execution time: '.$elapsed);
533 }
534
535 // --------------------------------------------------------------------
536
537 /**
538 * Write Cache
539 *
540 * @param string $output Output data to cache
541 * @return void
542 */
543 public function _write_cache($output)
544 {
545 $CI =& get_instance();
546 $path = $CI->config->item('cache_path');
547 $cache_path = ($path === '') ? APPPATH.'cache/' : $path;
548
549 if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
550 {
551 log_message('error', 'Unable to write cache file: '.$cache_path);
552 return;
553 }
554
Andrey Andreev155ee722014-01-10 15:50:54 +0200555 $uri = $CI->config->item('base_url')
556 .$CI->config->item('index_page')
557 .$CI->uri->uri_string();
Michael Dodge362b8002013-01-04 23:18:39 -0700558
Andrey Andreeva704aa72014-12-04 12:37:07 +0200559 if ($CI->config->item('cache_query_string') && ! empty($_SERVER['QUERY_STRING']))
560 {
561 $uri .= '?'.$_SERVER['QUERY_STRING'];
562 }
Stefano Mazzegaac41ca62014-12-03 11:55:47 +0100563
Michael Dodge362b8002013-01-04 23:18:39 -0700564 $cache_path .= md5($uri);
565
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200566 if ( ! $fp = @fopen($cache_path, 'w+b'))
Michael Dodge362b8002013-01-04 23:18:39 -0700567 {
568 log_message('error', 'Unable to write cache file: '.$cache_path);
569 return;
570 }
571
Michael Dodge362b8002013-01-04 23:18:39 -0700572 if (flock($fp, LOCK_EX))
573 {
Andrey Andreev155ee722014-01-10 15:50:54 +0200574 // If output compression is enabled, compress the cache
575 // itself, so that we don't have to do that each time
576 // we're serving it
577 if ($this->_compress_output === TRUE)
578 {
579 $output = gzencode($output);
580
581 if ($this->get_header('content-type') === NULL)
582 {
583 $this->set_content_type($this->mime_type);
584 }
585 }
586
587 $expire = time() + ($this->cache_expiration * 60);
588
589 // Put together our serialized info.
590 $cache_info = serialize(array(
591 'expire' => $expire,
592 'headers' => $this->headers
593 ));
594
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200595 $output = $cache_info.'ENDCI--->'.$output;
596
597 for ($written = 0, $length = strlen($output); $written < $length; $written += $result)
598 {
599 if (($result = fwrite($fp, substr($output, $written))) === FALSE)
600 {
601 break;
602 }
603 }
604
Michael Dodge362b8002013-01-04 23:18:39 -0700605 flock($fp, LOCK_UN);
606 }
607 else
608 {
609 log_message('error', 'Unable to secure a file lock for file at: '.$cache_path);
610 return;
611 }
Andrey Andreev155ee722014-01-10 15:50:54 +0200612
Michael Dodge362b8002013-01-04 23:18:39 -0700613 fclose($fp);
Michael Dodge362b8002013-01-04 23:18:39 -0700614
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200615 if (is_int($result))
616 {
Andrey Andreev45965742014-08-27 20:40:11 +0300617 chmod($cache_path, 0640);
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200618 log_message('debug', 'Cache file written: '.$cache_path);
Michael Dodge362b8002013-01-04 23:18:39 -0700619
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200620 // Send HTTP cache-control headers to browser to match file cache settings.
621 $this->set_cache_header($_SERVER['REQUEST_TIME'], $expire);
622 }
623 else
624 {
625 @unlink($cache_path);
626 log_message('error', 'Unable to write the complete cache content at: '.$cache_path);
627 }
Michael Dodge362b8002013-01-04 23:18:39 -0700628 }
629
630 // --------------------------------------------------------------------
631
632 /**
633 * Update/serve cached output
634 *
635 * @uses CI_Config
636 * @uses CI_URI
637 *
638 * @param object &$CFG CI_Config class instance
639 * @param object &$URI CI_URI class instance
640 * @return bool TRUE on success or FALSE on failure
641 */
642 public function _display_cache(&$CFG, &$URI)
643 {
644 $cache_path = ($CFG->item('cache_path') === '') ? APPPATH.'cache/' : $CFG->item('cache_path');
645
646 // Build the file path. The file name is an MD5 hash of the full URI
Andrey Andreev33572252014-12-03 20:19:38 +0200647 $uri = $CFG->item('base_url').$CFG->item('index_page').$URI->uri_string;
Andrey Andreeva704aa72014-12-04 12:37:07 +0200648
649 if ($CFG->item('cache_query_string') && ! empty($_SERVER['QUERY_STRING']))
650 {
651 $uri .= '?'.$_SERVER['QUERY_STRING'];
652 }
Stefano Mazzegaac41ca62014-12-03 11:55:47 +0100653
Michael Dodge362b8002013-01-04 23:18:39 -0700654 $filepath = $cache_path.md5($uri);
655
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200656 if ( ! file_exists($filepath) OR ! $fp = @fopen($filepath, 'rb'))
Michael Dodge362b8002013-01-04 23:18:39 -0700657 {
658 return FALSE;
659 }
660
661 flock($fp, LOCK_SH);
662
663 $cache = (filesize($filepath) > 0) ? fread($fp, filesize($filepath)) : '';
664
665 flock($fp, LOCK_UN);
666 fclose($fp);
667
Eric Robertsc90e67e2013-01-11 21:20:54 -0600668 // Look for embedded serialized file info.
669 if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match))
Michael Dodge362b8002013-01-04 23:18:39 -0700670 {
671 return FALSE;
672 }
Purwandi5dc6d512013-01-19 17:43:08 +0700673
Eric Robertsc90e67e2013-01-11 21:20:54 -0600674 $cache_info = unserialize($match[1]);
675 $expire = $cache_info['expire'];
Michael Dodge362b8002013-01-04 23:18:39 -0700676
Ivan Tcholakovfd1bc222015-04-23 23:21:08 +0300677 $last_modified = filemtime($filepath);
Michael Dodge362b8002013-01-04 23:18:39 -0700678
679 // Has the file expired?
680 if ($_SERVER['REQUEST_TIME'] >= $expire && is_really_writable($cache_path))
681 {
682 // If so we'll delete it.
683 @unlink($filepath);
684 log_message('debug', 'Cache file has expired. File deleted.');
685 return FALSE;
686 }
687 else
688 {
689 // Or else send the HTTP cache control headers.
690 $this->set_cache_header($last_modified, $expire);
691 }
Purwandi5dc6d512013-01-19 17:43:08 +0700692
Eric Robertsc90e67e2013-01-11 21:20:54 -0600693 // Add headers from cache file.
694 foreach ($cache_info['headers'] as $header)
695 {
696 $this->set_header($header[0], $header[1]);
697 }
Michael Dodge362b8002013-01-04 23:18:39 -0700698
699 // Display the cache
700 $this->_display(substr($cache, strlen($match[0])));
701 log_message('debug', 'Cache file is current. Sending it to browser.');
702 return TRUE;
703 }
704
705 // --------------------------------------------------------------------
706
707 /**
708 * Delete cache
709 *
710 * @param string $uri URI string
711 * @return bool
712 */
713 public function delete_cache($uri = '')
714 {
715 $CI =& get_instance();
716 $cache_path = $CI->config->item('cache_path');
717 if ($cache_path === '')
718 {
719 $cache_path = APPPATH.'cache/';
720 }
721
722 if ( ! is_dir($cache_path))
723 {
724 log_message('error', 'Unable to find cache path: '.$cache_path);
725 return FALSE;
726 }
727
728 if (empty($uri))
729 {
730 $uri = $CI->uri->uri_string();
Andrey Andreeva704aa72014-12-04 12:37:07 +0200731
732 if ($CI->config->item('cache_query_string') && ! empty($_SERVER['QUERY_STRING']))
733 {
734 $uri .= '?'.$_SERVER['QUERY_STRING'];
735 }
Michael Dodge362b8002013-01-04 23:18:39 -0700736 }
737
738 $cache_path .= md5($CI->config->item('base_url').$CI->config->item('index_page').$uri);
739
740 if ( ! @unlink($cache_path))
741 {
742 log_message('error', 'Unable to delete cache file for '.$uri);
743 return FALSE;
744 }
745
746 return TRUE;
747 }
748
749 // --------------------------------------------------------------------
750
751 /**
752 * Set Cache Header
753 *
754 * Set the HTTP headers to match the server-side file cache settings
755 * in order to reduce bandwidth.
756 *
757 * @param int $last_modified Timestamp of when the page was last modified
758 * @param int $expiration Timestamp of when should the requested page expire from cache
759 * @return void
760 */
761 public function set_cache_header($last_modified, $expiration)
762 {
763 $max_age = $expiration - $_SERVER['REQUEST_TIME'];
764
765 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
766 {
767 $this->set_status_header(304);
768 exit;
769 }
770 else
771 {
772 header('Pragma: public');
Andrey Andreev3ca060a2013-11-27 16:30:31 +0200773 header('Cache-Control: max-age='.$max_age.', public');
Michael Dodge362b8002013-01-04 23:18:39 -0700774 header('Expires: '.gmdate('D, d M Y H:i:s', $expiration).' GMT');
775 header('Last-modified: '.gmdate('D, d M Y H:i:s', $last_modified).' GMT');
776 }
777 }
778
Michael Dodge362b8002013-01-04 23:18:39 -0700779}