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()) && (!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__);
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) {
83 // Is there a link up?
84 if (!isCrackerTrackerDatabaseLinkUp()) {
85 // Abort silently here
90 if (!isCrackerTrackerEntryFound($rowData)) {
92 $SQL = 'INSERT INTO `' . $table . '` (`' . implode('`,`', array_keys($rowData)) . '`) VALUES(' . implode_secure($rowData) . ')';
95 $GLOBALS['ctracker_last_insert_id'] = false;
98 runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
100 // Remember the last insert id
101 $GLOBALS['ctracker_last_insert_id'] = mysql_insert_id($GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
103 // Only update the entry
104 updateCrackerTrackerEntry($rowData);
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';
113 // Run the SQL and check if we have one line
114 runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__);
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';
122 // Run the SQL and check if we have one line
123 return ((isCrackerTrackerDatabaseLinkUp()) && (mysql_num_rows(runCrackerTrackerSql($SQL, __FUNCTION__, __LINE__)) == 1));
126 // Escapes the string
127 function crackerTrackerEscapeString ($string) {
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']);
139 // Use fall-back (bad!)
140 $string = addslashes($string);
143 // Return the secured string
147 // Runs an SQL query and checks for errors
148 function runCrackerTrackerSql ($SQL, $F, $L) {
150 if (!isCrackerTrackerDatabaseLinkUp()) {
156 $GLOBALS['ctracker_last_sql'] = $SQL;
159 $GLOBALS['ctracker_last_result'] = mysql_query($SQL, $GLOBALS['ctracker_link']) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
162 return $GLOBALS['ctracker_last_result'];
165 // Checks wether a table was found
166 function isCrackerTrackerTableCreated ($table) {
167 // Default is not found
171 $result = runCrackerTrackerSql('SHOW TABLES', __FUNCTION__, __LINE__);
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
184 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
190 // Creates the given table with columns
191 function crackerTrackerCreateTable ($table, array $columns, array $keys) {
193 $SQL = 'CREATE TABLE IF NOT EXISTS `' . $table . '` (';
195 // Add table name as first column
196 $SQL .= '`' . $table . '` BIGINT ( 20 ) UNSIGNED NOT NULL AUTO_INCREMENT, ';
199 foreach ($columns as $column=>$type) {
201 $SQL .= '`' . $column . '` ' . $type . ', ';
204 // Add table name as primary key
205 $SQL .= 'PRIMARY KEY (`' . $table . '`), ';
208 foreach ($keys as $key=>$type) {
210 $SQL .= '' . $type . ' (`' . $key . '`), ';
214 $SQL = substr($SQL, 0, -2) . ') TYPE=InnoDB';
217 runCrackerTrackerSql($SQL);
220 // Inits a table by inserting
221 function crackerTrackerInitTable ($table) {
222 // Prepare SQL and run it
223 runCrackerTrackerSql('INSERT INTO `' . $table . '` (`' . $table . '`) VALUES (NULL)');
226 // Updates the database scheme automatically
227 function crackerTrackerUpdateDatabaseScheme () {
229 if (!isCrackerTrackerDatabaseLinkUp()) {
230 // Abort here silently
234 // Is the main config table there?
235 if (!isCrackerTrackerTableCreated('ctracker_config')) {
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'"
246 crackerTrackerInitTable('ctracker_config');
249 // Init update array here
250 crackerTrackerInitUpdates();
252 // Run any SQL updates recursively
253 while (isset($GLOBALS['ctracker_updates'][getCrackerTrackerConfig('ctracker_db_version')])) {
255 runCrackerTrackerUpdates(getCrackerTrackerConfig('ctracker_db_version'));
258 runCrackerTrackerSql('UPDATE `ctracker_config` SET `ctracker_db_version`=`ctracker_db_version`+1 WHERE `ctracker_config`=1 LIMIT 1', __FUNCTION__, __LINE__);
260 // And count it up in the config array
261 $GLOBALS['ctracker_config']['ctracker_db_version']++;
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__);
271 $GLOBALS['ctracker_config'] = mysql_fetch_array($result);
274 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
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!');
286 // die() on production systems
292 return $GLOBALS['ctracker_config'][$entry];
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__);
300 // Do we have entries?
301 $found = (mysql_num_rows($result) == 1);
304 if ($found === true) {
306 $GLOBALS['ctracker_last_suspicious_entry'] = mysql_fetch_array($result);
310 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
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__);
321 // Do we have a ticket?
322 $found = (mysql_num_rows($result) == 1);
325 if ($found === true) {
326 // Cache the ticket data
327 $GLOBALS['ctracker_last_ticket'] = mysql_fetch_array($result);
331 mysql_free_result($result) or crackerTrackerDatabaseError(__FUNCTION__, __LINE__);
337 // Adds a ticket based on given (mostly $_POST) data
338 function addCrackerTrackerTicket (array $data) {
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'])
349 crackerTrackerInsertArray('ctracker_ticket', $GLOBALS['ctracker_last_ticket']);
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
355 'ctracker_ticket_id' => $GLOBALS['ctracker_last_insert_id'],
356 'ctracker_data_id' => $GLOBALS['ctracker_last_suspicious_entry']['id']
359 // And insert it as well
360 crackerTrackerInsertArray('ctracker_ticket_data', $data);
362 // Add ticket id again
363 $GLOBALS['ctracker_ticket'] = $data['ctracker_ticket_id'];
365 // Merge all data for emails
366 $GLOBALS['ctracker_last_ticket'] = array_merge($GLOBALS['ctracker_last_ticket'], $data);
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');