<?php
/*

# CloudFW Only Admin Area Functions
# Author: Orkun Gürsel - contact@orkungursel.com - support@cloudfw.net

*/


add_action('wp_ajax_cloudfw_save_changes', 'cloudfw_save_changes_callback');
function cloudfw_save_changes_callback() {
	    	
	$form_selector = isset( $_POST['form_selector'] ) ? $_POST['form_selector'] : NULL;
	if ($form_selector !== ""){

		$nonce = $_REQUEST['_wpnonce'];
		if (! wp_verify_nonce($nonce) ) {
			
			echo '{
				'.$out.'
				"messageId":	"1003",
				"messageText":	"Oopss! You are not allowed here.",
				"messageCase":	"cancel"
			}';
			exit;

		}

		$_opt = getCO();
		cloudfw_form_register($form_selector);
		global $message, $extra_query;
		
		$msgs = cloudfw_admin_messages();
		
		if (!isset($message) || empty($message)) 
			$message = 1000;
		
		if ($extra_query && is_array($extra_query)) { unset($out);
			foreach((array) $extra_query as $query_key => $query) {
				$out .= '"'.$query_key.'":	"'.$query.'",';
			}
		}
			
		echo '{
			'.$out.'
			"messageId":	"'.$message.'",
			"nonce":	"'.$_POST['_wpnonce'].'",
			"messageText":	"'.$msgs[$message]['msg'].'",
			"messageCase":	"'.$msgs[$message]['key'].'"
		}';


	}
	exit;
}

add_action('wp_ajax_image_upload', 'cloudfw_image_upload_callback');
function cloudfw_image_upload_callback() {
    	
	/*if ( ! wp_verify_nonce( $nonce, 'cloudfw') )
		die(__("Failed nonce check and the action aborted.","cloudfw"));*/

	
	include_once(TMP_ADMIN_PATH.'/classes/class.uploader.php');	

    $uploads = wp_upload_dir();
    $upload_url = $uploads['url'].'/';
    $upload_path = $uploads['path'].'/';

    $allowedExtensions = array('jpg','png','gif');
	
	$sizeLimit = apply_filters('cloudfw_upload_limit', cloudfw_upload_size());
    
    $uploader = new qqFileUploader($allowedExtensions, $upload_url, $sizeLimit);
    $result = $uploader->handleUpload( $upload_path );

    echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    exit;
}



/*
@function cloudfw_PV_make_form_name();
*/

function cloudfw_PV_make_form_name($element = NULL, $attribute = NULL) {
	if (!$element) return false;
	
	$element = str_replace("-", "_", $element);
	$out = preg_replace("#[^A-Za-z0-9_]#", "_", $element);
	
	if ($attribute) {
		$attribute = str_replace("-", "_", $attribute);
		$attribute = preg_replace("#[^A-Za-z0-9_]#", "_", $attribute);
		$out .='_'.$attribute;
	}
	
	return $out;
}

/*
@function cloudfw_exclude_options();
*/

function cloudfw_exclude_options($data = array(), $server = NULL, $folder = NULL, $server_replace = FALSE){
	
	unset($data[PFIX.'_font_engine']);
	unset($data[PFIX.'_skin_engine']);
	unset($data[PFIX.'_slider_ids']);
	unset($data[PFIX.'_skin_ids']);
	unset($data[PFIX.'_last_checked_version']);
	unset($data['cloud_created_att_page']);
	
	if ($server_replace && $server) $data = cloudfw_server_replacer($data, $server, $folder);
	
	return $data;
	
}

/*
@function cloudfw_server_replacer();
*/

function cloudfw_server_replacer($data = array(), $a = NULL, $b = NULL){
	if (!$a || !$b) return $data;

	foreach ($data as $key => $value){
		if(is_array($value)) 
			$data[$key] = cloudfw_server_replacer($value, $a, $b);
		elseif(is_string($value)) {
			
			if (strpos($value, $a) === 0) {
				
				$pathinfo = pathinfo($value);
				
				if ($pathinfo['extension'] == 'png' || $pathinfo['extension'] == 'jpg' || $pathinfo['extension'] == 'gif' || $pathinfo['extension'] == 'tiff')
					$data[$key] = TMP_URL.'/resources/'.$b.$pathinfo['filename'].'.'.$pathinfo['extension'];
				else
					$data[$key] = $value;
				
			}else{
				$data[$key] = $value;
			}
			
		}else {
			$data[$key] = $value;
		}
	}
	
	return $data;
}

/*
@function cloudfw_prepare_URI_for_export();
*/
function cloudfw_prepare_URI_for_export($data = array(), $site_url = NULL, $tag = '%%SERVER%%') {

	if (!$site_url || !$tag || !is_array($data)) 
		return $data;

	foreach ($data as $key => $value){
		if(is_array($value)) 
			$data[$key] = cloudfw_prepare_URI_for_export($value, $site_url, $tag);
		elseif(is_string($value)) {
			
			if (strpos($value, $site_url) === 0) {
				
				$pathinfo = pathinfo($value);
				
				if ($pathinfo['extension'] == 'png' || $pathinfo['extension'] == 'jpg' || $pathinfo['extension'] == 'gif' || $pathinfo['extension'] == 'tiff')
					$data[$key] = $tag.$pathinfo['filename'].'.'.$pathinfo['extension'];
				else
					$data[$key] = $value;
				
			}else{
				$data[$key] = $value;
			}
			
		}else {
			$data[$key] = $value;
		}
	}
	
	return $data;
}

