function _wobi_addWebseedfiles($torrent_file_path, $relative_path, $httplocation, $hash) { $prefix = WOBI_PREFIX; $fd = fopen($torrent_file_path, "rb") or die(errorMessage() . "File upload error 1</p>"); $alltorrent = fread($fd, filesize($torrent_file_path)); fclose($fd); $array = BDecode($alltorrent); // Add in Bittornado HTTP seeding spec // //add information into database $info = $array["info"] or die("Invalid torrent file."); $fsbase = $relative_path; // We need single file only! mysql_query("INSERT INTO " . $prefix . "webseedfiles (info_hash,filename,startpiece,endpiece,startpieceoffset,fileorder) values (\"{$hash}\", \"" . mysql_real_escape_string($fsbase) . "\", 0, " . (strlen($array["info"]["pieces"]) / 20 - 1) . ", 0, 0)"); // Edit torrent file // $data_array = $array; $data_array["httpseeds"][0] = WOBI_URL . "/seed.php"; //$data_array["url-list"][0] = $httplocation; $to_write = BEncode($data_array); //write torrent file $write_httpseed = fopen($torrent_file_path, "wb"); fwrite($write_httpseed, $to_write); fclose($write_httpseed); //add in piecelength and number of pieces $query = "UPDATE " . $prefix . "summary SET piecelength=\"" . $info["piece length"] . "\", numpieces=\"" . strlen($array["info"]["pieces"]) / 20 . "\" WHERE info_hash=\"" . $hash . "\""; quickQuery($query); }
function send_pm($sender, $recepient, $subject, $msg) { global $FORUMLINK, $TABLE_PREFIX, $db_prefix, $CACHE_DURATION, $ipb_prefix; if ($FORUMLINK == "ipb") { ipb_send_pm($sender, $recepient, $subject, $msg); } elseif (substr($FORUMLINK, 0, 3) == 'smf') { # smf forum # get smf_fid of recepient $recepient = get_result('SELECT smf_fid FROM ' . $TABLE_PREFIX . 'users WHERE id=' . $recepient . ' LIMIT 1;', true, $CACHE_DURATION); if (!isset($recepient[0])) { return false; } # valid user $recepient = $recepient[0]['smf_fid']; if ($recepient == 0) { return false; } # valid smf_fid # get smf_fid of sender # if sender id is invalid or 0, use System $sender = $sender == 0 ? 0 : get_result('SELECT smf_fid, username FROM ' . $TABLE_PREFIX . 'users WHERE id=' . $sender . ' LIMIT 1;', true, $CACHE_DURATION); if (!isset($sender[0])) { $sender = array(); $sender['smf_fid'] = 0; $sender['username'] = '******'; } else { $sender = $sender[0]; } # insert message quickQuery("INSERT INTO `{$db_prefix}personal_messages` (" . ($FORUMLINK == "smf" ? "`ID_MEMBER_FROM`, `fromName`" : "`id_member_from`, `from_name`") . ", `msgtime`, `subject`, `body`) VALUES (" . $sender['smf_fid'] . ", " . sqlesc($sender['username']) . ", UNIX_TIMESTAMP(), " . $subject . ", " . $msg . ")"); # get id of message $pm_id = is_null($___mysqli_res = mysqli_insert_id($GLOBALS["___mysqli_ston"])) ? false : $___mysqli_res; # insert recepient for message quickQuery("INSERT INTO `{$db_prefix}pm_recipients` (" . ($FORUMLINK == "smf" ? "`ID_PM`, `ID_MEMBER`" : "`id_pm`, `id_member`") . ") VALUES (" . $pm_id . ", " . $recepient . ")"); # notify recepient if ($FORUMLINK == "smf") { quickQuery("UPDATE `{$db_prefix}members` SET `instantMessages`=`instantMessages`+1, `unreadMessages`=`unreadMessages`+1 WHERE `ID_MEMBER`=" . $recepient . " LIMIT 1"); } else { quickQuery("UPDATE `{$db_prefix}members` SET `instant_messages`=`instant_messages`+1, `unread_messages`=`unread_messages`+1 WHERE `id_member`=" . $recepient . " LIMIT 1"); } return true; } else { # internal PM system # insert pm quickQuery('INSERT INTO ' . $TABLE_PREFIX . 'messages (sender, receiver, added, subject, msg) VALUES (' . $sender . ', ' . $recepient . ', UNIX_TIMESTAMP(), ' . $subject . ', ' . $msg . ')'); return true; } return false; }
/** * (Static) Method to trim the action log (from over 500 back to 250 entries) */ function trimLog() { static $checked = 0; // only check once per run if ($checked) { return; } // trim $checked = 1; $iTotal = quickQuery('SELECT COUNT(*) AS result FROM ' . sql_table('actionlog')); // if size > 500, drop back to about 250 $iMaxSize = 500; $iDropSize = 250; if ($iTotal > $iMaxSize) { $tsChop = quickQuery('SELECT timestamp as result FROM ' . sql_table('actionlog') . ' ORDER BY timestamp DESC LIMIT ' . $iDropSize . ',1'); sql_query('DELETE FROM ' . sql_table('actionlog') . ' WHERE timestamp < \'' . $tsChop . '\''); } }
function send_pm($sender, $recepient, $subject, $msg) { global $FORUMLINK, $TABLE_PREFIX, $db_prefix, $CACHE_DURATION; if ($FORUMLINK == 'smf') { # smf forum # get smf_fid of recepient $recepient = get_result('SELECT smf_fid FROM ' . $TABLE_PREFIX . 'users WHERE id=' . $recepient . ' LIMIT 1;', true, $CACHE_DURATION); if (!isset($recepient[0])) { return false; } # valid user $recepient = $recepient[0]['smf_fid']; if ($recepient == 0) { return false; } # valid smf_fid # get smf_fid of sender # if sender id is invalid or 0, use System $sender = $sender == 0 ? 0 : get_result('SELECT smf_fid, username FROM ' . $TABLE_PREFIX . 'users WHERE id=' . $sender . ' LIMIT 1;', true, $CACHE_DURATION); if (!isset($sender[0])) { $sender = array(); $sender['smf_fid'] = 0; $sender['username'] = '******'; } else { $sender = $sender[0]; } # insert message quickQuery('INSERT INTO ' . $db_prefix . 'personal_messages (ID_MEMBER_FROM, fromName, msgtime, subject, body) VALUES (' . $sender['smf_fid'] . ', ' . sqlesc($sender['username']) . ', UNIX_TIMESTAMP(), ' . $subject . ', ' . $msg . ');'); # get id of message $pm_id = mysql_insert_id(); # insert recepient for message quickQuery('INSERT INTO ' . $db_prefix . 'pm_recipients (ID_PM, ID_MEMBER) VALUES (' . $pm_id . ', ' . $recepient . ');'); # notify recepient quickQuery('UPDATE ' . $db_prefix . 'members SET instantMessages=instantMessages+1, unreadMessages=unreadMessages+1 WHERE ID_MEMBER=' . $recepient . ' LIMIT 1;'); return true; } else { # internal PM system # insert pm quickQuery('INSERT INTO ' . $TABLE_PREFIX . 'messages (sender, receiver, added, subject, msg) VALUES (' . $sender . ', ' . $recepient . ', UNIX_TIMESTAMP(), ' . $subject . ', ' . $msg . ')'); return true; } return false; }
/** * @todo document this */ function deleteOnePlugin($pid, $callUninstall = 0) { global $manager; $pid = intval($pid); if (!$manager->pidInstalled($pid)) { return _ERROR_NOSUCHPLUGIN; } $name = quickQuery('SELECT pfile as result FROM ' . sql_table('plugin') . ' WHERE pid=' . $pid); /* // call the unInstall method of the plugin if ($callUninstall) { $plugin =& $manager->getPlugin($name); if ($plugin) $plugin->unInstall(); }*/ // check dependency before delete $res = sql_query('SELECT pfile FROM ' . sql_table('plugin')); while ($o = sql_fetch_object($res)) { $plug =& $manager->getPlugin($o->pfile); if ($plug) { $depList = $plug->getPluginDep(); foreach ($depList as $depName) { if ($name == $depName) { return sprintf(_ERROR_DELREQPLUGIN, $o->pfile); } } } } $manager->notify('PreDeletePlugin', array('plugid' => $pid)); // call the unInstall method of the plugin if ($callUninstall) { $plugin =& $manager->getPlugin($name); if ($plugin) { $plugin->unInstall(); } } // delete all subscriptions sql_query('DELETE FROM ' . sql_table('plugin_event') . ' WHERE pid=' . $pid); // delete all options // get OIDs from plugin_option_desc $res = sql_query('SELECT oid FROM ' . sql_table('plugin_option_desc') . ' WHERE opid=' . $pid); $aOIDs = array(); while ($o = sql_fetch_object($res)) { array_push($aOIDs, $o->oid); } // delete from plugin_option and plugin_option_desc sql_query('DELETE FROM ' . sql_table('plugin_option_desc') . ' WHERE opid=' . $pid); if (count($aOIDs) > 0) { sql_query('DELETE FROM ' . sql_table('plugin_option') . ' WHERE oid in (' . implode(',', $aOIDs) . ')'); } // update order numbers $res = sql_query('SELECT porder FROM ' . sql_table('plugin') . ' WHERE pid=' . $pid); $o = sql_fetch_object($res); sql_query('UPDATE ' . sql_table('plugin') . ' SET porder=(porder - 1) WHERE porder>' . $o->porder); // delete row sql_query('DELETE FROM ' . sql_table('plugin') . ' WHERE pid=' . $pid); $manager->clearCachedInfo('installedPlugins'); $manager->notify('PostDeletePlugin', array('plugid' => $pid)); return ''; }
function setOptionData($newText, $order, $optionId) { $newText = isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"]) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $newText) : (trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR) ? "" : ""); quickQuery("UPDATE {$this->table_prefix}poller_option set optionText='" . $newText . "',pollerOrder='{$order}' where ID='" . $optionId . "'"); }
function doInstall() { global $mysql_usePrefix, $mysql_prefix, $weblog_ping; // 0. put all POST-vars into vars $mysql_host = postVar('mySQL_host'); $mysql_user = postVar('mySQL_user'); $mysql_password = postVar('mySQL_password'); $mysql_database = postVar('mySQL_database'); $mysql_create = postVar('mySQL_create'); $mysql_usePrefix = postVar('mySQL_usePrefix'); $mysql_prefix = postVar('mySQL_tablePrefix'); $config_indexurl = postVar('IndexURL'); $config_adminurl = postVar('AdminURL'); $config_adminpath = postVar('AdminPath'); $config_mediaurl = postVar('MediaURL'); $config_skinsurl = postVar('SkinsURL'); $config_pluginurl = postVar('PluginURL'); $config_actionurl = postVar('ActionURL'); $config_mediapath = postVar('MediaPath'); $config_skinspath = postVar('SkinsPath'); $user_name = postVar('User_name'); $user_realname = postVar('User_realname'); $user_password = postVar('User_password'); $user_password2 = postVar('User_password2'); $user_email = postVar('User_email'); $blog_name = postVar('Blog_name'); $blog_shortname = postVar('Blog_shortname'); $charset = postVar('charset'); $config_adminemail = $user_email; $config_sitename = $blog_name; $weblog_ping = postVar('Weblog_ping'); $_POST = array(); $config_indexurl = replaceDoubleBackslash($config_indexurl); $config_adminurl = replaceDoubleBackslash($config_adminurl); $config_mediaurl = replaceDoubleBackslash($config_mediaurl); $config_skinsurl = replaceDoubleBackslash($config_skinsurl); $config_pluginurl = replaceDoubleBackslash($config_pluginurl); $config_actionurl = replaceDoubleBackslash($config_actionurl); $config_adminpath = replaceDoubleBackslash($config_adminpath); $config_skinspath = replaceDoubleBackslash($config_skinspath); $config_mediapath = replaceDoubleBackslash($config_mediapath); /** * Include and initialize multibyte functions as a replacement for mbstring extension * if mbstring extension is not loaded. * Jan.28, 2011. Japanese Package Release Team */ if (!function_exists('mb_convert_encoding')) { global $mbemu_internals; include_once $config_adminpath . 'libs/mb_emulator/mb-emulator.php'; } if (function_exists('date_default_timezone_set')) { @date_default_timezone_set(function_exists('date_default_timezone_get') ? @date_default_timezone_get() : 'UTC'); } if ($charset == 'ujis') { define('_CHARSET', 'EUC-JP'); $config_sitename = mb_convert_encoding($config_sitename, _CHARSET, 'UTF-8'); $user_realname = mb_convert_encoding($user_realname, _CHARSET, 'UTF-8'); $blog_name = mb_convert_encoding($blog_name, _CHARSET, 'UTF-8'); } else { define('_CHARSET', 'UTF-8'); } // 1. check all the data $errors = array(); if (!$mysql_database) { array_push($errors, _ERROR2); } if ($mysql_usePrefix == 1 && strlen($mysql_prefix) == 0) { array_push($errors, _ERROR3); } if ($mysql_usePrefix == 1 && !preg_match('#^[a-zA-Z0-9_]+$#', $mysql_prefix)) { array_push($errors, _ERROR4); } // TODO: add action.php check if (!endsWithSlash($config_indexurl) || !endsWithSlash($config_adminurl) || !endsWithSlash($config_mediaurl) || !endsWithSlash($config_pluginurl) || !endsWithSlash($config_skinsurl)) { array_push($errors, _ERROR5); } if (!endsWithSlash($config_adminpath)) { array_push($errors, _ERROR6); } if (!endsWithSlash($config_mediapath)) { array_push($errors, _ERROR7); } if (!endsWithSlash($config_skinspath)) { array_push($errors, _ERROR8); } if (!is_dir($config_adminpath)) { array_push($errors, _ERROR9); } if (!_isValidMailAddress($user_email)) { array_push($errors, _ERROR10); } if (!_isValidDisplayName($user_name)) { array_push($errors, _ERROR11); } if (!$user_password || !$user_password2) { array_push($errors, _ERROR12); } if ($user_password != $user_password2) { array_push($errors, _ERROR13); } if (!_isValidShortName($blog_shortname)) { array_push($errors, _ERROR14); } if (sizeof($errors) > 0) { showErrorMessages($errors); } // 2. try to log in to mySQL global $MYSQL_CONN; // this will need to be changed if we ever allow $MYSQL_CONN = @sql_connect_args($mysql_host, $mysql_user, $mysql_password); if ($MYSQL_CONN == false) { _doError(_ERROR15 . ': ' . sql_error()); } // 3. try to create database (if needed) $mySqlVer = implode('.', array_map('intval', explode('.', sql_get_server_info()))); $collation = $charset == 'utf8' ? 'utf8_general_ci' : 'ujis_japanese_ci'; if ($mysql_create == 1) { $sql = 'CREATE DATABASE ' . $mysql_database; // <add for garble measure> if (version_compare($mySqlVer, '4.1.0', '>=')) { $sql .= ' DEFAULT CHARACTER SET ' . $charset . ' COLLATE ' . $collation; } // </add for garble measure>*/ sql_query($sql, $MYSQL_CONN) or _doError(_ERROR16 . ': ' . sql_error($MYSQL_CONN)); } // 4. try to select database sql_select_db($mysql_database, $MYSQL_CONN) or _doError(_ERROR17); /* * 4.5. set character set to this database in MySQL server * This processing is added by Nucleus CMS Japanese Package Release Team as of Mar.30, 2011 */ sql_set_charset_jp($charset); // 5. execute queries $filename = 'install.sql'; $fd = fopen($filename, 'r'); $queries = fread($fd, filesize($filename)); fclose($fd); $queries = split("(;\n|;\r)", $queries); $aTableNames = array('nucleus_actionlog', 'nucleus_ban', 'nucleus_blog', 'nucleus_category', 'nucleus_comment', 'nucleus_config', 'nucleus_item', 'nucleus_karma', 'nucleus_member', 'nucleus_plugin', 'nucleus_skin', 'nucleus_template', 'nucleus_team', 'nucleus_activation', 'nucleus_tickets'); // these are unneeded (one of the replacements above takes care of them) // 'nucleus_plugin_event', // 'nucleus_plugin_option', // 'nucleus_plugin_option_desc', // 'nucleus_skin_desc', // 'nucleus_template_desc', $aTableNamesPrefixed = array($mysql_prefix . 'nucleus_actionlog', $mysql_prefix . 'nucleus_ban', $mysql_prefix . 'nucleus_blog', $mysql_prefix . 'nucleus_category', $mysql_prefix . 'nucleus_comment', $mysql_prefix . 'nucleus_config', $mysql_prefix . 'nucleus_item', $mysql_prefix . 'nucleus_karma', $mysql_prefix . 'nucleus_member', $mysql_prefix . 'nucleus_plugin', $mysql_prefix . 'nucleus_skin', $mysql_prefix . 'nucleus_template', $mysql_prefix . 'nucleus_team', $mysql_prefix . 'nucleus_activation', $mysql_prefix . 'nucleus_tickets'); // these are unneeded (one of the replacements above takes care of them) // $mysql_prefix . 'nucleus_plugin_event', // $mysql_prefix . 'nucleus_plugin_option', // $mysql_prefix . 'nucleus_plugin_option_desc', // $mysql_prefix . 'nucleus_skin_desc', // $mysql_prefix . 'nucleus_template_desc', $count = count($queries); for ($idx = 0; $idx < $count; $idx++) { $query = trim($queries[$idx]); // echo "QUERY = " . htmlspecialchars($query) . "<p>"; if ($query) { if ($mysql_usePrefix == 1) { $query = str_replace($aTableNames, $aTableNamesPrefixed, $query); } // <add for garble measure> if ($mysql_create != 1 && strpos($query, 'CREATE TABLE') === 0 && version_compare($mySqlVer, '4.1.0', '>=')) { $query .= ' DEFAULT CHARACTER SET ' . $charset . ' COLLATE ' . $collation; } // </add for garble measure>*/ sql_query($query, $MYSQL_CONN) or _doError(_ERROR30 . ' (' . htmlspecialchars($query) . '): ' . sql_error($MYSQL_CONN)); } } // 5a make first post if (strtoupper(_CHARSET) != 'UTF-8') { $itm_title = mb_convert_encoding(_1ST_POST_TITLE, _CHARSET, 'UTF-8'); $itm_body = mb_convert_encoding(_1ST_POST, _CHARSET, 'UTF-8'); $itm_more = mb_convert_encoding(_1ST_POST2, _CHARSET, 'UTF-8'); } else { $itm_title = _1ST_POST_TITLE; $itm_body = _1ST_POST; $itm_more = _1ST_POST2; } $newpost = "INSERT INTO " . tableName('nucleus_item') . " VALUES (" . "1, " . "'" . $itm_title . "'," . " '" . $itm_body . "'," . " '" . $itm_more . "'," . " 1, 1, '2005-08-15 11:04:26', 0, 0, 0, 1, 0, 1);"; sql_query($newpost, $MYSQL_CONN) or _doError(_ERROR18 . ' (' . htmlspecialchars($newpost) . '): ' . sql_error($MYSQL_CONN)); // 6. update global settings updateConfig('IndexURL', $config_indexurl); updateConfig('AdminURL', $config_adminurl); updateConfig('MediaURL', $config_mediaurl); updateConfig('SkinsURL', $config_skinsurl); updateConfig('PluginURL', $config_pluginurl); updateConfig('ActionURL', $config_actionurl); updateConfig('AdminEmail', $config_adminemail); updateConfig('SiteName', $config_sitename); if ($charset == 'ujis') { updateConfig('Language', 'japanese-euc'); } // 7. update GOD member $query = 'UPDATE ' . tableName('nucleus_member') . " SET mname\t = '" . addslashes($user_name) . "'," . " mrealname\t = '" . addslashes($user_realname) . "'," . " mpassword\t = '" . md5(addslashes($user_password)) . "'," . " murl\t\t = '" . addslashes($config_indexurl) . "'," . " memail\t\t= '" . addslashes($user_email) . "'," . " madmin\t\t= 1," . " mcanlogin\t = 1" . " WHERE" . " mnumber\t = 1"; sql_query($query, $MYSQL_CONN) or _doError(_ERROR19 . ': ' . sql_error($MYSQL_CONN)); // 8. update weblog settings $query = 'UPDATE ' . tableName('nucleus_blog') . " SET bname = '" . addslashes($blog_name) . "'," . " bshortname = '" . addslashes($blog_shortname) . "'," . " burl\t = '" . addslashes($config_indexurl) . "'" . " WHERE" . " bnumber\t= 1"; sql_query($query, $MYSQL_CONN) or _doError(_ERROR20 . ': ' . sql_error($MYSQL_CONN)); // 8-2. update category settings if (strtoupper(_CHARSET) != 'UTF-8') { $cat_name = mb_convert_encoding(_GENERALCAT_NAME, _CHARSET, 'UTF-8'); $cat_desc = mb_convert_encoding(_GENERALCAT_DESC, _CHARSET, 'UTF-8'); } else { $cat_name = _GENERALCAT_NAME; $cat_desc = _GENERALCAT_DESC; } $query = 'UPDATE ' . tableName('nucleus_category') . " SET cname = '" . $cat_name . "'," . " cdesc\t = '" . $cat_desc . "'" . " WHERE" . " catid\t = 1"; sql_query($query, $MYSQL_CONN) or _doError(_ERROR20 . ': ' . sql_error($MYSQL_CONN)); // 9. update item date $query = 'UPDATE ' . tableName('nucleus_item') . " SET itime = '" . date('Y-m-d H:i:s', time()) . "'" . " WHERE inumber = 1"; sql_query($query, $MYSQL_CONN) or _doError(_ERROR21 . ': ' . sql_error($MYSQL_CONN)); global $aConfPlugsToInstall, $aConfSkinsToImport; $aSkinErrors = array(); $aPlugErrors = array(); if (count($aConfPlugsToInstall) > 0 || count($aConfSkinsToImport) > 0) { // 10. set global variables global $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_PREFIX; $MYSQL_HOST = $mysql_host; $MYSQL_USER = $mysql_user; $MYSQL_PASSWORD = $mysql_password; $MYSQL_DATABASE = $mysql_database; $MYSQL_PREFIX = $mysql_usePrefix == 1 ? $mysql_prefix : ''; global $DIR_NUCLEUS, $DIR_MEDIA, $DIR_SKINS, $DIR_PLUGINS, $DIR_LANG, $DIR_LIBS; $DIR_NUCLEUS = $config_adminpath; $DIR_MEDIA = $config_mediapath; $DIR_SKINS = $config_skinspath; $DIR_PLUGINS = $DIR_NUCLEUS . 'plugins/'; $DIR_LANG = $DIR_NUCLEUS . 'language/'; $DIR_LIBS = $DIR_NUCLEUS . 'libs/'; // close database connection (needs to be closed if we want to include globalfunctions.php) sql_close($MYSQL_CONN); $manager = ''; include_once $DIR_LIBS . 'globalfunctions.php'; // 11. install custom skins $aSkinErrors = installCustomSkins($manager); $defskinQue = 'SELECT `sdnumber` as result FROM ' . sql_table('skin_desc') . ' WHERE `sdname` = "default"'; $defSkinID = quickQuery($defskinQue); $updateQuery = 'UPDATE ' . sql_table('blog') . ' SET `bdefskin` = ' . intval($defSkinID) . ' WHERE `bnumber` = 1'; sql_query($updateQuery); $updateQuery = 'UPDATE ' . sql_table('config') . ' SET `value` = ' . intval($defSkinID) . ' WHERE `name` = "BaseSkin"'; sql_query($updateQuery); // 12. install NP_Ping, if decided if ($weblog_ping == 1) { global $aConfPlugsToInstall; array_push($aConfPlugsToInstall, "NP_Ping"); } // 13. install custom plugins $aPlugErrors = installCustomPlugs($manager); } // 14. Write config file ourselves (if possible) $bConfigWritten = 0; if (@file_exists('../config.php') && is_writable('../config.php') && ($fp = @fopen('../config.php', 'w'))) { $config_data = '<' . '?php' . "\n\n"; //$config_data .= "\n"; (extraneous, just added extra \n to previous line $config_data .= " // mySQL connection information\n"; $config_data .= " \$MYSQL_HOST\t = '" . $mysql_host . "';\n"; $config_data .= " \$MYSQL_USER\t = '" . $mysql_user . "';\n"; $config_data .= " \$MYSQL_PASSWORD = '******';\n"; $config_data .= " \$MYSQL_DATABASE = '" . $mysql_database . "';\n"; $config_data .= " \$MYSQL_PREFIX = '" . ($mysql_usePrefix == 1 ? $mysql_prefix : '') . "';\n"; $config_data .= " // new in 3.50. first element is db handler, the second is the db driver used by the handler\n"; $config_data .= " // default is \$MYSQL_HANDLER = array('mysql','');\n"; $config_data .= " //\$MYSQL_HANDLER = array('mysql','mysql');\n"; $config_data .= " //\$MYSQL_HANDLER = array('pdo','mysql');\n"; $config_data .= " \$MYSQL_HANDLER = array('" . $MYSQL_HANDLER[0] . "','" . $MYSQL_HANDLER[1] . "');\n"; $config_data .= "\n"; $config_data .= " // main nucleus directory\n"; $config_data .= " \$DIR_NUCLEUS = '" . $config_adminpath . "';\n"; $config_data .= "\n"; $config_data .= " // path to media dir\n"; $config_data .= " \$DIR_MEDIA = '" . $config_mediapath . "';\n"; $config_data .= "\n"; $config_data .= " // extra skin files for imported skins\n"; $config_data .= " \$DIR_SKINS = '" . $config_skinspath . "';\n"; $config_data .= "\n"; $config_data .= " // these dirs are normally sub dirs of the nucleus dir, but \n"; $config_data .= " // you can redefine them if you wish\n"; $config_data .= " \$DIR_PLUGINS = \$DIR_NUCLEUS . 'plugins/';\n"; $config_data .= " \$DIR_LANG\t= \$DIR_NUCLEUS . 'language/';\n"; $config_data .= " \$DIR_LIBS\t= \$DIR_NUCLEUS . 'libs/';\n"; $config_data .= "\n"; $config_data .= " // include libs\n"; $config_data .= " include(\$DIR_LIBS . 'globalfunctions.php');\n"; $config_data .= "?" . ">"; $result = @fputs($fp, $config_data, strlen($config_data)); fclose($fp); if ($result) { $bConfigWritten = 1; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo _TITLE; ?> </title> <style>@import url('../nucleus/styles/manual.css');</style> </head> <body> <div style="text-align:center"><img src="../nucleus/styles/logo.gif" alt="<?php echo _ALT_NUCLEUS_CMS_LOGO; ?> " /></div> <!-- Nucleus logo --> <?php $aAllErrors = array_merge($aSkinErrors, $aPlugErrors); if (count($aAllErrors) > 0) { echo '<h1>' . _TITLE2 . '</h1>'; echo '<ul><li>' . implode('</li><li>', $aAllErrors) . '</li></ul>'; } if (!$bConfigWritten) { ?> <h1><?php echo _TITLE3; ?> </h1> <?php echo _TEXT10; ?> <pre><code><?php // mySQL connection information $MYSQL_HOST = '<b><?php echo $mysql_host; ?> </b>'; $MYSQL_USER = '******'; $MYSQL_PASSWORD = '******'; $MYSQL_DATABASE = '<b><?php echo $mysql_database; ?> </b>'; $MYSQL_PREFIX = '<b><?php echo $mysql_usePrefix == 1 ? $mysql_prefix : ''; ?> </b>'; // new in 3.50. first element is db handler, the second is the db driver used by the handler // default is $MYSQL_HANDLER = array('mysql',''); $MYSQL_HANDLER = array('<?php echo $MYSQL_HANDLER[0]; ?> ','<?php echo $MYSQL_HANDLER[1]; ?> '); // main nucleus directory $DIR_NUCLEUS = '<b><?php echo $config_adminpath; ?> </b>'; // path to media dir $DIR_MEDIA = '<b><?php echo $config_mediapath; ?> </b>'; // extra skin files for imported skins $DIR_SKINS = '<b><?php echo $config_skinspath; ?> </b>'; // these dirs are normally sub dirs of the nucleus dir, but // you can redefine them if you wish $DIR_PLUGINS = $DIR_NUCLEUS . 'plugins/'; $DIR_LANG = $DIR_NUCLEUS . 'language/'; $DIR_LIBS = $DIR_NUCLEUS . 'libs/'; // include libs include($DIR_LIBS . 'globalfunctions.php'); ?></code></pre> <?php echo _TEXT11; ?> <div class="note"> <?php echo _TEXT12; ?> </div> <?php } else { ?> <h1><?php echo _TITLE4; ?> </h1> <?php echo _TEXT13; ?> <?php } ?> <h1><?php echo _TITLE5; ?> </h1> <?php echo _TEXT14; ?> <ul> <li><?php echo _TEXT14_L1; ?> </li> <li><?php echo _TEXT14_L2; ?> </li> </ul> <h1><?php echo _HEADER10; ?> </h1> <?php echo _TEXT15; ?> <ul> <li><?php echo _TEXT15_L1; ?> </li> <li><?php echo _TEXT15_L2; ?> </li> <li><?php echo _TEXT15_L3; ?> </li> </ul> <?php echo _TEXT16; ?> <h1><?php echo _HEADER11; ?> </h1> <p><?php echo _TEXT16_H; ?> <ul> <li><a href="<?php echo $config_adminurl; ?> "><?php echo _TEXT16_L1; ?> </a></li> <li><a href="<?php echo $config_indexurl; ?> "><?php echo _TEXT16_L2; ?> </a></li> </ul> </p> </body> </html> <?php }
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //////////////////////////////////////////////////////////////////////////////////// if (!defined("IN_BTIT")) { die("non direct access!"); } require_once "include/functions.php"; dbconn(false); global $CURUSER, $btit_settings, $XBTT_USE; $id = $_GET["uid"]; if (!$id) { stderr("Error", "Bad ID!"); } if ($CURUSER["uid"] == $id) { $timeout = time() - intval($GLOBALS["report_interval"] + $btit_settings["ghost"]); $flush = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT pid FROM {$TABLE_PREFIX}users WHERE id ='" . $CURUSER["uid"] . "'"); $update = mysqli_fetch_row($flush); if ($XBTT_USE) { quickQuery("UPDATE `xbt_files_users` SET `active`=0 WHERE `mtime` < " . $timeout . " AND `uid`=" . $CURUSER["uid"]); } else { quickQuery("DELETE FROM {$TABLE_PREFIX}peers where lastupdate < " . $timeout . " AND pid=" . $update["pid"]); } information_msg("Success", "Your Ghost Peers Are Flushed!"); }
function userlogin() { global $CURUSER, $TABLE_PREFIX, $err_msg_install, $btit_settings, $update_interval, $THIS_BASEPATH, $STYLEPATH, $STYLEURL, $STYLETYPE, $BASEURL, $USERLANG; unset($GLOBALS['CURUSER']); session_name("xbtit"); session_start(); $ip = getip(); //$_SERVER["REMOTE_ADDR"]; $nip = ip2long($ip); $res = get_result("SELECT * FROM {$TABLE_PREFIX}bannedip WHERE INET_ATON('" . $ip . "') >= first AND INET_ATON('" . $ip . "') <= last LIMIT 1;", true, $btit_settings['cache_duration']); if (count($res) > 0) { header('HTTP/1.0 403 Forbidden'); ?> <html><body><h1>403 Forbidden</h1>Unauthorized IP address.</body></html> <?php die; } if (isset($_SESSION["CURUSER"]) && isset($_SESSION["CURUSER_EXPIRE"])) { if ($_SESSION["CURUSER_EXPIRE"] > time()) { if (!isset($STYLEPATH) || empty($STYLEPATH)) { $STYLEPATH = is_null($_SESSION["CURUSER"]["style_path"]) ? $THIS_BASEPATH . "/style/xbtit_default" : $_SESSION["CURUSER"]["style_path"]; } if (!isset($STYLEURL) || empty($STYLEURL)) { $STYLEURL = is_null($_SESSION["CURUSER"]["style_url"]) ? $BASEURL . "/style/xbtit_default" : $_SESSION["CURUSER"]["style_url"]; } if (!isset($STYLETYPE) || empty($STYLETYPE)) { $STYLETYPE = is_null($_SESSION["CURUSER"]["style_type"]) ? 3 : (int) 0 + $_SESSION["CURUSER"]["style_type"]; } if (!isset($USERLANG) || empty($USERLANG)) { $USERLANG = is_null($_SESSION["CURUSER"]["language_path"]) ? $THIS_BASEPATH . "/language/english" : $THIS_BASEPATH . "/" . $_SESSION["CURUSER"]["language_url"]; } $GLOBALS["CURUSER"] = $_SESSION["CURUSER"]; return; } else { unset($_SESSION["CURUSER"]); unset($_SESSION["CURUSER_EXPIRE"]); } } if ($btit_settings['xbtt_use']) { $udownloaded = "u.downloaded+IFNULL(x.downloaded,0)"; $uuploaded = "u.uploaded+IFNULL(x.uploaded,0)"; $utables = "{$TABLE_PREFIX}users u LEFT JOIN xbt_users x ON x.uid=u.id"; } else { $udownloaded = "u.downloaded"; $uuploaded = "u.uploaded"; $utables = "{$TABLE_PREFIX}users u"; } // guest if ($btit_settings["secsui_cookie_type"] == 1) { $id = isset($_COOKIE["uid"]) && is_numeric($_COOKIE["uid"]) && $_COOKIE["uid"] > 1 ? $id = (int) 0 + $_COOKIE["uid"] : ($id = 1); } elseif ($btit_settings["secsui_cookie_type"] == 2) { $user_cookie_name = isset($btit_settings["secsui_cookie_name"]) && !empty($btit_settings["secsui_cookie_name"]) ? $btit_settings["secsui_cookie_name"] : "xbtitLoginCookie"; if (isset($_COOKIE[$user_cookie_name])) { $user_cookie = unserialize($_COOKIE[$user_cookie_name]); $id = is_numeric($user_cookie["id"]) && $user_cookie["id"] > 1 ? (int) 0 + $user_cookie["id"] : ($id = 1); } else { $id = 1; } } elseif ($btit_settings["secsui_cookie_type"] == 3) { if (isset($_SESSION["login_cookie"])) { $user_cookie = unserialize($_SESSION["login_cookie"]); $id = is_numeric($user_cookie["id"]) && $user_cookie["id"] > 1 ? (int) 0 + $user_cookie["id"] : ($id = 1); } else { $id = 1; } } else { $id = 1; } //proxy $respr = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}blacklist WHERE tip =" . $nip) or sqlerr(__FILE__, __LINE__); if (mysqli_num_rows($respr) > 0 || $_SERVER["HTTP_X_FORWARDED_FOR"] || $_SERVER["HTTP_X_FORWARDED"] || $_SERVER["HTTP_FORWARDED_FOR"] || $_SERVER["HTTP_VIA"] || $_SERVER["HTTP_FORWARDED"] || $_SERVER["HTTP_FORWARDED_FOR_IP"] || $_SERVER["HTTP_PROXY_CONNECTION"] || $_SERVER["VIA"] || $_SERVER["X_FORWARDED_FOR"] || $_SERVER["FORWARDED_FOR"] || $_SERVER["FORWARDED"] || $_SERVER["X_FORWARDED"] || $_SERVER["CLIENT_IP"] || $_SERVER["FORWARDED_FOR_IP"] || $_SERVER["HTTP_CLIENT_IP"] || in_array($_SERVER['REMOTE_PORT'], array(8080, 80, 6588, 8000, 3128, 553, 554))) { $proxy = 'yes'; } else { $proxy = 'no'; } quickQuery("UPDATE {$TABLE_PREFIX}users SET proxy='{$proxy}' WHERE id = {$id}") or sqlerr(__FILE__, __LINE__); //proxy if ($id > 1) { $res = do_sqlquery("SELECT u.profileview, u.team,u.commentpm,u.pchat,u.tor,u.gender,u.gotgift,u.dona,u.donb,u.birt,u.mal,u.fem,u.bann,u.war,u.par,u.bot,u.trmu,u.trmo,u.vimu,u.vimo,u.friend,u.junkie,u.staff,u.sysop, u.emailnot, u.left_l, u.pid, u.cip, u.booted,u.announce,u.userbar, u.invisible, u.showporn , u.immunity, u.dob,u.warn, u.donor,u.seedbonus, u.salt, u.pass_type, u.lip, u.cip, {$udownloaded} as downloaded, {$uuploaded} as uploaded, u.smf_fid, u.ipb_fid, u.topicsperpage, u.postsperpage,u.torrentsperpage, u.flag, u.avatar, UNIX_TIMESTAMP(u.lastconnect) AS lastconnect, UNIX_TIMESTAMP(u.joined) AS joined, u.id as uid, u.username, u.password, u.random, u.email, u.language,u.style, u.time_offset, ul.*, `s`.`style_url`, `s`.`style_type`, `l`.`language_url` FROM {$utables} INNER JOIN {$TABLE_PREFIX}users_level ul ON u.id_level=ul.id LEFT JOIN `{$TABLE_PREFIX}style` `s` ON `u`.`style`=`s`.`id` LEFT JOIN `{$TABLE_PREFIX}language` `l` ON `u`.`language`=`l`.`id` WHERE u.id = {$id} LIMIT 1;", true); $row = mysqli_fetch_assoc($res); if ($btit_settings["secsui_cookie_type"] == 1) { if (md5($row["random"] . $row["password"] . $row["random"]) != $_COOKIE["pass"]) { $id = 1; } } elseif ($btit_settings["secsui_cookie_type"] == 2 || $btit_settings["secsui_cookie_type"] == 3) { $cookie_items = explode(",", $btit_settings["secsui_cookie_items"]); $cookie_string = ""; foreach ($cookie_items as $ci_value) { $ci_exp = explode("-", $ci_value); if ($ci_exp[0] == 8) { $ci_exp2 = explode("[+]", $ci_exp[1]); if ($ci_exp2[0] == 1) { $ip_parts = explode(".", getip()); if ($ci_exp2[1] == 1) { $cookie_string .= $ip_parts[0] . "-"; } if ($ci_exp2[1] == 2) { $cookie_string .= $ip_parts[1] . "-"; } if ($ci_exp2[1] == 3) { $cookie_string .= $ip_parts[2] . "-"; } if ($ci_exp2[1] == 4) { $cookie_string .= $ip_parts[3] . "-"; } if ($ci_exp2[1] == 5) { $cookie_string .= $ip_parts[0] . "." . $ip_parts[1] . "-"; } if ($ci_exp2[1] == 6) { $cookie_string .= $ip_parts[1] . "." . $ip_parts[2] . "-"; } if ($ci_exp2[1] == 7) { $cookie_string .= $ip_parts[2] . "." . $ip_parts[3] . "-"; } if ($ci_exp2[1] == 8) { $cookie_string .= $ip_parts[0] . "." . $ip_parts[2] . "-"; } if ($ci_exp2[1] == 9) { $cookie_string .= $ip_parts[0] . "." . $ip_parts[3] . "-"; } if ($ci_exp2[1] == 10) { $cookie_string .= $ip_parts[1] . "." . $ip_parts[3] . "-"; } if ($ci_exp2[1] == 11) { $cookie_string .= $ip_parts[0] . "." . $ip_parts[1] . "." . $ip_parts[2] . "-"; } if ($ci_exp2[1] == 12) { $cookie_string .= $ip_parts[1] . "." . $ip_parts[2] . "." . $ip_parts[3] . "-"; } if ($ci_exp2[1] == 13) { $cookie_string .= $ip_parts[0] . "." . $ip_parts[1] . "." . $ip_parts[2] . "." . $ip_parts[3] . "-"; } unset($ci_exp2); } } else { if ($ci_exp[0] == 1 && $ci_exp[1] == 1) { $cookie_string .= $row["uid"] . "-"; } if ($ci_exp[0] == 2 && $ci_exp[1] == 1) { $cookie_string .= $row["password"] . "-"; } if ($ci_exp[0] == 3 && $ci_exp[1] == 1) { $cookie_string .= $row["random"] . "-"; } if ($ci_exp[0] == 4 && $ci_exp[1] == 1) { $cookie_string .= strtolower($row["username"]) . "-"; } if ($ci_exp[0] == 5 && $ci_exp[1] == 1) { $cookie_string .= $row["salt"] . "-"; } if ($ci_exp[0] == 6 && $ci_exp[1] == 1) { $cookie_string .= $_SERVER["HTTP_USER_AGENT"] . "-"; } if ($ci_exp[0] == 7 && $ci_exp[1] == 1) { $cookie_string .= $_SERVER["HTTP_ACCEPT_LANGUAGE"] . "-"; } } unset($ci_exp); } $final_cookie["hash"] = sha1(trim($cookie_string, "-")); if ($final_cookie["hash"] != $user_cookie["hash"]) { $id = 1; } } } if ($id == 1) { $res = do_sqlquery("SELECT u.profileview, u.team,u.commentpm,u.pchat,u.tor,u.gender,u.gotgift,u.emailnot, u.dona,u.donb,u.birt,u.mal,u.fem,u.bann,u.war,u.par,u.bot,u.trmu,u.trmo,u.vimu,u.vimo,u.friend,u.junkie,u.staff,u.sysop, u.left_l, u.pid, u.cip,u.booted,u.announce,u.userbar, u.invisible, u.showporn , u.immunity, u.dob, u.warn, u.donor,u.seedbonus, u.salt, u.pass_type, u.lip, u.cip, {$udownloaded} as downloaded, {$uuploaded} as uploaded, u.smf_fid, u.ipb_fid, u.topicsperpage, u.postsperpage,u.torrentsperpage, u.flag, u.avatar, UNIX_TIMESTAMP(u.lastconnect) AS lastconnect, UNIX_TIMESTAMP(u.joined) AS joined, u.id as uid, u.username, u.password, u.random, u.email, u.language,u.style, u.time_offset, ul.*, `s`.`style_url`, `s`.`style_type`, `l`.`language_url` FROM {$utables} INNER JOIN {$TABLE_PREFIX}users_level ul ON u.id_level=ul.id LEFT JOIN `{$TABLE_PREFIX}style` `s` ON `u`.`style`=`s`.`id` LEFT JOIN `{$TABLE_PREFIX}language` `l` ON `u`.`language`=`l`.`id` WHERE u.id = 1 LIMIT 1;", true); $row = mysqli_fetch_assoc($res); } // warn-ban system with acp by DT $resdt = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT ban,bandt,booted,addbooted,whybooted FROM {$TABLE_PREFIX}users WHERE id=" . $id); $rowdt = mysqli_fetch_array($resdt); if ($rowdt["bandt"] == "yes" or $rowdt["ban"] == "yes" or $rowdt["booted"] == "yes") { header('HTTP/1.0 403 Forbidden'); ?> <html><body><h1>403 Forbidden</h1>You are Banned from this site !</body></html> <?php if ($rowdt["booted"] == "yes") { echo "<br><br>The reason :" . $rowdt["whybooted"]; } echo "<br><br><font color = red>But .... we give you one more change , you can come back , and login after : " . $rowdt["addbooted"] . "</font>"; die; } else { } // warn-ban system with acp by DT // bots start $crawler = crawlerDetect($_SERVER['HTTP_USER_AGENT']); if ($crawler) { @quickQuery("INSERT INTO {$TABLE_PREFIX}bots (name,visit) VALUES ('{$crawler}',NOW())") or die(is_object($GLOBALS["___mysqli_ston"]) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)); } else { // usual visitor } // bots end // CHECK FOR INSTALLATION FOLDER WITHOUT INSTALL.ME if ($row['id_level'] == 8 && (file_exists('install.php') || file_exists('upgrade.php'))) { // only owner level $err_msg_install = '<div align="center" style="color:red; font-size:12pt; font-weight: bold;">SECURITY WARNING: Delete install.php & upgrade.php!</div>'; } elseif ($btit_settings["site_offline"] && $row["id_level"] == 8) { $err_msg_install = "<div align=\"center\" style=\"color:red; font-size:12pt; font-weight: bold;\">REMEMBER: " . $btit_settings["name"] . " is currently offline.</div>"; } else { $err_msg_install = ''; } if (!isset($STYLEPATH) || empty($STYLEPATH)) { $STYLEPATH = $THIS_BASEPATH . "/" . (is_null($row["style_url"]) ? "style/xbtit_default" : $row["style_url"]); } if (!isset($STYLEURL) || empty($STYLEURL)) { $STYLEURL = $BASEURL . "/" . (is_null($row["style_url"]) ? "style/xbtit_default" : $row["style_url"]); } if (!isset($STYLETYPE) || empty($STYLETYPE)) { $STYLETYPE = is_null($row["style_type"]) ? 3 : (int) 0 + $row["style_type"]; } if (!isset($USERLANG) || empty($USERLANG)) { $USERLANG = is_null($row["language_url"]) ? $THIS_BASEPATH . "/language/english" : $THIS_BASEPATH . "/" . $row["language_url"]; } $_SESSION["CURUSER"] = $row; $_SESSION["CURUSER"]["style_url"] = $STYLEURL; $_SESSION["CURUSER"]["style_path"] = $STYLEPATH; $_SESSION["CURUSER"]["style_type"] = $STYLETYPE; $_SESSION["CURUSER"]["language_path"] = $USERLANG; $_SESSION["CURUSER_EXPIRE"] = time() + $btit_settings["cache_duration"]; $GLOBALS["CURUSER"] = $_SESSION["CURUSER"]; mysqli_free_result($res) || is_object($res) && get_class($res) == "mysqli_result" ? true : false; unset($row); }
} } else { $total_size = $info["length"]; } //Validate torrent file, make sure everything is correct $filename = $array["info"]["name"]; $filename = mysql_escape_string($filename); $filename = clean($filename); if (strlen($hash) != 40 || !verifyHash($hash)) { echo errorMessage() . "Error: Info hash must be exactly 40 hex bytes.</p>\n"; $error_status = false; } if ($error_status == true) { $query = "INSERT INTO " . $prefix . "namemap (info_hash, filename, url, size, pubDate) VALUES (\"{$hash}\", \"{$filename}\", \"{$url}\", \"{$total_size}\", \"" . date('D, j M Y h:i:s') . "\")"; $status = makeTorrent($hash, true); quickQuery($query); if ($status == true) { //create torrent file in folder, at this point we assume it's valid if (!($handle = fopen("torrents/" . $filename . ".torrent", 'w'))) { echo errorMessage() . "Error: Can't write to file.</p>\n"; break; } //populate file with contents if (fwrite($handle, $buffer) === FALSE) { echo errorMessage() . "Error: Can't write to file.</p>\n"; break; } fclose($handle); //make torrent file readable by all chmod("torrents/" . $filename . ".torrent", 0644); echo "<p class=\"success\">Torrent was added successfully.</p>\n";
$set[] = 'helped=' . sqlesc(htmlspecialchars($helped)); } if ($helplang != $curu['helplang']) { $set[] = 'helplang=' . sqlesc(htmlspecialchars($helplang)); } $updateset = isset($set) ? implode(',', $set) : ''; $updatesetxbt = isset($xbtset) ? implode(',', $xbtset) : ''; $updatesetsmf = isset($smfset) ? implode(',', $smfset) : ''; if ($updateset != '') { if ($XBTT_USE && $updatesetxbt != '') { quickQuery('UPDATE xbt_users SET ' . $updatesetxbt . ' WHERE uid=' . $uid . ' LIMIT 1;'); } if (substr($FORUMLINK, 0, 3) == 'smf' && $updatesetsmf != '' && !is_bool($smf_fid)) { quickQuery("UPDATE `{$db_prefix}members` SET " . $updatesetsmf . " WHERE " . ($FORUMLINK == "smf" ? "`ID_MEMBER`" : "`id_member`") . "=" . $smf_fid . " LIMIT 1"); } quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET ' . $updateset . ' WHERE id=' . $uid . ' LIMIT 1;'); success_msg($language['SUCCESS'], $language['INF_CHANGED'] . $note . '<br /><a href="index.php?page=admin&user='******'uid'] . '&code=' . $CURUSER['random'] . '">' . $language['MNU_ADMINCP'] . '</a>'); write_log('Modified user <a href="' . $btit_settings['url'] . '/index.php?page=userdetails&id=' . $uid . '">' . $curu['username'] . '</a> ' . $newname . ' ( ' . count($set) . ' changes on uid ' . $uid . ' )', 'modified'); stdfoot(true, false); die; } else { stderr($language['ERROR'], $language['USER_NO_CHANGE']); } } redirect('index.php?page=admin&user='******'uid'] . '&code=' . $CURUSER['random']); break; } # set template info if ($CURUSER['id_level'] == '8') { $admintpl->set('imm', ' Immunity <input type="checkbox" name="immunity" <tag:profile.immunity /> />'); }
function RegistPath($objID, $path, $bid, $oParam, $name, $new = FALSE) { global $CONF; switch ($oParam) { case 'item': case 'member': if (preg_match('/.html$/', $path)) { $path = substr($path, 0, -5); } break; case 'blog': case 'category': case 'subcategory': break; default: return; break; } $bid = intval($bid); $objID = intval($objID); $name = rawurlencode($name); if ($new && $oParam == 'item') { $tque = 'SELECT itime as result FROM %s WHERE inumber = %d'; $itime = quickQuery(sprintf($tque, sql_table('item'), $objID)); list($y, $m, $d, $trush) = sscanf($itime, '%d-%d-%d %s'); $param['year'] = sprintf('%04d', $y); $param['month'] = sprintf('%02d', $m); $param['day'] = sprintf('%02d', $d); $dfItem = $this->getOption('customurl_dfitem'); $ikey = TEMPLATE::fill($dfItem, $param); if ($path == $ikey) { $path = $ikey . '_' . $objID; } } elseif (!$new && strlen($path) == 0) { $del_que = 'DELETE FROM %s WHERE obj_id = %d AND obj_param = "%s"'; sql_query(sprintf($del_que, _CUSTOMURL_TABLE, $objID, $oParam)); $msg = array(0, _DELETE_PATH, $name, _DELETE_MSG); return $msg; exit; } $dotslash = array('.', '/'); $path = str_replace($dotslash, '_', $path); if (!preg_match('/^[-_a-zA-Z0-9]+$/', $path)) { $msg = array(1, _INVALID_ERROR, $name, _INVALID_MSG); return $msg; exit; } $tempPath = $path; if ($oParam == 'item' || $oParam == 'member') { $tempPath .= '.html'; } $conf_que = 'SELECT obj_id FROM %s' . ' WHERE obj_name = "%s"' . ' AND obj_bid = %d' . ' AND obj_param = "%s"' . ' AND obj_id != %d'; $res = sql_query(sprintf($conf_que, _CUSTOMURL_TABLE, $tempPath, $bid, $oParam, $objID)); if ($res && sql_num_rows($res)) { $msg = array(0, _CONFLICT_ERROR, $name, _CONFLICT_MSG); $path .= '_' . $objID; } if ($oParam == 'category' && !$msg) { $conf_cat = 'SELECT obj_id FROM %s WHERE obj_name = "%s"' . ' AND obj_param = "blog"'; $res = sql_query(sprintf($conf_cat, _CUSTOMURL_TABLE, $tempPath)); if ($res && sql_num_rows($res)) { $msg = array(0, _CONFLICT_ERROR, $name, _CONFLICT_MSG); $path .= '_' . $objID; } } if ($oParam == 'blog' && !$msg) { $conf_blg = 'SELECT obj_id FROM %s WHERE obj_name = "%s"' . ' AND obj_param = "category"'; $res = sql_query(sprintf($conf_blg, _CUSTOMURL_TABLE, $tempPath)); if ($res && sql_num_rows($res)) { $msg = array(0, _CONFLICT_ERROR, $name, _CONFLICT_MSG); $path .= '_' . $objID; } } $newPath = $path; if ($oParam == 'item' || $oParam == 'member') { $newPath .= '.html'; } $query = 'SELECT * FROM %s WHERE obj_id = %d AND obj_param = "%s"'; $res = sql_query(sprintf($query, _CUSTOMURL_TABLE, $objID, $oParam)); $row = sql_fetch_object($res); $pathID = $row->id; if ($pathID) { $query = 'UPDATE %s SET obj_name = "%s" WHERE id = %d'; sql_query(sprintf($query, _CUSTOMURL_TABLE, $newPath, $pathID)); } else { $query = 'INSERT INTO %s (obj_param, obj_name, obj_id, obj_bid)' . ' VALUES ("%s", "%s", %d, %d)'; sql_query(sprintf($query, _CUSTOMURL_TABLE, $oParam, $newPath, $objID, $bid)); } switch ($oParam) { case 'blog': $this->setBlogOption($objID, 'customurl_bname', $path); break; case 'category': $this->setCategoryOption($objID, 'customurl_cname', $path); break; case 'member': $this->setMemberOption($objID, 'customurl_mname', $path); break; default: break; } return $msg; }
function addTorrent() { global $dbhost, $dbuser, $dbpass, $database; global $_POST, $_FILES; require_once "funcsv2.php"; require_once "BDecode.php"; require_once "BEncode.php"; $hash = strtolower($_POST["hash"]); $db = mysql_connect($dbhost, $dbuser, $dbpass) or die("<p class=\"error\">Couldn't connect to database. contact the administrator</p>"); mysql_select_db($database) or die("<p class=\"error\">Can't open the database.</p>"); if (isset($_FILES["torrent"])) { if ($_FILES["torrent"]["error"] != 4) { $fd = fopen($_FILES["torrent"]["tmp_name"], "rb") or die("<p class=\"error\">File upload error 1</p>\n"); is_uploaded_file($_FILES["torrent"]["tmp_name"]) or die("<p class=\"error\">File upload error 2</p>\n"); $alltorrent = fread($fd, filesize($_FILES["torrent"]["tmp_name"])); $array = BDecode($alltorrent); if (!$array) { echo "<p class=\"error\">There was an error handling your uploaded torrent. The parser didn't like it.</p>"; endOutput(); exit; } $hash = @sha1(BEncode($array["info"])); fclose($fd); unlink($_FILES["torrent"]["tmp_name"]); } } if (isset($_POST["filename"])) { $filename = clean($_POST["filename"]); } else { $filename = ""; } if (isset($_POST["url"])) { $url = clean($_POST["url"]); } else { $url = ""; } if (isset($_POST["info"])) { $info = clean($_POST["info"]); } else { $info = ""; } if (isset($_POST["autoset"])) { if (strcmp($_POST["autoset"], "enabled") == 0) { if (strlen($filename) == 0 && isset($array["info"]["name"])) { $filename = $array["info"]["name"]; } if (strlen($info) == 0 && isset($array["info"]["piece length"])) { $info = $array["info"]["piece length"] / 1024 * (strlen($array["info"]["pieces"]) / 20) / 1024; $info = round($info, 2) . " MB"; if (isset($array["comment"])) { $info .= " - " . $array["comment"]; } } } $filename = mysql_escape_string($filename); $url = mysql_escape_string($url); $info = mysql_escape_string($info); if (strlen($hash) != 40 || !verifyHash($hash)) { echo "<p class=\"error\">Error: Info hash must be exactly 40 hex bytes.</p>"; endOutput(); } $query = "INSERT INTO BTPHP_namemap (info_hash, filename, url, info) VALUES (\"{$hash}\", \"{$filename}\", \"{$url}\", \"{$info}\")"; $status = makeTorrent($hash, true); quickQuery($query); if ($status) { echo "<p class=\"error\">Torrent was added successfully.</p>"; } else { echo "<p class=\"error\">There were some errors. Check if this torrent had been added previously.</p>"; } } endOutput(); }
die('non direct access!'); } # then require functions (is this needed?) require_once $THIS_BASEPATH . '/include/functions.php'; # connect to db dbconn(); # check if allowed and die if not if ($CURUSER['edit_torrents'] == 'no' && $CURUSER['edit_users'] == 'no') { die('Unauthorised access!'); } # inits $id = (int) $_GET['id']; $warn = addslashes($_POST['warn']); $warnreason = addslashes($_POST['warnreason']); $warnaddedby = $CURUSER['username']; $added = warn_expiration(mktime(date('H') + 2, date('i'), date('s'), date('m'), date('d') + addslashes($_POST['days']), date('Y'))); $returnto = $_POST['returnto']; $subj = sqlesc('You did recieve a Warning!'); $msg = sqlesc('[b]The reason for this warning is: ' . $warnreason . ' By: ' . $CURUSER['username'] . '[/b].Expire date for the warning: ' . $added . '.'); # get the username of warned dude $warneduser = get_result('SELECT username FROM `' . $TABLE_PREFIX . 'users` WHERE `id`=' . $id . ' LIMIT 1;', false, 3600); $warneduser = $warneduser[0]['username']; # process it in one line as to not stress the database server quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET warn="yes",warns=warns+1,warnreason="' . $warnreason . '",warnaddedby="' . $warnaddedby . '",warnadded="' . $added . '" WHERE id=' . $id); # message him send_pm(0, $id, $subj, $msg); # log it write_log('Warned User: '******'. Reason: ' . $warnreason, 'WARN'); # send back to original page header('Location: ' . $returnto); die;
/** * Adds a new comment to the database * @param string $timestamp * @param array $comment * @return mixed */ function addComment($timestamp, $comment) { global $CONF, $member, $manager; $blogid = getBlogIDFromItemID($this->itemid); $settings =& $manager->getBlog($blogid); $settings->readSettings(); // begin if: comments disabled if (!$settings->commentsEnabled()) { return _ERROR_COMMENTS_DISABLED; } // end if // begin if: public cannot comment if (!$settings->isPublic() && !$member->isLoggedIn()) { return _ERROR_COMMENTS_NONPUBLIC; } // end if // begin if: comment uses a protected member name if ($CONF['ProtectMemNames'] && !$member->isLoggedIn() && MEMBER::isNameProtected($comment['user'])) { return _ERROR_COMMENTS_MEMBERNICK; } // end if // begin if: email required, but missing (doesn't apply to members) if ($settings->emailRequired() && strlen($comment['email']) == 0 && !$member->isLoggedIn()) { return _ERROR_EMAIL_REQUIRED; } // end if ## Note usage of mb_strlen() vs strlen() below ## // begin if: commenter's name is too long if (mb_strlen($comment['user']) > 40) { return _ERROR_USER_TOO_LONG; } // end if // begin if: commenter's email is too long if (mb_strlen($comment['email']) > 100) { return _ERROR_EMAIL_TOO_LONG; } // end if // begin if: commenter's url is too long if (mb_strlen($comment['userid']) > 100) { return _ERROR_URL_TOO_LONG; } // end if $comment['timestamp'] = $timestamp; $comment['host'] = gethostbyaddr(serverVar('REMOTE_ADDR')); $comment['ip'] = serverVar('REMOTE_ADDR'); // begin if: member is logged in, use that data if ($member->isLoggedIn()) { $comment['memberid'] = $member->getID(); $comment['user'] = ''; $comment['userid'] = ''; $comment['email'] = ''; } else { $comment['memberid'] = 0; } // spam check $continue = FALSE; $plugins = array(); if (isset($manager->subscriptions['ValidateForm'])) { $plugins = array_merge($plugins, $manager->subscriptions['ValidateForm']); } if (isset($manager->subscriptions['PreAddComment'])) { $plugins = array_merge($plugins, $manager->subscriptions['PreAddComment']); } if (isset($manager->subscriptions['PostAddComment'])) { $plugins = array_merge($plugins, $manager->subscriptions['PostAddComment']); } $plugins = array_unique($plugins); while (list(, $plugin) = each($plugins)) { $p = $manager->getPlugin($plugin); $continue = $continue || $p->supportsFeature('handleSpam'); } $spamcheck = array('type' => 'comment', 'body' => $comment['body'], 'id' => $comment['itemid'], 'live' => TRUE, 'return' => $continue); // begin if: member logged in if ($member->isLoggedIn()) { $spamcheck['author'] = $member->displayname; $spamcheck['email'] = $member->email; } else { $spamcheck['author'] = $comment['user']; $spamcheck['email'] = $comment['email']; $spamcheck['url'] = $comment['userid']; } // end if $manager->notify('SpamCheck', array('spamcheck' => &$spamcheck)); if (!$continue && isset($spamcheck['result']) && $spamcheck['result'] == TRUE) { return _ERROR_COMMENTS_SPAM; } // isValidComment returns either "1" or an error message $isvalid = $this->isValidComment($comment, $spamcheck); if ($isvalid != 1) { return $isvalid; } // begin if: send email to notification address if ($settings->getNotifyAddress() && $settings->notifyOnComment()) { $mailto_msg = _NOTIFY_NC_MSG . ' ' . $this->itemid . "\n"; // $mailto_msg .= $CONF['IndexURL'] . 'index.php?itemid=' . $this->itemid . "\n\n"; $temp = parse_url($CONF['Self']); if ($temp['scheme']) { $mailto_msg .= createItemLink($this->itemid) . "\n\n"; } else { $tempurl = $settings->getURL(); if (substr($tempurl, -1) == '/' || substr($tempurl, -4) == '.php') { $mailto_msg .= $tempurl . '?itemid=' . $this->itemid . "\n\n"; } else { $mailto_msg .= $tempurl . '/?itemid=' . $this->itemid . "\n\n"; } } if ($comment['memberid'] == 0) { $mailto_msg .= _NOTIFY_USER . ' ' . $comment['user'] . "\n"; $mailto_msg .= _NOTIFY_USERID . ' ' . $comment['userid'] . "\n"; } else { $mailto_msg .= _NOTIFY_MEMBER . ' ' . $member->getDisplayName() . ' (ID=' . $member->getID() . ")\n"; } $mailto_msg .= _NOTIFY_HOST . ' ' . $comment['host'] . "\n"; $mailto_msg .= _NOTIFY_COMMENT . "\n " . $comment['body'] . "\n"; $mailto_msg .= getMailFooter(); $item =& $manager->getItem($this->itemid, 0, 0); $mailto_title = _NOTIFY_NC_TITLE . ' ' . strip_tags($item['title']) . ' (' . $this->itemid . ')'; $frommail = $member->getNotifyFromMailAddress($comment['email']); $notify =& new NOTIFICATION($settings->getNotifyAddress()); $notify->notify($mailto_title, $mailto_msg, $frommail); } $comment = COMMENT::prepare($comment); $manager->notify('PreAddComment', array('comment' => &$comment, 'spamcheck' => &$spamcheck)); $name = sql_real_escape_string($comment['user']); $url = sql_real_escape_string($comment['userid']); $email = sql_real_escape_string($comment['email']); $body = sql_real_escape_string($comment['body']); $host = sql_real_escape_string($comment['host']); $ip = sql_real_escape_string($comment['ip']); $memberid = intval($comment['memberid']); $timestamp = date('Y-m-d H:i:s', $comment['timestamp']); $itemid = $this->itemid; $qSql = 'SELECT COUNT(*) AS result ' . 'FROM ' . sql_table('comment') . ' WHERE ' . 'cmail = "' . $url . '"' . ' AND cmember = "' . $memberid . '"' . ' AND cbody = "' . $body . '"' . ' AND citem = "' . $itemid . '"' . ' AND cblog = "' . $blogid . '"'; $result = (int) quickQuery($qSql); if ($result > 0) { return _ERROR_BADACTION; } $query = 'INSERT INTO ' . sql_table('comment') . ' (CUSER, CMAIL, CEMAIL, CMEMBER, CBODY, CITEM, CTIME, CHOST, CIP, CBLOG) ' . "VALUES ('{$name}', '{$url}', '{$email}', {$memberid}, '{$body}', {$itemid}, '{$timestamp}', '{$host}', '{$ip}', '{$blogid}')"; sql_query($query); // post add comment $commentid = sql_insert_id(); $manager->notify('PostAddComment', array('comment' => &$comment, 'commentid' => &$commentid, 'spamcheck' => &$spamcheck)); // succeeded ! return TRUE; }
function do_sanity() { global $PRIVATE_ANNOUNCE, $TORRENTSDIR, $CURRENTPATH, $LIVESTATS, $LOG_HISTORY, $TABLE_PREFIX; // SANITY FOR TORRENTS $results = do_sqlquery("SELECT info_hash, seeds, leechers, dlbytes, filename FROM {$TABLE_PREFIX}files WHERE external='no'"); $i = 0; while ($row = mysql_fetch_row($results)) { list($hash, $seeders, $leechers, $bytes, $filename) = $row; $timeout = time() - intval($GLOBALS["report_interval"] * 2); // for testing purpose -- begin $resupd = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}peers where lastupdate < " . $timeout . " AND infohash='{$hash}'"); if (mysql_num_rows($resupd) > 0) { while ($resupdate = mysql_fetch_array($resupd)) { $uploaded = max(0, $resupdate["uploaded"]); $downloaded = max(0, $resupdate["downloaded"]); $pid = $resupdate["pid"]; $ip = $resupdate["ip"]; // update user->peer stats only if not livestat if (!$LIVESTATS) { if ($PRIVATE_ANNOUNCE) { quickQuery("UPDATE {$TABLE_PREFIX}users SET uploaded=uploaded+{$uploaded}, downloaded=downloaded+{$downloaded} WHERE pid='{$pid}' AND id>1 LIMIT 1"); } else { // ip quickQuery("UPDATE {$TABLE_PREFIX}users SET uploaded=uploaded+{$uploaded}, downloaded=downloaded+{$downloaded} WHERE cip='{$ip}' AND id>1 LIMIT 1"); } } // update dead peer to non active in history table if ($LOG_HISTORY) { $resuser = do_sqlquery("SELECT id FROM {$TABLE_PREFIX}users WHERE " . ($PRIVATE_ANNOUNCE ? "pid='{$pid}'" : "cip='{$ip}'") . " ORDER BY lastconnect DESC LIMIT 1"); $curu = @mysql_fetch_row($resuser); quickquery("UPDATE {$TABLE_PREFIX}history SET active='no' WHERE uid={$curu['0']} AND infohash='{$hash}'"); } } } // for testing purpose -- end quickQuery("DELETE FROM {$TABLE_PREFIX}peers where lastupdate < " . $timeout . " AND infohash='{$hash}'"); quickQuery("UPDATE {$TABLE_PREFIX}files SET lastcycle='" . time() . "' WHERE info_hash='{$hash}'"); $results2 = do_sqlquery("SELECT status, COUNT(status) from {$TABLE_PREFIX}peers WHERE infohash='{$hash}' GROUP BY status"); $counts = array(); while ($row = mysql_fetch_row($results2)) { $counts[$row[0]] = 0 + $row[1]; } quickQuery("UPDATE {$TABLE_PREFIX}files SET leechers=" . (isset($counts["leecher"]) ? $counts["leecher"] : 0) . ",seeds=" . (isset($counts["seeder"]) ? $counts["seeder"] : 0) . " WHERE info_hash=\"{$hash}\""); if ($bytes < 0) { quickQuery("UPDATE {$TABLE_PREFIX}files SET dlbytes=0 WHERE info_hash=\"{$hash}\""); } } // END TORRENT'S SANITY // optimize peers table quickQuery("OPTIMIZE TABLE {$TABLE_PREFIX}peers"); // delete readposts when topic don't exist or deleted *** should be done by delete, just in case quickQuery("DELETE readposts FROM {$TABLE_PREFIX}readposts LEFT JOIN topics ON readposts.topicid = topics.id WHERE topics.id IS NULL"); // delete readposts when users was deleted *** should be done by delete, just in case quickQuery("DELETE readposts FROM {$TABLE_PREFIX}readposts LEFT JOIN users ON readposts.userid = users.id WHERE users.id IS NULL"); // deleting orphan image in torrent's folder (if image code is enabled) $tordir = realpath("{$CURRENTPATH}/../{$TORRENTSDIR}"); if ($dir = @opendir($tordir . "/")) { } while (false !== ($file = @readdir($dir))) { if ($ext = substr(strrchr($file, "."), 1) == "png") { unlink("{$tordir}/{$file}"); } } @closedir($dir); }
function runSpeed($info_hash, $delta) { global $TABLE_PREFIX; //stick in our latest data before we calc it out quickQuery("INSERT IGNORE INTO {$TABLE_PREFIX}timestamps (info_hash, bytes, delta, sequence) SELECT '{$info_hash}' AS info_hash, dlbytes, UNIX_TIMESTAMP() - lastSpeedCycle, NULL FROM {$TABLE_PREFIX}files WHERE info_hash=\"{$info_hash}\""); // mysql blows sometimes so we have to read the data into php before updating it $results = mysql_query('SELECT (MAX(bytes)-MIN(bytes))/SUM(delta), COUNT(*), MIN(sequence) FROM ' . $TABLE_PREFIX . 'timestamps WHERE info_hash="' . $info_hash . '"'); $data = mysql_fetch_row($results); summaryAdd("speed", $data[0], true); summaryAdd("lastSpeedCycle", "UNIX_TIMESTAMP()", true); // if we have more than 20 drop the rest if ($data[1] == 21) { quickQuery("DELETE FROM {$TABLE_PREFIX}timestamps WHERE info_hash=\"{$info_hash}\" AND sequence={$data[2]}"); } else { if ($data[1] > 21) { // This query requires MySQL 4.0.x, but should rarely be used. quickQuery('DELETE FROM ' . $TABLE_PREFIX . 'timestamps WHERE info_hash="' . $info_hash . '" ORDER BY sequence LIMIT ' . ($data['1'] - 20)); } } }
function runSpeed($info_hash, $delta) { global $db; MCached::connect(); // stick in our latest data before we calc it out quickQuery("INSERT IGNORE INTO timestamps (info_hash, bytes, delta, sequence) SELECT '" . $info_hash . "' AS info_hash, dlbytes, UNIX_TIMESTAMP() - lastSpeedCycle, NULL FROM summary WHERE info_hash = '" . $info_hash . "'"); $key = 'ann::bytes::timestamps::' . $info_hash; $data = MCached::get($key); if ($data === MCached::NO_RESULT) { $results = $db->query('SELECT (MAX(bytes) - MIN(bytes)) / SUM(delta), COUNT(*), MIN(sequence) FROM timestamps WHERE info_hash = "' . $info_hash . '"'); $data = $results->fetch_row(); MCached::add($key, $data, 300); } summaryAdd("speed", $data[0], true); summaryAdd("lastSpeedCycle", "UNIX_TIMESTAMP()", true); // if we have more than 20 drop the rest if ($data[1] == 21) { quickQuery("DELETE FROM timestamps WHERE info_hash='" . $info_hash . "' AND sequence = " . $data['2']); MCached::del($key); } elseif ($data[1] > 21) { quickQuery('DELETE FROM timestamps WHERE info_hash = "' . $info_hash . '" ORDER BY sequence LIMIT ' . ($data['1'] - 20)); MCached::del($key); } }
public function event_CustomLogin(&$data) { if ($this->enable_security == 'yes' && $this->max_failed_login > 0) { global $_SERVER; $login = $data['login']; $ip = $_SERVER['REMOTE_ADDR']; sql_query("DELETE FROM " . sql_table('plug_securityenforcer') . " WHERE lastfail < " . (time() - $this->login_lockout * 60)); $query = "SELECT fails as result FROM " . sql_table('plug_securityenforcer') . " "; $query .= "WHERE login='******'"; $flogin = quickQuery($query); $query = "SELECT fails as result FROM " . sql_table('plug_securityenforcer') . " "; $query .= "WHERE login='******'"; $fip = quickQuery($query); if ($flogin >= $this->max_failed_login || $fip >= $this->max_failed_login) { $data['success'] = 0; $data['allowlocal'] = 0; $info = sprintf(_SECURITYENFORCER_LOGIN_DISALLOWED, htmlspecialchars($login), htmlspecialchars($ip)); ACTIONLOG::add(INFO, $info); } } return; }
function do_sanity($ts = 0) { // Lets try upping the max_execution_time and memory_limit if we can (Code from Pet/FM) if (@ini_get("max_execution_time") < 300) { @ini_set("max_execution_time", 300); } if (trim(@ini_get("memory_limit"), "M") < 128) { @ini_set("memory_limit", "128M"); } global $clean_interval, $BASEURL, $btit_settings, $XBTT_USE, $db_prefix, $autopruneusers, $email_on_prune, $days_members, $days_not_comfirm, $days_to_email, $PRIVATE_ANNOUNCE, $TORRENTSDIR, $CURRENTPATH, $LIVESTATS, $LOG_HISTORY, $TABLE_PREFIX, $DOXPATH, $DBDT; $THIS_BASEPATH = dirname(__FILE__); $days = 14; $time = time() - $days * 86400; mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM {$TABLE_PREFIX}bugs WHERE status != 'na' AND added < {$time}") or sqlerr(__FILE__, __LINE__); //delete bots after 48 hours mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM {$TABLE_PREFIX}bots WHERE visit < (NOW() - INTERVAL 2880 MINUTE)"); //end bots //delete last up/downloads after 48 hours mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM {$TABLE_PREFIX}downloads WHERE date < (NOW() - INTERVAL 2880 MINUTE)"); //end last up/downloads //show images in shoutbox if ($btit_settings["endtch"] == TRUE) { $shout = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM {$TABLE_PREFIX}chat ORDER BY id DESC LIMIT 1"); $shoutrow = mysqli_fetch_assoc($shout); $fp = $btit_settings["fix_chat"]; if ($shoutrow["count"] >= $btit_settings["don_chat"]) { if ($btit_settings["ran_chat"] == TRUE) { do_sqlquery("INSERT INTO {$TABLE_PREFIX}chat (uid, time, name, text) VALUES (0," . time() . ", 'System','[img]{$BASEURL}/images/shouts/shout.php[/img]')"); } else { do_sqlquery("INSERT INTO {$TABLE_PREFIX}chat (uid, time, name, text) VALUES (0," . time() . ", 'System','[img]{$BASEURL}/images/shouts/" . $fp . "[/img]')"); } } } //show images in shoutbox end //happy hour $happy_r = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT UNIX_TIMESTAMP(value_s) AS happy , value_i AS happys from {$TABLE_PREFIX}avps where arg='happyhour'") or sqlerr(__FILE__, __LINE__); $happy_a = mysqli_fetch_array($happy_r); $curDate = time(); $happyTime = $happy_a["happy"] + 3600; if ($happy_a["happys"] == 0) { $happyHour = happyHour(); mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}avps set value_s=" . sqlesc($happyHour) . ", value_i='1' WHERE arg='happyhour' LIMIT 1 ") or sqlerr(__FILE__, __LINE__); } elseif ($happy_a["happys"] == 1 && $curDate > $happyTime) { mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}avps set value_i='0' WHERE arg='happyhour' LIMIT 1 "); } $switch = do_sqlquery("SELECT * FROM `{$TABLE_PREFIX}files` WHERE `external`='no'", true); $switch_happy = mysqli_fetch_array($switch); if ($switch_happy["happy_hour"] == "yes") { if (ishappyHour("check") && $happyTime > "0:00") { do_sqlquery("ALTER TABLE `{$TABLE_PREFIX}files` CHANGE `happy` `happy` ENUM( 'yes', 'no' ) NULL DEFAULT 'yes'") or sqlerr(); do_sqlquery("UPDATE `{$TABLE_PREFIX}files` SET `happy`='yes' WHERE `external`='no'", true); } else { do_sqlquery("ALTER TABLE `{$TABLE_PREFIX}files` CHANGE `happy` `happy` ENUM( 'yes', 'no' ) NULL DEFAULT 'no'") or sqlerr(); do_sqlquery("UPDATE `{$TABLE_PREFIX}files` SET `happy`='no' WHERE `external`='no'", true); } } // happy hour // featured if ($btit_settings["auto_feat"] == TRUE) { $feat = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT info_hash , leechers , image from {$TABLE_PREFIX}files where image!='' ORDER BY leechers DESC limit 1"); $resfeat = mysqli_fetch_array($feat); do_sqlquery("INSERT INTO {$TABLE_PREFIX}featured (fid,torrent_id) VALUES ('','{$resfeat['info_hash']}')"); } //featured //sb if ($XBTT_USE) { $ressb = do_sqlquery("SELECT uid FROM xbt_files_users as u INNER JOIN xbt_files as x ON u.fid=x.fid WHERE u.left = '0' AND x.flags='0' AND u.active='1'"); if (mysqli_num_rows($ressb) > 0) { while ($arrsb = mysqli_fetch_assoc($ressb)) { $x = $arrsb["uid"]; quickQuery("UPDATE `{$TABLE_PREFIX}users` SET `seedbonus`=`seedbonus`+'" . number_format(($ts > 0 ? time() - $ts : $clean_interval) / 3600 * $GLOBALS["bonus"], 6, ".", "") . "' WHERE `id` = '{$x}'"); } } } else { $ressb = do_sqlquery("SELECT pid FROM {$TABLE_PREFIX}peers WHERE status = 'seeder'"); if (mysqli_num_rows($ressb) > 0) { while ($arrsb = mysqli_fetch_assoc($ressb)) { $x = $arrsb['pid']; quickQuery("UPDATE `{$TABLE_PREFIX}users` SET `seedbonus`=`seedbonus`+'" . number_format(($ts > 0 ? time() - $ts : $clean_interval) / 3600 * $GLOBALS["bonus"], 6, ".", "") . "' WHERE `pid`= '{$x}'"); } } } //sb //warn $query = do_sqlquery("SELECT * FROM `{$TABLE_PREFIX}users` WHERE warn='yes'"); while ($conf = mysqli_fetch_assoc($query)) { if (mysqli_num_rows($query) > 0) { $expire_dat = $conf['warnadded']; $expire2 = strtotime($expire_dat); $nown = strtotime("now"); if ($nown >= $expire2) { $subj = sqlesc("Your Warning time is expired !!"); $msg = sqlesc("You are not longer Warned , please be carefull to not make the same mistake again !!"); send_pm(0, $conf[id], $subj, $msg); mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET warn='no' WHERE id='{$conf['id']}'") or sqlerr(); } } } //warn //remove boot after expiration require_once load_language("lang_userdetails.php"); $datetime = gmdate("Y-m-d H:i:s"); $bootedstats = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM {$TABLE_PREFIX}users WHERE addbooted < '{$datetime}' AND booted='yes'"); while ($arr = mysqli_fetch_assoc($bootedstats)) { if (mysqli_num_rows($bootedstats) > 0) { $sub = sqlesc($language["BOOT_SUB"]); $mess = sqlesc($language["BOOT_MSG"]); send_pm(0, $arr[id], $sub, $mess); mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET booted='no' WHERE id='{$arr['id']}'") or sqlerr(); } } //remove boot after expiration // DT request hack start $reqprune = $btit_settings["req_prune"]; $request = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id FROM {$TABLE_PREFIX}requests WHERE filledby > '0' AND fulfilled < DATE_SUB(NOW(), INTERVAL {$reqprune} DAY)"); $reqrow = mysqli_fetch_assoc($request); $reqid = $reqrow["id"]; if (mysqli_num_rows($request) > 0) { mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM {$TABLE_PREFIX}requests WHERE filledby > 0 AND id = {$reqid}"); mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM {$TABLE_PREFIX}addedrequests WHERE requestid = {$reqid}"); } // DT request hack end if ($autopruneusers) { $timeout = $days_members * 60 * 60 * 24; $timeout2 = $days_not_comfirm * 60 * 60 * 24; if ($GLOBALS["FORUMLINK"] == "smf") { do_sqlquery("DELETE u,smfm FROM {$TABLE_PREFIX}users u INNER JOIN {$db_prefix}members smfm ON smfm.ID_MEMBER=u.smf_fid INNER JOIN {$TABLE_PREFIX}users_level ul ON ul.id=u.id_level WHERE (u.id_level = '2' AND UNIX_TIMESTAMP(u.lastconnect)<(UNIX_TIMESTAMP()-{$timeout2}) AND ul.auto_prune='yes') OR (UNIX_TIMESTAMP(lastconnect)<(UNIX_TIMESTAMP()-{$timeout}) AND ul.auto_prune='yes')"); } else { do_sqlquery("DELETE u FROM {$TABLE_PREFIX}users u INNER JOIN {$TABLE_PREFIX}users_level ul ON ul.id=u.id_level WHERE (u.id_level = '2' AND UNIX_TIMESTAMP(u.lastconnect)<(UNIX_TIMESTAMP()-{$timeout2}) AND ul.auto_prune='yes') OR (UNIX_TIMESTAMP(lastconnect)<(UNIX_TIMESTAMP()-{$timeout}) AND ul.auto_prune='yes')"); } if ($email_on_prune) { $timeout = $days_to_email * 60 * 60 * 24; $res = get_result("SELECT email, lastconnect FROM {$TABLE_PREFIX}users u INNER JOIN {$TABLE_PREFIX}users_level ul ON ul.id=u.id_level WHERE UNIX_TIMESTAMP()>=(UNIX_TIMESTAMP(lastconnect)+{$timeout}-{$clean_interval}/2) AND UNIX_TIMESTAMP()<(UNIX_TIMESTAMP(lastconnect)+{$timeout}+{$clean_interval}/2) AND UNIX_TIMESTAMP(lastconnect)<(UNIX_TIMESTAMP()-{$timeout}) AND ul.auto_prune='yes'", true); foreach ($res as $id => $rusers) { send_mail($rusers["email"], $language["EMAIL_INACTIVE_SUBJ"], $language["EMAIL_INACTIVE_MSG"] . "\n\n" . $BASEURL . "/index.php"); } } } // Autoprune torrents if ($btit_settings["autotprune"] == TRUE) { quickQuery("UPDATE `{$TABLE_PREFIX}files` `f` " . ($XBTT_USE ? "LEFT JOIN `xbt_files` `xf` ON `f`.`bin_hash`=`xf`.`info_hash`" : "") . " SET `f`.`dead_time`=UNIX_TIMESTAMP() WHERE ((" . ($XBTT_USE ? "`xf`.`seeders`>0 OR `xf`.`leechers`>0" : "`f`.`seeds`>0 OR `f`.`leechers`>0") . ") OR `f`.`dead_time`=0) AND `f`.`external`='no'"); $res = get_result("SELECT `info_hash`, `bin_hash` FROM `{$TABLE_PREFIX}files` WHERE `dead_time`<=" . (time() - $btit_settings["autotprundedays"] * 86400) . " AND `dead_time`!=0 AND `external`='no'"); if (count($res) > 0) { foreach ($res as $row) { quickQuery("DELETE FROM `{$TABLE_PREFIX}files` WHERE `info_hash`='" . mysqli_real_escape_string($DBDT, $row["info_hash"]) . "'"); quickQuery("DELETE FROM `{$TABLE_PREFIX}timestamps` WHERE `info_hash`='" . mysqli_real_escape_string($DBDT, $row["info_hash"]) . "'"); quickQuery("DELETE FROM `{$TABLE_PREFIX}comments` WHERE `info_hash`='" . mysqli_real_escape_string($DBDT, $row["info_hash"]) . "'"); quickQuery("DELETE FROM `{$TABLE_PREFIX}ratings` WHERE `infohash`='" . mysqli_real_escape_string($DBDT, $row["info_hash"]) . "'"); quickQuery("DELETE FROM `{$TABLE_PREFIX}peers` WHERE `infohash`='" . mysqli_real_escape_string($DBDT, $row["info_hash"]) . "'"); quickQuery("DELETE FROM `{$TABLE_PREFIX}history` WHERE `infohash`='" . mysqli_real_escape_string($DBDT, $row["info_hash"]) . "'"); if ($XBTT_USE) { quickQuery("UPDATE `xbt_files` SET `flags`=1 WHERE `info_hash`='" . mysqli_real_escape_string($DBDT, $row["bin_hash"]) . "'"); } } } } // Autoprune torrents // timed registration $expire_datetr = $btit_settings["regi_d"]; $expire_timetr = $btit_settings["regi_t"]; $expire_datetrs = $expire_datetr . " " . $expire_timetr . ":00:00"; $expiretr = strtotime($expire_datetrs); $nowtr = strtotime("now"); if ($nowtr >= $expiretr) { do_sqlquery("UPDATE `{$TABLE_PREFIX}settings` SET `value`='true' WHERE `key`='regi'", true); } // end timed registration // Anti Hit and Run V2 based on CobraCRK's Anti Hit&Run Mod v1 Enhanced By IntelPentium4 & fatepower // converted ( and improved ) to XBTIT 2 by DiemThuy Nov 2008 if (!$XBTT_USE) { // Get current time $timenow = time(); // Get last time that dosanity() was run $timeres = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT last_time FROM {$TABLE_PREFIX}anti_hit_run_tasks WHERE task='sanity'"); if (mysqli_num_rows($timeres) > 0) { $timearr = mysqli_fetch_array($timeres); $lastrecordedtime = intval($timearr['last_time']); } else { $lastrecordedtime = $timenow - $clean_interval; } // Update Active Seeders' Seeding Clock $res = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT pid, infohash FROM {$TABLE_PREFIX}peers WHERE status = 'seeder'"); if (mysqli_num_rows($res) > 0) { while ($arr = mysqli_fetch_assoc($res)) { $x = $arr['pid']; $t = $arr['infohash']; $pl = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id FROM {$TABLE_PREFIX}users WHERE pid='" . $x . "'"); if (mysqli_num_rows($pl) > 0) { $ccc = mysqli_result($pl, 0, "id"); } else { $ccc = "Unknown"; } mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}history SET seed = seed+" . $timenow . "-" . $lastrecordedtime . " WHERE uid = {$ccc} AND infohash='{$t}'"); } } //Update table anti_hit_run_tasks with new time info. $hunden = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT last_time FROM {$TABLE_PREFIX}anti_hit_run_tasks WHERE task='sanity'"); $manneplutt = mysqli_fetch_row($hunden); if (!$manneplutt) { mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO {$TABLE_PREFIX}anti_hit_run_tasks (task, last_time) VALUES ('sanity',{$timenow})"); } else { $ts = $manneplutt[0]; mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}anti_hit_run_tasks SET last_time={$timenow} WHERE task='sanity' AND last_time = {$ts}"); } // Rank who has no anti-hit punishment rule should be excluded $levels = mysqli_query($GLOBALS["___mysqli_ston"], "select id from {$TABLE_PREFIX}users_level order by id"); while ($SingleLevel = mysqli_fetch_array($levels)) { $hasAntiHitRecord = mysqli_query($GLOBALS["___mysqli_ston"], "select id_level from {$TABLE_PREFIX}anti_hit_run where id_level=" . $SingleLevel["id"]); if (mysqli_num_rows($hasAntiHitRecord) == 0) { @mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE `{$TABLE_PREFIX}history`,`users` set hitchecked= 2 where history.uid=users.id and users.id_level=" . $SingleLevel["id"] . " and completed='yes' and hitchecked='0'"); } } $hit_parameters = mysqli_query($GLOBALS["___mysqli_ston"], "select * from {$TABLE_PREFIX}anti_hit_run order by id_level"); while ($hit = mysqli_fetch_array($hit_parameters)) { // Punishment $r = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT DISTINCT uid,infohash FROM {$TABLE_PREFIX}history history inner join {$TABLE_PREFIX}users users on history.uid=users.id WHERE users.id_level=" . $hit["id_level"] . " AND active='no' AND completed='yes' AND hit='no' AND hitchecked= 0 AND date < ( UNIX_TIMESTAMP( ) - (86400 * " . $hit["tolerance_days_before_punishment"] . ")) AND history.downloaded>(1048576 * " . $hit["min_download_size"] . ") AND seed<( 3600 * " . $hit["min_seed_hours"] . ") AND (history.uploaded/history.downloaded)<" . $hit["min_ratio"]); while ($x = mysqli_fetch_array($r)) { @mysqli_query($GLOBALS["___mysqli_ston"], "Update {$TABLE_PREFIX}history SET hit='yes' WHERE uid=" . $x[uid] . " AND infohash='" . $x[infohash] . "' AND hitchecked=0"); if (mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) { if ($hit["reward"] == 'yes') { $reward = "\n\n[color=red]If you want to get the lost amount back , you must seed for at least " . $hit["min_seed_hours"] . " hour(s) or until the file\\'s ratio becomes greater than " . $hit["min_ratio"] . " then your total upload will incremented by " . $hit["upload_punishment"] . " MB !! \n\n\\ [/color][color=purple]This is a automatic system message , so DO NOT reply ![/color]"; } else { $reward = " "; } @mysqli_query($GLOBALS["___mysqli_ston"], "Update {$TABLE_PREFIX}history SET hitchecked= 1 ,punishment_amount=" . $hit["upload_punishment"] . " WHERE uid=" . $x[uid] . " AND infohash='" . $x[infohash] . "' AND hitchecked=0"); @mysqli_query($GLOBALS["___mysqli_ston"], "Update {$TABLE_PREFIX}users SET uploaded=(case when uploaded-(1048576 * " . $hit["upload_punishment"] . ")<0 then 0 else uploaded-(1048576 * " . $hit["upload_punishment"] . ") end) WHERE id={$x['uid']}"); send_pm(0, $x[uid], sqlesc("Auto Hit an Run warning"), sqlesc("You did Hit and Run on the following torrent :\n\n [url]" . $BASEURL . "/index.php?page=details&id={$x['infohash']}[/url] !\n\n\\We did take away " . $hit["upload_punishment"] . " MB as punishment\n\nBe carefull to not make the mistake once more ! " . $reward . "")); // DT reputation system start $reput = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}reputation_settings WHERE id =1"); $setrep = mysqli_fetch_array($reput); $plus = $setrep["rep_hit"]; if ($setrep["rep_is_online"] == FALSE) { //do nothing } else { @mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET reputation = reputation - '{$plus}' WHERE id='{$x['uid']}'"); } // DT reputation system end // warn at hit and run if ($hit["warn"] == 'yes') { $id = (int) $x[uid]; $warnreason = "Auto Hit & Run Warning"; $warnaddedby = "System"; $added = warn_expiration(mktime(date('H') + 2, date('i'), date('s'), date('m'), date('d') + addslashes($hit["days1"]), date('Y'))); quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET warn="yes",warns=warns+1,warnreason="' . $warnreason . '",warnaddedby="' . $warnaddedby . '",warnadded="' . $added . '" WHERE id=' . $id); } // end warn at hit and run // boot at hit and run if ($hit["boot"] == 'yes') { $id = (int) $x[uid]; $whybooted = "Auto Hit & Run Ban"; $whobooted = "System"; $addbooted = booted_expiration(mktime(date('H') + 2, date('i'), date('s'), date('m'), date('d') + addslashes($hit["days2"]), date('Y'))); quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET booted="yes", whybooted="' . $whybooted . '",whobooted="' . $whobooted . '",addbooted="' . $addbooted . '" WHERE id=' . $id); } // end boot at hit and run //Dox Hack Start $r = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id, filename, added FROM {$TABLE_PREFIX}dox WHERE added < '" . date('Y-m-d', strtotime('-' . $btit_settings["dox_del"] . ' weeks')) . "'"); while ($del = mysqli_fetch_array($r)) { $MANNE = "{$BASEURL}/{$DOXPATH}"; @unlink("{$MANNE}/{$del['filename']}"); quickQuery("DELETE FROM {$TABLE_PREFIX}dox WHERE id={$del['id']}"); } //Dox Hack End // boot after warn at hit and run if ($hit["warnboot"] == 'yes') { $diem = do_sqlquery("SELECT warns FROM {$TABLE_PREFIX}users WHERE id={$x['uid']}"); $thuy = mysqli_fetch_array($diem); if ($thuy["warns"] >= $hit["days3"]) { } $id = (int) $x[uid]; $whybooted = "Auto Hit & Run Ban after beeing warned"; $whobooted = "System"; $addbooted = booted_expiration(mktime(date('H') + 2, date('i'), date('s'), date('m'), date('d') + addslashes($hit["days2"]), date('Y'))); quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET booted="yes", whybooted="' . $whybooted . '",whobooted="' . $whobooted . '",addbooted="' . $addbooted . '" WHERE id=' . $id); } // end boot after warn at hit and run } } mysqli_free_result($r) || is_object($r) && get_class($r) == "mysqli_result" ? true : false; // Reward if ($hit["reward"] == 'yes') { $rr = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT DISTINCT uid,infohash,punishment_amount FROM {$TABLE_PREFIX}history history inner join {$TABLE_PREFIX}users users on history.uid=users.id WHERE users.id_level=" . $hit["id_level"] . " AND hit='yes' AND completed='yes' AND hitchecked= 1 AND (seed>=( 3600 * " . $hit["min_seed_hours"] . ") or (history.uploaded/history.downloaded)>=" . $hit["min_ratio"] . ")"); while ($xr = mysqli_fetch_array($rr)) { @mysqli_query($GLOBALS["___mysqli_ston"], "Update {$TABLE_PREFIX}history SET hitchecked= 3 WHERE uid=" . $xr[uid] . " AND infohash='" . $xr[infohash] . "' AND hitchecked=1"); if (mysqli_affected_rows($GLOBALS["___mysqli_ston"]) > 0) { @mysqli_query($GLOBALS["___mysqli_ston"], "Update {$TABLE_PREFIX}users SET uploaded=uploaded+(1048576 * " . $xr["punishment_amount"] . ") WHERE id={$xr['uid']}"); send_pm(0, $xr[uid], sqlesc("Thanks (Punishement Removed)"), sqlesc("Thank you very much for seeding back the following torrent:\n\n [url]" . $BASEURL . "/index.php?page=details&id={$xr['infohash']}[/url] !\n\n [color=green]The punishment is now removed and you total upload amount increased by " . $xr["punishment_amount"] . " MB! [/color]\n\n [color=purple]This is a automatic system message , so DO NOT reply ![/color]")); // DT reputation system start if ($setrep["rep_is_online"] == FALSE) { //do nothing } else { @mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET reputation = reputation + '{$plus}' WHERE id='{$x['uid']}'"); } // DT reputation system end // warn at hit and run if ($hit["warn"] == 'yes') { quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET warn="no", warns=warns-1 WHERE id=' . $xr[uid]); } // end warn at hit and run // boot at hit and run if ($hit["boot"] == 'yes') { quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET booted="no" WHERE id=' . $xr[uid]); } // end boot at hit and run } } mysqli_free_result($rr) || is_object($rr) && get_class($rr) == "mysqli_result" ? true : false; } // Who are fine should not be punished @mysqli_query($GLOBALS["___mysqli_ston"], "Update {$TABLE_PREFIX}history,users SET hitchecked= 1 WHERE history.uid=users.id AND users.id_level = users.id_level=" . $hit["id_level"] . " AND completed='yes' AND date < ( UNIX_TIMESTAMP( ) - (86400 * " . $hit["tolerance_days_before_punishment"] . ")) AND hitchecked= 0"); } mysqli_free_result($levels) || is_object($levels) && get_class($levels) == "mysqli_result" ? true : false; mysqli_free_result($hasAntiHitRecord) || is_object($hasAntiHitRecord) && get_class($hasAntiHitRecord) == "mysqli_result" ? true : false; mysqli_free_result($hit_parameters) || is_object($hit_parameters) && get_class($hit_parameters) == "mysqli_result" ? true : false; } // End of Anti Hit and Run //Invalid Login System Hack Start mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM {$TABLE_PREFIX}bannedip WHERE comment='max_number_of_invalid_logins_reached'"); //invalid Login System Hack Stop //start freeleech $queryd = do_sqlquery("SELECT free_expire_date, free FROM `{$TABLE_PREFIX}files` WHERE `external`='no'", true); $configd = mysqli_fetch_array($queryd); $expire_dated = $configd['free_expire_date']; $expired = strtotime($expire_dated); $nowd = strtotime("now"); if ($nowd >= $expired && $configd['free'] == 'yes') { do_sqlquery("UPDATE `{$TABLE_PREFIX}files` SET `free`='no',free_expire_date='0000-00-00 00:00:00' WHERE `external`='no'", true); do_sqlquery("ALTER TABLE `{$TABLE_PREFIX}files` CHANGE `free` `free` ENUM( 'yes', 'no' ) NULL DEFAULT 'no'", true); // xbtt if ($XBTT_USE) { do_sqlquery("UPDATE xbt_files SET down_multi=0, flags=2"); do_sqlquery("ALTER TABLE xbt_files CHANGE `down_multi` `down_multi` INT NULL DEFAULT '0'", true); } } // end freeleech $query = do_sqlquery("SELECT * FROM `{$TABLE_PREFIX}lottery_config` WHERE `id`=1", true); $config = mysqli_fetch_array($query); $expire_date = $config['lot_expire_date']; $expire = strtotime($expire_date); $now = strtotime("now"); if ($now >= $expire) { $number_winners = $config['lot_number_winners']; $number_to_win = $config['lot_number_to_win']; $minupload = $config['lot_amount']; $res = do_sqlquery("SELECT `id`, `user` FROM `{$TABLE_PREFIX}lottery_tickets` ORDER BY RAND(NOW()) LIMIT " . $number_winners . "", true); //select number of winners $total = mysqli_num_rows(do_sqlquery("SELECT * FROM `{$TABLE_PREFIX}lottery_tickets`", true)); //select total selled tickets $pot = $total * $minupload; //selled tickets * ticket price $pot += $number_to_win; // ticket prize + minimum win $win = $pot / $number_winners; // prize for each winner $subject = sqlesc("You have won a prize with the lottery"); //subject in pm $msg = sqlesc("Congratulations you have won a prize with our Lottery. Your prize has been added to your account. You won " . makesize($win) . ""); //next 3 rows are the msg for PM $sender = $config['sender_id']; // Sender id, in my case 0 //print the winners and send them PM en give them price while ($row = mysqli_fetch_array($res)) { $ras = do_sqlquery("SELECT `smf_fid`, `id`, `username` FROM `{$TABLE_PREFIX}users` WHERE `id`=" . $row['user'] . "", true); $raw = mysqli_fetch_array($ras); $rec = sqlesc("{$raw['id']}"); $lotid = $raw["id"]; $lotname = $raw["username"]; do_sqlquery("UPDATE `{$TABLE_PREFIX}users` SET `uploaded`=uploaded+" . $win . " WHERE `id`=" . $row['user'] . "", true); $smf = mysqli_fetch_assoc(do_sqlquery("SELECT smf_fid, username FROM `{$TABLE_PREFIX}users` WHERE `id`=" . $row["user"] . "", true)); send_pm($sender, $rec, $subject, $msg); // begin - announce winner in shoutbox do_sqlquery("INSERT INTO {$TABLE_PREFIX}chat (uid, time, name, text) VALUES (0," . time() . ", 'System','[color=red]Lottery winner : [/color][url={$BASEURL}/index.php?page=userdetails&id={$lotid}]" . $lotname . " did win " . makesize($win) . "[/url]')"); // end - announce winner in shoutbox do_sqlquery("INSERT INTO `{$TABLE_PREFIX}lottery_winners` (`id`, `win_user`, `windate`, `price`) VALUES ('', '" . $raw['username'] . "', '" . $expire_date . "', '" . $win . "')"); } do_sqlquery("TRUNCATE TABLE `{$TABLE_PREFIX}lottery_tickets`", true); do_sqlquery("UPDATE `{$TABLE_PREFIX}lottery_config` SET `lot_status`='closed' WHERE `id`=1", true); } // lottery auto start if ($btit_settings["autolot"] == TRUE) { $date_end = lastOfMonth(); $klaar = $config["lot_status"]; if ($klaar == 'closed') { $expire_date = $date_end; $expire_time = 23; $val1 = $expire_date . " " . $expire_time . ":59:59"; $val2 = 1; $val3 = 15 * 1024 * 1024 * 1024; // Gb $val4 = 500 * 1024 * 1024; // Mb $val5 = 'yes'; $val6 = 1; $val7 = 2; do_sqlquery("UPDATE `{$TABLE_PREFIX}lottery_config` SET `lot_expire_date`='" . $val1 . "', `lot_number_winners`='" . $val2 . "', `lot_number_to_win`='" . $val3 . "', `lot_amount`='" . $val4 . "', `lot_status`='" . $val5 . "', `limit_buy`='" . $val6 . "', `sender_id`=" . $val7 . " WHERE `id`=1", true); } // lottery end } // SANITY FOR TORRENTS $results = do_sqlquery("SELECT info_hash, seeds, leechers, dlbytes, filename FROM {$TABLE_PREFIX}files WHERE external='no'"); $i = 0; while ($row = mysqli_fetch_row($results)) { list($hash, $seeders, $leechers, $bytes, $filename) = $row; $timeout = time() - intval($GLOBALS["report_interval"] * 2); // for testing purpose -- begin $resupd = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}peers where lastupdate < " . $timeout . " AND infohash='{$hash}'"); if (mysqli_num_rows($resupd) > 0) { while ($resupdate = mysqli_fetch_array($resupd)) { $uploaded = max(0, $resupdate["uploaded"]); $downloaded = max(0, $resupdate["downloaded"]); $pid = $resupdate["pid"]; $ip = $resupdate["ip"]; // update user->peer stats only if not livestat if (!$LIVESTATS) { if ($PRIVATE_ANNOUNCE) { quickQuery("UPDATE {$TABLE_PREFIX}users SET uploaded=uploaded+{$uploaded}, downloaded=downloaded+{$downloaded} WHERE pid='{$pid}' AND id>1 LIMIT 1"); } else { // ip quickQuery("UPDATE {$TABLE_PREFIX}users SET uploaded=uploaded+{$uploaded}, downloaded=downloaded+{$downloaded} WHERE cip='{$ip}' AND id>1 LIMIT 1"); } } // update dead peer to non active in history table if ($LOG_HISTORY) { $resuser = do_sqlquery("SELECT id FROM {$TABLE_PREFIX}users WHERE " . ($PRIVATE_ANNOUNCE ? "pid='{$pid}'" : "cip='{$ip}'") . " ORDER BY lastconnect DESC LIMIT 1"); $curu = @mysqli_fetch_row($resuser); quickquery("UPDATE {$TABLE_PREFIX}history SET active='no' WHERE uid={$curu['0']} AND infohash='{$hash}'"); } } } // for testing purpose -- end quickQuery("DELETE FROM {$TABLE_PREFIX}peers where lastupdate < " . $timeout . " AND infohash='{$hash}'"); quickQuery("UPDATE {$TABLE_PREFIX}files SET lastcycle='" . time() . "' WHERE info_hash='{$hash}'"); $results2 = do_sqlquery("SELECT status, COUNT(status) from {$TABLE_PREFIX}peers WHERE infohash='{$hash}' GROUP BY status"); $counts = array(); while ($row = mysqli_fetch_row($results2)) { $counts[$row[0]] = 0 + $row[1]; } quickQuery("UPDATE {$TABLE_PREFIX}files SET leechers=" . (isset($counts["leecher"]) ? $counts["leecher"] : 0) . ",seeds=" . (isset($counts["seeder"]) ? $counts["seeder"] : 0) . " WHERE info_hash=\"{$hash}\""); if ($bytes < 0) { quickQuery("UPDATE {$TABLE_PREFIX}files SET dlbytes=0 WHERE info_hash=\"{$hash}\""); } } //Auto Seedbox Start do_sqlquery("UPDATE {$TABLE_PREFIX}files SET `seedbox`='0' "); $sid = do_sqlquery("select * FROM {$TABLE_PREFIX}peers WHERE `ip` =" . $btit_settings["seedip"]); while ($sow = mysqli_fetch_array($sid)) { do_sqlquery("UPDATE {$TABLE_PREFIX}files SET `seedbox`='1' WHERE `info_hash`='{$sow['infohash']}'"); } //Auto Seedbox End // END TORRENT'S SANITY //DT Uploader Medals global $btit_settings; do_sqlquery("UPDATE {$TABLE_PREFIX}users SET `up_med`='0' "); $time_B = 86400 * $btit_settings['UPD']; $time_E = strtotime(now); $time_D = $time_E - $time_B; $res = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT uploader,count( * ) AS Count FROM {$TABLE_PREFIX}files WHERE UNIX_TIMESTAMP(data) > " . $time_D . " GROUP by uploader"); while ($fetch_U = mysqli_fetch_array($res)) { if ($fetch_U['Count'] >= $btit_settings['UPB'] and $fetch_U['Count'] < $btit_settings['UPS']) { do_sqlquery("UPDATE {$TABLE_PREFIX}users SET `up_med`='1' WHERE `id`='{$fetch_U['uploader']}'"); } if ($fetch_U['Count'] >= $btit_settings['UPS'] and $fetch_U['Count'] < $btit_settings['UPG']) { do_sqlquery("UPDATE {$TABLE_PREFIX}users SET `up_med`='2' WHERE `id`='{$fetch_U['uploader']}'"); } if ($fetch_U['Count'] >= $btit_settings['UPG']) { do_sqlquery("UPDATE {$TABLE_PREFIX}users SET `up_med`='3' WHERE `id`='{$fetch_U['uploader']}'"); } } //DT end Uploader Medals // high speed report if ($btit_settings["highswitch"] == TRUE) { if ($GLOBALS["XBTT_USE"]) { $resch = do_sqlquery("SELECT `uid` `id`, `up_rate` FROM `xbt_files_users` WHERE `up_rate` >= (" . $btit_settings["highspeed"] . "*1024) AND `active`=1"); } else { $resch = do_sqlquery("SELECT `p`.`upload_difference`, `p`.`announce_interval`, `u`.`id` FROM `{$TABLE_PREFIX}peers` `p` LEFT JOIN `{$TABLE_PREFIX}users` `u` ON " . ($PRIVATE_ANNOUNCE ? "`p`.`pid`=`u`.`pid`" : "`p`.`ip`=`u`.`cip`") . " WHERE (`p`.`upload_difference`/`p`.`announce_interval`) >= (" . $btit_settings["highspeed"] . "*1024)"); } if (@mysqli_num_rows($resch) > 0) { while ($rowch = mysqli_fetch_assoc($resch)) { if (!is_null($rowch["id"])) { if ($GLOBALS["XBTT_USE"]) { $transferrate = "Upload speed " . round($rowch["up_rate"] / 1024, 2) . " KB/sec ?!"; } else { $transferrate = "Upload speed " . round(round($rowch['upload_difference'] / $rowch['announce_interval']) / 1024, 2) . " KB/sec ?!"; } $high = $rowch["id"]; if ($btit_settings["highonce"] == TRUE) { $once = do_sqlquery("SELECT `id` FROM `{$TABLE_PREFIX}reports` WHERE `addedby` = 0 AND `votedfor` = {$high} AND `type` = 'user' AND reason LIKE 'Upload speed%'"); if (@mysqli_num_rows($once) === FALSE) { do_sqlquery("INSERT INTO `{$TABLE_PREFIX}reports` (`addedby`,`votedfor`,`type`,`reason`) VALUES ('0','{$high}','user', '{$transferrate}')"); } } if ($btit_settings["highonce"] == FALSE) { do_sqlquery("INSERT INTO `{$TABLE_PREFIX}reports` (`addedby`,`votedfor`,`type`,`reason`) VALUES ('0','{$high}','user', '{$transferrate}')"); } } } } } // end high speed report // DT reputation system start $reput = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}reputation_settings WHERE id =1"); $setrep = mysqli_fetch_array($reput); if ($setrep["rep_is_online"] == FALSE or $setrep["rep_en_sys"] == FALSE) { //do nothing } else { // demote $rep_sub = sqlesc("You are Demoted!"); $rep_msg = sqlesc($setrep["rep_dm_text"]); $rep_demotelist = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id FROM {$TABLE_PREFIX}users WHERE reputation < " . $setrep["rep_dm"] . " AND id_level = " . $setrep["rep_pr_id"]); while ($rep_demote = mysqli_fetch_assoc($rep_demotelist)) { mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET id_level=" . $setrep["rep_dm_id"] . " WHERE id=" . $rep_demote["id"]); send_pm(0, $rep_demote[id], $rep_sub, $rep_msg); } // promote $rep_subj = sqlesc("You are Promoted!"); $rep_mesg = sqlesc($setrep["rep_pm_text"]); $rep_promotelist = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id FROM {$TABLE_PREFIX}users WHERE reputation > " . $setrep["rep_pr"] . " AND id_level = " . $setrep["rep_dm_id"]); while ($rep_promote = mysqli_fetch_assoc($rep_promotelist)) { mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET id_level=" . $setrep["rep_pr_id"] . " WHERE id=" . $rep_promote["id"]); send_pm(0, $rep_promote[id], $rep_subj, $rep_mesg); } } // DT reputation system start // Client Log for XBT if ($GLOBALS["XBTT_USE"]) { $timeout = time() - intval($GLOBALS["report_interval"] * 2); quickQuery("DELETE FROM `xbt_announce_log` WHERE `mtime`<={$timeout}"); $res = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT `u`.`id`, INET_NTOA(`al`.`ipa`) `ip`, `al`.`port`, LOWER(HEX(`al`.`peer_id`)) `peer_id`, `u`.`clientinfo` FROM `xbt_announce_log` `al` LEFT JOIN `{$TABLE_PREFIX}users` `u` ON `al`.`uid`=`u`.`id` WHERE `al`.`event`=2 GROUP BY `al`.`peer_id` ORDER BY `u`.`id` ASC"); if (@mysqli_num_rows($res) > 0) { $old_clients = array(); $current_clients = array(); while ($row = mysqli_fetch_assoc($res)) { $client = getagent("", $row["peer_id"]); if (!empty($row["clientinfo"])) { if (!array_key_exists($row["id"], $old_clients)) { $old_clients[$row["id"]] = unserialize($row["clientinfo"]); } if (!array_key_exists($row["id"], $current_clients)) { $current_clients[$row["id"]] = unserialize($row["clientinfo"]); } } else { if (!array_key_exists($row["id"], $old_clients)) { $old_clients[$row["id"]] = array(); } if (!array_key_exists($row["id"], $current_clients)) { $current_clients[$row["id"]] = array(); } } if (!in_array($client . "[X]" . $row["port"], $current_clients[$row["id"]])) { if (count($current_clients[$row["id"]]) == 20) { unset($current_clients[$row["id"]][0]); unset($current_clients[$row["id"]][1]); $newlist = array(); foreach ($current_clients[$row["id"]] as $v) { $newlist[] = $v; } $current_clients[$row["id"]] = $newlist; } $current_clients[$row["id"]][] = $client . "[X]" . $row["port"]; $current_clients[$row["id"]][] = time() . "[X]" . $row["ip"]; } } foreach ($current_clients as $k => $v) { $s_old_clients = serialize($old_clients[$k]); $s_current_clients = serialize($current_clients[$k]); if ($s_old_clients != $s_current_clients) { mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE `{$TABLE_PREFIX}users` SET `clientinfo`='" . mysqli_real_escape_string($DBDT, $s_current_clients) . "' WHERE `id`={$k}"); } } } } // Client Log for XBT // banbutton $timeout = $btit_settings["bandays"] * 86400; @mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM `{$TABLE_PREFIX}signup_ip_block` WHERE (UNIX_TIMESTAMP() - `added`) > {$timeout}"); // end banbutton # global language, $clean_interval, $reload_cfg_interval; global $language, $clean_interval, $reload_cfg_interval; require dirname(__FILE__) . '/khez.php'; quickQuery('OPTIMIZE TABLE `' . $TABLE_PREFIX . 'khez_configs`;'); # hacks can start here ==Khez== // warn-ban system with acp by DT global $XBTT_USE; $resset = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM {$TABLE_PREFIX}low_ratio_ban_settings WHERE id ='1'"); $art = mysqli_fetch_assoc($resset); $resban = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM {$TABLE_PREFIX}low_ratio_ban "); while ($ban = mysqli_fetch_assoc($resban)) { if ($art["wb_sys"] == TRUE) { if ($XBTT_USE) { $udownloaded = "u.downloaded+IFNULL(x.downloaded,0)"; $uuploaded = "u.uploaded+IFNULL(x.uploaded,0)"; $utables = "{$TABLE_PREFIX}users u LEFT JOIN xbt_users x ON x.uid=u.id"; } else { $udownloaded = "u.downloaded"; $uuploaded = "u.uploaded"; $utables = "{$TABLE_PREFIX}users u"; } $min_dl = $ban["wb_down"] * 1024 * 1024 * 1024; // find bad users 1 $demotelist = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id FROM {$utables} WHERE {$udownloaded} > " . $min_dl . " AND {$uuploaded}/{$udownloaded} <= " . $ban["wb_one"] . " AND id_level=" . $ban["wb_rank"] . " AND rat_warn_level = 0 "); while ($demote = mysqli_fetch_assoc($demotelist)) { // warn bad users 1 do_sqlquery("UPDATE {$TABLE_PREFIX}users SET rat_warn_level = 1 , rat_warn_time = NOW() WHERE id=" . $demote["id"]); // DT reputation system start $reput = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}reputation_settings WHERE id =1"); $setrep = mysqli_fetch_array($reput); $plus = $setrep["rep_minrep"]; if ($setrep["rep_is_online"] == FALSE) { //do nothing } else { @mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET reputation = reputation - '{$plus}' WHERE id='{$demote['id']}'"); } // DT reputation system end // send pm bad users 1 $sub = sqlesc("Low Ratio Warning!"); $msg = sqlesc($art["wb_text_one"]); send_pm(0, $demote[id], $sub, $msg); // add warn symbol 1 if ($ban["wb_warn"] == TRUE) { $id = $demote["id"]; $warnreason = "Low Ratio Warning"; $warnaddedby = "System"; $added = warn_expiration(mktime(date('H') + 2, date('i'), date('s'), date('m'), date('d') + addslashes($ban['wb_days_one']), date('Y'))); quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET warn="yes",warns=warns+1,warnreason="' . $warnreason . '",warnaddedby="' . $warnaddedby . '",warnadded="' . $added . '" WHERE id=' . $id); } } // time date stuff $time_AA = 86400 * $ban['wb_days_one']; $time_BB = strtotime(now); $time_CC = $time_BB - $time_AA; // find bad users 2 $demotelistt = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id,rat_warn_time FROM {$utables} WHERE {$udownloaded} > " . $min_dl . " AND {$uuploaded}/{$udownloaded} <= " . $ban["wb_two"] . " AND id_level=" . $ban["wb_rank"] . " AND rat_warn_level = 1 "); while ($demotee = mysqli_fetch_assoc($demotelistt)) { $time_DD = strtotime($demotee["rat_warn_time"]); if ($time_DD <= $time_CC) { // warn bad users 2 do_sqlquery("UPDATE {$TABLE_PREFIX}users SET rat_warn_level = 2 , rat_warn_time = NOW() WHERE id=" . $demotee["id"]); // DT reputation system start $reput = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}reputation_settings WHERE id =1"); $setrep = mysqli_fetch_array($reput); $plus = $setrep["rep_minrep"]; if ($setrep["rep_is_online"] == FALSE) { //do nothing } else { @mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET reputation = reputation - '{$plus}' WHERE id='{$demotee['id']}'"); } // DT reputation system end // send pm bad users 2 $sub = sqlesc("Low Ratio Warning Two!"); $msg = sqlesc($art["wb_text_two"]); send_pm(0, $demotee[id], $sub, $msg); // add warn symbol 2 if ($ban["wb_warn"] == TRUE) { $warnreason = "Low Ratio Warning"; $warnaddedby = "System"; $added = warn_expiration(mktime(date('H') + 2, date('i'), date('s'), date('m'), date('d') + addslashes($ban['wb_days_two']), date('Y'))); quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET warn="yes",warns=warns+1,warnreason="' . $warnreason . '",warnaddedby="' . $warnaddedby . '",warnadded="' . $added . '" WHERE id=' . $id); } } } // unwarn user who did improve $unwarnone = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id,rat_warn_time FROM {$utables} WHERE {$udownloaded} > " . $min_dl . " AND {$uuploaded}/{$udownloaded} > " . $ban["wb_one"] . " AND id_level=" . $ban["wb_rank"] . " AND rat_warn_level = 1 "); while ($unwarna = mysqli_fetch_assoc($unwarnone)) { $iid = $unwarna["id"]; quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET rat_warn_level=rat_warn_level-1 WHERE id=' . $iid); } // time date stuff $time_EE = 86400 * $ban['wb_days_two']; $time_FF = $time_BB - $time_EE; // find bad users 3 $demotelisttt = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id,rat_warn_time FROM {$utables} WHERE {$udownloaded} > " . $min_dl . " AND {$uuploaded}/{$udownloaded} <= " . $ban["wb_three"] . " AND id_level=" . $ban["wb_rank"] . " AND rat_warn_level = 2 "); while ($demoteee = mysqli_fetch_assoc($demotelisttt)) { $time_GG = strtotime($demoteee["rat_warn_time"]); if ($time_GG <= $time_FF) { // warn bad users 3 do_sqlquery("UPDATE {$TABLE_PREFIX}users SET rat_warn_level = 3 , rat_warn_time = NOW() WHERE id=" . $demoteee["id"]); // DT reputation system start $reput = do_sqlquery("SELECT * FROM {$TABLE_PREFIX}reputation_settings WHERE id =1"); $setrep = mysqli_fetch_array($reput); $plus = $setrep["rep_minrep"]; if ($setrep["rep_is_online"] == FALSE) { //do nothing } else { @mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET reputation = reputation - '{$plus}' WHERE id='{$demoteee['id']}'"); } // DT reputation system end // send pm bad users 3 $sub = sqlesc("Final Low Ratio Warning!"); $msg = sqlesc($art["wb_text_fin"]); send_pm(0, $demoteee[id], $sub, $msg); // add warn symbol 3 if ($ban["wb_warn"] == TRUE) { $id = $demoteee["id"]; $warnreason = "Low Ratio Warning"; $warnaddedby = "System"; $added = warn_expiration(mktime(date('H') + 2, date('i'), date('s'), date('m'), date('d') + addslashes($ban['wb_days_fin']), date('Y'))); quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET warn="yes",warns=warns+1,warnreason="' . $warnreason . '",warnaddedby="' . $warnaddedby . '",warnadded="' . $added . '" WHERE id=' . $id); } } } // unwarn user who did improve 2 $unwarntwo = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id,rat_warn_time FROM {$utables} WHERE {$udownloaded} > " . $min_dl . " AND {$uuploaded}/{$udownloaded} > " . $ban["wb_two"] . " AND id_level=" . $ban["wb_rank"] . " AND rat_warn_level = 2 "); while ($unwarnb = mysqli_fetch_assoc($unwarntwo)) { $oid = $unwarnb["id"]; quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET rat_warn_level=rat_warn_level-2 WHERE id=' . $oid); } // time date stuff $time_HH = 86400 * $ban['wb_days_fin']; $time_II = $time_BB - $time_HH; // find bad users 4 $demotelistttt = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id,rat_warn_time FROM {$utables} WHERE {$udownloaded} > " . $min_dl . " AND {$uuploaded}/{$udownloaded} <= " . $ban["wb_fin"] . " AND id_level=" . $ban["wb_rank"] . " AND rat_warn_level = 3 "); while ($demoteeee = mysqli_fetch_assoc($demotelistttt)) { $time_JJ = strtotime($demoteeee["rat_warn_time"]); if ($time_JJ <= $time_II) { // ban bad users 4 if ($btit_settings["en_sys"] == TRUE) { do_sqlquery("UPDATE {$TABLE_PREFIX}users SET rat_warn_level = 4 ,rat_warn_time = NOW(), id_level=" . $btit_settings["dm_id"] . " WHERE id=" . $demoteeee["id"]); } else { do_sqlquery("UPDATE {$TABLE_PREFIX}users SET rat_warn_level = 4 ,rat_warn_time = NOW(), bandt='yes' WHERE id=" . $demoteeee["id"]); } } } // unwarn user who did improve last $unwarnthree = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT id,rat_warn_time FROM {$utables} WHERE {$udownloaded} > " . $min_dl . " AND {$uuploaded}/{$udownloaded} > " . $ban["wb_three"] . " AND id_level=" . $ban["wb_rank"] . " AND rat_warn_level = 3 "); while ($unwarnc = mysqli_fetch_assoc($unwarnthree)) { $lid = $unwarnc["id"]; quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET rat_warn_level=rat_warn_level-3 WHERE id=' . $lid); } } } // warn-ban system with acp end // optimize peers table quickQuery("OPTIMIZE TABLE {$TABLE_PREFIX}peers"); // delete readposts when topic don't exist or deleted *** should be done by delete, just in case quickQuery("DELETE readposts FROM {$TABLE_PREFIX}readposts LEFT JOIN topics ON readposts.topicid = topics.id WHERE topics.id IS NULL"); // delete readposts when users was deleted *** should be done by delete, just in case quickQuery("DELETE readposts FROM {$TABLE_PREFIX}readposts LEFT JOIN users ON readposts.userid = users.id WHERE users.id IS NULL"); // deleting orphan image in captcha folder (if image code is enabled) $CAPTCHA_FOLDER = realpath("{$CURRENTPATH}/../{$CAPTCHA_FOLDER}"); if ($dir = @opendir($CAPTCHA_FOLDER . "/")) { while (false !== ($file = @readdir($dir))) { if ($ext = substr(strrchr($file, "."), 1) == "png") { unlink("{$CAPTCHA_FOLDER}/{$file}"); } } @closedir($dir); } quickQuery("UPDATE `{$TABLE_PREFIX}users` SET `birthday_bonus`=0 WHERE DAYOFMONTH(`dob`)!=" . date('j')); $res = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT `u`.`id`, `u`.`dob`,`l`.`language_url` FROM `{$TABLE_PREFIX}users` `u` LEFT JOIN `language` `l` ON `u`.`language`=`l`.`id` WHERE DAYOFMONTH(`u`.`dob`)=" . date('j') . " AND MONTH(`u`.`dob`)=" . date('n') . " AND `u`.`dob`!=CURDATE() AND `u`.`birthday_bonus`=0 ORDER BY `l`.`language_url` ASC"); if (@mysqli_num_rows($res) > 0) { global $THIS_BASEPATH; $firstrun = 1; $englang = "language/english"; $templang = $englang; require_once $THIS_BASEPATH . "/" . $englang . "/lang_main.php"; while ($row = mysqli_fetch_assoc($res)) { if ($row["language_url"] != $templang) { if ($firstrun != 1) { // Reset the language to English before loading the new language require_once $THIS_BASEPATH . "/" . $englang . "/lang_main.php"; } // Load the new language etc. require_once $THIS_BASEPATH . "/" . $row["language_url"] . "/lang_main.php"; $templang = $row["language_url"]; $firstrun = 0; } $dob = explode("-", $row["dob"]); $age = userage($dob[0], $dob[1], $dob[2]); $bonus = round($age * $btit_settings["birthday_bonus"] * 1073741824); $query1 = "UPDATE `{$TABLE_PREFIX}users` SET `uploaded`=`uploaded`+{$bonus}, `birthday_bonus`=1 WHERE `id`=" . $row["id"]; quickQuery($query1); send_pm(0, $row["id"], addslashes($language["HB_SUBJECT"]), addslashes($language["HB_MESSAGE_1"] . makesize($bonus) . $language["HB_MESSAGE_2"] . $btit_settings["birthday_bonus"] . $language["HB_MESSAGE_3"])); } } //timed rank $datetimedt = date("Y-m-d H:i:s"); $rankstats = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM {$TABLE_PREFIX}users WHERE timed_rank < '{$datetimedt}' AND rank_switch='yes'"); while ($arrdt = mysqli_fetch_assoc($rankstats)) { if (mysqli_num_rows($rankstats) > 0) { $res6 = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT level FROM {$TABLE_PREFIX}users_level WHERE id ='{$arrdt['old_rank']}'"); $arr6 = mysqli_fetch_assoc($res6); $oldrank = $arr6[level]; $subj = sqlesc("Your timed rank is expired !"); $msg = sqlesc("Your timed rank is expired !\n\n Your rank did changed back to " . $oldrank . "\n\n [color=red]This is a automatic system message , so DO NOT reply ![/color]"); send_pm(0, $arrdt["id"], $subj, $msg); mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET rank_switch='no', id_level = old_rank WHERE id='{$arrdt['id']}'") or sqlerr(); } } //timed rank end //begin invitation system by dodge global $INV_EXPIRES; $deadtime = $INV_EXPIRES * 86400; $user = do_sqlquery("SELECT inviter FROM {$TABLE_PREFIX}invitations WHERE time_invited < DATE_SUB(NOW(), INTERVAL {$deadtime} SECOND)"); @($arr = mysqli_fetch_assoc($user)); if (mysqli_num_rows($user) > 0) { mysqli_query($GLOBALS["___mysqli_ston"], "UPDATE {$TABLE_PREFIX}users SET invitations=invitations+1 WHERE id = '" . $arr["inviter"] . "'"); mysqli_query($GLOBALS["___mysqli_ston"], "DELETE FROM {$TABLE_PREFIX}invitations WHERE inviter = '" . $arr["inviter"] . "' AND time_invited < DATE_SUB(NOW(), INTERVAL {$deadtime} SECOND)"); } //end invitation system do_updateranks(); // auto ext update $num_torrents_to_update = 5; $torrents = get_result("SELECT `announces`, `info_hash` FROM `{$TABLE_PREFIX}files` WHERE `external`='yes' ORDER BY `lastupdate` DESC LIMIT " . $num_torrents_to_update); if (count($torrents) > 0) { require_once "getscrape.php"; for ($i = 0; $i < count($torrents); $i++) { $announces = @unserialize($torrents[$i]['announces']) ? unserialize($torrents[$i]['announces']) : array(); if (count($announces) > 0) { $keys = array_keys($announces); $random = mt_rand(0, count($keys) - 1); $url = $keys[$random]; scrape($url, $torrents[$i]['info_hash']); } } } // auto ext update // OK We're finished, let's reset max_execution_time and memory_limit back to the php.ini defaults @ini_restore("max_execution_time"); @ini_restore("memory_limit"); }
function do_sanity() { global $PRIVATE_ANNOUNCE, $TORRENTSDIR, $CURRENTPATH, $LIVESTATS, $LOG_HISTORY, $db; // SANITY FOR TORRENTS $results = $db->query("SELECT summary.info_hash, seeds, leechers, dlbytes, namemap.filename FROM summary LEFT JOIN namemap ON summary.info_hash = namemap.info_hash WHERE namemap.external = 'no'"); $i = 0; while ($row = $results->fetch_row()) { list($hash, $seeders, $leechers, $bytes, $filename) = $row; $timeout = vars::$timestamp - intval($GLOBALS["report_interval"]); // for testing purpose -- begin $resupd = $db->query("SELECT * FROM peers WHERE lastupdate < " . $timeout . " AND infohash = '" . $hash . "'"); if ($resupd->num_rows > 0) { while ($resupdate = $resupd->fetch_array(MYSQLI_BOTH)) { $uploaded = max(0, (int) $resupdate["uploaded"]); $downloaded = max(0, (int) $resupdate["downloaded"]); $pid = $db->real_escape_string($resupdate["pid"]); $ip = $db->real_escape_string($resupdate["ip"]); // update user->peer stats only if not livestat if (!$LIVESTATS) { if ($PRIVATE_ANNOUNCE) { quickQuery("UPDATE users SET uploaded = uploaded + " . $uploaded . ", downloaded = downloaded + " . $downloaded . " WHERE pid = '" . $pid . "' AND id > 1 LIMIT 1"); } else { // ip quickQuery("UPDATE users SET uploaded = uploaded + " . $uploaded . ", downloaded = downloaded + " . $downloaded . " WHERE cip = '" . $ip . "' AND id > 1 LIMIT 1"); } } // update dead peer to non active in history table if ($LOG_HISTORY) { $resuser = $db->query("SELECT id FROM users WHERE " . ($PRIVATE_ANNOUNCE ? "pid = '" . $pid . "'" : "cip = '" . $ip . "'") . " ORDER BY lastconnect DESC LIMIT 1"); $curu = @$resuser->fetch_row(); quickquery("UPDATE history SET active = 'no' WHERE uid = " . (int) $curu[0] . " AND infohash = '" . $hash . "'"); } } } // for testing purpose -- end quickQuery("DELETE FROM peers WHERE lastupdate < " . $timeout . " AND infohash = '" . $hash . "'"); quickQuery("UPDATE summary SET lastcycle = '" . vars::$timestamp . "' WHERE info_hash = '" . $hash . "'"); $results2 = $db->query("SELECT status, COUNT(status) FROM peers WHERE infohash = '" . $hash . "' GROUP BY status"); $counts = array(); while ($row = $results2->fetch_row()) { $counts[$row[0]] = 0 + (int) $row[1]; } quickQuery("UPDATE summary SET leechers = " . (isset($counts["leecher"]) ? $counts["leecher"] : 0) . ", seeds = " . (isset($counts["seeder"]) ? $counts["seeder"] : 0) . " WHERE info_hash = '" . $hash . "'"); if ($bytes < 0) { quickQuery("UPDATE summary SET dlbytes = 0 WHERE info_hash = '" . $hash . "'"); } } // END TORRENT'S SANITY // optimize peers table quickQuery("OPTIMIZE TABLE peers"); // delete readposts when topic don't exist or deleted *** should be done by delete, just in case quickQuery("DELETE readposts FROM readposts LEFT JOIN topics ON readposts.topicid = topics.id WHERE topics.id IS NULL"); // delete readposts when users was deleted *** should be done by delete, just in case quickQuery("DELETE readposts FROM readposts LEFT JOIN users ON readposts.userid = users.id WHERE users.id IS NULL"); // deleting orphan image in torrent's folder (if image code is enabled) $tordir = realpath($CURRENTPATH . "/../" . $TORRENTSDIR); if ($dir = @opendir($tordir . "/")) { } while (false !== ($file = @readdir($dir))) { if ($ext = substr(strrchr($file, "."), 1) == "png") { unlink($tordir . "/" . $file); } } @closedir($dir); }
// CyBerFuN xBTiT Fully MoDDeD v1.2 // https://cyberfun-xbtit.svn.sourceforge.net/svnroot/cyberfun-xbtit # first check for direct linking if (!defined('IN_BTIT')) { die('non direct access!'); } # then require functions (is this needed?) require_once $THIS_BASEPATH . '/include/functions.php'; # connect to db dbconn(); # check if allowed and die if not if ($CURUSER['edit_torrents'] == 'no' && $CURUSER['edit_users'] == 'no') { die('Unauthorised access!'); } # inits $warn = addslashes($_POST['warn']); $id = (int) $_GET['id']; $returnto = $_POST["returnto"]; $warneduser = get_result('SELECT username FROM `' . $TABLE_PREFIX . 'users` WHERE `id`=' . $id . ' LIMIT 1;', false, 3600); $warneduser = $warneduser[0]['username']; $subj = sqlesc('Your Warning is canceled !'); $msg = sqlesc('[b]We did cancel your Warning!\\n\\r' . $CURUSER['username'] . '[/b].'); # process it quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET warn="no", warns=warns-1 WHERE id=' . $id); # message him quickQuery('INSERT INTO ' . $TABLE_PREFIX . 'messages (sender, receiver, added, msg, subject) VALUES(0,' . $id . ',UNIX_TIMESTAMP(),' . $msg . ',' . $subj . ')') or sqlerr(__FILE__, __LINE__); # log it write_log("Warning canceled for " . $warneduser . " by: " . $CURUSER['username'] . "", " Warning removed"); # send back to original page header('Location: ' . $returnto); die;
/** * returns true if this member can move/update an item to a given category, * false if not (see comments fot the tests that are executed) * * @param itemid * @param newcat (can also be of form 'newcat-x' with x=blogid) */ function canUpdateItem($itemid, $newcat) { global $manager; // item does not exists -> NOK if (!$manager->existsItem($itemid, 1, 1)) { return 0; } // cannot alter item -> NOK if (!$this->canAlterItem($itemid)) { return 0; } // if this is a 'newcat' style newcat // no blog admin of destination blog -> NOK // blog admin of destination blog -> OK if (strstr($newcat, 'newcat')) { // get blogid list($blogid) = sscanf($newcat, 'newcat-%d'); return $this->blogAdminRights($blogid); } // category does not exist -> NOK if (!$manager->existsCategory($newcat)) { return 0; } // get item $item =& $manager->getItem($itemid, 1, 1); // old catid = new catid -> OK if ($item['catid'] == $newcat) { return 1; } // not a valid category -> NOK $validCat = quickQuery('SELECT COUNT(*) AS result FROM ' . sql_table('category') . ' WHERE catid=' . intval($newcat)); if (!$validCat) { return 0; } // get destination blog $source_blogid = getBlogIDFromItemID($itemid); $dest_blogid = getBlogIDFromCatID($newcat); // not a team member of destination blog -> NOK if (!$this->teamRights($dest_blogid)) { return 0; } // if member is author of item -> OK if ($item['authorid'] == $this->getID()) { return 1; } // if member has admin rights on both blogs: OK if ($this->blogAdminRights($dest_blogid) && $this->blogAdminRights($source_blogid)) { return 1; } // all other cases: NOK return 0; }
function getNameFromId($id) { return quickQuery('SELECT tdname as result FROM ' . sql_table('template_desc') . ' WHERE tdnumber=' . intval($id)); }
function check_online($session_id, $location) { global $TABLE_PREFIX, $CURUSER; $location = sqlesc($location); $ip = getip(); $uid = max(1, (int) $CURUSER['uid']); $suffix = sqlesc($CURUSER['suffixcolor']); $prefix = sqlesc($CURUSER['prefixcolor']); $uname = sqlesc($CURUSER['username']); $ugroup = sqlesc($CURUSER['level']); if ($uid == 1) { $where = "WHERE session_id='{$session_id}'"; } else { $where = "WHERE user_id='{$uid}' OR session_id='{$session_id}'"; } @quickQuery("UPDATE {$TABLE_PREFIX}online SET session_id='{$session_id}', user_name={$uname}, user_group={$ugroup}, prefixcolor={$prefix}, suffixcolor={$suffix}, location={$location}, user_id={$uid}, lastaction=UNIX_TIMESTAMP() {$where}"); // record don't already exist, then insert it if (mysql_affected_rows() == 0) { @quickQuery("UPDATE {$TABLE_PREFIX}users SET lastconnect=NOW() WHERE id={$uid} AND id>1"); @quickQuery("INSERT INTO {$TABLE_PREFIX}online SET session_id='{$session_id}', user_name={$uname}, user_group={$ugroup}, prefixcolor={$prefix}, suffixcolor={$suffix}, user_id={$uid}, user_ip='{$ip}', location={$location}, lastaction=UNIX_TIMESTAMP()"); } $timeout = time() - 900; // 15 minutes // @quickQuery("UPDATE {$TABLE_PREFIX}users SET lastconnect=NOW() WHERE id IN (SELECT user_id FROM {$TABLE_PREFIX}online ol WHERE ol.lastaction<$timeout AND ol.user_id>1)"); @quickQuery("UPDATE {$TABLE_PREFIX}users u INNER JOIN {$TABLE_PREFIX}online ol ON ol.user_id = u.id SET u.lastconnect=NOW(), u.cip=ol.user_ip, u.lip=INET_ATON(ol.user_ip) WHERE ol.lastaction<{$timeout} AND ol.user_id>1"); @quickQuery("DELETE FROM {$TABLE_PREFIX}online WHERE lastaction<{$timeout}"); }
//////////////////////////////////////////////////////////////////////////////////// # first check for direct linking if (!defined('IN_BTIT')) { die('non direct access!'); } # then require functions (is this needed?) require_once $THIS_BASEPATH . '/include/functions.php'; require_once load_language("lang_userdetails.php"); # connect to db dbconn(); # check if allowed and die if not if ($CURUSER['edit_torrents'] == 'no' && $CURUSER['edit_users'] == 'no') { die('Unauthorised access!'); } # inits $booted = addslashes($_POST['booted']); $id = isset($_GET['id']) ? (int) $_GET['id'] : 0; $returnto = $_POST["returnto"]; $booteduser = get_result('SELECT username FROM `' . $TABLE_PREFIX . 'users` WHERE `id`=' . $id . ' LIMIT 1;', false, 3600); $booteduser = $booteduser[0]['username']; $subj = sqlesc($language["BOOT_RM2"]); $msg = sqlesc('' . $language["BOOT_RM1"] . ' ' . $language["BOOT_LOG1"] . ' ' . $CURUSER['username'] . '[/b].'); # process it quickQuery('UPDATE ' . $TABLE_PREFIX . 'users SET booted="no" WHERE id=' . $id); # message him send_pm(0, $id, $subj, $msg); # log it write_log("" . $language["BOOT_LOG"] . " " . $booteduser . " " . $language["BOOT_LOG1"] . " " . $CURUSER['username'] . "", "delete"); # send back to original page header('Location: ' . $returnto); die;
function runSpeed($info_hash, $delta) { require "config.php"; //stick in our latest data before we calc it out quickQuery("INSERT IGNORE INTO " . $prefix . "timestamps (info_hash, bytes, delta, sequence) SELECT '{$info_hash}' AS info_hash, dlbytes, UNIX_TIMESTAMP() - lastSpeedCycle, NULL FROM " . $prefix . "summary WHERE info_hash=\"{$info_hash}\""); // mysql blows sometimes so we have to read the data into php before updating it $results = mysql_query('SELECT (MAX(bytes)-MIN(bytes))/SUM(delta), COUNT(*), MIN(sequence) FROM ' . $prefix . 'timestamps WHERE info_hash="' . $info_hash . '"'); $data = mysql_fetch_row($results); $results2 = mysql_query('SELECT ' . $prefix . 'summary.leechers FROM ' . $prefix . 'summary WHERE info_hash="' . $info_hash . '"'); $data2 = mysql_fetch_row($results2); if ($data2[0] == 0) { //if no leechers, speed is zero $data[0] = 0; } $results3 = mysql_query("SELECT MIN(d1.bytes), MAX(d1.bytes) FROM (SELECT bytes FROM " . $prefix . "timestamps WHERE info_hash='" . $info_hash . "' ORDER BY sequence DESC LIMIT 5) AS d1"); $data3 = mysql_fetch_row($results3); //if the last 5 updates from clients show the same bytes, it's probably stalled, set speed to zero if ($data3[0] == $data3[1]) { $data[0] = 0; } summaryAdd("speed", $data[0], true); summaryAdd("lastSpeedCycle", "UNIX_TIMESTAMP()", true); // if we have more than 20 drop the rest //if ($data[1] == 21) //quickQuery("DELETE FROM timestamps WHERE info_hash=\"$info_hash\" AND sequence=${data[2]}"); if ($data[1] > 21) { // This query requires MySQL 4.0.x, but should rarely be used. quickQuery('DELETE FROM ' . $prefix . 'timestamps WHERE info_hash="' . $info_hash . '" ORDER BY sequence LIMIT ' . ($data['1'] - 20)); } }
function action_itemview($bid = 0, $msg = '') { global $CONF, $oPluginAdmin; if (empty($bid)) { if (getVar('blogid')) { $bid = intGetVar('blogid'); } else { $bid = intval($CONF['DefaultBlog']); } } else { $bid = intval($bid); } $oPluginAdmin->start(); $printData = '<h2>' . _ADMIN_AREA_TITLE . '</h2>' . '<ul style="list-style:none;">' . ' <li>' . ' <a href="' . $this->pediturl . '">' . _OPTION_SETTING . ' </a>' . ' </li>' . ' <li>' . ' <a href="' . $this->adminurl . 'index.php?action=blogview">' . _FOR_BLOG_SETTING . ' </a>' . ' </li>' . ' <li>' . ' <a href="' . $this->adminurl . 'index.php?action=categoryview&blogid=' . $bid . '">' . _FOR_CATEGORY_SETTING . ' </a>' . ' </li>' . ' <li>' . ' <a href="' . $this->adminurl . 'index.php?action=memberview">' . _FOR_MEMBER_SETTING . ' </a>' . ' </li>' . '</ul>' . '<p><h3>' . $this->_hsc($msg) . '</h3>'; echo $printData; unset($printData); $this->print_tablehead(_LISTS_TITLE, _LISTS_ITEM_DESC); $query = 'SELECT %s,%s,%s FROM %s WHERE iblog = %d ORDER BY itime DESC'; $query = sprintf($query, ititle, inumber, ibody, sql_table('item'), $bid); $res = sql_query($query); while ($i = mysql_fetch_object($res)) { $query = 'SELECT obj_name as result FROM %s WHERE obj_param = "item" AND obj_id = %d'; $query = sprintf($query, sql_table('plug_customurl'), intval($i->inumber)); $temp_res = quickQuery($query); $ipath = $this->_hsc(substr($temp_res, 0, -5)); $data = array('oid' => intval($i->inumber), 'obd' => $bid, 'opr' => 'item', 'name' => $this->_hsc($i->ititle), 'ret' => 'itemview', 'ed_URL' => $this->editurl . 'index.php?action=itemedit' . '&itemid=' . intval($i->inumber), 'path' => $ipath); if (extension_loaded('mbstring')) { $data['desc'] = $this->_hsc(mb_substr(strip_tags($i->ibody), 0, 80)); } else { $this->_hsc(substr(strip_tags($i->ibody), 0, 80)); } $this->print_tablerow($data); } echo '</tbody></table></p>'; unset($query); $oPluginAdmin->end(); }
function uplMod($uid, $by, $exact = false) { global $TABLE_PREFIX; if ($exact && $by < 0) { return false; } # set to negative if (!$exact && $by == 0) { return false; } # modify to same quickQuery('UPDATE `' . $TABLE_PREFIX . 'users` SET uploaded=' . (!$exact ? 'uploaded+' : '') . $by . ' WHERE id=' . $uid . ' LIMIT 1;'); return true; }
function start($info_hash, $ip, $port, $peer_id, $left, $uploaded, $clientVer) { if ($left == 0) { $status = "seeder"; } else { $status = "leecher"; } if (@isFireWalled($info_hash, $peer_id, $ip, $port)) { $nat = "'Y'"; } else { $nat = "'N'"; } $results = @mysql_query("INSERT INTO x{$info_hash} SET peer_id=\"{$peer_id}\", port=\"{$port}\", ip=\"{$ip}\", lastupdate=UNIX_TIMESTAMP(), bytes=\"{$left}\", status=\"{$status}\", natuser={$nat}, uploaded={$uploaded}, clientversion=\"{$clientVer}\""); // Special case: duplicated peer_id. if (!$results) { $error = mysql_error(); if (stristr($error, "key")) { // Duplicate peer_id! Check IP address $peer = getPeerInfo($peer_id, $info_hash); if ($ip == $peer["ip"]) { // Same IP address. Tolerate this error. updatePeer($peer_id, $info_hash); return "WHERE natuser='******'"; } //showError("Duplicated peer_id or changed IP address. Please restart BitTorrent."); // Different IP address. Assume they were disconnected, and alter the IP address. quickQuery("UPDATE x{$info_hash} SET ip=\"{$ip}\", uploaded={$uploaded}, clientversion=\"{$clientVer}\" WHERE peer_id=\"{$peer_id}\""); return "WHERE natuser='******'"; } error_log("PHPBTTracker: start: " . $error); showError("Tracker/database error. The details are in the error log."); } $GLOBALS["trackerid"] = mysql_insert_id(); if ($GLOBALS["peercaching"]) { $compact = mysql_real_escape_string(pack('Nn', ip2long($ip), $port)); $peerid = mysql_real_escape_string('2:ip' . strlen($ip) . ':' . $ip . '7:peer id20:' . hex2bin($peer_id) . "4:porti{$port}e"); $no_peerid = mysql_real_escape_string('2:ip' . strlen($ip) . ':' . $ip . "4:porti{$port}e"); mysql_query("INSERT INTO y{$info_hash} SET sequence=\"{$GLOBALS["trackerid"]}\", compact=\"{$compact}\", with_peerid=\"{$peerid}\", without_peerid=\"{$no_peerid}\""); // Let's just assume success... :/ } if ($left == 0) { summaryAdd("seeds", 1); return "WHERE status=\"leecher\" AND natuser='******'"; } else { summaryAdd("leechers", 1); return "WHERE natuser='******'"; } }