Oppaitime'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

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