<?php
class FileJobs{
	var $sChmod = '0777';
	var $sFileName;
	function setFileName( $sFileName ){
		$this->sFileName = $sFileName;
	}
	function addFile( $sFileName = null ){
		if( isset( $sFileName ) ) $this->setFileName( $sFileName );
		if( !is_file( $this->sFileName ) ){
			@touch( $this->sFileName );
			@chmod( $this->sFileName, $this->sChmod );
			if( is_file( $this->sFileName ) ) return true;
			else return false;
		} else{
			return false;
		}
	}
	function throwNameOfFile( $sName ){
		$aExp = pathinfo( $sName );
		$sName = substr( $sName, 0, -strlen( '.' . $aExp['extension'] ) );
		return $sName;
	}
	function throwExtOfFile( $sName ){
		$aExp = pathinfo( $sName );
		return $aExp['extension'];
	}
	function throwNameExtOfFile( $sName ){
		return Array( self::throwNameOfFile( $sName ), self::throwExtOfFile( $sName ) );
	}
	function checkCorrectFile( $sFileName, $exts = 'gif|jpeg|jpg|png' ){
		return preg_match( '/^(' . $exts . ')$/', mb_strtolower( self::throwExtOfFile( $sFileName ), 'UTF-8' ) );
	}
	function changeFileName( $sFileName ){
		$sFileName = mb_strtolower( $sFileName, 'UTF-8' );
		$sFileName = str_replace( ' ', '_', $sFileName );
		$sFileName = str_replace( '$', '_', $sFileName );
		$sFileName = str_replace( '\'', '_', $sFileName );
		$sFileName = str_replace( '"', '_', $sFileName );
		$sFileName = str_replace( '~', '_', $sFileName );
		$sFileName = str_replace( '/', '_', $sFileName );
		$sFileName = str_replace( '\\', '_', $sFileName );
		$sFileName = str_replace( '?', '_', $sFileName );
		$sFileName = str_replace( '#', '_', $sFileName );
		$sFileName = str_replace( '%', '_', $sFileName );
		$sFileName = str_replace( '+', '_', $sFileName );
		$sFileName = str_replace( '*', '_', $sFileName );
		$sFileName = str_replace( ':', '_', $sFileName );
		$sFileName = str_replace( '|', '_', $sFileName );
		$sFileName = str_replace( '<', '_', $sFileName );
		$sFileName = str_replace( '>', '_', $sFileName );
		return change2Latin( $sFileName );
	}
	function checkIsFile( $sOrigName, $sOutDir = '' ){
		$sExt = self::throwExtOfFile( $sOrigName );
		$sBaseName = self::throwNameOfFile( $sOrigName );
		$sResult = $sBaseName . '.' . $sExt;
		$i = 0;
		while( is_file( $sOutDir . $sResult ) ){
			$i++;
			$sResult = $sBaseName . '[' . $i . '].' . $sExt;
		}
		return $sResult;
	}
	function uploadFile( $aFiles, $sOutDir = null, $sNewName = null ){
		$sUpFileName = self::changeFileName( $aFiles['name'] );
		$sUpFileSrc = $aFiles['tmp_name'];
		if( !isset( $sNewName ) ) $sNewName = $sUpFileName;
		$sResultName = self::checkIsFile( $sNewName, $sOutDir );
		if( move_uploaded_file( $sUpFileSrc, $sOutDir . $sResultName ) || copy( $sUpFileSrc, $sOutDir . $sResultName ) ){
			chmod( $sOutDir . $sResultName, 0777 );
			return $sResultName;
		} else return null;
	}
}
?>