示例#1
0
 public function loadFilesFromPathAction()
 {
     $this->_disableRender();
     $path = "C:\\tmp_arquivos";
     $idCategoriaDownloads = "24";
     $onlyUpdate = $this->getRequest()->getParam('only_update');
     $db = $this->getModel()->getAdapter();
     $_categoria = new Cms_Model_Categoria_Mapper();
     $_conteudo = new Cms_DataView_Conteudo_MapperView();
     $sql = 'SELECT * FROM upload_arquivo WHERE aprovado = :aprovado';
     $bind = array('aprovado' => 'S');
     $dataArquivos = $db->fetchAll($sql, $bind);
     foreach ($dataArquivos as $fileData) {
         $fileDir = glob($path . "\\" . $fileData['id'] . ".*");
         if (count($fileDir)) {
             $fileDir = $fileDir['0'];
             $fileContent = file_get_contents($fileDir);
             $fileName = end(explode("\\", $fileDir));
             $_file = new ZendT_File($fileName, $fileContent);
             if ($onlyUpdate) {
                 $_conteudo->newRow()->setArquivo(array('file' => $_file->toFilenameCrypt()))->findAll(null, '*');
                 while ($_conteudo->fetch()) {
                     $_conteudo->setIdUsuarioInc($fileData['id_usuario_inc']);
                     $_conteudo->update();
                 }
                 echo ">>> Arquivo {$fileData['id']} atualizado com sucesso!<br/>";
             } else {
                 $sql = 'SELECT * FROM upload_assunto WHERE id = :id_upload_assunto';
                 $bind = array('id_upload_assunto' => $fileData['id_upload_assunto']);
                 $dataAssunto = $db->fetchRow($sql, $bind);
                 $_categoria->newRow()->setDescricao($dataAssunto['descricao'])->retrieve();
                 $idCategoria = $_categoria->getId();
                 if (!$idCategoria) {
                     $_categoria->newRow()->setIdCategoriaPai($idCategoriaDownloads)->setDescricao($dataAssunto['descricao'])->setTipo('A')->insert();
                     $idCategoria = $_categoria->getId()->toPhp();
                 }
                 $subtitulo = substr(trim($fileData['observacao']), 0, 100);
                 $_conteudo->newRow()->setIdCategoria($idCategoria)->setTitulo($fileData['nome']);
                 if (!$_conteudo->exists()) {
                     $_conteudo->setSubTitulo($subtitulo)->setIdUsuarioInc($fileData['id_usuario_inc'])->setArquivo(array('file' => $_file->toFilenameCrypt()))->insert();
                     echo "+++ Arquivo {$fileData['id']} inserido com sucesso!<br/>";
                 } else {
                     echo ">>> Arquivo {$fileData['id']} já existe na base de dados!<br/>";
                 }
             }
         } else {
             echo "--- Arquivo {$fileData['name']} não encontrado!<br/>";
         }
     }
 }
示例#2
0
文件: Csv.php 项目: rtsantos/mais
 public function __construct($options = false)
 {
     $this->_driver = 'CSV';
     $this->_badString = array(';', chr(10), chr(13));
     $this->_espapedString = array(' ', ' ', ' ');
     $this->_memoryManager = Zend_Memory::factory('none');
     $this->_memObject = $this->_memoryManager->create();
     try {
         $this->_fileName = 'Report_Excel_' . date('dmyhis') . '.csv';
         $file = new ZendT_File($this->_fileName);
         $this->_fileName = $file->getFilename();
         if (!$this->_fileName) {
             throw new ZendT_Exception('Impossivel criar aquivo', '2');
         }
     } catch (Exception $e) {
         throw new ZendT_Exception($e->getMessage(), $e->getCode());
     }
 }
