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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 TODO: Remove
  36. if ($_SERVER['HTTP_HOST'] == 'www.'.SITE_DOMAIN) {
  37. header('Location: https://'.SITE_DOMAIN.$_SERVER['REQUEST_URI']); die();
  38. }
  39. }
  40. $ScriptStartTime = microtime(true); //To track how long a page takes to create
  41. if (!defined('PHP_WINDOWS_VERSION_MAJOR')) {
  42. $RUsage = getrusage();
  43. $CPUTimeStart = $RUsage['ru_utime.tv_sec'] * 1000000 + $RUsage['ru_utime.tv_usec'];
  44. }
  45. ob_start(); //Start a buffer, mainly in case there is a mysql error
  46. require(SERVER_ROOT.'/classes/debug.class.php'); //Require the debug class
  47. require(SERVER_ROOT.'/classes/mysql.class.php'); //Require the database wrapper
  48. require(SERVER_ROOT.'/classes/cache.class.php'); //Require the caching class
  49. require(SERVER_ROOT.'/classes/time.class.php'); //Require the time class
  50. require(SERVER_ROOT.'/classes/paranoia.class.php'); //Require the paranoia check_paranoia function
  51. require(SERVER_ROOT.'/classes/regex.php');
  52. require(SERVER_ROOT.'/classes/util.php');
  53. $Debug = new DEBUG;
  54. $Debug->handle_errors();
  55. $Debug->set_flag('Debug constructed');
  56. $DB = new DB_MYSQL;
  57. $Cache = new CACHE(MEMCACHED_SERVERS);
  58. // Autoload classes.
  59. require(SERVER_ROOT.'/classes/classloader.php');
  60. // Note: G::initialize is called twice.
  61. // This is necessary as the code inbetween (initialization of $LoggedUser) makes use of G::$DB and G::$Cache.
  62. // TODO: remove one of the calls once we're moving everything into that class
  63. G::initialize();
  64. //Begin browser identification
  65. $Browser = UserAgent::browser($_SERVER['HTTP_USER_AGENT']);
  66. $OperatingSystem = UserAgent::operating_system($_SERVER['HTTP_USER_AGENT']);
  67. $Debug->set_flag('start user handling');
  68. // Get classes
  69. // TODO: Remove these globals, replace by calls into Users
  70. list($Classes, $ClassLevels) = Users::get_classes();
  71. //-- Load user information
  72. // User info is broken up into many sections
  73. // 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)
  74. // Light - Things that appear in format_user
  75. // Stats - Uploaded and downloaded - can be updated by a script if you want super speed
  76. // Session data - Information about the specific session
  77. // Enabled - if the user's enabled or not
  78. // Permissions
  79. if (isset($_COOKIE['session']) && isset($_COOKIE['userid'])) {
  80. $SessionID = $_COOKIE['session'];
  81. $LoggedUser['ID'] = (int)$_COOKIE['userid'];
  82. $UserID = $LoggedUser['ID']; //TODO: UserID should not be LoggedUser
  83. if (!$LoggedUser['ID'] || !$SessionID) {
  84. logout();
  85. }
  86. $UserSessions = $Cache->get_value("users_sessions_$UserID");
  87. if (!is_array($UserSessions)) {
  88. $DB->query(
  89. "SELECT
  90. SessionID,
  91. Browser,
  92. OperatingSystem,
  93. IP,
  94. LastUpdate
  95. FROM users_sessions
  96. WHERE UserID = '$UserID'
  97. AND Active = 1
  98. ORDER BY LastUpdate DESC");
  99. $UserSessions = $DB->to_array('SessionID',MYSQLI_ASSOC);
  100. $Cache->cache_value("users_sessions_$UserID", $UserSessions, 0);
  101. }
  102. if (!array_key_exists($SessionID, $UserSessions)) {
  103. logout();
  104. }
  105. // Check if user is enabled
  106. $Enabled = $Cache->get_value('enabled_'.$LoggedUser['ID']);
  107. if ($Enabled === false) {
  108. $DB->query("
  109. SELECT Enabled
  110. FROM users_main
  111. WHERE ID = '$LoggedUser[ID]'");
  112. list($Enabled) = $DB->next_record();
  113. $Cache->cache_value('enabled_'.$LoggedUser['ID'], $Enabled, 0);
  114. }
  115. if ($Enabled == 2) {
  116. logout();
  117. }
  118. // Up/Down stats
  119. $UserStats = $Cache->get_value('user_stats_'.$LoggedUser['ID']);
  120. if (!is_array($UserStats)) {
  121. $DB->query("
  122. SELECT Uploaded AS BytesUploaded, Downloaded AS BytesDownloaded, RequiredRatio
  123. FROM users_main
  124. WHERE ID = '$LoggedUser[ID]'");
  125. $UserStats = $DB->next_record(MYSQLI_ASSOC);
  126. $Cache->cache_value('user_stats_'.$LoggedUser['ID'], $UserStats, 3600);
  127. }
  128. // Get info such as username
  129. $LightInfo = Users::user_info($LoggedUser['ID']);
  130. $HeavyInfo = Users::user_heavy_info($LoggedUser['ID']);
  131. // Create LoggedUser array
  132. $LoggedUser = array_merge($HeavyInfo, $LightInfo, $UserStats);
  133. $LoggedUser['RSS_Auth'] = md5($LoggedUser['ID'] . RSS_HASH . $LoggedUser['torrent_pass']);
  134. // $LoggedUser['RatioWatch'] as a bool to disable things for users on Ratio Watch
  135. $LoggedUser['RatioWatch'] = (
  136. $LoggedUser['RatioWatchEnds']
  137. && time() < strtotime($LoggedUser['RatioWatchEnds'])
  138. && ($LoggedUser['BytesDownloaded'] * $LoggedUser['RequiredRatio']) > $LoggedUser['BytesUploaded']
  139. );
  140. // Load in the permissions
  141. $LoggedUser['Permissions'] = Permissions::get_permissions_for_user($LoggedUser['ID'], $LoggedUser['CustomPermissions']);
  142. $LoggedUser['Permissions']['MaxCollages'] += Donations::get_personal_collages($LoggedUser['ID']);
  143. // Change necessary triggers in external components
  144. $Cache->CanClear = check_perms('admin_clear_cache');
  145. // Because we <3 our staff
  146. if (check_perms('site_disable_ip_history')) {
  147. $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  148. }
  149. // Update LastUpdate every 10 minutes
  150. if (strtotime($UserSessions[$SessionID]['LastUpdate']) + 600 < time()) {
  151. $DB->query("
  152. UPDATE users_main
  153. SET LastAccess = '".sqltime()."'
  154. WHERE ID = '$LoggedUser[ID]'");
  155. $SessionQuery =
  156. "UPDATE users_sessions
  157. SET ";
  158. // Only update IP if we have an encryption key in memory
  159. if (apcu_exists('DBKEY')) {
  160. $SessionQuery .= "IP = '".DBCrypt::encrypt($_SERVER['REMOTE_ADDR'])."', ";
  161. }
  162. $SessionQuery .=
  163. "Browser = '$Browser',
  164. OperatingSystem = '$OperatingSystem',
  165. LastUpdate = '".sqltime()."'
  166. WHERE UserID = '$LoggedUser[ID]'
  167. AND SessionID = '".db_string($SessionID)."'";
  168. $DB->query($SessionQuery);
  169. $Cache->begin_transaction("users_sessions_$UserID");
  170. $Cache->delete_row($SessionID);
  171. $UsersSessionCache = array(
  172. 'SessionID' => $SessionID,
  173. 'Browser' => $Browser,
  174. 'OperatingSystem' => $OperatingSystem,
  175. 'IP' => ((apcu_exists('DBKEY')) ? DBCrypt::encrypt($_SERVER['REMOTE_ADDR']) : $UserSessions[$SessionID]['IP']),
  176. 'LastUpdate' => sqltime() );
  177. $Cache->insert_front($SessionID, $UsersSessionCache);
  178. $Cache->commit_transaction(0);
  179. }
  180. // Notifications
  181. if (isset($LoggedUser['Permissions']['site_torrents_notify'])) {
  182. $LoggedUser['Notify'] = $Cache->get_value('notify_filters_'.$LoggedUser['ID']);
  183. if (!is_array($LoggedUser['Notify'])) {
  184. $DB->query("
  185. SELECT ID, Label
  186. FROM users_notify_filters
  187. WHERE UserID = '$LoggedUser[ID]'");
  188. $LoggedUser['Notify'] = $DB->to_array('ID');
  189. $Cache->cache_value('notify_filters_'.$LoggedUser['ID'], $LoggedUser['Notify'], 2592000);
  190. }
  191. }
  192. // We've never had to disable the wiki privs of anyone.
  193. if ($LoggedUser['DisableWiki']) {
  194. unset($LoggedUser['Permissions']['site_edit_wiki']);
  195. }
  196. // IP changed
  197. if (apcu_exists('DBKEY') && DBCrypt::decrypt($LoggedUser['IP']) != $_SERVER['REMOTE_ADDR'] && !check_perms('site_disable_ip_history')) {
  198. if (Tools::site_ban_ip($_SERVER['REMOTE_ADDR'])) {
  199. error('Your IP address has been banned.');
  200. }
  201. $CurIP = db_string($LoggedUser['IP']);
  202. $NewIP = db_string($_SERVER['REMOTE_ADDR']);
  203. $DB->query("
  204. SELECT IP
  205. FROM users_history_ips
  206. WHERE EndTime IS NULL
  207. AND UserID = '$LoggedUser[ID]'");
  208. while (list($EncIP) = $DB->next_record()) {
  209. if (DBCrypt::decrypt($EncIP) == $CurIP) {
  210. $CurIP = $EncIP;
  211. // CurIP is now the encrypted IP that was already in the database (for matching)
  212. break;
  213. }
  214. }
  215. $DB->query("
  216. UPDATE users_history_ips
  217. SET EndTime = '".sqltime()."'
  218. WHERE EndTime IS NULL
  219. AND UserID = '$LoggedUser[ID]'
  220. AND IP = '$CurIP'");
  221. $DB->query("
  222. INSERT IGNORE INTO users_history_ips
  223. (UserID, IP, StartTime)
  224. VALUES
  225. ('$LoggedUser[ID]', '".DBCrypt::encrypt($NewIP)."', '".sqltime()."')");
  226. $ipcc = Tools::geoip($NewIP);
  227. $DB->query("
  228. UPDATE users_main
  229. SET IP = '".DBCrypt::encrypt($NewIP)."', ipcc = '$ipcc'
  230. WHERE ID = '$LoggedUser[ID]'");
  231. $Cache->begin_transaction('user_info_heavy_'.$LoggedUser['ID']);
  232. $Cache->update_row(false, array('IP' => DBCrypt::encrypt($_SERVER['REMOTE_ADDR'])));
  233. $Cache->commit_transaction(0);
  234. }
  235. // Get stylesheets
  236. $Stylesheets = $Cache->get_value('stylesheets');
  237. if (!is_array($Stylesheets)) {
  238. $DB->query('
  239. SELECT
  240. ID,
  241. LOWER(REPLACE(Name, " ", "_")) AS Name,
  242. Name AS ProperName,
  243. LOWER(REPLACE(Additions, " ", "_")) AS Additions,
  244. Additions AS ProperAdditions
  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('userid', '', time() - 60 * 60 * 24 * 365, '/', '', false);
  265. setcookie('keeplogged', '', 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();