blob: 4743690c9961f5f2d203a0aaa38d46fac5936486 [file] [log] [blame]
Michael Dodge362b8002013-01-04 23:18:39 -07001<?php
2/**
3 * CodeIgniter
4 *
5 * An open source application development framework for PHP 5.2.4 or newer
6 *
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 Andreevbdb96ca2014-10-28 00:13:31 +02009 * Copyright (c) 2014, 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 Andreevbdb96ca2014-10-28 00:13:31 +020032 * @copyright Copyright (c) 2014, British Columbia Institute of Technology (http://bcit.ca/)
33 * @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
144 log_message('debug', 'Output Class Initialized');
145 }
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 *
394 * Processes sends the sends finalized output data to the browser along
395 * 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
429 // Is minify requested?
430 if ($CFG->item('minify_output') === TRUE)
431 {
432 $output = $this->minify($output, $this->mime_type);
433 }
434
435 // --------------------------------------------------------------------
436
437 // Do we need to write a cache file? Only if the controller does not have its
438 // own _output() method and we are not dealing with a cache file, which we
439 // can determine by the existence of the $CI object above
440 if ($this->cache_expiration > 0 && isset($CI) && ! method_exists($CI, '_output'))
441 {
442 $this->_write_cache($output);
443 }
444
445 // --------------------------------------------------------------------
446
447 // Parse out the elapsed time and memory usage,
448 // then swap the pseudo-variables with the data
449
450 $elapsed = $BM->elapsed_time('total_execution_time_start', 'total_execution_time_end');
451
452 if ($this->parse_exec_vars === TRUE)
453 {
454 $memory = round(memory_get_usage() / 1024 / 1024, 2).'MB';
Michael Dodge362b8002013-01-04 23:18:39 -0700455 $output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);
456 }
457
458 // --------------------------------------------------------------------
459
460 // Is compression requested?
Andrey Andreev155ee722014-01-10 15:50:54 +0200461 if (isset($CI) // This means that we're not serving a cache file, if we were, it would already be compressed
462 && $this->_compress_output === TRUE
Michael Dodge362b8002013-01-04 23:18:39 -0700463 && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
464 {
465 ob_start('ob_gzhandler');
466 }
467
468 // --------------------------------------------------------------------
469
470 // Are there any server headers to send?
471 if (count($this->headers) > 0)
472 {
473 foreach ($this->headers as $header)
474 {
475 @header($header[0], $header[1]);
476 }
477 }
478
479 // --------------------------------------------------------------------
480
481 // Does the $CI object exist?
482 // If not we know we are dealing with a cache file so we'll
483 // simply echo out the data and exit.
484 if ( ! isset($CI))
485 {
Andrey Andreev155ee722014-01-10 15:50:54 +0200486 if ($this->_compress_output === TRUE)
487 {
488 if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
489 {
490 header('Content-Encoding: gzip');
491 header('Content-Length: '.strlen($output));
492 }
493 else
494 {
495 // User agent doesn't support gzip compression,
496 // so we'll have to decompress our cache
497 $output = gzinflate(substr($output, 10, -8));
498 }
499 }
500
Michael Dodge362b8002013-01-04 23:18:39 -0700501 echo $output;
502 log_message('debug', 'Final output sent to browser');
503 log_message('debug', 'Total execution time: '.$elapsed);
504 return;
505 }
506
507 // --------------------------------------------------------------------
508
509 // Do we need to generate profile data?
510 // If so, load the Profile class and run it.
511 if ($this->enable_profiler === TRUE)
512 {
513 $CI->load->library('profiler');
514 if ( ! empty($this->_profiler_sections))
515 {
516 $CI->profiler->set_sections($this->_profiler_sections);
517 }
518
519 // If the output data contains closing </body> and </html> tags
520 // we will remove them and add them back after we insert the profile data
521 $output = preg_replace('|</body>.*?</html>|is', '', $output, -1, $count).$CI->profiler->run();
522 if ($count > 0)
523 {
524 $output .= '</body></html>';
525 }
526 }
527
528 // Does the controller contain a function named _output()?
529 // If so send the output there. Otherwise, echo it.
530 if (method_exists($CI, '_output'))
531 {
532 $CI->_output($output);
533 }
534 else
535 {
536 echo $output; // Send it to the browser!
537 }
538
539 log_message('debug', 'Final output sent to browser');
540 log_message('debug', 'Total execution time: '.$elapsed);
541 }
542
543 // --------------------------------------------------------------------
544
545 /**
546 * Write Cache
547 *
548 * @param string $output Output data to cache
549 * @return void
550 */
551 public function _write_cache($output)
552 {
553 $CI =& get_instance();
554 $path = $CI->config->item('cache_path');
555 $cache_path = ($path === '') ? APPPATH.'cache/' : $path;
556
557 if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
558 {
559 log_message('error', 'Unable to write cache file: '.$cache_path);
560 return;
561 }
562
Andrey Andreev155ee722014-01-10 15:50:54 +0200563 $uri = $CI->config->item('base_url')
564 .$CI->config->item('index_page')
565 .$CI->uri->uri_string();
Michael Dodge362b8002013-01-04 23:18:39 -0700566
Stefano Mazzegaac41ca62014-12-03 11:55:47 +0100567 // append querystring
568 $uri .= (empty($_SERVER['QUERY_STRING'])) ? '' : '?' . $_SERVER['QUERY_STRING'];
569
Michael Dodge362b8002013-01-04 23:18:39 -0700570 $cache_path .= md5($uri);
571
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200572 if ( ! $fp = @fopen($cache_path, 'w+b'))
Michael Dodge362b8002013-01-04 23:18:39 -0700573 {
574 log_message('error', 'Unable to write cache file: '.$cache_path);
575 return;
576 }
577
Michael Dodge362b8002013-01-04 23:18:39 -0700578 if (flock($fp, LOCK_EX))
579 {
Andrey Andreev155ee722014-01-10 15:50:54 +0200580 // If output compression is enabled, compress the cache
581 // itself, so that we don't have to do that each time
582 // we're serving it
583 if ($this->_compress_output === TRUE)
584 {
585 $output = gzencode($output);
586
587 if ($this->get_header('content-type') === NULL)
588 {
589 $this->set_content_type($this->mime_type);
590 }
591 }
592
593 $expire = time() + ($this->cache_expiration * 60);
594
595 // Put together our serialized info.
596 $cache_info = serialize(array(
597 'expire' => $expire,
598 'headers' => $this->headers
599 ));
600
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200601 $output = $cache_info.'ENDCI--->'.$output;
602
603 for ($written = 0, $length = strlen($output); $written < $length; $written += $result)
604 {
605 if (($result = fwrite($fp, substr($output, $written))) === FALSE)
606 {
607 break;
608 }
609 }
610
Michael Dodge362b8002013-01-04 23:18:39 -0700611 flock($fp, LOCK_UN);
612 }
613 else
614 {
615 log_message('error', 'Unable to secure a file lock for file at: '.$cache_path);
616 return;
617 }
Andrey Andreev155ee722014-01-10 15:50:54 +0200618
Michael Dodge362b8002013-01-04 23:18:39 -0700619 fclose($fp);
Michael Dodge362b8002013-01-04 23:18:39 -0700620
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200621 if (is_int($result))
622 {
Andrey Andreev45965742014-08-27 20:40:11 +0300623 chmod($cache_path, 0640);
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200624 log_message('debug', 'Cache file written: '.$cache_path);
Michael Dodge362b8002013-01-04 23:18:39 -0700625
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200626 // Send HTTP cache-control headers to browser to match file cache settings.
627 $this->set_cache_header($_SERVER['REQUEST_TIME'], $expire);
628 }
629 else
630 {
631 @unlink($cache_path);
632 log_message('error', 'Unable to write the complete cache content at: '.$cache_path);
633 }
Michael Dodge362b8002013-01-04 23:18:39 -0700634 }
635
636 // --------------------------------------------------------------------
637
638 /**
639 * Update/serve cached output
640 *
641 * @uses CI_Config
642 * @uses CI_URI
643 *
644 * @param object &$CFG CI_Config class instance
645 * @param object &$URI CI_URI class instance
646 * @return bool TRUE on success or FALSE on failure
647 */
648 public function _display_cache(&$CFG, &$URI)
649 {
650 $cache_path = ($CFG->item('cache_path') === '') ? APPPATH.'cache/' : $CFG->item('cache_path');
651
652 // Build the file path. The file name is an MD5 hash of the full URI
653 $uri = $CFG->item('base_url').$CFG->item('index_page').$URI->uri_string;
Stefano Mazzegaac41ca62014-12-03 11:55:47 +0100654 // append querystring
655 $uri .= (empty($_SERVER['QUERY_STRING'])) ? '' : '?' . $_SERVER['QUERY_STRING'];
656
Michael Dodge362b8002013-01-04 23:18:39 -0700657 $filepath = $cache_path.md5($uri);
658
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200659 if ( ! file_exists($filepath) OR ! $fp = @fopen($filepath, 'rb'))
Michael Dodge362b8002013-01-04 23:18:39 -0700660 {
661 return FALSE;
662 }
663
664 flock($fp, LOCK_SH);
665
666 $cache = (filesize($filepath) > 0) ? fread($fp, filesize($filepath)) : '';
667
668 flock($fp, LOCK_UN);
669 fclose($fp);
670
Eric Robertsc90e67e2013-01-11 21:20:54 -0600671 // Look for embedded serialized file info.
672 if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match))
Michael Dodge362b8002013-01-04 23:18:39 -0700673 {
674 return FALSE;
675 }
Purwandi5dc6d512013-01-19 17:43:08 +0700676
Eric Robertsc90e67e2013-01-11 21:20:54 -0600677 $cache_info = unserialize($match[1]);
678 $expire = $cache_info['expire'];
Michael Dodge362b8002013-01-04 23:18:39 -0700679
680 $last_modified = filemtime($cache_path);
Michael Dodge362b8002013-01-04 23:18:39 -0700681
682 // Has the file expired?
683 if ($_SERVER['REQUEST_TIME'] >= $expire && is_really_writable($cache_path))
684 {
685 // If so we'll delete it.
686 @unlink($filepath);
687 log_message('debug', 'Cache file has expired. File deleted.');
688 return FALSE;
689 }
690 else
691 {
692 // Or else send the HTTP cache control headers.
693 $this->set_cache_header($last_modified, $expire);
694 }
Purwandi5dc6d512013-01-19 17:43:08 +0700695
Eric Robertsc90e67e2013-01-11 21:20:54 -0600696 // Add headers from cache file.
697 foreach ($cache_info['headers'] as $header)
698 {
699 $this->set_header($header[0], $header[1]);
700 }
Michael Dodge362b8002013-01-04 23:18:39 -0700701
702 // Display the cache
703 $this->_display(substr($cache, strlen($match[0])));
704 log_message('debug', 'Cache file is current. Sending it to browser.');
705 return TRUE;
706 }
707
708 // --------------------------------------------------------------------
709
710 /**
711 * Delete cache
712 *
713 * @param string $uri URI string
714 * @return bool
715 */
716 public function delete_cache($uri = '')
717 {
718 $CI =& get_instance();
719 $cache_path = $CI->config->item('cache_path');
720 if ($cache_path === '')
721 {
722 $cache_path = APPPATH.'cache/';
723 }
724
725 if ( ! is_dir($cache_path))
726 {
727 log_message('error', 'Unable to find cache path: '.$cache_path);
728 return FALSE;
729 }
730
731 if (empty($uri))
732 {
733 $uri = $CI->uri->uri_string();
734 }
735
Stefano Mazzegaac41ca62014-12-03 11:55:47 +0100736 // append querystring
737 $uri .= (empty($_SERVER['QUERY_STRING'])) ? '' : '?' . $_SERVER['QUERY_STRING'];
738
Michael Dodge362b8002013-01-04 23:18:39 -0700739 $cache_path .= md5($CI->config->item('base_url').$CI->config->item('index_page').$uri);
740
741 if ( ! @unlink($cache_path))
742 {
743 log_message('error', 'Unable to delete cache file for '.$uri);
744 return FALSE;
745 }
746
747 return TRUE;
748 }
749
750 // --------------------------------------------------------------------
751
752 /**
753 * Set Cache Header
754 *
755 * Set the HTTP headers to match the server-side file cache settings
756 * in order to reduce bandwidth.
757 *
758 * @param int $last_modified Timestamp of when the page was last modified
759 * @param int $expiration Timestamp of when should the requested page expire from cache
760 * @return void
761 */
762 public function set_cache_header($last_modified, $expiration)
763 {
764 $max_age = $expiration - $_SERVER['REQUEST_TIME'];
765
766 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
767 {
768 $this->set_status_header(304);
769 exit;
770 }
771 else
772 {
773 header('Pragma: public');
Andrey Andreev3ca060a2013-11-27 16:30:31 +0200774 header('Cache-Control: max-age='.$max_age.', public');
Michael Dodge362b8002013-01-04 23:18:39 -0700775 header('Expires: '.gmdate('D, d M Y H:i:s', $expiration).' GMT');
776 header('Last-modified: '.gmdate('D, d M Y H:i:s', $last_modified).' GMT');
777 }
778 }
779
780 // --------------------------------------------------------------------
781
782 /**
783 * Minify
784 *
785 * Reduce excessive size of HTML/CSS/JavaScript content.
786 *
787 * @param string $output Output to minify
788 * @param string $type Output content MIME type
789 * @return string Minified output
790 */
791 public function minify($output, $type = 'text/html')
792 {
793 switch ($type)
794 {
795 case 'text/html':
796
797 if (($size_before = strlen($output)) === 0)
798 {
799 return '';
800 }
801
802 // Find all the <pre>,<code>,<textarea>, and <javascript> tags
803 // We'll want to return them to this unprocessed state later.
804 preg_match_all('{<pre.+</pre>}msU', $output, $pres_clean);
805 preg_match_all('{<code.+</code>}msU', $output, $codes_clean);
806 preg_match_all('{<textarea.+</textarea>}msU', $output, $textareas_clean);
807 preg_match_all('{<script.+</script>}msU', $output, $javascript_clean);
808
809 // Minify the CSS in all the <style> tags.
810 preg_match_all('{<style.+</style>}msU', $output, $style_clean);
811 foreach ($style_clean[0] as $s)
812 {
Andrey Andreev6a424902013-10-28 14:16:18 +0200813 $output = str_replace($s, $this->_minify_js_css($s, 'css', TRUE), $output);
Michael Dodge362b8002013-01-04 23:18:39 -0700814 }
815
816 // Minify the javascript in <script> tags.
817 foreach ($javascript_clean[0] as $s)
818 {
Andrey Andreev6a424902013-10-28 14:16:18 +0200819 $javascript_mini[] = $this->_minify_js_css($s, 'js', TRUE);
Michael Dodge362b8002013-01-04 23:18:39 -0700820 }
821
822 // Replace multiple spaces with a single space.
823 $output = preg_replace('!\s{2,}!', ' ', $output);
824
825 // Remove comments (non-MSIE conditionals)
Michael Dodge4d02e352013-01-04 23:22:51 -0700826 $output = preg_replace('{\s*<!--[^\[<>].*(?<!!)-->\s*}msU', '', $output);
Michael Dodge362b8002013-01-04 23:18:39 -0700827
828 // Remove spaces around block-level elements.
Purwandi5dc6d512013-01-19 17:43:08 +0700829 $output = preg_replace('/\s*(<\/?(html|head|title|meta|script|link|style|body|table|thead|tbody|tfoot|tr|th|td|h[1-6]|div|p|br)[^>]*>)\s*/is', '$1', $output);
Michael Dodge362b8002013-01-04 23:18:39 -0700830
831 // Replace mangled <pre> etc. tags with unprocessed ones.
832
833 if ( ! empty($pres_clean))
834 {
835 preg_match_all('{<pre.+</pre>}msU', $output, $pres_messed);
836 $output = str_replace($pres_messed[0], $pres_clean[0], $output);
837 }
838
839 if ( ! empty($codes_clean))
840 {
841 preg_match_all('{<code.+</code>}msU', $output, $codes_messed);
842 $output = str_replace($codes_messed[0], $codes_clean[0], $output);
843 }
844
Andrey Andreev3ffce982013-01-21 15:24:09 +0200845 if ( ! empty($textareas_clean))
Michael Dodge362b8002013-01-04 23:18:39 -0700846 {
847 preg_match_all('{<textarea.+</textarea>}msU', $output, $textareas_messed);
848 $output = str_replace($textareas_messed[0], $textareas_clean[0], $output);
849 }
850
851 if (isset($javascript_mini))
852 {
853 preg_match_all('{<script.+</script>}msU', $output, $javascript_messed);
854 $output = str_replace($javascript_messed[0], $javascript_mini, $output);
855 }
856
857 $size_removed = $size_before - strlen($output);
858 $savings_percent = round(($size_removed / $size_before * 100));
859
860 log_message('debug', 'Minifier shaved '.($size_removed / 1000).'KB ('.$savings_percent.'%) off final HTML output.');
861
862 break;
863
864 case 'text/css':
Andrey Andreev6a424902013-10-28 14:16:18 +0200865
866 return $this->_minify_js_css($output, 'css');
867
Michael Dodge362b8002013-01-04 23:18:39 -0700868 case 'text/javascript':
bayssmekanique7b903252013-03-12 13:25:24 -0700869 case 'application/javascript':
870 case 'application/x-javascript':
Michael Dodge362b8002013-01-04 23:18:39 -0700871
Andrey Andreev6a424902013-10-28 14:16:18 +0200872 return $this->_minify_js_css($output, 'js');
Michael Dodge362b8002013-01-04 23:18:39 -0700873
874 default: break;
875 }
876
877 return $output;
878 }
879
880 // --------------------------------------------------------------------
881
Andrey Andreev3c3bbac2013-10-31 15:10:49 +0200882 /**
883 * Minify JavaScript and CSS code
884 *
885 * Strips comments and excessive whitespace characters
886 *
887 * @param string $output
888 * @param string $type 'js' or 'css'
889 * @param bool $tags Whether $output contains the 'script' or 'style' tag
890 * @return string
891 */
Andrey Andreev6a424902013-10-28 14:16:18 +0200892 protected function _minify_js_css($output, $type, $tags = FALSE)
893 {
894 if ($tags === TRUE)
895 {
896 $tags = array('close' => strrchr($output, '<'));
897
898 $open_length = strpos($output, '>') + 1;
899 $tags['open'] = substr($output, 0, $open_length);
900
901 $output = substr($output, $open_length, -strlen($tags['close']));
902
903 // Strip spaces from the tags
904 $tags = preg_replace('#\s{2,}#', ' ', $tags);
905 }
906
907 $output = trim($output);
908
909 if ($type === 'js')
910 {
911 // Catch all string literals and comment blocks
Andrey Andreev0949b362013-10-31 16:07:40 +0200912 if (preg_match_all('#((?:((?<!\\\)\'|")|(/\*)|(//)).*(?(2)(?<!\\\)\2|(?(3)\*/|\n)))#msuUS', $output, $match, PREG_OFFSET_CAPTURE))
Andrey Andreev6a424902013-10-28 14:16:18 +0200913 {
914 $js_literals = $js_code = array();
915 for ($match = $match[0], $c = count($match), $i = $pos = $offset = 0; $i < $c; $i++)
916 {
Andrey Andreev3c3bbac2013-10-31 15:10:49 +0200917 $js_code[$pos++] = trim(substr($output, $offset, $match[$i][1] - $offset));
Andrey Andreev6a424902013-10-28 14:16:18 +0200918 $offset = $match[$i][1] + strlen($match[$i][0]);
919
920 // Save only if we haven't matched a comment block
921 if ($match[$i][0][0] !== '/')
922 {
923 $js_literals[$pos++] = array_shift($match[$i]);
924 }
925 }
926 $js_code[$pos] = substr($output, $offset);
927
928 // $match might be quite large, so free it up together with other vars that we no longer need
929 unset($match, $offset, $pos);
930 }
931 else
932 {
933 $js_code = array($output);
934 $js_literals = array();
935 }
936
937 $varname = 'js_code';
938 }
939 else
940 {
941 $varname = 'output';
942 }
943
944 // Standartize new lines
945 $$varname = str_replace(array("\r\n", "\r"), "\n", $$varname);
946
947 if ($type === 'js')
948 {
949 $patterns = array(
Andrey Andreev99f9b9a2013-10-30 23:07:23 +0200950 '#\s*([!\#%&()*+,\-./:;<=>?@\[\]^`{|}~])\s*#' => '$1', // Remove spaces following and preceeding JS-wise non-special & non-word characters
Andrey Andreev6a424902013-10-28 14:16:18 +0200951 '#\s{2,}#' => ' ' // Reduce the remaining multiple whitespace characters to a single space
952 );
953 }
954 else
955 {
956 $patterns = array(
957 '#/\*.*(?=\*/)\*/#s' => '', // Remove /* block comments */
958 '#\n?//[^\n]*#' => '', // Remove // line comments
Andrey Andreev99f9b9a2013-10-30 23:07:23 +0200959 '#\s*([^\w.\#%])\s*#U' => '$1', // Remove spaces following and preceeding non-word characters, excluding dots, hashes and the percent sign
Andrey Andreev6a424902013-10-28 14:16:18 +0200960 '#\s{2,}#' => ' ' // Reduce the remaining multiple space characters to a single space
961 );
962 }
963
964 $$varname = preg_replace(array_keys($patterns), array_values($patterns), $$varname);
965
966 // Glue back JS quoted strings
967 if ($type === 'js')
968 {
969 $js_code += $js_literals;
970 ksort($js_code);
971 $output = implode($js_code);
972 unset($js_code, $js_literals, $varname, $patterns);
973 }
974
975 return is_array($tags)
976 ? $tags['open'].$output.$tags['close']
977 : $output;
978 }
979
Michael Dodge362b8002013-01-04 23:18:39 -0700980}
981
982/* End of file Output.php */
Andrey Andreevd8dba5d2012-12-17 15:42:01 +0200983/* Location: ./system/core/Output.php */