示例#3
0
文件: Dynamic.php 项目: rtsantos/mais
 /**
  *
  * @return string 
  */
 public function render($type = '')
 {
     $content = parent::render();
     if ($type == 'PDF') {
         return $content;
     }
     $title = $this->_options['title'];
     $name = strtolower(str_replace(array(' '), array('-'), utf8_decode($title)));
     $nameIframe = strtolower('ifr' . clearAccent($name));
     $driver = strtolower($this->_options['driver']);
     $download = Zend_Controller_Front::getInstance()->getRequest()->getParam('download');
     $iframeDownload = Zend_Controller_Front::getInstance()->getRequest()->getParam('iframeDownload');
     $iframeHeight = Zend_Controller_Front::getInstance()->getRequest()->getParam('iframeHeight');
     if (!$driver) {
         $driver = 'pdf';
     }
     $file = new ZendT_File($name . '.' . $driver, $content, 'application/' . strtolower($driver));
     $fileUri = $file->toArrayJson();
     $cmdHtml = '';
     $src = ZendT_Url::getBaseUrl() . '/file';
     if ($driver == 'xls' || $download) {
         $src .= '/download';
         $width = 0;
         $height = 0;
         if (!$iframeDownload) {
             $cmdHtml .= '<div class="ui-widget ui-state-default ui-corner-all" style="height:30px;padding:5px;">' . "\n";
             $cmdHtml .= '    <span style="float:left;" class="ui-icon ui-icon-arrowstop-1-s"></span>' . "\n";
             $cmdHtml .= '    <span style="float:left;"><a href="javascript:javascript:downloadReport();">Se o download não iniciar automaticamente clique aqui.</a></span>' . "\n";
             $cmdHtml .= '    <span style="clear:both"></span>' . "\n";
             $cmdHtml .= '</div>' . "\n";
         }
     } else {
         if ($driver == 'html') {
             return $content;
         } else {
             $src .= '/pdf';
             $width = '100%';
             $height = '520';
             if (isset($this->_options['width'])) {
                 $width = $this->_options['width'];
             }
             if (isset($this->_options['height'])) {
                 $height = $this->_options['height'];
             }
         }
     }
     $src .= '?filename=' . $fileUri['filename'];
     $src .= '&type=' . $fileUri['type'];
     $src .= '&name=' . $fileUri['name'];
     $src .= '#zoom=120';
     $cmdHtml .= '<iframe';
     $cmdHtml .= ' id="' . $nameIframe . '"';
     $cmdHtml .= ' name="' . $nameIframe . '"';
     $cmdHtml .= ' src="' . $src . '"';
     $cmdHtml .= ' width="' . $width . '"';
     $cmdHtml .= ' height="100%"';
     $cmdHtml .= ' style="min-height:' . $height . 'px"';
     $cmdHtml .= ' border="0"';
     $cmdHtml .= ' frameborder="0"';
     $cmdHtml .= ' align="center"';
     $cmdHtml .= ' noresize="noresize"';
     $cmdHtml .= ' scrolling="yes"';
     if ($iframeDownload) {
         $cmdHtml .= ' onload="history.go(-1);"';
     }
     $cmdHtml .= '></iframe>';
     $cmdHtml .= '<script>function downloadReport(){this.' . $nameIframe . '.location = \'' . $src . '\'; }</script>';
     return $cmdHtml;
 }
示例#4
0
 /**
  * Ação para exportar os dados do grid para XLS
  */
 public function xlsAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender(true);
     $json = new ZendT_Json_Result();
     try {
         $result = $this->configReport('xls');
         $file = new ZendT_File($result['name'] . '.xls', $result['content'], 'application/vnd.ms-excel');
         $json->setResult($file->toArrayJson());
     } catch (ZendT_Exception $ex) {
         $json->setException($ex);
     }
     echo $json->render();
 }
