<?php

	//	генератор изображений для модулей
class admin_images{
	private $error = false;
	private $act = 'index';
	private $JsHttpRequest = false;
	
	
	function __construct(){
	global $MAIN_PAGE;
		define('M_PATH',MAIN_SOURCE_PATH.'/modules/'.$MAIN_PAGE -> dirname() );
		define('M_URL',MAIN_SOURCE_URL.'/modules/'.$MAIN_PAGE -> dirname() );
		define('A_CHARSET', $MAIN_PAGE -> charset() );
		include_once(M_PATH.'/inc/url.php');
		include(MAIN_SOURCE_PATH.'/ext/ajax/JsHttpRequest.php');
		$this -> JsHttpRequest = new JsHttpRequest( A_CHARSET );
		$this -> act = !empty($_REQUEST['act']) ? $_REQUEST['act'] : $this -> act;
		$GLOBALS['_RESULT']['id_request'] = $_REQUEST['id_request'];
	}
	

	
	function get(){
		$func = $this -> act;
		if ( !method_exists($this ,$func) ){
			sys_error(ERROR_404);
		}
		return $this -> $func();
		
		
		
	}
		//	выводим аякс форму для обработки изображений
	private function load_form(){
		
		if ( !sys_check_safe_dir($_REQUEST['path']) ){
			sys_error(ERROR_501,'Ошибка: не верно указан путь для загрузки изображения!');
		}
		
		$t = new PHPTAL( M_PATH.'/tmpl/control_images/form.html' );
		
		$t -> max_size = !empty($_REQUEST['max_size']) ? intval($_REQUEST['max_size']) : 500000 ;
		$t -> max_size_str= byte_to_str($_REQUEST['max_size']);
		$t -> path =  $_REQUEST['path'];
		$t -> crop_image_width = !empty($_REQUEST['crop_width']) ? intval($_REQUEST['crop_width']) : 0;
		$t -> crop_image_height = !empty($_REQUEST['crop_height']) ? intval($_REQUEST['crop_height']) : 0;
		$t -> max_width = !empty($_REQUEST['max_width']) ? intval($_REQUEST['max_width']) : 0;
		$t -> max_height = !empty($_REQUEST['max_height']) ? intval($_REQUEST['max_height']) : 0;
		
		return $t -> execute();
	}
	
	
	
	
			//	загружаем
	private function ajax_upload(){
	global $MAIN_DB;
		sys_block_disable();
		  //  аплод базового изображения
		include_once(MAIN_SOURCE_PATH.'/inc/class.upload.php');
		$up = new upload('ua_file');
		$up  -> access_size($_REQUEST['max_size']);
		$up  -> access_type('image');
		$up  -> set_safe_dir($_REQUEST['path']);
		$f_name = $up  -> load();
		if ( false===$f_name ){
			sys_error(ERROR_501,$up -> error() );
		}
		$name = $up -> get_result_name();
		
		
		  //  Ресайз базового изображения
		if ( !empty($_REQUEST['max_width']) || !empty($_REQUEST['max_height']) ){
		  include_once(MAIN_SOURCE_PATH.'/inc/class.img.php');
		  $save_dir = upload::get_safe_dir(); //  получим каталог
		  //echo $save_dir.$_REQUEST['path'].'/'.$name;
		  
		 $i = new img( $save_dir.$_REQUEST['path'].'/'.$name);
		 $i -> set_name($name);
		 $i -> set_path($save_dir.$_REQUEST['path'].'/');
		 $i -> resize($_REQUEST['max_width'],$_REQUEST['max_height']);
		  //$i -> 
		 
		  $i -> save();
		 // var_dump( $i);
		}
		
		$sql = "
		INSERT INTO ".$MAIN_DB -> prefix("system_files_tmp")." SET 
			user_ip = '".MAIN_USER_IP."',
			i_time = '".time()."'";
		$id = $MAIN_DB -> insert_id( $MAIN_DB -> query($sql) ) ;
		
		$sql = "
		INSERT INTO ".$MAIN_DB -> prefix("system_files_tmp_link")." SET 
			i_id = '".$id."',
			i_type = 'source',
			i_name = '".sys_in_sql($name)."',
			i_path = '".$_REQUEST['path']."'";
		$MAIN_DB -> query($sql) ;
		
		$GLOBALS['_RESULT']['img_name']= $name;
		$GLOBALS['_RESULT']['img_id']= $id;
		exit();
	}
	
