<?
class file
{//DigiHex Systems\\


	function init() {}


	function upload($post, $dir, $original_name=false, $specified_name=false, $return_mime=false) {
		global $X;

		if($_FILES[$post] && $_FILES[$post]['error']==UPLOAD_ERR_OK) {
			$temp_name	= $_FILES[$post]['tmp_name'];
			$file_name	= $_FILES[$post]['name'];
			$file_type	= $_FILES[$post]['type'];
			$ext=$ext2	= $this->get_ext($file_name);

			if($ext2=='jpeg') $ext2='jpg';


			if($specified_name==true) {
				$file_name=$X->URL->mod($specified_name).'.'.$ext2;
			} else if($original_name==true) {
				$file_name=str_replace('_'.$ext, '.'.$ext2, $X->URL->mod($file_name));
			} else {
				$file_name=$X->STR->uniq().'.'.$ext2;
         }

			move_uploaded_file($temp_name, $dir.'/'.$file_name);
			@chmod($dir.'/'.$file_name,0644);
		}
		if(file_exists($dir.'/'.$file_name)) return ($return_mime==true ? array('name'=>$file_name, 'type'=>$file_type) : $file_name);
	}

	///////////////

	function flash_upload($form_name, $name, $override_dir=false, $original_name=false) {
		global $X;

		$config = $_SESSION['flash_upload'][$form_name.'_form'][$name]['config'];
		$uploaded = $_SESSION['flash_upload'][$form_name.'_form'][$name]['uploaded'];
		$src_dir = CACHE.'/uploadify/'.session_id().'/'.$form_name.'_form/'.$name.'/';
		$dst_dir=(!empty($override_dir) ? $override_dir:$config['dir']);

		@mkdir($dst_dir, 0755, true);

		if(count($uploaded)>0) foreach($uploaded as $file) {
			$src = $src_dir.$file;
			$ori_file=substr($file,0,-4); //remove _tmp
			$dst_ext=$X->FILE->get_ext($ori_file);

			if($original_name==true) {
				$base_mod=substr($X->URL->mod($ori_file),0,-(strlen($dst_ext)+1));

				for($i=1; $i<=100; $i++) {
					if(!file_exists($dst_dir.'/'.$base_mod.'.'.$dst_ext)) {
						$dst_file=$base_mod.'.'.$dst_ext;
						$ori_file=$dst_file;
						break;
					} else {
						if(!file_exists($dst_dir.'/'.$base_mod.'('.$i.').'.$dst_ext)) {
							$dst_file=$base_mod.'('.$i.').'.$dst_ext;
							$ori_file=$dst_file;
							break;
						}
					}
				}
			} else {
				$dst_file=$X->STR->uniq().'.'.$dst_ext;
//				$ori_file=$X->URL->mod($ori_file);
			}

			$dst = $dst_dir.'/'.$dst_file;
			rename($src, $dst_dir.'/'.$dst_file);
			$R[]=array('file'=>$dst_file, 'ori_file'=>$ori_file);

			if($config['multiple']!=1) break;
		}

		$X->UTIL->rmdir_rf($src_dir);

		$temp_user_dir=CACHE.'/uploadify/'.session_id().'/'.$form_name.'_form/'.$name.'/';
		if($X->UTIL->count_dir_size($temp_user_dir)==0) $X->UTIL->rmdir_rf($temp_user_dir);

		$temp_user_dir2=CACHE.'/uploadify/'.session_id().'/';
		if($X->UTIL->count_dir_size($temp_user_dir2)==0) $X->UTIL->rmdir_rf($temp_user_dir2);

		unset($_SESSION['flash_upload'][$form_name.'_form'][$name]);
		return $R;
	}


	function check_flash_upload($form_name, $name, $override_dir=false, $original_name=false) {
		global $X;

		$config = $_SESSION['flash_upload'][$form_name.'_form'][$name]['config'];
		$uploaded = $_SESSION['flash_upload'][$form_name.'_form'][$name]['uploaded'];
		$src_dir = CACHE.'/uploadify/'.session_id().'/'.$form_name.'_form/'.$name.'/';
		$dst_dir=(!empty($override_dir) ? $override_dir:$config['dir']);

		if(count($uploaded)>0) foreach($uploaded as $file) {
			$src = $src_dir.$file;
			$ori_file=substr($file,0,-4); //remove _tmp
			$R[]=array('ori_file'=>$ori_file);

			if($config['multiple']!=1) break;
		}

		return $R;
	}