示例#5
0
文件: Crud.php 项目: rtsantos/mais
 /**
  * Retorna um registro no modelo de dados
  *
  * @param ZendT_Service_Param $param
  * @return ZendT_Service_Result_Data
  */
 public function retrieve($param)
 {
     $result = new ZendT_Service_Result_Data();
     $result->service = __METHOD__;
     try {
         #$this->isAllowed($token,'insert');
         /**
          * @var ZendT_Db_Mapper 
          */
         if ($param->mapperView == '') {
             throw new ZendT_Exception('MapperView não informada.');
         } else {
             $this->_loadTranslate($param->mapperView);
         }
         $_mapper = new $param->mapperView();
         $where = $this->_getWhere($_mapper, $param->id, $param->filter, $param->filters, $param->filterOp);
         $postData['noPage'] = true;
         $dataGrid = $_mapper->getDataGrid($where, $postData);
         $columns = $_mapper->getColumns()->getColumnsGrid(true);
         $row = $dataGrid->getRow();
         $result->data = array();
         $retrieve = $this->_getTypeRetrieve($param);
         if ($row) {
             foreach ($columns as $column) {
                 $key = strtolower($column->getName());
                 $_data = new ZendT_Service_Data();
                 $_data->field = $key;
                 if ($row[$key] instanceof ZendT_Type_Blob) {
                     if (isset($row[$key . '_name'])) {
                         $name = $row[$key . '_name'];
                     } else {
                         $name = 'Arquivo-' . date('dmyhis') . '.txt';
                     }
                     if (isset($row[$key . '_type'])) {
                         $type = $row[$key . '_type'];
                     } else {
                         $type = 'application/txt';
                     }
                     $_file = new ZendT_File($name, $row[$key]->get(), $type);
                     $row[$key . '_name'] = $name;
                     $row[$key . '_type'] = $type;
                     $_data->value = $_file->toFilenameCrypt(true);
                 } else {
                     $_data->value = $row[$key]->{$retrieve}();
                 }
                 $result->data[] = $_data;
             }
         }
         $result->success = 1;
     } catch (ZendT_Exception $Ex) {
         $result->success = 0;
         $result->message->code = $Ex->getCode();
         $result->message->message = $Ex->getMessage();
         $result->message->show = $Ex->getShow();
         $result->message->notification = $Ex->getNotification();
     } catch (Exception $Ex) {
         $result->success = 0;
         $result->message->code = $Ex->getCode();
         $result->message->message = $Ex->getMessage();
         $result->message->show = 1;
         $result->message->notification = 'Error';
     }
     return $result;
 }
示例#6
0
文件: Blob.php 项目: rtsantos/mais
 /**
  * Retorna o valor no famato do banco de dados
  * 
  * @return string
  */
 public function getValueToDb()
 {
     if (strpos($this->_value, ZendT_File::ZENDT_FILE_PREFIX_FILENAME) !== false) {
         $file = ZendT_File::fromFilenameCrypt($this->_value);
         return $file->getContent();
     } else {
         if (file_exists($this->_value)) {
             return file_get_contents($this->_value);
         } else {
             return $this->_value;
         }
     }
 }
示例#7
0
文件: Printer.php 项目: rtsantos/mais
 /**
  * 
  * @param string $printerName
  * @param \ZendT_Printer_Document[] $documents
  * @return boolean
  * @throws ZendT_Exception_Error
  */
 public function printDocuments($printerName, $documents)
 {
     if (substr($printerName, 0, 4) == 'WSPS') {
         $ipServer = $this->getIpServer($printerName);
         $db = Zend_Registry::get('db.wsapi');
         $this->_clearDocuments($db);
         $i = 0;
         foreach ($documents as $document) {
             $i++;
             $sql = "begin\n                             wsapi.ws_printserver_pkg.adddocument(pcontent => :content,\n                                                                  pformname => :formname,\n                                                                  pfilename => :filename);\n                           end;";
             $stmt = $db->prepare($sql);
             $stmt->bindParam(':content', new ZendT_Type_Clob($document->getContent()));
             $stmt->bindParam(':formname', $document->getFormName());
             $stmt->bindParam(':filename', $document->getFileName());
             $stmt->execute();
             if ($i == 30) {
                 $this->_printDocuments($db, $printerName, $ipServer);
                 $this->_clearDocuments($db);
                 $i = 0;
             }
         }
         if ($i > 0) {
             $this->_printDocuments($db, $printerName, $ipServer);
             $this->_clearDocuments($db);
         }
         return true;
     } else {
         $this->startDocument();
         foreach ($documents as $document) {
             $this->addContent($document);
         }
         $contentRaw = $this->endDocument();
         $_file = new ZendT_File('', $contentRaw);
         $result = $_file->toUrlDownload();
         return $result;
     }
 }
