false, "url" => $url, "message" => $json['error']['message'], "type" => $json['error']['type'], "code" => $json['error']['code'], "debug" => "Access token is not valid or missing", )); //die(''); return false; }else{ // access_token is valid return $json; } }else if($source == "twitter"){ require 'Application/Views/Landings/content/twitter/tmhOAuth.php'; require 'Application/Views/Landings/content/twitter/tmhUtilities.php'; $tmhOAuth = new tmhOAuth(array( 'consumer_key' => 'dNWaFpHEVZTVYtzpvaRADw', 'consumer_secret' => 'wdJzjJv4yFtSPYv9nmZhc3D9sDzzQs7rFzxPtk', )); if($access_token == ""){ $tmhOAuth->config['user_token'] = $_SESSION['access_token']['oauth_token']; $tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret']; }else{ $tmhOAuth->config['user_token'] = $access_token['oauth_token']; $tmhOAuth->config['user_secret'] = $access_token['oauth_token_secret']; } //print_array($_SESSION['access_token']); //echo "
"; $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/account/verify_credentials')); if($code == 200){ $json = json_decode($tmhOAuth->response['response'],true); // false by default (obj), if true (array) return $json; }else{ if(isset($_REQUEST['oauth_verifier'])){ $tmhOAuth->config['user_token'] = $_SESSION['oauth']['oauth_token']; $tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret']; $code = $tmhOAuth->request('POST', $tmhOAuth->url('oauth/access_token', ''), array( 'oauth_verifier' => $_REQUEST['oauth_verifier'] )); if ($code == 200) { $_SESSION['access_token'] = $tmhOAuth->extract_params($tmhOAuth->response['response']); $tmhOAuth->config['user_token'] = $_SESSION['access_token']['oauth_token']; $tmhOAuth->config['user_secret'] = $_SESSION['access_token']['oauth_token_secret']; $code = $tmhOAuth->request('GET', $tmhOAuth->url('1.1/account/verify_credentials')); if($code == 200){ $json = json_decode($tmhOAuth->response['response'],true); // false by default (obj), if true (array) return $json; }else{ outputError($tmhOAuth); return null; } } else { outputError($tmhOAuth); } } } }else if($source == "googleplus"){ //do something with the token, first check is real $data = @file_get_contents("https://www.googleapis.com/plus/v1/people/me?access_token={$access_token}"); $json = json_decode($data, true); if($json){ return $json; }else{ //use this since not all people have google plus accounts $data = @file_get_contents("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token={$access_token}"); $json = json_decode($data, true); if($json){ return $json; }else{ echo json_encode(array( // show as successful "success" => false, "message" => "Token not valid using oauth2 or google plus", "access_token"=>$access_token, )); return false; } } } return false; } function handle_login($source, $access_token, $json, $page, $createAccount = false){ $_SESSION['jid'] = $jid = $json['id']; if($source == "facebook"){ $name = $json['first_name']." ". $json['last_name']; $email = $json['email']; }else if($source == "twitter"){ $name = $json['name']; $tw_handle = $email = $json['screen_name']; }else if($source == "googleplus"){ $name = $json['given_name']." ". $json['family_name']; if(trim($name) == ""){ $name = $json['name']['givenName']." ".$json['name']['familyName']; } if(trim($name) == ""){ $name = $json['displayName']; } $email = $json['email']; } $uid = get_unique_user($jid, $email, $source); //echo("first:".$uid); if($uid > 0){ if(get_source($uid) == $source){ //login method is same as source }else{ update_user($uid, $access_token, $json, $source); // //add new FB info to existing GP } $msg = "Welcome back, $name!"; }else{ $uid = get_unique_user("", $email, "mpyr"); //echo("second:".$uid); //die(''); if($uid > 0){ update_user($uid, $access_token, $json, $source); // //add new FB info to existing GP $msg = "Thank you for signing up, $name. Now you are ready to claim a property."; }else{ $json['mpyr_email'] = $email; /* Has never created an account before */ if($createAccount){ if($source == "facebook"){ //logging in using facebook save_fb_user($access_token, $json, "", false, false); }else if($source == "googleplus"){ //logging in using google save_gp_user($access_token, $json, "", false, false); }else if($source == "twitter"){ //logging in using twitter save_tw_user($json, "", false, false); } $msg = "Thank you for signing up, $name. Now you are ready to claim a property."; //echo("third:".$_SESSION['uid']); }else{ $msg = "This account has not been linked with MPYR. Perhaps you used another account?"; return $msg; } } } //echo "uid:".$uid."
"; if($uid > 0){ $_SESSION['uid'] = $uid; } $_SESSION['source'] = $source; $_SESSION['name'] = $name; $_SESSION['uid'] = $uid; $_SESSION['social_url'] = "https://mpyr.com/?ref=$uid"; $_SESSION['submitted_claim'] = get_number_submitted_claims($uid); $_SESSION['submitted_login'] = $source; return $msg; } function get_user_email($uid, $json = null, $source = ""){ if($json){ if($source == "facebook"){ $email = $json['email']; }else if($source == "twitter"){ $tw_handle = $email = $json['screen_name']; }else if($source == "googleplus"){ $email = $json['email']; } return $email; } $condition = " uid='$uid' "; $row = select_db(0,"user","source,gp_email,fb_email,mpyr_email",1,$condition); if($row['source'] == "facebook"){ return $row['fb_email']; }else if($row['source'] == "googleplus"){ return $row['gp_email']; }else{ if($row['mpyr_email'] != ""){ return $row['mpyr_email']; }else{ return null; } } } function get_user_name($uid, $json = null, $source = ""){ if($json){ if($source == "facebook"){ $name = $json['first_name']." ". $json['last_name']; }else if($source == "twitter"){ $name = $json['name']; }else if($source == "googleplus"){ $name = $json['given_name']." ". $json['family_name']; } return $name; } $condition = " uid='$uid'"; $row = select_db(0,"user","source,first_name,last_name,tw_handle",1,$condition); if($row == null){ return "Anonymous"; }else{ if($row['source'] == "twitter"){ return $row['tw_handle']; }else{ return $row['first_name']." ".$row['last_name']; } } } function get_user_handle($uid){ $condition = " uid='$uid'"; $row = select_db(0,"user","tw_handle",1,$condition); if($row == null){ return null; }else{ return $row['tw_handle']; } } function get_user_link($uid){ $condition = " uid='$uid' "; $row = select_db(0,"user","source,gp_link,fb_link,tw_handle",1,$condition); if($row == null){ //$link = "http://www.google.com"; }else{ if($row['source'] == "twitter"){ $link = "https://www.twitter.com/".$row['tw_handle']; }else if($row['source'] == "facebook"){ $link = $row['fb_link']; }else{ $link = $row['gp_link']; } return $link; } } function get_pic($uid){ $condition = "uid='$uid'"; $pic = select_db(0,"user","fb_profile_image,tw_profile_image,gp_profile_image",1,$condition); if($pic == null){ //return "http://faculty.sites.uci.edu/ltemplate/files/2011/04/generic_profile.jpg"; return null; }else{ return $pic['local_image']; /* if($pic['fb_profile_image'] != ""){ return $pic['fb_profile_image']; }else if($pic['tw_profile_image'] != ""){ return $pic['tw_profile_image']; }else if($pic['gp_profile_image'] != ""){ return $pic['gp_profile_image']; }else{ //return "http://faculty.sites.uci.edu/ltemplate/files/2011/04/generic_profile.jpg"; return null; } */ } } function get_rank($uid,$db_rank="",$approved=0,$property = null){ if($uid > 0){ $condition = "uid='$uid'"; $user = select_db(0,"user","rank,approved",1,$condition); $db_rank = $user['db_rank']; $approved = $user['approved']; } if($approved == 1){ if($db_rank == ""){ if($property == null){ // no approved or pending properties $rank = "Newbie? (no properties)"; }else if($property['ostatus'] == "on hold"){ //$rank = "Newbie? (pending)"; $rank = "Newbie"; }else if($property['ostatus'] == "approved"){ //$rank = "Newbie? (approved)"; $rank = "Newbie"; } }else{ $rank = $db_rank; } }else if($approved == -1){ $rank = "Newbie? (rejected claim)"; }else{ if($uid > 0){ //$rank = "N/A (pending)"; $rank = "Newbie"; }else{ $rank = "N/A (unregistered)"; } } return $rank; } function get_award_status($uid, $type){ switch($type){ case "tweet": $condition = " uid='$uid' && type='$type'"; $row = select_db(0,"awards","status",1,$condition); if($row == null){ //return false; return "Not Awarded Yet"; }else{ return $row['status']; } break; } } function save_user_pic($uid,$url){ //save picture to local folder with a hash $filename = $uid."-".uniqid(); $path = "/home/mpyr/public_html/Media/userpic/$filename.jpg"; $image = @file_get_contents($url); @file_put_contents($path,$image); $condition = "uid='$uid'"; $fvs = array(); $fvs['local_image'] = "https://www.mpyr.com/Media/userpic/$filename.jpg"; update_db(0,"user",$fvs,$condition); } function subscribe($email, $source, $ret_value = "", $uid = ""){ $email = str_replace("googlemail","gmail",$email); /* $url = "http://api.kickofflabs.com/v1/14738/subscribe?email=".$email."&skip_ar=1&ip=".$_SERVER["REMOTE_ADDR"]; if(isset($_SESSION['kid'])){ $url .= "&social_id=".$_SESSION['kid']; } $data = @file_get_contents($url); $json = json_decode($data, true); */ /* $json = subscribe_kol_alternative($email); if($json){ $fvs = array(); $fvs['kol_social_id'] = $json['social_id']; $fvs['kol_parent_id'] = $json['parent_id']; $fvs['kol_social_id'] = $json['ref']; $fvs['kol_parent_id'] = $_SESSION['kid']; if($source == "facebook"){ $condition = "fb_email='$email'"; }else if($source == "googleplus"){ $condition = "gp_email='$email'"; }else if($source == "twitter"){ $condition = "mpyr_email='$email'"; } $fvs['updated_dt'] = "now()"; update_db(0,"user",$fvs,$condition); if($ret_value == ""){ return $json['social_url']; }else{ return $json['social_id']; } }else{ return null; } */ $uid = get_unique_user('uid',$email,$source); if($ret_value == ""){ return "https://mpyr.com/ref=".$uid; }else{ return $uid; } } function subscribe_kol_alternative($email){ $url = "https://admin.bishopnetwork.com/ajax/save_email.php"; $referrer = $_SERVER['HTTP_REFERRER']; $data = array('domain' => "mpyr.com", 'email' => $email, 'referrer' => $referrer, 'title'=>'title', 'ref' => $_GET['ref']); // use key 'http' even if you send the request to https://... $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data), ), ); $context = stream_context_create($options); $result = @file_get_contents($url, false, $context); $json = json_decode($result, true); return $json; } function get_share_buttons($social_url){ if($social_url == null || $social_url == ""){ $social_url = "https://www.mpyr.com/"; } $url = rawurlencode($social_url); $share_buttons = " Facebook Twitter Google+"; return $share_buttons; } function get_share_text($social_url, $uid = 0){ $referrals = get_number_referrals($uid); $share_text = "