		//	обрезаем изображение 
	private function ajax_crop(){
	global $MAIN_DB;
		sys_block_disable();
		$img_id = !empty($_REQUEST['img_id']) ? intval($_REQUEST['img_id']) : 0;
			//	получаем базовое изображение 
	/*	$sql = "
			SELECT ftl.i_name,ftl.i_path 
			FROM ".$MAIN_DB -> prefix("system_files_tmp")." ft
			LEFT JOIN ".$MAIN_DB -> prefix("system_files_tmp_link")." ftl
			USING(i_id)
			WHERE ft.i_id='$img_id' AND ft.user_ip='".MAIN_USER_IP."'";*/
		$sql = "
			SELECT ftl.i_name,ftl.i_path 
			FROM ".$MAIN_DB -> prefix("system_files_tmp")." ft
			LEFT JOIN ".$MAIN_DB -> prefix("system_files_tmp_link")." ftl
			USING(i_id)
			WHERE ft.i_id='$img_id' ";
		list($i_name,$i_path)= $MAIN_DB -> fetch_array($MAIN_DB -> query($sql));
		if ( empty($i_name) ){
		  sys_error(ERROR_501, 'Изображение '.$img_id.' не найдено!' );
		}
		
		include_once(MAIN_SOURCE_PATH.'/inc/class.img.php');
		$i = new img(MAIN_PATH.'/media/'.$i_path.'/'.$i_name);
		$i -> set_path(MAIN_PATH.'/media/'.$i_path);
		
		$i -> set_name($_REQUEST['crop_w'].'x'.$_REQUEST['crop_h'].'_'.$i_name);
		$i -> resize($_REQUEST['w'],$_REQUEST['h'],true);
		$i -> crop($_REQUEST['l'], $_REQUEST['t'], $_REQUEST['crop_w'], $_REQUEST['crop_h']);
		if ( false===$i -> save() ){
			sys_error(ERROR_501, $i -> error() );
		}
		$sql = "
			INSERT INTO  ".$MAIN_DB -> prefix("system_files_tmp_link")." 
			SET  
				i_id=$img_id, 
				i_name='".($_REQUEST['w'].'x'.$_REQUEST['h'].'_'.$i_name)."', 
				i_path='$i_path',
				i_type='sub'";
		$MAIN_DB -> query($sql);
		$GLOBALS['_RESULT']['img_src']= $_REQUEST['crop_w'].'x'.$_REQUEST['crop_h'].'_'.$i_name;
		exit();
	}
	
	private function ajax_delete(){
	global $MAIN_DB;
		sys_block_disable();
		$id = intval($_REQUEST['id']);
		if ( empty($id) ){
			sys_error(ERROR_501,'Ошибка: пустой идентификатор');
		}
		$sql = "
			SELECT COUNT(*) 
			FROM ".$MAIN_DB -> prefix("system_files_tmp")."
			WHERE i_id='".$id."' AND user_ip = '".MAIN_USER_IP."'";
		list($count) = $MAIN_DB -> fetch_array( $MAIN_DB -> query($sql) );
			//	нет файла или прав на его удаления
		if ( !$count ){
			exit();
		}
		
		$sql = "DELETE FROM ".$MAIN_DB -> prefix("system_files_tmp")." WHERE i_id='".$id."' ";
		$MAIN_DB -> query($sql);
		
		$sql = "DELETE FROM ".$MAIN_DB -> prefix("system_files_tmp_link")." WHERE i_id='".$id."' ";
		$MAIN_DB -> query($sql);
		
		exit();
	}

		//выводим 
	private function editor_upload(){
	global $MAIN_PAGE;	
		
		if ( preg_match('#[^0-9_a-z]#i',$_GET['module']) ){
			echo '1';
			exit();
		}
		if( !file_exists(MAIN_PATH.'/media/ck/'.$_GET['module'].'/images') ){
			echo $_GET['module'];
			exit();
		}
		
		include_once(MAIN_SOURCE_PATH.'/inc/class.upload.php');
		$funcNum = intval($_REQUEST['CKEditorFuncNum']) ;
		$name = $error ='';
		
		$u = new upload('upload');
		$u -> access_type('image');
		$u -> access_size( $MAIN_PAGE->config('sys_editor_upload_size') );
		//$u -> set_name()
		$u -> set_dir(MAIN_PATH.'media/ck/'.$_GET['module'].'/images');
		if ( !$u -> load() ){
			$error = $u -> error();
		}else{
			$name = MAIN_URL.'/media/ck/'.$_GET['module'].'/images/'.$u -> get_result_name();
			include_once(MAIN_SOURCE_PATH.'/inc/class.img.php');
			$im = new img( MAIN_PATH.'/media/ck/'.$_GET['module'].'/images/'.$u -> get_result_name() );
			$im -> set_path( MAIN_PATH.'/media/ck/'.$_GET['module'].'/preview/' );
			$im -> set_name( $u -> get_result_name() );
			$im -> resize(200,200);
			if ( !$im -> save() )
			{
				$error = $im -> error();
			}
			
		}
			
		
		echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum , '".MAIN_URL.'/media/ck/'.$_GET['module'].'/preview/'.$u -> get_result_name()." ', '$error');</script>";
		exit();
	}
	

//
	
}

?>