示例#8
0
文件: Ftp.php 项目: rtsantos/mais
 /**
  * Cria um arquivo no servidor de forma temporária
  * 
  * @param string $content
  * @return string
  */
 private function _createFilenameTmp($content)
 {
     $_file = new ZendT_File('', $content);
     return $_file->getFilename();
 }
示例#9
0
文件: Xls.php 项目: rtsantos/mais
    public function __construct($options = false)
    {
        $default = array('empresa' => 'TA', 'orientation' => 'P', 'unit' => 'mm', 'size' => 'A4', 'outputName' => 'relatorio', 'lineIndex' => 0);
        $this->_badString = array('&', '<', '>', "'", '"', 'ª', 'º', '¿');
        $this->_espapedString = array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;', '', '', '');
        $this->_memoryManager = Zend_Memory::factory('none');
        $this->_memObject = $this->_memoryManager->create();
        $this->_numColumns = 1;
        if (is_array($options)) {
            $options = array_merge($default, $options);
        } else {
            $options = $default;
        }
        foreach ($options as $key => $value) {
            $this->{'_' . $key} = $value;
        }
        $this->_objStyles = array('FontName', 'FontSize', 'FontColor', 'FontBold', 'FontItalic', 'TextDecoration', 'BackgroundColor', 'BorderTop', 'BorderLeft', 'BorderRight', 'BorderBottom', 'TextAlign', 'Type');
        $this->_alignArray = array('L' => 'Left', 'R' => 'Right', 'C' => 'Center');
        $this->_estruturaAntes = '<?xml version="1.0" encoding="UTF-8"?>
    <?mso-application progid="Excel.Sheet"?>
    <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
    xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
    xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
    xmlns:html="http://www.w3.org/TR/REC-html40">
    <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
    <Author>TA</Author>
    <LastAuthor>TA</LastAuthor>
    <Created>' . date('Y-m-d') . 'T' . date('H:i:s') . 'Z</Created>
    <Company>TA</Company>
    <Version>11.5606</Version>
    </DocumentProperties>
    <OfficeDocumentSettings xmlns="urn:schemas-microsoft-com:office:office">
    <AllowPNG/>
    </OfficeDocumentSettings>
    <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
    <WindowHeight>9345</WindowHeight>
    <WindowWidth>11340</WindowWidth>
    <WindowTopX>480</WindowTopX>
    <WindowTopY>60</WindowTopY>
    <ProtectStructure>False</ProtectStructure>
    <ProtectWindows>False</ProtectWindows>
    </ExcelWorkbook>
    <Styles>
    <Style ss:ID="Default" ss:Name="Normal">
    <Alignment ss:Vertical="Bottom"/>
    <Borders/>
    <Font/>
    <Interior/>
    <NumberFormat/>
    <Protection/>
    </Style>
    <Style ss:ID="Title">
    <Font x:Family="Swiss" ss:Bold="1"/>
    </Style>
    <Style ss:ID="String">
        <Font ss:FontName="Arial" ss:Size="7" ss:Color="#000000"/>
        <Alignment ss:Horizontal="Left" ss:Indent="0"/>    
    </Style>
    <Style ss:ID="Numeric">

    </Style>
    <Style ss:ID="Integer"></Style>
    <Style ss:ID="Date">
    <NumberFormat ss:Format="Short Date"/>
    </Style>
    <Style ss:ID="DateTime">
    <NumberFormat ss:Format="d/m/yy\\ h:mm;@"/>
    </Style>
    <Style ss:ID="Time">
    <NumberFormat ss:Format="Short Time"/>
    </Style>
    <Style ss:ID="NumberTime">
    <NumberFormat ss:Format="[hh]:mm:ss"/>
    </Style>
    TaStyles
    </Styles>
    <Worksheet ss:Name="titleFile">
    <Table ss:ExpandedColumnCount="columnQuantity" ss:ExpandedRowCount="rowQuantity" x:FullColumns="1" x:FullRows="1">
    columns';
        $this->_estruturaDepois = '
    </Table>
    <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
    <PageSetup>
        <Header x:Margin="0.49212598499999999"/>
        <Footer x:Margin="0.49212598499999999"/>
        <PageMargins x:Bottom="0.984251969" x:Left="0.78740157499999996" x:Right="0.78740157499999996" x:Top="0.984251969"/>
    </PageSetup>
    <Print>
        <ValidPrinterInfo/>
        <PaperSizeIndex>9</PaperSizeIndex>
        <HorizontalResolution>600</HorizontalResolution>
        <VerticalResolution>600</VerticalResolution>
    </Print>
    <Selected/>
    <Panes>
        <Pane>
        <Number>3</Number>
        <ActiveRow>12</ActiveRow>
        <ActiveCol>6</ActiveCol>
        </Pane>
    </Panes>
    <ProtectObjects>False</ProtectObjects>
    <ProtectScenarios>False</ProtectScenarios>
    </WorksheetOptions>
    </Worksheet>
    <Worksheet ss:Name="Plan2">
    <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1"
    x:FullRows="1" ss:DefaultRowHeight="15">
    </Table>
    <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
    <PageSetup>
        <Header x:Margin="0.49212598499999999"/>
        <Footer x:Margin="0.49212598499999999"/>
        <PageMargins x:Bottom="0.984251969" x:Left="0.78740157499999996" x:Right="0.78740157499999996" x:Top="0.984251969"/>
    </PageSetup>
    <ProtectObjects>False</ProtectObjects>
    <ProtectScenarios>False</ProtectScenarios>
    </WorksheetOptions>
    </Worksheet>
    <Worksheet ss:Name="Plan3">
    <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1"
    x:FullRows="1" ss:DefaultRowHeight="15">
    </Table>
    <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
    <PageSetup>
        <Header x:Margin="0.49212598499999999"/>
        <Footer x:Margin="0.49212598499999999"/>
        <PageMargins x:Bottom="0.984251969" x:Left="0.78740157499999996" x:Right="0.78740157499999996" x:Top="0.984251969"/>
    </PageSetup>
    <ProtectObjects>False</ProtectObjects>
    <ProtectScenarios>False</ProtectScenarios>
    </WorksheetOptions>
    </Worksheet>
    </Workbook>
    ';
        $this->_lineIndex = 0;
        $this->_memObject->value = '';
        $this->_cellType = array('NumberTime' => 'DateTime', 'Numbertime' => 'DateTime', 'Time' => 'DateTime', 'Datetime' => 'DateTime', 'DateTime' => 'DateTime', 'Date' => 'DateTime', 'Number' => 'Number', 'Integer' => 'Number', 'Numeric' => 'Number', 'String' => 'String');
        try {
            $this->_name = 'Report_Excel_' . time() . '.xml';
            $file = new ZendT_File($this->_name);
            $this->_fileName = $file->getFilename();
            if (!$this->_fileName) {
                throw new ZendT_Exception('Impossivel criar aquivo', '2');
            }
            //$this->_fileStream = fopen($this->_fileName, 'r+');
        } catch (Exception $e) {
            throw new ZendT_Exception($e->getMessage(), $e->getCode());
        }
    }