$social_url

Influenced so far:$referrals

"; return $share_text; } function is_linked($uid, $source){ $condition = "uid='$uid'"; switch($source){ case "facebook": $row = select_db(0,"user","fb_id",1,$condition); break; case "twitter": $row = select_db(0,"user","tw_id",1,$condition); break; case "googleplus": $row = select_db(0,"user","gp_id",1,$condition); break; } if($row == null){ return false; }else{ return $row[0] != ""; } } function get_parent_id($uid,$email="",$user_table=true){ $condition = "ref='$uid'"; $row = select_db(0, "user", "*", 1, $condition); if($row == null){ return ""; }else{ return $row['ref']; } } function get_number_referrals($uid){ $condition = "ref='$uid'"; $row = select_db(0,"user","COUNT(*)",1,$condition); if($row == null || $row < 1){ return 0; }else{ return $row; } } function get_number_linked_accounts($uid){ $count = 0; $condition = "uid='$uid'"; $user = select_db(0,"user","*",1,$condition); if($user == null){ return 0; } if($user['fb_id'] != ""){ $count++; } if($user['tw_id'] != ""){ $count++; } if($user['gp_id'] != ""){ $count++; } return $count; } function compute_progress($uid = 0,$source = ""){ if($uid == 247){ return 65; } if($uid > 0){ $social_url = "https://mpyr.com/?ref=$uid"; $number_linked = get_number_linked_accounts($uid); $url = "https://urls.api.twitter.com/1/urls/count.json?url=".$social_url; $data = get_api_results($url); $json = json_decode($data, true); $tw_count = $json['count']; $url = "https://graph.facebook.com/".$social_url; $data = get_api_results($url); $json = json_decode($data, true); $fb_count = $json['shares']; $url = "https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ"; $post = array(); $post['method'] = 'pos.plusones.get'; $post['id'] = 'p'; $post['params']['nolog'] = true; $post['params']['id'] = "$social_url"; $post['params']['source'] = "widget"; $post['params']['userId'] = "@viewer"; $post['params']['groupId'] = "@self"; $post['jsonrpc'] = '2.0'; $post['key'] = 'p'; $post['apiVersion'] = 'v1'; $headers = array('Content-Type: application/json'); $data = get_api_results($url, json_encode($post), $headers); $json = json_decode($data, true); $gp_count = $json['result']['metadata']['globalCounts']['count']; if(has_approved_or_pending_properties($uid)){ //at least 40 (twitter) + 50 (fb,g+) $progress = 50; if($tw_count > 0){ $progress += 10; } if($fb_count > 0){ $progress += 10; } if($gp_count > 0){ $progress += 10; } $count = get_number_linked_accounts($uid); $uid = ($count - 1) * 10; //check if has used tweet bar to tweet property $condition = "uid='$uid' && tweeted_property > 0"; $row = select_db(0, "user", "tweeted_property", 1, $condition); if($row == null){ }else{ $progress += 10; } //check referrals $referrals = get_number_referrals($uid); if($referrals > 0){ $progress += 10; } //linked accounts $progress += ($number_linked - 1) * 10; return min($progress, 100); }else{ //only made shares, at least 20 (email) return 20; } } if(isset($_SESSION['submitted_claim'])){ if($_SESSION['submitted_login'] == "twitter"){ if(isset($_SESSION['mpyr_email'])){ return 50; }else{ return 40; } }else{ return 50; } } if($_GET['source'] == "facebook" || $_GET['source'] == "googleplus"){ return 50; } else if($_GET['source'] == "twitter"){ if(isset($_SESSION['mpyr_email']) && $_SESSION['mpyr_email'] != ""){ return 50; }else{ return 40; } }else if(isset($_SESSION['mpyr_email']) && $_SESSION['mpyr_email'] != ""){ return 20; }else if(isset($_GET['learn-more'])){ return 10; }else{ return 0; } } function save_fb_user($access_token, $json, $success_msg = "", $return_fvs = false, $is_echo=true){ $source = "facebook"; //require_once( '/Facebook/FacebookSession.php' ); $fb = new \Facebook\Facebook([ 'app_id' => FB_APP_ID, 'app_secret' => FB_APP_SECRET, 'default_graph_version' => 'v2.12', ]); try { // Returns a `Facebook\FacebookResponse` object $response = $fb->get('/me?fields=id,name,email,first_name,last_name,link', $access_token); } catch(Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch(Facebook\Exceptions\FacebookSDKException $e) { echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } $json = $response->getGraphUser(); $fvs = array(); $fvs['fb_token'] = $access_token; $fvs['fb_id'] = $json['id']; //$fvs['fb_name'] = $json['name']; $fvs['first_name'] = $json['first_name']; $fvs['last_name'] = $json['last_name']; $fvs['fb_link'] = $json['link']; $fvs['fb_username'] = $json['username']; //TO-DO: since this is deprecated as of v2.0 scrape where facebook.com/profile.php?id=xxxx goes to get username $fvs['fb_location'] = $json['location']['name']; $fvs['fb_email'] = $json['email']; $fvs['fb_verified'] = $json['verified']; $fvs['fb_profile_image'] = get_fb_image($json['id']); if($_SESSION['traffic'] == null || $_SESSION['traffic'] == ""){ $fvs['traffic'] = $traffic = "direct"; }else{ $fvs['traffic'] = $traffic = $_SESSION['traffic']; } $fvs['browser'] = $browser = getBrowser(); $fvs['platform'] = $platform = getPlatform(); $fvs['ref'] = isset($_GET['ref']) ? $_GET['ref'] : $_SESSION['ref']; $uid = get_unique_user($json['id'],$json['email'],$source); //echo "
";
    //print_r($json);
    //print_r($fvs);
    //echo "
