Till Brehm
2014-08-13 94b44c61a92adcc52feed671f24a09f1f564cc3a
commit | author | age
b5a2f8 1 <?php
T 2 /*
f5b0ca 3    Copyright (c) 2005, Till Brehm, projektfarm Gmbh
N 4    All rights reserved.
b5a2f8 5
f5b0ca 6    Redistribution and use in source and binary forms, with or without modification,
N 7    are permitted provided that the following conditions are met:
b5a2f8 8
f5b0ca 9  * Redistributions of source code must retain the above copyright notice,
N 10  this list of conditions and the following disclaimer.
11  * Redistributions in binary form must reproduce the above copyright notice,
12  this list of conditions and the following disclaimer in the documentation
13  and/or other materials provided with the distribution.
14  * Neither the name of ISPConfig nor the names of its contributors
15  may be used to endorse or promote products derived from this software without
16  specific prior written permission.
b5a2f8 17
f5b0ca 18  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
N 19  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
25  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
27  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
b5a2f8 29
f5b0ca 30 class db extends mysqli
N 31 {
7fe908 32     private $dbHost = '';  // hostname of the MySQL server
MC 33     private $dbName = '';  // logical database name on that server
34     private $dbUser = '';  // database authorized user
35     private $dbPass = '';  // user's password
36     private $dbCharset = 'utf8';// Database charset
37     private $dbNewLink = false; // Return a new linkID when connect is called again
38     private $dbClientFlags = 0; // MySQL Client falgs
39     private $linkId = 0;  // last result of mysqli_connect()
40     private $queryId = 0;  // last result of mysqli_query()
41     private $record = array(); // last record fetched
42     private $autoCommit = 1;    // Autocommit Transactions
43     private $currentRow;  // current row number
44     private $errorNumber = 0; // last error number
45     public $errorMessage = ''; // last error message
46     private $errorLocation = '';// last error location
47     public $show_error_messages = false; // false in server, true in interface
48     private $isConnected = false; // needed to know if we have a valid mysqli object from the constructor
b5a2f8 49
7fe908 50     // constructor
MC 51     public function __construct($prefix = '') {
52         global $conf;
53         if($prefix != '') $prefix .= '_';
54         $this->dbHost = $conf[$prefix.'db_host'];
55         $this->dbName = $conf[$prefix.'db_database'];
56         $this->dbUser = $conf[$prefix.'db_user'];
57         $this->dbPass = $conf[$prefix.'db_password'];
58         $this->dbCharset = $conf[$prefix.'db_charset'];
59         $this->dbNewLink = $conf[$prefix.'db_new_link'];
60         $this->dbClientFlags = $conf[$prefix.'db_client_flags'];
61         parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'], $conf[$prefix.'db_password'], $conf[$prefix.'db_database']);
62         $try = 0;
63         //while(!is_null($this->connect_error) && $try < 5) {
64         while(mysqli_connect_error() && $try < 5) {
65             if($try > 0) sleep(1);
f5b0ca 66
7fe908 67             $try++;
MC 68             $this->updateError('DB::__construct');
f5b0ca 69
7fe908 70             parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'], $conf[$prefix.'db_password'], $conf[$prefix.'db_database']);
MC 71         }
f5b0ca 72
7fe908 73         //if(is_null($this->connect_error)) $this->isConnected = true;
MC 74         //else return false;
75         if(!mysqli_connect_error()) $this->isConnected = true;
76         else return false;
77
78         $this->setCharacterEncoding();
79     }
80
81     public function __destruct() {
82         $this->close(); // helps avoid memory leaks, and persitent connections that don't go away.
83     }
84
85     // error handler
86     public function updateError($location) {
87         global $app, $conf;
88
89         /*
72695f 90     if(!is_null($this->connect_error)) {
f5b0ca 91       $this->errorNumber = $this->connect_errno;
N 92       $this->errorMessage = $this->connect_error;
93     } else {
94       $this->errorNumber = $this->errno;
95       $this->errorMessage = $this->error;
e6c1c4 96     }
cc6568 97     */
7fe908 98         if(mysqli_connect_error()) {
MC 99             $this->errorNumber = mysqli_connect_errno();
100             $this->errorMessage = mysqli_connect_error();
101         } else {
102             $this->errorNumber = mysqli_errno($this);
103             $this->errorMessage = mysqli_error($this);
104         }
cc6568 105
f5b0ca 106
7fe908 107         $this->errorLocation = $location;
MC 108         if($this->errorNumber) {
109             $error_msg = $this->errorLocation .' '. $this->errorMessage;
110             // This right here will allow us to use the same file for server & interface
111             if($this->show_error_messages && $conf['demo_mode'] === false) {
112                 echo $error_msg;
113             } else if(is_object($app) && method_exists($app, 'log')) {
114                     $app->log($error_msg, LOGLEVEL_WARN);
115                 }
116         }
f5b0ca 117     }
7fe908 118
MC 119     private function setCharacterEncoding() {
120         if($this->isConnected == false) return false;
121         parent::query( 'SET NAMES '.$this->dbCharset);
122         parent::query( "SET character_set_results = '".$this->dbCharset."', character_set_client = '".$this->dbCharset."', character_set_connection = '".$this->dbCharset."', character_set_database = '".$this->dbCharset."', character_set_server = '".$this->dbCharset."'");
f5b0ca 123     }
N 124
7fe908 125     public function query($queryString) {
MC 126         global $conf;
127         if($this->isConnected == false) return false;
128         $try = 0;
129         do {
130             $try++;
131             $ok = $this->ping();
132             if(!$ok) {
133                 if(!$this->real_connect($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName)) {
134                     if($try > 4) {
135                         $this->updateError('DB::query -> reconnect');
136                         return false;
137                     } else {
138                         sleep(1);
139                     }
140                 } else {
141                     $this->setCharacterEncoding();
142                     $ok = true;
143                 }
144             }
145         } while($ok == false);
146         $this->queryId = parent::query($queryString);
147         $this->updateError('DB::query('.$queryString.') -> mysqli_query');
148         if($this->errorNumber && $conf['demo_mode'] === false) debug_print_backtrace();
149         if(!$this->queryId) {
150             return false;
151         }
152         $this->currentRow = 0;
153         return $this->queryId;
154     }
f5b0ca 155
7fe908 156     // returns all records in an array
MC 157     public function queryAllRecords($queryString) {
158         if(!$this->query($queryString))
159         {
160             return false;
161         }
162         $ret = array();
163         while($line = $this->nextRecord())
164         {
165             $ret[] = $line;
166         }
167         return $ret;
168     }
f5b0ca 169
7fe908 170     // returns one record in an array
MC 171     public function queryOneRecord($queryString) {
172         if(!$this->query($queryString) || $this->numRows() == 0)
173         {
174             return false;
175         }
176         return $this->nextRecord();
177     }
f5b0ca 178
7fe908 179     // returns the next record in an array
MC 180     public function nextRecord() {
181         $this->record = $this->queryId->fetch_assoc();
182         $this->updateError('DB::nextRecord()-> mysql_fetch_array');
183         if(!$this->record || !is_array($this->record))
184         {
185             return false;
186         }
187         $this->currentRow++;
188         return $this->record;
189     }
190
191     // returns number of rows returned by the last select query
192     public function numRows() {
193         return intval($this->queryId->num_rows);
194     }
195
196     public function affectedRows() {
197         return intval($this->queryId->affected_rows);
198     }
199
200     // returns mySQL insert id
201     public function insertID() {
202         return $this->insert_id;
203     }
204
205
206     //* Function to quote strings
207     public function quote($formfield) {
208         return $this->escape_string($formfield);
209     }
210
211     //* Function to unquotae strings
212     public function unquote($formfield) {
213         return stripslashes($formfield);
214     }
215
216     public function toLower($record) {
217         if(is_array($record)) {
218             foreach($record as $key => $val) {
219                 $key = strtolower($key);
220                 $out[$key] = $val;
221             }
222         }
223         return $out;
224     }
225
226     public function diffrec($record_old, $record_new) {
227         $diffrec_full = array();
228         $diff_num = 0;
229
230         if(is_array($record_old) && count($record_old) > 0) {
231             foreach($record_old as $key => $val) {
232                 // if(!isset($record_new[$key]) || $record_new[$key] != $val) {
233                 if(@$record_new[$key] != $val) {
234                     // Record has changed
235                     $diffrec_full['old'][$key] = $val;
236                     $diffrec_full['new'][$key] = @$record_new[$key];
237                     $diff_num++;
238                 } else {
239                     $diffrec_full['old'][$key] = $val;
240                     $diffrec_full['new'][$key] = $val;
241                 }
242             }
243         } elseif(is_array($record_new)) {
244             foreach($record_new as $key => $val) {
245                 if(isset($record_new[$key]) && @$record_old[$key] != $val) {
246                     // Record has changed
247                     $diffrec_full['new'][$key] = $val;
248                     $diffrec_full['old'][$key] = @$record_old[$key];
249                     $diff_num++;
250                 } else {
251                     $diffrec_full['new'][$key] = $val;
252                     $diffrec_full['old'][$key] = $val;
253                 }
254             }
255         }
256
257         return array('diff_num' => $diff_num, 'diff_rec' => $diffrec_full);
258
259     }
260
261     //** Function to fill the datalog with a full differential record.
262     public function datalogSave($db_table, $action, $primary_field, $primary_id, $record_old, $record_new, $force_update = false) {
263         global $app, $conf;
264
94b44c 265         // Check fields
TB 266         if(!preg_match('/^[a-zA-Z0-9\.\-]{1,64}$/',$db_table)) $app->error('Invalid table name '.$db_table);
267         if(!preg_match('/^[a-zA-Z0-9\-]{1,64}$/',$primary_field)) $app->error('Invalid primary field '.$primary_field.' in table '.$db_table);
268         
269         if(strpos($db_table, '.') !== false) {
270             $db_table = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $db_table);
7fe908 271         } else {
94b44c 272             $db_table = '`' . $db_table . '`';
7fe908 273         }
94b44c 274         
TB 275         $primary_field = $this->quote($primary_field);
276         $primary_id = intval($primary_id);
f5b0ca 277
b0eb45 278         if($force_update == true) {
T 279             //* We force a update even if no record has changed
7fe908 280             $diffrec_full = array('new' => $record_new, 'old' => $record_old);
b0eb45 281             $diff_num = count($record_new);
T 282         } else {
283             //* get the difference record between old and new record
284             $tmp = $this->diffrec($record_old, $record_new);
285             $diffrec_full = $tmp['diff_rec'];
286             $diff_num = $tmp['diff_num'];
287             unset($tmp);
288         }
f5b0ca 289
7fe908 290         // Insert the server_id, if the record has a server_id
MC 291         $server_id = (isset($record_old['server_id']) && $record_old['server_id'] > 0)?$record_old['server_id']:0;
292         if(isset($record_new['server_id'])) $server_id = $record_new['server_id'];
e9a57d 293         $server_id = intval($server_id);
f5b0ca 294
7fe908 295         if($diff_num > 0) {
MC 296             //print_r($diff_num);
297             //print_r($diffrec_full);
298             $diffstr = $app->db->quote(serialize($diffrec_full));
299             $username = $app->db->quote($_SESSION['s']['user']['username']);
300             $dbidx = $primary_field.':'.$primary_id;
f5b0ca 301
7fe908 302             if($action == 'INSERT') $action = 'i';
MC 303             if($action == 'UPDATE') $action = 'u';
304             if($action == 'DELETE') $action = 'd';
305             $sql = "INSERT INTO sys_datalog (dbtable,dbidx,server_id,action,tstamp,user,data) VALUES ('".$db_table."','$dbidx','$server_id','$action','".time()."','$username','$diffstr')";
306             $app->db->query($sql);
307         }
f5b0ca 308
7fe908 309         return true;
MC 310     }
f5b0ca 311
7fe908 312     //** Inserts a record and saves the changes into the datalog
MC 313     public function datalogInsert($tablename, $insert_data, $index_field) {
314         global $app;
e9a57d 315         
94b44c 316         // Check fields
TB 317         if(!preg_match('/^[a-zA-Z0-9\.\-]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename);
318         if(!preg_match('/^[a-zA-Z0-9\-]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename);
319         
320         if(strpos($tablename, '.') !== false) {
321             $tablename = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename);
322         } else {
323             $tablename = '`' . $tablename . '`';
324         }
325         
e9a57d 326         $index_field = $this->quote($index_field);
7fe908 327
MC 328         if(is_array($insert_data)) {
ee260d 329             $key_str = '';
T 330             $val_str = '';
331             foreach($insert_data as $key => $val) {
332                 $key_str .= "`".$key ."`,";
333                 $val_str .= "'".$this->quote($val)."',";
334             }
7fe908 335             $key_str = substr($key_str, 0, -1);
MC 336             $val_str = substr($val_str, 0, -1);
ee260d 337             $insert_data_str = '('.$key_str.') VALUES ('.$val_str.')';
T 338         } else {
339             $insert_data_str = $insert_data;
340         }
f5b0ca 341
7fe908 342         $old_rec = array();
MC 343         $this->query("INSERT INTO $tablename $insert_data_str");
344         $index_value = $this->insertID();
345         $new_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'");
346         $this->datalogSave($tablename, 'INSERT', $index_field, $index_value, $old_rec, $new_rec);
f5b0ca 347
7fe908 348         return $index_value;
MC 349     }
f5b0ca 350
7fe908 351     //** Updates a record and saves the changes into the datalog
MC 352     public function datalogUpdate($tablename, $update_data, $index_field, $index_value, $force_update = false) {
ee260d 353         global $app;
e9a57d 354         
94b44c 355         // Check fields
TB 356         if(!preg_match('/^[a-zA-Z0-9\.\-]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename);
357         if(!preg_match('/^[a-zA-Z0-9\-]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename);
358         
359         if(strpos($tablename, '.') !== false) {
360             $tablename = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename);
361         } else {
362             $tablename = '`' . $tablename . '`';
363         }
364         
e9a57d 365         $index_field = $this->quote($index_field);
TB 366         $index_value = $this->quote($index_value);
7fe908 367
MC 368         $old_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'");
369
370         if(is_array($update_data)) {
ee260d 371             $update_data_str = '';
T 372             foreach($update_data as $key => $val) {
373                 $update_data_str .= "`".$key ."` = '".$this->quote($val)."',";
374             }
7fe908 375             $update_data_str = substr($update_data_str, 0, -1);
ee260d 376         } else {
T 377             $update_data_str = $update_data;
378         }
f5b0ca 379
7fe908 380         $this->query("UPDATE $tablename SET $update_data_str WHERE $index_field = '$index_value'");
MC 381         $new_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'");
382         $this->datalogSave($tablename, 'UPDATE', $index_field, $index_value, $old_rec, $new_rec, $force_update);
f5b0ca 383
7fe908 384         return true;
MC 385     }
f5b0ca 386
7fe908 387     //** Deletes a record and saves the changes into the datalog
MC 388     public function datalogDelete($tablename, $index_field, $index_value) {
389         global $app;
e9a57d 390         
94b44c 391         // Check fields
TB 392         if(!preg_match('/^[a-zA-Z0-9\.\-]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename);
393         if(!preg_match('/^[a-zA-Z0-9\-]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename);
394         
395         if(strpos($tablename, '.') !== false) {
396             $tablename = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename);
397         } else {
398             $tablename = '`' . $tablename . '`';
399         }
400         
e9a57d 401         $index_field = $this->quote($index_field);
TB 402         $index_value = $this->quote($index_value);
f5b0ca 403
7fe908 404         $old_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'");
MC 405         $this->query("DELETE FROM $tablename WHERE $index_field = '$index_value'");
406         $new_rec = array();
407         $this->datalogSave($tablename, 'DELETE', $index_field, $index_value, $old_rec, $new_rec);
408
409         return true;
410     }
411
412     //* get the current datalog status for the specified login (or currently logged in user)
413     public function datalogStatus($login = '') {
414         global $app;
415
416         $return = array('count' => 0, 'entries' => array());
417         if($_SESSION['s']['user']['typ'] == 'admin') return $return; // these information should not be displayed to admin users
418
419         if($login == '' && isset($_SESSION['s']['user'])) {
420             $login = $_SESSION['s']['user']['username'];
421         }
422
423         $result = $this->queryAllRecords("SELECT COUNT( * ) AS cnt, sys_datalog.action, sys_datalog.dbtable FROM sys_datalog, server WHERE server.server_id = sys_datalog.server_id AND sys_datalog.user = '" . $this->quote($login) . "' AND sys_datalog.datalog_id > server.updated GROUP BY sys_datalog.dbtable, sys_datalog.action");
424         foreach($result as $row) {
425             if(!$row['dbtable'] || in_array($row['dbtable'], array('aps_instances', 'aps_instances_settings', 'mail_access', 'mail_content_filter'))) continue; // ignore some entries, maybe more to come
426             $return['entries'][] = array('table' => $row['dbtable'], 'action' => $row['action'], 'count' => $row['cnt'], 'text' => $app->lng('datalog_status_' . $row['action'] . '_' . $row['dbtable']));
427             $return['count'] += $row['cnt'];
428         }
429         unset($result);
430
431         return $return;
432     }
f5b0ca 433
N 434
7fe908 435     public function freeResult($query)
MC 436     {
437         if(is_object($query) && (get_class($query) == "mysqli_result")) {
438             $query->free();
439             return true;
440         } else {
441             return false;
442         }
443     }
12fcb2 444
7fe908 445     /* TODO: Does anything use this? */
MC 446     public function delete() {
b5a2f8 447
7fe908 448     }
f5b0ca 449
7fe908 450     /* TODO: Does anything use this? */
MC 451     public function Transaction($action) {
452         //action = begin, commit oder rollback
f5b0ca 453
7fe908 454     }
f5b0ca 455
7fe908 456     /*
f5b0ca 457        $columns = array(action =>   add | alter | drop
N 458        name =>     Spaltenname
459        name_new => neuer Spaltenname, nur bei 'alter' belegt
460        type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
461        typeValue => Wert z.B. bei Varchar
462        defaultValue =>  Default Wert
463        notNull =>   true | false
464        autoInc =>   true | false
465        option =>   unique | primary | index)
466
467
468      */
469
7fe908 470     public function createTable($table_name, $columns) {
MC 471         $index = '';
472         $sql = "CREATE TABLE $table_name (";
473         foreach($columns as $col){
474             $sql .= $col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
f5b0ca 475
7fe908 476             if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' ";
MC 477             if($col['notNull'] == true) {
478                 $sql .= 'NOT NULL ';
479             } else {
480                 $sql .= 'NULL ';
481             }
482             if($col['autoInc'] == true) $sql .= 'auto_increment ';
483             $sql.= ',';
484             // key Definitionen
485             if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),';
486             if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),';
487             if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),';
488         }
489         $sql .= $index;
490         $sql = substr($sql, 0, -1);
491         $sql .= ')';
492         $this->query($sql);
493         return true;
f5b0ca 494     }
N 495
7fe908 496     /*
f5b0ca 497        $columns = array(action =>   add | alter | drop
N 498        name =>     Spaltenname
499        name_new => neuer Spaltenname, nur bei 'alter' belegt
500        type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
501        typeValue => Wert z.B. bei Varchar
502        defaultValue =>  Default Wert
503        notNull =>   true | false
504        autoInc =>   true | false
505        option =>   unique | primary | index)
506
507
508      */
7fe908 509     public function alterTable($table_name, $columns) {
MC 510         $index = '';
511         $sql = "ALTER TABLE $table_name ";
512         foreach($columns as $col){
513             if($col['action'] == 'add') {
514                 $sql .= 'ADD '.$col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
515             } elseif ($col['action'] == 'alter') {
516                 $sql .= 'CHANGE '.$col['name'].' '.$col['name_new'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
517             } elseif ($col['action'] == 'drop') {
518                 $sql .= 'DROP '.$col['name'].' ';
519             }
520             if($col['action'] != 'drop') {
521                 if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' ";
522                 if($col['notNull'] == true) {
523                     $sql .= 'NOT NULL ';
524                 } else {
525                     $sql .= 'NULL ';
526                 }
527                 if($col['autoInc'] == true) $sql .= 'auto_increment ';
528                 $sql.= ',';
529                 // Index definitions
530                 if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),';
531                 if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),';
532                 if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),';
533             }
534         }
535         $sql .= $index;
536         $sql = substr($sql, 0, -1);
537
538         //die($sql);
539         $this->query($sql);
540         return true;
f5b0ca 541     }
7fe908 542
MC 543     public function dropTable($table_name) {
544         $this->check($table_name);
545         $sql = "DROP TABLE '". $table_name."'";
546         return $this->query($sql);
f5b0ca 547     }
N 548
7fe908 549     // gibt Array mit Tabellennamen zur�ck
MC 550     public function getTables($database_name = '') {
551         if($this->isConnected == false) return false;
552         if($database_name == '') $database_name = $this->dbName;
553         $result = parent::query("SHOW TABLES FROM $database_name");
554         for ($i = 0; $i < $result->num_rows; $i++) {
555             $tb_names[$i] = (($result->data_seek( $i) && (($___mysqli_tmp = $result->fetch_row()) !== NULL)) ? array_shift($___mysqli_tmp) : false);
556         }
557         return $tb_names;
558     }
f5b0ca 559
7fe908 560     // gibt Feldinformationen zur Tabelle zur�ck
MC 561     /*
f5b0ca 562        $columns = array(action =>   add | alter | drop
N 563        name =>     Spaltenname
564        name_new => neuer Spaltenname, nur bei 'alter' belegt
565        type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
566        typeValue => Wert z.B. bei Varchar
567        defaultValue =>  Default Wert
568        notNull =>   true | false
569        autoInc =>   true | false
570        option =>   unique | primary | index)
571
572
573      */
574
7fe908 575     function tableInfo($table_name) {
f5b0ca 576
7fe908 577         global $go_api, $go_info, $app;
MC 578         // Tabellenfelder einlesen
f5b0ca 579
7fe908 580         if($rows = $app->db->queryAllRecords('SHOW FIELDS FROM '.$table_name)){
MC 581             foreach($rows as $row) {
582                 /*
f5b0ca 583       $name = $row[0];
N 584       $default = $row[4];
585       $key = $row[3];
586       $extra = $row[5];
587       $isnull = $row[2];
588       $type = $row[1];
bfcdef 589       */
7fe908 590
MC 591                 $name = $row['Field'];
592                 $default = $row['Default'];
593                 $key = $row['Key'];
594                 $extra = $row['Extra'];
595                 $isnull = $row['Null'];
596                 $type = $row['Type'];
f5b0ca 597
N 598
7fe908 599                 $column = array();
f5b0ca 600
7fe908 601                 $column['name'] = $name;
MC 602                 //$column['type'] = $type;
603                 $column['defaultValue'] = $default;
604                 if(stristr($key, 'PRI')) $column['option'] = 'primary';
605                 if(stristr($isnull, 'YES')) {
606                     $column['notNull'] = false;
607                 } else {
608                     $column['notNull'] = true;
609                 }
610                 if($extra == 'auto_increment') $column['autoInc'] = true;
f5b0ca 611
N 612
7fe908 613                 // Type in Metatype umsetzen
f5b0ca 614
7fe908 615                 if(stristr($type, 'int(')) $metaType = 'int32';
MC 616                 if(stristr($type, 'bigint')) $metaType = 'int64';
617                 if(stristr($type, 'char')) {
618                     $metaType = 'char';
619                     $tmp_typeValue = explode('(', $type);
620                     $column['typeValue'] = substr($tmp_typeValue[1], 0, -1);
621                 }
622                 if(stristr($type, 'varchar')) {
623                     $metaType = 'varchar';
624                     $tmp_typeValue = explode('(', $type);
625                     $column['typeValue'] = substr($tmp_typeValue[1], 0, -1);
626                 }
627                 if(stristr($type, 'text')) $metaType = 'text';
628                 if(stristr($type, 'double')) $metaType = 'double';
629                 if(stristr($type, 'blob')) $metaType = 'blob';
f5b0ca 630
N 631
7fe908 632                 $column['type'] = $metaType;
f5b0ca 633
7fe908 634                 $columns[] = $column;
MC 635             }
636             return $columns;
637         } else {
638             return false;
639         }
f5b0ca 640
N 641
7fe908 642         //$this->createTable('tester',$columns);
f5b0ca 643
7fe908 644         /*
f5b0ca 645      $result = mysql_list_fields($go_info["server"]["db_name"],$table_name);
N 646      $fields = mysql_num_fields ($result);
647      $i = 0;
648      $table = mysql_field_table ($result, $i);
649      while ($i < $fields) {
650      $name  = mysql_field_name  ($result, $i);
651      $type  = mysql_field_type  ($result, $i);
652      $len   = mysql_field_len   ($result, $i);
653      $flags = mysql_field_flags ($result, $i);
654      print_r($flags);
655
656      $columns = array(name => $name,
657      type =>     "",
658      defaultValue =>  "",
659      isnull =>   1,
660      option =>   "");
661      $returnvar[] = $columns;
662
663      $i++;
664      }
665        */
666
667
668
7fe908 669     }
f5b0ca 670
7fe908 671     public function mapType($metaType, $typeValue) {
MC 672         global $go_api;
673         $metaType = strtolower($metaType);
674         switch ($metaType) {
675         case 'int16':
676             return 'smallint';
677             break;
678         case 'int32':
679             return 'int';
680             break;
681         case 'int64':
682             return 'bigint';
683             break;
684         case 'double':
685             return 'double';
686             break;
687         case 'char':
688             return 'char';
689             break;
690         case 'varchar':
691             if($typeValue < 1) die('Database failure: Lenght required for these data types.');
692             return 'varchar('.$typeValue.')';
693             break;
694         case 'text':
695             return 'text';
696             break;
697         case 'blob':
698             return 'blob';
699             break;
8748b3 700         case 'date':
TB 701             return 'date';
702             break;
7fe908 703         }
MC 704     }
f5b0ca 705
7fe908 706 }
f5b0ca 707
7fe908 708 ?>