示例#10
0
文件: Action.php 项目: rtsantos/mais
 protected function _retrieve()
 {
     $param = $this->getRequest()->getParams();
     if (isset($param['id']) && strpos($param['id'], ',') !== false) {
         $multi = true;
         /**
          * @todo analisar uma forma de popular o Mapper para identificação da coluna
          */
         $tableName = $this->getMapper()->getModel()->getName();
         $columnId = $this->getMapper()->getModel()->getPrimary();
         $columnId = $columnId[0];
         $where = new ZendT_Db_Where();
         $where->addFilter($tableName . '.' . $columnId, explode(',', $param['id']), 'in', $this->getMapper()->getModel()->getMapperName());
     } else {
         $multi = false;
         $where = $this->getMapper()->getWhere($param);
     }
     $wData = array('noPage' => true, 'returnType' => true);
     if ($param['findAll']) {
         $multi = true;
         $wData['count'] = false;
     }
     if ($this->_mapper instanceof ZendT_Db_View) {
         $dataGrid = $this->getMapper()->getDataGrid($where, $wData, true);
     } else {
         $dataGrid = $this->getModel()->getDataGrid($where, $wData);
     }
     $result = array();
     while ($row = $dataGrid->getRow()) {
         if ($row && count($row) > 0) {
             foreach ($row as $key => &$value) {
                 if ($value instanceof ZendT_Type_Blob) {
                     if (isset($row[$key . '_name'])) {
                         $name = $row[$key . '_name'];
                     } else {
                         $name = 'Arquivo-' . date('dmyhis') . '.txt';
                     }
                     if (isset($row[$key . '_type'])) {
                         $type = $row[$key . '_type'];
                     } else {
                         $type = 'application/txt';
                     }
                     $_file = new ZendT_File($name, $value->get(), $type);
                     $value = $_file->toFilenameCrypt();
                     $row[$key . '_id'] = $_file->getId();
                     $row[$key . '_name'] = $name;
                     $row[$key . '_type'] = $type;
                     $row[$key . '_file'] = $value;
                 } elseif ($value instanceof ZendT_Type_FileSystem) {
                     $_file = $value->getFile();
                     if ($_file) {
                         $row[$key . '_name'] = $_file->getName();
                         $row[$key . '_type'] = $_file->getType();
                         $row[$key . '_id'] = $_file->getId();
                         $row[$key . '_file'] = $_file->toFilenameCrypt();
                         $value = $_file->getName();
                     } else {
                         unset($row[$key]);
                     }
                 } elseif ($value instanceof ZendT_Type) {
                     $value = $value->get();
                 }
             }
             $listOptions = $this->getModel()->getListOptions();
             foreach ($this->getColumns() as $column) {
                 if (!$dataGrid->isRowFormated()) {
                     if (isset($listOptions[$column->getName()])) {
                         $chave = array_search($row[$column->getName()], $listOptions[$column->getName()]);
                         if ($chave !== false) {
                             $row[$column->getName()] = $column->format($chave);
                         }
                     }
                     $row[$column->getName()] = $column->format($row[$column->getName()]);
                 } else {
                     if (isset($listOptions[$column->getName()])) {
                         $chave = array_search($row[$column->getName()], $listOptions[$column->getName()]);
                         if ($chave !== false) {
                             $row[$column->getName()] = $chave;
                         }
                     }
                 }
             }
         }
         // $referenceMap = $this->getMapper()->getReferenceMap();
         // if (count($referenceMap) > 0) {
         // foreach ($referenceMap as $column => $prop) {
         // $column = strtolower($column);
         // if (isset($row[$column]) && $row[$column]) {
         // $id = $row[$column];
         // $_mapper = new $prop['mapper'];
         // $action = 'set' . $this->getMapper()->fieldToMethod($prop['column']);
         // unset($row[$column]);
         // $row[$column] = $_mapper->$action($id)->retrieveRow();
         // }
         // }
         // }
         $this->_prepareRetrieveRow($row);
         if ($multi == false) {
             $result = $row;
             break;
         } else {
             $result[] = $row;
         }
     }
     return $result;
 }