"; if($uid < 1){ //user doesn't exist or it's rom $fvs['signup_dt'] = "now()"; $fvs['signup_ip'] = $_SERVER["REMOTE_ADDR"]; $fvs['acct_type'] = "beta tester"; $fvs['notes'] = "pre-launch signup"; if($return_fvs){ return $fvs; }else{ $fvs['source'] = $source; // don't overwrite source $uid = insert_db(0,"user",$fvs); // save user to database save_user_pic($uid,$fvs['fb_profile_image']); $social_url = "https://mpyr.com/?ref=".$uid; } } if($uid > 0){ $_SESSION['uid'] = $uid; } if($uid > 0 && has_approved_or_pending_properties($uid) == false){ //user is registered, but doesn't have approved or on hold properties so choose $oid = save_ownership($uid, false); // take care of outputting if($oid){ $name = ""; if(isset($json['first_name'])){ $name .= rawurlencode($json['first_name']); } if(isset($json['last_name'])){ $name .= rawurlencode(" ".$json['last_name']); } $link = rawurlencode($json['link']); $pid = $_SESSION['property_id']; $property = urlencode(get_property_name($_SESSION['property_id'])); $location = urlencode(get_location($_SESSION['property_id'])); //send email to Shawn & Rom $url = "https://www.mpyr.com/email?action=signup-alert&property=$property&location=$location&source=$source&traffic=$traffic&browser=$browser&platform=$platform&oid=$oid&uid=$uid&pid=$pid&name={$name}&link=$link"; get_api_results($url); //send email to user $email_encoded = rtrim(strtr(base64_encode($json['email']), '+/', '-_'), '='); $url = "https://www.mpyr.com/email?action=welcome-user&name=$name&to_email=$email_encoded&property=$property&location=$location&source=$source"; get_api_results($url); if($is_echo){ echo json_encode(array( // show as successful "success" => true, "social_url" => $social_url, "email" => $json['email'], "uid" => $uid, "name" => urldecode($name), "num_linked" => get_number_linked_accounts($uid), "share_buttons" => get_share_buttons($social_url), "share_text" => get_share_text($social_url,$uid), "message" => ($success_msg == "") ? "Thank you for signing up. Your claim has been received." : $success_msg )); } }else{ //can't save property //error will display if($is_echo){ $social_url = "https://mpyr.com/?ref=$uid"; echo json_encode(array( "success" => false, "social_url" => $social_url, "uid" => $uid, "email" => $json['email'], "name" => get_user_name($uid), "share_buttons" => get_share_buttons($social_url), "share_text" => get_share_text($social_url,$uid), "message" => "It looks like you have already placed a claim (FB)." )); } } }else{ $condition = "uid='$uid'"; $fvs['updated_dt'] = "now()"; update_db(0,"user",$fvs,$condition); if($is_echo){ $social_url = "https://mpyr.com/?ref=$uid"; echo json_encode(array( "success" => false, "social_url" => $social_url, "uid" => $uid, "email" => $json['email'], "name" => get_user_name($uid), "share_buttons" => get_share_buttons($social_url), "share_text" => get_share_text($social_url,$uid), "message" => "It looks like you are already registered (FB)." )); } } } function get_fb_image($fb_id){ $url = "http://graph.facebook.com/$fb_id/?fields=picture&type=large"; $data = @file_get_contents($url); $json = json_decode($data, true); if($json){ return $json["picture"]["data"]["url"]; }else{ return ""; } } function save_gp_user($access_token, $json, $success_msg = "", $return_fvs = false, $is_echo=true){ $source = "googleplus"; $fvs = array(); $fvs['gp_token'] = $access_token; $fvs['gp_id'] = $json['id']; //$fvs['gp_email'] = $json['email']; $fvs['gp_email'] = $json['emails'][0]['value']; $fvs['gp_verified_email'] = $json['gp_verified_email']; $fvs['etag'] = $json['etag']; $fvs['gender']= $json['gender']; $fvs['objectType'] = $json['objectType']; //$fvs['gp_name'] = $json['name']['givenName']." ".$json['name']['familyName']; $fvs['gp_name'] = $json['displayName']; $fvs['first_name'] = isset($json['given_name']) ? $json['given_name'] : $json['name']['givenName']; $fvs['last_name'] = isset($json['family_name']) ? $json['family_name'] : $json['name']['familyName']; $fvs['tagline'] = $json['tagline']; $fvs['braggingRights'] = $json['braggingRights']; $fvs['aboutMe'] = $json['aboutMe']; $fvs['gp_link']= $json['url']; $fvs['gp_profile_image'] = isset($json['image']['url']) ? $json['image']['url'] : $json['picture']; $fvs['plus_user'] = $json['isPlusUser'] * 1; $fvs['locale'] = $json['locale']; //echo "
";print_r($json);die('aaaaaa');
	if($_SESSION['traffic'] == null || $_SESSION['traffic'] == ""){
		$fvs['traffic'] = $traffic = "direct";
	}else{
		$fvs['traffic'] = $traffic = $_SESSION['traffic'];
	}
	$fvs['browser'] = $browser = getBrowser();
	$fvs['platform'] = $platform = getPlatform();
    $fvs['ref'] = isset($_GET['ref']) ? $_GET['ref'] : $_SESSION['ref'];

	$email = $json['emails'][0]['value']; //may change!
	$uid = get_unique_user($json['id'],$email,$source);
	//die("uid : $uid");
	if($uid < 1) {
		$fvs['signup_dt'] = "now()";
		$fvs['signup_ip'] = $_SERVER["REMOTE_ADDR"];
		$fvs['acct_type'] = "beta tester";
		$fvs['notes'] = "pre-launch signup";

		if($return_fvs){
			return $fvs;
		}else{
			$fvs['source'] = $source; // don't overwrite source
			$uid = insert_db(0,"user",$fvs); // save user to database
            save_user_pic($uid,$fvs['gp_profile_image']);
			$social_url = "https://mpyr.com/?ref=".$uid;
		}
	}
	if($uid > 0){
		$_SESSION['uid'] = $uid;
	}

	if($uid > 0 && has_approved_or_pending_properties($uid) == false){	//user is registered, but doesn't have approved or on hold properties so choose
		$oid = save_ownership($uid, false); // take care of outputting
		if($oid){
			$name = "";
			if(isset($json['first_name'])){
				$name .= rawurlencode($json['first_name']);
			}
			if(isset($json['last_name'])){
				$name .= rawurlencode(" ".$json['last_name']);
			}
            if(trim($name) == ""){
                $name = $json['displayName'];
            }
			$link = urlencode($fvs['gp_link']);
			$pid = $_SESSION['property_id'];
			$property = urlencode(get_property_name($_SESSION['property_id']));
			$location = urlencode(get_location($_SESSION['property_id']));

			//send email to Shawn & Rom
			$url = "https://www.mpyr.com/email?action=signup-alert&property=$property&location=$location&source=$source&traffic=$traffic&browser=$browser&platform=$platform&oid=$oid&uid=$uid&pid=$pid&name={$name}&link=$link";
			get_api_results($url);

			//send email to user
			$url = "https://www.mpyr.com/email?action=welcome-user&name=$name&to_email=$email&property=$property&location=$location&source=$source";
			get_api_results($url);
			//die($url);

			if($is_echo){
				echo json_encode(array( // show as successful
					"success" => true,
					"social_url" => $social_url,
					"email" => $email,
					"uid" => $uid,
					"name" => urldecode($name),
					"num_linked" => get_number_linked_accounts($uid),
					"share_buttons" => get_share_buttons($social_url),
					"share_text" => get_share_text($social_url,$uid),
					"message" => ($success_msg == "") ? "Thank you for signing up. Your claim has been received." : $success_msg
				));
			}
		}else{
			//can't save property
			//error will display
			if($is_echo){
                $social_url = "https://mpyr.com/?ref=$uid";
				echo json_encode(array(
					"success" => false,
					"social_url" => $social_url,
					"uid" => $uid,
					"email" => $json['email'],
					"name" => get_user_name($uid),
					"share_buttons" => get_share_buttons($social_url),
					"share_text" => get_share_text($social_url,$uid),
					"message" => "It looks like you have already placed a claim (G)."
				));
			}
		}
	}else {
		$condition = "uid='$uid'";
		$fvs['updated_dt'] =  "now()";
		update_db(0,"user",$fvs,$condition);

		if($is_echo){
            $social_url = "https://mpyr.com/?ref=$uid";
			echo json_encode(array(
				"success" => false,
				"social_url" => $social_url,
				"uid" => $uid,
				"email" => $json['email'],
				"name" => get_user_name($uid),
				"share_buttons" => get_share_buttons($social_url),
				"share_text" => get_share_text($social_url,$uid),
				"message" => "It looks like you are already registered (G)."
			));
		}
	}
}

