<?php

/* Megatokyo Website Administration */

require_once('../LocalSettings.php');

// Core lib
require_once('html.php');
require_once('mysql.php');
require_once('cookies.php');
require_once('functions.php');
require_once('error.php');

require_once('uploads.php');
require_once('nonce.php');

// Objects
require_once('rants.php');
require_once('user.php');
require_once('strip.php');
require_once('transcript.php');
require_once('type.php');
require_once('pages.php');
require_once('extra.php');
require_once('twitter.php');
require_once('tumblr.php');
require_once('images.php');
require_once('rss.php');

require_once('twitteroauth/twitteroauth.php');

$mtdb = new MysqlStore();
$mtdb->connect( DB_SERVER, DB_WRITE_USER, DB_WRITE_PASS, DB_NAME );

/* TODO: Move these definitions to LocalSettings.php */
if ( !defined('RANTIMG') )
	define('RANTIMG', '../rantimgs/');

define('USING_TIDY', false);



/* These function are all for core authentication. */

function mt_hash_password($password) {
	return sha1($password);
}

// Remove invalid characters from username. Permit only alpha, underscore, period, at, hypen
function sanitize_username( $username ) {
	return preg_replace('|[^a-z_.@-]|i', '', $username);
}

// Attempt to login with a username and password. If from cookies, set already_hashed = true.
function mt_login($username, $password, $already_hashed = false) {
	global $error,$mtdb;

	if ( '' == $username )
		return false;

	if ( '' == $password ) {
		$error = ('<strong>ERROR</strong>: The password field is empty.');
		return false;
	}

	$username = sanitize_username( $username );

	$login = $mtdb->getRow( 'SELECT id,name,email,nameplate,default_image,default_link,password FROM contributor WHERE name = "' . mysqli_real_escape_string($mtdb->link, $username) . '"');
	if (!$login) {
		$error = ('<strong>ERROR</strong>: Invalid username or password.');
		adminlog("Failed login attempt from ".$_SERVER['REMOTE_ADDR']." for $username.", MTS_LOGIN, MTA_CHANGE);
		//logthis ('AUTH: Failed login attempt from ' . $_SERVER["REMOTE_ADDR"], var_export( $_SERVER, true ) );
		return false;
	} else {
		// If the password is already_md5, it has been double hashed.
		// Otherwise, it is plain text.
		if ( $already_hashed && $username == $login->name && $login->password == $password) {
			global $currentuser;
			$currentuser=$login;
			return true;
		}

		if (!$already_hashed) {
			$passhash = mt_hash_password($password);
			if( $username == $login->name && $passhash == $login->password ) {
				global $currentuser;
				$currentuser=$login;
				return true;
			}
		}
		$error = ('<strong>ERROR</strong>: Invalid username or password.');
		adminlog("Failed login attempt from ".$_SERVER['REMOTE_ADDR']." for $username.", MTS_LOGIN, MTA_CHANGE);
		//logthis ('AUTH: Failed login attempt from ' . $_SERVER["REMOTE_ADDR"], var_export( $_SERVER, true ) );
		return false;
	}
}

// Attempt to login using cookies with failback to HTTP Basic Auth.  If that fails, return a 401 to the browser.
function auth_basic() {
	if ( !empty($_COOKIE[USER_COOKIE]) && mt_login($_COOKIE[USER_COOKIE], $_COOKIE[PASS_COOKIE], true) )
		return;

	// Either there is no cookie or the cookie is not valid
	if (!isset($_SERVER['PHP_AUTH_USER']) || !mt_login($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) ) {
		header('WWW-Authenticate: Basic realm="My Realm"');
		header('HTTP/1.0 401 Unauthorized');
		die('You do not have permission to view this page.');
	}
}

// Attempt to login using cookies. If that fails, redirect to login.php to get credentials.
function auth_redirect($showloginui=true) {
	// Checks if a user is logged in, if not redirects them to the login page
	if ( (!empty($_COOKIE[USER_COOKIE]) &&
				!mt_login($_COOKIE[USER_COOKIE], $_COOKIE[PASS_COOKIE], true)) ||
			 (empty($_COOKIE[USER_COOKIE])) ) {
		nocache_headers();

		if($showloginui) _redirect( ADMIN_PATH . '/login.php?redirect_to=' . urlencode($_SERVER['REQUEST_URI']));
		die('You do not have permission to view this page.');
	}
}

// Safe redirect, defaults to Temporary
function _redirect($location, $status = 302) {
	$location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%]|i', '', $location);
	$strip = array('%0d', '%0a');
	$location = str_replace($strip, '', $location);

	if ( substr(php_sapi_name(), 0, 3) != 'cgi' )
		header('Status: '.$status); // This causes problems on IIS and some FastCGI setups

	header("Location: $location");
	die();
}

// When doing redirect to login form, ensure headers are never cached.
function nocache_headers() {
	@ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
	@ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
	@ header('Cache-Control: no-cache, must-revalidate, max-age=0');
	@ header('Pragma: no-cache');
}


?>
