<?php

class FileUploader {

	private $_column = '';
	private $_glob = '';
	private $_cnf = array();
	private $_foundFolders = array();
	private $_record = null;
	private $BAD_FILE_SIGNS = array();
	private $OK_FILE_SIGNS  = array();
	private $_lastUploadedFile = null;

	public function __construct($column, $record) {
		$this->_column = $column;
		$this->_record = $record;
		$this->BAD_FILE_SIGNS = array('.', ' ', ',',  '/',   'ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż', 'Ą', 'Ć', 'Ę', 'Ł', 'Ń', 'Ó', 'Ś', 'Ź', 'Ż');
		$this->OK_FILE_SIGNS  = array('-', '_', '--', '---', 'a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z', 'A', 'C', 'E', 'L', 'N', 'O', 'S', 'Z', 'Z');
	}

	public function setConfig($conf, &$errMsg = '') {
		$DBG = (V::get('DBG_F', 0, $_GET, 'int') > 0);
		$this->_cnf['LOCAL_PATH'] = V::get('mount_point', null, $conf);
		$this->_cnf['PATH'] = V::get('share_point', null, $conf);
		$this->_cnf['WWW'] = V::get('www_share_point', null, $conf);
		$this->_cnf['LOOKAT_FOLDER'] = array();
		$this->_cnf['LOOKAT_FILES'] = array();// LOOKAT_FILES_LOOK_GLOB
		$this->_cnf['DEST_FOLDER'] = array();
		foreach ($conf as $key => $val) {
			if (substr($key, 0, 14) == 'LOOKAT_FOLDER_') {
				$key = substr($key, 14);
				$this->_cnf['LOOKAT_FOLDER'][$key] = $val;
			}
			else if (substr($key, 0, 12) == 'DEST_FOLDER_') {
				$key = substr($key, 12);
				$this->_cnf['DEST_FOLDER'][$key] = $val;
			}
			else if (substr($key, 0, 13) == 'LOOKAT_FILES_') {
				$key = substr($key, 13);
				$this->_cnf['LOOKAT_FILES'][$key] = $val;
			}
		}
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">this->_conf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_cnf);echo'</pre>'."\n"; }
		foreach ($this->_cnf as $key => $val) {
			if ($key == 'LOOKAT_FILES') {
				continue;
			}
			if ($val == null) {
				$errMsg = "Brak wartości dla {$key}.";
				return false;
			}
		}

		if (!is_writable($this->_cnf['LOCAL_PATH'])) {
			$errMsg = "Error: brak uprawnień do zapisu w głównym katalogu!";
			return false;
		}
		return true;
	}

	private function setLastUploadedFile($lastUploadedFile) {
		$this->_lastUploadedFile = $lastUploadedFile;
	}

	public function getLastUploadedFile() {
		return $this->_lastUploadedFile;
	}

	public function getFolderWeb() {
		return $this->_cnf['WWW'];
	}

	public function getLocalPath() {
		return $this->_cnf['LOCAL_PATH'];
	}

	function findFolder() {
		$DBG = (V::get('DBG_F', 0, $_GET, 'int') > 0);
		if (!empty($this->_foundFolders)) {
			return $this->_foundFolders;
		}
		$this->_foundFolders = array();
		if (empty($this->_cnf['LOOKAT_FOLDER'])) {
			return $this->_foundFolders;
		}

		$look = new stdClass();
		//$look->regex = V::get('LOOK_REGEX', '', $this->_cnf['LOOKAT_FOLDER']);
		$look->glob = V::get('LOOK_GLOB', '', $this->_cnf['LOOKAT_FOLDER']);
		$look->varname = array();
		$look->varname['VARNAME']  = V::get('VARNAME', '', $this->_cnf['LOOKAT_FOLDER']);
		$look->varname['VARNAME1'] = V::get('VARNAME1', '', $this->_cnf['LOOKAT_FOLDER']);
		$look->varname['VARNAME2'] = V::get('VARNAME2', '', $this->_cnf['LOOKAT_FOLDER']);
		$look->varname['VARNAME3'] = V::get('VARNAME3', '', $this->_cnf['LOOKAT_FOLDER']);
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$look (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($look);echo'</pre>'; }
		foreach ($look->varname as $kName => $vVar) {
			if ($vVar) {
				if (isset($this->_record->{$vVar})) {
					$vVar = $this->_record->{$vVar};
				}

				$look->glob = str_replace("<{$kName}>", $vVar, $look->glob);
			}
		}
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">look->glob (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($look->glob);echo'</pre>'."\n"; }
		$foundFolders = glob("{$this->_cnf['LOCAL_PATH']}/{$look->glob}", GLOB_ONLYDIR & GLOB_NOSORT);
		if (false == $foundFolders) {
			return false;
		} else {
			foreach ($foundFolders as $vFolder) {
				$this->_foundFolders []= end(explode('/', $vFolder));
			}
		}
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">this->_foundFolders (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($this->_foundFolders);echo'</pre>'."\n"; }
		return $this->_foundFolders;
	}

