Untyp
[infodrom.org/service.infodrom.org] / class / database.class.php
1 <?php
2
3 class Database {
4   private $db;
5   private $error_log = false;
6   private $error_mail = false;
7   private $lastInsertTable = null;
8
9   public function __construct($driver, $host, $dbname, $user, $passwd)
10   {
11     $this->db = new PDO(sprintf('%s:host=%s;dbname=%s', $driver, $host, $dbname), $user, $passwd);
12
13     #    $this->db->query("SET NAMES 'utf8'"); 
14     #    $this->db->query("SET CHARACTER SET 'utf8'");
15     #    $this->db->query("SET collation_connection = 'utf8_general_ci'");
16     #    $this->db->query("SET lc_time_names = 'de_DE'");
17   }
18
19   public function enableErrorLog()
20   {
21     $this->error_log = true;
22   }
23
24   public function disableErrorLog()
25   {
26     $this->error_log = false;
27   }
28
29   public function setErrorMail($address)
30   {
31     $this->error_mail = $address;
32   }
33
34   private function logQuery($sql)
35   {
36     if ($this->error_log) error_log(trim(str_replace("\n", ' ', $sql)));
37   }
38
39   private function handleError($sth, $sql)
40   {
41     if (!$this->error_log) error_log(trim(str_replace("\n", ' ', $sql)));
42     $arr = $this->db->errorInfo();
43     foreach (explode("\n", $arr[2]) as $line)
44       error_log($line);
45
46     if ($this->error_mail && defined('MAIL_FROM') && defined('MAIL_FROM_NAME')) {
47       $mail = new Mail();
48       $mail->env_from(MAIL_FROM);
49       $mail->set('From', mb_encode_mimeheader(utf8_decode(sprintf("%s <%s>", MAIL_FROM_NAME, MAIL_FROM)),'latin1'));
50       $mail->set('To', $this->error_mail);
51       $mail->set('Subject', 'SQL Error in ' . $_SERVER['REQUEST_URI']);
52
53       $body = sprintf("http://%s%s%s\nReferer: %s\nUser: %s\n\n%s\n\nError Number %d\n%s\n\n",
54                       $_SERVER['SERVER_NAME'],
55                       $_SERVER['SERVER_PORT'] != 80 ? ':'.$_SERVER['SERVER_PORT'] : '',
56                       $_SERVER['REQUEST_URI'],
57                       $_SERVER['HTTP_REFERER'],
58                       $_SESSION['sys']['login'],
59                       trim($sql),
60                       $arr[1],
61                       $arr[2]);
62
63       ob_start();
64       debug_print_backtrace();
65       $body .= ob_get_contents()."\n";
66       ob_end_clean();
67
68       if (count($_POST)) $body .= 'POST: ' . var_export($_POST,true)."\n";
69       if (count($_GET)) $body .= 'GET: ' . var_export($_GET,true)."\n";
70       if (count($_SESSION)) $body .= 'SESSION: ' . var_export($_SESSION,true)."\n";
71
72       $mail->send($body);
73     }
74     return $sth;
75   }
76
77   public function errorInfo()
78   {
79     return $this->db->errorInfo();
80   }
81
82   public function quote($string)
83   {
84     if (is_null($string)) return 'NULL';
85     if (strtolower($string) == 'now()' || strtolower($string) == 'current_timestamp') return 'now()';
86     return $this->db->quote($string);
87   }
88
89   public function lastInsertId()
90   {
91     if (DBDRIVER == 'pgsql')
92       return $this->db->lastInsertId($this->lastInsertTable.'_id_seq');
93     else
94       return $this->db->lastInsertId();
95   }
96
97   private function query($sql)
98   {
99     $this->logQuery($sql);
100     $sth = $this->db->query($sql);
101
102     if ($sth === false) return $this->handleError($sth,$sql);
103
104     if (preg_match('/INSERT\s+INTO\s+(\S+)\s+/i', $sql, $matches))
105       $this->lastInsertTable = $matches[1];
106
107     return $sth;
108   }
109
110   public function execute($sql)
111   {
112     return $this->query($sql) !== false;
113   }
114
115   public function fetchValue($sql)
116   {
117     $sth = $this->query($sql);
118     if ($sth === false) return false;
119     $ret = $sth->fetch(PDO::FETCH_BOTH);
120     if ($ret === false) return false;
121     return $ret[0];
122   }
123
124   public function fetchAssoc($sql)
125   {
126     $sth = $this->query($sql);
127     if ($sth === false) return false;
128     return $sth->fetch(PDO::FETCH_ASSOC);
129   }
130
131   public function fetchObject($sql)
132   {
133     $sth = $this->query($sql);
134     if ($sth === false) return false;
135     return $sth->fetchObject();
136   }
137
138   public function fetchAssocList($sql)
139   {
140     $result = array();
141     $sth = $this->query($sql);
142     if ($sth === false) return $result;
143     while ($row = $sth->fetch(PDO::FETCH_ASSOC))
144       $result[] = $row;
145     return $result;
146   }
147
148   public function fetchObjectList($sql)
149   {
150     $result = array();
151     $sth = $this->query($sql);
152     if ($sth === false) return $result;
153     while ($row = $sth->fetchObject())
154       $result[] = $row;
155     return $result;
156   }
157
158   private function executeBind($sql, $data)
159   {
160     $sth = $this->db->prepare($sql);
161     if ($sth === false) return $this->handleError($sth,$sql);
162
163     foreach ($data as $k => $v)
164       $sth->bindValue(':'.$k, $v); // , PDO::PARAM_STR);
165
166     $ok = $this->db->execute();
167     if ($ok === false) return $this->handleError($sth,$sql);
168
169     if (preg_match('/INSERT\s+INTO\s+(\S+)\s+/i', $sql, $matches))
170       $this->lastInsertTable = $matches[1];
171
172     return $sth;
173   }
174
175   public function insertInto($table, $data)
176   {
177     if (!is_array($data)) throw Exception('insertInto called without data array');
178
179     $columns = array();
180     foreach ($data as $k => $v) {
181       $columns[] = $k;
182       $values[] = ':' . $k;
183     }
184
185     $sql = sprintf("INSERT INTO %s (%s)\n    VALUES (%s)",
186                    $table,
187                    implode(',', $columns),
188                    implode(',', $values));
189     return $this->executeBind($sql, $data);
190
191     /*
192    $db = new PDO('sqlsrv:server=SQLSERVERNAME;Database=own_exchange', 'user', 'password');
193    $sql = "INSERT INTO dbo.files(file_name, file_source) VALUES(:file_name, :file_source)";
194    $stmt = $db->prepare($sql);
195    $stmt->bindParam(":file_name", $files->name, PDO::PARAM_STR);
196    $stmt->bindParam(":file_source", file_get_contents($files->tempName), PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
197    $stmt->execute();
198
199
200    $stmt = $dbh->prepare("INSERT INTO tExample (id,value) VALUES (:id,:value)");
201    $taValues = array(
202     'id' => '1',
203     'value' => '2'
204    ); // array
205    PDOBindArray($stmt,$taValues);
206    $stmt->execute();
207
208
209
210      */
211   }
212
213 }
214
215 ?>