<?php
class Pages{
	var $aPages = null;
	var $aPageParents = null;
	var $aPagesParentsTypes = null;
	var $aPagesParents = null;
	var $aPagesChildren = null;
	var $mData = null;
	
	const SUBPAGES_SHOW_DATE = 0x01;
	const SUBPAGES_SHOW_DESC = 0x02;
	const SUBPAGES_SHOW_IMG = 0x04;
	const SUBPAGES_ORDER_DATE = 0x08; //~0x08 - ORDER_NAME
	const SUBPAGES_ORDER_DESC = 0x10; //~0x10 - ORDER_ASC
	
	function __construct( ){
		$this->generateCache( );
	}
	/**
	 * $iDepthLimit - określa maksymalną głębokość generowanego menu (skraca menu).
	 * $iHideLimit - określa minimalny poziom zagłębienie menu przy wejściu którego pokazywne są dalsze subpozycje menu. Daje możliwość częściowego ukrywania dużego menu - wyświetla się w pełni po wejściu w daną kategorię.
	 * $iShowLimit - określa poziom zagłębienia menu do którego ukrywane są wszystkie pozycje menu. Menu jest pokazywane gdy wejdziemy na dany poziom lub wyższy. Pozwala na generowanie częśćiowych menu (podwójna nawigacja).
	 */
	function throwMenu( $sFile, $iType, $iPageCurrent = null, $iDepthLimit = 1, $iCountLimit = null, $bShowProducts = false, $bForceHeadFoot = false, $iHideLimit = 0, $iShowLimit = 0 ){
		if( !isset( $this->aPagesParentsTypes[$iType] ) && !$bForceHeadFoot ) return null;
		$this->mData = null;
		if( isset( $iPageCurrent ) ) $this->generatePageParents( $iPageCurrent );
		$this->generateMenuData( $iType, $iPageCurrent, $iDepthLimit, 0, null, $iShowLimit );
		if( isset( $this->mData[0] ) || $bForceHeadFoot ){
			$aMenu = Array( );
			if( is_array( $this->mData[0] ) ) foreach( $this->mData[0] as $iPage => $bValue ){
				$aData = $this->aPages[$iPage];
				$bShowSub = ( $aData['iMenuSubpages'] && ( ( $this->aPageParents[$aData['iPage']] ) || ( $iPageCurrent == $aData['iPage'] ) || ( $iDepth >= $iHideLimit ) ) ) ? true : false;
				$aData['sub'] = ( isset( $this->mData[$iPage] ) && $bShowSub ) ? $this->throwSubMenu( $sFile, $iPage, $iPageCurrent, 1, $bShowProducts, $iHideLimit ) : ( $bShowProducts ? $GLOBALS['oProduct']->throwSubMenu( $sFile, $iPage, $iDepth + 1, false, $iHideLimit ) : null );
				$aData['bSelected'] = ( $aData['iPage'] == $iPageCurrent );
				$aData['bParent'] = ( $this->aPageParents[$aData['iPage']] );
				$aMenu[$iPage] = $aData;
			}
			$oTpl = TplParser::getInstance( );
			$oTpl->assign( 'aMenu', $aMenu );
			$oTpl->assign( 'iMenuType', $iType );
			return $oTpl->parse( $sFile );
		}
	}
	function throwSubMenu( $sFile, $iPageParent, $iPageCurrent, $iDepth = 1, $bShowProducts = false, $iHideLimit = 0 ){
		$aMenu = Array( );
		if( isset( $this->mData[$iPageParent] ) ){
			foreach( $this->mData[$iPageParent] as $iPage => $bValue ){
				$aData = $this->aPages[$iPage];
				$bShowSub = ( $aData['iMenuSubpages'] && ( ( $this->aPageParents[$aData['iPage']] ) || ( $iPageCurrent == $aData['iPage'] ) || ( $iDepth >= $iHideLimit ) ) ) ? true : false;
				$aData['sub'] = ( isset( $this->mData[$iPage] ) && $bShowSub ) ? $this->throwSubMenu( $sFile, $iPage, $iPageCurrent, 1, $bShowProducts, $iHideLimit ) : ( $bShowProducts ? $GLOBALS['oProduct']->throwSubMenu( $sFile, $iPage, $iDepth + 1, false, $iHideLimit ) : null );
				$aData['bSelected'] = ( $aData['iPage'] == $iPageCurrent );
				$aData['bParent'] = ( $this->aPageParents[$aData['iPage']] );
				$aMenu[$iPage] = $aData;
			}
		}
		return $aMenu;
	}
	function generateMenuData( $iType, $iPageCurrent, $iDepthLimit, $iDepth = 0, $iPageParent = null, $iShowLimit = 0 ){
		if( !isset( $iPageParent ) ){
			$aData = $this->aPagesParentsTypes[$iType];
		} else{
			if( isset( $this->aPagesChildren[$iPageParent] ) ) $aData = $this->aPagesChildren[$iPageParent];
		}
		if( isset( $aData ) ){
			foreach( $aData as $iPage ){
				$bGeneratePage = ( ( $this->aPageParents[$iPage] ) || ( $iDepth >= $iShowLimit ) || ( $iPageCurrent == $iPage ) ) ? true : false;
				if( $bGeneratePage ){
					if( $iShowLimit == $iDepth ){
						$this->mData[0][$iPage] = true;
					} elseif( $iShowLimit > $iDepth ){
						//nie zapisujemy - idziemy w głąb
						
					} else{
						$iParentPage = $this->aPages[$iPage]['iPageParent'];
						$this->mData[$iParentPage][$iPage] = true;
					}
					if( $iDepthLimit > $iDepth ){
						$this->generateMenuData( $iType, $iPageCurrent, $iDepthLimit, $iDepth + 1, $iPage, $iShowLimit );
					}
				}
			}
		}
	}
	function throwCategories( $iType, $iPageCurrent = null, $iDepthLimit = 1 ){
		if( !isset( $this->aPagesParentsTypes[$iType] ) ) return null;
		$this->mData = null;
		if( isset( $iPageCurrent ) ){
			if( is_array( $iPageCurrent ) ) foreach( $iPageCurrent as $iPageT ){
				$this->generatePageParents( $iPageT );
			} else{
				$this->generatePageParents( $iPageCurrent );
			}
		}
		$this->generateSearchCategoriesData( $iType, /*$iPageCurrent,*/ $iDepthLimit, 0 );
		$aCategories = Array( );
		if( isset( $this->mData[0] ) ) foreach( $this->mData[0] as $iPage => $bValue ){
			$aData = $this->aPages[$iPage];
			$aData['aSubcategories'] = isset( $this->mData[$iPage] ) ? $this->throwSubCategories( $iPage, $iPageCurrent ) : null;
			$aData['bSelected'] = ( ( $GLOBALS['s_category'] == $aData['iPage'] ) || ( $aData['iPage'] == $iPageCurrent ) || ( is_array( $iPageCurrent ) && in_array( $aData['iPage'], $iPageCurrent ) ) );
			$aCategories[$iPage] = $aData;
		}
		return $aCategories;
	}
	function throwSubCategories( $iPageParent, $iPageCurrent, $iDepth = 1 ){
		if( isset( $this->mData[$iPageParent] ) ){
			$aCategories = Array( );
			foreach( $this->mData[$iPageParent] as $iPage => $bValue ){
				$aData = $this->aPages[$iPage];
				$aData['aSubcategories'] = isset( $this->mData[$iPage] ) ? $this->throwSubCategories( $iPage, $iPageCurrent ) : null;
				$aData['bSelected'] = ( ( $GLOBALS['s_category'] == $aData['iPage'] ) || ( $aData['iPage'] == $iPageCurrent ) || ( is_array( $iPageCurrent ) && in_array( $aData['iPage'], $iPageCurrent ) ) );
				$aCategories[$iPage] = $aData;
			}
			return $aCategories;
		}
	}
	function generateSearchCategoriesData( $iType, /*$iPageCurrent,*/ $iDepthLimit, $iDepth = 0, $iPageParent = null ){
		if( isset( $this->mData ) ){
			if( isset( $this->aPagesChildren[$iPageParent] ) ) $aData = $this->aPagesChildren[$iPageParent];
		} else{
			$aData = $this->aPagesParentsTypes[$iType];
		}
		if( isset( $aData ) ){
			foreach( $aData as $iKey => $iPage ){
				$this->mData[$this->aPages[$iPage]['iPageParent']][$iPage] = true;
				$this->generateSearchCategoriesData( $iType, /*$iPageCurrent,*/ $iDepthLimit, $iDepth + 1, $iPage );
			}
		}
	}
	function throwPage( $iPage ){
		$oDB = & DataBase::getInstance( );
		if( isset( $this->aPages[$iPage] ) ){
			$aData = $oDB->throwData( DB_PAGES_EXT, $iPage, 'iPage' );
			if( isset( $aData ) ){
				$aData['aTags'] = $oDB->executeSQL( 'SELECT `sTag` FROM `' . $oDB->throwTableName( DB_PAGES_TAGS ) . '` WHERE `iPage` = ' . intval( $aData['iPage'] ), true, DataBase::SINGLE_COLUMN );
				$aData['aZboziCategories'] = $oDB->executeSQL( 'SELECT `sCategory` FROM `' . $oDB->throwTableName( DB_PAGES_ZBOZI ) . '` WHERE `iPage` = ' . intval( $aData['iPage'] ), true, DataBase::SINGLE_COLUMN );
				if( defined( 'CUSTOMER_PAGE' ) && strstr( $aData['sDescriptionFull'], '<p><!-- pagebreak --></p>' ) ){
					$aExp = explode( '<p><!-- pagebreak --></p>', $aData['sDescriptionFull'] );
					if( !isset( $GLOBALS['aActions']['o4'] ) || !is_numeric( $GLOBALS['aActions']['o4'] ) ) $iPageContent = 1;
					else $iPageContent = $GLOBALS['aActions']['o4'];
					if( isset( $aExp[$iPageContent - 1] ) ){
						$aData['aPagesCount'] = Array( 'iPageNumber' => $iPageContent, 'iPages' => count( $aExp ), 'sUrl' => throwPageUrl( $this->aPages[$iPage]['sLinkName'] . ',,', true ) );
						$aData['sDescriptionFull'] = $aExp[$iPageContent - 1];
					}
				}
				return array_merge( $this->aPages[$iPage], $aData );
			}
		} else return null;
	}
	function getPagesTree( $iPage ){
		if( isset( $this->aPagesParents[$iPage] ) && isset( $this->aPages[$this->aPagesParents[$iPage]] ) ){
			$aReturn = $this->getPagesTree( $this->aPagesParents[$iPage] );
			$aReturn['aPath'][] = $aReturn['aCurrent'];
			$aReturn['aCurrent'] = Array( 'sName' => $this->aPages[$iPage]['sName'], 'sLinkName' => $this->getLinkName( $iPage ) );
		} elseif( $iPage && isset( $this->aPages[$iPage] ) ){
			$aReturn = Array( 'aPath' => Array( ), 'aCurrent' => Array( 'sName' => $this->aPages[$iPage]['sName'], 'sLinkName' => $this->getLinkName( $iPage ) ) );
			if( $this->aPages[$iPage]['iType'] < 60 ){
				$aReturn['sMenu'] = $GLOBALS['aMenuTypes'][$this->aPages[$iPage]['iType']];
			}
		}
		return $aReturn;
	}
	function throwAllChildren( $iPage ){
		$bFirst = !isset( $this->mData );
		if( isset( $this->aPagesChildren[$iPage] ) ){
			foreach( $this->aPagesChildren[$iPage] as $iValue ){
				if( isset( $this->aPages[$iValue] ) ){
					$this->mData[] = $iValue;
					$this->throwAllChildren( $iValue );
				}
			}
		}
		return $bFirst ? $this->mData : null;
	}
/*	function getSubpagesIds( $iPage, $sPhrase = null, $iFullSearch = false ){
		if( isset( $sPhrase ) ){
			$oDB = DataBase::getInstance( );
			$sql = 'SELECT `iPage` FROM `' . $oDB->throwTableName( DB_PAGES ) . '`';
			if( isset( $iFullSearch ) && $iFullSearch ){
				$sql.= ' LEFT JOIN `' . $oDB->throwTableName( DB_PAGES_EXT ) . '` AS `ext` USING( `iPage` )';
			}
			$sql.= ' WHERE ';
			$aWords = explode( ' ', $sPhrase );
			$aSearchP = Array( );
			foreach( $aWords as $sWord ){
				$sWord = $oDB->escape( $sWord );
				$aSearchP[] = '( LOWER( `sName` ) LIKE LOWER( \'%' . $sWord . '%\' ) OR LOWER( `sDescriptionShort` ) LIKE LOWER( \'%' . $sWord . '%\' ) ' . ( ( isset( $iFullSearch ) && $iFullSearch ) ? 'OR LOWER( `sDescriptionFull` ) LIKE LOWER( \'%' . $sWord . '%\' ) ' : null ) . ')';
			}
			$sql.= implode( ' AND ', $aSearchP );
			$aPages = $oDB->executeSQL( $sql, true, DataBase::SINGLE_COLUMN );
		} elseif( isset( $this->aPagesChildren[$iPage] ) ){
			$aPages = $this->aPagesChildren[$iPage];
		}
		return $aPages;
	}*/
	function checkPageGenerateCache(&$aPage ){
		$bAuthorizationPassed = checkMenuElementForUser( $aPage );
		$this->aPagesAuthorizedPassed[$aPage['iPage']] = $bAuthorizationPassed;
		if( !isset( $bAuthorizationPassed ) ){
			$this->aPagesAuthorizatioRemoved[$aPage['iPage']] = true;
			$aPage = null;
		}
	}
	function checkPageAuthorizedNotPassed( $iPage ){
		if( isset( $this->aPagesAuthorizedPassed[$iPage] ) && $this->aPagesAuthorizedPassed[$iPage] == 1 ) return false;
		else return true;
	}
	function checkCachePages( ){
		if( is_array( $this->aPages ) ) foreach( $this->aPages as $iPage => $aPage ){
			$iMainParent = $this->throwPagesMainParent( $iPage );
			if( ( isset( $iMainParent ) && $this->checkPageAuthorizedNotPassed( $iMainParent ) ) || !isset( $iMainParent ) ){
				unset( $this->aPages[$iPage] );
			}
		}
	}
	function addZboziToCache( ){
		$oDB = & DataBase::getInstance( );
		foreach( $this->aPages as &$aPage ){
			$aPage['aZboziCategories'] = $oDB->executeSQL( 'SELECT `sCategory` FROM `' . $oDB->throwTableName( DB_PAGES_ZBOZI ) . '` WHERE `iPage` = ' . intval( $aPage['iPage'] ), true, DataBase::SINGLE_COLUMN );
		}
	}
	function generateCache( ){
		$oDB = & DataBase::getInstance( );
		$iStatus = throwStatus( );
		if( $GLOBALS['config']['count_products_in_menu'] ){
			$sql = 'SELECT `pages`.*, `new_comments`.`count` AS `iNewCommentsCount`, IFNULL( `counter`.`iProductsCount`, 0 ) AS `iProductsCountInt`
								FROM `' . $oDB->throwTableName( DB_PAGES ) . '` AS `pages`
									LEFT JOIN (
										SELECT `iLink` AS `iPage`, COUNT( `iComment` ) AS `count`
											FROM `' . $oDB->throwTableName( DB_PAGES_COMMENTS ) . '`
											WHERE `iAccepted` = 0
											GROUP BY `iPage`
									) AS `new_comments` USING( `iPage` )
									LEFT JOIN (
										SELECT COUNT( `iElement` ) AS `iProductsCount`, `iPage`
											FROM `' . $oDB->throwTableName( DB_PRODUCTS_PAGES ) . '`
												INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS ) . '` USING( `iProduct` )
											WHERE `iStatus` >= ' . $iStatus;

			if( $GLOBALS['config']['hide_unavailable_products'] ){
				$sql.= ' AND `TiCanBuy` >= ' . $iStatus;
			}

			$sql .= '
											GROUP BY `iPage`
									) AS `counter` USING( `iPage` )
								' . $oDB->generateDefaultSort( DB_PAGES );
		} else{
			$sql = 'SELECT `pages`.*, `new_comments`.`count` AS `iNewCommentsCount`
								FROM `' . $oDB->throwTableName( DB_PAGES ) . '` AS `pages`
									LEFT JOIN (
										SELECT `iLink` AS `iPage`, COUNT( `iComment` ) AS `count`
											FROM `' . $oDB->throwTableName( DB_PAGES_COMMENTS ) . '`
											WHERE `iAccepted` = 0
											GROUP BY `iPage`
									) AS `new_comments` USING( `iPage` )
								' . $oDB->generateDefaultSort( DB_PAGES );
		}
		$aFile = $oDB->executeSQL( $sql, true );
		$this->aPages = null;
		$this->aPagesChildren = null;
		$this->aPagesParents = null;
		$this->aPagesParentsTypes = null;
		if( is_array( $aFile ) ) foreach( $aFile as $aPage ){
			if( $GLOBALS['config']['users_plugin_active'] == true && defined( 'CUSTOMER_PAGE' ) && isset( $aPage['iStatus'] ) && $aPage['iStatus'] >= $iStatus && defined( 'HIDE_AUTHORIZED_PAGES' ) && HIDE_AUTHORIZED_PAGES == true ){
				$this->checkPageGenerateCache( $aPage );
			}
			if( isset( $aPage['iStatus'] ) && $aPage['iStatus'] >= $iStatus ){
				if( !is_numeric( $aPage['iPageParent'] ) ) $aPage['iPageParent'] = 0;
//				$aPage['aTags'] = $oDB->executeSQL( 'SELECT `sTag` FROM `' . $oDB->throwTableName( DB_PAGES_TAGS ) . '` WHERE `iPage` = ' . intval( $aPage['iPage'] ), true, DataBase::SINGLE_COLUMN );
				$this->aPages[$aPage['iPage']] = $aPage;
				$this->aPages[$aPage['iPage']]['sDate'] = is_numeric( $this->aPages[$aPage['iPage']]['iTime'] ) ? date( 'Y-m-d H:i:s', $this->aPages[$aPage['iPage']]['iTime'] ) : null;
				$this->aPages[$aPage['iPage']]['sLinkName'] = $this->getLinkName( $aPage['iPage'], $this->aPages[$aPage['iPage']]['sName'] );// throwPageUrl( change2Url( $this->aPages[$aPage['iPage']]['sName'] ) . ',' . $aPage['iPage'] );
				$this->aPages[$aPage['iPage']]['sName'] = htmlspecialchars( $aPage['sName'] );
				if( $aPage['iPageParent'] > 0 ){
					$this->aPagesChildren[$aPage['iPageParent']][] = $aPage['iPage'];
					$this->aPagesParents[$aPage['iPage']] = $aPage['iPageParent'];
				} else{
					if( !empty( $aPage['iType'] ) ) $this->aPagesParentsTypes[$aPage['iType']][] = $aPage['iPage'];
				}
			}
		}
		if( is_array( $this->aPages ) ){
			if( $GLOBALS['config']['count_products_in_menu'] ) foreach( $this->aPages as $iPage => $aPage ){
				$iPageParent = $iPage;
				while( $iPageParent > 0 ){
					$this->aPages[$iPageParent]['iProductsCount']+= $aPage['iProductsCountInt'];
					$iPageParent = $this->aPages[$iPageParent]['iPageParent'];
				}
			}
		} elseif( defined( 'CUSTOMER_PAGE' ) ){
			die( $GLOBALS['lang']['Error_occured'] );
		}
		if( $GLOBALS['config']['users_plugin_active'] == true && defined( 'CUSTOMER_PAGE' ) && defined( 'HIDE_AUTHORIZED_PAGES' ) && HIDE_AUTHORIZED_PAGES == true ){
			$this->checkCachePages( );
		}
	}
	function generatePageParents( $iPage ){
		if( isset( $this->aPagesParents[$iPage] ) ){
			$this->aPageParents[$this->aPagesParents[$iPage]] = true;
			$this->generatePageParents( $this->aPagesParents[$iPage] );
		}
	}
	function listSiteMap( $iPageParent = null ){
		$iSiteMap = $GLOBALS['config']['site_map'];
		if( !isset( $iPageParent ) ){
			foreach( $this->aPages as $iPage => $aData ){
				if( !isset( $this->aPagesParents[$iPage] ) && ( $aData['iType'] < 50 ) && $iSiteMap != $iPage ) $aPages[] = $iPage;
			}
		} else{
			if( isset( $this->aPagesChildren[$iPageParent] ) ) $aPages = $this->aPagesChildren[$iPageParent];
		}
		if( isset( $aPages ) ){
			$aResult = Array( );
			foreach( $aPages as $iPage ){
				$aData = $this->aPages[$iPage];
				$aData['aSubPages'] = ( isset( $this->aPagesChildren[$iPage] ) /*&& $aData['iSubpagesShow'] > 0 && $aData['iSubpagesShow'] != 3*/ ) ? $this->listSiteMap( $iPage ) : null;
				$aData['aProducts'] = ( $aData['iProducts'] == 1 && isset( $GLOBALS['config']['site_map_products'] ) ) ? $GLOBALS['oProduct']->listSiteMap( $iPage ) : null;
				$aResult[] = $aData;
			}
			return $aResult;
		}
	}
	function throwCompare( $iPageParent = null ){
		$iSiteMap = $GLOBALS['config']['site_map'];
		if( !isset( $iPageParent ) ){
			foreach( $this->aPages as $iPage => $aData ){
				if( $this->aPages[$iPage]['iProducts'] == 1 ) $aPages[] = $iPage;
			}
		}
		if( isset( $aPages ) ){
			foreach( $aPages as &$aData ){
				$aData = $this->aPages[$aData];
				$aData['aPages'] = $this->getPagesTree( $aData['iPage'] );
			}
			return $aPages;
		}
	}
	function throwSubpagesForRss( $iPage ){
		$sSiteUrl = 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'] . dirname( $_SERVER['REQUEST_URI'] ) . '/';
		$aPage = $this->aPages[$iPage];
		if( !isset( $aPage['iTime'] ) || empty( $aPage['iTime'] ) ) $aPage['iTime'] = time( );
		$aPage['sDate'] = date( 'r', $aPage['iTime'] );
		$aPage['sDescriptionShort'] = changeTxt( $aPage['sDescriptionShort'], 'nlNds' );
		$aPage['sSiteUrl'] = $sSiteUrl;
		if( isset( $this->aPagesChildren[$iPage] ) ){
			foreach( $this->aPagesChildren[$iPage] as $iPageChild ){
				$aData = $this->aPages[$iPageChild];
				if( !isset( $aData['iTime'] ) || empty( $aData['iTime'] ) ) $aData['iTime'] = time( );
				$aData['sDescriptionShort'] = changeTxt( $aData['sDescriptionShort'], 'nlNds' );
				$aData['sDate'] = date( 'r', $aData['iTime'] );
				$aData['sSiteUrl'] = $sSiteUrl;
				$aPage['aSubpages'][] = $aData;
			}
		}
		return $aPage;
	}
	function throwSubpagesBlock( $iPage, $iBlock, $iList = null, $iSubpagesShow = 0, $iPositionMin = null, $iPositionMax = null ){
		$oDB = & DataBase::getInstance( );
		$oFile = Files::getInstance( );
		$sql = 'SELECT SQL_CALC_FOUND_ROWS `iPage`';
		$sql .= ' FROM `' . $oDB->throwTableName( DB_PAGES ) . '` `p` ';
		
		if( isset( $_GET['sPhrase'] ) && ( !empty( $_GET['sPhrase'] ) || !empty( $_GET['sTag'] ) ) ){
			$sPhrase = $_GET['sPhrase'];
			if( isset( $sPhrase ) && !empty( $sPhrase ) ){
				preg_match_all( '/(-?)((\\"([^\\"]+)\\")|([^\\"\\s][^\\s]*))/', htmlspecialchars_decode( $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[] = '( `sName` NOT LIKE \'%' . $sWord . '%\' AND `sDisplayTitle` NOT LIKE \'%' . $sWord . '%\' '  . ( ( isset( $GLOBALS['iFullSearch'] ) && $GLOBALS['iFullSearch'] ) ? 'AND `sDescriptionShort` NOT LIKE \'%' . $sWord . '%\' AND NOT EXISTS( SELECT 1 FROM `' . $oDB->throwTableName( DB_PAGES_BLOCKS ) . '` `pb` WHERE `sText` LIKE \'%' . $sWord . '%\' AND `pb`.`iPage` = `p`.`iPage` ) ' : null ) . ' )';
					} else{
						$aSearchP[] = '( `sName` LIKE \'%' . $sWord . '%\' OR `sDisplayTitle` LIKE \'%' . $sWord . '%\' '  . ( ( isset( $GLOBALS['iFullSearch'] ) && $GLOBALS['iFullSearch'] ) ? 'OR `sDescriptionShort` LIKE \'%' . $sWord . '%\' OR EXISTS( SELECT 1 FROM `' . $oDB->throwTableName( DB_PAGES_BLOCKS ) . '` `pb` WHERE `sText` LIKE \'%' . $sWord . '%\' AND `pb`.`iPage` = `p`.`iPage` ) ' : null ) . ' )';
					}
				}
				$sql.= 'WHERE (' . implode( ' AND ', $aSearchP ) . ')';
			} elseif( isset( $_GET['sTag'] ) && !empty( $_GET['sTag'] ) ){
				$sql.= ' WHERE EXISTS( SELECT 1 FROM `' . $oDB->throwTableName( DB_PAGES_TAGS ) . '` WHERE `iPage` = `p`.`iPage` AND REPLACE( `sTag`, \' \', \'_\' ) LIKE \'' . $oDB->escape( $_GET['sTag'] ) . '\' )';
			} else{
				$sql.= ' WHERE 1';
			}
		} else{
			$sql .= 'WHERE `iPageParent` = ' . intval( $iPage );
		}
		$sql .= ' AND `iStatus` >= ' . throwStatus( );
		
		if( isset( $iPositionMin ) ) $sql .= ' AND `iPosition` >= ' . intval( $iPositionMin );
		if( isset( $iPositionMax ) ) $sql .= ' AND `iPosition` <= ' . intval( $iPositionMax );
		$sql .= ' ORDER BY `iPosition` ASC, `' . ( $iSubpagesShow & self::SUBPAGES_ORDER_DATE ? 'iTime' : 'sName' ) . '` ' . ( $iSubpagesShow & self::SUBPAGES_ORDER_DESC ? 'DESC' : 'ASC' );

		if( empty( $iList ) ){
			$iList = $GLOBALS['config']['news_list'];
		}
		$iPageNumber = ( isset( $GLOBALS['aActions']['o3'] ) && $GLOBALS['aActions']['o2'] == $iBlock ) ? $GLOBALS['aActions']['o3'] : 1;
		if( !isset( $iPageNumber ) || !is_numeric( $iPageNumber ) || $iPageNumber < 1 ) $iPageNumber = 1;
		if( isset( $_POST['sort'] ) || isset( $_POST['news_list'] ) ){
			$iPageNumber = 1;
		}
		$iEnd = $iPageNumber * $iList;
		$iStart = $iEnd - $iList;
		$sql.= ' LIMIT ' . $iStart . ',' . $iList;

		$aSubpagesList = $oDB->executeSQL( $sql, true );
		$iCount = $oDB->executeSQL( 'SELECT FOUND_ROWS();', true, DataBase::SINGLE_VALUE );

		if( $iCount > 0 ){
			$aSubpagesInfo['aPagesCountData'] = Array( 'iCount' => ceil( $iCount / $iList ), 'iPageNumber' => $iPageNumber );
			$aSubpagesInfo['bImageDisplay'] = $iSubpagesShow & self::SUBPAGES_SHOW_IMG;
			$aSubpagesInfo['bDetailsDisplay'] = $iSubpagesShow & ( self::SUBPAGES_SHOW_DATE | self::SUBPAGES_SHOW_DESC );
			$aSubpagesInfo['aMainpage'] = $this->aPages[$iPage];
			foreach( $aSubpagesList as &$aSubpage ){
				$aSubpage = $this->aPages[$aSubpage['iPage']];
				if( $iSubpagesShow & self::SUBPAGES_SHOW_DATE ) $aSubpage['sDate'] = date( 'Y-m-d H:i:s', $aSubpage['iTime'] ); else $aSubpage['sDate'] = null;
				if( $iSubpagesShow & self::SUBPAGES_SHOW_IMG && isset( $oFile->aImagesDefault[1][$aSubpage['iPage']] ) ){
					$aSubpage['aDataImage'] = $oFile->aImagesDefault[1][$aSubpage['iPage']];
				} else $aSubpage['aDataImage'] = null;
				if( !( $iSubpagesShow & self::SUBPAGES_SHOW_DESC ) ){
					$aSubpage['sDescriptionShort'] = null;
					$aSubpage['aTags'] = null;
				} else{
					$aSubpage['sDescriptionShort'] = changeTxt( $aSubpage['sDescriptionShort'], 'nlNds' );
					$aSubpage['aTags'] = $oDB->executeSQL( 'SELECT `sTag` FROM `' . $oDB->throwTableName( DB_PAGES_TAGS ) . '` WHERE `iPage` = ' . intval( $aSubpage['iPage'] ), true, DataBase::SINGLE_COLUMN );
				}
			}
		}

		$aSubpagesInfo['iColumncount'] = floor( $iSubpagesShow / 0x20 ) % 4;

		$aSubpagesInfo['aList'] = $aSubpagesList;
		$aSubpagesInfo['sLinkNamePages'] = throwPageUrl( $this->getLinkName( $iPage ), true );
		$aSubpagesInfo['sLinkName'] = $GLOBALS['oPage']->getLinkName( $iPage ) . '?';
		$aSubpagesInfo['iList'] = $iList;
		return $aSubpagesInfo;
	}
	/**
	 * $iPages - ilość stron na jednej podstronie (do stronnicowania wyników). false, jeśli chcemy mieć wszystkie strony, niezależnie od ilości
	 * $sSortOrder - np. dla newsów '`iTime` DESC', domyślnie '`iPosition` ASC, `sName` ASC, `iPage` ASC' - po pozycji, a następnie po nazwie alfabetycznie
	 */
	function throwSubpages( $iPage, $iPages = false, $sSortOrder = '`iPosition` ASC, `sName` ASC, `iPage` ASC' ){
		$oDB = & DataBase::getInstance( );
		$oFile = Files::getInstance( );
		$sql = 'SELECT `iPage` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` `p`';
		if( isset( $GLOBALS['iFullSearch'] ) && $GLOBALS['iFullSearch'] ){
			$sql.= ' LEFT JOIN `' . $oDB->throwTableName( DB_PAGES_EXT ) . '` AS `ext` USING( `iPage` )';
		}
		if( isset( $_GET['sPhrase'] ) ){
			$sPhrase = $_GET['sPhrase'];
			if( isset( $sPhrase ) && !empty( $sPhrase ) ){
				preg_match_all( '/(-?)((\\"([^\\"]+)\\")|([^\\"\\s][^\\s]*))/', htmlspecialchars_decode( $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[] = '( `sName` NOT LIKE \'%' . $sWord . '%\' AND `sDisplayTitle` NOT LIKE \'%' . $sWord . '%\' '  . ( ( isset( $GLOBALS['iFullSearch'] ) && $GLOBALS['iFullSearch'] ) ? 'AND `sDescriptionShort` NOT LIKE \'%' . $sWord . '%\' AND `sDescriptionFull` NOT LIKE \'%' . $sWord . '%\' ' : null ) . ' )';
					} else{
						$aSearchP[] = '( `sName` LIKE \'%' . $sWord . '%\' OR `sDisplayTitle` LIKE \'%' . $sWord . '%\' '  . ( ( isset( $GLOBALS['iFullSearch'] ) && $GLOBALS['iFullSearch'] ) ? 'OR `sDescriptionShort` LIKE \'%' . $sWord . '%\' OR `sDescriptionFull` LIKE \'%' . $sWord . '%\' ' : null ) . ' )';
					}
				}
				$sql.= ' WHERE (' . implode( ' AND ', $aSearchP ) . ')';
			} elseif( isset( $_GET['sTag'] ) && !empty( $_GET['sTag'] ) ){
				$sql.= ' WHERE EXISTS( SELECT 1 FROM `' . $oDB->throwTableName( DB_PAGES_TAGS ) . '` WHERE `iPage` = `p`.`iPage` AND REPLACE( `sTag`, \' \', \'_\' ) LIKE \'' . $oDB->escape( $_GET['sTag'] ) . '\' )';
			} else{
				$sql.= ' WHERE 1';
			}
		} else{
			$sql = 'SELECT `iPage` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` WHERE `iPageParent` = ' . intval( $iPage );
		}
		$sql .= ' AND `iStatus` >= ' . throwStatus( ) . ' ORDER BY ' . $sSortOrder;
		$aPages = $oDB->executeSQL( $sql, true, DataBase::SINGLE_COLUMN );
		foreach( $aPages as $iRow => $iSubPage ){
			if( !isset( $this->aPages[$iSubPage] ) ) unset( $aPages[$iRow] );
		}
		if( $iPages > 0 ){
			$iPageNumber = isset( $GLOBALS['aActions']['o3'] ) ? $GLOBALS['aActions']['o3'] : 1;
			if( !isset( $iPageNumber ) || !is_numeric( $iPageNumber ) || $iPageNumber < 1 ) $iPageNumber = 1;
			$aPages = array_chunk( $aPages, $iPages );
			$iPages = count( $aPages );
			if( $iPageNumber > $iPages ) $iPageNumber = 1;
			$aPages = $aPages[$iPageNumber - 1];
		}
		if( is_array( $aPages ) ) foreach( $aPages as &$mPage ){
			$mPage = $this->aPages[$mPage];
			$mPage['sDescriptionShort'] = changeTxt( $mPage['sDescriptionShort'], 'nlNds' );
			if( isset( $oFile->aImagesDefault[1][$mPage['iPage']] ) ){
				$mPage['aDataImage'] = $oFile->aImagesDefault[1][$mPage['iPage']];
			}
		}
		return Array( 'aPages' => $aPages, 'iPages' => $iPages, 'iPageNumber' => $iPageNumber, 'sUrl' => throwPageUrl( $this->aPages[$iPage]['sLinkName'] . ',', true ) );
	}
	function throwPagesMainParent( $iPage ){
		if( isset( $this->aPages[$iPage] ) && $this->aPages[$iPage]['iPageParent'] == 0 ){
			$this->mData = null;
			return $iPage;
		}
		if( !isset( $this->aPagesParents[$iPage] ) || !isset( $this->aPages[$this->aPagesParents[$iPage]] ) ){
			if( isset( $this->mData ) ){
				$iCount = count( $this->mData );
				$iMainParent = $this->mData[$iCount - 1];
				$this->mData = null;
				return $iMainParent;
			}
		} else{
			$this->mData[] = $this->aPagesParents[$iPage];
			return $this->throwPagesMainParent( $this->aPagesParents[$iPage] );
		}
	}
	function getLinkName( $iPage, $sName = null ){
		if( $iPage == $GLOBALS['config']['start_page'] ){
			return $GLOBALS['config']['index'];
		} elseif( !isset( $sName ) ){
			$oDB = & DataBase::getInstance( );
			$sql = 'SELECT `iPage`, `sName` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` WHERE `iPage` = \'' . intval( $iPage ) . '\'';
			$aPage = $oDB->executeSQL( $sql, true, DataBase::SINGLE_RECORD );
			if( $aPage ){
				return throwPageUrl( change2Url( $aPage['sName'] ) . ',' . $aPage['iPage'] );
			} else{
				return null;
			}
		} else{
			return throwPageUrl( change2Url( $sName ) . ',' . $iPage );
		}
	}
	function throwAllegroPath( $iAllegroCat ){
		$catPath = $this->getCategoryPath( $iAllegroCat );
		$catPath = array_reverse( $catPath );
		$catPath = implode( "", $catPath );
		return $catPath;
	}
	function getCategoryPath( $iSelectedIndex, $path = null ){
		$oDB = DataBase::getInstance( );
		if( $path == null ) $path = array( );
		$sql = 'SELECT * FROM `' . $oDB->throwTableName( DB_ALLEGRO_CAT ) . '` WHERE iAllegroCat = ' . $iSelectedIndex;
		$aCategory = $oDB->executeSQL( $sql, true );
		$sName = $aCategory[0]['sName'];
		$path[] = " > " . $sName;
		$aCatParent = $aCategory[0]['iAllegroCatParent'];
		if( !is_null( $aCatParent ) ){
			$path = $this->getCategoryPath( $aCatParent, $path );
		}
		return $path;
	}
};
?>