<?php

/**
 * Part of sitemush DB changing
 * This is just below $wpdb connection
 * By Default we connect to sitemush DB to verify session
 */

// We need the ABSPATH
if (!defined('ABSPATH')){
	die('Hacking Attempt');
};

global $sitepad, $globals, $l, $SESS;

function sitepad_mirrors(){
	
	global $sitepad;
	
	$r = array(
			'https://s1.softaculous.com/a/sitepad/',
			'https://s2.softaculous.com/a/sitepad/',
			'https://s3.softaculous.com/a/sitepad/',
			'https://s4.softaculous.com/a/sitepad/',
			'https://s5.softaculous.com/a/sitepad/'
		);
	
	if(!empty($sitepad['dev'])){
		return 'http://127.0.0.1/website/api/sitepad/';
	}
	
	$mirror = $r[array_rand($r)];
	
	// If the license is newly issued, we need to fetch from API only
	if(!empty($sitepad['license']['last_edit']) && (time() - 1800) < $sitepad['license']['last_edit']){
		$mirror = 'https://api.sitepad.com/';
	}
	
	// If the license is newly issued, we need to fetch from API only
	if(!empty($sitepad['server_license']['last_edit']) && (time() - 1800) < $sitepad['server_license']['last_edit']){
		$mirror = 'https://api.sitepad.com/';
	}
	
	return $mirror;
}

// This is only for static content
function sitepad_themes_api_url($theme){
	
	global $sitepad;
	
	if(!empty($sitepad['dev'])){
		return 'http://127.0.0.1/sitepad/themes/'.$theme.'/';
	}
	
	return sitepad_mirrors().'/files/themes/'.$theme.'/';
}

function sitepad_assets_url(){
	global $sitepad;
	
	$url = $sitepad['url'];
	
	if(function_exists('home_url')){
		$url = home_url();
	}
		
	return $url.'/site-data/assets';
}

// Sitepad WP URL
function sitepad_admin_url($path){
	global $sitepad;
	if($path[0] == '/'){
		$path = ltrim($path, '/');
	}
	
	$url = $sitepad['url'];
	
	if(function_exists('home_url')){
		$url = home_url();
	}
	
	return $url.'/site-admin/'.$path;
}

function sitepad_stored_web_url($id){
	return get_user_meta(1, $id.'_sitepad_domain', 1).get_user_meta(1, $id.'_sitepad_path', 1);
}

// Gives the screenshot URL
function sitepad_screenshot_relative($id){
	global $sitepad;
	return 'screenshots/'.$id.'.jpg';
}

// Check Session
function check_session_key(){

global $globals, $l, $SESS;	
	
	//May be in the GET
	//'as' - Session Key
	if(isset($_GET['as'])){
	
		$id = inputsec(htmlizer(trim($_GET['as'])));
	
		if(preg_match('~^[A-Za-z0-9]{32}$~', $id) == 0){
			
			//Return False
			return 0;
			
		}else{
		
			//Return Session ID
			return $id;
		
		}
	
	// Check the cookie
	}elseif(isset($_COOKIE[$globals['cookie_name'].'_sid']) && 
		strlen(trim($_COOKIE[$globals['cookie_name'].'_sid'])) == 32){
	
		$id = inputsec(htmlizer(trim($_COOKIE[$globals['cookie_name'].'_sid'])));

		if(preg_match('~^[A-Za-z0-9]{32}$~', $id) == 0){
			
			//Return False
			return 0;
			
		}else{
		
			//Return Session ID
			return $id;
		
		}
		
	}else{
		
		//Return False
		return 0;
	
	}

}//End of function

