Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
43.75% covered (warning)
43.75%
7 / 16
CRAP
53.92% covered (warning)
53.92%
55 / 102
TFile
0.00% covered (danger)
0.00%
0 / 1
43.75% covered (warning)
43.75%
7 / 16
147.10
53.92% covered (warning)
53.92%
55 / 102
 __construct
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
26 / 26
 setPostFileInfo
0.00% covered (danger)
0.00%
0 / 1
7.46
40.00% covered (warning)
40.00%
4 / 10
 getMsgUploadException
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setMsgUploadException
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 setMaxSize
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
4 / 4
 getMaxSize
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 setMaxSizeKb
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
15 / 15
 getMaxSizeKb
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 validate
0.00% covered (danger)
0.00%
0 / 1
56
0.00% covered (danger)
0.00%
0 / 16
 clear
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 9
 setAllowedFileTypes
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 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
2
0.00% covered (danger)
0.00%
0 / 5
 getValue
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 7
 getFileName
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getTempFile
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 TFile extends TEdit {
43    private $maxSize;
44    private $maxSizeKb;
45    private $allowedFileTypes;
46    private $msgUploadException;
47    
48    
49    
50    public function __construct($strName,$intSize=null,$boolRequired=null,$strAllowedFileTypes=null,$strMaxSize=null) {
51        $intSize= is_null($intSize) ? 50 : $intSize;
52        parent::__construct($strName,null,5000,$boolRequired,$intSize);
53        $this->setFieldType('file');
54        $this->setProperty('type','file');
55        $this->setMaxSize($strMaxSize);
56        $this->setMaxSizeKb($strMaxSize);
57        $this->setAllowedFileTypes($strAllowedFileTypes);
58        $this->addEvent('onchange','fwCampoArquivoChange(this)');
59        // guardar os dados do arquivo temporário postado em campos ocultos
60        try {
61            $this->setPostFileInfo();
62        } catch (Exception $e) {
63            $this->setMsgUploadException($e->getMessage());
64        }
65        
66        $temp= new THidden($this->getId().'_temp');
67        $this->setValue($temp->getValue());
68        $btnClear = new TButton($this->getId().'_clear','Apagar',null,'fwLimparCampoAnexo(this,"'.$this->getId().'")',null,'lixeira.gif','lixeira_bw.gif');
69        //$btnClear->setEnabled( ($imageClear=='lixeira.gif'));
70        $btnClear->setProperty('title','Limpar arquivo anexado');
71        $btnClear->setCss('width','16');
72        $btnClear->setCss('height','16');
73        
74        $this->add($btnClear);
75        //$this->add($btnView);
76        $this->add($temp);
77        // adiciona os campos ocultos de suporte ao campo arquivo
78        $type= new THidden($this->getId().'_type');
79        $this->add($type);
80        $size= new THidden($this->getId().'_size');
81        $this->add($size);
82        $name= new THidden($this->getId().'_name');
83        $this->add($name);
84    }
85    //-------------------------------------------------------------------------------------------
86    /**
87     * define os valores dos campos ocultos que serão adicionados ao form
88     * @throws UploadException
89     */
90    public function setPostFileInfo(){
91        if(isset($_FILES[$this->getId()])) {
92            if( $_FILES[$this->getId()]['error'] == UPLOAD_ERR_OK ) {
93                $to = $this->getBase().'tmp/'.$_FILES[$this->getId()]['name'];
94                if( move_uploaded_file( $_FILES[$this->getId()]['tmp_name'],$to ) ) {
95                    $_POST[$this->getId().'_temp']     = $to;
96                    $_POST[$this->getId().'_type']     = $_FILES[$this->getId()]['type'];
97                    $_POST[$this->getId().'_size']     = $_FILES[$this->getId()]['size'];
98                    $_POST[$this->getId().'_name']    = $_FILES[$this->getId()]['name'];
99                }
100            }else{
101                throw new UploadException($_FILES[$this->getId()]['error']);
102            }
103        }
104    }
105    //-------------------------------------------------------------------------------------------
106    public function getMsgUploadException() {
107        return $this->msgUploadException;
108    }
109    //-------------------------------------------------------------------------------------------
110    public function setMsgUploadException($msgUploadException) {
111        $this->msgUploadException = $msgUploadException;
112    }
113    //-------------------------------------------------------------------------------------------
114    public function setMaxSize($strMaxSize=null){
115        $post_max_size = ini_get('post_max_size');
116        $strMaxSize = is_null($strMaxSize) ? $post_max_size : $strMaxSize;
117        $this->maxSize = $strMaxSize;
118    }
119    //-------------------------------------------------------------------------------------------
120    public function getMaxSize(){
121        return $this->maxSize;
122    }
123    //-------------------------------------------------------------------------------------------
124    public function setMaxSizeKb($strMaxSize=null){
125        $this->setMaxSize($strMaxSize);
126        
127        $maxSize = preg_replace('/[^0-9]/','',$this->getMaxSize());
128        $fator = null;
129        $sizeKilbytes = 1024;
130        if( strpos(strtoupper($this->getMaxSize()),'M')!==false ) {
131            // megabytes
132            $fator = pow($sizeKilbytes,2);
133            $this->setMaxSize($maxSize.'Mb');
134        } else if( strpos(strtoupper($this->getMaxSize()),'G')!==false ) {
135            // gigabytes
136            $fator = pow($sizeKilbytes,3);
137            $this->setMaxSize($maxSize.'Gb');
138        } else {
139            // padrão é kilbytes
140            $fator = $sizeKilbytes;
141            $this->setMaxSize($maxSize.'Kb');
142        }
143        
144        $maxSize = $maxSize*$fator;
145        $this->maxSizeKb = $maxSize;
146    }
147    //-------------------------------------------------------------------------------------------
148    public function getMaxSizeKb(){
149        return $this->maxSizeKb;
150    }
151    //-------------------------------------------------------------------------------------------
152    public function validate() {
153        if( parent::validate()) {
154            if($this->getMsgUploadException()){
155                $this->addError('ERRO interno: '.$this->getMsgUploadException());
156            }else{
157                $fileSizeKb = PostHelper::get($this->getId().'_size');
158                if( $fileSizeKb ) {
159                    $maxSize = $this->getMaxSizeKb();
160                    if( (int)$fileSizeKb > (int)$maxSize) {
161                        $msg = 'Tamanho máximo permitido '.$this->getMaxSize().' O arquivo selecionado possui '.ceil($_POST[$this->getId().'_size'] / 1024).'Kb';
162                        $this->addError($msg);
163                        $this->clear();
164                        $this->setCss('border','1px solid #ff0000');
165                    } else {
166                        // validar extensão
167                        if( $this->getAllowedFileTypes() ) {
168                            $aExtensions = explode(',',strtolower($this->getAllowedFileTypes()));
169                            if( array_search($this->getFileExtension(),$aExtensions)===false) {
170                                $this->addError('Arquivo inválido. Tipo(s) válido(s):'.$this->getAllowedFileTypes());
171                            }
172                        }
173                    }
174                }
175            }
176        }
177        return ( (string)$this->getError()==="" );
178    }
179    //------------------------------------------------------------------------
180    public function clear()
181    {
182        // excluir o arquivo temporário
183        if( FileHelper::exists($this->getValue(true)))
184        {
185            unlink($_POST[$this->getId().'_temp']);
186        }
187        // excluir os campos ocultos que registram os dados do arquivo anexo
188        $this->clearChildren();
189        // limpar os valores postados
190        unset($_POST[$this->getId().'_temp']);
191        unset($_POST[$this->getId().'_type']);
192        unset($_POST[$this->getId().'_size']);
193        unset($_POST[$this->getId().'_name']);
194        parent::clear();
195    }
196    /**
197     * Define as extensões de arquivos permitidas.
198     * Devem ser informadas separadas por virgula
199     * Ex: doc,gif,jpg
200     *
201     * @param string $strNewFileTypes
202     */
203    public function setAllowedFileTypes($strNewFileTypes=null)
204    {
205        $this->allowedFileTypes = $strNewFileTypes;
206    }
207    /**
208     * Recupera os tipos de extensões permitidas
209     *
210     */
211    public function getAllowedFileTypes()
212    {
213        return $this->allowedFileTypes;
214    }
215    /**
216     * Retorna a extensão do arquivo anexado
217     * Ex. teste.gif -> retorna: gif
218     */
219    public function getFileExtension() {
220        $filename = strtolower($this->getValue(true)) ;
221        $exts = explode(".", $filename);
222        $n = count($exts)-1;
223        $exts = $exts[$n];
224        return $exts;
225    }
226    //----------------------------------------
227    public function getValue($boolFileName=null)
228    {
229        if($boolFileName===true)
230        {
231            return parent::getValue();
232        }
233        if( isset( $_POST[$this->getId().'_temp'] ) )
234        {
235            $tempFile = $_POST[$this->getId().'_temp'];
236            if( FileHelper::exists($tempFile) ){
237                return file_get_contents($tempFile);
238            }
239        }
240        return null;
241    }
242    /**
243     * Retorna o caminho completo do arquivo na pasta temporária
244     *
245     */
246    public function getFileName()
247    {
248        return $this->getValue(true);
249    }
250    /**
251     * Retorna o caminho completo do arquivo na pasta temporária
252     *
253     */
254    public function getTempFile()
255    {
256        return $this->getFileName();
257    }
258    
259}
260/*
261 print '<form enctype="multipart/form-data" method="POST" action="" name="formdin">';
262 $val = new TFile('arq_anexo',50,true,'doc,pdf','170K');
263 $val->validate();
264 $val->show();
265 //print_r($val->getValue());
266 print '<hr><input type="submit" value="Gravar" name="btnGravar">';
267 print '</form>';
268 print '<hr>';
269 print_r($_POST);
270 print '<hr>';
271 //print_r($_FILES);
272 if($val->getValue(true))
273 {
274 print '<IFRAME id="results" name="Results" src="'.$val->getValue(true).'" frameBorder=1 style="position:absolute;top:15px;left:600px;width:600px;height:600px;background-color:white;"></IFRAME>-->';
275 }
276 */
277?>