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

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