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