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.

script_start.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. <?php
  2. /*-- Script Start Class --------------------------------*/
  3. /*------------------------------------------------------*/
  4. /* This isnt really a class but a way to tie other */
  5. /* classes and functions used all over the site to the */
  6. /* page currently being displayed. */
  7. /*------------------------------------------------------*/
  8. /* The code that includes the main php files and */
  9. /* generates the page are at the bottom. */
  10. /*------------------------------------------------------*/
  11. /********************************************************/
  12. require 'config.php'; // The config contains all site wide configuration information
  13. // Check for common setup pitfalls
  14. if (!ini_get('short_open_tag')) {
  15. die('short_open_tag must be On in php.ini');
  16. }
  17. if (!extension_loaded('apcu')) {
  18. die('APCu extension not loaded');
  19. }
  20. // Deal with dumbasses
  21. if (isset($_REQUEST['info_hash']) && isset($_REQUEST['peer_id'])) {
  22. die('d14:failure reason40:Invalid .torrent, try downloading again.e');
  23. }
  24. require(SERVER_ROOT.'/classes/proxies.class.php');
  25. // Get the user's actual IP address if they're proxied.
  26. // Or if cloudflare is used
  27. if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
  28. $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
  29. }
  30. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])
  31. && proxyCheck($_SERVER['REMOTE_ADDR'])
  32. && filter_var(
  33. $_SERVER['HTTP_X_FORWARDED_FOR'],
  34. FILTER_VALIDATE_IP,
  35. FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
  36. )) {
  37. $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
  38. }
  39. if (!isset($argv) && !empty($_SERVER['HTTP_HOST'])) {
  40. // Skip this block if running from cli or if the browser is old and shitty
  41. // This should really be done in nginx config
  42. // todo: Remove
  43. if ($_SERVER['HTTP_HOST'] == 'www.'.SITE_DOMAIN) {
  44. header('Location: https://'.SITE_DOMAIN.$_SERVER['REQUEST_URI']);
  45. die();
  46. }
  47. }
  48. $ScriptStartTime = microtime(true); // To track how long a page takes to create
  49. if (!defined('PHP_WINDOWS_VERSION_MAJOR')) {
  50. $RUsage = getrusage();
  51. $CPUTimeStart = $RUsage['ru_utime.tv_sec'] * 1000000 + $RUsage['ru_utime.tv_usec'];
  52. }
  53. ob_start(); // Start a buffer, mainly in case there is a mysql error
  54. require SERVER_ROOT.'/classes/debug.class.php'; // Require the debug class
  55. require SERVER_ROOT.'/classes/mysql.class.php'; // Require the database wrapper
  56. require SERVER_ROOT.'/classes/cache.class.php'; // Require the caching class
  57. require SERVER_ROOT.'/classes/time.class.php'; // Require the time class
  58. require SERVER_ROOT.'/classes/paranoia.class.php'; // Require the paranoia check_paranoia function
  59. require SERVER_ROOT.'/classes/regex.php';
  60. require SERVER_ROOT.'/classes/util.php';
  61. $Debug = new DEBUG;
  62. $Debug->handle_errors();
  63. $Debug->set_flag('Debug constructed');
  64. $DB = new DB_MYSQL;
  65. $Cache = new Cache(MEMCACHED_SERVERS);
  66. // Autoload classes.
  67. require(SERVER_ROOT.'/classes/classloader.php');
  68. // Note: G::initialize is called twice.
  69. // This is necessary as the code inbetween (initialization of $LoggedUser) makes use of G::$DB and G::$Cache.
  70. // todo: Remove one of the calls once we're moving everything into that class
  71. G::initialize();
  72. //Begin browser identification
  73. $Browser = UserAgent::browser($_SERVER['HTTP_USER_AGENT']);
  74. $OperatingSystem = UserAgent::operating_system($_SERVER['HTTP_USER_AGENT']);
  75. $Debug->set_flag('start user handling');
  76. // Get classes
  77. // todo: Remove these globals, replace by calls into Users
  78. list($Classes, $ClassLevels) = Users::get_classes();
  79. //-- Load user information
  80. // User info is broken up into many sections
  81. // Heavy - Things that the site never has to look at if the user isn't logged in (as opposed to things like the class, donor status, etc)
  82. // Light - Things that appear in format_user
  83. // Stats - Uploaded and downloaded - can be updated by a script if you want super speed
  84. // Session data - Information about the specific session
  85. // Enabled - if the user's enabled or not
  86. // Permissions
  87. if (isset($_COOKIE['session']) && isset($_COOKIE['userid'])) {
  88. $SessionID = $_COOKIE['session'];
  89. $LoggedUser['ID'] = (int)$_COOKIE['userid'];
  90. $UserID = $LoggedUser['ID']; //todo: UserID should not be LoggedUser
  91. if (!$LoggedUser['ID'] || !$SessionID) {
  92. logout();
  93. }
  94. $UserSessions = $Cache->get_value("users_sessions_$UserID");
  95. if (!is_array($UserSessions)) {
  96. $DB->query(
  97. "
  98. SELECT
  99. SessionID,
  100. Browser,
  101. OperatingSystem,
  102. IP,
  103. LastUpdate
  104. FROM users_sessions
  105. WHERE UserID = '$UserID'
  106. AND Active = 1
  107. ORDER BY LastUpdate DESC"
  108. );
  109. $UserSessions = $DB->to_array('SessionID', MYSQLI_ASSOC);
  110. $Cache->cache_value("users_sessions_$UserID", $UserSessions, 0);
  111. }
  112. if (!array_key_exists($SessionID, $UserSessions)) {
  113. logout();
  114. }
  115. // Check if user is enabled
  116. $Enabled = $Cache->get_value('enabled_'.$LoggedUser['ID']);
  117. if ($Enabled === false) {
  118. $DB->query("
  119. SELECT Enabled
  120. FROM users_main
  121. WHERE ID = '$LoggedUser[ID]'");
  122. list($Enabled) = $DB->next_record();
  123. $Cache->cache_value('enabled_'.$LoggedUser['ID'], $Enabled, 0);
  124. }
  125. # todo: Check strict equality
  126. if ($Enabled == 2) {
  127. logout();
  128. }
  129. // Up/Down stats
  130. $UserStats = $Cache->get_value('user_stats_'.$LoggedUser['ID']);
  131. if (!is_array($UserStats)) {
  132. $DB->query("
  133. SELECT Uploaded AS BytesUploaded, Downloaded AS BytesDownloaded, RequiredRatio
  134. FROM users_main
  135. WHERE ID = '$LoggedUser[ID]'");
  136. $UserStats = $DB->next_record(MYSQLI_ASSOC);
  137. $Cache->cache_value('user_stats_'.$LoggedUser['ID'], $UserStats, 3600);
  138. }
  139. // Get info such as username
  140. $LightInfo = Users::user_info($LoggedUser['ID']);
  141. $HeavyInfo = Users::user_heavy_info($LoggedUser['ID']);
  142. // Create LoggedUser array
  143. $LoggedUser = array_merge($HeavyInfo, $LightInfo, $UserStats);
  144. $LoggedUser['RSS_Auth'] = md5($LoggedUser['ID'] . RSS_HASH . $LoggedUser['torrent_pass']);
  145. // $LoggedUser['RatioWatch'] as a bool to disable things for users on Ratio Watch
  146. $LoggedUser['RatioWatch'] = (
  147. $LoggedUser['RatioWatchEnds']
  148. && time() < strtotime($LoggedUser['RatioWatchEnds'])
  149. && ($LoggedUser['BytesDownloaded'] * $LoggedUser['RequiredRatio']) > $LoggedUser['BytesUploaded']
  150. );
  151. // Load in the permissions
  152. $LoggedUser['Permissions'] = Permissions::get_permissions_for_user($LoggedUser['ID'], $LoggedUser['CustomPermissions']);
  153. $LoggedUser['Permissions']['MaxCollages'] += Donations::get_personal_collages($LoggedUser['ID']);
  154. // Change necessary triggers in external components
  155. $Cache->CanClear = check_perms('admin_clear_cache');
  156. // Because we <3 our staff
  157. if (check_perms('site_disable_ip_history')) {
  158. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  159. }
  160. // Update LastUpdate every 10 minutes
  161. if (strtotime($UserSessions[$SessionID]['LastUpdate']) + 600 < time()) {
  162. $DB->query("
  163. UPDATE users_main
  164. SET LastAccess = NOW()
  165. WHERE ID = '$LoggedUser[ID]'");
  166. $SessionQuery =
  167. "UPDATE users_sessions
  168. SET ";
  169. // Only update IP if we have an encryption key in memory
  170. if (apcu_exists('DBKEY')) {
  171. $SessionQuery .= "IP = '".Crypto::encrypt($_SERVER['REMOTE_ADDR'])."', ";
  172. }
  173. $SessionQuery .=
  174. "Browser = '$Browser',
  175. OperatingSystem = '$OperatingSystem',
  176. LastUpdate = NOW()
  177. WHERE UserID = '$LoggedUser[ID]'
  178. AND SessionID = '".db_string($SessionID)."'";
  179. $DB->query($SessionQuery);
  180. $Cache->begin_transaction("users_sessions_$UserID");
  181. $Cache->delete_row($SessionID);
  182. $UsersSessionCache = array(
  183. 'SessionID' => $SessionID,
  184. 'Browser' => $Browser,
  185. 'OperatingSystem' => $OperatingSystem,
  186. 'IP' => (apcu_exists('DBKEY') ? Crypto::encrypt($_SERVER['REMOTE_ADDR']) : $UserSessions[$SessionID]['IP']),
  187. 'LastUpdate' => sqltime() );
  188. $Cache->insert_front($SessionID, $UsersSessionCache);
  189. $Cache->commit_transaction(0);
  190. }
  191. // Notifications
  192. if (isset($LoggedUser['Permissions']['site_torrents_notify'])) {
  193. $LoggedUser['Notify'] = $Cache->get_value('notify_filters_'.$LoggedUser['ID']);
  194. if (!is_array($LoggedUser['Notify'])) {
  195. $DB->query("
  196. SELECT ID, Label
  197. FROM users_notify_filters
  198. WHERE UserID = '$LoggedUser[ID]'");
  199. $LoggedUser['Notify'] = $DB->to_array('ID');
  200. $Cache->cache_value('notify_filters_'.$LoggedUser['ID'], $LoggedUser['Notify'], 2592000);
  201. }
  202. }
  203. // We've never had to disable the wiki privs of anyone.
  204. if ($LoggedUser['DisableWiki']) {
  205. unset($LoggedUser['Permissions']['site_edit_wiki']);
  206. }
  207. // IP changed
  208. if (apcu_exists('DBKEY') && Crypto::decrypt($LoggedUser['IP']) != $_SERVER['REMOTE_ADDR'] && !check_perms('site_disable_ip_history')) {
  209. if (Tools::site_ban_ip($_SERVER['REMOTE_ADDR'])) {
  210. error('Your IP address has been banned.');
  211. }
  212. $CurIP = db_string($LoggedUser['IP']);
  213. $NewIP = db_string($_SERVER['REMOTE_ADDR']);
  214. $DB->query("
  215. SELECT IP
  216. FROM users_history_ips
  217. WHERE EndTime IS NULL
  218. AND UserID = '$LoggedUser[ID]'");
  219. while (list($EncIP) = $DB->next_record()) {
  220. if (Crypto::decrypt($EncIP) == $CurIP) {
  221. $CurIP = $EncIP;
  222. // CurIP is now the encrypted IP that was already in the database (for matching)
  223. break;
  224. }
  225. }
  226. $DB->query("
  227. UPDATE users_history_ips
  228. SET EndTime = NOW()
  229. WHERE EndTime IS NULL
  230. AND UserID = '$LoggedUser[ID]'
  231. AND IP = '$CurIP'");
  232. $DB->query("
  233. INSERT IGNORE INTO users_history_ips
  234. (UserID, IP, StartTime)
  235. VALUES
  236. ('$LoggedUser[ID]', '".Crypto::encrypt($NewIP)."', NOW())");
  237. $ipcc = Tools::geoip($NewIP);
  238. $DB->query("
  239. UPDATE users_main
  240. SET IP = '".Crypto::encrypt($NewIP)."', ipcc = '$ipcc'
  241. WHERE ID = '$LoggedUser[ID]'");
  242. $Cache->begin_transaction('user_info_heavy_'.$LoggedUser['ID']);
  243. $Cache->update_row(false, array('IP' => Crypto::encrypt($_SERVER['REMOTE_ADDR'])));
  244. $Cache->commit_transaction(0);
  245. }
  246. // Get stylesheets
  247. $Stylesheets = $Cache->get_value('stylesheets');
  248. if (!is_array($Stylesheets)) {
  249. $DB->query('
  250. SELECT
  251. ID,
  252. LOWER(REPLACE(Name, " ", "_")) AS Name,
  253. Name AS ProperName,
  254. LOWER(REPLACE(Additions, " ", "_")) AS Additions,
  255. Additions AS ProperAdditions
  256. FROM stylesheets');
  257. $Stylesheets = $DB->to_array('ID', MYSQLI_BOTH);
  258. $Cache->cache_value('stylesheets', $Stylesheets, 0);
  259. }
  260. // todo: Clean up this messy solution
  261. $LoggedUser['StyleName'] = $Stylesheets[$LoggedUser['StyleID']]['Name'];
  262. if (empty($LoggedUser['Username'])) {
  263. logout(); // Ghost
  264. }
  265. }
  266. G::initialize();
  267. $Debug->set_flag('end user handling');
  268. $Debug->set_flag('start function definitions');
  269. /**
  270. * Log out the current session
  271. */
  272. function logout()
  273. {
  274. global $SessionID;
  275. setcookie('session', '', time() - 60 * 60 * 24 * 365, '/', '', false);
  276. setcookie('userid', '', time() - 60 * 60 * 24 * 365, '/', '', false);
  277. setcookie('keeplogged', '', time() - 60 * 60 * 24 * 365, '/', '', false);
  278. if ($SessionID) {
  279. G::$DB->query("
  280. DELETE FROM users_sessions
  281. WHERE UserID = '" . G::$LoggedUser['ID'] . "'
  282. AND SessionID = '".db_string($SessionID)."'");
  283. G::$Cache->begin_transaction('users_sessions_' . G::$LoggedUser['ID']);
  284. G::$Cache->delete_row($SessionID);
  285. G::$Cache->commit_transaction(0);
  286. }
  287. G::$Cache->delete_value('user_info_' . G::$LoggedUser['ID']);
  288. G::$Cache->delete_value('user_stats_' . G::$LoggedUser['ID']);
  289. G::$Cache->delete_value('user_info_heavy_' . G::$LoggedUser['ID']);
  290. header('Location: login.php');
  291. die();
  292. }
  293. function logout_all_sessions()
  294. {
  295. $UserID = G::$LoggedUser['ID'];
  296. G::$DB->query("
  297. DELETE FROM users_sessions
  298. WHERE UserID = '$UserID'");
  299. G::$Cache->delete_value('users_sessions_' . $UserID);
  300. logout();
  301. }
  302. function enforce_login()
  303. {
  304. global $SessionID;
  305. if (!$SessionID || !G::$LoggedUser) {
  306. setcookie('redirect', $_SERVER['REQUEST_URI'], time() + 60 * 30, '/', '', false);
  307. logout();
  308. }
  309. }
  310. /**
  311. * Make sure $_GET['auth'] is the same as the user's authorization key
  312. * Should be used for any user action that relies solely on GET.
  313. *
  314. * @param Are we using ajax?
  315. * @return authorisation status. Prints an error message to LAB_CHAN on IRC on failure.
  316. */
  317. function authorize($Ajax = false)
  318. {
  319. if (empty($_REQUEST['auth']) || $_REQUEST['auth'] != G::$LoggedUser['AuthKey']) {
  320. send_irc("PRIVMSG ".LAB_CHAN." :".G::$LoggedUser['Username']." just failed authorize on ".$_SERVER['REQUEST_URI'].(!empty($_SERVER['HTTP_REFERER']) ? " coming from ".$_SERVER['HTTP_REFERER'] : ""));
  321. error('Invalid authorization key. Go back, refresh, and try again.', $Ajax);
  322. return false;
  323. }
  324. return true;
  325. }
  326. $Debug->set_flag('ending function definitions');
  327. //Include /sections/*/index.php
  328. $Document = basename(parse_url($_SERVER['SCRIPT_FILENAME'], PHP_URL_PATH), '.php');
  329. if (!preg_match('/^[a-z0-9]+$/i', $Document)) {
  330. error(404);
  331. }
  332. $StripPostKeys = array_fill_keys(array('password', 'cur_pass', 'new_pass_1', 'new_pass_2', 'verifypassword', 'confirm_password', 'ChangePassword', 'Password'), true);
  333. $Cache->cache_value('php_' . getmypid(), array(
  334. 'start' => sqltime(),
  335. 'document' => $Document,
  336. 'query' => $_SERVER['QUERY_STRING'],
  337. 'get' => $_GET,
  338. 'post' => array_diff_key($_POST, $StripPostKeys)), 600);
  339. // Locked account constant
  340. define('STAFF_LOCKED', 1);
  341. $AllowedPages = ['staffpm', 'ajax', 'locked', 'logout', 'login'];
  342. if (isset(G::$LoggedUser['LockedAccount']) && !in_array($Document, $AllowedPages)) {
  343. require(SERVER_ROOT . '/sections/locked/index.php');
  344. } else {
  345. require(SERVER_ROOT . '/sections/' . $Document . '/index.php');
  346. }
  347. $Debug->set_flag('completed module execution');
  348. /* Required in the absence of session_start() for providing that pages will change
  349. upon hit rather than being browser cached for changing content.
  350. Old versions of Internet Explorer choke when downloading binary files over HTTPS with disabled cache.
  351. Define the following constant in files that handle file downloads */
  352. if (!defined('SKIP_NO_CACHE_HEADERS')) {
  353. header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
  354. header('Pragma: no-cache');
  355. }
  356. // Flush to user
  357. ob_end_flush();
  358. $Debug->set_flag('set headers and send to user');
  359. // Attribute profiling
  360. $Debug->profile();