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 14KB

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