KGRKJGETMRETU895U-589TY5MIGM5JGB5SDFESFREWTGR54TY
Server : Apache/2.4.62
System : FreeBSD fbsdweb2.web.rcn.net 14.1-RELEASE FreeBSD 14.1-RELEASE releng/14.1-n267679-10e31f0946d8 GENERIC amd64
User : www ( 80)
PHP Version : 8.3.8
Disable Function : NONE
Directory :  /domains/owens.enteract/server_scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /domains/owens.enteract/server_scripts/api.php
<?php
//ERROR REPORT
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set("display_errors", 1);
set_time_limit(20); //Timeout after 20 seconds

//If not PHP 5.6 or higher you might need the following
ini_set('default_charset', 'UTF-8');

include("../inc/utils.php");
if (USE_TUMBLR) {include('../inc/libs/tumblr/tumblrPHP.php');}

//Set the language of the API based on incoming value...
$incomingLang = strtolower(substr(ValidationUtils::getRequestVar("both","language",""),0,2));
if ($incomingLang === "en" || $incomingLang === ""){
	define("LANGUAGE","");	
}else{
	define("LANGUAGE","_" . $incomingLang);	
}

//Build API Object
$apiObj = new API($charCategories);
$apiObj->execute(ValidationUtils::getRequestVar("both","a",""),intval(ValidationUtils::getRequestVar("both","forceFresh","0")));
$apiObj->writeJSON();

class API {
	public $debug = false;
	public $cacheSeconds = 0;
	public $today;
	public $now;
	public $ip;
	public $cacheObj;
	public $usedDB = 0;
	public $forceFresh = 0;
	public $globalCopy;	
		
