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.

script_start.php 14KB

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