<?php

require_once(dirname(__FILE__).'/../init.php');
require_once(dirname(__FILE__).'/../de_lang/language.php');

if (!isset($_GET['action'])) die(errorImageEditingActionNotDefined);

switch ($_GET['action']) {
	case 'step1':
		if (isset($_SESSION['editImageSkipFileName'])) {
			if ($_SESSION['editImageSkipFileName']==1) {
				SkipFileName();
				break;
			}
		}
		AskForFileName();
		break;
	case 'step2':
		SaveEditedFile();
		break;
	default:
		die(errorImageEditingActionUnknown);
		break;
}

die();










function SkipFileName() {

	if (!isset($_GET['source_image'])) {
		HandleError(errorImageEditing.errorImageEditingSourceNotDefined, true);
	}

	$localarray = DefineLocalFileName($_GET['source_image']);
	if ($localarray['error']) {
		HandleError($localarray['error_str'], false);
	}

	$_SESSION['editImageSavePathInformation'] = $localarray;

	die(
<<<EOT
<html>
<head>
	<title>Media Manager</title>
	<script type="text/javascript">
		if(document.all) {
			var css_file_2 = "iemm.css";
		} else {
			var css_file_2 = "mzmm.css";
		}
		document.write('<link rel="stylesheet" href="{$skin_path}/'+css_file_2+'" type="text/css">');
	</script>
</head>
<body style="background-color: #EAE8E4">

<script type="text/javascript">
location.href = location.href.replace(/action=step1/,'action=step2') + '&save_file_as='+escape('{$localarray['save_filename']}')+'&sk1={$skin_path}#{$skin_file}';
</script>
</body>
</html>
EOT
	);
}










function AskForFileName() {
	// define the new file location
	// define the library:
	if (!isset($_GET['source_image'])) {
		HandleError(errorImageEditing.errorImageEditingSourceNotDefined, true);
	}

	$localarray = DefineLocalFileName($_GET['source_image']);
	if ($localarray['error']) {
		HandleError($localarray['error_str'], false);
	}

	$_SESSION['editImageSavePathInformation'] = $localarray;

	$filestring = $localarray['other_files'];

	$savepath = ImageEditingSavingDirectory." {$localarray['save_rel_path']}";
	$question = ImageEditingSavingFile;
	$diff_extension = ImageEditingDifferentExtension;
	$save = ImageEditingSaveImageButton;
	$back = ImageEditingBackToImageButton;
	$overwritefile = ImageEditingImageAlreadyExists;
	
	list($skin_path, $skin_file) = explode('#',$_GET['sk1']);

	die(
<<<EOT
<html>
<head>
	<title>Media Manager</title>
	<script type="text/javascript">
		if(document.all) {
			var css_file_2 = "iemm.css";
		} else {
			var css_file_2 = "mzmm.css";
		}
		document.write('<link rel="stylesheet" href="{$skin_path}/'+css_file_2+'" type="text/css">');
	</script>
</head>
<body style="background-color: #EAE8E4">

<div align="center">
<div class="ImageSaveFormBox">
<p>{$savepath}</p>
<p>{$question} <input id="filenameinput" type="text" value="{$localarray['save_filename']}"></p>
<p><input type="button" value="{$back}" onClick="history.back();" class="ImageSaveForm"> <input type="button" value="{$save}" onClick="GoToStep1()" class="ImageSaveForm"></p>
</div></div>
<script type="text/javascript">
var currentfiles = new Array({$filestring});
function GoToStep1() {
	filename = document.getElementById('filenameinput').value;
	extpos = filename.lastIndexOf('.');
	tst = true;
	if (extpos==-1) {
		extension = '{$image_original_extension}';
		filename = filename + '.' + extension;
	} else {
		extension = filename.substr(extpos+1);
	}
	if (extension.toLowerCase()!='{$localarray['save_extension']}'.toLowerCase()) {
		tst = confirm('{$diff_extension}');
		if (!tst) {
			return false;
		}
	}
	var found = false;
	for (idx=0; idx<currentfiles.length; idx++) {
		if (currentfiles[idx]==filename) {
			found = true;
			break;
		}
	}
	if (found) {
		tst = confirm('{$overwritefile}');
		if (!tst) {
			return false;
		}
	}
	GoToStep2(filename);
}

function GoToStep2(fn) {
	location.href = location.href.replace(/action=step1/,'action=step2') + '&save_file_as='+escape(fn)+'&sk1={$skin_path}#{$skin_file}';
}
</script>
</body>
</html>
EOT
	);
}










