blob: 76c1329d2996c706c5be73615c93625dce504381 [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 Andreev298e0052015-07-15 17:17:18 +0300559 if (($cache_query_string = $CI->config->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING']))
Andrey Andreeva704aa72014-12-04 12:37:07 +0200560 {
w0dendc29c6d2015-05-11 18:58:20 +0300561 if (is_array($cache_query_string))
562 {
563 $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string)));
564 }
565 else
566 {
567 $uri .= '?'.$_SERVER['QUERY_STRING'];
568 }
Andrey Andreeva704aa72014-12-04 12:37:07 +0200569 }
Stefano Mazzegaac41ca62014-12-03 11:55:47 +0100570
Michael Dodge362b8002013-01-04 23:18:39 -0700571 $cache_path .= md5($uri);
572
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200573 if ( ! $fp = @fopen($cache_path, 'w+b'))
Michael Dodge362b8002013-01-04 23:18:39 -0700574 {
575 log_message('error', 'Unable to write cache file: '.$cache_path);
576 return;
577 }
578
Michael Dodge362b8002013-01-04 23:18:39 -0700579 if (flock($fp, LOCK_EX))
580 {
Andrey Andreev155ee722014-01-10 15:50:54 +0200581 // If output compression is enabled, compress the cache
582 // itself, so that we don't have to do that each time
583 // we're serving it
584 if ($this->_compress_output === TRUE)
585 {
586 $output = gzencode($output);
587
588 if ($this->get_header('content-type') === NULL)
589 {
590 $this->set_content_type($this->mime_type);
591 }
592 }
593
594 $expire = time() + ($this->cache_expiration * 60);
595
596 // Put together our serialized info.
597 $cache_info = serialize(array(
598 'expire' => $expire,
599 'headers' => $this->headers
600 ));
601
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200602 $output = $cache_info.'ENDCI--->'.$output;
603
604 for ($written = 0, $length = strlen($output); $written < $length; $written += $result)
605 {
606 if (($result = fwrite($fp, substr($output, $written))) === FALSE)
607 {
608 break;
609 }
610 }
611
Michael Dodge362b8002013-01-04 23:18:39 -0700612 flock($fp, LOCK_UN);
613 }
614 else
615 {
616 log_message('error', 'Unable to secure a file lock for file at: '.$cache_path);
617 return;
618 }
Andrey Andreev155ee722014-01-10 15:50:54 +0200619
Michael Dodge362b8002013-01-04 23:18:39 -0700620 fclose($fp);
Michael Dodge362b8002013-01-04 23:18:39 -0700621
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200622 if (is_int($result))
623 {
Andrey Andreev45965742014-08-27 20:40:11 +0300624 chmod($cache_path, 0640);
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200625 log_message('debug', 'Cache file written: '.$cache_path);
Michael Dodge362b8002013-01-04 23:18:39 -0700626
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200627 // Send HTTP cache-control headers to browser to match file cache settings.
628 $this->set_cache_header($_SERVER['REQUEST_TIME'], $expire);
629 }
630 else
631 {
632 @unlink($cache_path);
633 log_message('error', 'Unable to write the complete cache content at: '.$cache_path);
634 }
Michael Dodge362b8002013-01-04 23:18:39 -0700635 }
636
637 // --------------------------------------------------------------------
638
639 /**
640 * Update/serve cached output
641 *
642 * @uses CI_Config
643 * @uses CI_URI
644 *
645 * @param object &$CFG CI_Config class instance
646 * @param object &$URI CI_URI class instance
647 * @return bool TRUE on success or FALSE on failure
648 */
649 public function _display_cache(&$CFG, &$URI)
650 {
651 $cache_path = ($CFG->item('cache_path') === '') ? APPPATH.'cache/' : $CFG->item('cache_path');
652
653 // Build the file path. The file name is an MD5 hash of the full URI
Andrey Andreev33572252014-12-03 20:19:38 +0200654 $uri = $CFG->item('base_url').$CFG->item('index_page').$URI->uri_string;
Andrey Andreeva704aa72014-12-04 12:37:07 +0200655
Andrey Andreev298e0052015-07-15 17:17:18 +0300656 if (($cache_query_string = $CFG->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING']))
Andrey Andreeva704aa72014-12-04 12:37:07 +0200657 {
w0dendc29c6d2015-05-11 18:58:20 +0300658 if (is_array($cache_query_string))
659 {
660 $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string)));
661 }
662 else
663 {
664 $uri .= '?'.$_SERVER['QUERY_STRING'];
665 }
Andrey Andreeva704aa72014-12-04 12:37:07 +0200666 }
Stefano Mazzegaac41ca62014-12-03 11:55:47 +0100667
Michael Dodge362b8002013-01-04 23:18:39 -0700668 $filepath = $cache_path.md5($uri);
669
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200670 if ( ! file_exists($filepath) OR ! $fp = @fopen($filepath, 'rb'))
Michael Dodge362b8002013-01-04 23:18:39 -0700671 {
672 return FALSE;
673 }
674
675 flock($fp, LOCK_SH);
676
677 $cache = (filesize($filepath) > 0) ? fread($fp, filesize($filepath)) : '';
678
679 flock($fp, LOCK_UN);
680 fclose($fp);
681
Eric Robertsc90e67e2013-01-11 21:20:54 -0600682 // Look for embedded serialized file info.
683 if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match))
Michael Dodge362b8002013-01-04 23:18:39 -0700684 {
685 return FALSE;
686 }
Purwandi5dc6d512013-01-19 17:43:08 +0700687
Eric Robertsc90e67e2013-01-11 21:20:54 -0600688 $cache_info = unserialize($match[1]);
689 $expire = $cache_info['expire'];
Michael Dodge362b8002013-01-04 23:18:39 -0700690
Ivan Tcholakovfd1bc222015-04-23 23:21:08 +0300691 $last_modified = filemtime($filepath);
Michael Dodge362b8002013-01-04 23:18:39 -0700692
693 // Has the file expired?
694 if ($_SERVER['REQUEST_TIME'] >= $expire && is_really_writable($cache_path))
695 {
696 // If so we'll delete it.
697 @unlink($filepath);
698 log_message('debug', 'Cache file has expired. File deleted.');
699 return FALSE;
700 }
701 else
702 {
703 // Or else send the HTTP cache control headers.
704 $this->set_cache_header($last_modified, $expire);
705 }
Purwandi5dc6d512013-01-19 17:43:08 +0700706
Eric Robertsc90e67e2013-01-11 21:20:54 -0600707 // Add headers from cache file.
708 foreach ($cache_info['headers'] as $header)
709 {
710 $this->set_header($header[0], $header[1]);
711 }
Michael Dodge362b8002013-01-04 23:18:39 -0700712
713 // Display the cache
714 $this->_display(substr($cache, strlen($match[0])));
715 log_message('debug', 'Cache file is current. Sending it to browser.');
716 return TRUE;
717 }
718
719 // --------------------------------------------------------------------
720
721 /**
722 * Delete cache
723 *
724 * @param string $uri URI string
725 * @return bool
726 */
727 public function delete_cache($uri = '')
728 {
729 $CI =& get_instance();
730 $cache_path = $CI->config->item('cache_path');
731 if ($cache_path === '')
732 {
733 $cache_path = APPPATH.'cache/';
734 }
735
736 if ( ! is_dir($cache_path))
737 {
738 log_message('error', 'Unable to find cache path: '.$cache_path);
739 return FALSE;
740 }
741
742 if (empty($uri))
743 {
744 $uri = $CI->uri->uri_string();
Andrey Andreeva704aa72014-12-04 12:37:07 +0200745
Andrey Andreev298e0052015-07-15 17:17:18 +0300746 if (($cache_query_string = $CI->config->item('cache_query_string')) && ! empty($_SERVER['QUERY_STRING']))
Andrey Andreeva704aa72014-12-04 12:37:07 +0200747 {
w0dendc29c6d2015-05-11 18:58:20 +0300748 if (is_array($cache_query_string))
749 {
750 $uri .= '?'.http_build_query(array_intersect_key($_GET, array_flip($cache_query_string)));
751 }
752 else
753 {
754 $uri .= '?'.$_SERVER['QUERY_STRING'];
755 }
Andrey Andreeva704aa72014-12-04 12:37:07 +0200756 }
Michael Dodge362b8002013-01-04 23:18:39 -0700757 }
758
w0den0b978dd2015-05-02 17:53:33 +0300759 $cache_path .= md5($CI->config->item('base_url').$CI->config->item('index_page').ltrim($uri, '/'));
Michael Dodge362b8002013-01-04 23:18:39 -0700760
761 if ( ! @unlink($cache_path))
762 {
763 log_message('error', 'Unable to delete cache file for '.$uri);
764 return FALSE;
765 }
766
767 return TRUE;
768 }
769
770 // --------------------------------------------------------------------
771
772 /**
773 * Set Cache Header
774 *
775 * Set the HTTP headers to match the server-side file cache settings
776 * in order to reduce bandwidth.
777 *
778 * @param int $last_modified Timestamp of when the page was last modified
779 * @param int $expiration Timestamp of when should the requested page expire from cache
780 * @return void
781 */
782 public function set_cache_header($last_modified, $expiration)
783 {
784 $max_age = $expiration - $_SERVER['REQUEST_TIME'];
785
786 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
787 {
788 $this->set_status_header(304);
789 exit;
790 }
791 else
792 {
793 header('Pragma: public');
Andrey Andreev3ca060a2013-11-27 16:30:31 +0200794 header('Cache-Control: max-age='.$max_age.', public');
Michael Dodge362b8002013-01-04 23:18:39 -0700795 header('Expires: '.gmdate('D, d M Y H:i:s', $expiration).' GMT');
796 header('Last-modified: '.gmdate('D, d M Y H:i:s', $last_modified).' GMT');
797 }
798 }
799
Michael Dodge362b8002013-01-04 23:18:39 -0700800}