// Save Session
function save_session(){

global $globals, $l, $SESS;

	// Only on CP
	if(!empty($globals['iam'])){
		return false;
	}
	
	if(empty($SESS['sid'])){
		return false;
	}
	
	// Are you an admin logged in as a USER
	if(!empty($SESS['temp_uid']) && !empty($SESS['is_admin'])){	
		$SESS['uid'] = $SESS['og_uid'];
	}
	
	$SESS['ip'] = $_SERVER['REMOTE_ADDR'];
	$SESS['user-agent'] = $_SERVER['HTTP_USER_AGENT'];
	
	////////////////////////////////
	// REPLACE in the Session Table
	////////////////////////////////
	
	$res = vquery("REPLACE INTO sitemush.sessions 
					SET sid = '".$SESS['sid']."',
					last_updated = '".time()."',
					data = '".addslashes(serialize($SESS))."'");
						
	if(vsql_affected_rows($res) < 1){
		return false;
	}

	return true;

}//End of function

// Execute a select query and return an array
function vquery($query, $array = 0){
	
	global $sitepad;
	
	$result = vsql_query($query, $sitepad['conn']);
	
	if( !$result ){
			
		//Didnt get anyresult - DIE
		die('Could not make the Query.<br /><br /><br />'.$query.'<br /><br />MySQL Error No : '.vsql_errno($sitepad['conn']).'<br /><br />MySQL Error : '.vsql_error($sitepad['conn']));
			
	}
	
	return $result;
}

// Connect to the database and return the conn
function vsql_connect($host, $db, $user, $pass){
	
	global $error;
	
	// Make the Connection
	$exh = explode(':', $host);
	if(!empty($exh[1])){
		$sconn = @mysqli_connect($exh[0], $user, $pass, '', $exh[1]);
	}else{
		$sconn = @mysqli_connect($host, $user, $pass);
	}
	
	//CHECK Errors and SELECT DATABASE
	if(!empty($sconn)){	
		if(!@mysqli_select_db($sconn, $db)){
			$error['db_select'] = 'Could not select the database !';
			return false;
		}
	}else{
		$error['db_conn'] = 'Could not make the database connection !';
		return false;
	}
	
	return $sconn;

}

/**
 * Executes the query mysqli if exists else mysql
 * @package      softaculous 
 * @author       Brijesh Kothari
 * @param        string $db database to be selected
 * @param        string $conn Resource Link
 * @returns 	 bool TRUE on success or FALSE on failure
 * @since     	 4.4.3
 */
function vsql_query($query, $conn){
	
	try{
		if(extension_loaded('mysqli')){
			$return = @mysqli_query($conn, $query);
		}else{
			$return = @mysql_query($query, $conn);
		}
	}catch(Exception $e){
		return false;
	}
	
	return $return;
}

/**
 * Fetches the result into associative array from a result link mysqli if exists else mysql
 * @package      softaculous 
 * @author       Brijesh Kothari
 * @param        string $result result to fetch the data from
 * @returns 	 mixed Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows
 * @since     	 4.4.3
 */
function vsql_fetch_assoc($result){
	
	if(extension_loaded('mysqli')){
		$return = @mysqli_fetch_assoc($result);
	}else{
		$return = @mysql_fetch_assoc($result);
	}
	
	return $return;
}

/**
 * Get a result row as an enumerated array mysqli if exists else mysql
 * @package      softaculous 
 * @author       Brijesh Kothari
 * @param        string $result result to fetch the data from
 * @returns 	 mixed returns an array of strings that corresponds to the fetched row or FALSE if there are no more rows
 * @since     	 4.4.3
 */
function vsql_fetch_row($result){
	
	if(extension_loaded('mysqli')){
		$return = @mysqli_fetch_row($result);
	}else{
		$return = @mysql_fetch_row($result);
	}
	
	return $return;
}

function vsql_affected_rows($result){
	
	if(extension_loaded('mysqli')){
		$return = @mysqli_affected_rows($conn);
	}else{
		$return = @mysql_affected_rows($conn);
	}
	
	return $return;
}

function vsql_num_rows($result){
	
	if(extension_loaded('mysqli')){
		$return = @mysqli_num_rows($result);
	}else{
		$return = @mysql_num_rows($result);
	}
	
	return $return;
}

// Get the insert ID
function vsql_insert_id($conn){
	
	if(extension_loaded('mysqli')){
		$return = @mysqli_insert_id($conn);
	}else{
		$return = @mysql_insert_id($conn);
	}
	
	return $return;
}

/**
 * Returns the text of the error message from previous MySQL/MySQLi operation
 * @package      softaculous 
 * @author       Brijesh Kothari
 * @param        string $conn MySQL/MySQLi connection
 * @returns 	 string Returns the error text from the last MySQL function
 * @since     	 4.4.3
 */
function vsql_error($conn){
	
	if(extension_loaded('mysqli')){
		$return = @mysqli_error($conn);
		
		// In mysqli if connection  is not made then we will get connection error using the following function.
		if(empty($conn)){
			$return = @mysqli_connect_error();
		}
		
	}else{
		$return = @mysql_error($conn);
	}
	
	return $return;
}

/**
 * Returns the numerical value of the error message from previous MySQL operation
 * @package      softaculous 
 * @author       Brijesh Kothari
 * @param        string $conn MySQL/MySQLi connection
 * @returns 	 int Returns the error number from the last MySQL function
 * @since     	 4.4.3
 */
function vsql_errno($conn){
	
	if(extension_loaded('mysqli')){
		$return = @mysqli_errno($conn);
	}else{
		$return = @mysql_errno($conn);
	}
	
	return $return;
}

// Matches for valid characters in a domain name and returns
function is_domain($domain){
	//Made a fix to add ~ and / for MOD DIR if enabled
	return !preg_match('/[^~A-Za-z0-9_\-\/\.]/is', $domain);
	
}

// Matches for valid characters in a path and returns
function is_domain_path($path){
	
	return !preg_match('/[^A-Za-z0-9_\-\.\\/]/is', $path);
	
}

// Makes an API Call to the URL given
function get_license_info($path, $post = array()){
	
global $globals;
	
	//echo $url.'<br/>';
	
	$url = $globals['sitemush_api'].'/'.$path;
	
	// Make curl call
	$resp = curl_call($url, $post);
	
	if(empty($resp)){
		return false;
	}
	
	// Decode it
	$resp = sm_decode($resp);
	if(empty($resp)){
		return false;
	}
	
	$r = @json_decode($resp, true);
	
	if(empty($r)){
		return false;
	}
	
	return $r;
}

// Does the login - maybe, you can combine with make_session() itself
function sm_login($siteid){	
	
	global $SESS;
	
	// Create the session
	make_session();
	
	// NOTE : uid is siteid and we have used uid to avoid variable name changes of the session functions borrowed from Pinguzo	
	// Set the SITE ID
	$SESS['uid'] = $siteid;
		
	// Generate 16 Bit random token key for to prevent CSRF from every form
	$SESS['token_key'] = 'sess'.generateRandStr(16);
		
	/*// Are you an admin ?
	if($SESS['uid'] == 166){
		
		// Set you are the ADMIN
		$SESS['is_admin'] = 1;
		$SESS['uid'] = $sitemush_site['siteid'];
		$SESS['og_uid'] = $sitemush_site['siteid'];
		
	}*/
	
}

function sm_api_return($arr){
	die(json_encode($arr));
}


// Execute shell commands
function myexec($command, &$array, &$ret){
	
	if(strtoupper(substr(PHP_OS, 0, 3)) != 'WIN'){
		exec($command, $array, $ret);
		return $ret;
	}
	
	$tmpnam = 't'.rand(1, 999).".bat";
	$fp = fopen ($tmpnam, "w");
	fwrite($fp, $command);
	fclose ($fp);
	exec($tmpnam, $array, $ret);
	unlink($tmpnam);
	return $ret;
}

/**
 * Connect to the ftp server
 *
 * @param        string $host The hostname of the ftp server
 * @param        string $username The username Login detail
 * @param        string $pass The Login password
 * @param        string $cd The path of the file or directory to be changed
 * @returns 	 bool
 */
function sftp_connect($host, $username, $pass, $protocol = 'ftp', $port = 21, $cd = false, $pub = '', $pri = '', $passphrase = '', $test_upload = ''){

	global $globals, $cli_data;
	
	$port = (int) $port; // Converting to INT as FTP class requires an integer
	
	if(!class_exists('ftp_base') && $protocol == 'ftp'){	
		include_once(ABSPATH . 'site-admin/includes/ftp.php');
	}
	
	if(!class_exists('sftp') && $protocol == 'sftp'){
		include_once(ABSPATH . 'site-admin/includes/sftp.php');
	}
	
	if(!class_exists('ftps') && $protocol == 'ftps'){
		include_once(ABSPATH . 'site-admin/includes/ftps.php');
	}
	
	if(!class_exists('CustomIO') && $protocol == 'customio'){
		include_once(ABSPATH . 'site-admin/includes/customio.php');
	}
	
	if(!class_exists($protocol) && file_exists($globals['mainfiles'].'/classes/'.$protocol.'.php')){
		include_once(ABSPATH . 'site-admin/includes/'.$protocol.'.php');
	}
	
	if($protocol == 'ftp'){
		$ftp = new ftp(FALSE, FALSE);
		
		if($_GET['debug'] == 'died' && $_GET['echo'] == '1') $ftp->LocalEcho = true; 
		if($_GET['debug'] == 'died' && $_GET['verbose'] == '1') $ftp->Verbose = true; 
		
		// We get this when executing publis-cli.php via exec() in background
		if(!empty($cli_data['debug']) && $cli_data['debug'] == 'publish'){
			$ftp->LocalEcho = true;
			$ftp->Verbose = true;
		}
		
		if(!$ftp->SetServer($host, $port)) {
			$ftp->quit();
			return 0;
		}
		
		if (!$ftp->connect()) {
			return -1;
		}
		
		if (!$ftp->login($username, $pass)) {
			$ftp->quit();
			return -2;
		}
		
		if(!empty($cd)){
			if(!$ftp->chdir($cd)){
				if(!$ftp->chdir(trim($cd, '/'))){
					return -3;
				}
				//return -3;
			}
		}
		
		if(!$ftp->SetType(FTP_AUTOASCII)){
			
		}
		
		if(!$ftp->Passive(TRUE)){
			
		}
	}
	
	// Class other than FTP
	if(empty($ftp)){
	
		// Initialize a Class
		if($protocol == 'customio' && file_exists(ABSPATH . 'site-admin/includes/customio.php')){
			$ftp = new CustomIO();
		}else{
			$ftp = new $protocol();
		}
		
		// Return if Class not found
		if(!is_object($ftp)){
			return -1;
		}
		
		// For SFTP authentication with keys or password
		if($protocol == 'sftp' && !empty($pub) && !empty($pri)){
			$ftp->auth_pass = 0;
		}else{
			$ftp->auth_pass = 1;
		}
		
		// Can connect ?
		$ret = $ftp->connect($host, $port, $username, $pass, $pub, $pri, $passphrase);
		
		if(!$ret){
			return -2;
		}
		
		// Is directory present
		if(!empty($cd)){
			if(!$ftp->is_dir($cd)){
				return -3;
			}
		}
	}
	
	// Try to upload a test file (if we have to test it) This is to make sure we will be able to upload file or not
	if(!empty($test_upload)){
		
		if(!empty($test_upload) && $test_upload != "/"){
			$ftp->mkdir($test_upload);
		}
		
		if(!$ftp->softput($test_upload.'/testsitepad.html', '<html></html>')){
			return -4;
		}
		
		// Delete the test file
		$ftp->delete($test_upload.'/testsitepad.html');
	}
	
	return $ftp;
	
}

// Merge error
function error_merge($orig, $new){
	
	$orig = (!is_array() ? array($orig) : $orig);
	$new = (!is_array() ? array($orig) : $new);
	
	// Merge errors
	return array_merge($orig, $new);
	
}

function current_script_name(){
	
	$a_wp_dir = cleanpath(ABSPATH).'/';
	
	$this_script_file = str_replace($a_wp_dir, '', cleanpath($_SERVER['SCRIPT_FILENAME']));
	//echo ($this_script_file.' - '.$_SERVER['SCRIPT_FILENAME']);
	return $this_script_file;
	
}

function sm_redirect($location, $header = true, $raw = false){

global $globals, $redirect;
	
	$redirect = true;

	$prefix = (empty($raw) ? $globals['index'] : '');
	
	if(isset($_SERVER['argv']) || isset($argv)){
		$header = false;
	}
	
	if($header){
	
		//Redirect
		header("Location: ".$prefix.$location);
		
	}else{
		
		echo '<meta http-equiv="Refresh" content="0;url='.$prefix.$location.'">';
	
	}

}

// Just reads a TPL file and handles branding
function get_tpl_file($path){	
	
	// Read the file
	$data = file_get_contents($path);
	
	// Handle the branding
	$data = str_ireplace('SitePad Editor', BRAND_SM_EDITOR, $data);
	$data = str_ireplace('http://sitepad.com', BRAND_SM_URL, $data);
	$data = str_ireplace('http://www.sitepad.com', BRAND_SM_URL, $data);
	$data = str_ireplace('https://sitepad.com', BRAND_SM_URL, $data);
	$data = str_ireplace('https://www.sitepad.com', BRAND_SM_URL, $data);
	$data = str_replace('SitePad', BRAND_SM, $data);
	$data = str_replace('Sitepad', BRAND_SM, $data);
	
	return $data;
}


// encrypts the text with salt
function pass_encrypt($txt){
	
	global $universal;
	
	return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($universal['salt']), $txt, MCRYPT_MODE_CBC, md5(md5($universal['salt']))));
}
	
