<?php
function files_sort_FILENAME_ASC( $a, $b ){
	$iRet = strnatcmp( $a['iPosition'], $b['iPosition'] );
	if( $iRet == 0 ) $iRet = strnatcmp( $a['sFileName'], $b['sFileName'] );
	return $iRet;
}

function files_sort_FILENAME_DESC( $a, $b ){
	$iRet = strnatcmp( $a['iPosition'], $b['iPosition'] );
	if( $iRet == 0 ) $iRet = strnatcmp( $b['sFileName'], $a['sFileName'] );
	return $iRet;
}

function files_sort_TITLE_ASC( $a, $b ){
	$iRet = strnatcmp( $a['iPosition'], $b['iPosition'] );
	if( $iRet == 0 ) $iRet = strnatcmp( $a['sDescription'], $b['sDescription'] );
	return $iRet;
}

function files_sort_TITLE_DESC( $a, $b ){
	$iRet = strnatcmp( $a['iPosition'], $b['iPosition'] );
	if( $iRet == 0 ) $iRet = strnatcmp( $b['sDescription'], $a['sDescription'] );
	return $iRet;
}

class Files{
	var $aFiles;
	var $aImagesDefault;
	static function &getInstance( ){
		static $oInstance = null;
		if( !isset( $oInstance ) ){
			$oInstance = new Files( );
		}
		return $oInstance;
	}
	function __construct( ){
		$this->generateCache( );
	}
	function throwDbNames( $iDbType = null ){
		$aFiles[1] = DB_PAGES_FILES;
		$aFiles[2] = DB_PRODUCTS_FILES;
		$aFiles[3] = DB_BOXES_FILES; //Boksy
		$aFiles[50] = DB_PRODUCERS; //Loga producentów
		$aFiles[51] = DB_BANNERS; //Bannery
		if( isset( $iDbType ) ) return isset( $aFiles[$iDbType] ) ? $aFiles[$iDbType] : null;
		else return $aFiles;
	}
	function throwIndexes( $iDbType = null ){
		$aIndexes[1] = 'iPage';
		$aIndexes[2] = 'iProduct';
		$aIndexes[3] = 'iBox';
		$aIndexes[50] = 'iProducer';
		$aIndexes[51] = 'iBanner';
		if( isset( $iDbType ) ) return isset( $aIndexes[$iDbType] ) ? $aIndexes[$iDbType] : null;
		else return $aIndexes;
	}
	function listFilesByTypes( $iLink, $iLinkType = 1, $sFile = 'media_%BLOCK%.tpl', $iTypeDisplay = null, $iPosMin = null, $iPosMax = null, $iMinSize = null, $sSortOrder = null ){
		$oTpl = & TplParser::getInstance( );
		$oDB = & DataBase::getInstance( );
		switch( $iLinkType ){
			case 1:
				$configBlocks = $GLOBALS['aFilePositionPageBlock'];
				$aMinSizes = $GLOBALS['aPageMinSizes'];
			break;
			case 2:
				$configBlocks = $GLOBALS['aFilePositionProductBlock'];
				$aMinSizes = $GLOBALS['aProductMinSizes'];
			break;
		}
		if( isset( $iTypeDisplay ) )
			$aReturn = null;
		else
			$aReturn = Array( 1 => null, null, null, null );
		$aExt = throwIconsFromExt( );
		if( is_array( $this->aFiles[$iLinkType][$iLink] ) ) foreach( $this->aFiles[$iLinkType][$iLink] as $iType => $aFiles ){
			if( !isset( $iTypeDisplay ) || $iTypeDisplay == $iType ){
				if( isset( $configBlocks[$iType] ) ){
					$sBlock = $configBlocks[$iType];
					$iColumns = $GLOBALS['config']['aGalleryColumns'][$iType];
					$i = 0;
					if( is_array( $aFiles ) ){
						if( !empty( $sSortOrder ) ){
							usort( $aFiles, 'files_sort_' . $sSortOrder );
						}
						foreach( $aFiles as $iFile => &$aData ){
							if( ( !isset( $iPosMin ) || $iPosMin <= $aData['iPosition'] ) && ( !isset( $iPosMax ) || $iPosMax >= $aData['iPosition'] ) ){
								if( $GLOBALS['config']['aFilesShowIcons'][$iType] ){
									if( $sIcon = $oDB->executeSQL( 'SELECT `sFileName` FROM `' . $oDB->throwTableName( $this->throwDbNames( $iLinkType ) ) . '` WHERE `iPhoto` = 1 AND `sDescription` = \'' . $oDB->escape( $aData['sFileName'] ) . '\' LIMIT 1', true, DataBase::SINGLE_VALUE ) ){
										$aData['sIcon'] = $sIcon;
										$aData['bCustomIcon'] = true;
									} else{
										$sExt = pathinfo( $aData['sFileName'], PATHINFO_EXTENSION );
										if( !isset( $aExt[$sExt] ) ) $aExt[$sExt] = 'nn';
										$aData['sIcon'] = 'ico_' . $aExt[$sExt];
									}
								}
								if( empty( $aData['iSize'] ) && isset( $aMinSizes[$iType] ) ){
									$aData['iSize'] = $aMinSizes[$iType];
								}
								if( isset( $iMinSize ) ){
									$aData['iSize'] = $iMinSize;
								}
								$aData['iFileSize'] = filesize( $GLOBALS['config']['dir_files'] . $aData['sFileName'] );
								if( $aData['iFileSize'] > 1024 * 1024 * 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 * 1024 * 1024 ), 2 ) . ' GB';
								elseif( $aData['iFileSize'] > 1024 * 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 * 1024 ), 2 ) . ' MB';
								elseif( $aData['iFileSize'] > 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 ), 2 ) . ' kB';
								else $aData['sFileSize'] = $aData['iFileSize'] . ' B';
								$aData['sFileDate'] = date( 'Y-m-d H:i', filemtime( $GLOBALS['config']['dir_files'] . $aData['sFileName'] ) );
								$i++;
							} else{
								unset( $aFiles[$iFile] );
							}
						}
					}
					if( !empty( $iColumns ) ) while( $i % $iColumns > 0 ){
						$aFiles[] = 'blank';
						$i++;
					}
					$oTpl->assign( 'aFiles', $aFiles );
					$oTpl->assign( 'iColumns', $iColumns );
					$oTpl->assign( 'aUrl', $GLOBALS['aUrl'] );
					if( isset( $iTypeDisplay ) ){
						return $oTpl->parse( str_replace( '%BLOCK%', $sBlock, $sFile ) );
					} else{
						$aReturn[$iType] = $oTpl->parse( str_replace( '%BLOCK%', $sBlock, $sFile ) );
					}
				}
			}
		} elseif( isset( $_GET['sPhrase'] ) && !empty( $_GET['sPhrase'] ) ){
			$iType = 1;
			$sql = 'SELECT * FROM ( SELECT * FROM `' . $oDB->throwTableName( $this->throwDbNames( 1 ) ) . '` UNION ALL SELECT * FROM `' . $oDB->throwTableName( $this->throwDbNames( 2 ) ) . '` UNION ALL SELECT * FROM `' . $oDB->throwTableName( $this->throwDbNames( 3 ) ) . '` ) `sq` WHERE 1';
			preg_match_all( '/(-?)((\\"([^\\"]+)\\")|([^\\"\\s][^\\s]*))/', htmlspecialchars_decode( $_GET['sPhrase'] ), $aWords, PREG_SET_ORDER );
			$aSearchP = Array( );
			foreach( $aWords as $aWord ){
				$sWord = $aWord[4];
				if( empty( $sWord ) ) $sWord = $aWord[5];
				$sWord = $oDB->escape( $sWord );
				if( $aWord[1] == '-' ){
					$aSearchP[] = '( `sq`.`sFileName` NOT LIKE \'%' . $sWord . '%\' AND `sq`.`sTextSearch` NOT LIKE \'%' . $sWord . '%\' AND `sq`.`sDescription` NOT LIKE \'%' . $sWord . '%\' )';
				} else{
					$aSearchP[] = '( `sq`.`sFileName` LIKE \'%' . $sWord . '%\' OR `sq`.`sTextSearch` LIKE \'%' . $sWord . '%\' OR `sq`.`sDescription` LIKE \'%' . $sWord . '%\' )';
				}
			}
			$sql.= ' AND (' . implode( ' AND ', $aSearchP ) . ') ORDER BY `iPosition` ASC';
			switch( $sSortOrder ){
				case 'FILENAME_ASC': $sql.= ', `sFileName` ASC'; break;
				case 'FILENAME_DESC': $sql.= ', `sFileName` DESC'; break;
				case 'TITLE_ASC': $sql.= ', `sDescription` ASC'; break;
				case 'TITLE_DESC': $sql.= ', `sDescription` ASC'; break;
			}
			$aFiles = $oDB->executeSQL( $sql, true );
			if( isset( $configBlocks[$iType] ) ){
				$sBlock = $configBlocks[$iType];
				$iColumns = $GLOBALS['config']['aGalleryColumns'][$iType];
				$i = 0;
				if( is_array( $aFiles ) ) foreach( $aFiles as &$aData ){
					if( $GLOBALS['config']['aFilesShowIcons'][$iType] ){
						if( $sIcon = $oDB->executeSQL( 'SELECT `sFileName` FROM `' . $oDB->throwTableName( $this->throwDbNames( $iLinkType ) ) . '` WHERE `iPhoto` = 1 AND `sDescription` = \'' . $oDB->escape( $aData['sFileName'] ) . '\' LIMIT 1', true, DataBase::SINGLE_VALUE ) ){
							$aData['sIcon'] = $sIcon;
							$aData['bCustomIcon'] = true;
						} else{
							$sExt = pathinfo( $aData['sFileName'], PATHINFO_EXTENSION );
							if( !isset( $aExt[$sExt] ) ) $aExt[$sExt] = 'nn';
							$aData['sIcon'] = 'ico_' . $aExt[$sExt];
						}
					}
					if( empty( $aData['iSize'] ) && isset( $aMinSizes[$iType] ) ){
						$aData['iSize'] = $aMinSizes[$iType];
					}
					$aData['iFileSize'] = filesize( $GLOBALS['config']['dir_files'] . $aData['sFileName'] );
					if( $aData['iFileSize'] > 1024 * 1024 * 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 * 1024 * 1024 ), 2 ) . ' GB';
					elseif( $aData['iFileSize'] > 1024 * 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 * 1024 ), 2 ) . ' MB';
					elseif( $aData['iFileSize'] > 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 ), 2 ) . ' kB';
					else $aData['sFileSize'] = $aData['iFileSize'] . ' B';
					$aData['sFileDate'] = date( 'Y-m-d H:i', filemtime( $GLOBALS['config']['dir_files'] . $aData['sFileName'] ) );
					$i++;
				}
				if( !empty( $iColumns ) ) while( $i % $iColumns > 0 ){
					$aFiles[] = 'blank';
					$i++;
				}
				$oTpl->assign( 'aFiles', $aFiles );
				$oTpl->assign( 'iColumns', $iColumns );
				$oTpl->assign( 'aUrl', $GLOBALS['aUrl'] );
				if( isset( $iTypeDisplay ) ){
					return $oTpl->parse( str_replace( '%BLOCK%', $sBlock, $sFile ) );
				} else{
					$aReturn[$iType] = $oTpl->parse( str_replace( '%BLOCK%', $sBlock, $sFile ) );
				}
			}
		}
		return $aReturn;
	}
	
	public static function sortByPosition($a, $b) {
		if($a['iPosition'] == $b['iPosition']){
			return $b['iFile'] - $a['iFile'];
		}else{
			return $a['iPosition'] - $b['iPosition'];
		}
	}
	
	function listPageFiles( $iPage, $iType, $iCount = null ){
		$oDB = DataBase::getInstance( );
		$oTpl = & TplParser::getInstance( );
		$configBlocks = $GLOBALS['aFilePositionPageBlock'];
		$aMinSizes = $GLOBALS['aPageMinSizes'];
		$iFileLimit = isset( $iCount ) ? $iCount : $GLOBALS['aFilePageLimits'][$iType];
		$aExt = throwIconsFromExt( );
		$aAllFiles = $this->aFiles[1][$iPage][$iType];
		if( is_array( $aAllFiles ) ){
			usort($aAllFiles, Array( 'Files', 'sortByPosition' ) );
			$aFiles = $aAllFiles;
			if( isset( $configBlocks[$iType] ) ){
				$sBlock = $configBlocks[$iType];
				if( is_array( $sBlock ) ) $sBlock = $sBlock['pages_default.tpl'];
				$iColumns = $GLOBALS['config']['aGalleryColumns'][$iType];
				$i = 0;
				if( is_array( $aFiles ) ) foreach( $aFiles as $iFile => &$aData ) if( !isset( $iFileLimit ) || ( $i < $iFileLimit ) ){
					$aData['iFileSize'] = filesize( $GLOBALS['config']['dir_files'] . $aData['sFileName'] );
					if( $aData['iFileSize'] > 1024 * 1024 * 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 * 1024 * 1024 ), 2 ) . ' GB';
					elseif( $aData['iFileSize'] > 1024 * 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 * 1024 ), 2 ) . ' MB';
					elseif( $aData['iFileSize'] > 1024 ) $aData['sFileSize'] = number_format( $aData['iFileSize'] / ( 1024 ), 2 ) . ' kB';
					else $aData['sFileSize'] = $aData['iFileSize'] . ' B';
					$aData['sFileDate'] = date( 'Y-m-d H:i', filemtime( $GLOBALS['config']['dir_files'] . $aData['sFileName'] ) );

					if( $GLOBALS['config']['aFilesShowIcons'][$iType] ){
						$sExt = pathinfo( $aData['sFileName'], PATHINFO_EXTENSION );
						if( !isset( $aExt[$sExt] ) ) $aExt[$sExt] = 'nn';
						$aData['sIcon'] = 'ico_' . $aExt[$sExt];
					}
					if( empty( $aData['iSize'] ) && isset( $aMinSizes[$iType] ) ){
						$aData['iSize'] = $aMinSizes[$iType];
					}
					$i++;
				} else{
					unset( $aFiles[$iFile] );
				}
				if( !empty( $iColumns ) ) while( $i % $iColumns > 0 ){
					$aFiles[] = 'blank';
					$i++;
				}
				$oTpl->assign( 'aFiles', $aFiles );
				$oTpl->assign( 'iColumns', $iColumns );
				$oTpl->assign( 'aUrl', $GLOBALS['aUrl'] );
				$oTpl->assign( 'oPage', $GLOBALS['oPage'] );
				$oTpl->assign( 'iPage', $iPage );
				$sReturn = $oTpl->parse( str_replace( '%BLOCK%', $sBlock, 'media_%BLOCK%.tpl' ) );
			}
		}
		return $sReturn;
	}
	function throwDefaultImage( $iLink, $iLinkType ){
		if( isset( $this->aImagesDefault[$iLinkType][$iLink] ) ) return $this->aImagesDefault[$iLinkType][$iLink];
	}
	function generateCache( ){
		global $config;
		$oDB = DataBase::getInstance( );
		$aFiles = $this->throwDbNames( );
		$aIndexes = Array( 1 => 'iPage', 2 => 'iProduct', 3 => 'iBox' );
		foreach( $aFiles as $iKey => $sValue ) if( $iKey < 50 ){
			$sIndex = $aIndexes[$iKey];
			$this->aFiles[$iKey] = null;
			$sql = 'SELECT * FROM `' . $oDB->throwTableName( $sValue ) . '` ORDER BY `iPosition`, `sFileName`, `' . $sIndex . '`, `sDescription`, `iFile`';
			$aResult = $oDB->executeSQL( $sql, true );
			foreach( $aResult as $aData ){
				$this->aFiles[$iKey][$aData[$sIndex]][$aData['iType']][] = $aData;
				if( !empty( $aData['iPhoto'] ) && ( $aData['iPhoto'] == 1 ) ){
					if( !isset( $this->aImagesDefault[$iKey][$aData[$sIndex]] ) ) $this->aImagesDefault[$iKey][$aData[$sIndex]] = $aData;
				}
			}
		}
	}
	function throwFile( $iLinkType, $iFile ){
		global $config;
		$oDB = DataBase::getInstance( );
		$aFiles = $this->throwDbNames( );
		$sql = 'SELECT * FROM `' . $oDB->throwTableName( $aFiles[$iLinkType] ) . '` WHERE `iFile` = ' . intval( $iFile );
		return $oDB->executeSQL( $sql, true, DataBase::SINGLE_RECORD );
	}
}
?>