function save_tw_user($json, $success_msg = "", $return_fvs = false, $is_echo=false){ // do not echo by default
	$source = "twitter";
	$fvs = array();
	if($_SESSION['traffic'] == null || $_SESSION['traffic'] == ""){
		$fvs['traffic'] = $traffic = "direct";
	}else{
		$fvs['traffic'] = $traffic = $_SESSION['traffic'];
	}
	$fvs['browser'] = $browser = getBrowser();
	$fvs['platform'] = $platform = getPlatform();
    $fvs['ref'] = isset($_GET['ref']) ? $_GET['ref'] : $_SESSION['ref'];

	$uid = get_unique_user($json['id'],'',$source);
	//echo("first uid.$uid");
	//die('');
	if($uid < 1){ //user doesn't exist	and has no approved property claim
		$fvs['acct_type'] = "beta tester";
		$fvs['notes'] = "pre-launch signup";
		$fvs['signup_dt'] = "now()";
		$fvs['signup_ip'] = $_SERVER["REMOTE_ADDR"];
		$fvs['source'] = $source;
		$fvs['tw_id'] = $json['id'];
		$fvs['tw_handle'] = $json['screen_name'];
		$fvs['tw_name'] = $json['name'];
		$fvs['tw_profile_image'] = $json['profile_image_url'];
		$fvs['followers_count'] = $json['followers_count'];
		$fvs['statuses_count'] = $json['statuses_count'];
		$fvs['time_zone'] = $json['time_zone'];
		$unix = strtotime($json['created_at']);
		$fvs['tw_created_dt'] = date("Y-m-d",$unix);
		$fvs['tw_link'] = $json['url'];
		$fvs['tw_friends'] = $json['friends_count'];
		$fvs['tw_location'] = $json['location'];
		$fvs['tw_description'] = $json['description'];

		if($return_fvs){
			return $fvs;
		}else{
			$uid = insert_db(0,"user",$fvs); // save user to database
            save_user_pic($uid,$fvs['tw_profile_image']);
			$social_url = "https://mpyr.com/?ref=".$uid;
		}

		/** Can't subscribe to KOL since there's no email **/
	}
	if($uid > 0){
		$_SESSION['uid'] = $uid;
		$email = get_user_email($uid);
		if($email != null && $email != ""){
			$_SESSION['email'] = get_user_email($uid);
		}
	}

	if($uid > 0 && has_approved_or_pending_properties($uid) === false){	//user is registered, but doesn't have approved or on hold properties so can choose
		$oid = save_ownership($uid, false);//take care of outputting
		if($oid){
            $name = "";
			if(isset($json['screen_name'])){
				$name .= rawurlencode($json['screen_name']);
			}
			$link = rawurlencode($json['url']);
			$property = urlencode(get_property_name($_SESSION['property_id']));
			$location = urlencode(get_location($_SESSION['property_id']));

			//send email to Shawn & Rom
			$url = "https://www.mpyr.com/email?action=signup-alert&property={$property}&location={$location}&source=$source&traffic=$traffic&browser=$browser&platform=$platform&oid=$oid&uid=$uid&pid=$pid&name={$name}&link=$link";
			get_api_results($url);

			//tweet to user
			$_SESSION['tw_handle'] = $json['screen_name'];

			if(!is_banned($json['screen_name'])){ // check if name of property is offensive, don't tweet
				if(stripos($json['screen_name'], "froghog") === false){ //not a test account
					if($email == null || $email == "" ){
						$tweet = urlencode("@".$json['screen_name']." We received your claim request and will be reviewing it shortly ... #MPYR");
					}else{
						$social_url = subscribe($email, $source);
						$tweet = urlencode("@".$json['screen_name']." We received your claim request and will be reviewing it shortly ... Share MPYR for earlier access: ".$social_url);
					}
					$url = "https://www.mpyr.com/tweet?name={$_SESSION['tw_handle']}&property=$property&location=$location&tweet=$tweet";
					get_api_results($url);
				}
			}

			if($is_echo){
				echo json_encode(array( // show as successful
					"success" => true,
					"social_url" => $social_url,
					"uid" => $uid,
					"email" => $_SESSION['mpyr_email'],
					"name" => urldecode($name),
					"num_linked" => get_number_linked_accounts($uid),
					"share_buttons" => get_share_buttons($social_url),
					"share_text" => get_share_text($social_url,$uid),
					"message" => ($success_msg == "") ? "Thank you for signing up. Your claim has been received." : $success_msg
				));
			}else{
				header("location: https://www.mpyr.com/index.php?source=twitter");
			}
		}else{
			if($is_echo){
				echo json_encode(array(
					"success" => false,
					"social_url" => "https://mpyr.com/?ref=$uid",
                    "uid" => $uid,
					"email" => $_SESSION['mpyr_email'],
					"name" => get_user_name($uid),
					"share_buttons" => get_share_buttons($social_url),
					"share_text" => get_share_text($social_url,$uid),
					"message" => "It looks like you have already placed a claim (TW)."
				));
			}else{
				header("location: https://www.mpyr.com/index.php?source=twitter&error=hasClaimed&uid=$uid");
			}
		}
	}else{
		if($is_echo){
            $social_url = "https://mpyr.com/?ref=$uid";
			echo json_encode(array(
				"success" => false,
				"social_url" => $social_url,
				"uid" => $uid,
				"email" => $_SESSION['mpyr_email'],
				"name" => get_user_name($uid),
				"share_buttons" => get_share_buttons($social_url),
				"share_text" => get_share_text($social_url,$uid),
				"message" => "It looks like you are already registered (TW)."
			));
		}else{
            //TO-DO: fix this: property and location not passed to this function
			$tweet = "@".$json['screen_name'].", you are already registered and have approved/pending claims.";
			$url = "https://www.mpyr.com/tweet?name={$_SESSION['tw_handle']}&property=$property&location=$location&tweet=$tweet";
			get_api_results($url);
			header("location: https://www.mpyr.com/index.php?source=twitter&error=isRegistered");
		}
	}
}
?>results as $result)
	{
		foreach($result->address_components as $addressPart) {
			if((in_array('locality', $addressPart->types)) && (in_array('political', $addressPart->types))){
	    		$city = $addressPart->long_name;
	    	}else if((in_array('administrative_area_level_1', $addressPart->types)) && (in_array('political', $addressPart->types))){
	    		//$state = $addressPart->long_name;
				$state = $addressPart->short_name;
	    	}else if((in_array('country', $addressPart->types)) && (in_array('political', $addressPart->types))){
	    		$country = $addressPart->long_name;
			}
		}
	}
	
	/*
	if(($city != '') && ($state != '') && ($country != ''))
		$address = $city.', '.$state.', '.$country;
	else if(($city != '') && ($state != ''))
		$address = $city.', '.$state;
	else if(($state != '') && ($country != ''))
		$address = $state.', '.$country;
	else if($country != '')
		$address = $country;
		
	// return $address;
	*/
	$geocode = array();
	$geocode['city'] = $city;
	$geocode['state'] = $state;
	return $geocode;
}