function SaveEditedFile() {
	if (!isset($_GET['snipshot_output'])) {
		HandleError(errorImageEditing.errorImageEditingImageNotDefinedOnQuery, true);
	}
	if (!isset($_GET['save_file_as'])) {
		HandleError(errorImageEditing.errorImageEditingFileNameNotDefined, true);
	}
	if (!isset($_GET['source_image'])) {
		HandleError(errorImageEditing.errorImageEditingSourceNotDefined, true);
	}
	$_GET['save_file_as'] = urldecode($_GET['save_file_as']);
	if ($_GET['save_file_as']=='') {
		HandleError(errorImageEditing.errorImageEditingFileNameNotDefined, true);
	}
	if (!isset($_SESSION['editImageSavePathInformation'])) {
		HandleError(ImageEditingSavePathInformation,true);
	}
	if (!isset($_SESSION['editImageSavePathInformation']['save_path'])) {
		HandleError(ImageEditingSavePathInformation,true);
	}
	if (!isset($_SESSION['editImageSavePathInformation']['save_rel_path'])) {
		HandleError(ImageEditingSavePathInformation,true);
	}
	
	$invalid_chars = array('/','\\');
	foreach($invalid_chars as $iv) {
		if (is_numeric(strpos($_GET['save_file_as'],$iv))) {
			HandleError(errorImageEditing.errorImageEditingFileNameInvalid, true);
		}
	}

	$fileInfo = GetPageContents($_GET['snipshot_output']);

	if ($fileInfo[0]===false) {
		switch($fileInfo[1]) {
			case 'no curl or fopen support':
				$fileInfo[1] = errorImageEditing.errorImageEditingNoCurlOrFopen;
				$b = false;
				break;
			case 'cant read url':
				$fileInfo[1] = errorImageEditing.errorImageEditingCantReadURL;
				$b = false;
				break;
			case 'No URL':
				$fileInfo[1] = errorImageEditing.errorImageEditingURLNotDefined;
				$b = false;
				break;
			default:
				$fileInfo[1] = errorImageEditing.errorImageEditingCurlSaid.$fileInfo[1];
				$b = true;
				break;
		}
		HandleError($fileInfo[1],$b);
	}

	$new_file_name = eregi_replace("/{2,}", "/", $_SESSION['editImageSavePathInformation']['save_path'].'/'.$_GET['save_file_as']);

	$file_already_exists = false;
	if (file_exists($new_file_name)) {
		$file_already_exists = true;
	}	

	$new_file = fopen($new_file_name,'w');
	if ($new_file===false) {
		HandleError(errorImageEditingCouldNotCreateImageFile);
	}

	$written = fwrite($new_file, $fileInfo[0]);
	if ($written===false) {
		HandleError(errorImageEditingCouldNotSaveImageFile);
	}

	fclose($new_file);


	// if you got here, things are good
	HandleError(
		ImageEditingImageSaved.$_GET['save_file_as'],
		null,
		"window.opener.document.jsobj = 'image'; window.opener.ChangeLib('{$_SESSION['editImageSavePathInformation']['save_rel_path']}', '{$_GET['save_file_as']}');"
	);

}








function HandleError($c,$back=false,$other='') {
	$h = '';
	if ($back)			$h = 'history.back();';
	if(isset($_GET['sk1'])) {
		list($skin_path, $skin_file) = explode('#',$_GET['sk1']);
		$styles =
<<<EOT
	<script type="text/javascript">
		if(document.all) {
			var css_file_2 = "iemm.css";
		} else {
			var css_file_2 = "mzmm.css";
		}
		document.write('<link rel="stylesheet" href="{$skin_path}/'+css_file_2+'" type="text/css">');
	</script>
EOT;
	} else {
		$styles = '';
	}

	$close = ImageEditingCloseWindow;

	//if (is_null($back)) $h = 'opener.editImageWindow.close();';
	die(
<<<EOT
<html>
<head>
	<title>Media Manager - Editing File</title>
{$styles}
</head>
<body style="background-color: #EAE8E4">

<div align="center">
<div class="ImageSaveFormBox">
<p>{$c}</p>
<p><input type="button" onClick="window.opener.executeImageSelection(); window.close();" value="{$close}"></p>
</div></div>

<script type="text/javascript">
{$other}
{$h}
</script>
</body>
</html>
EOT
	);
}










