]> git.mxchange.org Git - ctracker.git/blob - libs/lib_connect.php
Updated to allow database-less operation
[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()) && (!empty($GLOBALS['ctracker_host'])) && (!empty($GLOBALS['ctracker_dbname'])) && (!empty($GLOBALS['ctracker_user']))) {
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 there a link up?
84         if (!isCrackerTrackerDatabaseLinkUp()) {
85                 // Abort silently here
86                 return false;
87         } // END - if
88
89         // Is it found?
90         if (!isCrackerTrackerEntryFound($rowData)) {
91                 // Prepare SQL
92                 $SQL = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($rowData)) . '`) VALUES(' . implode_secure($rowData) . ')';
93
94                 // Reset insert id
95                 $GLOBALS['ctracker_last_insert_id'] = false;
96
97                 // Run it
98                 runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
99
100                 // Remember the last insert id
101                 $GLOBALS['ctracker_last_insert_id'] = mysql_insert_id($GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
102         } else {
103                 // Only update the entry
104                 updateCrackerTrackerEntry($rowData);
105         }
106 }
107
108 // Updates a given entry by just counting it up
109 function updateCrackerTrackerEntry ($rowData) {
110         // Construct the SELECT query
111         $SQL = 'UPDATE `ctracker_data` SET `count`=`count`+1 WHERE `remote_addr`="' . crackerTrackerEscapeString($rowData['remote_addr']) . '" AND `check_worm` = "' . crackerTrackerEscapeString($rowData['check_worm']) . '" LIMIT 1';
112
113         // Run the SQL and check if we have one line
114         runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
115 }
116
117 // Checks if an entry with IP/check_worm/domain combination is there
118 function isCrackerTrackerEntryFound ($rowData) {
119         // Construct the SELECT query
120         $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';
121
122         // Run the SQL and check if we have one line
123         return ((isCrackerTrackerDatabaseLinkUp()) && (mysql_num_rows(runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__)) == 1));
124 }
125
126 // Escapes the string
127 function crackerTrackerEscapeString ($string) {
128         // Is the link up?
129         if (!isCrackerTrackerDatabaseLinkUp()) {
130                 // Then we cant use mysql_real_escape_string!
131                 $string = addslashes($string);
132         } elseif (function_exists('mysql_real_escape_string')) {
133                 // Use mysql_real_escape_string()
134                 $string = mysql_real_escape_string($string, $GLOBALS['ctracker_link']);
135         } elseif (function_exists('mysql_escape_string')) {
136                 // Use deprecated function
137                 $string = mysql_escape_string($string, $GLOBALS['ctracker_link']);
138         } else {
139                 // Use fall-back (bad!)
140                 $string = addslashes($string);
141         }
142
143         // Return the secured string
144         return $string;
145 } // END - if
146
147 // Runs an SQL query and checks for errors
148 function runCrackerTrackerSql ($SQL, $F, $L) {
149         // Is the link up?
150         if (!isCrackerTrackerDatabaseLinkUp()) {
151                 // Abort here
152                 crackerTrackerDie();
153         } // END - if
154
155         // Remember last SQL
156         $GLOBALS['ctracker_last_sql'] = $SQL;
157
158         // Run the query
159         $GLOBALS['ctracker_last_result'] = mysql_query($SQL, $GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
160
161         // And return it
162         return $GLOBALS['ctracker_last_result'];
163 }
164
165 // Checks wether a table was found
166 function isCrackerTrackerTableCreated ($table) {
167         // Default is not found
168         $found = false;
169
170         // Run the query
171         $result = runCrackerTrackerSql('SHOW TABLES', __FUNCTION__, __LINE__);
172
173         // Is our table there?
174         while (list($tab) = mysql_fetch_row($result)) {
175                 // Is the table there?
176                 if ($tab == $table) {
177                         // Okay, found. So abort
178                         $found = true;
179                         break;
180                 } // END - if
181         } // END - if
182
183         // Free result
184         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
185
186         // Return result
187         return $found;
188 }
189
190 // Creates the given table with columns
191 function crackerTrackerCreateTable ($table, array $columns, array $keys) {
192         // Begin the SQL
193         $SQL = 'CREATE TABLE IF NOT EXISTS `' . $table . '` (';
194
195         // Add table name as first column
196         $SQL .= '`' . $table . '` BIGINT ( 20 ) UNSIGNED NOT NULL AUTO_INCREMENT, ';
197
198         // Add all columns
199         foreach ($columns as $column=>$type) {
200                 // Add this entry
201                 $SQL .= '`' . $column . '` ' . $type . ', ';
202         } // END - foreach
203
204         // Add table name as primary key
205         $SQL .= 'PRIMARY KEY (`' . $table . '`), ';
206
207         // Add keys
208         foreach ($keys as $key=>$type) {
209                 // Add this entry
210                 $SQL .= '' . $type . ' (`' . $key . '`), ';
211         } // END - foreach
212
213         // Finish SQL
214         $SQL = substr($SQL, 0, -2) . ') TYPE=InnoDB';
215
216         // And run it
217         runCrackerTrackerSql($SQL);
218 }
219
220 // Inits a table by inserting 
221 function crackerTrackerInitTable ($table) {
222         // Prepare SQL and run it
223         runCrackerTrackerSql('INSERT INTO `' . $table . '` (`' . $table . '`) VALUES (NULL)');
224 }
225
226 // Updates the database scheme automatically
227 function crackerTrackerUpdateDatabaseScheme () {
228         // Is a link there?
229         if (!isCrackerTrackerDatabaseLinkUp()) {
230                 // Abort here silently
231                 return;
232         } // END - if
233
234         // Is the main config table there?
235         if (!isCrackerTrackerTableCreated('ctracker_config')) {
236                 // Then do it for us
237                 crackerTrackerCreateTable('ctracker_config', array(
238                         'ctracker_db_version' => 'BIGINT ( 20 ) UNSIGNED NOT NULL DEFAULT 0',
239                         'ctracker_min_sleep'  => 'SMALLINT ( 5 ) UNSIGNED NOT NULL DEFAULT 10',
240                         'ctracker_max_sleep'  => 'SMALLINT ( 5 ) UNSIGNED NOT NULL DEFAULT 30',
241                         'ctracker_alert_user' => "ENUM('Y','N') NOT NULL DEFAULT 'Y'",
242                         'ctracker_language'   => "CHAR ( 2) NOT NULL DEFAULT 'en'"
243                 ), array());
244
245                 // Init that table
246                 crackerTrackerInitTable('ctracker_config');
247         } // END - if
248
249         // Init update array here
250         crackerTrackerInitUpdates();
251
252         // Run any SQL updates recursively
253         while (isset($GLOBALS['ctracker_updates'][getCrackerTrackerConfig('ctracker_db_version')])) {
254                 // Run that updates
255                 runCrackerTrackerUpdates(getCrackerTrackerConfig('ctracker_db_version'));
256
257                 // Update config
258                 runCrackerTrackerSql('UPDATE `ctracker_config` SET `ctracker_db_version`=`ctracker_db_version`+1 WHERE `ctracker_config`=1 LIMIT 1', __FUNCTION__, __LINE__);
259
260                 // And count it up in the config array
261                 $GLOBALS['ctracker_config']['ctracker_db_version']++;
262         } // END - if
263 }
264
265 // Load the configuration
266 function crackerTrackerLoadConfig () {
267         // Construct SQL command and run it
268         $result = runCrackerTrackerSql('SELECT * FROM `ctracker_config` WHERE `ctracker_config`=1 LIMIT 1', __FUNCTION__, __LINE__);
269
270         // And get it
271         $GLOBALS['ctracker_config'] = mysql_fetch_array($result);
272
273         // Free result
274         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
275 }
276
277 // Getter for config
278 function getCrackerTrackerConfig ($entry) {
279         // Is the config entry there?
280         if (!isset($GLOBALS['ctracker_config'][$entry])) {
281                 // Then better die here, else we may have an endless loop
282                 if (isCrackerTrackerDebug()) {
283                         // Nicer message in debug mode
284                         die('Configuration entry ' . $entry . ' missing!');
285                 } else {
286                         // die() on production systems
287                         die();
288                 }
289         } // END - if
290
291         // Return it
292         return $GLOBALS['ctracker_config'][$entry];
293 }
294
295 // Did the current IP already generated blocked attempts?
296 function isCrackerTrackerIpSuspicious () {
297         // We only need the very last attempt to get!
298         $result = runCrackerTrackerSql("SELECT * FROM `ctracker_data` WHERE `remote_addr`='" . determineCrackerTrackerRealRemoteAddress() . "' ORDER BY `last_attempt` DESC LIMIT 1", __FUNCTION__, __LINE__);
299
300         // Do we have entries?
301         $found = (mysql_num_rows($result) == 1);
302
303         // And again?
304         if ($found === true) {
305                 // Cache the entry
306                 $GLOBALS['ctracker_last_suspicious_entry'] = mysql_fetch_array($result);
307         } // END - if
308
309         // Free result
310         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
311
312         // Return the result
313         return $found;
314 }
315
316 // Does the current IP have a ticket?
317 function ifCrackerTrackerIpHasTicket () {
318         // We only give one ticket per IP!
319         $result = runCrackerTrackerSql("SELECT * FROM `ctracker_ticket` WHERE `ctracker_ticket_remote_addr`='" . determineCrackerTrackerRealRemoteAddress() . "' LIMIT 1", __FUNCTION__, __LINE__);
320
321         // Do we have a ticket?
322         $found = (mysql_num_rows($result) == 1);
323
324         // And again?
325         if ($found === true) {
326                 // Cache the ticket data
327                 $GLOBALS['ctracker_last_ticket'] = mysql_fetch_array($result);
328         } // END - if
329
330         // Free result
331         mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
332
333         // Return the result
334         return $found;
335 }
336
337 // Adds a ticket based on given (mostly $_POST) data
338 function addCrackerTrackerTicket (array $data) {
339         // Prepare the array
340         $GLOBALS['ctracker_last_ticket'] = array(
341                 'ctracker_ticket_remote_addr' => determineCrackerTrackerRealRemoteAddress(),
342                 'ctracker_ticket_user_agent'  => crackerTrackerUserAgent(),
343                 'ctracker_ticket_name'        => crackerTrackerSecureString($data['name']),
344                 'ctracker_ticket_email'       => crackerTrackerSecureString($data['email']),
345                 'ctracker_ticket_comment'     => crackerTrackerSecureString($data['comment'])
346         );
347
348         // Insert it
349         crackerTrackerInsertArray('ctracker_ticket', $GLOBALS['ctracker_last_ticket']);
350
351         // Is there an entry?
352         if ((isset($GLOBALS['ctracker_last_insert_id'])) && ($GLOBALS['ctracker_last_insert_id'] > 0)) {
353                 // All fine, so prepare the link between ticket<->data
354                 $data = array(
355                         'ctracker_ticket_id' => $GLOBALS['ctracker_last_insert_id'],
356                         'ctracker_data_id'   => $GLOBALS['ctracker_last_suspicious_entry']['id']
357                 );
358
359                 // And insert it as well
360                 crackerTrackerInsertArray('ctracker_ticket_data', $data);
361
362                 // Add ticket id again
363                 $GLOBALS['ctracker_ticket'] = $data['ctracker_ticket_id'];
364
365                 // Merge all data for emails
366                 $GLOBALS['ctracker_last_ticket'] = array_merge($GLOBALS['ctracker_last_ticket'], $data);
367
368                 // Is this also there?
369                 if ((isset($GLOBALS['ctracker_last_insert_id'])) && ($GLOBALS['ctracker_last_insert_id'] > 0)) {
370                         // All fine, so display "thank you page"
371                         crackerTrackerLoadTemplate('add_ticket_thanks');
372                 } else {
373                         // Did not insert
374                         crackerTrackerDie();
375                 }
376         } else {
377                 // Did not insert
378                 crackerTrackerDie();
379         }
380 }
381
382 // [EOF]
383 ?>