3 * Database connection library
5 * @author Roland Haeder <webmaster@ship-simu.org>
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
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.
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.
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/>.
25 // Function to aquire a database link
26 function aquireCrackerTrackerDatabaseLink () {
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__);
32 // Select the database
33 if (!mysql_select_db($GLOBALS['ctracker_dbname'], $GLOBALS['ctracker_link'])) {
35 crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
36 } elseif (isCrackerTrackerTableCreated('ctracker_config')) {
38 crackerTrackerLoadConfig();
43 // Checks if the link is up
44 function isCrackerTrackerDatabaseLinkUp () {
45 return ((isset($GLOBALS['ctracker_link'])) && (is_resource($GLOBALS['ctracker_link'])));
48 // Database error detected
49 function crackerTrackerDatabaseError ($F, $L) {
51 if (isCrackerTrackerDebug()) {
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 />';
59 // Currently only die here
63 // Closes a maybe open database link
64 function crackerTrackerCloseDatabaseLink () {
66 if (isCrackerTrackerDatabaseLinkUp()) {
68 if (!mysql_close($GLOBALS['ctracker_link'])) {
69 // Remove the link from global array
70 unset($GLOBALS['ctracker_link']);
73 crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
77 // Remove the link from global array
78 unset($GLOBALS['ctracker_link']);
81 // Inserts given array, if IP/check_worm combination was not found
82 function crackerTrackerInsertArray ($table, $rowData) {
84 if (!isCrackerTrackerEntryFound($rowData)) {
86 $SQL = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($rowData)) . '`) VALUES(' . implode_secure($rowData) . ')';
89 $GLOBALS['ctracker_last_insert_id'] = false;
92 runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
94 // Remember the last insert id
95 $GLOBALS['ctracker_last_insert_id'] = mysql_insert_id($GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
97 // Only update the entry
98 updateCrackerTrackerEntry($rowData);
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';
107 // Run the SQL and check if we have one line
108 runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
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';
116 // Run the SQL and check if we have one line
117 return (mysql_num_rows(runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__)) == 1);
120 // Escapes the string
121 function crackerTrackerEscapeString ($string) {
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']);
133 // Use fall-back (bad!)
134 $string = addslashes($string);
137 // Return the secured string
141 // Runs an SQL query and checks for errors
142 function runCrackerTrackerSql ($SQL, $F, $L) {
144 if (!isCrackerTrackerDatabaseLinkUp()) {
150 $GLOBALS['ctracker_last_sql'] = $SQL;
153 $GLOBALS['ctracker_last_result'] = mysql_query($SQL, $GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
156 return $GLOBALS['ctracker_last_result'];
159 // Checks wether a table was found
160 function isCrackerTrackerTableCreated ($table) {
161 // Default is not found
165 $result = runCrackerTrackerSql('SHOW TABLES', __FUNCTION__, __LINE__);
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
178 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
184 // Creates the given table with columns
185 function crackerTrackerCreateTable ($table, array $columns, array $keys) {
187 $SQL = 'CREATE TABLE IF NOT EXISTS `' . $table . '` (';
189 // Add table name as first column
190 $SQL .= '`' . $table . '` BIGINT ( 20 ) UNSIGNED NOT NULL AUTO_INCREMENT, ';
193 foreach ($columns as $column=>$type) {
195 $SQL .= '`' . $column . '` ' . $type . ', ';
198 // Add table name as primary key
199 $SQL .= 'PRIMARY KEY (`' . $table . '`), ';
202 foreach ($keys as $key=>$type) {
204 $SQL .= '' . $type . ' (`' . $key . '`), ';
208 $SQL = substr($SQL, 0, -2) . ') TYPE=InnoDB';
211 runCrackerTrackerSql($SQL);
214 // Inits a table by inserting
215 function crackerTrackerInitTable ($table) {
216 // Prepare SQL and run it
217 runCrackerTrackerSql('INSERT INTO `' . $table . '` (`' . $table . '`) VALUES (NULL)');
220 // Updates the database scheme automatically
221 function crackerTrackerUpdateDatabaseScheme () {
222 // Is the main config table there?
223 if (!isCrackerTrackerTableCreated('ctracker_config')) {
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'"
234 crackerTrackerInitTable('ctracker_config');
237 // Init update array here
238 crackerTrackerInitUpdates();
240 // Run any SQL updates recursively
241 while (isset($GLOBALS['ctracker_updates'][getCrackerTrackerConfig('ctracker_db_version')])) {
243 runCrackerTrackerUpdates(getCrackerTrackerConfig('ctracker_db_version'));
246 runCrackerTrackerSql('UPDATE `ctracker_config` SET `ctracker_db_version`=`ctracker_db_version`+1 WHERE `ctracker_config`=1 LIMIT 1', __FUNCTION__, __LINE__);
248 // And count it up in the config array
249 $GLOBALS['ctracker_config']['ctracker_db_version']++;
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__);
259 $GLOBALS['ctracker_config'] = mysql_fetch_array($result);
262 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
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!');
274 // die() on production systems
280 return $GLOBALS['ctracker_config'][$entry];
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__);
288 // Do we have entries?
289 $found = (mysql_num_rows($result) == 1);
292 if ($found === true) {
294 $GLOBALS['ctracker_last_suspicious_entry'] = mysql_fetch_array($result);
298 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
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__);
309 // Do we have a ticket?
310 $found = (mysql_num_rows($result) == 1);
313 if ($found === true) {
314 // Cache the ticket data
315 $GLOBALS['ctracker_last_ticket'] = mysql_fetch_array($result);
319 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
325 // Adds a ticket based on given (mostly $_POST) data
326 function addCrackerTrackerTicket (array $data) {
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'])
337 crackerTrackerInsertArray('ctracker_ticket', $GLOBALS['ctracker_last_ticket']);
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
343 'ctracker_ticket_id' => $GLOBALS['ctracker_last_insert_id'],
344 'ctracker_data_id' => $GLOBALS['ctracker_last_suspicious_entry']['id']
347 // And insert it as well
348 crackerTrackerInsertArray('ctracker_ticket_data', $data);
350 // Add ticket id again
351 $GLOBALS['ctracker_ticket'] = $data['ctracker_ticket_id'];
353 // Merge all data for emails
354 $GLOBALS['ctracker_last_ticket'] = array_merge($GLOBALS['ctracker_last_ticket'], $data);
356 // Is this also there?
357 if ((isset($GLOBALS['ctracker_last_insert_id'])) && ($GLOBALS['ctracker_last_insert_id'] > 0)) {
358 // All fine, so display "thank you page"
359 crackerTrackerLoadTemplate('add_ticket_thanks');