]> git.mxchange.org Git - ctracker.git/blob - libs/lib_connect.php
Complete rewrite:
[ctracker.git] / libs / lib_connect.php
1 <?php
2 /**
3  * Database connection library
4  *
5  * @author              Roland Haeder <webmaster@ship-simu.org>
6  * @version             3.0.0
7  * @copyright   Copyright (c) 2009, 2010 Cracker Tracker Team
8  * @license             GNU GPL 3.0 or any newer version
9  * @link                http://www.ship-simu.org
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program. If not, see <http://www.gnu.org/licenses/>.
23  */
24
25 // Function to aquire a database link
26 function aquireCrackerTrackerDatabaseLink () {
27         // Is the link up?
28         if (!isCrackerTrackerDatabaseLinkUp()) {
29                 // Then connect to the database
30                 $GLOBALS['ctracker_link'] = mysql_connect($GLOBALS['ctracker_host'], $GLOBALS['ctracker_user'], $GLOBALS['ctracker_password']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
31
32                 // Select the database
33                 if (!mysql_select_db($GLOBALS['ctracker_dbname'], $GLOBALS['ctracker_link'])) {
34                         // Attempt has failed
35                         crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
36                 } elseif (isCrackerTrackerTableCreated('ctracker_config')) {
37                         // Load the config
38                         crackerTrackerLoadConfig();
39                 }
40         } // END - if
41 }
42
43 // Checks if the link is up
44 function isCrackerTrackerDatabaseLinkUp () {
45         return ((isset($GLOBALS['ctracker_link'])) && (is_resource($GLOBALS['ctracker_link'])));
46 }
47
48 // Database error detected
49 function crackerTrackerDatabaseError ($F, $L) {
50         // Should we debug?
51         if (isCrackerTrackerDebug()) {
52                 // Output error
53                 print 'Function    : ' . $F . '<br />';
54                 print 'Line        : ' . $L . '<br />';
55                 print 'MySQL error : ' . mysql_error() . '<br />';
56                 print 'Last SQL    : '. $GLOBALS['ctracker_last_sql'] . '<br />';
57         } // END - if
58
59         // Currently only die here
60         crackerTrackerDie();
61 }
62
63 // Closes a maybe open database link
64 function crackerTrackerCloseDatabaseLink () {
65         // Is the link up?
66         if (isCrackerTrackerDatabaseLinkUp()) {
67                 // Did it work?
68                 if (!mysql_close($GLOBALS['ctracker_link'])) {
69                         // Remove the link from global array
70                         unset($GLOBALS['ctracker_link']);
71
72                         // Attempt has failed
73                         crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
74                 } // END - if
75         } // END - if
76
77         // Remove the link from global array
78         unset($GLOBALS['ctracker_link']);
79 }
80
81 // Inserts given array, if IP/check_worm combination was not found
82 function crackerTrackerInsertArray ($table, $rowData) {
83         // Is it found?
84         if (!isCrackerTrackerEntryFound($rowData)) {
85                 // Prepare SQL
86                 $SQL = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($rowData)) . '`) VALUES(' . implode_secure($rowData) . ')';
87
88                 // Reset insert id
89                 $GLOBALS['ctracker_last_insert_id'] = false;
90
91                 // Run it
92                 runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
93
94                 // Remember the last insert id
95                 $GLOBALS['ctracker_last_insert_id'] = mysql_insert_id($GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
96         } else {
97                 // Only update the entry
98                 updateCrackerTrackerEntry($rowData);
99         }
100 }
101
102 // Updates a given entry by just counting it up
103 function updateCrackerTrackerEntry ($rowData) {
104         // Construct the SELECT query
105         $SQL = 'UPDATE `ctracker_data` SET `count`=`count`+1 WHERE `remote_addr`="' . crackerTrackerEscapeString($rowData['remote_addr']) . '" AND `check_worm` = "' . crackerTrackerEscapeString($rowData['check_worm']) . '" LIMIT 1';
106
107         // Run the SQL and check if we have one line
108         runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
109 }
110
111 // Checks if an entry with IP/check_worm/domain combination is there
112 function isCrackerTrackerEntryFound ($rowData) {
113         // Construct the SELECT query
114         $SQL = 'SELECT `id` FROM `ctracker_data` WHERE `remote_addr`="' . crackerTrackerEscapeString($rowData['remote_addr']) . '" AND `check_worm` = "' . crackerTrackerEscapeString($rowData['check_worm']) . '" AND `server_name`="' . crackerTrackerEscapeString($rowData['server_name']) . '" LIMIT 1';
115
116         // Run the SQL and check if we have one line
117         return (mysql_num_rows(runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__)) == 1);
118 }
119
120 // Escapes the string
121 function crackerTrackerEscapeString ($string) {
122         // Is the link up?
123         if (!isCrackerTrackerDatabaseLinkUp()) {
124                 // Then we cant use mysql_real_escape_string!
125                 $string = addslashes($string);
126         } elseif (function_exists('mysql_real_escape_string')) {
127                 // Use mysql_real_escape_string()
128                 $string = mysql_real_escape_string($string, $GLOBALS['ctracker_link']);
129         } elseif (function_exists('mysql_escape_string')) {
130                 // Use deprecated function
131                 $string = mysql_escape_string($string, $GLOBALS['ctracker_link']);
132         } else {
133                 // Use fall-back (bad!)
134                 $string = addslashes($string);
135         }
136
137         // Return the secured string
138         return $string;
139 } // END - if
140
141 // Runs an SQL query and checks for errors
142 function runCrackerTrackerSql ($SQL, $F, $L) {
143         // Is the link up?
144         if (!isCrackerTrackerDatabaseLinkUp()) {
145                 // Abort here
146                 crackerTrackerDie();
147         } // END - if
148
149         // Remember last SQL
150         $GLOBALS['ctracker_last_sql'] = $SQL;
151
152         // Run the query
153         $GLOBALS['ctracker_last_result'] = mysql_query($SQL, $GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
154
155         // And return it
156         return $GLOBALS['ctracker_last_result'];
157 }
158
159 // Checks wether a table was found
160 function isCrackerTrackerTableCreated ($table) {
161         // Default is not found
162         $found = false;
163
164         // Run the query
165         $result = runCrackerTrackerSql('SHOW TABLES', __FUNCTION__, __LINE__);
166
167         // Is our table there?
168         while (list($tab) = mysql_fetch_row($result)) {
169                 // Is the table there?
170                 if ($tab == $table) {
171                         // Okay, found. So abort
172                         $found = true;
173                         break;
174                 } // END - if
175         } // END - if
176
177         // Free result
178         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
179
180         // Return result
181         return $found;
182 }
183
184 // Creates the given table with columns
185 function crackerTrackerCreateTable ($table, array $columns, array $keys) {
186         // Begin the SQL
187         $SQL = 'CREATE TABLE IF NOT EXISTS `' . $table . '` (';
188
189         // Add table name as first column
190         $SQL .= '`' . $table . '` BIGINT ( 20 ) UNSIGNED NOT NULL AUTO_INCREMENT, ';
191
192         // Add all columns
193         foreach ($columns as $column=>$type) {
194                 // Add this entry
195                 $SQL .= '`' . $column . '` ' . $type . ', ';
196         } // END - foreach
197
198         // Add table name as primary key
199         $SQL .= 'PRIMARY KEY (`' . $table . '`), ';
200
201         // Add keys
202         foreach ($keys as $key=>$type) {
203                 // Add this entry
204                 $SQL .= '' . $type . ' (`' . $key . '`), ';
205         } // END - foreach
206
207         // Finish SQL
208         $SQL = substr($SQL, 0, -2) . ') TYPE=InnoDB';
209
210         // And run it
211         runCrackerTrackerSql($SQL);
212 }
213
214 // Inits a table by inserting 
215 function crackerTrackerInitTable ($table) {
216         // Prepare SQL and run it
217         runCrackerTrackerSql('INSERT INTO `' . $table . '` (`' . $table . '`) VALUES (NULL)');
218 }
219
220 // Updates the database scheme automatically
221 function crackerTrackerUpdateDatabaseScheme () {
222         // Is the main config table there?
223         if (!isCrackerTrackerTableCreated('ctracker_config')) {
224                 // Then do it for us
225                 crackerTrackerCreateTable('ctracker_config', array(
226                         'ctracker_db_version' => 'BIGINT ( 20 ) UNSIGNED NOT NULL DEFAULT 0',
227                         'ctracker_min_sleep'  => 'SMALLINT ( 5 ) UNSIGNED NOT NULL DEFAULT 10',
228                         'ctracker_max_sleep'  => 'SMALLINT ( 5 ) UNSIGNED NOT NULL DEFAULT 30',
229                         'ctracker_alert_user' => "ENUM('Y','N') NOT NULL DEFAULT 'Y'",
230                         'ctracker_language'   => "CHAR ( 2) NOT NULL DEFAULT 'en'"
231                 ), array());
232
233                 // Init that table
234                 crackerTrackerInitTable('ctracker_config');
235         } // END - if
236
237         // Init update array here
238         crackerTrackerInitUpdates();
239
240         // Run any SQL updates recursively
241         while (isset($GLOBALS['ctracker_updates'][getCrackerTrackerConfig('ctracker_db_version')])) {
242                 // Run that updates
243                 runCrackerTrackerUpdates(getCrackerTrackerConfig('ctracker_db_version'));
244
245                 // Update config
246                 runCrackerTrackerSql('UPDATE `ctracker_config` SET `ctracker_db_version`=`ctracker_db_version`+1 WHERE `ctracker_config`=1 LIMIT 1', __FUNCTION__, __LINE__);
247
248                 // And count it up in the config array
249                 $GLOBALS['ctracker_config']['ctracker_db_version']++;
250         } // END - if
251 }
252
253 // Load the configuration
254 function crackerTrackerLoadConfig () {
255         // Construct SQL command and run it
256         $result = runCrackerTrackerSql('SELECT * FROM `ctracker_config` WHERE `ctracker_config`=1 LIMIT 1', __FUNCTION__, __LINE__);
257
258         // And get it
259         $GLOBALS['ctracker_config'] = mysql_fetch_array($result);
260
261         // Free result
262         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
263 }
264
265 // Getter for config
266 function getCrackerTrackerConfig ($entry) {
267         // Is the config entry there?
268         if (!isset($GLOBALS['ctracker_config'][$entry])) {
269                 // Then better die here, else we may have an endless loop
270                 if (isCrackerTrackerDebug()) {
271                         // Nicer message in debug mode
272                         die('Configuration entry ' . $entry . ' missing!');
273                 } else {
274                         // die() on production systems
275                         die();
276                 }
277         } // END - if
278
279         // Return it
280         return $GLOBALS['ctracker_config'][$entry];
281 }
282
283 // Did the current IP already generated blocked attempts?
284 function isCrackerTrackerIpSuspicious () {
285         // We only need the very last attempt to get!
286         $result = runCrackerTrackerSql("SELECT * FROM `ctracker_data` WHERE `remote_addr`='" . determineCrackerTrackerRealRemoteAddress() . "' ORDER BY `last_attempt` DESC LIMIT 1", __FUNCTION__, __LINE__);
287
288         // Do we have entries?
289         $found = (mysql_num_rows($result) == 1);
290
291         // And again?
292         if ($found === true) {
293                 // Cache the entry
294                 $GLOBALS['ctracker_last_suspicious_entry'] = mysql_fetch_array($result);
295         } // END - if
296
297         // Free result
298         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
299
300         // Return the result
301         return $found;
302 }
303
304 // Does the current IP have a ticket?
305 function ifCrackerTrackerIpHasTicket () {
306         // We only give one ticket per IP!
307         $result = runCrackerTrackerSql("SELECT * FROM `ctracker_ticket` WHERE `ctracker_ticket_remote_addr`='" . determineCrackerTrackerRealRemoteAddress() . "' LIMIT 1", __FUNCTION__, __LINE__);
308
309         // Do we have a ticket?
310         $found = (mysql_num_rows($result) == 1);
311
312         // And again?
313         if ($found === true) {
314                 // Cache the ticket data
315                 $GLOBALS['ctracker_last_ticket'] = mysql_fetch_array($result);
316         } // END - if
317
318         // Free result
319         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
320
321         // Return the result
322         return $found;
323 }
324
325 // Adds a ticket based on given (mostly $_POST) data
326 function addCrackerTrackerTicket (array $data) {
327         // Prepare the array
328         $GLOBALS['ctracker_last_ticket'] = array(
329                 'ctracker_ticket_remote_addr' => determineCrackerTrackerRealRemoteAddress(),
330                 'ctracker_ticket_user_agent'  => crackerTrackerUserAgent(),
331                 'ctracker_ticket_name'        => crackerTrackerSecureString($data['name']),
332                 'ctracker_ticket_email'       => crackerTrackerSecureString($data['email']),
333                 'ctracker_ticket_comment'     => crackerTrackerSecureString($data['comment'])
334         );
335
336         // Insert it
337         crackerTrackerInsertArray('ctracker_ticket', $GLOBALS['ctracker_last_ticket']);
338
339         // Is there an entry?
340         if ((isset($GLOBALS['ctracker_last_insert_id'])) && ($GLOBALS['ctracker_last_insert_id'] > 0)) {
341                 // All fine, so prepare the link between ticket<->data
342                 $data = array(
343                         'ctracker_ticket'  => $GLOBALS['ctracker_last_insert_id'],
344                         'ctracker_data_id' => $GLOBALS['ctracker_last_suspicious_entry']['id']
345                 );
346
347                 // And insert it as well
348                 crackerTrackerInsertArray('ctracker_ticket_data', $data);
349
350                 // Merge all data for emails
351                 $GLOBALS['ctracker_last_ticket'] = array_merge($GLOBALS['ctracker_last_ticket'], $data);
352
353                 // Is this also there?
354                 if ((isset($GLOBALS['ctracker_last_insert_id'])) && ($GLOBALS['ctracker_last_insert_id'] > 0)) {
355                         // All fine, so display "thank you page"
356                         crackerTrackerLoadTemplate('add_ticket_thanks');
357                 } else {
358                         // Did not insert
359                         crackerTrackerDie();
360                 }
361         } else {
362                 // Did not insert
363                 crackerTrackerDie();
364         }
365 }
366
367 // [EOF]
368 ?>