// decrypts the text with salt
function pass_decrypt($crypttxt){
	
	global $universal;
	
	return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($universal['salt']), base64_decode($crypttxt), MCRYPT_MODE_CBC, md5(md5($universal['salt']))), "\0");
}

/**
 * Generate the Sitemap <url> tag
 *
 * @package      sitepad
 * @author       Brijesh Kothari
 * @param        string $loc Full URL for the <loc> tag
 * @param        string $lastmod Last 
 * @param        string $changefreq Full URL for the <loc> tag
 * @param        string $priority Full URL for the <loc> tag
 * @param        string $path (Optional) If given the FETCHED data is saved in the file instead of having it returned 
 * @return       string The FETCHED DATA
 * @since     	
 */
function sitemap_url_tag($loc, $lastmod = '', $changefreq = '', $priority = ''){
	
	// Default values
	if(empty($lastmod)){
		$lastmod = date('Y-m-d', time());
	}
	
	if(empty($changefreq)){
		$changefreq = 'monthly';
	}
	
	if(empty($priority)){
		$priority = '0.5';
	}
	
	$sitemap = '<url>
	<loc>'.$loc.'</loc>
	<lastmod>'.$lastmod.'</lastmod>
	<changefreq>'.$changefreq.'</changefreq>
	<priority>'.$priority.'</priority>
</url>
';

	return $sitemap;
}

