OSDN Git Service

18b989847ab779b9af9bfe7b2ba393fa22924219
[nucleus-jp/nucleus-next.git] / nucleus / libs / sql / DB.php
1 <?php
2
3 /*
4  * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
5  * Copyright (C) 2012 The Nucleus Group
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * (see nucleus/documentation/index.html#license for more info)
12  */
13 /**
14  * @license http://nucleuscms.org/license.txt GNU General Public License
15  * @copyright Copyright (C) 2012 The Nucleus Group
16  * @version $Id$
17  */
18
19 class DB
20 {
21         private static $dbh;
22         private static $execCount = 0;
23         private static $dateFormat = '\'%Y-%m-%d %H:%M:%S\'';
24         
25         /**
26          * DB::setConnectionInfo()
27          * Set the information to connect to the database, it will attempt to connect.
28          * @param string $engine Engine
29          * @param string $host Host
30          * @param string $user User
31          * @param string $password Password
32          * @param string $database Database
33          * @return bool Returns TRUE if able to connect, otherwise it returns FALSE.
34          */
35         public static function setConnectionInfo($engine, $host, $user, $password, $database)
36         {
37                 self::disConnect();
38
39                 try
40                 {
41                         if ( i18n::strpos($host, ':') === false )
42                         {
43                                 $portnum = '';
44                         }
45                         else
46                         {
47                                 list($host, $portnum) = i18n::explode(":", $host);
48                                 if ( isset($portnum) )
49                                 {
50                                         $portnum = trim($portnum);
51                                 }
52                                 else
53                                 {
54                                         $portnum = '';
55                                 }
56                         }
57
58                         switch ( $engine )
59                         {
60                                 case 'sybase':
61                                 case 'dblib':
62                                         $port = is_numeric($portnum) ? ':' . intval($portnum) : '';
63                                         $db = $database ? ';dbname=' . $database : '';
64                                         self::$dbh = new PDO($engine . ':host=' . $host . $port . $db, $user, $password);
65                                         break;
66                                 case 'mssql':
67                                         $port = is_numeric($portnum) ? ',' . intval($portnum) : '';
68                                         $db = $database ? ';dbname=' . $database : '';
69                                         self::$dbh = new PDO($engine . ':host=' . $host . $port . $db, $user, $password);
70                                         break;
71                                 case 'oci':
72                                         $port = is_numeric($portnum) ? ':' . intval($portnum) : '';
73                                         self::$dbh = new PDO($engine . ':dbname=//' . $host . $port . '/' . $database, $user, $password);
74                                         break;
75                                 case 'odbc':
76                                         $port = is_numeric($portnum) ? ';PORT=' . intval($portnum) : '';
77                                         self::$dbh = new PDO(
78                                                 $engine . ':DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=' . $host . $port . ';DATABASE=' . $database . ';PROTOCOL=TCPIP;UID='
79                                                         . $user . ';PWD=' . $password);
80                                         break;
81                                 case 'pgsql':
82                                         $port = is_numeric($portnum) ? ';port=' . intval($portnum) : '';
83                                         $db = $database ? ';dbname=' . $database : '';
84                                         self::$dbh = new PDO($engine . ':host=' . $host . $port . $db, $user, $password);
85                                         break;
86                                 case 'sqlite':
87                                 case 'sqlite2':
88                                         $port = is_numeric($portnum) ? ':' . intval($portnum) : '';
89                                         self::$dbh = new PDO($engine . ':' . $database, $user, $password);
90                                         if ( self::$dbh )
91                                         {
92                                                 self::$dbh->sqliteCreateFunction('SUBSTRING', 'substr', 3);
93                                                 self::$dbh->sqliteCreateFunction('UNIX_TIMESTAMP', 'strtotime', 1);
94                                         }
95                                         break;
96                                 case 'mysql':
97                                         $port = is_numeric($portnum) ? ';port=' . intval($portnum) : '';
98                                         $db = $database ? ';dbname=' . $database : '';
99                                         self::$dbh = new PDO(
100                                                 'mysql' . ':host=' . $host . $port . $db,
101                                                 $user,
102                                                 $password,
103                                                 array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8\''));
104                                         break;
105                                 default: // mysql
106                                         if ( !class_exists('MysqlPDO') )
107                                         {
108                                                 include_once realpath(dirname(__FILE__)) . '/MYSQLPDO.php';
109                                         }
110                                         $port = is_numeric($portnum) ? ';port=' . intval($portnum) : '';
111                                         $db = $database ? ';dbname=' . $database : '';
112                                         self::$dbh = new MysqlPDO(
113                                                 'mysql' . ':host=' . $host . $port . $db,
114                                                 $user,
115                                                 $password,
116                                                 array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8\''));
117                                         break;
118                         }
119                 }
120                 catch (PDOException $e)
121                 {
122                         self::disConnect();
123                         return FALSE;
124                 }
125                 return TRUE;
126         }
127
128         /**
129          * DB::disConnect()
130          * Disconnect the connection to the database.
131          */
132         public static function disConnect()
133         {
134                 self::$dbh = null;
135         }
136
137         /**
138          * DB::getExecCount()
139          * To get the number of times you run the statement.
140          * @return int Number of executions
141          */
142         public static function getExecCount()
143         {
144                 return self::$execCount;
145         }
146
147         /**
148          * DB::formatDateTime()
149          * The value converted to a format that can be passed to the database datetime.
150          * @param int $timestamp UNIX timestamp
151          * @param int $offset timestamp offset
152          * @return string formatted datetime (quart treated)
153          */
154         public static function formatDateTime($timestamp = null, $offset=0)
155         {
156                 if ( $timestamp == null )
157                 {
158                         $timestamp = time();
159                 }
160                 $timestamp += $offset;
161                 return preg_replace_callback('/(%[a-z%])/i',
162                         create_function('$matches', 'return strftime($matches[1], ' . intval($timestamp) . ');'),
163                         self::$dateFormat
164                 );
165         }
166         
167         /**
168          * DB::getValue()
169          * Gets the value of the first column of the first row of the results obtained in the statement.
170          * @param string $statement SQL Statement
171          * @return mixed Result value. If the call fails, it will return FALSE.
172          */
173         public static function getValue($statement)
174         {
175                 if ( self::$dbh == null ) return FALSE;
176                 self::$execCount++;
177                 $result = self::callQuery($statement);
178                 if ( $row = $result->fetch(PDO::FETCH_NUM) )
179                 {
180                         return $row[0];
181                 }
182                 return FALSE;
183         }
184
185         /**
186          * DB::getRow()
187          * Gets the first row of the results obtained in the statement.
188          * @param string $statement SQL Statement
189          * @return array Result row. If the call fails, it will return FALSE.
190          */
191         public static function getRow($statement)
192         {
193                 if ( self::$dbh == null ) return FALSE;
194                 self::$execCount++;
195                 $result = self::callQuery($statement);
196                 return $result->fetch(PDO::FETCH_BOTH);
197         }
198
199         /**
200          * DB::getResult()
201          * Gets the set of results obtained in the statement.
202          * @param string $statement SQL Statement
203          * @return PDOStatement Result set object. If the call fails, it will return FALSE.
204          */
205         public static function getResult($statement)
206         {
207                 if ( self::$dbh == null ) return FALSE;
208                 self::$execCount++;
209                 return self::callQuery($statement);
210         }
211
212         /**
213          * DB::execute()
214          * Execute an SQL statement and return the number of affected rows.
215          * @param string $statement SQL Statement
216          * @return int number of rows that were modified or deleted by the SQL statement you issued. If the call fails, it will return FALSE.
217          */
218         public static function execute($statement)
219         {
220                 if ( self::$dbh == null ) return FALSE;
221                 self::$execCount++;
222                 return self::callExec($statement);
223         }
224
225         /**
226          * DB::callQuery()
227          * Run the query to retrieve the result set.
228          * @param string $statement query to be executed
229          * @return PDOStatement Result set object. If the call fails, it will return FALSE.
230          */
231         private static function callQuery($statement)
232         {
233                 $result = self::$dbh->query($statement);
234                 if ( $result === FALSE )
235                 {
236                         self::showErrorDisplay($statement);
237                 }
238                 return $result;
239         }
240         
241         /**
242          * DB::callExec()
243          * Run the query and returns the number of rows affected.
244          * @param string $statement query to be executed
245          * @return int number of rows that were modified or deleted by the SQL statement you issued. If the call fails, it will return FALSE.
246          */
247         private static function callExec($statement)
248         {
249                 $result = self::$dbh->exec($statement);
250                 if ( $result === FALSE )
251                 {
252                         self::showErrorDisplay($statement);
253                 }
254                 return $result;
255         }
256         
257         /**
258          * DB::showErrorDisplay()
259          * The error message is output to the screen of the query.
260          * @param string $statement query output to the screen
261          */
262         private static function showErrorDisplay($statement)
263         {
264                 global $CONF;
265                 if ( array_key_exists('debug', $CONF) && $CONF['debug'] )
266                 {
267                         $err = self::getError();
268                         print("mySQL error with query '{$statement}' : " . $err[2]);
269                 }
270                 return;
271         }
272         
273         /**
274          * DB::getError()
275          * Gets the error information associated with the last operation.
276          * @return array Error info
277          */
278         public static function getError()
279         {
280                 if ( self::$dbh == null ) return FALSE;
281                 return self::$dbh->errorInfo();
282         }
283
284         /**
285          * DB::quoteValue()
286          * Quotes a string for use in a query.
287          * @param string $value Value to quote
288          * @return string Quoted value
289          */
290         public static function quoteValue($value)
291         {
292                 if ( self::$dbh == null ) return FALSE;
293                 return self::$dbh->quote($value);
294         }
295
296         /**
297          * DB::getInsertId()
298          * Get the value of the ID of the rows that are inserted at the end.
299          * @return string ID of the row
300          */
301         public static function getInsertId()
302         {
303                 if ( self::$dbh == null ) return FALSE;
304                 return self::$dbh->lastInsertId();
305         }
306
307         /**
308          * DB::getAttribute()
309          * Gets the attribute of the database.
310          * @return string Attribute
311          */
312         public static function getAttribute($attribute)
313         {
314                 if ( self::$dbh == null ) return FALSE;
315                 return self::$dbh->getAttribute($attribute);
316         }
317         
318 }