示例#11
0
 public function pluploadAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender(true);
     $json = new ZendT_Json_Result();
     try {
         $targetDir = ZendT_Lib::getTmpDir() . '/files/' . DIRECTORY_SEPARATOR . "plupload";
         // Create target dir
         if (!file_exists($targetDir)) {
             @($result = mkdir($targetDir));
             if (!$result) {
                 throw new ZendT_Exception_Error('Não foi possível criar o diretório "$targetDir".', 1001);
             }
         }
         if (!file_exists($targetDir)) {
             @($result = mkdir($targetDir));
             if (!$result) {
                 throw new ZendT_Exception_Error('Não foi possível criar o diretório "$targetDir".', 1001);
             }
         }
         //$targetDir = 'uploads';
         $cleanupTargetDir = true;
         // Remove old files
         $maxFileAge = 1 * 3600;
         // Temp file age in seconds
         // 5 minutes execution time
         @set_time_limit(5 * 60);
         // Uncomment this one to fake upload time
         // usleep(5000);
         // Get parameters
         $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
         $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
         $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
         // Clean the fileName for security reasons
         $fileName = removeAccent(trim($fileName));
         $fileName = preg_replace('/[^\\w\\._]+/', '_', $fileName);
         $fileName = str_replace(' ', '_', $fileName);
         // Make sure the fileName is unique but only if chunking is disabled
         if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
             $ext = strrpos($fileName, '.');
             $fileName_a = substr($fileName, 0, $ext);
             $fileName_b = substr($fileName, $ext);
             $count = 1;
             while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) {
                 $count++;
             }
             $fileName = $fileName_a . '_' . $count . $fileName_b;
         }
         $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
         // Remove old temp files
         if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
             while (($file = readdir($dir)) !== false) {
                 $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                 // Remove temp file if it is older than the max age and is not the current file
                 if (preg_match('/\\.part$/', $file) && filemtime($tmpfilePath) < time() - $maxFileAge && $tmpfilePath != "{$filePath}.part") {
                     @unlink($tmpfilePath);
                 }
             }
             closedir($dir);
         } else {
             throw new ZendT_Exception_Error('Failed to open temp directory.', 100);
         }
         // Look for the content type header
         if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
             $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
         }
         if (isset($_SERVER["CONTENT_TYPE"])) {
             $contentType = $_SERVER["CONTENT_TYPE"];
         }
         // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
         if (strpos($contentType, "multipart") !== false) {
             if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                 // Open temp file
                 $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                 if ($out) {
                     // Read binary input stream and append it to temp file
                     $in = fopen($_FILES['file']['tmp_name'], "rb");
                     if ($in) {
                         while ($buff = fread($in, 4096)) {
                             fwrite($out, $buff);
                         }
                     } else {
                         throw new ZendT_Exception_Error('Failed to open input stream.', 101);
                     }
                     fclose($in);
                     fclose($out);
                     @unlink($_FILES['file']['tmp_name']);
                 } else {
                     throw new ZendT_Exception_Error('Failed to open output stream.', 102);
                 }
             } else {
                 throw new ZendT_Exception_Error('Failed to move uploaded file.', 103);
             }
         } else {
             // Open temp file
             $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen("php://input", "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     throw new ZendT_Exception_Error('Failed to open input stream.', 104);
                 }
                 fclose($in);
                 fclose($out);
             } else {
                 throw new ZendT_Exception_Error('Failed to open output stream.', 105);
             }
         }
         // Check if file has been uploaded
         if (!$chunks || $chunk == $chunks - 1) {
             // Strip the temp .part suffix off
             @($result = rename("{$filePath}.part", $filePath));
             if (!$result) {
                 throw new ZendT_Exception_Error('Não foi possível renomear o arquivo.', 1002);
             }
         }
         if ($this->getRequest()->getParam('platform')) {
             $_file = new ZendT_File($fileName, file_get_contents($filePath), $_FILES['file']['type']);
             if (file_exists($filePath)) {
                 unlink($filePath);
             }
             $infoFile = $_file->toArrayJson();
             $infoFile['size'] = $_FILES['file']['size'];
             $infoFile['type'] = $_FILES['file']['type'];
             $json->setResult($infoFile);
         } else {
             $json->setResult(base64_encode($filePath));
         }
     } catch (Exception $Ex) {
         $json->setException($Ex);
     }
     echo $json->toRpc();
 }