function fetch_plan($plan = ''){
	
	global $SESS, $themes;
	
	$plans = json_decode(file_get_contents(ABSPATH.'/site-data/plans.json'), true);
	
	if(empty($plan)){
		return $plans;
	}
	
	if(!empty($plans[$plan])){
		return $plans[$plan];
	}
	
	return false;
}

/**
 * A Function to add file to a ZIP file
 *
 * @package      files 
 * @author       Pulkit Gupta
 * @param        string $file The existing ZIP file Path
 * @param        string $dir The file / directory to add
 * @param        string $addpath The path in the zip of the new file(s)
 * @param        string $pre
 * @return       boolean
 * @since     	 1.0
 */
function sme_add_to_zip($file, $dir, $addpath = '', $pre = ''){

global $globals;
	
	if(!defined('PCLZIP_TEMPORARY_DIR')){
		define('PCLZIP_TEMPORARY_DIR', ($globals['os'] == 'linux' ? '/tmp/' : ''));
	}
	
	if(!class_exists('softpclzip')){
		include_once(ABSPATH . 'site-admin/includes/softaculous.pclzip.php');
	}
	
	$archive = new softpclzip($file);
	
	$rempath = (is_dir($dir) ? $dir : dirname($dir));
	
	if(empty($pre)){
	
		$result = $archive->_add($dir, PCLZIP_OPT_REMOVE_PATH, $rempath,
								  PCLZIP_OPT_ADD_PATH, $addpath,
								  PCLZIP_OPT_TEMP_FILE_ON);
								  
	}else{
	
		$result = $archive->_add($dir, PCLZIP_OPT_REMOVE_PATH, $rempath,
								  PCLZIP_OPT_ADD_PATH, $addpath,
								  PCLZIP_CB_PRE_ADD, $pre,
								  PCLZIP_OPT_TEMP_FILE_ON);
	
	}
	
	if($result == 0){
		
		if(!empty($_GET['debug']) && @$_GET['debug'] == 'soft'){
			echo $archive->errorInfo();
		}
		
		return false;
	}
	
	return true;

}

