<?php
define("WP_ADMIN", true);
// Call WP Load
$wp_include = "../wp-load.php";$i = 0;
while (!file_exists($wp_include) && $i++ < 10) {$wp_include = "../$wp_include";} require($wp_include);
if ( !is_user_logged_in() || !current_user_can('edit_posts') ) 
	wp_die(__("You are not allowed to be here","cloudfw"));
	
require_once (TMP_ADMIN_PATH.'/classes/JSON.php'); 

if ( !is_user_logged_in() || !current_user_can('edit_posts') ) 
	wp_die(__("You are not allowed to be here", "cloudfw"));

$case = $_GET["case"];
if (!$_REQUEST['comeback']) $_REQUEST['comeback'] = $_SERVER['HTTP_REFERER'];
		
switch ($case){
	case 'export-all-options':
	default:
			
			$all_settings = cloudfw_exclude_options(getCO(NULL, FALSE));
			
			$signatured_settings = array(
					'case' => 'options',
					'key' => CLOUD_THEMEKEY,
					'server' => TMP_URL,
					'data' => $all_settings
				);
				
				

			$json = new Services_JSON();
			$parse_all_options = $json->encode($signatured_settings);
			$encoded_options = base64_encode($parse_all_options);
			
			$pfix = cloudfw_PV_make_form_name( CLOUD_THEMENAME.' '. get_bloginfo('name'));
			$the_file = CLOUD_UPLOAD_DIR."/{$pfix}_backup.backup";
			$cfile = CLOUD_UPLOAD_DIR."/{$pfix}_backup_copy.backup";
			$file = cloud_cache_write($encoded_options, $the_file, $cfile, FALSE);


			header("Content-Type: application/octet-stream");
			header("Content-Disposition: attachment; filename=" . urlencode( substr( $pfix.'_backup_'.date("Y_m_d"), 0, 200 ).'.backup'));   
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Description: File Transfer");            
			header("Content-Length: " . filesize($file));
			flush(); // this doesn't really matter.
			$fp = fopen($file, "r");
			while (!feof($fp))
			{
				echo fread($fp, 65536);
				flush(); // this is essential for large downloads
			} 
			fclose($fp);
				
	break;
	case 'export-skins':
		$ids = $_REQUEST["ids"];
		
		$pfix = substr( cloudfw_PV_make_form_name( CLOUD_THEMENAME ), 0, 200 );
		$the_file = CLOUD_UPLOAD_DIR."/{$pfix}.skin";
		$cfile = CLOUD_UPLOAD_DIR."/{$pfix}_copy.skin";
		$file = cloud_cache_write($encoded_options, $the_file, $cfile, FALSE);
		$homeURL = cloudfw_home_url();
		
		$is_ZIP = $_REQUEST['zip'];

		if (is_array($ids)) {
			$i = 0;
		
			foreach ($ids as $id) {
				
				if ($the_content = cloudfw_get_a_skin($id)):
			
					$the_content['data']['custom']['foldername'] = cloudfw_PV_make_form_name($the_content['data']['custom']["foldername"] ? $the_content['data']['custom']["foldername"] : $the_content["name"]);

					$the_content['data'] = cloudfw_prepare_URI_for_export($the_content['data'], $homeURL);
					$all_contents[$id] = $the_content;

					$i++;
				endif;
								
			}//foreach
			
			if ($i>1)
				$downloadable_file = urlencode($pfix.'_skins_'.$i.'_'.date("Y_m_d"));
			else
				$downloadable_file = urlencode($pfix.'_skins_'.cloudfw_PV_make_form_name($the_content["name"]).'_'.date("Y_m_d"));
				
		}else{
			$i = 1;
		
			if ($the_content = cloudfw_get_a_skin($ids)):
				
				
				$the_content['foldername'] = cloudfw_PV_make_form_name($the_content["name"]);
				$the_content['data']['custom']['foldername'] = cloudfw_PV_make_form_name($the_content['data']['custom']["foldername"] ? $the_content['data']['custom']["foldername"] : $the_content["name"]);

				if ($is_ZIP)	
					$to_download_images = cloudfw_detect_skin_URIs($the_content['data'], $homeURL);
				

				$the_content['data'] = cloudfw_prepare_URI_for_export($the_content['data'], $homeURL);

				$all_contents[$ids] = $the_content;
				$downloadable_file = urlencode($pfix.'_skin_'.cloudfw_PV_make_form_name($the_content["name"]).'_'.date("Y_m_d"));
			
			endif;
			
		}

		if ($to_download_images)
			$to_download_images = array_unique($to_download_images);
		
		$signatured_settings = array(
			'case' => 'skin',
			'key' => CLOUD_THEMEKEY,
			'data' => $all_contents
		);


			
		if (!$all_contents) { wp_redirect(($_REQUEST['comeback'].'&m=9013')); exit;}

		$json = new Services_JSON();
		$parse_all_options = $json->encode($signatured_settings);
		$encoded_options = base64_encode($parse_all_options);
		$file = cloud_cache_write($encoded_options, $the_file, $cfile, FALSE);


		if (!$is_ZIP || empty($to_download_images)) {
			
			header("Content-Type: application/octet-stream");
			header("Content-Disposition: attachment; filename=" . urlencode( substr( $downloadable_file, 0, 230 ).'.skin'));   
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Description: File Transfer");            
			header("Content-Length: " . filesize($file));
			flush(); // this doesn't really matter.
			$fp = fopen($file, "r");
			while (!feof($fp))
			{
				echo fread($fp, 65536);
				flush(); // this is essential for large downloads
			} 
			fclose($fp);

		} else {
			
			$class_path = apply_filters('createZipfile', TMP_ADMIN_PATH.'/classes/class.createZipFile.php');

			if (!$class_path)
				exit;

			include_once($class_path);

			$no_found_count = 0;
				
			$createZip = new CreateZipFile;
			$createZip->addFile($encoded_options, urlencode( substr( $downloadable_file, 0, 230 ).'.skin'));

			if (is_array($to_download_images)) {
				foreach ($to_download_images as $img) {

					if (file_exists($img)) {
						$filecontent = file_get_contents($img);
						$pathinfo = pathinfo($img);

						if ($filecontent)
							$createZip->addFile($filecontent, $pathinfo['filename'].'.'.$pathinfo['extension']);
						else {
							$no_found_count++;
							$no_found_paths .= "{$no_found_count}:\t'{$img}' source of the file cannot read\r\n";
						}
												
					} else {
						
						$no_found_count++;
						$no_found_paths .= "{$no_found_count}:\t'{$img}' file cannot found\r\n";
					}

				}
			}

			/*echo ABSPATH. ' -> ' .$homeURL;

			echo '<pre>';
			 print_r($to_download_images);
			echo '</pre>';*/
			//echo $no_found_paths; exit;

			$folder_name = $the_content['foldername'];
			if ($no_found_count > 0) {

				$createZip->addFile($no_found_paths, "error_log.txt");
				$folder_name = "With_{$no_found_count}_Error_{$folder_name}";
			}


			$zipFileName = ( substr( $folder_name, 0, 230 ).'.zip');
			$handle      = fopen($zipFileName, 'wb');
			$out         = fwrite($handle, $createZip->getZippedFile());
			 
			fclose($handle);				 
			$createZip->forceDownload($zipFileName);
			 
			@unlink($zipFileName);


		}

			
	break;
	
	case 'export-sliders':
			$ids = $_REQUEST["ids"];
			
						
			$pfix = cloudfw_PV_make_form_name(CLOUD_THEMENAME);
			$the_file = CLOUD_UPLOAD_DIR."/{$pfix}_backup.backup";
			$cfile = CLOUD_UPLOAD_DIR."/{$pfix}_backup_copy.backup";
			$file = cloud_cache_write($encoded_options, $the_file, $cfile, FALSE);
			$sliders = get_option(PFIX.'_slider_ids');
			$homeURL = cloudfw_home_url();
			$is_ZIP = $_REQUEST['zip'];
			$to_download_images = array();

			
			if (is_array($ids)) {
				$i = 0;
			
				foreach ($ids as $id) {
					
					if ($sliders[$id]):
						
						$sliders[$id]['foldername'] = $folder_name = cloudfw_PV_make_form_name($sliders[$id]["foldername"] ? $sliders[$id]["foldername"] : $sliders[$id]["title"]);

						$the_slider = $sliders[$id];
						$the_content = get_option($id);

						if ($is_ZIP){
							$to_download_images = array_merge((array) $to_download_images, (array) cloudfw_detect_skin_URIs($the_slider, $homeURL));
							$to_download_images = array_merge((array) $to_download_images, (array) cloudfw_detect_skin_URIs($the_content, $homeURL));
						}

						$all_contents[$id] = array(
							'main'	=> cloudfw_prepare_URI_for_export($the_slider, $homeURL),
							'data'	=> cloudfw_prepare_URI_for_export($the_content, $homeURL)
						);
						$i++;
						
					endif;
									
				}//foreach
				
				if ($i>1)
					$downloadable_file = urlencode($pfix.'_sliders_'.$i.'_'.date("Y_m_d"));
				else
					$downloadable_file = urlencode($pfix.'_slider_'.cloudfw_PV_make_form_name($sliders[$id]["title"]).'_'.date("Y_m_d"));
					
			}else{
			
					if ($sliders[$ids]):
						
						$sliders[$ids]['foldername'] = $folder_name = cloudfw_PV_make_form_name($sliders[$ids]["foldername"] ? $sliders[$ids]["foldername"] : $sliders[$ids]["title"]);

						$the_slider = $sliders[$ids];
						$the_content = get_option($ids);

						if ($is_ZIP){
							$to_download_images = array_merge((array) $to_download_images, (array) cloudfw_detect_skin_URIs($the_slider, $homeURL));
							$to_download_images = array_merge((array) $to_download_images, (array) cloudfw_detect_skin_URIs($the_content, $homeURL));
						}

						$all_contents[$ids] = array(
							'main'	=> cloudfw_prepare_URI_for_export($the_slider, $homeURL),
							'data'	=> cloudfw_prepare_URI_for_export($the_content, $homeURL)
						);
						$downloadable_file = urlencode($pfix.'_slider_'.cloudfw_PV_make_form_name($sliders[$ids]["title"]).'_'.date("Y_m_d"));
						
											
					endif;
					
			}

			if ($to_download_images)
				$to_download_images = array_unique($to_download_images);
				
			$signatured_settings = array(
				'case' => 'slider',
				'key' => CLOUD_THEMEKEY,
				'data' => $all_contents
			);


			if (!$all_contents) { wp_redirect(($_REQUEST['comeback'].'&m=9013')); exit;}

			$json = new Services_JSON();
			$parse_all_options = $json->encode($signatured_settings);
			$encoded_options = base64_encode($parse_all_options);
			$file = cloud_cache_write($encoded_options, $the_file, $cfile, FALSE);


		if (!$is_ZIP || empty($to_download_images)) {

			header("Content-Type: application/octet-stream");
			header("Content-Disposition: attachment; filename=" . urlencode( substr( $downloadable_file, 0, 230 ).'.slider'));   
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Description: File Transfer");            
			header("Content-Length: " . filesize($file));
			flush(); // this doesn't really matter.
			$fp = fopen($file, "r");
			while (!feof($fp)) {
				echo fread($fp, 65536);
				flush(); // this is essential for large downloads
			} 
			fclose($fp);

		} else {
			
			// ZIP
			$class_path = apply_filters('createZipfile', TMP_ADMIN_PATH.'/classes/class.createZipFile.php');

			if (!$class_path)
				exit;

			include_once($class_path);

			$no_found_count = 0;
				
			$createZip = new CreateZipFile;
			$createZip->addFile($encoded_options, urlencode( substr( $downloadable_file, 0, 230 ).'.slider'));

			if (is_array($to_download_images)) {
				foreach ($to_download_images as $img) {

					if (file_exists($img)) {
						$filecontent = file_get_contents($img);
						$pathinfo = pathinfo($img);

						if ($filecontent)
							$createZip->addFile($filecontent, $pathinfo['filename'].'.'.$pathinfo['extension']);
						else {
							$no_found_count++;
							$no_found_paths .= "{$no_found_count}:\t'{$img}' source of the file cannot read\r\n";
						}
												
					} else {
						
						$no_found_count++;
						$no_found_paths .= "{$no_found_count}:\t'{$img}' file cannot found\r\n";
					}

				}
			}

			if ($no_found_count > 0) {

				$createZip->addFile($no_found_paths, "error_log.txt");
				$folder_name = "With_{$no_found_count}_Error_{$folder_name}";
			}


			$zipFileName = ( substr( $folder_name, 0, 230 ).'.zip');
			$handle      = fopen($zipFileName, 'wb');
			$out         = fwrite($handle, $createZip->getZippedFile());
			 
			fclose($handle);				 
			$createZip->forceDownload($zipFileName);
			 
			@unlink($zipFileName);

		}
			
	break;					
}


?>