BioTorrents.de’s version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tools.class.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. # todo: Check strick equality gently
  3. class Tools
  4. {
  5. /**
  6. * Returns true if given IP is banned.
  7. *
  8. * @param string $IP
  9. */
  10. public static function site_ban_ip($IP)
  11. {
  12. global $Debug;
  13. $A = substr($IP, 0, strcspn($IP, '.:'));
  14. $IPNum = Tools::ip_to_unsigned($IP);
  15. $IPBans = G::$Cache->get_value('ip_bans_'.$A);
  16. if (!is_array($IPBans)) {
  17. $SQL = sprintf("
  18. SELECT ID, FromIP, ToIP
  19. FROM ip_bans
  20. WHERE FromIP BETWEEN %d << 24 AND (%d << 24) - 1", $A, $A + 1);
  21. $QueryID = G::$DB->get_query_id();
  22. G::$DB->query($SQL);
  23. $IPBans = G::$DB->to_array(0, MYSQLI_NUM);
  24. G::$DB->set_query_id($QueryID);
  25. G::$Cache->cache_value('ip_bans_'.$A, $IPBans, 0);
  26. }
  27. $Debug->log_var($IPBans, 'IP bans for class '.$A);
  28. foreach ($IPBans as $Index => $IPBan) {
  29. list($ID, $FromIP, $ToIP) = $IPBan;
  30. if ($IPNum >= $FromIP && $IPNum <= $ToIP) {
  31. return true;
  32. }
  33. }
  34. return false;
  35. }
  36. /**
  37. * Returns the unsigned form of an IP address.
  38. *
  39. * @param string $IP The IP address x.x.x.x
  40. * @return string the long it represents.
  41. */
  42. public static function ip_to_unsigned($IP)
  43. {
  44. $IPnum = sprintf('%u', ip2long($IP));
  45. if (!$IPnum) {
  46. // Try to encode as IPv6 (stolen from stackoverflow)
  47. // Note that this is *wrong* and because of PHP's wankery stops being accurate after the most significant 16 digits or so
  48. // But since this is only used for geolocation and IPv6 blocks are allocated in huge numbers, it's still fine
  49. $IPnum = '';
  50. foreach (unpack('C*', inet_pton($IP)) as $byte) {
  51. $IPnum .= str_pad(decbin($byte), 8, "0", STR_PAD_LEFT);
  52. }
  53. $IPnum = base_convert(ltrim($IPnum, '0'), 2, 10);
  54. }
  55. return $IPnum;
  56. }
  57. /**
  58. * Geolocate an IP address using the database
  59. *
  60. * @param $IP the ip to fetch the country for
  61. * @return the country of origin
  62. */
  63. public static function geoip($IP)
  64. {
  65. static $IPs = [];
  66. if (isset($IPs[$IP])) {
  67. return $IPs[$IP];
  68. }
  69. if (is_number($IP)) {
  70. $Long = $IP;
  71. } else {
  72. $Long = Tools::ip_to_unsigned($IP);
  73. }
  74. if (!$Long || $Long == 2130706433) { // No need to check cc for 127.0.0.1
  75. return false;
  76. }
  77. $QueryID = G::$DB->get_query_id();
  78. G::$DB->query("
  79. SELECT EndIP, Code
  80. FROM geoip_country
  81. WHERE $Long >= StartIP
  82. ORDER BY StartIP DESC
  83. LIMIT 1");
  84. if ((!list($EndIP, $Country) = G::$DB->next_record()) || $EndIP < $Long) {
  85. $Country = '?';
  86. }
  87. G::$DB->set_query_id($QueryID);
  88. $IPs[$IP] = $Country;
  89. return $Country;
  90. }
  91. /**
  92. * Gets the hostname for an IP address
  93. *
  94. * @param $IP the IP to get the hostname for
  95. * @return hostname fetched
  96. */
  97. public static function get_host_by_ip($IP)
  98. {
  99. $testar = explode('.', $IP);
  100. if (count($testar) != 4) {
  101. return $IP;
  102. }
  103. for ($i = 0; $i < 4; ++$i) {
  104. if (!is_numeric($testar[$i])) {
  105. return $IP;
  106. }
  107. }
  108. $host = `host -W 1 $IP`;
  109. return ($host ? end(explode(' ', $host)) : $IP);
  110. }
  111. /**
  112. * Gets an hostname using AJAX
  113. *
  114. * @param $IP the IP to fetch
  115. * @return a span with JavaScript code
  116. */
  117. public static function get_host_by_ajax($IP)
  118. {
  119. static $ID = 0;
  120. ++$ID;
  121. return '<span id="host_'.$ID.'">Resolving host...<script type="text/javascript">ajax.get(\'tools.php?action=get_host&ip='.$IP.'\',function(host) {$(\'#host_'.$ID.'\').raw().innerHTML=host;});</script></span>';
  122. }
  123. /**
  124. * Looks up the full host of an IP address, by system call.
  125. * Used as the server-side counterpart to get_host_by_ajax.
  126. *
  127. * @param string $IP The IP address to look up.
  128. * @return string the host.
  129. */
  130. public static function lookup_ip($IP)
  131. {
  132. // todo: Use the G::$Cache
  133. $Output = explode(' ', shell_exec('host -W 1 '.escapeshellarg($IP)));
  134. if (count($Output) == 1 && empty($Output[0])) {
  135. return '';
  136. }
  137. if (count($Output) != 5) {
  138. return false;
  139. }
  140. if ($Output[2].' '.$Output[3] == 'not found:') {
  141. return false;
  142. }
  143. return trim($Output[4]);
  144. }
  145. /**
  146. * Format an IP address with links to IP history.
  147. *
  148. * @param string IP
  149. * @return string The HTML
  150. */
  151. public static function display_ip($IP)
  152. {
  153. $Line = display_str($IP).' ('.Tools::get_country_code_by_ajax($IP).') ';
  154. $Line .= '<a href="user.php?action=search&amp;ip_history=on&amp;ip='.display_str($IP).'&amp;matchtype=strict" title="Search" class="brackets tooltip">S</a>';
  155. return $Line;
  156. }
  157. public static function get_country_code_by_ajax($IP)
  158. {
  159. static $ID = 0;
  160. ++$ID;
  161. return '<span id="cc_'.$ID.'">Resolving CC...<script type="text/javascript">ajax.get(\'tools.php?action=get_cc&ip='.$IP.'\', function(cc) {$(\'#cc_'.$ID.'\').raw().innerHTML = cc;});</script></span>';
  162. }
  163. /**
  164. * Disable an array of users.
  165. *
  166. * @param array $UserIDs (You can also send it one ID as an int, because fuck types)
  167. * @param BanReason 0 - Unknown, 1 - Manual, 2 - Ratio, 3 - Inactive, 4 - Unused.
  168. */
  169. public static function disable_users($UserIDs, $AdminComment, $BanReason = 1)
  170. {
  171. $QueryID = G::$DB->get_query_id();
  172. if (!is_array($UserIDs)) {
  173. $UserIDs = array($UserIDs);
  174. }
  175. G::$DB->query("
  176. UPDATE users_info AS i
  177. JOIN users_main AS m ON m.ID = i.UserID
  178. SET m.Enabled = '2',
  179. m.can_leech = '0',
  180. i.AdminComment = CONCAT('".sqltime()." - ".($AdminComment ? $AdminComment : 'Disabled by system')."\n\n', i.AdminComment),
  181. i.BanDate = NOW(),
  182. i.BanReason = '$BanReason',
  183. i.RatioWatchDownload = ".($BanReason == 2 ? 'm.Downloaded' : "'0'")."
  184. WHERE m.ID IN(".implode(',', $UserIDs).') ');
  185. G::$Cache->decrement('stats_user_count', G::$DB->affected_rows());
  186. foreach ($UserIDs as $UserID) {
  187. G::$Cache->delete_value("enabled_$UserID");
  188. G::$Cache->delete_value("user_info_$UserID");
  189. G::$Cache->delete_value("user_info_heavy_$UserID");
  190. G::$Cache->delete_value("user_stats_$UserID");
  191. G::$DB->query("
  192. SELECT SessionID
  193. FROM users_sessions
  194. WHERE UserID = '$UserID'
  195. AND Active = 1");
  196. while (list($SessionID) = G::$DB->next_record()) {
  197. G::$Cache->delete_value("session_$UserID"."_$SessionID");
  198. }
  199. G::$Cache->delete_value("users_sessions_$UserID");
  200. G::$DB->query("
  201. DELETE FROM users_sessions
  202. WHERE UserID = '$UserID'");
  203. }
  204. // Remove the users from the tracker.
  205. G::$DB->query('
  206. SELECT torrent_pass
  207. FROM users_main
  208. WHERE ID in ('.implode(', ', $UserIDs).')');
  209. $PassKeys = G::$DB->collect('torrent_pass');
  210. $Concat = '';
  211. foreach ($PassKeys as $PassKey) {
  212. if (strlen($Concat) > 3950) { // Ocelot's read buffer is 4 KiB and anything exceeding it is truncated
  213. Tracker::update_tracker('remove_users', array('passkeys' => $Concat));
  214. $Concat = $PassKey;
  215. } else {
  216. $Concat .= $PassKey;
  217. }
  218. }
  219. Tracker::update_tracker('remove_users', array('passkeys' => $Concat));
  220. G::$DB->set_query_id($QueryID);
  221. }
  222. /**
  223. * Warn a user.
  224. *
  225. * @param int $UserID
  226. * @param int $Duration length of warning in seconds
  227. * @param string $reason
  228. */
  229. public static function warn_user($UserID, $Duration, $Reason)
  230. {
  231. global $Time;
  232. $QueryID = G::$DB->get_query_id();
  233. G::$DB->query("
  234. SELECT Warned
  235. FROM users_info
  236. WHERE UserID = $UserID
  237. AND Warned IS NOT NULL");
  238. if (G::$DB->has_results()) {
  239. //User was already warned, appending new warning to old.
  240. list($OldDate) = G::$DB->next_record();
  241. $NewExpDate = date('Y-m-d H:i:s', strtotime($OldDate) + $Duration);
  242. Misc::send_pm(
  243. $UserID,
  244. 0,
  245. 'You have received multiple warnings.',
  246. "When you received your latest warning (set to expire on ".date('Y-m-d', (time() + $Duration)).'), you already had a different warning (set to expire on '.date('Y-m-d', strtotime($OldDate)).").\n\n Due to this collision, your warning status will now expire at $NewExpDate."
  247. );
  248. $AdminComment = date('Y-m-d')." - Warning (Clash) extended to expire at $NewExpDate by " . G::$LoggedUser['Username'] . "\nReason: $Reason\n\n";
  249. G::$DB->query('
  250. UPDATE users_info
  251. SET
  252. Warned = \''.db_string($NewExpDate).'\',
  253. WarnedTimes = WarnedTimes + 1,
  254. AdminComment = CONCAT(\''.db_string($AdminComment).'\', AdminComment)
  255. WHERE UserID = \''.db_string($UserID).'\'');
  256. } else {
  257. //Not changing, user was not already warned
  258. $WarnTime = time_plus($Duration);
  259. G::$Cache->begin_transaction("user_info_$UserID");
  260. G::$Cache->update_row(false, array('Warned' => $WarnTime));
  261. G::$Cache->commit_transaction(0);
  262. $AdminComment = date('Y-m-d')." - Warned until $WarnTime by " . G::$LoggedUser['Username'] . "\nReason: $Reason\n\n";
  263. G::$DB->query('
  264. UPDATE users_info
  265. SET
  266. Warned = \''.db_string($WarnTime).'\',
  267. WarnedTimes = WarnedTimes + 1,
  268. AdminComment = CONCAT(\''.db_string($AdminComment).'\', AdminComment)
  269. WHERE UserID = \''.db_string($UserID).'\'');
  270. }
  271. G::$DB->set_query_id($QueryID);
  272. }
  273. /**
  274. * Update the notes of a user
  275. * @param unknown $UserID ID of user
  276. * @param unknown $AdminComment Comment to update with
  277. */
  278. public static function update_user_notes($UserID, $AdminComment)
  279. {
  280. $QueryID = G::$DB->get_query_id();
  281. G::$DB->query('
  282. UPDATE users_info
  283. SET AdminComment = CONCAT(\''.db_string($AdminComment).'\', AdminComment)
  284. WHERE UserID = \''.db_string($UserID).'\'');
  285. G::$DB->set_query_id($QueryID);
  286. }
  287. /**
  288. * Check if an IP address is part of a given CIDR range.
  289. * @param string $CheckIP the IP address to be looked up
  290. * @param string $Subnet the CIDR subnet to be checked against
  291. */
  292. public static function check_cidr_range($CheckIP, $Subnet)
  293. {
  294. $IP = ip2long($CheckIP);
  295. $CIDR = split('/', $Subnet);
  296. $SubnetIP = ip2long($CIDR[0]);
  297. $SubnetMaskBits = 32 - $CIDR[1];
  298. return (($IP>>$SubnetMaskBits) == ($SubnetIP>>$SubnetMaskBits));
  299. }
  300. }