Till Brehm
2014-08-14 7272e49c868f30d434965a59b1dc209925aec1b2
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
7272e4 266         if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$db_table)) $app->error('Invalid table name '.$db_table);
cd48c7 267         if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$primary_field)) $app->error('Invalid primary field '.$primary_field.' in table '.$db_table);
94b44c 268         
TB 269         $primary_field = $this->quote($primary_field);
270         $primary_id = intval($primary_id);
f5b0ca 271
b0eb45 272         if($force_update == true) {
T 273             //* We force a update even if no record has changed
7fe908 274             $diffrec_full = array('new' => $record_new, 'old' => $record_old);
b0eb45 275             $diff_num = count($record_new);
T 276         } else {
277             //* get the difference record between old and new record
278             $tmp = $this->diffrec($record_old, $record_new);
279             $diffrec_full = $tmp['diff_rec'];
280             $diff_num = $tmp['diff_num'];
281             unset($tmp);
282         }
f5b0ca 283
7fe908 284         // Insert the server_id, if the record has a server_id
MC 285         $server_id = (isset($record_old['server_id']) && $record_old['server_id'] > 0)?$record_old['server_id']:0;
286         if(isset($record_new['server_id'])) $server_id = $record_new['server_id'];
e9a57d 287         $server_id = intval($server_id);
f5b0ca 288
7fe908 289         if($diff_num > 0) {
MC 290             //print_r($diff_num);
291             //print_r($diffrec_full);
292             $diffstr = $app->db->quote(serialize($diffrec_full));
293             $username = $app->db->quote($_SESSION['s']['user']['username']);
294             $dbidx = $primary_field.':'.$primary_id;
f5b0ca 295
7fe908 296             if($action == 'INSERT') $action = 'i';
MC 297             if($action == 'UPDATE') $action = 'u';
298             if($action == 'DELETE') $action = 'd';
299             $sql = "INSERT INTO sys_datalog (dbtable,dbidx,server_id,action,tstamp,user,data) VALUES ('".$db_table."','$dbidx','$server_id','$action','".time()."','$username','$diffstr')";
300             $app->db->query($sql);
301         }
f5b0ca 302
7fe908 303         return true;
MC 304     }
f5b0ca 305
7fe908 306     //** Inserts a record and saves the changes into the datalog
MC 307     public function datalogInsert($tablename, $insert_data, $index_field) {
308         global $app;
e9a57d 309         
94b44c 310         // Check fields
7272e4 311         if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename);
cd48c7 312         if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename);
94b44c 313         
TB 314         if(strpos($tablename, '.') !== false) {
7272e4 315             $tablename_escaped = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename);
94b44c 316         } else {
7272e4 317             $tablename_escaped = '`' . $tablename . '`';
94b44c 318         }
TB 319         
e9a57d 320         $index_field = $this->quote($index_field);
7fe908 321
MC 322         if(is_array($insert_data)) {
ee260d 323             $key_str = '';
T 324             $val_str = '';
325             foreach($insert_data as $key => $val) {
326                 $key_str .= "`".$key ."`,";
327                 $val_str .= "'".$this->quote($val)."',";
328             }
7fe908 329             $key_str = substr($key_str, 0, -1);
MC 330             $val_str = substr($val_str, 0, -1);
ee260d 331             $insert_data_str = '('.$key_str.') VALUES ('.$val_str.')';
T 332         } else {
333             $insert_data_str = $insert_data;
334         }
f5b0ca 335
7fe908 336         $old_rec = array();
7272e4 337         $this->query("INSERT INTO $tablename_escaped $insert_data_str");
7fe908 338         $index_value = $this->insertID();
7272e4 339         $new_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'");
7fe908 340         $this->datalogSave($tablename, 'INSERT', $index_field, $index_value, $old_rec, $new_rec);
f5b0ca 341
7fe908 342         return $index_value;
MC 343     }
f5b0ca 344
7fe908 345     //** Updates a record and saves the changes into the datalog
MC 346     public function datalogUpdate($tablename, $update_data, $index_field, $index_value, $force_update = false) {
ee260d 347         global $app;
e9a57d 348         
94b44c 349         // Check fields
7272e4 350         if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename);
cd48c7 351         if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename);
94b44c 352         
TB 353         if(strpos($tablename, '.') !== false) {
7272e4 354             $tablename_escaped = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename);
94b44c 355         } else {
7272e4 356             $tablename_escaped = '`' . $tablename . '`';
94b44c 357         }
TB 358         
e9a57d 359         $index_field = $this->quote($index_field);
TB 360         $index_value = $this->quote($index_value);
7fe908 361
7272e4 362         $old_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'");
7fe908 363
MC 364         if(is_array($update_data)) {
ee260d 365             $update_data_str = '';
T 366             foreach($update_data as $key => $val) {
367                 $update_data_str .= "`".$key ."` = '".$this->quote($val)."',";
368             }
7fe908 369             $update_data_str = substr($update_data_str, 0, -1);
ee260d 370         } else {
T 371             $update_data_str = $update_data;
372         }
f5b0ca 373
7272e4 374         $this->query("UPDATE $tablename_escaped SET $update_data_str WHERE $index_field = '$index_value'");
TB 375         $new_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'");
7fe908 376         $this->datalogSave($tablename, 'UPDATE', $index_field, $index_value, $old_rec, $new_rec, $force_update);
f5b0ca 377
7fe908 378         return true;
MC 379     }
f5b0ca 380
7fe908 381     //** Deletes a record and saves the changes into the datalog
MC 382     public function datalogDelete($tablename, $index_field, $index_value) {
383         global $app;
e9a57d 384         
94b44c 385         // Check fields
7272e4 386         if(!preg_match('/^[a-zA-Z0-9\-\_\.]{1,64}$/',$tablename)) $app->error('Invalid table name '.$tablename);
cd48c7 387         if(!preg_match('/^[a-zA-Z0-9\-\_]{1,64}$/',$index_field)) $app->error('Invalid index field '.$index_field.' in table '.$tablename);
94b44c 388         
TB 389         if(strpos($tablename, '.') !== false) {
7272e4 390             $tablename_escaped = preg_replace('/^(.+)\.(.+)$/', '`$1`.`$2`', $tablename);
94b44c 391         } else {
7272e4 392             $tablename_escaped = '`' . $tablename . '`';
94b44c 393         }
TB 394         
e9a57d 395         $index_field = $this->quote($index_field);
TB 396         $index_value = $this->quote($index_value);
f5b0ca 397
7272e4 398         $old_rec = $this->queryOneRecord("SELECT * FROM $tablename_escaped WHERE $index_field = '$index_value'");
TB 399         $this->query("DELETE FROM $tablename_escaped WHERE $index_field = '$index_value'");
7fe908 400         $new_rec = array();
MC 401         $this->datalogSave($tablename, 'DELETE', $index_field, $index_value, $old_rec, $new_rec);
402
403         return true;
404     }
405
406     //* get the current datalog status for the specified login (or currently logged in user)
407     public function datalogStatus($login = '') {
408         global $app;
409
410         $return = array('count' => 0, 'entries' => array());
411         if($_SESSION['s']['user']['typ'] == 'admin') return $return; // these information should not be displayed to admin users
412
413         if($login == '' && isset($_SESSION['s']['user'])) {
414             $login = $_SESSION['s']['user']['username'];
415         }
416
417         $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");
418         foreach($result as $row) {
419             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
420             $return['entries'][] = array('table' => $row['dbtable'], 'action' => $row['action'], 'count' => $row['cnt'], 'text' => $app->lng('datalog_status_' . $row['action'] . '_' . $row['dbtable']));
421             $return['count'] += $row['cnt'];
422         }
423         unset($result);
424
425         return $return;
426     }
f5b0ca 427
N 428
7fe908 429     public function freeResult($query)
MC 430     {
431         if(is_object($query) && (get_class($query) == "mysqli_result")) {
432             $query->free();
433             return true;
434         } else {
435             return false;
436         }
437     }
12fcb2 438
7fe908 439     /* TODO: Does anything use this? */
MC 440     public function delete() {
b5a2f8 441
7fe908 442     }
f5b0ca 443
7fe908 444     /* TODO: Does anything use this? */
MC 445     public function Transaction($action) {
446         //action = begin, commit oder rollback
f5b0ca 447
7fe908 448     }
f5b0ca 449
7fe908 450     /*
f5b0ca 451        $columns = array(action =>   add | alter | drop
N 452        name =>     Spaltenname
453        name_new => neuer Spaltenname, nur bei 'alter' belegt
454        type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
455        typeValue => Wert z.B. bei Varchar
456        defaultValue =>  Default Wert
457        notNull =>   true | false
458        autoInc =>   true | false
459        option =>   unique | primary | index)
460
461
462      */
463
7fe908 464     public function createTable($table_name, $columns) {
MC 465         $index = '';
466         $sql = "CREATE TABLE $table_name (";
467         foreach($columns as $col){
468             $sql .= $col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
f5b0ca 469
7fe908 470             if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' ";
MC 471             if($col['notNull'] == true) {
472                 $sql .= 'NOT NULL ';
473             } else {
474                 $sql .= 'NULL ';
475             }
476             if($col['autoInc'] == true) $sql .= 'auto_increment ';
477             $sql.= ',';
478             // key Definitionen
479             if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),';
480             if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),';
481             if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),';
482         }
483         $sql .= $index;
484         $sql = substr($sql, 0, -1);
485         $sql .= ')';
486         $this->query($sql);
487         return true;
f5b0ca 488     }
N 489
7fe908 490     /*
f5b0ca 491        $columns = array(action =>   add | alter | drop
N 492        name =>     Spaltenname
493        name_new => neuer Spaltenname, nur bei 'alter' belegt
494        type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
495        typeValue => Wert z.B. bei Varchar
496        defaultValue =>  Default Wert
497        notNull =>   true | false
498        autoInc =>   true | false
499        option =>   unique | primary | index)
500
501
502      */
7fe908 503     public function alterTable($table_name, $columns) {
MC 504         $index = '';
505         $sql = "ALTER TABLE $table_name ";
506         foreach($columns as $col){
507             if($col['action'] == 'add') {
508                 $sql .= 'ADD '.$col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
509             } elseif ($col['action'] == 'alter') {
510                 $sql .= 'CHANGE '.$col['name'].' '.$col['name_new'].' '.$this->mapType($col['type'], $col['typeValue']).' ';
511             } elseif ($col['action'] == 'drop') {
512                 $sql .= 'DROP '.$col['name'].' ';
513             }
514             if($col['action'] != 'drop') {
515                 if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' ";
516                 if($col['notNull'] == true) {
517                     $sql .= 'NOT NULL ';
518                 } else {
519                     $sql .= 'NULL ';
520                 }
521                 if($col['autoInc'] == true) $sql .= 'auto_increment ';
522                 $sql.= ',';
523                 // Index definitions
524                 if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),';
525                 if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),';
526                 if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),';
527             }
528         }
529         $sql .= $index;
530         $sql = substr($sql, 0, -1);
531
532         //die($sql);
533         $this->query($sql);
534         return true;
f5b0ca 535     }
7fe908 536
MC 537     public function dropTable($table_name) {
538         $this->check($table_name);
539         $sql = "DROP TABLE '". $table_name."'";
540         return $this->query($sql);
f5b0ca 541     }
N 542
7fe908 543     // gibt Array mit Tabellennamen zur�ck
MC 544     public function getTables($database_name = '') {
545         if($this->isConnected == false) return false;
546         if($database_name == '') $database_name = $this->dbName;
547         $result = parent::query("SHOW TABLES FROM $database_name");
548         for ($i = 0; $i < $result->num_rows; $i++) {
549             $tb_names[$i] = (($result->data_seek( $i) && (($___mysqli_tmp = $result->fetch_row()) !== NULL)) ? array_shift($___mysqli_tmp) : false);
550         }
551         return $tb_names;
552     }
f5b0ca 553
7fe908 554     // gibt Feldinformationen zur Tabelle zur�ck
MC 555     /*
f5b0ca 556        $columns = array(action =>   add | alter | drop
N 557        name =>     Spaltenname
558        name_new => neuer Spaltenname, nur bei 'alter' belegt
559        type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
560        typeValue => Wert z.B. bei Varchar
561        defaultValue =>  Default Wert
562        notNull =>   true | false
563        autoInc =>   true | false
564        option =>   unique | primary | index)
565
566
567      */
568
7fe908 569     function tableInfo($table_name) {
f5b0ca 570
7fe908 571         global $go_api, $go_info, $app;
MC 572         // Tabellenfelder einlesen
f5b0ca 573
7fe908 574         if($rows = $app->db->queryAllRecords('SHOW FIELDS FROM '.$table_name)){
MC 575             foreach($rows as $row) {
576                 /*
f5b0ca 577       $name = $row[0];
N 578       $default = $row[4];
579       $key = $row[3];
580       $extra = $row[5];
581       $isnull = $row[2];
582       $type = $row[1];
bfcdef 583       */
7fe908 584
MC 585                 $name = $row['Field'];
586                 $default = $row['Default'];
587                 $key = $row['Key'];
588                 $extra = $row['Extra'];
589                 $isnull = $row['Null'];
590                 $type = $row['Type'];
f5b0ca 591
N 592
7fe908 593                 $column = array();
f5b0ca 594
7fe908 595                 $column['name'] = $name;
MC 596                 //$column['type'] = $type;
597                 $column['defaultValue'] = $default;
598                 if(stristr($key, 'PRI')) $column['option'] = 'primary';
599                 if(stristr($isnull, 'YES')) {
600                     $column['notNull'] = false;
601                 } else {
602                     $column['notNull'] = true;
603                 }
604                 if($extra == 'auto_increment') $column['autoInc'] = true;
f5b0ca 605
N 606
7fe908 607                 // Type in Metatype umsetzen
f5b0ca 608
7fe908 609                 if(stristr($type, 'int(')) $metaType = 'int32';
MC 610                 if(stristr($type, 'bigint')) $metaType = 'int64';
611                 if(stristr($type, 'char')) {
612                     $metaType = 'char';
613                     $tmp_typeValue = explode('(', $type);
614                     $column['typeValue'] = substr($tmp_typeValue[1], 0, -1);
615                 }
616                 if(stristr($type, 'varchar')) {
617                     $metaType = 'varchar';
618                     $tmp_typeValue = explode('(', $type);
619                     $column['typeValue'] = substr($tmp_typeValue[1], 0, -1);
620                 }
621                 if(stristr($type, 'text')) $metaType = 'text';
622                 if(stristr($type, 'double')) $metaType = 'double';
623                 if(stristr($type, 'blob')) $metaType = 'blob';
f5b0ca 624
N 625
7fe908 626                 $column['type'] = $metaType;
f5b0ca 627
7fe908 628                 $columns[] = $column;
MC 629             }
630             return $columns;
631         } else {
632             return false;
633         }
f5b0ca 634
N 635
7fe908 636         //$this->createTable('tester',$columns);
f5b0ca 637
7fe908 638         /*
f5b0ca 639      $result = mysql_list_fields($go_info["server"]["db_name"],$table_name);
N 640      $fields = mysql_num_fields ($result);
641      $i = 0;
642      $table = mysql_field_table ($result, $i);
643      while ($i < $fields) {
644      $name  = mysql_field_name  ($result, $i);
645      $type  = mysql_field_type  ($result, $i);
646      $len   = mysql_field_len   ($result, $i);
647      $flags = mysql_field_flags ($result, $i);
648      print_r($flags);
649
650      $columns = array(name => $name,
651      type =>     "",
652      defaultValue =>  "",
653      isnull =>   1,
654      option =>   "");
655      $returnvar[] = $columns;
656
657      $i++;
658      }
659        */
660
661
662
7fe908 663     }
f5b0ca 664
7fe908 665     public function mapType($metaType, $typeValue) {
MC 666         global $go_api;
667         $metaType = strtolower($metaType);
668         switch ($metaType) {
669         case 'int16':
670             return 'smallint';
671             break;
672         case 'int32':
673             return 'int';
674             break;
675         case 'int64':
676             return 'bigint';
677             break;
678         case 'double':
679             return 'double';
680             break;
681         case 'char':
682             return 'char';
683             break;
684         case 'varchar':
685             if($typeValue < 1) die('Database failure: Lenght required for these data types.');
686             return 'varchar('.$typeValue.')';
687             break;
688         case 'text':
689             return 'text';
690             break;
691         case 'blob':
692             return 'blob';
693             break;
8748b3 694         case 'date':
TB 695             return 'date';
696             break;
7fe908 697         }
MC 698     }
f5b0ca 699
7fe908 700 }
f5b0ca 701
7fe908 702 ?>