asset.php

<?php if(!defined('BASEPATH')) die('No direct script access allowed.');

class Asset extends Controller {
	
	function Asset() {
		parent::Controller();
		// Find the requested resource
		$this->request = $this->uri->rsegment(3);
		// If the request is false, 404 em!
		if($this->request == false) show_404();
		// Location of the images (this is outside of the docroot)
		$this->imageroot = '/home/wgilk/storage/images';
		// Allowed image types, the key is a constant
		// returned by getimagesize()
		$this->allowed = array(
			IMAGETYPE_GIF     => 'gif',
			IMAGETYPE_JPEG    => 'jpg',
			IMAGETYPE_PNG     => 'png',
			IMAGETYPE_TIFF_II => 'tiff',
			IMAGETYPE_TIFF_MM => 'tiff',
			IMAGETYPE_BMP     => 'bmp');
	}
	
	function javascript() {
		// We will always output javascript
		header('Content-Type: application/x-javascript');
		// Filename and full path
		$filename = str_replace('.js', '', $this->request);
		$fullpath = APPPATH."views/js/$filename.php";
		// Default output
		$output = "// File $filename does not exist!";
		// Make sure the requested ip is the same as the server
		$referrer = @$_SERVER['HTTP_REFFERER'];
		if ($referrer != false && strpos($referrer, SITENAME) === FALSE) {
			// Load settings for site name
			$this->load->model('sitedb');
			$settings = $this->sitedb->settings();
			// Display message
			print "// This script belongs to ".$settings['name'].", located at\n"
			    . "// ".site_url($this->uri->uri_string).", copyright ".date('Y').".\n"
			    . "// Please do not link to our scripts, $referrer. Thank you.\n";
			return;
		}
		// Check if the file exists
		if (is_file($fullpath)) {
			// The cache path is outside of the docroot
			$cachepath = '/home/wgilk/storage/cache/';
			// Create cache dir
			if (!is_dir($cachepath)) {
				mkdir($cachepath);
				chmod('2770'); // rwxrws---
			}
			// Use caching
			if($this->input->get('nocache') == 'true' || $this->input->get('nopack') == 'true') {
				$output = ($this->input->get('nopack') == 'true')
				        ? $this->load->view ("js/$filename", true, true)
				        : $this->_packer($filename);
			} else {
				// Generate a unique file name
				$cachefile = $cachepath.sha1($this->uri->uri_string());
				// Is the cache file less than an hour old?
				if(is_file($cachefile) && (time() - filemtime($cachefile)) < 7200)
					$output = @file_get_contents($cachefile);
				// Generate a new cache
				else {
					$output = $this->_packer($filename);
					@file_put_contents($cachefile, $output);
				}
			}
		}
		// Print output
		print $output;
		
	}
	
	function image () {
		$type  = $this->uri->rsegment(3);
		$id    = $this->uri->rsegment(4);
		$type  = ($type == 't') ? 'thumbnail' : 'fullsize';
		$image = "$this->imageroot/$type/$id.jpg";
		
		// Check to make sure we are working with a valid image
		$mime  = @exif_imagetype($image);
		if (! isset ($this->allowed[$mime])) {
			$image = "./media/img/gallery_{$type}_na.jpg";
			$mime  = @exif_imagetype ($image);
		}
		
		$mime = image_type_to_mime_type ($mime);
		$size = @filesize ($image);
		$modf = @filemtime ($image);
		$mgmt = gmdate ('D, d M Y H:i:s', $modf);
		$egmt = gmdate ('D, d M Y H:i:s', (time()+7200));
		
		if ($mime == false || $size == 0) show_404();
		// Set Headers
		header("Cache-Control: public, must-revalidate");
		header("Last-Modified: $mgmt GMT");
		header("Expires: $egmt GMT");
		header("Content-Type: $mime");
		header("Content-Length: $size");
		
		ob_end_clean();     // Clear the buffer for clean output
		define('COPEN', 0); // Define the "connection open" status
		// Open the image in read-only, binary mode
		if ($file = fopen ($image, 'rb')) {
			// Prevent the user from aborting the script
			// * Don't worry, we handle aborting in the output loop.
			// * This is necessary to make sure that the file is closed properly
			ignore_user_abort(true);
			// Read the file
			while (! feof ($file)) {
				// Read the output in 32 byte chunks
				// * It is recommended that you not lower this, benchmarks
				// * have proven that using anything less than a 32 byte
				// * will work poorly with IE (w00t!) and don't allow full
				// * saturation of the bandwidth.
				print (fread ($file, 1024*32));
				// Good connection status, output data chunk
				// * Remember that ob_flush() and flush() must ALWAYS be used
				if (connection_status() == COPEN) { ob_flush(); flush(); }
				// User has closed the connection, close the file and stop
				else { fclose($file); return; }
			}
			// Finished reading, close the file
			fclose($file);
		}
		// Stop
		return;

		
		return;
	}
	
	// HELPER FUNCTIONS
	function _packer($filename) {
		if (!class_exists('JavaScriptPacker')) $this->load->helper('jspack');
		// Load script file
		$script = $this->load->view("js/$filename", null, true);
		// Pack and return
		$packer = new JavaScriptPacker($script, 'Normal', true, false);
		return $packer->pack();
	}
	
}

if (!function_exists('jsarray')) {
	// Returns a nicely formatted output
	function jsarray($array) {
		return "\n\t'".implode("',\n\t'", $array)."'";
	}
}

?>