blob: 8b7d6efbd72a2d052b977f3aca97af6c4624a3d1 [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
567 $cache_path .= md5($uri);
568
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200569 if ( ! $fp = @fopen($cache_path, 'w+b'))
Michael Dodge362b8002013-01-04 23:18:39 -0700570 {
571 log_message('error', 'Unable to write cache file: '.$cache_path);
572 return;
573 }
574
Michael Dodge362b8002013-01-04 23:18:39 -0700575 if (flock($fp, LOCK_EX))
576 {
Andrey Andreev155ee722014-01-10 15:50:54 +0200577 // If output compression is enabled, compress the cache
578 // itself, so that we don't have to do that each time
579 // we're serving it
580 if ($this->_compress_output === TRUE)
581 {
582 $output = gzencode($output);
583
584 if ($this->get_header('content-type') === NULL)
585 {
586 $this->set_content_type($this->mime_type);
587 }
588 }
589
590 $expire = time() + ($this->cache_expiration * 60);
591
592 // Put together our serialized info.
593 $cache_info = serialize(array(
594 'expire' => $expire,
595 'headers' => $this->headers
596 ));
597
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200598 $output = $cache_info.'ENDCI--->'.$output;
599
600 for ($written = 0, $length = strlen($output); $written < $length; $written += $result)
601 {
602 if (($result = fwrite($fp, substr($output, $written))) === FALSE)
603 {
604 break;
605 }
606 }
607
Michael Dodge362b8002013-01-04 23:18:39 -0700608 flock($fp, LOCK_UN);
609 }
610 else
611 {
612 log_message('error', 'Unable to secure a file lock for file at: '.$cache_path);
613 return;
614 }
Andrey Andreev155ee722014-01-10 15:50:54 +0200615
Michael Dodge362b8002013-01-04 23:18:39 -0700616 fclose($fp);
Michael Dodge362b8002013-01-04 23:18:39 -0700617
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200618 if (is_int($result))
619 {
Andrey Andreev45965742014-08-27 20:40:11 +0300620 chmod($cache_path, 0640);
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200621 log_message('debug', 'Cache file written: '.$cache_path);
Michael Dodge362b8002013-01-04 23:18:39 -0700622
Andrey Andreevd8b1ad32014-01-15 17:42:52 +0200623 // Send HTTP cache-control headers to browser to match file cache settings.
624 $this->set_cache_header($_SERVER['REQUEST_TIME'], $expire);
625 }
626 else
627 {
628 @unlink($cache_path);
629 log_message('error', 'Unable to write the complete cache content at: '.$cache_path);
630 }
Michael Dodge362b8002013-01-04 23:18:39 -0700631 }
632
633 // --------------------------------------------------------------------
634
635 /**
636 * Update/serve cached output
637 *
638 * @uses CI_Config
639 * @uses CI_URI
640 *
641 * @param object &$CFG CI_Config class instance
642 * @param object &$URI CI_URI class instance
643 * @return bool TRUE on success or FALSE on failure
644 */
645 public function _display_cache(&$CFG, &$URI)
646 {
647 $cache_path = ($CFG->item('cache_path') === '') ? APPPATH.'cache/' : $CFG->item('cache_path');
648
649 // Build the file path. The file name is an MD5 hash of the full URI
650 $uri = $CFG->item('base_url').$CFG->item('index_page').$URI->uri_string;
651 $filepath = $cache_path.md5($uri);
652
Andrey Andreev7cf682a2014-03-13 14:55:45 +0200653 if ( ! file_exists($filepath) OR ! $fp = @fopen($filepath, 'rb'))
Michael Dodge362b8002013-01-04 23:18:39 -0700654 {
655 return FALSE;
656 }
657
658 flock($fp, LOCK_SH);
659
660 $cache = (filesize($filepath) > 0) ? fread($fp, filesize($filepath)) : '';
661
662 flock($fp, LOCK_UN);
663 fclose($fp);
664
Eric Robertsc90e67e2013-01-11 21:20:54 -0600665 // Look for embedded serialized file info.
666 if ( ! preg_match('/^(.*)ENDCI--->/', $cache, $match))
Michael Dodge362b8002013-01-04 23:18:39 -0700667 {
668 return FALSE;
669 }
Purwandi5dc6d512013-01-19 17:43:08 +0700670
Eric Robertsc90e67e2013-01-11 21:20:54 -0600671 $cache_info = unserialize($match[1]);
672 $expire = $cache_info['expire'];
Michael Dodge362b8002013-01-04 23:18:39 -0700673
674 $last_modified = filemtime($cache_path);
Michael Dodge362b8002013-01-04 23:18:39 -0700675
676 // Has the file expired?
677 if ($_SERVER['REQUEST_TIME'] >= $expire && is_really_writable($cache_path))
678 {
679 // If so we'll delete it.
680 @unlink($filepath);
681 log_message('debug', 'Cache file has expired. File deleted.');
682 return FALSE;
683 }
684 else
685 {
686 // Or else send the HTTP cache control headers.
687 $this->set_cache_header($last_modified, $expire);
688 }
Purwandi5dc6d512013-01-19 17:43:08 +0700689
Eric Robertsc90e67e2013-01-11 21:20:54 -0600690 // Add headers from cache file.
691 foreach ($cache_info['headers'] as $header)
692 {
693 $this->set_header($header[0], $header[1]);
694 }
Michael Dodge362b8002013-01-04 23:18:39 -0700695
696 // Display the cache
697 $this->_display(substr($cache, strlen($match[0])));
698 log_message('debug', 'Cache file is current. Sending it to browser.');
699 return TRUE;
700 }
701
702 // --------------------------------------------------------------------
703
704 /**
705 * Delete cache
706 *
707 * @param string $uri URI string
708 * @return bool
709 */
710 public function delete_cache($uri = '')
711 {
712 $CI =& get_instance();
713 $cache_path = $CI->config->item('cache_path');
714 if ($cache_path === '')
715 {
716 $cache_path = APPPATH.'cache/';
717 }
718
719 if ( ! is_dir($cache_path))
720 {
721 log_message('error', 'Unable to find cache path: '.$cache_path);
722 return FALSE;
723 }
724
725 if (empty($uri))
726 {
727 $uri = $CI->uri->uri_string();
728 }
729
730 $cache_path .= md5($CI->config->item('base_url').$CI->config->item('index_page').$uri);
731
732 if ( ! @unlink($cache_path))
733 {
734 log_message('error', 'Unable to delete cache file for '.$uri);
735 return FALSE;
736 }
737
738 return TRUE;
739 }
740
741 // --------------------------------------------------------------------
742
743 /**
744 * Set Cache Header
745 *
746 * Set the HTTP headers to match the server-side file cache settings
747 * in order to reduce bandwidth.
748 *
749 * @param int $last_modified Timestamp of when the page was last modified
750 * @param int $expiration Timestamp of when should the requested page expire from cache
751 * @return void
752 */
753 public function set_cache_header($last_modified, $expiration)
754 {
755 $max_age = $expiration - $_SERVER['REQUEST_TIME'];
756
757 if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $last_modified <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
758 {
759 $this->set_status_header(304);
760 exit;
761 }
762 else
763 {
764 header('Pragma: public');
Andrey Andreev3ca060a2013-11-27 16:30:31 +0200765 header('Cache-Control: max-age='.$max_age.', public');
Michael Dodge362b8002013-01-04 23:18:39 -0700766 header('Expires: '.gmdate('D, d M Y H:i:s', $expiration).' GMT');
767 header('Last-modified: '.gmdate('D, d M Y H:i:s', $last_modified).' GMT');
768 }
769 }
770
771 // --------------------------------------------------------------------
772
773 /**
774 * Minify
775 *
776 * Reduce excessive size of HTML/CSS/JavaScript content.
777 *
778 * @param string $output Output to minify
779 * @param string $type Output content MIME type
780 * @return string Minified output
781 */
782 public function minify($output, $type = 'text/html')
783 {
784 switch ($type)
785 {
786 case 'text/html':
787
788 if (($size_before = strlen($output)) === 0)
789 {
790 return '';
791 }
792
793 // Find all the <pre>,<code>,<textarea>, and <javascript> tags
794 // We'll want to return them to this unprocessed state later.
795 preg_match_all('{<pre.+</pre>}msU', $output, $pres_clean);
796 preg_match_all('{<code.+</code>}msU', $output, $codes_clean);
797 preg_match_all('{<textarea.+</textarea>}msU', $output, $textareas_clean);
798 preg_match_all('{<script.+</script>}msU', $output, $javascript_clean);
799
800 // Minify the CSS in all the <style> tags.
801 preg_match_all('{<style.+</style>}msU', $output, $style_clean);
802 foreach ($style_clean[0] as $s)
803 {
Andrey Andreev6a424902013-10-28 14:16:18 +0200804 $output = str_replace($s, $this->_minify_js_css($s, 'css', TRUE), $output);
Michael Dodge362b8002013-01-04 23:18:39 -0700805 }
806
807 // Minify the javascript in <script> tags.
808 foreach ($javascript_clean[0] as $s)
809 {
Andrey Andreev6a424902013-10-28 14:16:18 +0200810 $javascript_mini[] = $this->_minify_js_css($s, 'js', TRUE);
Michael Dodge362b8002013-01-04 23:18:39 -0700811 }
812
813 // Replace multiple spaces with a single space.
814 $output = preg_replace('!\s{2,}!', ' ', $output);
815
816 // Remove comments (non-MSIE conditionals)
Michael Dodge4d02e352013-01-04 23:22:51 -0700817 $output = preg_replace('{\s*<!--[^\[<>].*(?<!!)-->\s*}msU', '', $output);
Michael Dodge362b8002013-01-04 23:18:39 -0700818
819 // Remove spaces around block-level elements.
Purwandi5dc6d512013-01-19 17:43:08 +0700820 $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 -0700821
822 // Replace mangled <pre> etc. tags with unprocessed ones.
823
824 if ( ! empty($pres_clean))
825 {
826 preg_match_all('{<pre.+</pre>}msU', $output, $pres_messed);
827 $output = str_replace($pres_messed[0], $pres_clean[0], $output);
828 }
829
830 if ( ! empty($codes_clean))
831 {
832 preg_match_all('{<code.+</code>}msU', $output, $codes_messed);
833 $output = str_replace($codes_messed[0], $codes_clean[0], $output);
834 }
835
Andrey Andreev3ffce982013-01-21 15:24:09 +0200836 if ( ! empty($textareas_clean))
Michael Dodge362b8002013-01-04 23:18:39 -0700837 {
838 preg_match_all('{<textarea.+</textarea>}msU', $output, $textareas_messed);
839 $output = str_replace($textareas_messed[0], $textareas_clean[0], $output);
840 }
841
842 if (isset($javascript_mini))
843 {
844 preg_match_all('{<script.+</script>}msU', $output, $javascript_messed);
845 $output = str_replace($javascript_messed[0], $javascript_mini, $output);
846 }
847
848 $size_removed = $size_before - strlen($output);
849 $savings_percent = round(($size_removed / $size_before * 100));
850
851 log_message('debug', 'Minifier shaved '.($size_removed / 1000).'KB ('.$savings_percent.'%) off final HTML output.');
852
853 break;
854
855 case 'text/css':
Andrey Andreev6a424902013-10-28 14:16:18 +0200856
857 return $this->_minify_js_css($output, 'css');
858
Michael Dodge362b8002013-01-04 23:18:39 -0700859 case 'text/javascript':
bayssmekanique7b903252013-03-12 13:25:24 -0700860 case 'application/javascript':
861 case 'application/x-javascript':
Michael Dodge362b8002013-01-04 23:18:39 -0700862
Andrey Andreev6a424902013-10-28 14:16:18 +0200863 return $this->_minify_js_css($output, 'js');
Michael Dodge362b8002013-01-04 23:18:39 -0700864
865 default: break;
866 }
867
868 return $output;
869 }
870
871 // --------------------------------------------------------------------
872
Andrey Andreev3c3bbac2013-10-31 15:10:49 +0200873 /**
874 * Minify JavaScript and CSS code
875 *
876 * Strips comments and excessive whitespace characters
877 *
878 * @param string $output
879 * @param string $type 'js' or 'css'
880 * @param bool $tags Whether $output contains the 'script' or 'style' tag
881 * @return string
882 */
Andrey Andreev6a424902013-10-28 14:16:18 +0200883 protected function _minify_js_css($output, $type, $tags = FALSE)
884 {
885 if ($tags === TRUE)
886 {
887 $tags = array('close' => strrchr($output, '<'));
888
889 $open_length = strpos($output, '>') + 1;
890 $tags['open'] = substr($output, 0, $open_length);
891
892 $output = substr($output, $open_length, -strlen($tags['close']));
893
894 // Strip spaces from the tags
895 $tags = preg_replace('#\s{2,}#', ' ', $tags);
896 }
897
898 $output = trim($output);
899
900 if ($type === 'js')
901 {
902 // Catch all string literals and comment blocks
Andrey Andreev0949b362013-10-31 16:07:40 +0200903 if (preg_match_all('#((?:((?<!\\\)\'|")|(/\*)|(//)).*(?(2)(?<!\\\)\2|(?(3)\*/|\n)))#msuUS', $output, $match, PREG_OFFSET_CAPTURE))
Andrey Andreev6a424902013-10-28 14:16:18 +0200904 {
905 $js_literals = $js_code = array();
906 for ($match = $match[0], $c = count($match), $i = $pos = $offset = 0; $i < $c; $i++)
907 {
Andrey Andreev3c3bbac2013-10-31 15:10:49 +0200908 $js_code[$pos++] = trim(substr($output, $offset, $match[$i][1] - $offset));
Andrey Andreev6a424902013-10-28 14:16:18 +0200909 $offset = $match[$i][1] + strlen($match[$i][0]);
910
911 // Save only if we haven't matched a comment block
912 if ($match[$i][0][0] !== '/')
913 {
914 $js_literals[$pos++] = array_shift($match[$i]);
915 }
916 }
917 $js_code[$pos] = substr($output, $offset);
918
919 // $match might be quite large, so free it up together with other vars that we no longer need
920 unset($match, $offset, $pos);
921 }
922 else
923 {
924 $js_code = array($output);
925 $js_literals = array();
926 }
927
928 $varname = 'js_code';
929 }
930 else
931 {
932 $varname = 'output';
933 }
934
935 // Standartize new lines
936 $$varname = str_replace(array("\r\n", "\r"), "\n", $$varname);
937
938 if ($type === 'js')
939 {
940 $patterns = array(
Andrey Andreev99f9b9a2013-10-30 23:07:23 +0200941 '#\s*([!\#%&()*+,\-./:;<=>?@\[\]^`{|}~])\s*#' => '$1', // Remove spaces following and preceeding JS-wise non-special & non-word characters
Andrey Andreev6a424902013-10-28 14:16:18 +0200942 '#\s{2,}#' => ' ' // Reduce the remaining multiple whitespace characters to a single space
943 );
944 }
945 else
946 {
947 $patterns = array(
948 '#/\*.*(?=\*/)\*/#s' => '', // Remove /* block comments */
949 '#\n?//[^\n]*#' => '', // Remove // line comments
Andrey Andreev99f9b9a2013-10-30 23:07:23 +0200950 '#\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 +0200951 '#\s{2,}#' => ' ' // Reduce the remaining multiple space characters to a single space
952 );
953 }
954
955 $$varname = preg_replace(array_keys($patterns), array_values($patterns), $$varname);
956
957 // Glue back JS quoted strings
958 if ($type === 'js')
959 {
960 $js_code += $js_literals;
961 ksort($js_code);
962 $output = implode($js_code);
963 unset($js_code, $js_literals, $varname, $patterns);
964 }
965
966 return is_array($tags)
967 ? $tags['open'].$output.$tags['close']
968 : $output;
969 }
970
Michael Dodge362b8002013-01-04 23:18:39 -0700971}
972
973/* End of file Output.php */
Andrey Andreevd8dba5d2012-12-17 15:42:01 +0200974/* Location: ./system/core/Output.php */