Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 99
TFileAsync
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 16
1640
0.00% covered (danger)
0.00%
0 / 99
 __construct
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 8
 show
0.00% covered (danger)
0.00%
0 / 1
42
0.00% covered (danger)
0.00%
0 / 33
 setMaxSize
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getMaxSize
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 10
 validate
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 4
 clear
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 9
 setAllowedFileTypes
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getAllowedFileTypes
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getFileExtension
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 4
 getContent
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getTempFile
0.00% covered (danger)
0.00%
0 / 1
72
0.00% covered (danger)
0.00%
0 / 15
 getFileName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setCallBackJs
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getCallBackJs
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setMessageInvalidFileType
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getMessageInvalidFileType
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
1<?php
2/*
3 * Formdin Framework
4 * Copyright (C) 2012 Ministério do Planejamento
5 * Criado por Luís Eugênio Barbosa
6 * Essa versão é um Fork https://github.com/bjverde/formDin
7 *
8 * ----------------------------------------------------------------------------
9 * This file is part of Formdin Framework.
10 *
11 * Formdin Framework is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License version 3
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public License version 3
21 * along with this program; if not,  see <http://www.gnu.org/licenses/>
22 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
23 * Fifth Floor, Boston, MA  02110-1301, USA.
24 * ----------------------------------------------------------------------------
25 * Este arquivo é parte do Framework Formdin.
26 *
27 * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou
28 * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação
29 * do Software Livre (FSF).
30 *
31 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
32 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
33 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português
34 * para maiores detalhes.
35 *
36 * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
37 * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/>
38 * ou escreva para a Fundação do Software Livre (FSF) Inc.,
39 * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
40 */
41
42class TFileAsync extends TEdit
43{
44    private $maxSize;
45    private $allowedFileTypes;
46    private $jsCallBack;
47    private $messageInvalidFileType;
48    /**
49    * Classe para fazer upload de arquivo de forma asyncrona
50    * $intSize = numero de caracteres do arquivo anexado que serão exibido na tela, pode ser utilizado
51    * o parametro $intWidth tambem
52    *
53    * O parametro $strJsCallBack define a função javascript que será chamada quando o upload assincrono terminar.
54    * Esta função receberá, como parametros, o nome do arquivo temporário e o nome do arquivo anexado.
55    *
56    * @param string $strName
57    * @param integer $intSize
58    * @param boolean  $boolRequired
59    * @param string $strAllowedFileTypes
60    * @param string $strMaxSize
61    * @param integer $intWidth
62    * @param $strJsCallBack
63    * @return TFileAsync
64    */
65    public function __construct($strName,$intSize=null,$boolRequired=null,$strAllowedFileTypes=null,$strMaxSize=null,$intWidth=null,$strJsCallBack=null,$strMessageInvalidFileType=null)
66    {
67        $intSize= is_null($intSize) ? 50 : $intSize;
68        parent::__construct($strName,null,5000,$boolRequired,$intSize);
69        $this->setFieldType('fileAsync');
70        $this->setMaxSize($strMaxSize);
71        $this->setAllowedFileTypes($strAllowedFileTypes);
72        //$this->setEnabled(false);
73        $this->jsCallBack = $strJsCallBack;
74        $this->setMessageInvalidFileType($strMessageInvalidFileType);
75        //$intWidth = $intWidth === null ? '300px' : $intWidth;
76        //$this->setWidth($intWidth);
77    }
78    /**
79    * Exibe o html ou devolve o html se $print for false
80    *
81    * @param bool $print
82    * @return mixed
83    */
84    public function show($print=true)
85    {
86        $table = new TTable($this->getId().'_table');
87        $row = $table->addRow();
88        // adiciona o iframe de suporte ao campo arquivo
89        $size= new THidden($this->getId().'_size');
90        $tempFileNameHidden = new THidden($this->getId().'_temp_name',(  isset( $_REQUEST[ $this->getId().'_temp_name'] ) ? $_REQUEST[ $this->getId().'_temp_name'] : '' ) );
91        $fileExtension = new THidden($this->getId().'_extension');
92        $fileExtension->setValue($this->getFileExtension());
93        $fileType = new THidden($this->getId().'_type');
94        $this->setCss('background-repeat',"no-repeat");
95        $iframe = new TElement('iframe');
96        $iframe->setId($this->getId().'_upload_iframe');
97        $iframe->setName($this->getId().'_upload_iframe');
98        $iframe->setCss('padding','0px');
99        $iframe->setCss('margin','0px');
100        $iframe->setCss('width','130px');
101        $iframe->setCss('height','23px');
102        $iframe->setCss('border-width','0px');
103        $iframe->setCss('margin-width','0px');
104        $iframe->setCss('overflow','hidden');
105        $iframe->setCss('vertical-align','top');
106        //$iframe->setCss('background-color','green');
107        $boolReadOnly = $this->getReadOnly() ? 1 : 0;
108        $iframe->setProperty('frameBorder','0');
109        $iframe->setProperty("allowTransparency","true");
110        $indexFileName = $this->getIndexFileName();
111       if( $indexFileName )
112       {
113           $iframe->setProperty('src',$this->getIndexFileName().'?ajax=1&modulo='.$this->getBase().'includes/upload.php&readOnly='.$boolReadOnly.'&name='.$this->getId().'&tamanhoMaxAlert='.$this->maxSize.'&tamanhoMaxBytes='.$this->getMaxSize().'&callBack='.$this->jsCallBack.'&messageInvalidFileType='.$this->getMessageInvalidFileType());
114       }
115       else
116       {
117           $iframe->setProperty('src',$this->getBase().'includes/upload.php?readOnly='.$boolReadOnly.'&name='.$this->getId().'&tamanhoMax='.$this->maxSize.'&callBack='.$this->jsCallBack.'&messageInvalidFileType='.$this->getMessageInvalidFileType());
118       }
119
120        $_SESSION['frmFileAsync'][$this->getId()]['tiposValidos']     = $this->getAllowedFileTypes();
121        $_SESSION['frmFileAsync'][$this->getId()]['tamanhoKb']         = $this->getMaxSize();
122        $img = ( isset( $_REQUEST[$this->getId().'_temp_name'] ) && $_REQUEST[$this->getId().'_temp_name'] ) ? 'lixeira.gif': 'lixeira_disabled.gif';
123        $btnDelete = new TButton($this->getId().'_btn_delete',null,null,'fwClearFileAsync("'.$this->getId().'")',null,$img);
124        $this->setReadOnly(true);
125        $row->addCell( parent::show(false).$btnDelete->show(false).$iframe->show(false).$size->show(false).$tempFileNameHidden->show(false).$fileExtension->show(false).$fileType->show(false))->setProperty('nowrap','true');
126
127        return $table->show($print);
128        //return '<table id="xxxx"><tr><td nowrap>'.parent::show(false).$iframe->show(false).$size->show(false).'</td></tr></table>';
129    }
130    //-------------------------------------------------------------------------------------------
131    /**
132    * Define o tamanho máximo do arquivo permitido
133    * Pode ser definido assim:
134    * ex: 1T, 2G, 30M, 1024KB
135    * se não for espeficificado a unidade T, G, M, KB será assumido KB
136    * @param string $strMaxSize
137    */
138    public function setMaxSize($strMaxSize=null)
139    {
140        $strMaxSize = is_null($strMaxSize) ? ini_get('post_max_size') : $strMaxSize;
141        $this->maxSize = $strMaxSize;
142    }
143    /**
144    * Retorna o tamanho máximo em bytes permitido para o arquivo ser válido
145    *
146    */
147    public function getMaxSize()
148    {
149        $maxSize = preg_replace('/[^0-9]/','',$this->maxSize);
150    $bytes=1024; // padrao 1kb
151    if( strpos(strtoupper($this->maxSize),'M')!==false )
152    {
153        // megabytes
154        $bytes  =  ( 1024 * $maxSize ) * 1024;
155        $this->setMaxSize($maxSize.'Mb');
156    }
157    else if( strpos(strtoupper($this->maxSize),'G')!==false )
158    {
159        // gigabytes
160        $bytes = ( ( 1024 *1024 ) * $maxSize) * 1024;
161        $this->setMaxSize($maxSize.'Gb');
162    }
163    else
164    {
165        $this->setMaxSize('1Kb');
166    }
167    return $bytes;
168}
169/**
170    * faz a validação da extensão e do tamanho máximo permitido
171    *
172    */
173    public function validate()
174    {
175        //verficar se o arquivo está no servidor
176        $filename = $this->getTempFile();
177
178        if ( !FileHelper::exists($filename) && $this->getRequired() )
179        {
180            $this->addError('Campo obrigatório');
181        }
182        return ( (string)$this->getError()==="" );
183    }
184    //------------------------------------------------------------------------
185    public function clear()
186    {
187        // excluir o arquivo temporário
188        if( FileHelper::exists($this->getTempFile()) ){
189            @unlink($this->getTempFile());
190        }
191        if( isset( $_REQUEST[$this->getId().'_temp_name'] ) )
192        {
193            $_REQUEST[$this->getId().'_temp_name']=null;
194            $_REQUEST[$this->getId().'_name']=null;
195            $_REQUEST[$this->getId().'_size']=null;
196            $_REQUEST[$this->getId().'_extension']=null;
197        }
198        // excluir os campos ocultos que registram os dados do arquivo anexo
199        parent::clear();
200    }
201    /**
202    * Define as extensões de arquivos permitidas.
203    * Devem ser informadas separadas por virgula
204    * Ex: doc,gif,jpg
205    *
206    * @param string $strNewFileTypes
207    */
208    public function setAllowedFileTypes($strNewFileTypes=null)
209    {
210        $this->allowedFileTypes = $strNewFileTypes;
211    }
212    /**
213    * Recupera os tipos de extensões permitidas
214    *
215    */
216    public function getAllowedFileTypes()
217    {
218        return $this->allowedFileTypes;
219    }
220    /**
221    * Retorna a extensão do arquivo anexado
222    * Ex. teste.gif -> retorna: gif
223    */
224    public function getFileExtension() {
225        $value = $this->getValue();
226        $filename  = isset($value)?strtolower($value):null;
227        $aFileInfo = isset($filename)?pathinfo( $filename ):null;
228        return  isset( $aFileInfo[ 'extension' ] ) ? $aFileInfo[ 'extension' ]  : '';
229    }
230    /**
231    * Retorna o conteudo do arquivo anexado
232    *
233    */
234    public function getContent()
235    {
236        if($this->getTempFile())
237        {
238            return file_get_contents($this->getTempFile());
239        }
240        return null;
241    }
242    /**
243    * Retorna o nome temporário do arquivo gravado na pasta base/tmp
244    *
245    */
246    public function getTempFile()
247    {
248        if( isset($_POST[$this->getId().'_temp_name']))
249        {
250            $tempFileName = $_POST[$this->getId().'_temp_name'];
251        }
252        else if( isset($_GET[$this->getId().'_temp_name']))
253        {
254            $tempFileName = $_GET[$this->getId().'_temp_name'];
255        }
256        else if( isset($_REQUEST[$this->getId().'_temp_name']))
257        {
258            $tempFileName = $_REQUEST[$this->getId().'_temp_name'];
259        }
260        if( FormDinHelper::pregMatch('/base\//',$tempFileName)) {
261            $x = strpos($tempFileName,'base/');
262            $tempFileName = $this->getBase.substr($tempFileName,($x+5));
263        }
264        if( $tempFileName) {
265            if(FileHelper::exists($tempFileName)) {
266                return $tempFileName;
267            } else {
268                // procurar no diretorio base/tmp
269                if(FileHelper::exists($this->getBase().$tempFileName)){
270                    return $this->getBase().$tempFileName;
271                }
272            }
273        }
274        return null;
275    }
276    /**
277    * Retorna o caminho completo do arquivo na pasta temporária
278    *
279    */
280    public function getFileName()
281    {
282        return $this->getValue();
283    }
284    /**
285    * Define a função javascript que será chamada quando o upload assincrono terminar.
286    * Serão passados o nome do arquivo temporário e o nome do arquivo anexado
287    *
288    * @param string $strNewValue
289    */
290    public function setCallBackJs($strNewValue=null)
291    {
292        $this->jsCallBack=$strNewValue;
293    }
294    public function getCallBackJs()
295    {
296        return $this->jsCallBack;
297    }
298    public function setMessageInvalidFileType( $strNewValue=null )
299    {
300        $this->messageInvalidFileType = $strNewValue;
301    }
302    public function getMessageInvalidFileType()
303    {
304        return $this->messageInvalidFileType;
305    }
306
307
308}
309?>