	function cleanFilenamePart($part) {
		if ($part == '') return '_';
		$part = str_replace($this->BAD_FILE_SIGNS, $this->OK_FILE_SIGNS, trim($part));
		if (strlen($part) > 20) $part = substr($part, 0, 20) . '_';
		$part = preg_replace('/[^0-9a-zA-Z\-_]/', '_', $part);
		return $part;
	}

	/**
	 * TODO: 
	 */
	function generateFolderName() {
		$DBG = false;

		$folderParts = array();
		$look = new stdClass();
		$look->format = V::get('FORMAT', '', $this->_cnf['DEST_FOLDER']);
		$look->varname = array();
		$look->varname['VARNAME']  = V::get('VARNAME', '', $this->_cnf['DEST_FOLDER']);
		$look->varname['VARNAME1'] = V::get('VARNAME1', '', $this->_cnf['DEST_FOLDER']);
		$look->varname['VARNAME2'] = V::get('VARNAME2', '', $this->_cnf['DEST_FOLDER']);
		$look->varname['VARNAME3'] = V::get('VARNAME3', '', $this->_cnf['DEST_FOLDER']);
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$look (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($look);echo'</pre>'; }
		foreach ($look->varname as $kName => $vVar) {
			if (!empty($vVar)) {
				if (isset($this->_record->{$vVar})) {
					if ($vVar == 'M_DIST_DESC') {
						$badPrefixes = array();
						$badPrefixes[] = 'Sprawy związane z ';
						$badPrefixes[] = 'Sprawy związane ze ';
						$badPrefixes[] = 'Sprawy zwiazane z ';
						$badPrefixes[] = 'Sprawy zwiazane ze ';
						$badPrefixes[] = 'Sprawy prowadzone przez ';
						$badPrefixes[] = 'Sprawy ';

						foreach ($badPrefixes as $vBadPrefix) {
							$prefixLen = strlen($vBadPrefix);
							if (substr($this->_record->{$vVar}, 0, $prefixLen) == $vBadPrefix) {
								$this->_record->{$vVar} = substr($this->_record->{$vVar}, $prefixLen);
								break;
							}
						}
					}

					$part = $this->cleanFilenamePart($this->_record->{$vVar});
				}
				if (empty($part)) {
					$part = '_';
				}
				$look->format = str_replace("<{$kName}>", $part, $look->format);
			}
		}
		if (false !== strpos('<', $look->format) || false !== strpos('>', $look->format)) {
			return false;// TODO: blad konfiguracji - brakuje definicji zmiennych
		}
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$look (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($look);echo'</pre>'; }
		return $look->format;
	}

	function generateFolderName__OLD() {
		$dir_tree = array();
		foreach ($this->_cnf['DEST_FOLDER'] as $k => $v_fldr) {
			$look = new stdClass();
			$look->regex = V::get('LOOK_REGEX', '', $v_fldr);
			$look->varname = array();
			foreach ($v_fldr['VARNAME'] as $k_var_ind => $v_look) {
				if (false !== strpos($v_look, '$_SESSION[$thiss->DETECT_TABLE_COLUMN][EDITRECORD][')) {
					$v_look = substr($v_look, strlen('$_SESSION[$thiss->DETECT_TABLE_COLUMN][EDITRECORD]['), -1);
					$v_look = V::get($v_look, '', $_SESSION[$this->_column]['EDITRECORD']);
				}
				$v_look = (empty($v_look))? '_' : $this->cleanFilenamePart($v_look);

				$look->regex = str_replace('<VARNAME' . $k_var_ind.'>', $v_look, $look->regex);
			}

			if (false !== strpos('<', $look->regex) || false !== strpos('>', $look->regex)) {
				die('<p>' . "Error: Blad konfiguracji \$FOLDERS[{$this->_column}_DEST_FOLDER]" . '</p>');
			} else {
				$dir_tree []= $look->regex;
			}
		}
		return implode('/', $dir_tree);
	}

	function getDestFolder($show_if_not_found = false) {
		if (empty($this->_foundFolders)) {
			if ($show_if_not_found) {
				return $this->generateFolderName();
			} else {
				return null;
			}
		} else {
			return reset($this->_foundFolders);
		}
	}

	function getDestPathShare($show_if_not_found = false) {
		$dest_dir = $this->getDestFolder($show_if_not_found);
		if (!$dest_dir) {
			return null;
		}
		return $this->_cnf['PATH'] . '/' . $dest_dir;
	}

	function getDestLocalPath($show_if_not_found = false) {
		$dest_dir = $this->getDestFolder($show_if_not_found);
		if (!$dest_dir) {
			return null;
		}
		return "{$this->_cnf['LOCAL_PATH']}/{$dest_dir}";
	}

	function getFoundFolders() {
		return $this->_foundFolders;
	}

