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

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