/*
@function cloudfw_prepare_URI_for_import();
*/
function cloudfw_prepare_URI_for_import($data = array(), $site_url = NULL, $tag = '%%SERVER%%') {

	if (!$site_url || !$tag) 
		return $data;

	foreach ($data as $key => $value){
		if(is_array($value)) 
			$data[$key] = cloudfw_prepare_URI_for_import($value, $site_url, $tag);
		elseif(is_string($value)) {
			
			$data[$key] = str_replace($tag, $site_url, $value);
			
		}else {
			$data[$key] = $value;
		}
	}
	
	return $data;
}


/*
@function cloudfw_detect_skin_URIs();
*/

function cloudfw_detect_skin_URIs($data = array(), $site_url = NULL, $tag = '%%SERVER%%') {

	if (!$site_url || !$tag || !is_array($data)) 
		return array();

	$only_images = array();

	foreach ($data as $key => $value){
		if(is_array($value)) 
			$only_images = array_merge( (array) $only_images, (array) cloudfw_detect_skin_URIs($value, $site_url, $tag));

		elseif(is_string($value)) {
			
			if (strpos($value, $site_url) === 0) {
				
				$pathinfo = pathinfo($value);
				
				if ($pathinfo['extension'] == 'png' || $pathinfo['extension'] == 'jpg' || $pathinfo['extension'] == 'gif' || $pathinfo['extension'] == 'tiff') {
					$value = str_replace($site_url, ABSPATH, $value);
					$only_images[] = $value;
				}
				
					//$data[$key] = $value;
				
			} else{
				//$only_images[] = $value;
			}
			
		} else {
			//$data[$key] = $value;
		}
	}
	
	return $only_images;
}


/*
@function cloudfw_grouped_font_list();
*/
function cloudfw_grouped_font_list(){
	global $_opt, $custom_fonts, $google_fonts, $default_fonts;
	$fonts = cloudfw_get_fonts();
	
	$custom_array_fonts[] = array(
		'item_name'		=> __("Default",'cloudfw'),
		'item_value'		=> ""
	);
		
	if (is_array($fonts)){
	
		foreach ($fonts as $font_id) {
			
			 if (cloudfw_get_font_type($font_id) == "custom") {
					
					$custom_array_fonts[] = array(
							'item_value' 	=> $font_id,
							'item_name'		=> $custom_fonts[$font_id]["name"]
						);				
	
			}elseif (cloudfw_get_font_type($font_id) == "google") {
					
					$google_array_fonts[] = array(
							'item_value' 	=> $font_id,
							'item_name'		=> $font_id
						);				
	
			}
					
			
		} // foreach: font
		

		
	} else {return false;}	
	
				foreach((array)$default_fonts as $font_id => $font_det) {
					$default_array_fonts[] = array(
							'item_value' 	=> $font_id,
							'item_name'		=> $font_det["name"]
					);
				}
	

	// Total
	if ($default_array_fonts):
	$array_fonts[] = array(
		'group'	 		=> TRUE,
		'item_name'		=> __("System Fonts",'cloudfw'),
		'item_value'	=> $default_array_fonts
	);
	endif;
	
	if ($custom_array_fonts):
	$array_fonts[] = array(
		'group'	 		=> TRUE,
		'state'			=> 'opened',
		'item_name'		=> __("Installed Fonts",'cloudfw'),
		'item_value'	=> $custom_array_fonts
	);
	endif;
	
	if ($google_array_fonts):
	$array_fonts[] = array(
		'group'	 		=> TRUE,
		'state'			=> 'opened',
		'item_name'		=> __("Google Fonts",'cloudfw'),
		'item_value'	=> $google_array_fonts
	);
	endif;
	
	return $array_fonts;
}


/*
@function cloudfw_grouped_pattern_list();
*/

function cloudfw_grouped_pattern_list(){
	global $_opt, $patterns;
	
	$array_patterns[] = array(
		'item_name'			=> "No Pattern",
		'item_value'		=> ""
	);
		
	if (is_array($patterns)){
	
		foreach ($patterns as $pattern_id => $pattern) {
			
			$groups[] = $pattern["group"];
			
			 if ($pattern["name"]) {
					
					${$pattern["group"].'_array'}[] = array(
							'item_value' 	=> $pattern_id,
							'item_name'		=> $pattern["name"],
							'item_before'	=> '<span class="pattern-preview" style="'.$pattern["code"].'"></span>'
						);				
	
			}
					
			
		} // foreach: pattern
		

		
	} else {return false;}
	
	$groups = array_unique($groups);
	asort($groups);
	
	
	foreach ((array)$groups as $group) {
	
		$array_patterns[] = array(
			'group'	 		=> TRUE,
			'item_name'		=> $group,
			'item_value'	=> ${$group.'_array'}
		);
			
		
	}
	
	return $array_patterns;

}

/*
@function extractZip();
*/

function extractZip($file_to_open, $target) {
	$class_path = apply_filters('createZipfile', ABSPATH.'/wp-admin/includes/file.php');
	require_once($class_path);
	
	global $wp_filesystem;
	WP_Filesystem();

	return $result = unzip_file($file_to_open, $target);
}

function cloudfw_upload_size(){
	require_once(ABSPATH.'/wp-admin/includes/template.php');
	$u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  	$p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
	$sizeLimit = min($u_bytes, $p_bytes);

	if ( !$sizeLimit )
		$sizeLimit = 4 * 1024 * 1024;

	return $sizeLimit;
}