	function getFilesFromFolder($folder, $fileNamesOnly = false, $recursive = false) {
		$DBG = (V::get('DBG_F', 0, $_GET, 'int') > 0);
		if (empty($folder)) {
			return false;
		}
		$look = new stdClass();
		if ($this->_cnf['LOOKAT_FILES']) {
			//$look->regex = V::get('LOOK_REGEX', '', $this->_cnf['LOOKAT_FOLDER']);
			$look->glob = V::get('LOOK_GLOB', '', $this->_cnf['LOOKAT_FILES']);
			$look->varname = array();
			$look->varname['VARNAME']  = V::get('VARNAME', '', $this->_cnf['LOOKAT_FILES']);
			$look->varname['VARNAME1'] = V::get('VARNAME1', '', $this->_cnf['LOOKAT_FILES']);
			$look->varname['VARNAME2'] = V::get('VARNAME2', '', $this->_cnf['LOOKAT_FILES']);
			$look->varname['VARNAME3'] = V::get('VARNAME3', '', $this->_cnf['LOOKAT_FILES']);
			if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$look (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($look);echo'</pre>'; }
			foreach ($look->varname as $kName => $vVar) {
				if ($vVar) {
					if (isset($this->_record->{$vVar})) {
						$vVar = $this->_record->{$vVar};
					}

					$look->glob = str_replace("<{$kName}>", $vVar, $look->glob);
				}
			}
		} else {
			$look->glob = "*.*";
		}
		$ret = glob("{$this->_cnf['LOCAL_PATH']}/{$folder}/{$look->glob}", GLOB_NOSORT);
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">glob('."{$this->_cnf['LOCAL_PATH']}/{$folder}/*.*".') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ret);echo'</pre>'; }
		if ($recursive) {
			$retSubFolderFiles = glob("{$this->_cnf['LOCAL_PATH']}/{$folder}/*/*.*", GLOB_NOSORT);
			if ($retSubFolderFiles !== false) {
				foreach ($retSubFolderFiles as $vFile) {
					if ($fileNamesOnly == true) {
						$ret[] = str_replace("{$this->_cnf['LOCAL_PATH']}/{$folder}/", '', $vFile);
					} else {
						$ret[] = $vFile;
					}
				}
			}
		}