	function save_flash_upload($data) {
		global $X;

		$single=(!empty($data['col']) ? true:false);
		$dir=$data['dir'];
		$original_name=$data['original_name'];

		if($single==true) {
			$files=$X->FILE->check_flash_upload($data['form'], $data['name'], $dir, $original_name);
			$F=@array_pop($files);

			if(!empty($F)) {
				$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}


				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if(!empty($data['force_filename'])) {
					$force_name=$data['force_filename'].'.'.$X->FILE->get_ext($F['file']);
					rename($dir.'/'.$F['file'], $dir.'/'.$force_name);
					$F['file']=$force_name;
				}

				$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="'.$F['file'].'" WHERE '.$data['cond'].' ');
				$R=$F['file'];
			} else {
				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if($_POST[$data['name'].'_del']==1) {
					$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
					@unlink($dir.'/'.$del_file);
					if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
						if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
					}
					$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="" WHERE '.$data['cond'].' ');
				}
				if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);
			}
		} else {
			if(count($_POST[$data['name'].'_del'])>0) foreach($_POST[$data['name'].'_del'] as $ID) {
				$del_file=$X->DB->fast(' SELECT file FROM '.$data['table'].' WHERE '.$data['cond'].' AND id="'.$ID.'" ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}
				$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$data['cond'].' AND id="'.$ID.'" ');

			}
			if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);


			$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);

			if(count($files)>0) foreach($files as $F) {
				if(empty($pozycja)) $pozycja=$X->DB->fast(' SELECT MAX(pozycja) FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				preg_match("/(.*)parent_id=\"([0-9]+)\"(.*)/", $data['cond'], $matches);
				$parent_id=$matches[2];
				if(strlen($parent_id)==0) $parent_id=$_GET['id'];
				$X->DB->q(' INSERT INTO '.$data['table'].' (parent_id,file,ori_file,pozycja'.$data['table_insert_custom_col'].') VALUES ("'.$parent_id.'","'.$F['file'].'","'.$F['ori_file'].'","'.++$pozycja.'"'.$data['table_insert_custom_val'].') ');
				$R[]=$F['file'];
			}


			if(count($_POST[$data['name'].'_pozycja'])>0) foreach($_POST[$data['name'].'_pozycja'] as $ID => $POZ) {
				if(!empty($data['custom_save_col'])) $custom_save_col=', '.$data['custom_save_col'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col']][$ID].'"';
				if(!empty($data['custom_save_col2'])) $custom_save_col2=', '.$data['custom_save_col2'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col2']][$ID].'"';
				if(!empty($data['custom_save_col3'])) $custom_save_col3=', '.$data['custom_save_col3'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col3']][$ID].'"';

				$X->DB->q(' UPDATE '.$data['table'].' SET pozycja="'.++$i.'", title="'.$_POST[$data['name'].'_title'][$ID].'" '.$custom_save_col.$custom_save_col2.$custom_save_col3.' WHERE '.$data['cond'].' AND id="'.$ID.'" ');
			}
		}

		$temp_user_dir=CACHE.'/uploadify/'.session_id().'/';
		if(count($X->FILE->read_dir($temp_user_dir))==0) $X->UTIL->rmdir_rf($temp_user_dir);

		return $R;
	}


	function save_flash_upload_fotograf($data) {
		global $X;

		$single=(!empty($data['col']) ? true:false);
		$dir=$data['dir'];
		$original_name=$data['original_name'];

		if($single==true) {
			$files=$X->FILE->check_flash_upload($data['form'], $data['name'], $dir, $original_name);
			$F=@array_pop($files);

			if(!empty($F)) {
				$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}


				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if(!empty($data['force_filename'])) {
					$force_name=$data['force_filename'].'.'.$X->FILE->get_ext($F['file']);
					rename($dir.'/'.$F['file'], $dir.'/'.$force_name);
					$F['file']=$force_name;
				}

				$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="'.$F['file'].'" WHERE '.$data['cond'].' ');
				$R=$F['file'];
			} else {
				$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);
				$F=@array_pop($files);

				if($_POST[$data['name'].'_del']==1) {
					$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
					@unlink($dir.'/'.$del_file);
					if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
						if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
					}
					$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="" WHERE '.$data['cond'].' ');
				}
				if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);
			}
		} else {
			if(count($_POST[$data['name'].'_del'])>0) foreach($_POST[$data['name'].'_del'] as $ID) {
				$del_file=$X->DB->fast(' SELECT zdjecie FROM '.$data['table'].' WHERE '.$data['cond'].' AND fotograf_zdjecia_id="'.$ID.'" ');
				@unlink($dir.'/'.$del_file);
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($dir.'/'.$X->FILE->add_suffix($del_file, $suff));
				}
				$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$data['cond'].' AND fotograf_zdjecia_id="'.$ID.'" ');

			}
			if(count($X->FILE->read_dir($dir))==0) $X->UTIL->rmdir_rf($dir);


			$files=$X->FILE->flash_upload($data['form'], $data['name'], $dir, $original_name);

			if(count($files)>0) foreach($files as $F) {
				if(empty($pozycja)) $pozycja=$X->DB->fast(' SELECT MAX(pozycja) FROM '.$data['table'].' WHERE '.$data['cond'].' ');
				preg_match("/(.*)fotograf_id=\"([0-9]+)\"(.*)/", $data['cond'], $matches);
				$parent_id=$matches[2];
				if(strlen($parent_id)==0) $parent_id=$_GET['id'];

				list($width,$height)=@getimagesize($dir.'/'.$F['file']);
				$orientation=($width>$height ? 'h':'v');
				$aspect=@($width/$height);


				$miasto=$X->DB->fast(' SELECT miasto FROM fotograf_miasta WHERE fotograf_id="'.$_SESSION['user_id'].'" ORDER BY rand() LIMIT 1 ');
				if(empty($miasto)) $miasto=$X->DB->fast(' SELECT miasto FROM fotograf WHERE id="'.$_SESSION['user_id'].'" ');
				$miasto=$X->STR->out($miasto);

				$title=$GLOBALS['PHOTO_TITLE'][round(rand(0,count($GLOBALS['PHOTO_TITLE'])-1))].' - '.$miasto;
				if(empty($title))	$title=$GLOBALS['PHOTO_TITLE'][round(rand(0,count($GLOBALS['PHOTO_TITLE'])-1))].' - '.$miasto;


				$X->DB->q(' INSERT INTO '.$data['table'].' (fotograf_id,zdjecie,title,pozycja'.$data['table_insert_custom_col'].') VALUES ("'.$parent_id.'","'.$F['file'].'","'.$title.'","'.++$pozycja.'"'.$data['table_insert_custom_val'].') ');
				$R[]=$F['file'];
			}


			if(count($_POST[$data['name'].'_pozycja'])>0) foreach($_POST[$data['name'].'_pozycja'] as $ID => $POZ) {
				if(!empty($data['custom_save_col'])) $custom_save_col=', '.$data['custom_save_col'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col']][$ID].'"';
				if(!empty($data['custom_save_col2'])) $custom_save_col2=', '.$data['custom_save_col2'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col2']][$ID].'"';
				if(!empty($data['custom_save_col3'])) $custom_save_col3=', '.$data['custom_save_col3'].'="'.$_POST[$data['name'].'_'.$data['custom_save_col3']][$ID].'"';

				$X->DB->q(' UPDATE '.$data['table'].' SET pozycja="'.++$i.'", title="'.$_POST[$data['name'].'_title'][$ID].'" '.$custom_save_col.$custom_save_col2.$custom_save_col3.' WHERE '.$data['cond'].' AND fotograf_zdjecia_id="'.$ID.'" ');
			}
		}

		$temp_user_dir=CACHE.'/uploadify/'.session_id().'/';
		if(count($X->FILE->read_dir($temp_user_dir))==0) $X->UTIL->rmdir_rf($temp_user_dir);

		return $R;
	}


	function delete_flash_upload($data) {
		global $X;

		$single=(!empty($data['col']) ? true:false);

		if($single==true) {
			$del_file=$X->DB->single(' SELECT '.$data['col'].' FROM '.$data['table'].' WHERE '.$data['cond'].' ');
			@unlink($data['dir'].'/'.$del_file);
			if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
				if(!empty($suff)) @unlink($data['dir'].'/'.$X->FILE->add_suffix($del_file, $suff));
			}
			$X->DB->q(' UPDATE '.$data['table'].' SET '.$data['col'].'="" WHERE '.$data['cond'].' ');
			if(count($X->FILE->read_dir($data['dir']))==0) $X->UTIL->rmdir_rf($data['dir']);
		} else {
			$sql=$X->DB->q(' SELECT id, file FROM '.$data['table'].' WHERE '.$data['cond'].' ORDER BY pozycja ');
			while($dane=$X->DB->fa($sql)) {
				@unlink($data['dir'].'/'.$dane['file']);
				$R[]=$dane['file'];
				if(count($data['suff_'])>0) foreach($data['suff_'] as $suff) {
					if(!empty($suff)) @unlink($data['dir'].'/'.$X->FILE->add_suffix($dane['file'], $suff));
				}
				$X->DB->q(' DELETE FROM '.$data['table'].' WHERE '.$data['cond'].' AND id="'.$dane['id'].'" ');
			}
			if(count($X->FILE->read_dir($data['dir']))==0) $X->UTIL->rmdir_rf($data['dir']);
		}
		return $R;
	}


	function table_file_single($name, $dir, $file, $title=false, $width=false, $title_w=false, $preview_suff=false, $skip_enlarge=false, $enlarge_suff=false) {
		global $X;
		if(empty($file)) return false;
		if(empty($width)) $width=405;

		return '
			<table id="'.$name.'_db_data" class="sub_data_cont sub_data_cont_single" style="width:'.$width.'px;">
				<tbody>
					<tr>
						<td>
							'.$X->FORM->hidden($name.'_exists[]',$file).'
							'.($preview_suff!==false ? '
								'.($X->FILE->get_ext($dir.$file)=='swf' ? '
									'.$X->FLASH->get('swf_'.time(),$dir.$file,'auto','auto',true).'<br /><br />
								':'
									'.($skip_enlarge!=true ? '<a href="'.$X->FILE->add_suffix($dir.$file,$enlarge_suff).'" target="_blank" class="box_img">':'').'<img src="'.$X->FILE->add_suffix($dir.$file,$preview_suff).'" alt="" />'.($skip_enlarge!=true ? '</a>':'').'
								').'
							':'').'
							'.($title!==false ? $X->FORM->input($name.'_title',(!empty($title_w)? $title_w:295),$title).'<div class="clear"></div>' : '').'
							'.($preview_suff===false ? '<a class="name" href="'.$dir.$file.'" target="_blank">'.$file.'</a>':'').'
							<span class="del">'.$X->FORM->checkbox($name.'_del',1).'<span class="ico b_no" onclick="$(this).prev().click()">Usuń</span></span>
						</td>
					</tr>
				</tbody>
			</table>
		';
//							<span class="size">'.$X->FILE->get_size($dir.$file).'</span>
	}


	function file_div($F) {
		global $X;

		if(!empty($F['img_w'])) $w=$F['img_w'];
		if(!empty($F['img_h'])) $h=$F['img_h']+40;

		if(!empty($F['cont_w'])) $w=$F['cont_w'];
		if(!empty($F['cont_h'])) $h=$F['cont_h'];

		if($F['rotate']==true) {
			$h+=20;
			$rotate='
				<div class="clr"></div>
				<div style="text-align:center; margin-top:4px;"><a href="javascript:void(0)" onclick="image_rotate(this,\'left\',\''.$F['dir'].$F['file'].'\',\''.$X->FILE->add_suffix($F['dir'].$F['file'],$F['preview_suff']).'\')"><img src="images/object-rotate-left.png" alt="" /></a> <span>obróć</span> <a href="javascript:void(0)" onclick="image_rotate(this,\'right\',\''.$F['dir'].$F['file'].'\',\''.$X->FILE->add_suffix($F['dir'].$F['file'],$F['preview_suff']).'\')"><img src="images/object-rotate-right.png" alt="" /></a></div>
			';
			$_SESSION['allow_image_rotate']=true;
		}

		return '
			<div style="width:'.$w.'px; height:'.$h.'px;">
				'.$X->FORM->hidden($F['name'].'_pozycja['.$F['id'].']',$F['pozycja']).'
				'.$X->FORM->hidden($F['name'].'_exists['.$F['id'].']',$F['file']).'
				'.($F['preview_suff']!==false ? '
					<div class="img" style="height:'.($F['img_h']).'px">
						<div style="width:'.($F['img_w']).'px">
							<a href="'.$F['dir'].$F['file'].'" target="_blank" class="box_img"><img src="'.$X->FILE->add_suffix($F['dir'].$F['file'],$F['preview_suff']).'" alt="" /></a>
						</div>
					</div>
				':'').'
				'.(isset($F['title']) ? '
					<div class="input_small_cont"><input type="text" id="'.$F['name'].'_title['.$F['id'].']" name="'.$F['name'].'_title['.$F['id'].']" class="form-control input input_small" style="'.(!empty($F['title_w'])? $F['title_w']:275).'px;" value="'.$F['title'].'"'.(!empty($F['placeholder']) ? ' placeholder="'.$F['placeholder'].'"':'').' /></div>
				':'
				').'
				<span class="del">Usuń '.$X->FORM->checkbox($F['name'].'_del[]',$F['id'],false,false,$F['name'].'_del_'.$F['id']).'<span class="ico b_no" onclick="$(this).prev().click()"></span></span>
				<span class="drag ico b_move">Przenieś</span>
				'.$rotate.'
			</div>
		';
//					<div style="margin-bottom:10px">'.$F['ori_file'].'</div>
	}


	function file_div2($F) {
		global $X;

		return '
			<div>
				'.$X->FORM->hidden($F['name'].'_pozycja['.$F['id'].']',$F['pozycja']).'
				'.$X->FORM->hidden($F['name'].'_exists['.$F['id'].']',$F['file']).'
				'.(isset($F['title']) ? $X->FORM->input($F['name'].'_title['.$F['id'].']',(!empty($F['title_w'])? $F['title_w']:275),$F['title'],false,false,'input input_small').'<br />':'').'
				<span class="drag ico b_move">Przenieś</span>
				<a href="'.$F['dir'].$F['file'].'" class="title" target="_blank" '.($F['skip_tip']!=true ? $X->FORM->tip('<span class="gray">Dodano: </span><span>'.date('Y-m-d H:i:s',@filemtime($F['dir'].$F['file'])).'</span>',true):'').'>'.$F['ori_file'].'</a>
				<span class="del">Usuń '.$X->FORM->checkbox($F['name'].'_del[]',$F['id'],false,false,$F['name'].'_del_'.$F['id']).'<span class="ico b_no" onclick="$(this).prev().click()"></span></span>
				'.$rotate.'
			</div>
		';
//					<div style="margin-bottom:10px">'.$F['ori_file'].'</div>
	}


	function sort_file_div($name, $data, $use_title=false) {
		global $X;
		if(empty($data)) return false;

		$X->JS[]=JS.'/jquery.sort/jquery.dragsort.js';

		return '
			<div id="'.$name.'_db_data" class="sub_data_cont">'.$data.'</div>
			<script type="text/javascript">$("#'.$name.'_db_data").dragsort({dragSelector:"span.drag"});</script>
		';
	}


	//////////////

	function del($post, $dir) {
		if(!empty($_POST[$post])) {
			@unlink($dir.$_POST[$post]);
			return true;
		}
	}


	function add_suffix($file, $sufix=false) {
		global $X;
		$ext=$X->FILE->get_ext($file);
		return substr($file, 0, -strlen($ext)-1).$sufix.'.'.$ext;
	}


	function get_ext($file_name) {
		return trim(strtolower(array_pop(@explode('.',$file_name))));
	}


	function get_size($file_name, $bytes=false) {
		if(!file_exists($file_name)) return '-1 MB';
		$size=filesize($file_name);
		if($bytes==true) return $size;

		if($size>=1024*1024*1024) return round($size/(1024*1024*1024), 2).' GB';
		if($size>=1024*1024) return round($size/(1024*1024), 1).' MB';
		return round($size/1024, 1).' KB';
	}


	function get_size2($file_name, $bytes=false) {
		if(!file_exists($file_name)) return '-1 MB';
		$size=filesize($file_name);
		if($bytes==true) return $size;

		if($size>=1024*1024*1024) return round($size/(1024*1024*1024), 2).' GB';
		return round($size/(1024*1024), 2).' MB';
	}


	function read_dir($dir, $add_path=false) {
		if(!is_dir($dir)) return false;
		$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST);//CHILD_FIRST
		foreach($files as $file) {
			if($file->getFilename()!='.' && $file->getFilename()!='..') $R[] = str_replace('//','/',($add_path==true ? $dir.'/':'').$file->getFilename());
		}
		@natcasesort($R);
		return $R;
	}


}//DigiHex Systems\\
?>