function get_property_zip($lat,$lng){
	$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lng;
	//echo $url."\n";
	$data = @file_get_contents($url);
	$json = json_decode($data, true);	
	//print_array($json);
	if(isset($json['results'])){
		for($i=0; $i<12; $i++){
			if($json['results'][0]['address_components'][$i]['types'][0] == "postal_code"){
				$zip = $json['results'][0]['address_components'][$i]['long_name'];
				break;
			}
		}
		return $zip;
	}else{
		return "";
	}
}

function get_property_views($pid){
	$condition = "pid='$pid'";
	$count = select_db(0,"property_views","COUNT(vid)as ct",1,$condition);
	return $count['ct'];
}

/** Check if property is on hold for another user */
function is_on_hold($pid){
	$condition = "pid='$pid' && hold_expires!='0000-00-00'";
	$row = select_db(0,"property","added_by_ip, hold_sessionid, hold_expires",1,$condition);
	
	if($row == null){
		return false;
	}else{
		if($_SERVER["REMOTE_ADDR"] == $row['added_by_ip']){ // user who placed this on hold is same user claiming it
			extend_hold($pid);
			return false;
		}else{
			//hold found but see if it has expired
			$now = date('Y-m-d H:i:s');
			$expires = $row['hold_expires'];
			if($expires < $now){ // expiry before current time
				remove_hold($pid);
				return false;
			}else{
				return true;
			}
		}
	}		
}	