/**
* GetPageContents
* Returns the url's contents.
*
* @param String $url The url to import from.
*
* @return False|String Returns false if there is no url or it can't be opened (invalid url). Otherwise returns the content from the url. Tries to use curl functions if they are available, otherwise it uses 'fopen' if it's available (ie safe-mode is off and it's not disabled).
*/
function GetPageContents($url='')
{
	if (!$url) {
		return array(false, 'No URL');
	}

	if (function_exists('curl_init')) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		if (!ini_get('safe_mode')) {
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		}
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);

		$pageData = curl_exec($ch);

		if (!$pageData) {
			$error = curl_error($ch);
		}
		curl_close($ch);

		if (!$pageData) {
			return array(false, $error);
		}
		return array($pageData, true);
	}

	if (!ini_get('allow_url_fopen')) {
		return array(false, 'no curl or fopen support');
	}

	if (!@$fp = fopen($url, "rb")) {
		return array(false, 'cant read url');
	}

	// Grab the files content
	$pageData = "";

	while (!feof($fp)) {
		$pageData .= fgets($fp, 4096);
	}

	fclose($fp);

	return array($pageData, true);
}











/********************************************************************
* returns
*	array (
*		'save_path'		=> string
*		'save_rel_path'	=> string
*		'save_filename'	=> string
*		'save_complete'	=> string
*		'save_extension'=> string
*		'overwrite'		=> boolean
*		'url'			=> string
*		'error_str'		=> string
*		'error'			=> boolean
*		'other_files'	=> array
*	);
********************************************************************/

function DefineLocalFileName($fileurl) {

	$res = array();

	$res['url'] = $fileurl;
	$res['error_str'] = 'no match';
	$res['error'] = false;
	$res['overwrite'] = false;
	$res['other_files'] = '';
	$res['save_filename'] = array_pop(explode('/', $fileurl));
	$res['save_extension'] = array_pop(explode('.', $res['save_filename']));

	if (isset($_SESSION['editImageSavePath'])) {

		if (($_SESSION['editImageSavePath']!='') && (!is_null($_SESSION['editImageSavePath']))) {

			$res['save_rel_path']	= eregi_replace("/{2,}", "/", '/'.$_SESSION['editImageSavePath']);
			$res['save_path']		= eregi_replace("/{2,}", "/", $_SESSION['userdocroot'].'/'.$_SESSION['editImageSavePath']);
			$res['save_complete']	= eregi_replace("/{2,}", "/", $res['save_path'].'/'.$res['save_filename']);
			if (file_exists($res['save_path'])) {
				$res['overwrite'] = file_exists($res['save_complete']);
				$res['other_files'] = ListFilesAsJSArray($res['save_path']);
				return $res;
			} else {
				$res['error_str'] = ImageEditingSavePathNotDefined.' '.$res['save_path'];
			}

		}

	}

	$islocalfile = strpos($fileurl, $_SESSION['serverurl']);
	if (is_numeric($islocalfile)) {

		if ($islocalfile==0) {

			if (isset($_SESSION['editImageSaveAnywhere'])) {
				if ($_SESSION['editImageSaveAnywhere']==1) {

					$image_original_http_path_array = explode('/', trim(str_replace($_SESSION['serverurl'], '', $fileurl), '/'));
					$image_original_file_name = array_pop($image_original_http_path_array);
					$image_original_path = implode('/', $image_original_http_path_array);

					$res['save_rel_path']	= eregi_replace("/{2,}", "/", '/'.$image_original_path);
					$res['save_path']		= eregi_replace("/{2,}", "/", $_SESSION['userdocroot'].'/'.$image_original_path);
					$res['save_complete']	= eregi_replace("/{2,}", "/", $res['save_path'].'/'.$res['save_filename']);

					if (file_exists($res['save_path'])) {
						$res['overwrite'] = file_exists($res['save_complete']);
						$res['other_files'] = ListFilesAsJSArray($res['save_path']);
						return $res;
					} else {
						$res['error_str'] = ImageEditingSavePathNotDefined.' '.$res['save_path'];
					}

				}
			}

		}

	}


	$res['save_rel_path']	= eregi_replace("/{2,}", "/", '/'.$_SESSION['imgDir']);
	$res['save_path']		= eregi_replace("/{2,}", "/", $_SESSION['userdocroot'].'/'.$_SESSION['imgDir']);
	$res['save_complete']	= eregi_replace("/{2,}", "/", $res['save_path'].'/'.$res['save_filename']);

	if (file_exists($res['save_path'])) {
		$res['overwrite'] = file_exists($res['save_complete']);
		$res['other_files'] = ListFilesAsJSArray($res['save_path']);
		return $res;
	} else {
		$res['error_str'] = ImageEditingSavePathNotDefined.' '.$res['save_path'];
	}


	$res['error'] = true;

	return $res;

}










function ListFilesAsJSArray($path) {
	$path = eregi_replace("/{2,}", "/", $path.'/*');
	$lst = array();
	foreach(glob($path) as $fl) {
		if (($fl=='.') || ($fl=='..')) continue;
		$filename = array_pop(explode('/',$fl));
		$lst[] = $filename;
	}
	return '"'.implode('","',$lst).'"';
}

?>