0, 'email' => '', 'account_code' => '', 'password' => '', 'phone' => '', 'fb' => '0:0'); protected $config = array(); protected function __construct($config = false) { if (is_array($config)) { $this->config = array_merge(self::$default_config, $config); } else { $this->config = self::$default_config; } } /** * Function to Create User Account to DB * * @param array $varUserData * @return integer $varUserID */ public static function createUser($params) { return ($params['type'] == 'fb' ? self::createFbUser($params) : self::createStandardUser($params)); } public static function createStandardUser($params) { // Get fields $varEmail = trim($params['email']); $varPassword = self::DoubleSaltedHash($params['password']); $varPhone = trim($params['phone']); // Validate email if(!filter_var($varEmail, FILTER_VALIDATE_EMAIL)) { return false; } // Add user mysql_query("INSERT INTO `user` (account_code, email, password, fb, phone) VALUES('".$varEmail."', '".$varEmail."', '".$varPassword."', '0:0', '".$varPhone."' )"); if (mysql_insert_id() == 0) { return false; } // Verify user $self = self::loadFromEmail($varEmail); if ($self->getId() == 0) { return false; } // Store user for auto login $_SESSION['pid'] = $self->getId(); return $self; } public static function createFbUser($params) { // Get fields $varFbUser = trim($params['user']); $varFbToken = trim($params['password']); $varEmail = trim($params['email']); // Add user mysql_query("INSERT INTO `user` (account_code, email, fb) VALUES('".$varEmail."', '".$varEmail."', '".$varFbUser.':'.$varFbToken."' )"); if (mysql_insert_id() == 0) { return false; } // Verify user $self = self::loadFromFb($varFbUser, $varFbToken); if ($self->getId() == 0) { return false; } // Store user for auto login $_SESSION['pid'] = $self->getId(); return $self; } /** * Function to return id of current user, annoymous is zero * * @return integer $varUserID */ public function getId() { if (isset($this->config['pid'])) { return (int)$this->config['pid']; } return 0; } public function isAuthenticated() { return $this->getId() > 0; } public function getUsername() { if (isset($this->config['email'])) { return $this->config['email']; } return ''; } public function getAccountCode() { if (isset($this->config['account_code'])) { return $this->config['account_code']; } return ''; } public function getState() { if (isset($this->config['state'])) { return (int)$this->config['state']; } return 0; } public function getUserDetails() { return (isset($this->config) ? $this->config : false); } public function getBillingDetails() { return RecurlyManager::getBillingDetails($this->getAccountCode(), true); } /** * Function to Update User Billing Detail on Recurly * * @param integer $varUserID * @param array $varUserBilling * @return string */ public function setBillingDetails($varUserBilling) { return RecurlyManager::setBillingDetails($this->getAccountCode(), $varUserBilling); } /** * Function to Update User Billing Detail on Recurly * * @param integer $varUserID * @param array $varUserBilling * @return string */ public function setBillingDetailsWithToken($varUserBilling) { return RecurlyManager::setBillingDetailsWithToken($this->getAccountCode(), $varUserBilling); } /** * Function to get user account details on Recurly * (if refresh is false a cached copy will be used from the session. * * @param boolean $refresh * @param array $varUserData * @return integer $varUserID */ public function getPersonalDetails() { $details = RecurlyManager::getPersonalDetails($this->getAccountCode()); if ($details == false) { $details = $details = array( 'accEmail' => $this->config['email'], 'accFName' => '', 'accLName' => '', 'accStatus' => 'incomplete', 'accCode' => $this->getUsername(), 'accToken' => '' ); } // Add local details $details['accPhone'] = $this->config['phone']; return $details; } /** * Function to Update User Account on Recurly * * @param integer $varUserID * @param array $varUserData * @return integer $varUserID */ public function setPersonalDetails($varUserData) { return RecurlyManager::setPersonalDetails($this->getAccountCode(), $varUserData); } public function getSubscriptionDetails() { return RecurlyManager::getLiveSubscriptionDetails($this->getAccountCode()); } public function getCouponDetails() { return RecurlyManager::getCouponDetails($this->getAccountCode()); } /** * Function to Check User Login Detail From DB * * @param string $varEmail * @param string $varPassword * @return boolean */ public function checkLogin($varEmail, $varPassword) { $row = self::lookupUser($varEmail); if (is_array($row) && self::comparePassword($row['password'], $varPassword)) { // Update config $this->config = $row; // Prevent session fixation when logging in //session_regenerate_id(); // Store id in session $_SESSION['pid'] = $this->getId(); return true; } $this->logout(); return false; } public function logout() { $this->config = self::$default_config; session_unset(); session_destroy(); } /** * Function to Check User Email From DB * * @param string $varEmail * @return array */ public static function lookupUser($varEmail) { // Validate email $varEmail = sanitize_field($varEmail); if (!filter_var($varEmail, FILTER_VALIDATE_EMAIL)) { return false; } $rs = mysql_query("SELECT * FROM user WHERE email = '".$varEmail."' LIMIT 1"); if (!$rs) { return false; } return mysql_fetch_assoc($rs); } public static function lookupUserFb($varUserId) { // Validate user id $varUserId = sanitize_field($varUserId); $rs = mysql_query("SELECT * FROM user WHERE fb LIKE '".$varUserId.":%' LIMIT 1"); if (!$rs) { return false; } return mysql_fetch_assoc($rs); } public static function refreshFbToken($id, $token, $pid) { // Validate user id $id = sanitize_field($id); $token = sanitize_field($token); $sql = 'UPDATE `user` SET `fb` = "'.$id.':'.$token.'" WHERE `user`.`pid` = '.$pid.';'; $rs = mysql_query($sql); if (!$rs) { return false; } return true; } public static function loadAll() { $rs = mysql_query("SELECT * FROM user WHERE 1"); if (!$rs) { return false; } $users = array(); while (($r = mysql_fetch_assoc($rs)) != false ) { $users[] = new User($r); } return $users; } public static function loadFromSession() { session_start(); if (isset($_SESSION['pid'])) { $pid = (int)$_SESSION['pid']; $rs = mysql_query("SELECT * FROM `user` WHERE `pid` = ".$pid." LIMIT 1"); if ($rs) { return new self(mysql_fetch_assoc($rs)); } else { $self = new self(); $self->logout(); } } return new self(); } public static function loadFromFb($id, $token) { $sql = "SELECT * FROM `user` WHERE `fb` = '".$id.":".$token."' LIMIT 1"; $rs = mysql_query($sql); if ($rs) { // Setup the session $self = new self(mysql_fetch_assoc($rs)); // Set Session ID $_SESSION['pid'] = $self->getId(); } else { $self = new self(); $self->logout(); } return $self; } public static function loadFromAccountCode($varEmail) { // Validate email $varEmail = sanitize_field($varEmail); if (!filter_var($varEmail, FILTER_VALIDATE_EMAIL)) { return new self(); } $rs = mysql_query("SELECT * FROM user WHERE account_code = '".$varEmail."' LIMIT 1"); if (!$rs) { return new self(); } return new self(mysql_fetch_assoc($rs)); } public static function loadFromEmail($varEmail) { return new self(self::lookupUser($varEmail)); } /** * Function to Update User Detail on DB * * @param integer $varUserID * @param array $varUserData * @return string */ public function update($varUserData) { //Validate fields and build SQL $varTxt = ""; $delim = '`'; foreach (array('email','password','phone', 'fb') as $key ) { if (!isset($varUserData[$key])) { continue; } // Prepare field $val = $varUserData[$key]; if ($key == 'password') { $val = self::DoubleSaltedHash($val); } $varUserData[$key] = $val; $varTxt .= $delim.$key."` = '".$val; $delim = "', `"; } $varTxt .= "'"; $rs = mysql_query("UPDATE `user` SET ".$varTxt." WHERE `pid` = ".$this->getId()." LIMIT 1"); if (!$rs) { return false; } // Sync with local config foreach (array('email', 'password','phone','fb') as $key) { if (isset($varUserData[$key])) { $this->config[$key] = $varUserData[$key]; } } // Remove non-recurly fields unset($varUserData['password']); unset($varUserData['phone']); unset($varUserData['fb']); // Sync with recurly if (!empty($varUserData)) { $rs = $this->setPersonalDetails($varUserData); } return ($rs ? true : false); } /** * Function to check User Password From DB * * @param string $varPassword * @return array */ public function checkPassword($varPassword) { if (isset($this->config['password'])) { $password = $this->config['password']; } else { $password = ''; } $rs = mysql_query("SELECT * FROM `user` WHERE `pid` = ".$this->getId()); if (!$rs) { return false; } $row = mysql_fetch_array($rs); if (is_array($row)) { return self::comparePassword($row['password'], $varPassword); } else { return false; } } /** * Function to Check Subscription Status From Reculry * * @return boolean */ public function isActive() { return is_array(RecurlyManager::getLiveSubscriptionDetails($this->getAccountCode())); } /** * Function to Check if the user is an administrator * * @return boolean */ public function isAdmin() { return in_array($this->getId(), array(1, 239)); } public function delete() { $id = $this->getId(); if ($id > 0) { mysql_query("DELETE FROM `user` WHERE `pid`=".$id." LIMIT 1"); } $this->logout(); } public static function comparePassword($varSaltedHash, $pw) { list($hash, $salt) = explode(':', $varSaltedHash); $cryptpass = sha1($pw.$salt); return ($hash==$cryptpass); } public static function DoubleSaltedHash($pw) { $salt = self::generate_salt(); //return sha1($salt.sha1($salt.sha1($pw))); return sha1($pw.sha1($salt)).":".sha1($salt); } public static function generate_salt() { $dummy = array_merge(range('0', '9')); mt_srand((double)microtime()*1000000); for ($i = 1; $i <= (count($dummy)*2); $i++) { $swap = mt_rand(0,count($dummy)-1); $tmp = $dummy[$swap]; $dummy[$swap] = $dummy[0]; $dummy[0] = $tmp; } return sha1(substr(implode('',$dummy),0,9)); } } $v) { $path .= $delim.urlencode($k).'='.urlencode($v); $delim = '&'; } return $path; } function redirect($action, $params=array()) { if (strpos($action,'http') === 0) { $url = $action; } else { $url = href($action,$params); } if (headers_sent()){ echo ' '; } else { header('Location: '.$url); exit(); } } function not_found() { redirect('404'); } function internal_error() { redirect('500'); } function shortenText($text, $len) { return (strlen($text) > $len) ? substr($text, 0, $len).'...' : $text; } function sendPasswordReminder($email) { $varUser = User::loadFromEmail($email); if ($varUser->getId() == 0) { // User not found return false; } $varUserDetails = $varUser->getPersonalDetails(); if (empty($varUserDetails['fname'])) { $fullName = 'Dear Sir / Madam'; } else { $fullName = 'Dear '.$varUserDetails['fname'].' '.$varUserDetails['lname']; } // Generate new password $varPassword = substr(md5($varUser->getUsername().time().$varUser->getId()), 8, 8); // Set password $varUser->update(array('password' => $varPassword)); $varUserData = $varUser->getPersonalDetails(); $message = $fullName.' We received a "Forgot Password" request from this email address. Your new password is: '.$varPassword.' Please contact Wigan TV if you have any concerns. The Wigan TV Team '; $headers = array( 'To' => $varUserData['accFName'].' '.$varUserData['accLName'].' <'.$varUserData['accEmail'].'>', 'From' => 'Wigan TV < tv@wiganwarriors.com>' ); // Process headers $rawHeaders = ''; foreach($headers as $header => $value) { $rawHeaders .= $header.':'.$value."\r\n"; } // Mail it return mail($varUser->getUsername(), 'Forgot Password - Wigan TV', $message, $rawHeaders); } function sendPasswordReminderNew($email) { $varUser = User::loadFromEmail($email); if ($varUser->getId() == 0) { // User not found return false; } $varUserDetails = $varUser->getPersonalDetails(); if (empty($varUserDetails['fname'])) { $fullName = 'Dear Sir / Madam'; } else { $fullName = 'Dear '.$varUserDetails['fname'].' '.$varUserDetails['lname']; } // Generate new password $varPassword = substr(md5($varUser->getUsername().time().$varUser->getId()), 8, 8); // Set password $varUser->update(array('password' => $varPassword)); $varUserData = $varUser->getPersonalDetails(); $message = $fullName.' We received a "Forgot Password" request from this email address. Your new password is: '.$varPassword.' Please contact Wigan TV if you have any concerns. The Wigan TV Team '; require '../vendor/autoload.php'; $mg = new Mailgun\Mailgun("key-3adf656de5289f80b52d2fae88b43c3f"); // $domain = "example.com"; // $domain = "sandbox73cd4ac3ad2e4f278540bb948e5b33d2.mailgun.org"; $domain = "mg.wiganwarriors.com"; $result = $mg->sendMessage($domain, array( 'from' => 'Wigan TV ', 'to' => $varUserData['accEmail'], 'cc' => 'tv@wiganwarriors.com', 'subject' => 'Forgot Password - Wigan TV', 'text' => $message )); return ($result->http_response_code == '200'); } function ajax_error($code, $msg='') { static $codeNames = array( 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found', 406 => 'Not Acceptable', 409 => 'Conflict' ); header('HTTP/1.0 '.$code.' '.$codeNames[$code]); if (!empty($msg)) { echo json_encode(array('msg' => $msg)); } exit(); } function detect_device() { /* User Agent match criteria for a device * * Array order is important in correct matching with minimal checks */ static $deviceMatch = array( // IOS 'mobile.tablet.ipad' => array('iPad'), 'mobile.phone.iphone' => array('iPhone'), // Android 'mobile.phone.android' => array('Android', 'Mobile'), 'mobile.tablet.android' => array('Android'), // BlackBerry 'mobile.tablet.blackberry' => array('BlackBerry', 'WebKit'), 'mobile.phone.blackberry' => array('BlackBerry'), // Generic matches 'mobile.phone' => array('Mobile'), 'mobile.tablet' => array('Tablet') ); // Detect device from user agent $device = 'default'; if (isset($_SERVER['HTTP_USER_AGENT'])) { foreach($deviceMatch as $d => $conditions) { $match = true; foreach ($conditions as $str) { // Case insensitive match if (stripos($_SERVER['HTTP_USER_AGENT'], $str) === false) { $match = false; break; } } if ($match) { $device = $d; break; } } } return $device; } function partial($name, array $context= array()) { $path = VIEWS.'/_'.$name.'.php'; if (!file_exists($path)) { throw new Exception('Could not find partial: '.$path); } extract($context); ob_start(); include($path); return ob_get_clean(); } function asset($path) { if (strpos($path,'assets/') === 0) { $path = substr($path, 7); } return '//tv.wiganwarriors.com/assets/'.$path; //return '//d24luxq2i65k3y.cloudfront.net/tv.wiganwarriors.com/'.$path; } function videoPath($playlistID, $videoID = null) { $params = array('playlistID' => base64_encode($playlistID)); if ($videoID) { $params['videoID'] = base64_encode($videoID); } return href('tv', $params ); } function pr($arr, $exit = false) { echo '
';
	echo print_r($arr, true);
	echo '
'; if ($exit) { exit; } }