function fill_gp_url(){
	$condition = "gp_url = ''";
	$join = "1=1";
	$group_by = "";
	$order_by = "pid DESC";

	$rows = select_db(0,"property","pid,reference",999,$condition,$join,$group_by,$order_by); 
	foreach($rows as $row){
		$reference = $row['reference'];
		$json = get_property_data($reference);
		if($json == null){
			continue;
		}
		$fvs = array();
		$fvs['gp_url'] = $json['result']['url'];
		
		$condition = "pid=".$row['pid'];
		update_db(1,"property",$fvs,$condition);
	}
}

function save_view($pid = null,$uid = "",$page="",$action=""){
	$fvs = array();
	if(!isset($pid)){
		$pid = $_SESSION['property_id'];
	}
	$fvs['pid'] = $pid;
	$fvs['uid'] = $uid; // user id
	$fvs['dt'] = "now()";
	$fvs['ip'] = $_SERVER["REMOTE_ADDR"];
	$fvs['browser'] = getBrowser();
	$fvs['platform'] = getPlatform();
	$fvs['page'] = $page;
	$fvs['action'] = $action;
	$vid = insert_db(0,"property_views",$fvs); // update property to show user 
	return $vid;
}


function extend_hold($pid){
	$fvs = array();
	$expires = date('Y-m-d H:i:s', time()+900);
	$fvs['hold_expires'] = "$expires"; //lock property 15 minutes so no one else can add it
	$condition = " pid='$pid' ";
	update_db(0,"property",$fvs,$condition);	
}

