OSDN Git Service

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