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

Source for file FileLibrary.class.php

Documentation is available at FileLibrary.class.php

  1. <?php
  2. /**
  3.  * Содержит класс FileLibrary
  4.  *
  5.  * @package energine
  6.  * @subpackage share
  7.  * @author dr.Pavka
  8.  * @copyright Energine 2006
  9.  * @version $Id$
  10.  */
  11.  
  12. /**
  13.  * Библитека изображений
  14.  *
  15.  * @package energine
  16.  * @subpackage share
  17.  * @author dr.Pavka
  18.  * @final
  19.  */
  20. final class FileLibrary extends DataSet {
  21.     /**
  22.      * Путь к директории в которой хранятся загруженные пользователями файлы
  23.      *
  24.      */
  25.     const UPLOADS_MAIN_DIR = 'uploads/public';
  26.  
  27.     /**
  28.      * Uploads Directory
  29.      *
  30.      * @var DirectoryObject 
  31.      * @access private
  32.      */
  33.     private $uploadsDir;
  34.  
  35.     /**
  36.      * Конструктор класса
  37.      *
  38.      * @param string $name 
  39.      * @param string $module 
  40.      * @param Document $document 
  41.      * @param array $params 
  42.      * @access public
  43.      */
  44.     public function __construct($name$moduleDocument $document,  array $params null{
  45.         parent::__construct($name$module$document,  $params);
  46.         $this->setProperty('exttype''grid');
  47.         $this->setType(self::COMPONENT_TYPE_LIST);
  48.         $this->setTitle($this->translate('TXT_'.strtoupper($this->getName())));
  49.         //Отключили pager
  50.         $this->setParam('recordsPerPage'false);
  51.         if (!isset($_POST['path'])) {
  52.             $path self::UPLOADS_MAIN_DIR;
  53.         }
  54.         else {
  55.             $path $_POST['path'];
  56.         }
  57.         $this->uploadsDir DirectoryObject::loadFrom($path);
  58.     }
  59.  
  60.     /**
  61.      * Переопределен параметр active
  62.      *
  63.      * @return int 
  64.      * @access protected
  65.      */
  66.  
  67.     protected function defineParams({
  68.         $result array_merge(parent::defineParams(),
  69.         array(
  70.         'active'=>true,
  71.         ));
  72.         return $result;
  73.     }
  74.  
  75.     /**
  76.      * Загружает описание данных из таблицы
  77.      *
  78.      * @return DataDescription 
  79.      * @access protected
  80.      */
  81.  
  82.     protected function loadDataDescription({
  83.         $result $this->dbh->getColumnsInfo(DirectoryObject::TABLE_NAME);
  84.         $result['upl_mime_type'array(
  85.         'length'=>100,
  86.         'nullable'=>false,
  87.         'default' => false,
  88.         'key' => false,
  89.         'type' => FieldDescription::FIELD_TYPE_STRING
  90.         );
  91.         $result['className'array(
  92.         'length'=>100,
  93.         'nullable'=>false,
  94.         'default' => false,
  95.         'key' => false,
  96.         'type' => FieldDescription::FIELD_TYPE_STRING
  97.         );
  98.         foreach ($result as $key => $value{
  99.             $result[$key]['tabName']  $this->getTitle();
  100.         }
  101.         return $result;
  102.     }
  103.  
  104.     /**
  105.      * Метод загрузки данных
  106.      *
  107.      * @return void 
  108.      * @access public
  109.      */
  110.  
  111.     public function loadData({
  112.         if ($this->getAction(== 'getRawData'{
  113.             $result array();
  114.             if ($this->uploadsDir->getPath(!= self::UPLOADS_MAIN_DIR{
  115.                 $result $this->uploadsDir->asArray();
  116.                 $result['upl_path'dirname($result['upl_path']);
  117.                 $result['upl_name''...';
  118.             }
  119.             $this->uploadsDir->open();
  120.  
  121.             if (!empty($result)) {
  122.                 $result array_merge(array($result)$this->uploadsDir->asArray());
  123.             }
  124.             else {
  125.                 $result $this->uploadsDir->asArray();
  126.             }
  127.  
  128.             $result array_map(array($this'addClass')$result);
  129.         }
  130.         elseif ($this->getAction(== self::DEFAULT_ACTION_NAME{
  131.             $result false;
  132.         }
  133.         else {
  134.             $result parent::loadData();
  135.         }
  136.         return $result;
  137.     }
  138.  
  139.     /**
  140.      * На основании значения константы набора типов формируется поле типа class
  141.      *
  142.      * @return array 
  143.      * @access private
  144.      */
  145.  
  146.     private function addClass($row{
  147.         switch ($row['upl_mime_type']{
  148.             case FileSystemObject::IS_FOLDER:
  149.                 $row['className''folder';
  150.                 break;
  151.             case FileSystemObject::IS_IMAGE:
  152.                 $row['className''image';
  153.             break;
  154.             case FileSystemObject::IS_ZIP:
  155.                 $row['className''zip';
  156.             break;
  157.             default:
  158.                 $row['className''undefined';
  159.                 break;
  160.         }
  161.         return $row;
  162.     }
  163.  
  164.     /**
  165.      * Выводит данные в JSON формате для AJAX
  166.      *
  167.      * @return void 
  168.      * @access protected
  169.      */
  170.  
  171.     protected function getRawData({
  172.         try {
  173.             $this->config->setCurrentMethod(self::DEFAULT_ACTION_NAME);
  174.             $this->setBuilder(new JSONUploadBuilder());
  175.  
  176.  
  177.             $this->setDataDescription($this->createDataDescription());
  178.             $this->getBuilder()->setDataDescription($this->getDataDescription());
  179.             $this->getBuilder()->setCurrentDir($this->uploadsDir->getPath());
  180.  
  181.             $data $this->createData();
  182.             if ($data instanceof Data{
  183.                 $this->setData($data);
  184.                 $this->getBuilder()->setData($this->getData());
  185.             }
  186.  
  187.             if ($this->getBuilder()->build()) {
  188.                 $result $this->getBuilder()->getResult();
  189.             }
  190.             else {
  191.                 $result $this->getBuilder()->getErrors();
  192.             }
  193.  
  194.         }
  195.         catch (Exception $e){
  196.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  197.             $result json_encode(array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message));
  198.         }
  199.  
  200.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  201.         $this->response->write($result);
  202.         $this->response->commit();
  203.     }
  204.  
  205.     /**
  206.      * Method Description
  207.      *
  208.      * @return type 
  209.      * @access protected
  210.      */
  211.  
  212.      protected function main({
  213.         parent::main();
  214.         $this->setProperty('allowed_file_type''all');
  215.         if ($params $this->getActionParams()) {
  216.             if (is_array($params&& !empty($params&& $params[0== 'image-only'{
  217.                 $this->setProperty('allowed_file_type''image');
  218.             }
  219.         }
  220.      }
  221.  
  222.     /**
  223.      * Метод выводит форму создания новой папки
  224.      *
  225.      * @return void 
  226.      * @access protected
  227.      */
  228.  
  229.     protected function addDir({
  230.         $this->setType(self::COMPONENT_TYPE_FORM_ADD);
  231.         $this->prepare();
  232.     }
  233.  
  234.     /**
  235.      * Сохранение данных о папке
  236.      *
  237.      * @return void 
  238.      * @access protected
  239.      */
  240.  
  241.     protected function saveDir({
  242.         try {
  243.             $folder new DirectoryObject();
  244.             $folder->create($_POST);
  245.  
  246.             $JSONResponse array(
  247.             'result' => true,
  248.             'mode' => 'insert'
  249.             );
  250.         }
  251.         catch (SystemException $e){
  252.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  253.             $JSONResponse array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message);
  254.  
  255.         }
  256.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  257.         $this->response->write(json_encode($JSONResponse));
  258.         $this->response->commit();
  259.     }
  260.  
  261.     /**
  262.      * Метод сохранения файла
  263.      *
  264.      * @return void 
  265.      * @access protected
  266.      */
  267.  
  268.     protected function save({
  269.         try {
  270.             $file new FileObject();
  271.             $file->create($_POST);
  272.  
  273.             $JSONResponse array(
  274.             'result' => true,
  275.             'mode' => 'insert'
  276.             );
  277.         }
  278.         catch (SystemException $e){
  279.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  280.             $JSONResponse array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message);
  281.  
  282.         }
  283.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  284.         $this->response->write(json_encode($JSONResponse));
  285.         $this->response->commit();
  286.     }
  287.  
  288.     /**
  289.      * Удаление папки/файла
  290.      *
  291.      * @return void 
  292.      * @access protected
  293.      */
  294.  
  295.     protected function delete({
  296.         try {
  297.             if (!isset($_POST['file'])) {
  298.  
  299.             }
  300.             if (($fileType key($_POST['file'])) == 'folder'{
  301.                 $file DirectoryObject::loadFrom($_POST['file'][$fileType]);
  302.             }
  303.             else {
  304.                 $file FileObject::loadFrom($_POST['file'][$fileType]);
  305.             }
  306.  
  307.             $file->delete();
  308.  
  309.             $JSONResponse array(
  310.             'result' => true,
  311.             'mode' => 'delete'
  312.             );
  313.         }
  314.         catch (SystemException $e){
  315.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  316.             $JSONResponse array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message);
  317.  
  318.         }
  319.  
  320.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  321.         $this->response->write(json_encode($JSONResponse));
  322.         $this->response->commit();
  323.  
  324.     }
  325.  
  326.     /**
  327.      * Распаковка залитого zip файла
  328.      *
  329.      * @return void 
  330.      * @access protected
  331.      */
  332.     protected function saveZip(){
  333.         try {
  334.             $filename FileObject::getTmpFilePath($_POST['share_uploads']['upl_path']);
  335.  
  336.             if(file_exists($filename)){
  337.                 setlocale(LC_CTYPE"uk_UA.UTF-8");
  338.                 $zip new ZipArchive();
  339.                 $zip->open($filename);
  340.  
  341.                 for ($i 0$i $zip->numFiles$i++){
  342.                     
  343.                     $currentFile $zip->statIndex($i);
  344.                         
  345.                     $currentFile $currentFile['name'];
  346.                     $fileInfo pathinfo($currentFile);
  347.                     /*if($fileInfo['filename'] === ''){
  348.                         
  349.                     }
  350.                     else*/if(
  351.                         !(
  352.                             (substr($fileInfo['filename']01=== '.')
  353.                             ||
  354.                             (strpos($currentFile'MACOSX'!== false)
  355.                         )
  356.                     ){
  357.                         if($fileInfo['dirname'== '.'){
  358.                             $path '';
  359.                         }
  360.                         else{
  361.                             $path Translit::transliterate(addslashes($fileInfo['dirname'])).'/';
  362.                         }
  363.  
  364.  
  365.                         //Directory
  366.                         if(!isset($fileInfo['extension'])){
  367.  
  368.                             $zip->renameIndex(
  369.                                 $i,
  370.                                 $currentFile $path.Translit::transliterate($fileInfo['filename'])
  371.                             );
  372.                         }
  373.                         else{
  374.                             $zip->renameIndex(
  375.                                 $i,
  376.                                 $currentFile $path.FileObject::generateFilename('' $fileInfo['extension'])
  377.                             );
  378.                         }
  379.  
  380.                         $zip->extractTo($this->uploadsDir->getPath()$currentFile);
  381.                         $f new FileObject();
  382.                         $f->createFromPath($this->uploadsDir->getPath().'/'.$currentFile$fileInfo['filename']);
  383.                     }
  384.                 }
  385.                 $zip->close();
  386.             }
  387.  
  388.  
  389.             $JSONResponse array(
  390.             'result' => true,
  391.             'mode' => 'insert'
  392.             );
  393.         }
  394.         catch (SystemException $e){
  395.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  396.             $JSONResponse array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message);
  397.  
  398.         }
  399.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  400.         $this->response->write(json_encode($JSONResponse));
  401.         $this->response->commit();
  402.     }
  403.  
  404.     /**
  405.      * Выводит форму создания файла
  406.      *
  407.      * @return void 
  408.      * @access protected
  409.      */
  410.  
  411.     protected function add({
  412.         $this->setType(self::COMPONENT_TYPE_FORM_ADD);
  413.         $this->prepare();
  414.     }
  415.  
  416.     /**
  417.      * Выводи форму загрузки Zip файла содержащего набор файлов
  418.      *
  419.      * @return void 
  420.      * @access protected
  421.      */
  422.     protected function uploadZip(){
  423.         $this->setType(self::COMPONENT_TYPE_FORM_ADD);
  424.         $this->prepare();
  425.     }
  426.  
  427.     /**
  428.      * Метод для заливки файла
  429.      * Вызывается в невидимом фрейме и должен отдать HTML страницу включающаю скрипт
  430.      *
  431.      * @return void 
  432.      * @access protected
  433.      * @final
  434.      */
  435.     final protected function upload({
  436.         $js =
  437.             'var doc = window.parent.document;'."\n".
  438.             'var path = doc.getElementById(\'path\');'."\n".
  439.             'var pb = doc.getElementById(\'progress_bar\'); '."\n".
  440.             'var filename = doc.getElementById(\'upl_name\'); '."\n".
  441.             'var iframe = doc.getElementById(\'uploader\');'."\n"/*.
  442.             'var preview = doc.getElementById(iframe.getAttribute("preview"));'."\n"*/;
  443.  
  444.         try {
  445.             if (empty($_FILES|| !isset($_FILES['file'])) {
  446.                 throw new SystemException('ERR_NO_FILE'SystemException::ERR_CRITICAL);
  447.             }
  448.  
  449.             $uploader new FileUploader();
  450.             $uploader->setFile($_FILES['file']);
  451.             $uploader->upload('tmp/');
  452.             $fileName $uploader->getFileObjectName();
  453.             if (($fileType FileSystemObject::getTypeInfo($fileName)) == FileSystemObject::IS_IMAGE{
  454.                 $js .= 'iframe.preview.src = "'.$fileName.'";';
  455.             }
  456.             elseif($fileType == FileSystemObject::IS_ZIP){
  457.                 $js .= 'iframe.preview.src = "images/icons/icon_zip.gif";';
  458.             }
  459.             else {
  460.                 $js .= 'iframe.preview.src = "images/icons/icon_undefined.gif";';
  461.             }
  462.             $js .= sprintf(
  463.             'filename.value = "%s";'.
  464.             'path.parentNode.removeChild(path);'.
  465.             'pb.parentNode.removeChild(pb); '.
  466.             'iframe.filename.value = "%s"; '/*.
  467.             'iframe.parentNode.removeChild(iframe);'*/,
  468.             $uploader->getFileRealName(),
  469.             $_POST['path'].'/'.basename($fileName)
  470.             );
  471.  
  472.         }
  473.         catch (SystemException $e{
  474.             $js .=
  475.             'path.parentNode.removeChild(path);'."\n".
  476.             'pb.parentNode.removeChild(pb); '."\n".
  477.             'alert(\''.$this->translate('TXT_SHIT_HAPPENS').': '.$e->getMessage().'\'); '/*.
  478.             'iframe.parentNode.removeChild(iframe); '*/."\n";
  479.         }
  480.  
  481.         $responseText '<html><head/><body><script type="text/javascript">'.$js.'</script></body></html>';
  482.         $response Response::getInstance();
  483.         $response->setHeader('Content-Type''text/html; charset=UTF-8');
  484.         $response->write($responseText);
  485.         $response->commit();
  486.     }
  487.  
  488.     /**
  489.      * Переименование файла/папки
  490.      *
  491.      * @return void 
  492.      * @access protected
  493.      */
  494.  
  495.      protected function rename({
  496.         try {
  497.             if (!isset($_POST['file'])) {
  498.  
  499.             }
  500.             if (($fileType key($_POST['file'])) == 'folder'{
  501.                 $file DirectoryObject::loadFrom($_POST['file'][$fileType]);
  502.             }
  503.             else {
  504.                 $file FileObject::loadFrom($_POST['file'][$fileType]);
  505.             }
  506.  
  507.             $file->rename($_POST['name']);
  508.  
  509.             $JSONResponse array(
  510.             'result' => true,
  511.             'mode' => 'insert'
  512.             );
  513.         }
  514.         catch (SystemException $e){
  515.             $message['errors'][array('message'=>$e->getMessage().current($e->getCustomMessage()));
  516.             $JSONResponse array_merge(array('result'=>false'header'=>$this->translate('TXT_SHIT_HAPPENS'))$message);
  517.  
  518.         }
  519.         $this->response->setHeader('Content-Type''text/javascript; charset=utf-8');
  520.         $this->response->write(json_encode($JSONResponse));
  521.         $this->response->commit();
  522.      }
  523. }
В создании документации нам помог: phpDocumentor