function remove_hold($pid){
	$fvs = array();
	$fvs['hold_sessionid'] = "";
	$fvs['hold_expires'] = "0000-00-00";
	$condition = " pid='$pid' ";
	update_db(0,"property",$fvs,$condition);
}
?>= 200 && $httpCode < 300) {
        return false;
    } else {
        return true;
    }
}

function get_full_url(){
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $sp = strtolower($_SERVER["SERVER_PROTOCOL"]);
    $protocol = substr($sp, 0, strpos($sp, "/")) . $s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
    return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
}

/** Auxiliary Functions */

function isMobile($className = ""){
	global $detect;
	$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
	$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
	$iPad = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
	//$WebKit = stripos($_SERVER['HTTP_USER_AGENT'],"WebKit");
	$Android = stripos($_SERVER['HTTP_USER_AGENT'],"Android");
	$webOS = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");
	$isMobile = ($detect->isMobile() || $iPod || $iPhone || $iPad || $WebKit);
	//echo $_SERVER['HTTP_USER_AGENT'];
	if($className == ""){
		return $isMobile;
	}else{
		if($isMobile){
			echo "xxx";
		}else{
			echo $className;		
		}
	}
}

function is_banned($check_word){
	$check_word = strtolower($check_word);
	include "_banned_words.php";
	foreach($banned_words as $word){
		$pos = stripos($check_word,$word);
		if($pos !== false){
			//echo "xx $pos, $check_word - $word 
\n"; return true; } } return false; } function get_page_rank($url){ $rootDomain = getRootDomain($url); $url = "https://www.mpyr.com/non-mvc/_getPR.php?url=http://".$rootDomain; $api = get_api_results($url); if(strpos($api,"Failed") ) { return "N/A"; }else{ return $api; } } function getRootDomain($domain){ $pieces = parse_url($domain); //print_r($pieces); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if (preg_match('/(?P[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $regs['domain']; }else{ return false; } } function getPlatform(){ $u_agent = $_SERVER['HTTP_USER_AGENT']; $platform = 'Unknown'; if( strpos($_SERVER['HTTP_USER_AGENT'],"iPhone") ) { $platform = 'iphone'; }elseif( strpos($_SERVER['HTTP_USER_AGENT'],"iPad") ) { $platform = 'ipad'; }elseif( strpos($_SERVER['HTTP_USER_AGENT'],"Android") ) { $platform = 'android'; }elseif (preg_match('/linux/i', $u_agent)) { $platform = 'linux'; }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) { $platform = 'mac'; }elseif (preg_match('/windows|win32/i', $u_agent)) { $platform = 'windows'; } return $platform; } function getBrowser(){ $u_agent = $_SERVER['HTTP_USER_AGENT']; $ub = "Unknown"; if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) { $ub = "MSIE"; } elseif(preg_match('/Firefox/i',$u_agent)) { $ub = "Firefox"; } elseif(preg_match('/Chrome/i',$u_agent)) { $ub = "Chrome"; } elseif(preg_match('/Safari/i',$u_agent)) { $ub = "Safari"; } elseif(preg_match('/Opera/i',$u_agent)) { $ub = "Opera"; } elseif(preg_match('/Netscape/i',$u_agent)) { $ub = "Netscape"; } return $ub; } ?> MPYR - Take Over the World isTablet()){ ?> isMobile()){ ?>