/**
 * Checks if the user can download the site
 * @package      sitepad 
 * @author       Brijesh Kothari
 * @returns 	 bool false if the user is not allowed to download the site else true
 * @since     	 4.4.3
 */
function can_download_site(){
	
	global $SESS, $sitepad;
	
	if(!empty($SESS['enable_downloads'])){
		return true;
	}
	
	if(!empty($sitepad['features']['download_site'])){
		return true;
	}
	
	return false;
}

/**
 * Encode a TEXT string into a Softaculous Encode Format
 *
 * @package      softaculous
 * @subpackage   license
 * @author       Pulkit Gupta
 * @param        string $txt The string to be encoded.
 * @return       string The encoded string.
 * @since     	 1.0
 */
function sm_encode($txt){
	
	$from = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
	
	$to = array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')');
	
	$txt = base64_encode($txt);
	$txt = str_replace($from, $to, $txt);
	$txt = gzcompress($txt);
	
	// Reverse the Bits	
	for($i = 0; $i < strlen($txt); $i++){
		$txt[$i] = sm_reverse_bits($txt[$i]);
		//echo $i.' - '.$txt[$i].' - '.sm_reverse_bits($txt[$i]).'<br>';
	}
	
	$txt = base64_encode($txt);
	
	//echo '<br>---------------<br>';
	
	return $txt;
}