	public $json = "";
	public $errorCode = "";
	public $errorMessage = "";

/*========================================================================================
PUBLIC METHODS
========================================================================================*/	
	public function __construct() {	
		$this->today = date("Y-m-d");
		$this->now = date("Y-m-d H:i:s");
		$this->cacheSeconds = CACHE_SECONDS;
		$this->ip = addslashes($_SERVER["REMOTE_ADDR"]);
		$this->globalCopy = [];		
		$this->usedDB = 0;
	}	
	public function execute($actions,$forceFresh=0){
		$this->forceFresh = $forceFresh;
		//Split all actions and append into one JSON block
		$actionsArray = explode("|", $actions);
		//Setup cache path (always use MEMCACHE if it's available)
		if (MEMCACHE_SERVER != ""){
			$this->cacheObj = new Cacher("","memcached");
		}else{
			$this->cacheObj = new Cacher("../".CACHE_PATH);
		}
		foreach($actionsArray as $key => $action) {
			if ($action == "saveSubscriber"){
				$this->saveSubscriber(ValidationUtils::getRequestVar("post","email",""),ValidationUtils::getRequestVar("post","zip",""));	
			}else if ($action == "saveVote"){
				$this->saveVote(intval(ValidationUtils::getRequestVar("post","mid","")),intval(ValidationUtils::getRequestVar("post","cid","")),intval(ValidationUtils::getRequestVar("post","pid","0")));	
			}else if ($action == "links"){ 
				$this->getSocialLinks($action);
			}else if ($action == "likeTumblrPost"){ 
				//Refer to I3 to see this in action
				$this->likeTumblrPost(ValidationUtils::getRequestVar("both","tumblrPostID",""),ValidationUtils::getRequestVar("both","tumblrReblogKey",""));
			}else if ($_GET["oauth_verifier"] != ""){
				$this->tumblrCallback(ValidationUtils::getRequestVar("both","oauth_verifier",""));				
			}else if ($action == "getTumblrPosts"){ 
				$this->getTumblrPosts($action);
			}else if ($action == "getTumblrPost"){
				$this->getTumblrPost(ValidationUtils::getRequestVar("both","tumblrPostID",""));
			}									
		}
	}	
	public function writeJSON(){
		if ($this->errorMessage != ""){
			$jsonStatus = "\"status\":".json_encode("error") . ",";
			$jsonStatus .= "\"usedDB\":".json_encode($this->usedDB) . ",";
			$jsonStatus .= "\"errorCode\":".json_encode($this->errorCode."") . ",";
			$jsonStatus .= "\"errorMsg\":".json_encode($this->errorMessage."");
		}else{
			$jsonStatus = "\"status\":".json_encode("ok") . ",";
			$jsonStatus .= "\"usedDB\":".json_encode($this->usedDB);
		}
		if ($this->debug){
			$this->json .= "\"debug\":".json_encode(ValidationUtils::getRequestVar("both","a","")) . ",";	
			$this->json .= "\"ip\":".json_encode($this->ip) . ",";
		}
		if ($this->json != ""){
			$json = "{\"data\": {" . $this->json . $jsonStatus . "}}";
		}else{
			$json = "{\"data\": {" . $jsonStatus . "}}";
		}
		//Do jsonp?
		if (ValidationUtils::getRequestVar("both","jsoncallback","") != ""){
			echo ValidationUtils::getRequestVar("both","jsoncallback","") . "(" . $json . ");";
		}else{
			echo $json;
		}		
	}
/*========================================================================================
TRANSLATION/LOCALIZATION METHODS
========================================================================================*/	
	public function globalCopyTranslation($contentCode,$contentField="content_title"){
		if ($this->globalCopy[$contentCode . $contentField] != "") {
			return $this->globalCopy[$contentCode . $contentField];
		}else{
			$sql = "SELECT ".$this->sqlLanguage($contentField) ."
					FROM ".TABLEPRE."page_content WHERE active = 1 AND content_code = '".$contentCode."'";				
			$result = mysqli_query($this->dbh,$sql);
			if ($rs = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
				$this->globalCopy[$contentCode . $contentField] = $this->languageResults($rs,$contentField);
				return $this->globalCopy[$contentCode . $contentField];
			}else{
				return "";
			}	
		}			
	}
	public function dateTranslation($date){
		if (LANGUAGE == "_de"){
			return DateUtils::displayDate($date,"d.m.Y");
		}else if (LANGUAGE == "_fr"){
			return DateUtils::displayDate($date,"d-m-Y");
		}else{
			return DateUtils::displayDate($date,"F d, Y");			
		}
	}
	/*
	Example query: 			
		$sql = "SELECT bio_id,".$this->sqlLanguage("bio_name")." FROM ".TABLEPRE."bios WHERE active = 1 ORDER BY rank";	
	*/		
	public function sqlLanguage($fieldName){
		if (LANGUAGE == ""){
			return $fieldName;
		}else{
			return $fieldName . "," . $fieldName . LANGUAGE;
		}
	}
	public function languageResults($rs,$fieldName){
		if (LANGUAGE == ""){
			return ValidationUtils::stripHiddenBreaks($rs[$fieldName]) . "";
		}else{
			$value = $rs[$fieldName.LANGUAGE] . "";
			if ($value == ""){
				$value = $rs[$fieldName] . "";
			}
			return ValidationUtils::stripHiddenBreaks($value);
		}
	}
/*========================================================================================
PRIVATE HELPER METHODS
========================================================================================*/	
	private function clearCache(){
		//If necessary use fine grain control over what cache wiped (most likely not a problem)
		$this->cacheObj->setDataCache("getAll","");
		$this->cacheObj->setDataCache("xxxx","");	
		$this->cacheObj->setDataCache("xxxx","");
		$this->cacheObj->setDataCache("xxxx","");
		$this->cacheObj->setDataCache("xxxx","");
	}	
	private function wrapJSONSet($setName,$json,$hangingComma=true){
		//Remove last comma from result set
		if ($json != ""){$json = substr($json,0,-1);}
		$json = "\"".$setName."\":[" . $json . "]";
		if ($hangingComma){
			return $json . ",";
		}else{
			return $json;
		}		
	}	
	private function dbConn(){
		if ($this->usedDB == 0){
			$this->dbh = DBConn::open();
		}
		$this->usedDB = 1;
	}
	private function error($errorCode,$errorMessage){
		$this->errorCode = $errorCode;
		$this->errorMessage = $errorMessage;
	}			
/*========================================================================================
GET METHODS
========================================================================================*/	
	private function getSocialLinks($action){
		$cacheID = $action;
		if ($this->forceFresh == 1){$this->cacheObj->setDataCache($cacheID,"");}
		$json = $this->cacheObj->checkDataCache($cacheID,$this->cacheSeconds);
		if ($json == ""){
			$this->dbConn();
			$sql = "SELECT link_id,handle,link_url,link_body,link_url,img
					FROM ".TABLEPRE."links WHERE active = 1
					ORDER BY rank";
			$result = mysqli_query($this->dbh,$sql);
			while ($rs = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
				$json .= $this->getSocialLinksJSON($rs);	
			}
			$json = $this->wrapJSONSet("social",$json);
			$this->cacheObj->setDataCache($cacheID,$json);
		}	
		$this->json .= $json;
	}	
	private function getLocations($action){
		$cacheID = $action;
		if ($this->forceFresh == 1){$this->cacheObj->setDataCache($cacheID,"");}
		$json = $this->cacheObj->checkDataCache($cacheID,$this->cacheSeconds);
		if ($json == ""){
			$this->dbConn();
			$sql = "SELECT location_id,location_name,address,city,state,postal,coordinates
					FROM ".TABLEPRE."locations WHERE active = 1";
			$result = mysqli_query($this->dbh,$sql);
			while ($rs = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
				$json .= $this->getLocationsJSON($rs);	
			}			
			$json = $this->wrapJSONSet("locations",$json);
			$this->cacheObj->setDataCache($cacheID,$json);
		}	
		$this->json .= $json;
	}		
	private function getAssets($wrapperName,$type,$type_id){
		//We don't cache assets since asset json will be cached inside of content types json cache
		$this->dbConn();
		$sql = "SELECT asset_id,file_type,title,filename,url
				FROM ".TABLEPRE."assets WHERE active = 1 AND asset_type = '".$type."' AND join_id = '".$type_id."'
				ORDER BY rank";
		$result = mysqli_query($this->dbh,$sql);
		while ($rs = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
			$json .= $this->getAssetsJSON($rs);	
		}
		$json = $this->wrapJSONSet($wrapperName,$json);
		return $json;
	}	
/*========================================================================================
SAVE METHODS
========================================================================================*/		
	private function saveSubscriber($email,$postalCode){
		if ($email != "" && $postalCode != ""){
			$this->dbConn();
			//Check to see if they exist
			$sql = "SELECT email FROM ".TABLEPRE."subscribers WHERE active = 1 AND email = '".$email."'";
			$result = mysqli_query($this->dbh,$sql);
			if ($rs = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
				//Return a message? Maybe not?
			}else{
				$ipnum = FormatUtils::ipToNumber($this->ip);
				//We can store this in memcache and use cron to push to file/DB on regular basis
				$sql = "INSERT INTO ".TABLEPRE."subscribers (email,postal_code,date_created,date_updated,active) VALUES('".$email."','".$postalCode."','".$this->now."','".$this->now."',1)";
				mysqli_query($this->dbh,$sql);
			}
		}
	}
	private function saveVote($matchID,$charID){
		if ($matchID > 0 && $charID > 0){
			$this->dbConn();
			$ipnum = FormatUtils::ipToNumber($this->ip);
			//We can store this in memcache and use cron to push to file/DB on regular basis
			$sql = "INSERT INTO ".TABLEPRE."votes (match_id,char_id,ip,date_vote) VALUES(".$matchID.",".$charID.",".$ipnum.",'".$this->now."')";
			mysqli_query($this->dbh,$sql);
		}
	}
/*========================================================================================
TUMBLR METHODS
========================================================================================*/		
	private function likeTumblrPost($postID,$reblogKey){
		if ($_COOKIE['tumblr_user_oauth_token'] != ""){
			// Create a new instance of the Tumblr Class with the Request Tokens that we just set at line 20 and 21
			$tumblr = new Tumblr(TUMBLR_CONSUMER_KEY, TUMBLR_SECRET_KEY, $_COOKIE['tumblr_user_oauth_token'], $_COOKIE['tumblr_user_oauth_token_secret']);

			// Grab the followers by using the oauth_get method.
			$tumblrResponse = $tumblr->oauth_post("/user/like?id=" . $postID . "&reblog_key=" . $reblogKey);
			
			$this->json .= "\"likeComplete\": 1,";
		}else{
			//We'll need to store post id for user for when they're done authenticating
			setcookie("tumblr_like_post_id",$postID,time()+(365 * 24 * 60));
			setcookie("tumblr_reblog_key",$reblogKey,time()+(365 * 24 * 60));
			//Authenticate this user
			$this->getTumblrAuth();
		}
	}
	private function getTumblrAuth(){
		// Create a new instance of the Tumblr Class with your Conumser and Secret when you create your app.
		$tumblr = new Tumblr(TUMBLR_CONSUMER_KEY, TUMBLR_SECRET_KEY);

		// Get the request tokens based on your consumer and secret and store them in $token
		$token = $tumblr->getRequestToken();

		// Set session of those request tokens so we can use them after the application passes back to your callback URL
		setcookie("tumblr_request_oauth_token",$token['oauth_token'],time()+(365 * 24 * 60));
		setcookie("tumblr_request_oauth_token_secret",$token['oauth_token_secret'],time()+(365 * 24 * 60));		

		// Grab the Authorize URL and pass through the variable of the oauth_token
		$data = $tumblr->getAuthorizeURL($token['oauth_token']);

		// The user will be directed to the "Allow Access" screen on Tumblr
		$this->json .= "\"tumblrAuthURL\":" . json_encode($data) . ",";	
	}
	private function tumblrCallback($oauth_verifier){
		$tumblr = new Tumblr(TUMBLR_CONSUMER_KEY, TUMBLR_SECRET_KEY, $_COOKIE['tumblr_request_oauth_token'], $_COOKIE['tumblr_request_oauth_token_secret']);

		// The oauth_verfier is set back from Tumblr and is needed to obtain access tokens

		// User the getAcessToken method and pass through the oauth_verifier to get tokens;
		$token = $tumblr->getAccessToken($oauth_verifier);

		// Set the session for the new access tokens, replacing the request tokens
		setcookie("tumblr_user_oauth_token",$token['oauth_token'],time()+(365 * 24 * 60));
		setcookie("tumblr_user_oauth_token_secret",$token['oauth_token_secret'],time()+(365 * 24 * 60));

		//Like the post they asked for in first place...
		$this->likeTumblrPost($_COOKIE['tumblr_like_post_id'],$_COOKIE['tumblr_reblog_key']);
		
		//Redirect directly to this post id
		header('Location: '.ROOT_LOCATION.'test.php#gallery/' . $_COOKIE['tumblr_like_post_id']);
	}
	private function getTumblrPosts($action){
		$cacheID = $action;
		if ($this->forceFresh == 1){$this->cacheObj->setDataCache($cacheID,"");}
		$json = $this->cacheObj->checkDataCache($cacheID,$this->cacheSeconds);
		if ($json == ""){
			//Vars for tumblr api
			$tumblrOffset = 0;
			$tumblrPostsPerPage = 20;
		
			$postsArray = array();		
			//Go out to Tumblr and get ALL posts (several API calls)
			
			//First API call determine how many TOTAL posts there are so we can make appropriate amount of calls
			$json = file_get_contents("http://api.tumblr.com/v2/blog/". TUMBLR_BLOG ."/posts?offset=0&reblog_info=false&notes_info=false&api_key=" . TUMBLR_CONSUMER_KEY);
			
			$decodedJSON = json_decode($json);
			$postsArray = array_merge($postsArray,$decodedJSON->{'response'}->{'posts'});
			$totalPosts = intval($decodedJSON->{'response'}->{'total_posts'});
			$pages = ceil($totalPosts/$tumblrPostsPerPage);
			
			//Now cycle through and make more API calls based on total_posts
			if ($totalPosts > $tumblrPostsPerPage){
				for ($i = 1; $i < $pages; $i++) {
					$tumblrOffset = ($i*$tumblrPostsPerPage);
					$json = file_get_contents("http://api.tumblr.com/v2/blog/". TUMBLR_BLOG ."/posts?offset=".$tumblrOffset."&api_key=" . TUMBLR_CONSUMER_KEY);
					$decodedJSON = json_decode($json);					
					$postsArray = array_merge($postsArray,$decodedJSON->{'response'}->{'posts'});
				}
			}
		
			$json = json_encode($postsArray);
			$json = str_replace("timestamp","t",$json);
			$json = str_replace("width","w",$json);
			$json = str_replace("height","h",$json);
			
			$json = "\"tumblrPosts\":" . ValidationUtils::stripHiddenBreaks($json) . ",";		
			$this->cacheObj->setDataCache($cacheID,$json);			
		}	
		$this->json .= $json;
	}	
	private function getTumblrPost($postID){
		$cacheID = "tr" . $postID;
		if ($this->forceFresh == 1){$this->cacheObj->setDataCache($cacheID,"");}
		$json = $this->cacheObj->checkDataCache($cacheID,$this->cacheSeconds);
		if ($json == ""){			
			//Get post
			$json = file_get_contents("http://api.tumblr.com/v2/blog/". TUMBLR_BLOG ."/posts?id=". $postID ."&reblog_info=true&notes_info=true&api_key=" . TUMBLR_CONSUMER_KEY);
			
			$decodedJSON = json_decode($json);
			$post = $decodedJSON->{'response'}->{'posts'};
		
			$json = json_encode($post);
			$json = str_replace("timestamp","t",$json);
			$json = str_replace("width","w",$json);
			$json = str_replace("height","h",$json);
			
			$json = "\"tumblrPost\":" . ValidationUtils::stripHiddenBreaks($json) . ",";		
			$this->cacheObj->setDataCache($cacheID,$json);			
		}	
		$this->json .= $json;
	}		
	
/*========================================================================================
JSON RESULTS
========================================================================================*/	
	//Get assets associated with a content type (see example getCocktailsJSON call below)
	private function getAssetsJSON($rs){	
		$json = "{";
		$json .= "\"id\":".json_encode($rs["asset_id"]."") . ",";
		$json .= "\"title\":".json_encode($rs["title"]."") . ",";
		if ($rs["file_type"] == "images"){
			$json .= "\"img\":".json_encode(getFullImage($rs["filename"],"asset_default.png"));
		}else{
			$json .= "\"video\":".json_encode(preg_replace("(^https?://)","",$rs["url"])."");
		}
		$json .= "},";	
		return $json;
	}	
	private function getLocationsJSON($rs){	
		$json = "{";
		$json .= "\"id\":".json_encode($rs["location_id"]."") . ",";
		$json .= "\"name\":".json_encode($rs["location_name"]."") . ",";
		$json .= "\"address\":".json_encode($rs["address"]."") . ",";
		$json .= "\"city\":".json_encode($rs["city"]."") . ",";
		$json .= "\"state\":".json_encode($rs["state"]."") . ",";
		$json .= "\"postal\":".json_encode($rs["postal"]."") . ",";
		$json .= "\"coordinates\":".json_encode($rs["coordinates"]."");
		$json .= "},";	
		return $json;
	}	
	private function getSocialLinksJSON($rs){	
		$json = "{";
		$json .= "\"id\":".json_encode($rs["link_id"]."") . ",";
		$json .= "\"url\":".json_encode($rs["link_url"]."") . ",";
		$json .= "\"handle\":".json_encode($rs["handle"]."") . ",";		
		$json .= "\"body\":".json_encode(ValidationUtils::stripHiddenBreaks($rs["link_body"])."") . ",";	
		$json .= "\"img\":".json_encode(getFullImage($rs["img"],"default_social.png"));
		$json .= "},";	
		return $json;
	}	
	/*	
	private function getPostsJSON($rs){	
		$featured_cta = $this->languageResults($rs,"featured_cta");
		if ($featured_cta == ""){$featured_cta = $this->globalCopyTranslation("news_default_cta");}
		
		$json = "{";
		$json .= "\"id\":".json_encode($rs["post_id"]."") . ",";			
		$json .= "\"post_title\":".json_encode($this->languageResults($rs,"post_title")) . ",";
		$json .= "\"post_short\":".json_encode($this->languageResults($rs,"post_short")) . ",";
		$json .= "\"external_url\":".json_encode($rs["external_url"]."") . ",";
		$json .= "\"featured_cta\":". json_encode($featured_cta) . ",";
		$json .= "\"featured\":".json_encode($rs["featured"]."") . ",";	
		$json .= "\"date_posted\":". json_encode($this->dateTranslation($rs["date_posted"])) . ",";			
		$json .= "\"img\":".json_encode(getFullImage($rs["img"],"default_post.jpg"));
		$json .= "},";	
		return $json;
	}		
	private function getCocktailsJSON($rs){	
		$json = "{";
		$json .= "\"id\":".json_encode($rs["cocktail_id"]."") . ",";
		$json .= "\"title\":".json_encode($rs["cocktail_title"]."") . ",";
		$json .= "\"post_title\":".json_encode($this->languageResults($rs,"post_title")) . ","; //Example of translation of field		
		$json .= "\"desc\":".json_encode(ValidationUtils::stripHiddenBreaks($rs["cocktail_desc"])."") . ",";
		$json .= $this->getAssets("gallery","cocktails",$rs["cocktail_id"]);				
		$json .= "\"thumb\":".json_encode(getFullImage($rs["thumb"],"cocktail_thumb.png"));
		$json .= "},";	
		return $json;
	}	
	*/
}		
?>	

Anon7 - 2021