<?php

/**
 * FilesystemTools
 *
 * @author Eugene I. Nezhuta
 */
class RCMS_Tools_FilesystemTools {

/**
 * This function returns content of file.
 * @param string $filePath
 * @return string
 */
	static public function getFile($filePath) {
		if(!file_exists($filePath)) {
			throw new Exception('Can\'t find this file or this file doesn\'t exist');
		}
		return file_get_contents($filePath);
	}

	/**
	 * This function saves content into a file.
	 * @param string $filePath
	 * @param string $fileContent
	 * @return boolean
	 */
	static public function saveFile($filePath, $fileContent) {
		if(false === file_put_contents($filePath, $fileContent)) {
			throw new Exception('Can\'t save file. Something went wrong');

		}
		return true;
	}

	/**
	 * This function deletes a file.
	 * @param string $fileName
	 * @return boolean
	 */
	static public function deleteFile($fileName) {
		$fileName = (string) trim($fileName);

		if($fileName === '') {
			return false;
		}

		if(file_exists($fileName)) {
			return @unlink($fileName);
		}
		else {
			return false;
		}

	}

	/**
	 * This function is validated files name.
	 * @param string $fileName
	 * @return string
	 */
	static public function validateName($name) {
		$name = (string) trim($name);
		if($name === '') {
			return '';
		}
		$name = str_replace(' ', '-', $name);
		return strtolower(preg_replace("/[\s\$\#\%\<\>\.\*\&\(\)\}\{\+\,\=\/\|\?\@\!\~\^\:\'\"\[\]\_\\\]/", '', $name));

	}

	/**
	 * This function are scaning a directory and returns array of files.
	 * @param string $path
	 * @return array
	 */
	static public function scanDir($path) {
		$path = (string) trim($path);
		$files = array();

		if($path === '') {
			return $files;
		}

		if(is_dir($path)) {
			$dir = @scandir($path);
			if(empty($dir)) {
				return array();
			}

			foreach($dir as $file) {
				if($file !== '.' && $file !== '..' && $file !== '.svn' && $file !== '.htaccess')
					$files[] = $file;
			}
		}
		return $files;
	}

	/**
	 * This function creates a directory.
	 * @param string $pathName
	 * @return boolean
	 */
	static public function mkDir($pathName) {
		$pathName = (string) trim($pathName);

		if($pathName === '') {
			return false;
		}

		if(!is_dir($pathName)) {
			return @mkdir($pathName);
		}
		else {
			return false;
		}
	}

	/**
	 * This function is removing a directory.
	 * @param string $dirName
	 * @return boolean
	 */
	static public function rmDir($dirName) {
		$dirName = (string) trim($dirName);

		if($dirName === '') {
			return false;
		}

		if(is_dir($dirName)) {
			return @rmdir($dirName);
		}
		else {
			return false;
		}
	}

	/**
	 * This function deletes a lot of spaces.
	 * @param string $string
	 * @return string
	 */
	static public function trimInternalSpaces($string) {
		if($string) {
			$pattern = "/[\s]+/";
			return preg_replace($pattern, " ", trim($string));
		}
	}

	/**
	 * This function checks if a file exists.
	 * @param string $filePath
	 * @return boolean
	 */
	static public function isFileExists($filePath) {
		return file_exists($filePath);
	}

	/**
	 * This function finds files where type of files equal $ext.
	 * @param string $dir
	 * @param string $ext
	 * @return array or boolean
	 */
	static public function findFilesByExt($dir, $ext) {
		$extFiles = array();
		$files = array();
		$files = self::scanDir($dir);
		if(!empty($files)) {
			foreach ($files as $file) {
				if(preg_match('/[a-zA-Z0-9-_\s]+\.'.$ext.'/', $file)) {
					$extFiles[] = $file;
				}
			}
			if(!empty ($extFiles)) {
				return $extFiles;
			}
		}
		return false;
	}

