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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. "SELECT
  98. SessionID,
  99. Browser,
  100. OperatingSystem,
  101. IP,
  102. LastUpdate
  103. FROM users_sessions
  104. WHERE UserID = '$UserID'
  105. AND Active = 1
  106. ORDER BY LastUpdate DESC"
  107. );
  108. $UserSessions = $DB->to_array('SessionID', MYSQLI_ASSOC);
  109. $Cache->cache_value("users_sessions_$UserID", $UserSessions, 0);
  110. }
  111. if (!array_key_exists($SessionID, $UserSessions)) {
  112. logout();
  113. }
  114. // Check if user is enabled
  115. $Enabled = $Cache->get_value('enabled_'.$LoggedUser['ID']);
  116. if ($Enabled === false) {
  117. $DB->query("
  118. SELECT Enabled
  119. FROM users_main
  120. WHERE ID = '$LoggedUser[ID]'");
  121. list($Enabled) = $DB->next_record();
  122. $Cache->cache_value('enabled_'.$LoggedUser['ID'], $Enabled, 0);
  123. }
  124. if ($Enabled == 2) {
  125. logout();
  126. }
  127. // Up/Down stats
  128. $UserStats = $Cache->get_value('user_stats_'.$LoggedUser['ID']);
  129. if (!is_array($UserStats)) {
  130. $DB->query("
  131. SELECT Uploaded AS BytesUploaded, Downloaded AS BytesDownloaded, RequiredRatio
  132. FROM users_main
  133. WHERE ID = '$LoggedUser[ID]'");
  134. $UserStats = $DB->next_record(MYSQLI_ASSOC);
  135. $Cache->cache_value('user_stats_'.$LoggedUser['ID'], $UserStats, 3600);
  136. }
  137. // Get info such as username
  138. $LightInfo = Users::user_info($LoggedUser['ID']);
  139. $HeavyInfo = Users::user_heavy_info($LoggedUser['ID']);
  140. // Create LoggedUser array
  141. $LoggedUser = array_merge($HeavyInfo, $LightInfo, $UserStats);
  142. $LoggedUser['RSS_Auth'] = md5($LoggedUser['ID'] . RSS_HASH . $LoggedUser['torrent_pass']);
  143. // $LoggedUser['RatioWatch'] as a bool to disable things for users on Ratio Watch
  144. $LoggedUser['RatioWatch'] = (
  145. $LoggedUser['RatioWatchEnds']
  146. && time() < strtotime($LoggedUser['RatioWatchEnds'])
  147. && ($LoggedUser['BytesDownloaded'] * $LoggedUser['RequiredRatio']) > $LoggedUser['BytesUploaded']
  148. );
  149. // Load in the permissions
  150. $LoggedUser['Permissions'] = Permissions::get_permissions_for_user($LoggedUser['ID'], $LoggedUser['CustomPermissions']);
  151. $LoggedUser['Permissions']['MaxCollages'] += Donations::get_personal_collages($LoggedUser['ID']);
  152. // Change necessary triggers in external components
  153. $Cache->CanClear = check_perms('admin_clear_cache');
  154. // Because we <3 our staff
  155. if (check_perms('site_disable_ip_history')) {
  156. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  157. }
  158. // Update LastUpdate every 10 minutes
  159. if (strtotime($UserSessions[$SessionID]['LastUpdate']) + 600 < time()) {
  160. $DB->query("
  161. UPDATE users_main
  162. SET LastAccess = NOW()
  163. WHERE ID = '$LoggedUser[ID]'");
  164. $SessionQuery =
  165. "UPDATE users_sessions
  166. SET ";
  167. // Only update IP if we have an encryption key in memory
  168. if (apcu_exists('DBKEY')) {
  169. $SessionQuery .= "IP = '".Crypto::encrypt($_SERVER['REMOTE_ADDR'])."', ";
  170. }
  171. $SessionQuery .=
  172. "Browser = '$Browser',
  173. OperatingSystem = '$OperatingSystem',
  174. LastUpdate = NOW()
  175. WHERE UserID = '$LoggedUser[ID]'
  176. AND SessionID = '".db_string($SessionID)."'";
  177. $DB->query($SessionQuery);
  178. $Cache->begin_transaction("users_sessions_$UserID");
  179. $Cache->delete_row($SessionID);
  180. $UsersSessionCache = array(
  181. 'SessionID' => $SessionID,
  182. 'Browser' => $Browser,
  183. 'OperatingSystem' => $OperatingSystem,
  184. 'IP' => (apcu_exists('DBKEY') ? Crypto::encrypt($_SERVER['REMOTE_ADDR']) : $UserSessions[$SessionID]['IP']),
  185. 'LastUpdate' => sqltime() );
  186. $Cache->insert_front($SessionID, $UsersSessionCache);
  187. $Cache->commit_transaction(0);
  188. }
  189. // Notifications
  190. if (isset($LoggedUser['Permissions']['site_torrents_notify'])) {
  191. $LoggedUser['Notify'] = $Cache->get_value('notify_filters_'.$LoggedUser['ID']);
  192. if (!is_array($LoggedUser['Notify'])) {
  193. $DB->query("
  194. SELECT ID, Label
  195. FROM users_notify_filters
  196. WHERE UserID = '$LoggedUser[ID]'");
  197. $LoggedUser['Notify'] = $DB->to_array('ID');
  198. $Cache->cache_value('notify_filters_'.$LoggedUser['ID'], $LoggedUser['Notify'], 2592000);
  199. }
  200. }
  201. // We've never had to disable the wiki privs of anyone.
  202. if ($LoggedUser['DisableWiki']) {
  203. unset($LoggedUser['Permissions']['site_edit_wiki']);
  204. }
  205. // IP changed
  206. if (apcu_exists('DBKEY') && Crypto::decrypt($LoggedUser['IP']) != $_SERVER['REMOTE_ADDR'] && !check_perms('site_disable_ip_history')) {
  207. if (Tools::site_ban_ip($_SERVER['REMOTE_ADDR'])) {
  208. error('Your IP address has been banned.');
  209. }
  210. $CurIP = db_string($LoggedUser['IP']);
  211. $NewIP = db_string($_SERVER['REMOTE_ADDR']);
  212. $DB->query("
  213. SELECT IP
  214. FROM users_history_ips
  215. WHERE EndTime IS NULL
  216. AND UserID = '$LoggedUser[ID]'");
  217. while (list($EncIP) = $DB->next_record()) {
  218. if (Crypto::decrypt($EncIP) == $CurIP) {
  219. $CurIP = $EncIP;
  220. // CurIP is now the encrypted IP that was already in the database (for matching)
  221. break;
  222. }
  223. }
  224. $DB->query("
  225. UPDATE users_history_ips
  226. SET EndTime = NOW()
  227. WHERE EndTime IS NULL
  228. AND UserID = '$LoggedUser[ID]'
  229. AND IP = '$CurIP'");
  230. $DB->query("
  231. INSERT IGNORE INTO users_history_ips
  232. (UserID, IP, StartTime)
  233. VALUES
  234. ('$LoggedUser[ID]', '".Crypto::encrypt($NewIP)."', NOW())");
  235. $ipcc = Tools::geoip($NewIP);
  236. $DB->query("
  237. UPDATE users_main
  238. SET IP = '".Crypto::encrypt($NewIP)."', ipcc = '$ipcc'
  239. WHERE ID = '$LoggedUser[ID]'");
  240. $Cache->begin_transaction('user_info_heavy_'.$LoggedUser['ID']);
  241. $Cache->update_row(false, array('IP' => Crypto::encrypt($_SERVER['REMOTE_ADDR'])));
  242. $Cache->commit_transaction(0);
  243. }
  244. // Get stylesheets
  245. $Stylesheets = $Cache->get_value('stylesheets');
  246. if (!is_array($Stylesheets)) {
  247. $DB->query('
  248. SELECT
  249. ID,
  250. LOWER(REPLACE(Name, " ", "_")) AS Name,
  251. Name AS ProperName,
  252. LOWER(REPLACE(Additions, " ", "_")) AS Additions,
  253. Additions AS ProperAdditions
  254. FROM stylesheets');
  255. $Stylesheets = $DB->to_array('ID', MYSQLI_BOTH);
  256. $Cache->cache_value('stylesheets', $Stylesheets, 0);
  257. }
  258. // todo: Clean up this messy solution
  259. $LoggedUser['StyleName'] = $Stylesheets[$LoggedUser['StyleID']]['Name'];
  260. if (empty($LoggedUser['Username'])) {
  261. logout(); // Ghost
  262. }
  263. }
  264. G::initialize();
  265. $Debug->set_flag('end user handling');
  266. $Debug->set_flag('start function definitions');
  267. /**
  268. * Log out the current session
  269. */
  270. function logout()
  271. {
  272. global $SessionID;
  273. setcookie('session', '', time() - 60 * 60 * 24 * 365, '/', '', false);
  274. setcookie('userid', '', time() - 60 * 60 * 24 * 365, '/', '', false);
  275. setcookie('keeplogged', '', time() - 60 * 60 * 24 * 365, '/', '', false);
  276. if ($SessionID) {
  277. G::$DB->query("
  278. DELETE FROM users_sessions
  279. WHERE UserID = '" . G::$LoggedUser['ID'] . "'
  280. AND SessionID = '".db_string($SessionID)."'");
  281. G::$Cache->begin_transaction('users_sessions_' . G::$LoggedUser['ID']);
  282. G::$Cache->delete_row($SessionID);
  283. G::$Cache->commit_transaction(0);
  284. }
  285. G::$Cache->delete_value('user_info_' . G::$LoggedUser['ID']);
  286. G::$Cache->delete_value('user_stats_' . G::$LoggedUser['ID']);
  287. G::$Cache->delete_value('user_info_heavy_' . G::$LoggedUser['ID']);
  288. header('Location: login.php');
  289. die();
  290. }
  291. function logout_all_sessions()
  292. {
  293. $UserID = G::$LoggedUser['ID'];
  294. G::$DB->query("
  295. DELETE FROM users_sessions
  296. WHERE UserID = '$UserID'");
  297. G::$Cache->delete_value('users_sessions_' . $UserID);
  298. logout();
  299. }
  300. function enforce_login()
  301. {
  302. global $SessionID;
  303. if (!$SessionID || !G::$LoggedUser) {
  304. setcookie('redirect', $_SERVER['REQUEST_URI'], time() + 60 * 30, '/', '', false);
  305. logout();
  306. }
  307. }
  308. /**
  309. * Make sure $_GET['auth'] is the same as the user's authorization key
  310. * Should be used for any user action that relies solely on GET.
  311. *
  312. * @param Are we using ajax?
  313. * @return authorisation status. Prints an error message to LAB_CHAN on IRC on failure.
  314. */
  315. function authorize($Ajax = false)
  316. {
  317. if (empty($_REQUEST['auth']) || $_REQUEST['auth'] != G::$LoggedUser['AuthKey']) {
  318. send_irc("PRIVMSG ".LAB_CHAN." :".G::$LoggedUser['Username']." just failed authorize on ".$_SERVER['REQUEST_URI'].(!empty($_SERVER['HTTP_REFERER']) ? " coming from ".$_SERVER['HTTP_REFERER'] : ""));
  319. error('Invalid authorization key. Go back, refresh, and try again.', $Ajax);
  320. return false;
  321. }
  322. return true;
  323. }
  324. $Debug->set_flag('ending function definitions');
  325. //Include /sections/*/index.php
  326. $Document = basename(parse_url($_SERVER['SCRIPT_FILENAME'], PHP_URL_PATH), '.php');
  327. if (!preg_match('/^[a-z0-9]+$/i', $Document)) {
  328. error(404);
  329. }
  330. $StripPostKeys = array_fill_keys(array('password', 'cur_pass', 'new_pass_1', 'new_pass_2', 'verifypassword', 'confirm_password', 'ChangePassword', 'Password'), true);
  331. $Cache->cache_value('php_' . getmypid(), array(
  332. 'start' => sqltime(),
  333. 'document' => $Document,
  334. 'query' => $_SERVER['QUERY_STRING'],
  335. 'get' => $_GET,
  336. 'post' => array_diff_key($_POST, $StripPostKeys)), 600);
  337. // Locked account constant
  338. define('STAFF_LOCKED', 1);
  339. $AllowedPages = ['staffpm', 'ajax', 'locked', 'logout', 'login'];
  340. if (isset(G::$LoggedUser['LockedAccount']) && !in_array($Document, $AllowedPages)) {
  341. require(SERVER_ROOT . '/sections/locked/index.php');
  342. } else {
  343. require(SERVER_ROOT . '/sections/' . $Document . '/index.php');
  344. }
  345. $Debug->set_flag('completed module execution');
  346. /* Required in the absence of session_start() for providing that pages will change
  347. upon hit rather than being browser cached for changing content.
  348. Old versions of Internet Explorer choke when downloading binary files over HTTPS with disabled cache.
  349. Define the following constant in files that handle file downloads */
  350. if (!defined('SKIP_NO_CACHE_HEADERS')) {
  351. header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
  352. header('Pragma: no-cache');
  353. }
  354. //Flush to user
  355. ob_end_flush();
  356. $Debug->set_flag('set headers and send to user');
  357. //Attribute profiling
  358. $Debug->profile();