示例#12
0
 /**
  * Salva o arquivo no diretório e na tabela (inclui / altera)
  * 
  * @param ZendT_File $file - arquivo
  * @param array $configs - configurações de propriedades do arquivo
  * @param array $param - propriedades do arquivo
  * @return integer - id do arquivo salvo
  */
 private function _saveFile($file, $configs, &$param)
 {
     $_propDocto = $this->_getPropDocto($param->propName);
     $param->fileName = $file->getName();
     $fileContent = $file->getContent();
     $fileType = $file->getContentType();
     $hashCode = md5($fileContent);
     $fileName = $this->_formatFileName($hashCode, $param->fileName);
     $propName = $param->propName;
     $dtExpira = '';
     $_arquivo = new Ged_DataView_Arquivo_MapperView();
     $_arquivo->setHashcode($hashCode);
     $path = $this->getFilePath($configs['bkpProp'], $propName, $fileName);
     $_arquivo->setPathArq($path['path']);
     if (!$_arquivo->exists()) {
         #$_arquivo->setPathArq($path['path']);
     } else {
         $_arquivo_aux = clone $_arquivo;
         $dtExpira = $_arquivo_aux->retrieve()->getDtExpira()->toPhp();
     }
     if ($configs['lifeTime'] && !$dtExpira) {
         $dtExpira = ZendT_Type_Date::nowDate()->addDay($configs['lifeTime']);
         $_arquivo->setDtExpira($dtExpira);
     }
     $_arquivo->setConteudoName($param->fileName);
     $_arquivo->setIdPropDocto($_propDocto->getId());
     $_arquivo->setConteudoType($fileType);
     if ($configs['bkpProp'] == 2 && $param->fileId) {
         $_arquivo->setId($param->fileId);
         $_arquivo_aux = new Ged_DataView_Arquivo_MapperView();
         $_arquivo_aux->setId($_arquivo->getId());
         if ($_arquivo_aux->exists()) {
             $_arquivo_aux->retrieve();
             if ($_arquivo_aux->getHashCode()->toPhp() != $_arquivo->getHashcode()->toPhp()) {
                 $this->remove($_arquivo->getId(), false);
                 $_arquivo->update();
                 //$path_aux = $this->_getArquivoPath($_arquivo->getId()->toPhp());
             }
         }
     }
     $idArquivo = $_arquivo->save(true);
     //echo "Path: " . $path['full'] . "\n";
     if (!file_exists($path['full'])) {
         if (!file_exists($path['pathBase'])) {
             //mkdir($path['pathBase'], null, true);
             $this->mkdirRecursive($path['pathBase']);
         }
         $result = file_put_contents($path['full'], $file->getContent());
         if (!$result) {
             throw new ZendT_Exception('Erro ao armazenar o arquivo no servidor "' . $path['full'] . '". Erro: "' . $php_errormsg . '" ');
         }
         if (!$result) {
             throw new ZendT_Exception('Não foi possível salvar o arquivo "' . $path['full'] . '"');
         } else {
             if ($this->_config['linux']) {
                 $this->_execCmd("chmod 777 {$path['full']} -R");
             }
         }
     }
     if ($param->parentId) {
         $_docto = new Ged_DataView_Docto_MapperView();
         $_docto->setIdPropRelac($param->parentId);
         $_docto->setDescricao($param->desc);
         $_docto->setDhInclusao("SYSDATE");
         $_docto->setIdArquivo($idArquivo);
         $_docto->setIdTipoDocto($param->typeId);
         $_docto->setIdUsuIncl($param->userId);
         $idDocto = $_docto->save();
     }
     return $idArquivo;
 }
