Stream library

Каждый топик здесь посвящен конкретной библиотеке или наработкам конкретного проекта

Stream library

Сообщение michail1982 » 12 июл 2009, 15:39

Вот написал библиотечку, которая файлы в поток отдаёт поблочно, незнаю, нужна ли она кому, ведь есть download_helper.php
Код: Выделить всё
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package        CodeIgniter
 * @author        Maksarov Michail
 * @copyright    Copyright (c) 2009, Michail1982
 * @license        http://codeigniter.com/user_guide/license.html
 * @link        http://codeigniter.com
 * @since        Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * CodeIgniter Stream Class
 *
 * Send files to steram output
 *
 * @package        CodeIgniter
 * @subpackage    Libraries
 * @category    Libraries
 * @author        Maksarov Michail
 */
class MY_Stream {
    var 
$file_path FALSE//file path on server
    
var $needle_name FALSE//attachment name (default is file name on server)
    
var $part_size 512//file read block size (in bytes)
    
var $mime FALSE//any mime-type
    
var $use_mime_config FALSE;//use config/mimes.php
    /**
     * Constructor - Sets Stream Preferences
     *
     * The constructor can be passed an array of config values
     */
    
function MY_Stream($config = array()) {
        if(! 
function_exists('get_file_info' || ! function_exists('get_mime_by_extension'))){
            
$CI =& get_instance();
            
$CI->load->helper('file');
        }
        
$this->initialize($config);
        
log_message('debug''Stream Class Initialized');
    }

    
// --------------------------------------------------------------------

    /**
     * Initialize preferences
     *
     * @access    public
     * @param    array
     * @return    void
     */
    
function initialize($config = array())
    {
        if(
sizeof($config 0)){
            foreach (
$config as $key => $val) {
                if (isset(
$this->$key))
                {
                    
$method 'set_'.$key;

                    if (
method_exists($this$method))
                    {
                        
$this->$method($val);
                    }
                    else
                    {
                        
$this->$key $val;
                    }
                }

            }
        }
    }

    
// --------------------------------------------------------------------

    /**
     * Set part size Value
     *
     * @access    public
     * @param    int
     * @return    void
     */

    
function set_part_size($part_size FALSE){
        
$part_size abs(intval($part_size));
        if(
$part_size>0){
            
$this->part_size $part_size;
        }
    }

    
// --------------------------------------------------------------------

    /**
     * Set mime Value
     *
     * @access    public
     * @param    string
     * @return    void
     */

    
function set_mime($mime FALSE){
        
$mime strtolower(trim($mime));
        if(
preg_match('/^([a-z]+)\/([a-z0-9\+\-\.]+)$/',$mime)){
            
$this->mime $mime;
        }
    }

    
// --------------------------------------------------------------------

    /**
     * Send file to stream
     *
     * @access    public
     * @return    bool
     */

     
function send_content($config = array()){
        if(
sizeof($config)>0){
            
$this->initialize($config);
        }
        if(!
$this->file_path){
            
log_message('error''Stream Class: Empty filePath');
            return 
FALSE;
        }
        if(!
$file_info get_file_info($this->file_path,array('name','server_path','size','date','readable'))){
            
log_message('error''Stream Class: File not exists');
            return 
FALSE;
        } else {
            
$fileinfo['date'] = date('D, d M Y H:i:s T'$fileinfo['date']);
        }
        if(!
$file_info['readable']){
            
log_message('error''Stream Class: file not readable');
            return 
FALSE;
        }
        if(!
$needle_name $this->needle_name){
            
$needle_name $file_info['name'];
        }
        
$range 0;
        
$handle = @fopen($file_info['server_path'], FOPEN_READ);
        if (!
$handle){
            
log_message('error''Stream Class: Cannot read file :-/');
            return 
FALSE;
        }
        if (@
$_SERVER['HTTP_RANGE']) {
            
$range = @$_SERVER['HTTP_RANGE'];
            
$range str_replace('bytes='''$range);
            
$range str_replace('-'''$range);
            if (
$range) {
                
fseek($handle$range);
            }
        }
        if(!
$content_type $this->mime){
            if(
$this->use_mime_config && $content_type get_mime_by_extension($needle_name)){
                continue;
            } else {
                if(isset(
$_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')){
                    
$content_type 'application/force-download';
                }
                else{
                    
$content_type 'application/octet-stream';
                }
            }
        }
        if (
$range) {
            
$server_responce '206 Partial Content';
        } else {
            
$server_responce 'HTTP/1.1 200 OK';
        }
        
header('HTTP/1.1 '.$server_responce);
        
header('Content-Disposition: attachment; filename="'.$needle_name.'"');
        
header('Last-Modified: '.$file_info['date']);
        
header('Content-Length: '.($file_info['size']-$range));
        
header('Accept-Ranges: bytes');
        
header('Content-Range: bytes '.$range.'-'.($file_info['size'] - 1).'/'.$file_info['size']);
        
header('Content-Type: '.$content_type);
        while(!
feof($handle)) {
            
$buf fread($handle$this->part_size);
            print(
$buf);
        }
        
fclose($handle);
        return 
TRUE;
    }

    
// --------------------------------------------------------------------
}

/* End of file Stream.php */
/* Location: ./system/application/libraries/MY_Stream.php */ 
Аватара пользователя
michail1982
 
Сообщения: 533
Зарегистрирован: 25 ноя 2008, 15:36

Вернуться в Решения, авторский код и библиотеки

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 0