energine
[ class tree: energine ] [ index: energine ] [ all elements ]

Source for file FileUploader.class.php

Documentation is available at FileUploader.class.php

  1. <?php
  2.  
  3. /**
  4.  * Класс FileUploader.
  5.  *
  6.  * @package energine
  7.  * @subpackage core
  8.  * @author 1m.dm
  9.  * @copyright Energine 2006
  10.  * @version $Id$
  11.  */
  12.  
  13. //require_once('core/framework/Object.class.php');
  14.  
  15. /**
  16.  * Загрузчик файлов на сервер.
  17.  *
  18.  * @package energine
  19.  * @subpackage core
  20.  * @author 1m.dm
  21.  */
  22. class FileUploader extends Object {
  23.  
  24.     /**
  25.      * @access protected
  26.      * @var array описание загружаемого файла - $_FILE
  27.      * @see PHP manual, POST method uploads
  28.      */
  29.     protected $file = array();
  30.  
  31.     /**
  32.      * @access private
  33.      * @var array ограничения для загружаемого файла
  34.      */
  35.     private $restrictions = array();
  36.  
  37.     /**
  38.      * @access private
  39.      * @var string расширение файла
  40.      */
  41.     private $ext;
  42.  
  43.     /**
  44.      * @access protected
  45.      * @var string имя, под которым загруженный файл сохранен на сервере
  46.      */
  47.     protected $FileObjectName;
  48.     
  49.     protected $FileRealName;
  50.  
  51.     /**
  52.      * @access private
  53.      * @var string путь к корневому каталогу загружаемых файлов
  54.      */
  55.     private $uploadsPath = '';
  56.  
  57.     /**
  58.      * @access private
  59.      * @var boolean флаг, указывающий была ли произведена валидация (проверяется методом upload)
  60.      */
  61.     private $validated = false;
  62.  
  63.     ////////////////////////////////////////////////////////////////////////////
  64.  
  65.     /**
  66.      * Конструктор класса.
  67.      *
  68.      * @access public
  69.      * @return void 
  70.      */
  71.     public function __construct(Array $restrictions array()) {
  72.         parent::__construct();
  73.         $this->restrictions = $restrictions;
  74.     }
  75.  
  76.     /**
  77.      * Устанавливает ограничения которым должен соответствовать загружаемый
  78.      *
  79.      * 
  80.      * array(
  81.      *      'ext' => array('jpg', 'gif')
  82.      * )
  83.      *
  84.      * @access public
  85.      * @param array $restrictions 
  86.      * @return void 
  87.      */
  88.     public function setRestrictions(array $restrictions{
  89.         $this->restrictions $restrictions;
  90.     }
  91.  
  92.     /**
  93. /**
  94.      * Устанавливает описание файла.
  95.      *
  96.      * @access public
  97.      * @param array $file 
  98.      * @return void 
  99.      */
  100.     public function setFile(array $file{
  101.         if (!isset($file['name']$file['size']$file['tmp_name']$file['error'])) {
  102.             throw new SystemException('ERR_DEV_BAD_DATA'SystemException::ERR_DEVELOPER$file);
  103.         }
  104.         $this->file = $file;
  105.         
  106.         $this->validate();
  107.     }
  108.  
  109.     /**
  110.      * Валидация загружаемого файла.
  111.      *
  112.      * @access public
  113.      * @return boolean 
  114.      */
  115.     public function validate({
  116.         /*
  117.          * Браузер может не посылать MIME type, поэтому расчитывать на него нельзя.
  118.          */
  119.         if (empty($this->file)) {
  120.             throw new SystemException('ERR_DEV_BAD_DATA'SystemException::ERR_DEVELOPER$this->file['name']);
  121.         }
  122.  
  123.         if ($this->file['error'!= UPLOAD_ERR_OK || !is_uploaded_file($this->file['tmp_name'])) {
  124.             throw new SystemException('ERR_UPLOAD_FAILED'SystemException::ERR_WARNING$this->file['error']);
  125.         }
  126.         
  127.         $dummy explode('.'$this->file['name']);
  128.         $this->ext array_pop($dummy);
  129.         
  130.         if(isset($this->restrictions['ext'])){
  131.             if(!in_array($this->ext$this->restrictions['ext'])){
  132.                 throw new SystemException('ERR_BAD_FILE_TYPE'SystemException::ERR_DEVELOPER$this->file['name']);
  133.             }
  134.         }
  135.         
  136.         return ($this->validated true);
  137.     }
  138.  
  139.     /**
  140.      * Фактическая загрузка файла в определенную директорию.
  141.      *
  142.      * @access public
  143.      * @param string $dir директория внутри корневого каталога загружаемых файлов
  144.      * @return boolean 
  145.      */
  146.     public function upload($dir{
  147.         if (!$this->validated{
  148.             $this->validate();
  149.         }
  150.         if(!is_uploaded_file($this->file['tmp_name'])){
  151.             throw new SystemException('ERR_BAD_UPLOAD'SystemException::ERR_WARNING$this->file['name']);
  152.         }
  153.         
  154.         $filePath $this->generateFilename($dir$this->ext);
  155.         if (
  156.             !@move_uploaded_file(
  157.                 $this->file['tmp_name']
  158.                 $filePath
  159.             )
  160.         {
  161.             throw new SystemException('ERR_DEV_UPLOAD_FAILED'SystemException::ERR_WARNING$this->file['name']);
  162.         }
  163.         //Ресайзим изображение
  164.         if(in_array($this->getExtension()array('gif''png''jpg''jpeg'))){
  165.             $img new Image();
  166.             $img->loadFromFile($filePath);
  167.             
  168.             if(($img->getWidth()800&& ($img->getHeight(600)){
  169.                 $img->resize(800600);
  170.                 $img->saveToFile($filePath);    
  171.             }
  172.             /*
  173.             elseif($img->getWidth()> 800){
  174.                 $img->resize(800, null);
  175.                 $img->saveToFile($filePath);
  176.             }
  177.             elseif($img->getHeight()> 600){
  178.                 $img->resize(null, 600);
  179.                 $img->saveToFile($filePath);
  180.             }
  181.             */
  182.               unset($image);
  183.                 
  184.         }
  185.         
  186.         $this->FileRealName $this->file['name'];
  187.         $this->FileObjectName $filePath;
  188.         chmod($this->FileObjectName0666);
  189.  
  190.         return true;
  191.     }
  192.     
  193.     protected function generateFilename($dir$ext){
  194.         if ($dir[0== '/'{
  195.             $dir substr($dir1);
  196.         }
  197.         if ($dir[strlen($dir)-1!= '/'{
  198.             $dir .= '/';
  199.         }
  200.  
  201.         return $this->uploadsPath.$dir.FileObject::generateFilename($this->uploadsPath.$dir$ext);
  202.     }
  203.  
  204.     /**
  205.      * Возвращает имя загруженного файла.
  206.      *
  207.      * @access public
  208.      * @return string 
  209.      */
  210.     public function getFileObjectName({
  211.         return $this->FileObjectName;
  212.     }
  213.     
  214.     public function getFileRealName({
  215.         return $this->FileRealName;
  216.     }
  217.  
  218.     /**
  219.      * Возвращает расширение файла.
  220.      *
  221.      * @access public
  222.      * @return string 
  223.      */
  224.     public function getExtension({
  225.         return $this->ext;
  226.     }
  227.     
  228.  
  229.     /**
  230.      * Очищает состояние объекта для повторного использования.
  231.      *
  232.      * @access public
  233.      * @return void 
  234.      */
  235.     public function cleanUp({
  236.         $this->restrictions array();
  237.         $this->ext null;
  238.         $this->FileObjectName null;
  239.         $this->validated false;
  240.     }
  241. }
В создании документации нам помог: phpDocumentor