示例#13
0
 /**
  * 
  * @param type $value
  * @param type $options
  * @param type $locale
  */
 public function set($value, $options = null, $locale = null)
 {
     if ($value && is_numeric($value)) {
         $this->_valueDb = $value;
     } else {
         if ($value instanceof ZendT_File) {
             $this->_value = $value;
         } else {
             if ($value !== null && $value) {
                 $file = ZendT_File::fromFilenameCrypt($value);
                 $this->_value = $file;
             }
         }
     }
     if (!is_array($this->_options)) {
         $this->_options = array();
     }
     if (!is_array($options)) {
         $options = array();
     }
     $this->_options = array_merge($this->_options, $options);
     $this->_locale = $locale;
     return $this;
 }
示例#14
0
文件: File.php 项目: rtsantos/mais
 /**
  * Configura o nome do arquivo criptografado
  * 
  * @param type $filename
  * @return \ZendT_File 
  */
 public static function fromFilenameCrypt($crypt)
 {
     $crypt = urldecode($crypt);
     $file = new ZendT_File();
     $crypt = str_replace(ZendT_File::ZENDT_FILE_PREFIX_FILENAME . '-', '', $crypt);
     //$deCrypt = mcrypt_decrypt($file->getAlgorithm(),$file->getKey(),$crypt);
     $deCrypt = utf8_decode(base64_decode($crypt));
     $pos = strrpos($deCrypt, '/');
     $name = substr($deCrypt, $pos + 1);
     $folder = substr($deCrypt, 0, $pos);
     return $file->setName($name)->setFolder($folder);
 }