	/**
	 *
	 * @param string $directory
	 * @param boolean $empty
	 * @return boolean
	 */
	static public function recursive_remove_directory($directory, $empty=FALSE) {
	// if the path has a slash at the end we remove it here
		if(substr($directory,-1) == '/') {
			$directory = substr($directory,0,-1);
		}

		// if the path is not valid or is not a directory ...
		if(!file_exists($directory) || !is_dir($directory)) {
		// ... we return false and exit the function
			return FALSE;

		// ... if the path is not readable
		}elseif(!is_readable($directory)) {
		// ... we return false and exit the function
			return FALSE;

		// ... else if the path is readable
		}else {

		// we open the directory
			$handle = opendir($directory);

			// and scan through the items inside
			while (FALSE !== ($item = readdir($handle))) {
			// if the filepointer is not the current directory
			// or the parent directory
				if($item != '.' && $item != '..' && $item != '.svn' && $item != 'pfs.prs') {
				// we build the new path to delete
					$path = $directory.'/'.$item;

					// if the new path is a directory
					if(is_dir($path)) {
					// we call this function with the new path

						self::recursive_remove_directory($path);

					// if the new path is a file
					}else {
					// we remove the file

						@unlink($path);
					}
				}
			}
			// close the directory
			closedir($handle);

			// if the option to empty is not set to true
			//         if($empty == FALSE)
			//        {
			//             // try to delete the now empty directory
			//             if(!@rmdir($directory))
			//             {
			//                 // return false if not possible
			//                 return FALSE;
			//             }
			//
			//         }
			// return success
			return TRUE;
		}
	}


	/**
	 *
	 * @param string $directory
	 * @param string $empty
	 * @return boolean
	 */
	static public function recursive_remove_files_from_directory($directory, $empty=FALSE) {
	// if the path has a slash at the end we remove it here
		if(substr($directory,-1) == '/') {
			$directory = substr($directory,0,-1);
		}

		// if the path is not valid or is not a directory ...
		if(!file_exists($directory) || !is_dir($directory)) {
		// ... we return false and exit the function
			return FALSE;

		// ... if the path is not readable
		}elseif(!is_readable($directory)) {
		// ... we return false and exit the function
			return FALSE;

		// ... else if the path is readable
		}else {

		// we open the directory
			$handle = opendir($directory);

			// and scan through the items inside
			while (FALSE !== ($item = readdir($handle))) {
			// if the filepointer is not the current directory
			// or the parent directory
				if($item != '.' && $item != '..' && $item != 'pfs.prs' && $item != 'cache') {
				// we build the new path to delete
					$path = $directory.'/'.$item;

					// if the new path is a directory
					if(is_dir($path)) {
					// we call this function with the new path
						self::recursive_remove_directory($path);

					// if the new path is a file
					}else {
					// we remove the file

						@unlink($path);
					}
				}
			}
			// close the directory
			closedir($handle);

			// if the option to empty is not set to true
       /*  if($empty == FALSE)
        {
             // try to delete the now empty directory
             if(!rmdir($directory))
             {
                 // return false if not possible
                 return FALSE;
             }
         }*/
			// return success
			return TRUE;
		}
	}

	/**
	 *
	 * @param string $themeName
	 * @return void
	 */
	public static function createZip($themeName) {
		$websitePath  = unserialize(Zend_Registry::get('config'))->website->website->path;
		$websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		ini_set('max_execution_time', 300);
		// create object
		$zip = new ZipArchive();
		// open archive
		if(is_file($websitePath.'public/themes/'.$themeName.'/'.$themeName.'.zip')) {
			@unlink($websitePath.'public/themes/'.$themeName.'/'.$themeName.'.zip');
		}
		if ($zip->open($websitePath.'public/themes/'.$themeName.'/'.$themeName.'.zip', ZIPARCHIVE::CREATE) !== TRUE) {
			die ('Could not open archive');
		}

		$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($websitePath.'public/themes/'.$themeName));

		foreach ($iterator as $key=>$value) {
			$zip->addFile($key, strstr($key,$themeName)) or die ('ERROR: Could not add file: $key');
		}
		// close and save archive
		$zip->close();
		return $websiteUrl.'themes/'.$themeName.'/'.$themeName.'.zip';
	}

	public static function normalize ($string,$pageId) {

		$table = array(
			'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
			'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
			'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
			'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
			'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
			'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
			'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
			'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
		);
		$string = preg_replace('/[^_A-Za-z0-9\.]/','',strtr($string, $table));
		if(trim($string)=="") {
			$string = $pageId;
		}
		return $string;
	}

	 public static function cutStringOnWords($cuttedString,$length){
		$substr = substr($cuttedString, 0, $length);
		$arr = explode(" ", $substr);
		$arrLen = sizeof($arr);

		if($arr[$arrLen-1]!='' || $arr[$arrLen-1]!=" "){
			$arr[$arrLen-1] = '';
		}
		return implode(" ", $arr);
	 }
}