/**
 * Decode a TEXT string from a Softaculous Encode Formatted string
 *
 * @package      softaculous
 * @subpackage   license
 * @author       Pulkit Gupta
 * @param        string $txt The string to be decoded.
 * @return       string The decoded string.
 * @since     	 1.0
 */
function sm_decode($txt){
	
	$from = array('!', '@', '#', '$', '%', '^', '&', '*', '(', ')');

	$to = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
	
	$txt = base64_decode($txt);
	
	// Reverse the Bits	
	for($i = 0; $i < strlen($txt); $i++){
		$txt[$i] = sm_reverse_bits($txt[$i]);
		//echo $i.' - '.$txt[$i].' - '.sm_reverse_bits($txt[$i]).'<br>';
	}
	
	$txt = gzuncompress($txt);
	$txt = str_replace($from, $to, $txt);
	$txt = base64_decode($txt);
	return $txt;
	
}

function sm_reverse_bits($orig){
	$v = decbin(ord($orig));
	$pad = str_pad($v, 8, '0', STR_PAD_LEFT);
	$rev = strrev($pad);
	$bin = bindec($rev);
	$chr = chr($bin);
	//echo $pad.' - '.$v.' - '.$txt[$i].' - '.$rev.' - '.$bin.' - '.$chr.'<br>';
	return $chr;
}

// Get languages translations
function sitepad_get_available_translations(){
	$file = WP_LANG_DIR.'/lang.json';
		
	$trans_array = array();
	$translations = file_exists($file) ? json_decode(file_get_contents($file), true) : array();
	
	if(empty($translations) || !is_array($translations)){
		return array();
	}
	
	foreach($translations as $k => $name){
		$trans_array[$k] = array(
			'language' => $k,
			'native_name' => $name,
			'iso' => array($k)
		);
	}
	
	return $trans_array;
}