		if (false === $ret) {
			return false;
		} else {
			foreach ($ret as $k => $vFile) {
				if ($fileNamesOnly == true) {
					$ret[$k] = str_replace("{$this->_cnf['LOCAL_PATH']}/{$folder}/", '', $vFile);
				} else {
					$ret[$k] = $vFile;
				}
			}
		}
		return $ret;
	}

	function getFilesFromSkany($skanyConf, $fileNamesOnly = false) {
		$DBG = (V::get('DBG_F', 0, $_GET, 'int') > 0);
		if (empty($skanyConf)) {
			return false;
		}
		$skanyLocalPath = V::get('mount_point', '', $skanyConf);
		if (empty($skanyLocalPath)) {
			return false;
		}
		$ret = glob("{$skanyLocalPath}/*.*", GLOB_NOSORT);
		if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">glob('."{$this->_cnf['LOCAL_PATH']}/{$folder}/*.*".') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ret);echo'</pre>'; }
		if (false === $ret) {
			return false;
		} else {
			foreach ($ret as $k => $vFile) {
				if ($fileNamesOnly == true) {
					$ret[$k] = end(explode('/', $vFile));
				} else {
					$ret[$k] = $vFile;
				}
			}
		}
		return $ret;
	}

	function showFoundFolders() {// TODO: RMME not used
		$cnt_dirs = count($this->_foundFolders);
		if ($cnt_dirs > 1) {
			echo '<p style="color:red">' . "Odnaleziono {$cnt_dirs} folderów, przenieś pliki do jednego folderu i usuń błędnie nazwane." . '</p>';
		} else if ($cnt_dirs == 0) {
			echo '<p>' . "Nie odnaleziono folderu - zostanie utworzony automatycznie podczas dodawania pliku." . '</p>';
		} else {
			echo '<p style="color:green">' . "Odnaleziono odpowiedni folder: " . '<code><b>' . $this->getDestFolder() . '</b></code>' . '</p>';
		}
		foreach ($this->_foundFolders as $v_dir) {
			$v_files = $this->getFilesFromFolder($v_dir);
			$path_samba = $this->_cnf['PATH'] . '/' . $v_dir;
			$path_www = $this->_cnf['WWW'] . '/' . $v_dir;
			echo '<table cellspacing="0" cellpadding="0" border="0" style="margin:20px 0;border:1px solid #777;">';
				echo '<tr><td colspan="3" bgcolor="#ccf" style="font-size:small;"><img src="icon/ms_directory.gif" border="0">' . "Adres:" . '<a href="' . "file://{$path_samba}" . '">' . $path_samba . '</a>' . " WWW: " . '<a href="' . $path_www . '" target="_blank">' . "(Web)" . '</font></a> </td></tr>';
				echo '<tr>';
					echo '<th style="border-right:1px solid #777;text-align:left;">' . "Nazwa" . '</th>';
					echo '<th style="border-right:1px solid #777;text-align:left;">' . "Rozmiar" . '</th>';
					echo '<th style="text-align:left;">' . "Typ" . '</th>';
				echo '</tr>';
				if (empty($v_files)) {
					echo '<tr><td colspan="3">' . '<i style="color:#777;">' . "Folder jest pusty" . '</i>' . '</td></tr>';
				} else {
					foreach ($v_files as $v_file) {
						$v_file_name = end(explode('/', $v_file));
						$v_file_www = $path_www . '/' . $v_file_name;
						echo '<tr>';
							echo '<td style="border-right:1px solid #777;">' . $v_file_name . '</td>';
							echo '<td style="border-right:1px solid #777;text-align:right">' . filesize($v_file) . " B" . '</td>';
							echo '<td>' . (is_dir($v_file)? "Folder" : "Plik") . " " . '<a href="' . $v_file_www . '" target="_blank">' . "(Web)" . '</a>' . '</td>';
						echo '</tr>';
					}
				}
			echo '</table>';
		}
	}

	/**
	 * TODO: obecnie działa tylko werjs tryUploadAjax
	 */
	function tryUpload() {
		return false;

		if ($_FILES['M_DIST_FILES_NAME']['error'] > 0) {
			echo '<p style="color:red">Error: Wystąpił błąd podczas wgrywania pliku: ' . $_FILES['M_DIST_FILES_NAME']['error'] . '</p>';
			return;
		}

		echo '<div style="border:1px solid #777">';
			echo 'Informacje o wgrywanym pliku:<br />';
			echo 'Nazwa: ' . $_FILES['M_DIST_FILES_NAME']['name'] . '<br>';
			echo 'Typ: ' . $_FILES['M_DIST_FILES_NAME']['type'] . '<br>';
			echo 'Rozmiar: ' . $_FILES['M_DIST_FILES_NAME']['size'] . ' B<br>';
			if ($_SESSION['DEBUG']) echo 'Stored in: ' . $_FILES['M_DIST_FILES_NAME']['tmp_name'];
		echo '</div>';

		//if (false === strpos($_SESSION[$this->_column]['PERMEDIT']['M_DIST_FILES'], "W")) {
		//	echo '<p>' . "Error: Brak uprawnień do zapisu (W) dla pola M_DIST_FILES." . '</p>';
		//	return;
		//}

		if (!is_uploaded_file($_FILES['M_DIST_FILES_NAME']['tmp_name'])) {
			echo '<p>' . "Error: Wystąpił błąd podczas wgrywania pliku." . '</p>';
			return;
		}

		$IN7_FILERENAME = $this->renameFile($_POST, $_FILES['M_DIST_FILES_NAME']['name'], $this->getDestLocalPath(true));
		if ($IN7_FILERENAME == false) {
			return false;
		}

		if (!empty($IN7_FILERENAME['ERROR'])) {
			echo "<br> <font color=red> Wystapil error (".$IN7_FILERENAME['ERROR'].")<br>EOL.";
		}
		else if (!empty($IN7_FILERENAME['DST_FILE_NAME']) && !empty($IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER'])) {

			if (!move_uploaded_file($_FILES['M_DIST_FILES_NAME']['tmp_name'], $IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER'] . "/" . $IN7_FILERENAME['DST_FILE_NAME'])) {
				echo '<hr /><h1 style="color:red">' . "Error: plik nie został przeniesiony do odpowiedniego katalogu, " . '<a href="JavaScript:window.close()">zamknij to okno i wroc do wczesniejszego</a></h1>';
			}
			else {
				echo "<br>wykonalem funkcje move dla parametrow ".$_FILES['M_DIST_FILES_NAME']['tmp_name']." oraz ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME'] ." <br>Informacje dodatkowe :".$IN7_FILERENAME['INFO']." <br> EOL <br> ";

				if (file_exists($IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME'])) {
					echo '<hr /><h1 style="color:green">' . "Plik został poprawnie wgrany do odpowiedniego katalogu, " . '<a href="JavaScript:window.close()">zamknij to okno i wroc do wczesniejszego</a></h1>';
					IN7_POST_HISTORY($TABLE, array('M_DIST_FILES'), array(" Wgrano plik z przegladarki WWW ".$_SERVER['REMOTE_ADDR']." ".$_FILES['M_DIST_FILES_NAME']['name']." do ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME']." "), $thiss, $SESSION);
				}
				else {
					echo '<hr /><h1 style="color:red">' . "PLIK NIE ZOSTAL WGRANY BLAD/ERROR, " . '<a href="JavaScript:window.close()">zamknij to okno i wroc do wczesniejszego</a></h1>';
				}
			}
		}
	}

	function tryUploadAjax(&$errorMsg) {
		if ($_FILES['M_DIST_FILES_NAME']['error'] > 0) {
			$errorMsg = 'Wystąpił błąd podczas wgrywania pliku: ' . $_FILES['M_DIST_FILES_NAME']['error'] . '';
			return false;
		}
/*
		echo '<div style="border:1px solid #777">';
			echo 'Informacje o wgrywanym pliku:<br />';
			echo 'Nazwa: ' . $_FILES['M_DIST_FILES_NAME']['name'] . '<br>';
			echo 'Typ: ' . $_FILES['M_DIST_FILES_NAME']['type'] . '<br>';
			echo 'Rozmiar: ' . $_FILES['M_DIST_FILES_NAME']['size'] . ' B<br>';
			if ($_SESSION['DEBUG']) echo 'Stored in: ' . $_FILES['M_DIST_FILES_NAME']['tmp_name'];
		echo '</div>';
*/
		//if (false === strpos($_SESSION[$this->_column]['PERMEDIT']['M_DIST_FILES'], "W")) {
		//	echo '<p>' . "Error: Brak uprawnień do zapisu (W) dla pola M_DIST_FILES." . '</p>';
		//	return;
		//}

		if (!is_uploaded_file($_FILES['M_DIST_FILES_NAME']['tmp_name'])) {
			$errorMsg = ' Wystąpił błąd podczas wgrywania pliku';
			return;
		}

		$renameErrorMsg = '';
		$IN7_FILERENAME = $this->renameFile($_POST, $_FILES['M_DIST_FILES_NAME']['name'], $this->getDestLocalPath(true), $renameErrorMsg);
		if ($IN7_FILERENAME == false) {
			$errorMsg = "Wystąpił błąd podczas zmiany nazwy wgrywanego pliku: {$renameErrorMsg}.";
			return false;
		}

		if (!empty($IN7_FILERENAME['ERROR'])) {
			$errorMsg = "Wystąpiły błądy podczas zmiany nazwy wgrywanego pliku: '{$IN7_FILERENAME['ERROR']}'";
		}
		else if (!empty($IN7_FILERENAME['DST_FILE_NAME']) && !empty($IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER'])) {
			$newFilePath = "{$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']}/{$IN7_FILERENAME['DST_FILE_NAME']}";
			if (!move_uploaded_file($_FILES['M_DIST_FILES_NAME']['tmp_name'], $newFilePath)) {
				$errorMsg = "plik nie został przeniesiony do odpowiedniego katalogu";
			}
			else {
				if (file_exists($newFilePath)) {
					$this->setLastUploadedFile($newFilePath);
					return true;
				}
				else {
					$errorMsg = "PLIK NIE ZOSTAL WGRANY BLAD/ERROR";
				}
			}
		}
		return false;
	}

	function tryMoveFromScanAjax(&$errorMsg) {
		$destFolderPath = $this->getDestLocalPath(true);

		$skanFileName = V::get('SCANS_COLUMN_ADD', '', $_POST);
		if (empty($skanFileName)) {
			$errorMsg = 'Nie wybrano pliku ze skanów';
			return false;
		}

		Lib::loadClass('FoldersConfig');
		$skanyConf = FoldersConfig::getAll('SCANS_COLUMN');
		$skanyLocalPath = V::get('mount_point', '', $skanyConf);
		$skanyFiles = $this->getFilesFromSkany($skanyConf, true);

		if (!in_array($skanFileName, $skanyFiles)) {
			$errorMsg = 'Wybrany plik nie istnieje w skanach';
			return false;
		}

		$renameErrorMsg = '';
		$IN7_FILERENAME = $this->renameFile($_POST, $skanFileName, $destFolderPath, $renameErrorMsg);
		if ($IN7_FILERENAME == false) {
			$errorMsg = "Wystąpił błąd podczas zmiany nazwy wgrywanego pliku: {$renameErrorMsg}.";
			return false;
		}

		if (!empty($IN7_FILERENAME['ERROR'])) {
			$errorMsg = "Wystąpiły błądy podczas zmiany nazwy wgrywanego pliku: '{$IN7_FILERENAME['ERROR']}'";
		}
		else if (!empty($IN7_FILERENAME['DST_FILE_NAME']) && !empty($IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER'])) {
			$newFilePath = "{$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']}/{$IN7_FILERENAME['DST_FILE_NAME']}";
			if (!copy("{$skanyLocalPath}/{$skanFileName}", "{$newFilePath}")) {
				$errorMsg = "Plik nie został przeniesiony do odpowiedniego katalogu";
			}
			else {
				unlink("{$skanyLocalPath}/{$skanFileName}");
				if (file_exists("{$newFilePath}")) {
					$this->setLastUploadedFile($newFilePath);
					return true;
				}
				else {
					$errorMsg = "Plik nie został przenisiony ze skanów";
				}
			}
		}
		return false;
	}

	/**
	 * TODO: obecnie działa tylko wersja tryMoveFromScanAjax
	 */
	function tryMoveFromScan() {
		return false;
		$dest_folder = $this->getDestLocalPath(true);

		foreach ($_POST as $POST_I => $POST_V) {
			if (false === strpos($POST_I, 'SCANS_COLUMN_ADD__')) continue;

			echo "<br> Proba przeniesienia pliku ze SCANS_COLUMN \n";
			$SCAN_PLIK = end(explode('__',$POST_I));
			echo "DLa ID {$SCAN_PLIK} ";
			echo $_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FOLDER'];

			$IN7_FILERENAME = $this->renameFile($_POST, $_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FILE'], $dest_folder);

			if (($IN7_FILERENAME['DST_FILE_NAME'])&&($IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER'])&&(!$IN7_FILERENAME['ERROR'])) {
				if(file_exists($_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FOLDER']."/".$_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FILE'])) {
				if(copy($_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FOLDER']."/".$_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK][FILE],$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME'])) {
				chmod("$IN7_FILERENAME[M_DIST_FILES_DEST_FOLDER]."/".$IN7_FILERENAME[DST_FILE_NAME]", 0777);
				unlink($_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FOLDER']."/".$_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FILE']);
				} else $IN7_FILERENAME['ERROR'].="COPY_ERROR Problem z kopiowaniem pliku w docelowe miejsce , ";
				} else $IN7_FILERENAME['ERROR'].="COPY_ERROR Problem z kopiowaniem brak pliku zrodlowego , ";
				echo "<br>wykonalem funkcje move dla parametrow ".$_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FOLDER']."/".$_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FILE']." oraz ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME'] ." <br>
				Informacje dodatkowe :".$IN7_FILERENAME['INFO']." <br> EOL <br> <hr><h1>PRAWDOPODOBNIE WGRALES PLIK, zamknij to okno i wroc do wczesniejszego</h1>";
			} else if($IN7_FILERENAME['ERROR']) {
				echo "<br> <font color=red> Wystapil error (".$IN7_FILERENAME['ERROR'].")<br>EOL.";
			}
			if ($IN7_FILERENAME['ERROR']) {
				echo "<br> <font color=red> Wystapil error (".$IN7_FILERENAME['ERROR'].")<br>EOL.";
			}
			else {
				SEF('IN7_POST_HISTORY');
				IN7_POST_HISTORY($TABLE,array('M_DIST_FILES'),array("Przeniesiono plik z folderu ".$_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FOLDER']."/".$_SESSION["SCANS_COLUMN"]["ADD_FILE"][$SCAN_PLIK]['FILE']." do ".$IN7_FILERENAME['M_DIST_FILES_DEST_FOLDER']."/".$IN7_FILERENAME['DST_FILE_NAME']." "),$thiss,$SESSION);
			}
		}
	}

	function _isDate($str) {
		$str_arr = explode("-", $str);
		if (count($str_arr) == 3 &&
			strlen($str_arr[2]) == 2 &&
			strlen($str_arr[1]) == 2 &&
			strlen($str_arr[0]) == 4 &&
			$str_arr[0] > 1980 &&
			$str_arr[0] < 9999 &&
			$str_arr[1] <= 12 &&
			$str_arr[2] <= 33
		) {
			return true;
		}
		return false;
	}

	/**
	 * Rename file by params.
	 * 
	 * @param array $params
	 * @param string $FILENAME_POST
	 * @param string $dest_folder
	 * 
	 * @returns array (
	 *                  'M_DIST_FILES_DEST_FOLDER',
	 *                  'DST_FILE_NAME',
	 *                  'ERROR',
	 *                  'INFO'
	 *                )
	 */
	function renameFile($params, $FILENAME_POST, $dest_folder, &$errorMsg = '') {
		$genLog = array();// return array
		$genLog_INDEX = array();
		$postFileNameByDot = explode('.', $FILENAME_POST);
		$postFileNameBy_ = explode('_', $FILENAME_POST);

		if (empty($params['M_DIST_FILES_TYPE'])) {
			$errorMsg = "nie wybrano typu pliku";
			return false;
		}

		$genLog['INDEXNAME'] = $this->_record->ID;
		$genLog['EXT'] = end($postFileNameByDot);

		$genLog['TYPE'] = $params['M_DIST_FILES_TYPE'];
		if (!empty($params['M_DIST_FILES_TEMP'])) {
			$genLog['TYPE'] .= "_TEMP";
		}

		// set $genLog['DATE'], $genLog_INDEX['DATE']
		// use $params M_DIST_FILES_DATE
		$postFileNameBy_Cnt = count($postFileNameBy_);
		if ($postFileNameBy_Cnt >= 2 && $postFileNameBy_Cnt <= 7) {
			foreach ($postFileNameBy_ as $ind => $file_part) {
				if ($this->_isDate($file_part)) {
					if (empty($params['M_DIST_FILES_DATE'])) {
						$genLog['DATE'] = $file_part;
					}
					$genLog_INDEX['DATE'] []= array('PREFIX'=>"_", 'INDEKS'=>"$ind", 'VALUE'=>$file_part);
				}
			}
		}

		// set $genLog['DATE'], $genLog_INDEX['DATE']
		// use $params M_DIST_FILES_DATE
		$FILE_P_COUNT = count($postFileNameByDot);
		if ($FILE_P_COUNT >= 2 && $FILE_P_COUNT <= 7) {
			foreach ($postFileNameByDot as $ind => $file_part) {
				if ($this->_isDate($file_part)) {
					if (empty($params['M_DIST_FILES_DATE'])) {
						if (!$genLog_INDEX['DATE'][1]) {
							$genLog['DATE'] = $file_part;
						}
					}
					$genLog_INDEX['DATE'] []= array('PREFIX'=>".", 'INDEKS'=>"$ind", 'VALUE'=>$file_part);
				}
			}
		}

		// set $genLog['VERSION']
		// TODO: szuka wersji w miejscu drugiej daty?
		if (!empty($params['M_DIST_FILES_VERSION'])) {
			$genLog['VERSION'] = $params['M_DIST_FILES_VERSION'];
		}
		else if (!empty($params['M_DIST_FILES_VERSION_AUTO'])) {
			if (isset($genLog_INDEX['DATE'][1])) {// sa 2 poprawne daty w pliku
				$SPLITER = $genLog_INDEX['DATE'][1]['PREFIX'];
				$GIS = explode($SPLITER, $FILENAME_POST);
				echo $genLog_INDEX['DATE'][1]['INDEKS'];
				$pattern = '/[[:alpha:]]/';
				$subject = $GIS[$genLog_INDEX['DATE'][1]['INDEKS']];
				$PO = preg_match($pattern, $subject, $PO2, PREG_OFFSET_CAPTURE);
				if ($PO == 0 && $GIS[$genLog_INDEX['DATE'][1]['INDEKS']] >= 0 && $GIS[$genLog_INDEX['DATE'][1]['INDEKS']] <= 999) {
					$genLog['VERSION'] = $GIS[$genLog_INDEX['DATE'][1]['INDEKS']];
				}
			}
		}

		// set $genLog['DESCRIPTION']
		$genLog['DESCRIPTION'] = '';
		if (!empty($params['M_DIST_FILES_DESCRIPTION'])) {
			$genLog['DESCRIPTION'] = $params['M_DIST_FILES_DESCRIPTION'];
		}
		else {// !empty($params['M_DIST_FILES_DESCRIPTION_AUTO'])
			//echo "M_DIST_FILES_DESCRIPTION_AUTO <br> dla parametru $FILENAME_POST (FILENAME_POST) <br>\n";
			$genLog['DESCRIPTION'] = $params['M_DIST_FILES_DESCRIPTION'] . "_" . $FILENAME_POST;
			if (isset($genLog_INDEX['DATE'][0])) {
				$SPL = explode('_', $genLog['DESCRIPTION']);
				$genLog['DESCRIPTION'] = '';// clear $genLog['DESCRIPTION']
				foreach ($SPL as $SPLL) {
					//echo "<br> if $SPLL == ".$genLog_INDEX['DATE'][0]['VALUE']." EOL";
					if (false === strpos($SPLL, $genLog_INDEX['DATE'][0]['VALUE'])) {
						$genLog['DESCRIPTION'] .= "_" . $SPLL;
						//echo "<br>  Added Line 177a | $SPLL |";
					}
				}
				//echo "<br> GUESS[DESCRIPTION] line 177: ".$genLog['DESCRIPTION']." should be added ".$params['M_DIST_FILES_DESCRIPTION']." EOL.";
				if (isset($genLog_INDEX['DATE'][1])) {
					$SPL = explode('.', $genLog['DESCRIPTION']);
					$genLog['DESCRIPTION'] = '';// clear $genLog['DESCRIPTION']
					foreach ($SPL as $SPLL) {
						if (false === strpos($SPLL, $genLog_INDEX['DATE'][1]['VALUE'])) {
							$genLog['DESCRIPTION'] .= "." . $SPLL;
						}
					}
				}
				//echo "<br> DESCRIPT TO $genLog[DESCRIPTION] - line 203";
			}

			$genLog['DESCRIPTION'] = str_replace('.' . $genLog['EXT'], '', $genLog['DESCRIPTION']);

			$SPL = explode('.', $genLog['DESCRIPTION']);
			$genLog['DESCRIPTION'] = '';// clear $genLog['DESCRIPTION'] po raz kolejny
			$I = 0;
			foreach ($SPL as $SPLL) {
				if (!strstr($genLog['VERSION'], $SPLL)) {
					$genLog['DESCRIPTION'] .= $SPLL;
					//if ($_SESSION['DEBUG']) echo "<br>Sciagam z desc wersje $SPLL == ".$genLog['VERSION']." |";
				}
				//if ($_SESSION['DEBUG']) echo "<br>line 203: teraz GUESS[DESCRIPTION]= ".$genLog['DESCRIPTION']." | a w oryginale z parametru: ".$FILENAME_POST." |";
			}
		}

		if (!empty($params['M_DIST_FILES_DATE'])) {
			$genLog['DATE'] = $params['M_DIST_FILES_DATE'];
		}

		if (empty($genLog['DATE'])) {
			//$errorMsg = "Error: Pusta data {$genLog['DATE']} - ustawiam na dzisiaj";
			$genLog['DATE'] = date('Y-m-d');
		}
		else {
			if ($this->_isDate($genLog['DATE'])) {
				$genLog['INFO'] .= "3.1.1 WALIDACJA DATY OK , ";
			}
			else {
				$genLog['ERROR'] .= "ERROR_BAD_M_DIST_FILES_DATE (zly format daty {$genLog['DATE']}) , ";
				$errorMsg = "zły format daty {$genLog['DATE']}";
				return false;
			}
		}

		if (!$genLog['VERSION'] && $params['M_DIST_FILES_VERSION']) {
			$genLog['VERSION'] = $params['M_DIST_FILES_VERSION'];
		}
		else if (!$genLog['VERSION'] && !$params['M_DIST_FILES_VERSION']) {
			$genLog['VERSION'] = "1";
		}

		$genLog['VERSION'] = str_replace(' ', '_', $genLog['VERSION']);
		$genLog['DESCRIPTION'] = str_replace(' ', '_', $genLog['DESCRIPTION']);

		if($_SESSION['DEBUG']) print_r($genLog);

		// try to create folder if not exists
		if (!file_exists($dest_folder)) {
			mkdir($dest_folder, 0777, true);
			@chmod($dest_folder, 0777);
			$genLog['INFO'] .= "TWORZE_NOWY_FOLDER , ";

			if (!file_exists($dest_folder)) {
				//$genLog['ERROR'] .= "ERROR_DEST_FOLDER_NOT_EXISTS";
				$errorMsg = "folder nie istnieje - nie udało się go utworzyć";
				return false;
			}
		}

		$dest_folder_name = end(explode('/', $dest_folder));

		$genLog['M_DIST_FILES_DEST_FOLDER'] = $dest_folder;

		$genLog['DST_FILE_NAME'] = $this->generateFileName( array($genLog['INDEXNAME'], $genLog['TYPE'], $genLog['DESCRIPTION'], $genLog['DATE'], $genLog['VERSION'], $genLog['EXT']) );
		$v_files = $this->getFilesFromFolder($dest_folder_name, true);
		if (!empty($v_files)) {
			$genLog['VERSION'] = $this->getFileNextVersion($v_files, $genLog['TYPE'], $genLog['DATE'], $genLog['VERSION']);
			$genLog['DST_FILE_NAME'] = $this->generateFileName( array($genLog['INDEXNAME'], $genLog['TYPE'], $genLog['DESCRIPTION'], $genLog['DATE'], $genLog['VERSION'], $genLog['EXT']) );
		}

		return $genLog;
	}

	function generateFileName($dirname_parts) {
		foreach ($dirname_parts as $k_ind => $v_part) {
			$dirname_parts[$k_ind] = $this->cleanFilenamePart($v_part);
		}
		return implode('.', $dirname_parts);
	}

	/**
	 * Generate next file version if exists with the same type and date.
	 */
	function getFileNextVersion($files, $type, $date, $version) {
		$max_version = $version;
		if (empty($files)) {
			return $max_version;
		}
		foreach ($files as $v_file) {
			$v_file_parts = explode('.', $v_file);
			if (count($v_file_parts) == 6) {// nowe nazewnictwo 5 kropek
				$v_file_type = $v_file_parts[1];
				$v_file_date = $v_file_parts[3];
				$v_file_version = $v_file_parts[4];
				if ($v_file_type == $type && $v_file_date == $date) {
					// TODO: echo "<br>WARNING Plik typu $v_file_type dodany w dniu $v_file_date juz istnieje z numerem wersji = $v_file_version ($v_file)";
					if (is_numeric($v_file_version)) {
						$v_file_version++;
						$max_version = max($max_version, $v_file_version);
					}
				}
			} else {
				// pomin plik - bledna nazwa
			}
		}
		return $max_version;
	}

	function tryRemoveFromAjax($fileName) {
		$localPath = $this->getDestLocalPath();
		if (!$localPath) {
			return false;
		}
		$pathParts = explode('/', $fileName);
		$realFileName = array_pop($pathParts);
		if (!empty($pathParts)) {
			array_unshift($pathParts, $localPath);
			$localPath = implode('/', $pathParts);
		}
		if (file_exists("{$localPath}/{$realFileName}")) {
			//return unlink("{$localPath}/{$realFileName}");
			$deletedFileName = ".deleted-" . date("Y-m-d-H-i") . ".{$realFileName}";
			rename("{$localPath}/{$realFileName}", "{$localPath}/{$deletedFileName}");
			return true;
		}
		return false;
	}

}
