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 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 113
TConnection
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 5
2450
0.00% covered (danger)
0.00%
0 / 112
 __construct
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 __clone
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 connect
0.00% covered (danger)
0.00%
0 / 1
1806
0.00% covered (danger)
0.00%
0 / 96
 showExemple
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 5
 getRoot
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 9
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 */
41include_once( 'autoload_formdin.php');
42final class TConnection
43{
44    // construtor
45    private function __construct(){}
46    private function __clone(){}
47    //------------------------------------------------------------------------------------------
48    public static function connect($dbType='postgres|mysql|sqlite|oracle|sqlserver',$username=null,$password=null,$database=null,$host=null,$port=null,$schema=null,$boolUtf8=null)
49    {
50        if( preg_match('/\|/',$dbType) || is_null($dbType) )
51        {
52            $dbType='';
53            $dbType='default';
54        }
55        $boolUtf8 = ( $boolUtf8 === false ) ? false : true;
56        $dbType = strtolower($dbType);
57        $configFile = "conn_$dbType.php";
58        $configErrors=array();
59        if( !$database && !$username )
60        {
61            if( !file_exists( $configFile ))
62            {
63                $configFile = "includes/conn_$dbType.php";
64                if( !file_exists( $configFile ))
65                {
66                    $root = self::getRoot();
67                    $configFile = $root.$configFile;
68                }
69            }
70            //die( $configFile);
71            if( ! file_exists( $configFile ) )
72            {
73                self::showExemple(array("Classe TConnection.class.php - Arquivo {$configFile} não encontrado!"));
74                return false;
75            }
76            try
77            {
78                require_once($configFile);
79                if( isset($utf8))
80                {
81                    $boolUtf8 = $utf8;
82                }
83            }
84            catch(Exception $e)
85            {
86                throw $e;
87            }
88            /*$db            = parse_ini_file($configFile);
89            $dbType     = isset($db['dbtype'])         ? $db['dbtype']     : $dbType;
90            $username    = isset($db['username'])     ? $db['username']     : null;
91            $password     = isset($db['password'])     ? $db['password']     : null;
92            $database     = isset($db['database'])     ? $db['database']     : null;
93            $host         = isset($db['host'])         ? $db['host']         : null;
94            $port         = isset($db['port'])         ? $db['port']         : null;
95            $schema        = isset($db['schema'])         ? $db['schema']     : null;
96            $boolUtf8    = isset($db['utf8'])         ? $db['utf8']         : $boolUtf8;
97            */
98
99            $decimal_separator = isset($db['decimal_separator'])         ? $db['decimal_separator']         : null;
100            if( preg_match('/false|0/i',$boolUtf8 ) == 1 || trim( $boolUtf8 ) == '' )
101            {
102                $boolUtf8 = 0;
103            }
104            else
105            {
106                $boolUtf8 = 1;
107            }
108        }
109
110
111        switch( $dbType )
112        {
113            case 'mysql':
114                if( ! $port )
115                {
116                    $port = '3306';
117                }
118                $dsn='mysql:host='.$host.';dbname='.$database.';port='.$port;
119            break;
120            //-----------------------------------------------------------------------
121            case 'postgre':
122            case 'postgres':
123            case 'pgsql':
124                $dbType = 'postgres';
125                if(! $port )
126                {
127                    $port = '5432';
128                }
129                $dsn='pgsql:host='.$host.';dbname='.$database.';port='.$port;
130            break;
131            //-----------------------------------------------------------------------
132            case 'sqllite':
133            case 'sqlite':
134                if( !file_exists( $database ) )
135                {
136                    $configErrors[] = 'Arquivo '.$database.' não encontrado!';
137                }
138                $dsn='sqlite:'.$database;
139            break;
140            //-----------------------------------------------------------------------
141            case 'oracle':
142                if( ! $port )
143                {
144                    $port = '1152';
145                }
146                $dsn="oci:dbname=(DESCRIPTION =(ADDRESS_LIST=(ADDRESS = (PROTOCOL = TCP)(HOST = ".$host.")(PORT = ".$port.")))(CONNECT_DATA =(SERVICE_NAME = ".$database.")))";
147            break;
148            //----------------------------------------------------------
149            case 'mssql':
150            if( ! $port ){
151                $port = '1433';
152            }
153            $dsn='mssql:host='.$host.';dbname='.$database.';port='.$port;
154            break;
155            //----------------------------------------------------------
156            case 'sqlserver':
157                if( ! $port ){
158                    $port = '1433';
159                }
160                /**
161                 * Dica de Reinaldo A. Barrêto Junior para utilizar o sql server no linux
162                 * 
163                 * No PHP 5.4 ou superior o drive mudou de MSSQL para SQLSRV
164                 * */
165                    if (PHP_OS == "Linux") {
166                    $driver = 'dblib';
167                    $dsn = $driver.':host='.$host.';dbname='.$database.';port='.$port;
168                } else {
169                    $driver = 'sqlsrv';
170                    $dsn = $driver.':Server='.$host.';Database='.$database;
171                }
172            break;
173            case 'firebird':
174                $dsn = 'firebird:dbname='.( ( is_null($host) ? '' : $host.':') ).$database;
175            break;
176            //----------------------------------------------------------
177            default:
178                $configErrors[] = 'Variavel $dbType não definida no arquivo de configuração!';
179        }
180
181        if( count( $configErrors ) > 0 )
182        {
183            self::showExemple( $configErrors );
184        }
185        if( !$dsn)
186        {
187            //die('Tipo do banco de dados '.$dbType.' não reconhecido. Ex: postgres, mysql, sqlite, oracle.');
188            throw new Exception('Tipo do banco de dados '.$dbType.' não reconhecido. Ex: postgres, mysql, sqlite, oracle.');
189        }
190        //print 'dns:'.$dsn.'<br>User:'.$username.'<br>Senha:'.$password.'<br>';
191        //die();
192        try
193        {
194            if( $dbType!='oracle')
195            {
196                $conn = new PDO($dsn,$username,$password);
197                $conn->isPDO = true;
198
199//                $conn->dsn         = $dsn;
200//                $conn->utf8     = $boolUtf8;
201//                $conn->dbType    = $dbType;
202//                $conn->schema    = $schema;
203                $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
204                $conn->setAttribute(PDO::ATTR_CASE,PDO::CASE_UPPER );
205
206                if( $dbType == 'postgres' && $schema )
207                {
208                    $stmt = $conn->prepare( 'set search_path='.$schema );
209                    $stmt->execute();
210                    $stmt=null;
211                }
212            }
213            else
214            {
215                $dsn=$database;
216                $charSet = ( ( $boolUtf8===true) ? 'UTF8': null );
217                $connection = @oci_connect($username, $password, $database, $charSet);
218                if( ! $connection )
219                {
220                    $e = oci_error();
221                    throw new Exception('Connection error'.$e['message']);
222                }
223                $conn = (object) array('connection'=>$connection,'isPDO'=>false);
224                /*
225                $stid = oci_parse($conn, 'SELECT * from tb_uf where cod_uf = 59');
226                oci_execute($stid);
227                $nrows = oci_fetch_all($stid, $res);
228                print_r($res);
229                */
230            }
231            if( is_object($conn))
232            {
233                $conn->dsn         = $dsn;
234                $conn->utf8     = $boolUtf8;
235                $conn->dbType    = $dbType;
236                $conn->schema    = $schema;
237            }
238
239        }
240        catch( Exception $e )
241        {
242            // capturar error de sql
243            throw new Exception("<br><b>Connection error using dsn ".$dsn."</b><br>Message:".$e->getMessage().'<br>');
244        }
245        return $conn;
246    }
247    private static function showExemple($arrErros=null)
248    {
249        $msgErro =  implode('<br>',$arrErros);
250        $html='</pre><div style="padding:5px;border:1px solid red;background-color:lightyellow;width:400px;color:blue;overflow:auto;">';
251        $html.='<div style="border-bottom:1px solid blue;color:red;text-align:center;"><blink>'.$msgErro.'</blink></div>';
252        $html.='<center>Exemplo de configuração para conexão com banco ORACLE. Arquivo: conn_oracle.php</center><br>
253                    $dbType = "oracle"<br>
254                    $host = "192.168.1.140";<br>
255                    $port = "1521";<br>
256                    $database = "xe";<br>
257                    $username = "root";<br>
258                    $password = "123456";<br>
259                    $utf8=0;<br><hr>
260                <center>Exemplo de configuração para conexão com banco MYSQL. Arquivo: conn_mysql.php</center><br>
261                    $dbType = "mysql";<br>
262                    $host = "192.168.1.140";<br>
263                    $port = "3306";<br>
264                    $database = "dbteste";<br>
265                    $username = "root";<br>
266                    $password = "";<br>
267                    $utf8=1;<br><br><hr>
268                <center>Exemplo de configuração para conexão com banco POSTGRES. Arquivo: conn_postgres.php</center><br>
269                    $dbType = "postgres";<br>
270                    $host = "192.168.1.140";<br>
271                    $port = "5432";<br>
272                    $database = "dbteste";<br>
273                    $username = "postgres";<br>
274                    $password = "123456";<br>
275                    $utf8=1;<br>
276                    schema   = sisteste<br<br><hr>
277                <center>Exemplo de configuração para conexão com banco SQLITE. Arquivo: conn_sqlite.php</center><br>
278                    dbtype="sqlite"<br>
279                    database = "includes/exemplo.s3db"<hr>
280                <center>Exemplo de configuração para conexão com banco SQLSERVER. Arquivo: conn_sqlserver.php</center><br>
281                    $dbType = "sqlserver";<br>
282                    $host = "192.168.1.140";<br>
283                    $port = "1433";<br>
284                    $database = "dbteste";<br>
285                    $username = "sa";<br>
286                    $password = "123456";<br>
287                    $utf8=0;<br><hr>
288        </div>';
289        die( $html);
290        //throw new Exception( utf8_encode($html) );
291    }
292    /**
293    * Localiza a pasta base da framework
294    *
295    */
296    private static function getRoot()
297    {
298        $base='';
299        for($i=0;$i<10;$i++)
300        {
301            $base = str_repeat('../',$i).'base/';
302            if( file_exists($base) )
303            {
304                $i=10;
305                break;
306            }
307        }
308        $base = str_replace('base/','',$base);
309        $root = ($base == '/') ? './' : $base;
310        return $root;
311    }
312}
313?>