<?php
require_once 'libraries/PHPExcel.php';
$sXmlVer = '12.0';
$aDefaultPageOptionValues = Array( 'active' => '1', 'products' => '1', 'rss' => '0', 'comments' => '0', 'logged-only' => '0', 'url' => '', 'date' => date( 'Y-m-d H:i:s' ), 'admin-id' => '0', 'subpages-show' => '1', );
$aDefaultProductOptionValues = Array( 'active' => '1', 'date' => date( 'Y-m-d H:i:s' ), 'avail_on_stock' => $config['default_onstock'], 'avail_out_of_stock' => $config['default_outofstock'], 'producer' => '', 'weight' => '', 'client_weight' => '', 'size' => '', 'comments' => '0', 'fotolia' => '0', 'alert_stock' => '', 'measure' => '', 'user_discount' => '1', 'admin-id' => '0', 'promoted' => '0', 'terminating' => '0', 'sellout' => '0', 'used' => '0', 'not_for_sale' => '0', 'producer_url' => '', 'review' => '', 'catalog_number' => '', 'product_index' => '', );
$aDefaultVariantOptionValues = Array( 'active' => '1', 'avail_on_stock' => '', 'avail_out_of_stock' => '', 'user_discount' => '', );
if( !defined( 'CRLF' ) ) define( 'CRLF', "\r\n" );
if( !defined( 'CR' ) ) define( 'CR', "\r" );
if( !defined( 'LF' ) ) define( 'LF', "\n" );
$aFieldNamesAv = Array( 'iProduct', 'sName', 'fPrice', 'iStatus', 'sAvailable', 'iProducer', 'iNewUsed', 'sCatalogNumber', 'sProductIndex' );
$aEncodingsAv = Array( 'US-ASCII' => $lang['US-ASCII'], 'UTF-8' => $lang['UTF-8'], 'ISO-8859-1' => $lang['ISO-8859-1'], 'CP1252' => $lang['CP1252'], 'ISO-8859-2' => $lang['ISO-8859-2'], 'CP1250' => $lang['CP1250'], 'ISO-8859-3' => $lang['ISO-8859-3'], 'ISO-8859-4' => $lang['ISO-8859-4'], 'CP1257' => $lang['CP1257'], 'ISO-8859-5' => $lang['ISO-8859-5'], 'CP1251' => $lang['CP1251'], 'ISO-8859-6' => $lang['ISO-8859-6'], 'CP1256' => $lang['CP1256'], 'ISO-8859-7' => $lang['ISO-8859-7'], 'CP1253' => $lang['CP1253'], 'ISO-8859-8' => $lang['ISO-8859-8'], 'CP1255' => $lang['CP1255'], 'ISO-8859-9' => $lang['ISO-8859-9'], 'CP1254' => $lang['CP1254'] );
function select_data_fields( $aData, $aFields ){
	$aResult = Array( );
	foreach( $aData as $iKey => $aRow ){
		foreach( $aFields as $sField ){
			$aResult[$iKey][$sField] = $aRow[$sField];
		}
	}
	return $aResult;
}
if( $a == 'imp_export' ){
	if( isset( $sOption ) ){
		$content .= $oTpl->parse('message_done.tpl');
	}
	$oTpl->assign( 'aStores', $oDB->throwFileArraySmall( DB_STORES, 'iStore', 'sName', 'iPriority' ) );
	$content.= $oTpl->parse( 'migrate_importexport.tpl' );
} elseif( $a == 'import' && is_numeric( $_POST['iStore'] ) ){
	$objPHPExcel = PHPExcel_IOFactory::load( $_FILES['xls_file']['tmp_name'] );
	$objWorksheet = $objPHPExcel->getActiveSheet( );
	$highestRow = $objWorksheet->getHighestRow( );
	$aProducts = Array( );
	$iProduct = null;
	for( $iRow = 2;$iRow <= $highestRow;$iRow++ ){
		$aRow = Array( );
		for( $iColumn = 0;$iColumn <= 7;$iColumn++ ){
			$aRow[$iColumn] = $objWorksheet->getCellByColumnAndRow( $iColumn, $iRow )->getValue( );
		}
		if( isset( $aRow[0] ) && is_numeric( $aRow[0] ) ){
			if( empty( $aRow[1] ) ){
				$aProducts[$aRow[0]] = Array( /*'iMainCategory' => $aRow[2], */
				'sName' => $aRow[4], 'fPrice' => $aRow[6], 'aVariants' => Array( ) );
			} else{
				$aProducts[$aRow[0]]['aVariants'][$aRow[1]] = Array( 'fPrice' => $aRow[6], 'iStock' => $aRow[7] );
			}
		}
	}
	foreach( $aProducts as $iProduct => $aProduct ){
		$sql = 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS ) . '` SET `sName` = \'' . $oDB->escape( $aProduct['sName'] ) . '\', `fPrice` = ' . $aProduct['fPrice'] . ' WHERE `iProduct` = ' . $iProduct;
		$oDB->executeSQL( $sql );
		foreach( $aProduct['aVariants'] as $iProductVariant => $aVariant ){
			$sql = 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` SET `fPrice` = ' . ( isset( $aVariant['fPrice'] ) ? $aVariant['fPrice'] : 'NULL' ) . ' WHERE `iProductVariant` = ' . $iProductVariant;
			$oDB->executeSQL( $sql );
			$iStock = $aVariant['iStock'];
			if( is_numeric( $iStock ) ){
				if( !$oDB->update( DB_STORES_PRODUCTS, Array( 'iStock' => intval( $iStock ) ), Array( 'iProductVariant' => intval( $iProductVariant ), 'iStore' => intval( $_POST['iStore'] ) ) ) ){
					$oDB->save( DB_STORES_PRODUCTS, Array( 'iStock' => intval( $iStock ), 'iProductVariant' => intval( $iProductVariant ), 'iStore' => intval( $_POST['iStore'] ) ) );
				}
			} else{
				$oDB->executeSQL( 'DELETE FROM `' . $oDB->throwTableName( DB_STORES_PRODUCTS ) . '` WHERE `iStore` = ' . intval( $_POST['iStore'] ) . ' AND `iProductVariant` = ' . intval( $iProductVariant ) );
			}
		}
	}
	header( 'Location: admin.php?p=migrate-imp_export&sOption=import' );
	exit;
} elseif( $a == 'export' && is_numeric( $iStore ) ){
	$objPHPExcel = PHPExcel_IOFactory::load( DIR_TEMPLATES . 'admin/export.xlsx' );
	$objWorksheet = $objPHPExcel->getActiveSheet( );
	$styleArrayHeader = array( 'font' => array( 'color' => array( 'argb' => 'FFFFFFFF' ), ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FF376091', ), ), );
	$styleArrayProduct = array( 'font' => array( 'bold' => true, ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FF8DB4E3', ), ), );
	$styleArrayVariant1 = array( 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FFD8D8D8', ), ), );
	$styleArrayVariant2 = array( 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, ), ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'startcolor' => array( 'argb' => 'FFFFFFFF', ), ), );
	$iRow = 2;
	$objWorksheet->getStyle( 'A' . $iRow . ':H' . $iRow )->applyFromArray( $styleArrayHeader );
	$sStore = $oDB->executeSQL( 'SELECT `sName` FROM `' . $oDB->throwTableName( DB_STORES ) . '` WHERE `iStore` = ' . intval( $iStore ), true, DataBase::SINGLE_VALUE );
	$objWorksheet->getCellByColumnAndRow( 1, 1 )->setValue( $sStore );
	$sql = 'SELECT `iProduct` FROM `' . $oDB->throwTableName( DB_PRODUCTS ) . '`';
	$aProducts = $oDB->executeSQL( $sql, true, DataBase::SINGLE_COLUMN );
	foreach( $aProducts as $iProduct ){
		$iRow++;
		$objWorksheet->getStyle( 'A' . $iRow . ':H' . $iRow )->applyFromArray( $styleArrayProduct );
		$aData = $oProduct->throwProduct( $iProduct );
		$aProducer = throwProducer( $aData['iProducer'] );
		$objWorksheet->getCellByColumnAndRow( 0, $iRow )->setValue( $aData['iProduct'] );
		$objWorksheet->getCellByColumnAndRow( 2, $iRow )->setValue( $aData['iMainCategory'] );
		$objWorksheet->getCellByColumnAndRow( 3, $iRow )->setValue( $oPage->aPages[$aData['iMainCategory']]['sName'] );
		$objWorksheet->getCellByColumnAndRow( 4, $iRow )->setValue( $aData['sName'] );
		$objWorksheet->getCellByColumnAndRow( 5, $iRow )->setValue( $aProducer['sName'] );
		$objWorksheet->getCellByColumnAndRow( 6, $iRow )->setValue( $aData['fPrice'] );
		list( $aVariants, $aAttributes ) = $oProduct->throwAdminVariants( $aData['iProduct'] );
		$iAlt = true;
		foreach( $aVariants as $aVariant ){
			$iRow++;
			$iAlt = !$iAlt;
			$objWorksheet->getStyle( 'A' . $iRow . ':H' . $iRow )->applyFromArray( $iAlt ? $styleArrayVariant1 : $styleArrayVariant2 );
			$aVariant['sName'] = $aData['sName'];
			foreach( $aAttributes as $aAttribute ){
				if( $aAttribute['bActive'] ){
					foreach( $aAttribute['aValues'] as $iValue => $sValue ){
						if( in_array( $iValue, $aVariant['aValues'] ) ) $aVariant['sName'].= ', ' . $aAttribute['sName'] . ': ' . $sValue;
					}
				}
			}
			$objWorksheet->getCellByColumnAndRow( 0, $iRow )->setValue( $aData['iProduct'] );
			$objWorksheet->getCellByColumnAndRow( 1, $iRow )->setValue( $aVariant['iProductVariant'] );
			$objWorksheet->getCellByColumnAndRow( 4, $iRow )->setValue( $aVariant['sName'] );
			$objWorksheet->getCellByColumnAndRow( 6, $iRow )->setValue( $aVariant['fPrice'] );
			$objWorksheet->getCellByColumnAndRow( 7, $iRow )->setValue( $aVariant['aStore'][$iStore]['iStock'] );
		}
	}
	$objWorksheet->getStyle( 'G2:G' . $iRow )->getNumberFormat( )->setFormatCode( '#,##0.00_-"' . $config['currency_symbol'] . '"' );
	$objWorksheet->getColumnDimension( 'E' )->setAutoSize( true );
	$objWorksheet->getColumnDimension( 'F' )->setAutoSize( true );
	$objWriter = new PHPExcel_Writer_Excel5( $objPHPExcel );
	$objWriter->save( 'upload/export/export.xls' );
	header( 'Content-type: application/vnd.ms-excel' );
	header( 'Content-disposition: attachment; filename=export-' . date( 'Ymd' ) . '.xls' );
	readfile( 'upload/export/export.xls' );
	unlink( 'upload/export/export.xls' );
	exit;
} elseif( $a == 'fsimport' && !isset( $_FILES['csv_file'] ) ){
	$oTpl->assign( 'aStores', $oDB->throwFileArraySmall( DB_STORES, 'iStore', 'sName', 'iPriority' ) );
	$content.= $oTpl->parse( 'migrate_fsimport.tpl' );
} elseif( $a == 'fsimport' && is_numeric( $_POST['iStore'] ) ){
	switch( $config['CSV_default_line_separator'] ){
		case 'CRLF':
			define( 'CSV_LINE_DELIMITER', CRLF );
		break;
		case 'CR':
			define( 'CSV_LINE_DELIMITER', CR );
		break;
		case 'LF':
			define( 'CSV_LINE_DELIMITER', LF );
		break;
		default:
			define( 'CSV_LINE_DELIMITER', CRLF );
	}
	define( 'CSV_TEXT_DELIMITER', $config['CSV_default_text_delimiter'] );
	define( 'CSV_FIELD_DELIMITER', $config['CSV_default_field_separator'] );
	define( 'CSV_ENCODING', $config['CSV_default_charset'] );
	$csvFile = iconv( CSV_ENCODING, "UTF-8", file_get_contents( $_FILES['csv_file']['tmp_name'] ) );
	$aProducts = Array( );
	$aProduct = Array( );
	while( !empty( $csvFile ) ){
		$tdPos = strpos( $csvFile, CSV_TEXT_DELIMITER );
		if( $tdPos === 0 ){
			$tdPos = strpos( $csvFile, CSV_TEXT_DELIMITER, strlen( CSV_TEXT_DELIMITER ) );
			$aProduct[] = substr( $csvFile, strlen( CSV_TEXT_DELIMITER ), $tdPos - strlen( CSV_TEXT_DELIMITER ) );
			$csvFile = substr( $csvFile, $tdPos + strlen( CSV_TEXT_DELIMITER ) );
			if( strpos( $csvFile, CSV_LINE_DELIMITER ) === 0 ){
				$csvFile = substr( $csvFile, strlen( CSV_LINE_DELIMITER ) );
				$aProducts[] = $aProduct;
				$aProduct = Array( );
			} elseif( strpos( $csvFile, CSV_FIELD_DELIMITER ) == 0 ){
				$csvFile = substr( $csvFile, strlen( CSV_FIELD_DELIMITER ) );
			} else{
				die( $lang['CSV_Invalid_file'] );
			}
		} else{
			$nlPos = strpos( $csvFile, CSV_LINE_DELIMITER );
			$fdPos = strpos( $csvFile, CSV_FIELD_DELIMITER );
			if( $nlPos === false && $fdPos === false ){
				$aProduct[] = $csvFile;
				$aProducts[] = $aProduct;
				$aProduct = Array( );
				$csvFile = '';
			} elseif( $nlPos === false ){
				$aProduct[] = substr( $csvFile, 0, $fdPos );
				$csvFile = substr( $csvFile, $fdPos + strlen( CSV_FIELD_DELIMITER ) );
			} elseif( $fdPos === false ){
				$aProduct[] = substr( $csvFile, 0, $nlPos );
				$aProducts[] = $aProduct;
				$aProduct = Array( );
				$csvFile = substr( $csvFile, $nlPos + strlen( CSV_LINE_DELIMITER ) );
			} elseif( $fdPos < $nlPos ){
				$aProduct[] = substr( $csvFile, 0, $fdPos );
				$csvFile = substr( $csvFile, $fdPos + strlen( CSV_FIELD_DELIMITER ) );
			} elseif( $nlPos < $fdPos ){
				$aProduct[] = substr( $csvFile, 0, $nlPos );
				$aProducts[] = $aProduct;
				$aProduct = Array( );
				$csvFile = substr( $csvFile, $nlPos + strlen( CSV_LINE_DELIMITER ) );
			} else{
				die( $lang['CSV_Invalid_file'] );
			}
		}
	}
	if( $aProducts[0] == Array( '#1' ) ){
		array_shift( $aProducts );
		$aProductIds = Array( );
		foreach( $aProducts as $aProduct ) if( !empty( $aProduct ) ){
			$fVatValue = str_replace( '%', '', $aProduct[2] ) / 100.;
			$aProductInfo = $oProduct->getProductIdAndVariantIdByOuter( $aProduct[0] );
			$iProduct = $aProductInfo['iProduct'];
			$iVariant = $aProductInfo['iProductVariant'];
			$aVariantInfo = Array( 'iProductVariant' => $iVariant, 'iStock' => preg_replace( '/,.*/', '', $aProduct[5] ), 'fPrice' => str_replace( ',', '.', $aProduct[7] ), 'iVat' => throwVatIdByValue( $fVatValue ) );
			if( !empty( $iVariant ) && $oProduct->updateVariant( $aVariantInfo, $_POST['iStore'] ) ){
				if( !in_array( $iProduct, $aProductIds ) ) $aProductIds[] = $iProduct;
			} else{
				$aForm = Array( 'iStatus' => 1, 'iActiveDiscount' => 1, 'fPrice' => str_replace( ',', '.', $aProduct[7] ), 'aPages' => Array( $config['flysoft_products_page'] ), 'sName' => $aProduct[8], 'iVat' => throwVatIdByValue( $fVatValue ), 'aNewVariants' => Array( Array( 'iStatus' => 1, 'aStore' => Array( $_POST['iStore'] => Array( 'iActive' => 1, 'iStock' => preg_replace( '/,.*/', '', $aProduct[5] ) ) ), 'fPrice' => str_replace( ',', '.', $aProduct[7] ), 'iVat' => throwVatIdByValue( $fVatValue ), 'sEan' => $aProduct[1], 'sOuterId' => $aProduct[0] ) ), 'iAvailableOnStock' => $config['default_onstock'], 'iAvailableOutOfStock' => $config['default_outofstock'] );
				$oProduct->saveProduct( $aForm );
			}
		}
		if( !empty( $aProductIds ) ){
			$sql = 'UPDATE `' . $oDB->throwTableName( DB_PRODUCTS ) . '` AS `p` SET `fPrice` = ( SELECT MIN( `pv`.`fPrice` ) FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` AS `pv` WHERE `pv`.`iProduct` = `p`.`iProduct` ) WHERE `p`.`iProduct` IN( \'' . implode( '\', \'', $aProductIds ) . '\' )';
			$oDB->executeSQL( $sql );
		}
		$content.= $oTpl->parse( 'message_done.tpl' );
	} else{
		die( $lang['CSV_Invalid_file'] );
	}
} elseif( $a == 'xmlexport' && isset( $_GET['iStore'] ) ){
	if( !isset( $aUrl ) ){
		$aUrl = parse_url( 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
		if( !isset( $aUrl['host'] ) ) $aUrl['host'] = null;
		if( !isset( $aUrl['path'] ) ) $aUrl['path'] = null;
		if( isset( $aUrl['query'] ) ) $aUrl['query'] = '?' . $aUrl['query'];
		else $aUrl['query'] = null;
		$aUrl['dir'] = dirname( $aUrl['path'] );
	}
	function xml_pages( $resTop, $xml, $pageParent ){
		$oDB = DataBase::getInstance( );
		while( $aPage = mysqli_fetch_array( $resTop ) ){
			$page = $xml->createElement( 'page' );
			$attr = $xml->createAttribute( 'id' );
			$attr->value = $aPage['iPage'];
			$page->appendChild( $attr );
			if( $aPage['iPosition'] != 0 ){
				$attr = $xml->createAttribute( 'position' );
				$attr->value = $aPage['iPosition'];
				$page->appendChild( $attr );
			}
			$opt = $xml->createElement( 'name' );
			$cdata = $xml->createCDATASection( $aPage['sName'] );
			$opt->appendChild( $cdata );
			$page->appendChild( $opt );
			if( !empty( $aPage['sFilesXML'] ) ){
				$filesTMP = new DOMDocument( '1.0', 'utf-8' );
				$filesTMP->loadXML( $aPage['sFilesXML'] );
				$page->appendChild( $xml->importNode( $filesTMP->documentElement, true ) );
			}
			if( !empty( $aPage['sDescriptionShort'] ) ){
				$opt = $xml->createElement( 'description' );
				$attr = $xml->createAttribute( 'type' );
				$attr->value = 'short';
				$opt->appendChild( $attr );
				$cdata = $xml->createCDATASection( str_replace( '|n|', "\n", $aPage['sDescriptionShort'] ) );
				$opt->appendChild( $cdata );
				$page->appendChild( $opt );
			}
//			if( !empty( $aPage['sDescriptionFull'] ) ){
//				$opt = $xml->createElement( 'description' );
//				$attr = $xml->createAttribute( 'type' );
//				$attr->value = 'full';
//				$opt->appendChild( $attr );
//				$cdata = $xml->createCDATASection( str_replace( '|n|', "\n", $aPage['sDescriptionFull'] ) );
//				$opt->appendChild( $cdata );
//				$page->appendChild( $opt );
//			}
			//OPTIONS + SEO:
			$options = $xml->createElement( 'options' );
			$aOptions = Array( 'active' => $aPage['iStatus'], 'products' => $aPage['iProducts'], 'rss' => $aPage['iRss'], 'logged-only' => $aPage['iAuthorized'], 'url' => $aPage['sUrl'], 'date' => date( 'Y-m-d H:i:s', $aPage['iTime'] ), 'admin-id' => $aPage['iAdmin'], /*'subpages-show' => $aPage['iSubpagesShow'],*/ );
			foreach( $aOptions as $sOption => $sValue ) if( $sValue !== null && $sValue !== $GLOBALS['aDefaultPageOptionValues'][$sOption] ){
				$opt = $xml->createElement( 'option' );
				$attr = $xml->createAttribute( 'name' );
				$attr->value = $sOption;
				$opt->appendChild( $attr );
				$attr = $xml->createAttribute( 'value' );
				$attr->value = $sValue;
				$opt->appendChild( $attr );
				$options->appendChild( $opt );
			}
			if( $options->hasChildNodes( ) ) $page->appendChild( $options );
			$options = $xml->createElement( 'seo' );
			$aOptions = Array( 'title' => $aPage['sNameTitle'], 'description' => $aPage['sMetaDescription'], 'keywords' => $aPage['sMetaKeywords'], 'topic' => $aPage['sMetaPageTopic'], 'abstract' => $aPage['sMetaAbstract'], );
			foreach( $aOptions as $sOption => $sValue ) if( $sValue !== null && $sValue !== '' ){
				$opt = $xml->createElement( 'option' );
				$attr = $xml->createAttribute( 'name' );
				$attr->value = $sOption;
				$opt->appendChild( $attr );
				$attr = $xml->createAttribute( 'value' );
				$attr->value = $sValue;
				$opt->appendChild( $attr );
				$options->appendChild( $opt );
			}
			if( $options->hasChildNodes( ) ) $page->appendChild( $options );
			// /OPTIONS + SEO
			//SUBPAGES:
			$sql = 'SELECT `pages`.*, `pages_ext`.*, `pages_files`.`sFilesXML`
								FROM `' . $oDB->throwTableName( DB_PAGES ) . '` `pages`
									INNER JOIN `' . $oDB->throwTableName( DB_PAGES_EXT ) . '` `pages_ext` USING( `iPage` )
									LEFT JOIN (
										SELECT
												`iPage`,
												CONCAT( \'<files>\', GROUP_CONCAT( CONCAT( \'<file href="' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['dir'] . '/' . DIR_FILES . '\', `sFileName`, \'"\',
													IF( `iPhoto` IS NULL, \'\', \' image="1"\' ),
													IF( `iType` IS NULL, \'\', CONCAT( \' display="\', `iType`, \'"\' ) ),
													IF( `iPosition` IS NULL, \'\', CONCAT( \' position="\', `iPosition`, \'"\' ) ),
													IF( `sDescription` IS NULL, \'\', CONCAT( \' description="\', REPLACE( `sDescription`, \'"\', \'&quot;\' ), \'"\' ) ),
													\' />\' ) SEPARATOR \'\' ), \'</files>\' ) AS `sFilesXML`
											FROM `' . $oDB->throwTableName( DB_PAGES_FILES ) . '`
											GROUP BY `iPage`
											ORDER BY NULL
									) `pages_files` USING( `iPage` )
								WHERE `iPageParent` = ' . intval( $aPage['iPage'] ) . '
								ORDER BY NULL';
			$res = mysqli_query( $oDB->rDBConnection ,  $sql);
			$subpages = $xml->createElement( 'subpages' );
			xml_pages( $res, $xml, $subpages );
			if( $subpages->hasChildNodes( ) ) $page->appendChild( $subpages );
			// /SUBPAGES
			$pageParent->appendChild( $page );
		}
	}
	$time = microtime( true );
	$xml = new DOMDocument( '1.0', 'utf-8' );
	$xml->formatOutput = true;
	$oDB->executeSQL( 'SET group_concat_max_len=4096' );
	$root = $xml->createElement( 'shop' );
	$ver = $xml->createAttribute( 'ver' );
	$ver->value = $sXmlVer;
	$root->appendChild( $ver );
	// PAGES:
	$pages = $xml->createElement( 'pages' );
	$sql = 'SELECT `pages`.*, `pages_ext`.*, `pages_files`.`sFilesXML`
						FROM `' . $oDB->throwTableName( DB_PAGES ) . '` `pages`
							INNER JOIN `' . $oDB->throwTableName( DB_PAGES_EXT ) . '` `pages_ext` USING( `iPage` )
							LEFT JOIN (
								SELECT
										`iPage`,
										CONCAT( \'<files>\', GROUP_CONCAT( CONCAT( \'<file href="' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['dir'] . '/' . DIR_FILES . '\', `sFileName`, \'"\',
											IF( `iPhoto` IS NULL, \'\', \' image="1"\' ),
											IF( `iType` IS NULL, \'\', CONCAT( \' display="\', `iType`, \'"\' ) ),
											IF( `iPosition` IS NULL, \'\', CONCAT( \' position="\', `iPosition`, \'"\' ) ),
											IF( `sDescription` IS NULL, \'\', CONCAT( \' description="\', REPLACE( `sDescription`, \'"\', \'&quot;\' ), \'"\' ) ),
											\' />\' ) SEPARATOR \'\' ), \'</files>\' ) AS `sFilesXML`
									FROM `' . $oDB->throwTableName( DB_PAGES_FILES ) . '`
									GROUP BY `iPage`
									ORDER BY NULL
							) `pages_files` USING( `iPage` )
						WHERE ( `iPageParent` = 0 OR `iPageParent` IS NULL ) AND `iType` = 4
						ORDER BY NULL';
	$res = mysqli_query( $oDB->rDBConnection ,  $sql);
	xml_pages( $res, $xml, $pages );
	$root->appendChild( $pages );
	// /PAGES
	// PRODUCTS:
	$products = $xml->createElement( 'products' );
	$sql = 'SELECT `products`.*, `products_ext`.*, `producers`.`sName` AS `sProducer`, `products_pages`.`sPagesXML`, `products_files`.`sFilesXML`, `attributes`.`sAttributesXML`
						FROM `' . $oDB->throwTableName( DB_PRODUCTS ) . '` `products`
							INNER JOIN `' . $oDB->throwTableName( DB_PRODUCTS_EXT ) . '` `products_ext` USING( `iProduct` )
							LEFT JOIN `' . $oDB->throwTableName( DB_PRODUCERS ) . '` `producers` USING( `iProducer` )
							LEFT JOIN (
								SELECT
										`iProduct`,
										CONCAT( \'<pages>\', GROUP_CONCAT( CONCAT( \'<page id="\', `iPage`, \'"\', IF( `iMainCategory` IS NULL, \'\', \' main="1"\' ), \'/>\' ) SEPARATOR \'\' ), \'</pages>\' ) AS `sPagesXML`
									FROM `' . $oDB->throwTableName( DB_PRODUCTS_PAGES ) . '`
									GROUP BY `iProduct`
									ORDER BY NULL
							) `products_pages` USING( `iProduct` )
							LEFT JOIN (
								SELECT
										`iProduct`,
										CONCAT( \'<files>\', GROUP_CONCAT( CONCAT( \'<file href="' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['dir'] . '/' . DIR_FILES . '\', REPLACE( REPLACE( `sFileName`, \'&\', \'&amp;\' ), \'"\', \'&quot;\' ), \'"\',
											IF( `iPhoto` IS NULL, \'\', \' image="1"\' ),
											IF( `iType` IS NULL, \'\', CONCAT( \' display="\', `iType`, \'"\' ) ),
											IF( `iPosition` IS NULL, \'\', CONCAT( \' position="\', `iPosition`, \'"\' ) ),
											IF( `sDescription` IS NULL, \'\', CONCAT( \' description="\', REPLACE( REPLACE( `sDescription`, \'&\', \'&amp;\' ), \'"\', \'&quot;\' ), \'"\' ) ),
											\' />\' ) SEPARATOR \'\' ), \'</files>\' ) AS `sFilesXML`
									FROM `' . $oDB->throwTableName( DB_PRODUCTS_FILES ) . '`
									GROUP BY `iProduct`
									ORDER BY NULL
							) `products_files` USING( `iProduct` )
							LEFT JOIN (
								SELECT
										`iProduct`,
										CONCAT( \'<attributes>\', GROUP_CONCAT( CONCAT( \'<attribute name="\', REPLACE( `sName`, \'"\', \'&quot;\' ), \'" value="\', REPLACE( `sValue`, \'"\', \'&quot;\' ), \'" />\' ) SEPARATOR \'\' ), \'</attributes>\' ) AS `sAttributesXML`
									FROM `' . $oDB->throwTableName( DB_PRODUCTS_ATTRIBUTES_CONST ) . '` `pa`
										INNER JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` `av` USING( `iAttributeValue` )
										INNER JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES ) . '` `a` ON( `a`.`iAttribute` = `av`.`iAttribute` )
									GROUP BY `iProduct`
									ORDER BY NULL
							) `attributes` USING( `iProduct` )							
						ORDER BY NULL';
	$res = mysqli_query( $oDB->rDBConnection ,  $sql);
	while( $aProduct = mysqli_fetch_array( $res,  MYSQLI_ASSOC ) ){
		$product = $xml->createElement( 'product' );
		$attr = $xml->createAttribute( 'id' );
		$attr->value = $aProduct['iProduct'];
		$product->appendChild( $attr );
		if( $aProduct['iPosition'] != 0 ){
			$attr = $xml->createAttribute( 'position' );
			$attr->value = $aProduct['iPosition'];
			$product->appendChild( $attr );
		}
		$opt = $xml->createElement( 'name' );
		$cdata = $xml->createCDATASection( $aProduct['sName'] );
		$opt->appendChild( $cdata );
		$product->appendChild( $opt );
		if( !empty( $aProduct['sPagesXML'] ) ){
			$pagesTMP = new DOMDocument( '1.0', 'utf-8' );
			$pagesTMP->loadXML( $aProduct['sPagesXML'] );
			$product->appendChild( $xml->importNode( $pagesTMP->documentElement, true ) );
		} else{
			continue;
		}
		$price = $xml->createElement( 'price', $aProduct['fPrice'] );
		if( $aProduct['iCurrencyDependent'] ){
			$attr = $xml->createAttribute( 'currency_dependent' );
			$attr->value = 1;
			$price->appendChild( $attr );
		}
		$product->appendChild( $price );
		if( !empty( $aProduct['fPriceOld'] ) ){
			$price = $xml->createElement( 'price_old', $aProduct['fPriceOld'] );
			$product->appendChild( $price );
		}
		if( !empty( $aProduct['fBuyPrice'] ) ){
			$price = $xml->createElement( 'price_buy', $aProduct['fBuyPrice'] );
			$product->appendChild( $price );
		}
		if( !empty( $aProduct['fPriceTimeValue'] ) ){
			$price = $xml->createElement( 'time_price', $aProduct['fPriceTimeValue'] );
			$attr = $xml->createAttribute( 'from' );
			$attr->value = date( 'Y-m-d H:i:s', $aProduct['iPriceTimeFrom'] );
			$price->appendChild( $attr );
			$attr = $xml->createAttribute( 'to' );
			$attr->value = date( 'Y-m-d H:i:s', $aProduct['iPriceTimeTo'] );
			$price->appendChild( $attr );
			$product->appendChild( $price );
		}
		$opt = $xml->createElement( 'vat', $aProduct['iVat'] );
		$product->appendChild( $opt );

		if( isset( $aProduct['sAttributesXML'] ) ){
			$attributesTMP = new DOMDocument( '1.0', 'utf-8' );
			$attributesTMP->loadXML( $aProduct['sAttributesXML'] );
			$product->appendChild( $xml->importNode( $attributesTMP->documentElement, true ) );
		}
		//VARIANTS:
		$variants = $xml->createElement( 'variants' );
		$sql = 'SELECT `variants`.*, `attributes`.`sAttributesXML`, `store`.`iStock` AS `iStoreStock`
							FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` `variants`
								LEFT JOIN (
									SELECT
											`iProductVariant`,
											CONCAT( \'<attributes>\', GROUP_CONCAT( CONCAT( \'<attribute name="\', REPLACE( `sName`, \'"\', \'&quot;\' ), \'" value="\', REPLACE( `sValue`, \'"\', \'&quot;\' ), \'" />\' ) SEPARATOR \'\' ), \'</attributes>\' ) AS `sAttributesXML`
										FROM `' . $oDB->throwTableName( DB_PRODUCTS_ATTRIBUTES ) . '` `pa`
											INNER JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` `av` USING( `iAttributeValue` )
											INNER JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES ) . '` `a` USING( `iAttribute` )
										GROUP BY `iProductVariant`
										ORDER BY NULL
								) `attributes` USING( `iProductVariant` )
								LEFT JOIN `' . $oDB->throwTableName( DB_STORES_PRODUCTS ) . '` `store` ON( `variants`.`iProductVariant` = `store`.`iProductVariant` AND `store`.`iStore` = ' . intval( $_GET['iStore'] ) . ' )
							WHERE `iProduct` = ' . intval( $aProduct['iProduct'] ) . '
							ORDER BY NULL';
		foreach( $oDB->executeSQL( $sql, true ) as $aVariant ){
			$variant = $xml->createElement( 'variant' );
			if( !empty( $aVariant['fPrice'] ) ){
				$price = $xml->createElement( 'price', $aVariant['fPrice'] );
				$variant->appendChild( $price );
			}
			if( !empty( $aVariant['fPriceOld'] ) ){
				$price = $xml->createElement( 'price_old', $aVariant['fPriceOld'] );
				$variant->appendChild( $price );
			}
			if( !empty( $aVariant['fBuyPrice'] ) ){
				$price = $xml->createElement( 'price_buy', $aVariant['fBuyPrice'] );
				$variant->appendChild( $price );
			}
			if( !empty( $aVariant['fPriceTimeValue'] ) ){
				$price = $xml->createElement( 'time_price', $aVariant['fPriceTimeValue'] );
				$variant->appendChild( $price );
			}
			if( !empty( $aVariant['iVat'] ) ){
				$opt = $xml->createElement( 'vat', $aVariant['iVat'] );
				$variant->appendChild( $opt );
			}
			if( !empty( $aVariant['sOuterId'] ) ){
				$attr = $xml->createAttribute( 'outerid' );
				$attr->value = $aVariant['sOuterId'];
				$variant->appendChild( $attr );
			}
			if( !empty( $aVariant['sEan'] ) ){
				$attr = $xml->createAttribute( 'ean' );
				$attr->value = $aVariant['sEan'];
				$variant->appendChild( $attr );
			}
			if( !empty( $aVariant['iStock'] ) ){
				$attr = $xml->createAttribute( 'stock' );
				$attr->value = $aVariant['iStoreStock'];
				$variant->appendChild( $attr );
			}
			//VARIANT OPTIONS:
			$options = $xml->createElement( 'options' );
			$aOptions = Array( 'active' => $aVariant['iStatus'], 'avail_on_stock' => $aVariant['iAvailableOnStock'], 'avail_out_of_stock' => $aVariant['iAvailableOutOfStock'], 'user_discount' => $aVariant['iActiveDiscount'], );
			foreach( $aOptions as $sOption => $sValue ) if( $sValue !== null && $sValue !== $aDefaultVariantOptionValues[$sOption] ){
				$opt = $xml->createElement( 'option' );
				$attr = $xml->createAttribute( 'name' );
				$attr->value = $sOption;
				$opt->appendChild( $attr );
				$attr = $xml->createAttribute( 'value' );
				$attr->value = $sValue;
				$opt->appendChild( $attr );
				$options->appendChild( $opt );
			}
			if( $options->hasChildNodes( ) ) $variant->appendChild( $options );
			// /VARIANT OPTIONS
			if( isset( $aVariant['sAttributesXML'] ) ){
				$attributesTMP = new DOMDocument( '1.0', 'utf-8' );
				$attributesTMP->loadXML( $aVariant['sAttributesXML'] );
				$variant->appendChild( $xml->importNode( $attributesTMP->documentElement, true ) );
			}
			$variants->appendChild( $variant );
		}
		$product->appendChild( $variants );
		// /VARIANTS
		if( !empty( $aProduct['sDescriptionShort'] ) ){
			$opt = $xml->createElement( 'description' );
			$attr = $xml->createAttribute( 'type' );
			$attr->value = 'short';
			$opt->appendChild( $attr );
			$cdata = $xml->createCDATASection( str_replace( '|n|', "\n", $aProduct['sDescriptionShort'] ) );
			$opt->appendChild( $cdata );
			$product->appendChild( $opt );
		}
		if( !empty( $aProduct['sDescriptionFull'] ) ){
			$opt = $xml->createElement( 'description' );
			$attr = $xml->createAttribute( 'type' );
			$attr->value = 'full';
			$opt->appendChild( $attr );
			$cdata = $xml->createCDATASection( str_replace( '|n|', "\n", $aProduct['sDescriptionFull'] ) );
			$opt->appendChild( $cdata );
			$product->appendChild( $opt );
		}
		//TABS:
		$sql = 'SELECT `iTab`, `sContent` FROM `' . $oDB->throwTableName( DB_PRODUCTS_TABS ) . '` WHERE `iProduct` = ' . intval( $aProduct['iProduct'] ) . ' AND `sContent` IS NOT NULL ORDER BY `iTab` ASC';
		foreach( $oDB->executeSQL( $sql, true, DataBase::ASSOCIATIVE ) as $iTab => $sTab ){
			$opt = $xml->createElement( 'tab' );
			$attr = $xml->createAttribute( 'type' );
			$attr->value = $iTab;
			$opt->appendChild( $attr );
			$cdata = $xml->createCDATASection( str_replace( '|n|', "\n", $sTab ) );
			$opt->appendChild( $cdata );
			$product->appendChild( $opt );
		}
		// /TABS
		//RELATED:
		$sql = 'SELECT CONCAT( \'<related type="\', `iBox`, \'">\', GROUP_CONCAT( CONCAT( \'<product id="\', `iRelated`, \'" />\' ) SEPARATOR \'\' ), \'</related>\' )
							FROM `' . $oDB->throwTableName( DB_PRODUCTS_RELATED ) . '`
							WHERE `iProduct` = ' . intval( $aProduct['iProduct'] ) . '
							GROUP BY `iBox`
							ORDER BY `iBox`';
		foreach( $oDB->executeSQL( $sql, true, DataBase::SINGLE_COLUMN ) as $sRelated ){
			$relatedTMP = new DOMDocument( '1.0', 'utf-8' );
			$relatedTMP->loadXML( $sRelated );
			$product->appendChild( $xml->importNode( $relatedTMP->documentElement, true ) );
		}
		// /RELATED
		//FILES:
		if( !empty( $aProduct['sFilesXML'] ) ){
			$filesTMP = new DOMDocument( '1.0', 'utf-8' );
			$filesTMP->loadXML( $aProduct['sFilesXML'] );
			$product->appendChild( $xml->importNode( $filesTMP->documentElement, true ) );
		}
		// /FILES
		//OPTIONS + SEO:
		$options = $xml->createElement( 'options' );
		$aOptions = Array( 'active' => $aProduct['iStatus'], 'date' => date( 'Y-m-d H:i:s', $aProduct['iTime'] ), 'avail_on_stock' => $aProduct['iAvailableOnStock'], 'avail_out_of_stock' => $aProduct['iAvailableOutOfStock'], 'producer' => $aProduct['sProducer'], 'weight' => $aProduct['sWeight'], 'client_weight' => $aProduct['sWeightDisplayed'], 'size' => $aProduct['sSizeXYZ'], 'comments' => $aProduct['iComments'], 'fotolia' => $aProduct['iFotolia'], 'alert_stock' => $aProduct['iStockSendAdminMin'], 'measure' => $aProduct['sMeasure'], 'user_discount' => $aProduct['iActiveDiscount'], 'admin-id' => $aProduct['iAdmin'], /*'promoted' => $aProduct['iPromoted'], 'terminating' => $aProduct['iTerminating'], 'sellout' => $aProduct['iSellOut'],*/ 'used' => $aProduct['iNewUsed'], 'not_for_sale' => $aProduct['iNotForSale'], 'producer_url' => $aProduct['sProducerURL'], 'review' => $aProduct['sReviewURL'], 'catalog_number' => $aProduct['sCatalogNumber'], 'product_index' => $aProduct['sProductIndex'], );
		foreach( $aOptions as $sOption => $sValue ) if( $sValue !== null && $sValue !== $aDefaultProductOptionValues[$sOption] ){
			$opt = $xml->createElement( 'option' );
			$attr = $xml->createAttribute( 'name' );
			$attr->value = $sOption;
			$opt->appendChild( $attr );
			$attr = $xml->createAttribute( 'value' );
			$attr->value = $sValue;
			$opt->appendChild( $attr );
			$options->appendChild( $opt );
		}
		if( $options->hasChildNodes( ) ) $product->appendChild( $options );
		$options = $xml->createElement( 'seo' );
		$aOptions = Array( 'title' => $aProduct['sNameTitle'], 'description' => $aProduct['sMetaDescription'], 'keywords' => $aProduct['sMetaKeywords'], 'topic' => $aProduct['sMetaPageTopic'], 'abstract' => $aProduct['sMetaAbstract'], );
		foreach( $aOptions as $sOption => $sValue ) if( $sValue !== null && $sValue !== '' ){
			$opt = $xml->createElement( 'option' );
			$attr = $xml->createAttribute( 'name' );
			$attr->value = $sOption;
			$opt->appendChild( $attr );
			$attr = $xml->createAttribute( 'value' );
			$attr->value = $sValue;
			$opt->appendChild( $attr );
			$options->appendChild( $opt );
		}
		if( $options->hasChildNodes( ) ) $product->appendChild( $options );
		// /OPTIONS + SEO
		//ADVSEARCHER
		$aProduct['aAdvsearcherValues'] = $oDB->executeSQL( 'SELECT `sValue`, `sParentValues` FROM `' . $oDB->throwTableName( DB_ADVSEARCHER_PRODUCTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_ADVSEARCHER_VALUES ) . '` USING( `iValue` ) WHERE `iProduct` = ' . $aProduct['iProduct'], true );
		foreach( $aProduct['aAdvsearcherValues'] as $aValue ){
			xmlAddCdataElement( $xml, $product, 'advsearcher', empty( $aValue['sParentValues'] ) ? $aValue['sValue'] : $aValue['sParentValues'] . ' &raquo; ' . $aValue['sValue'] );
		}
		// /ADVSEARCHER
		$products->appendChild( $product );
	}
	$root->appendChild( $products );
	// /PRODUCTS
	$xml->appendChild( $root );
	//Output
	if( $iZip ){
		$tmp = tempnam( 'tmp', 'zip' );
		$zip = new ZipArchive();
		$zip->open( $tmp, ZipArchive::OVERWRITE );
		$zip->addFromString( 'export.xml', $xml->saveXML() );
		$zip->close();
		
		header( 'Content-type: application/zip' );
		header( 'Content-length: ' . filesize( $tmp ) );
		header( 'Content-Disposition: attachment; filename=export.zip;' );
		readfile( $tmp );
		unlink( $tmp );
	} else{
		header( 'Content-type: application/xml' );
		header( 'Content-Disposition: attachment; filename=export.xml;' );
		echo $xml->saveXML( );
	}
	//	file_put_contents( 'logs/xml-generate-time.log', 'time: ' . ( microtime( true ) - $time ) . "\n" . 'memory: ' . memory_get_peak_usage() . "\n\n", FILE_APPEND );
	exit;
} elseif( $a == 'xmlimport' ){
	$iTimeStart = microtime( true );
	function xPathVal( $xPath, $sPath, $oNode = null ){
		if( isset( $oNode ) ) $oTmp = $xPath->query( $sPath, $oNode );
		else $oTmp = $xPath->query( $sPath );
		if( empty( $oTmp->item( 0 )->value ) && isset( $oTmp->item( 0 )->childNodes ) ){
			return $oTmp->item( 0 )->childNodes->item( 0 )->wholeText;
		} else{
			return $oTmp->item( 0 )->value;
		}
	}
	$aProductOptions = Array( 'active' => 'iStatus', 'date' => 'sDate', 'avail_on_stock' => 'iAvailableOnStock', 'avail_out_of_stock' => 'iAvailableOutOfStock', 'producer' => 'sProducer', 'weight' => 'sWeight', 'client_weight' => 'sWeightDisplayed', 'size' => 'sSizeXYZ', 'fotolia' => 'iFotolia', 'alert_stock' => 'iStockSendAdminMin', 'measure' => 'sMeasure', 'user_discount' => 'iActiveDiscount', 'admin-id' => 'iAdmin', /*'promoted' => 'iPromoted', 'terminating' => 'iTerminating', 'sellout' => 'iSellOut',*/ 'used' => 'iNewUsed', 'not_for_sale' => 'iNotForSale', 'producer_url' => 'sProducerURL', 'review' => 'sReviewURL', 'catalog_number' => 'sCatalogNumber', 'product_index' => 'sProductIndex', 'comments' => 'iComments', );
	$aProductSeo = Array( 'title' => 'sNameTitle', 'description' => 'sMetaDescription', 'keywords' => 'sMetaKeywords', 'topic' => 'sMetaPageTopic', 'abstract' => 'sMetaAbstract', );
	$aVariantOptions = Array( 'active' => 'iStatus', 'user_discount' => 'iActiveDiscount', 'avail_on_stock' => 'iAvailableOnStock', 'avail_out_of_stock' => 'iAvailableOutOfStock', );
	function subpages_recurency( $xml, $oPagesNode, $xPath, $iPageParent = 0 ){
		$aPageOptions = Array( 'active' => 'iStatus', 'products' => 'iProducts', 'rss' => 'iRss', 'logged-only' => 'iAuthorized', 'url' => 'sUrl', 'date' => 'sDate', 'admin-id' => 'iAdmin', /*'subpages-show' => 'iSubpagesShow',*/ );
		$aPageSeo = Array( 'title' => 'sNameTitle', 'description' => 'sMetaDescription', 'keywords' => 'sMetaKeywords', 'topic' => 'sMetaPageTopic', 'abstract' => 'sMetaAbstract', );
		global $aPagesIds;
		$oDB = DataBase::getInstance( );
		for( $i = 0;$i < $oPagesNode->childNodes->length;$i++ ){
			$oPageNode = $oPagesNode->childNodes->item( $i );
			$cdata = $xPath->query( 'name', $oPageNode )->item( 0 );
			if( $cdata->childNodes->length > 0 ){
				$aPage = Array( 'sName' => $cdata->childNodes->item( 0 )->data );
				$aPage['iPage'] = $oDB->executeSQL( 'SELECT `iPage` FROM `' . $oDB->throwTableName( DB_PAGES ) . '` WHERE LOWER( `sName` ) = LOWER( \'' . $oDB->escape( $aPage['sName'] ) . '\' ) AND ( `iPageParent` = ' . intval( $iPageParent ) . ( empty( $iPageParent ) ? ' OR `iPageParent` IS NULL ) AND `iType` = 4' : ' )' ), true, DataBase::SINGLE_VALUE );
				$aPage['iPageXML'] = xPathVal( $xPath, '@id', $oPageNode );
				$aPage['iPosition'] = xPathVal( $xPath, '@position', $oPageNode );
				if( empty( $aPage['iPosition'] ) ) $aPage['iPosition'] = 0;
				$aPage['iPageParent'] = $iPageParent;
				$aPage['iType'] = 4;
				$aDescriptions = $xPath->query( 'description', $oPageNode );
				for( $j = 0;$j < $aDescriptions->length;$j++ ){
					$cdata = null;
					foreach( $aDescriptions->item( $j )->childNodes as $node ){
						if( get_class( $node ) == 'DOMCdataSection' ){
							$cdata = $node;
							break;
						}
					}
					if( isset( $cdata ) ){
						$type = xPathVal( $xPath, '@type', $aDescriptions->item( $j ) );
						/*if( $type == 'full' ) $aPage['sDescriptionFull'] = $cdata->data;
						else*/if( $type == 'short' ) $aPage['sDescriptionShort'] = $cdata->data;
						else die( 'Nieznany typ dla pola page/description (' . $type . ')!' );
					}
				}
				$aOptions = $xPath->query( 'options/option', $oPageNode );
				for( $j = 0;$j < $aOptions->length;$j++ ){
					$name = xPathVal( $xPath, '@name', $aOptions->item( $j ) );
					$value = xPathVal( $xPath, '@value', $aOptions->item( $j ) );
					if( isset( $aPageOptions[$name] ) ) $aPage[$aPageOptions[$name]] = $value;
					else die( 'Nieznana opcja page/options/option (' . $name . ')!' );
				}
				$aOptions = $xPath->query( 'seo/option', $oPageNode );
				for( $j = 0;$j < $aOptions->length;$j++ ){
					$name = xPathVal( $xPath, '@name', $aOptions->item( $j ) );
					$value = xPathVal( $xPath, '@value', $aOptions->item( $j ) );
					if( isset( $aPageSeo[$name] ) ) $aPage[$aPageSeo[$name]] = $value;
					else die( 'Nieznana opcja page/seo/option (' . $name . ')!' );
				}
				$aFiles = $xPath->query( 'files/file', $oPageNode );
				for( $j = 0;$j < $aFiles->length;$j++ ){
					$aPhoto = Array( );
					$aPhoto['sFileName'] = xPathVal( $xPath, '@href', $aFiles->item( $j ) );
					$aPhoto['iPhoto'] = xPathVal( $xPath, '@image', $aFiles->item( $j ) );
					$aPhoto['iType'] = xPathVal( $xPath, '@display', $aFiles->item( $j ) );
					$aPhoto['iPosition'] = xPathVal( $xPath, '@position', $aFiles->item( $j ) );
					$aPhoto['sDescription'] = xPathVal( $xPath, '@description', $aFiles->item( $j ) );
					$aPage['aFiles'][] = $aPhoto;
				}
				if( !isset( $aPage['iPage'] ) ){
					foreach( $GLOBALS['aDefaultPageOptionValues'] as $sOption => $mValue ){
						if( !isset( $aPage[$aPageOptions[$sOption]] ) ) $aPage[$aPageOptions[$sOption]] = $mValue;
					}
				}
				$aPage['iTime'] = (int)abs( ( !empty( $aPage['sDate'] ) ) ? dateToTime( $aPage['sDate'] ) : time( ) );
				$aPage['iPage'] = $oDB->save( DB_PAGES, $aPage, 'iPage' );
				$oDB->save( DB_PAGES_EXT, $aPage, 'iPage' );
				if( is_array( $aPage['aFiles'] ) ){
					$oDB->delete( DB_PAGES_FILES, Array( 'iPage' => $aPage['iPage'] ) );
					foreach( $aPage['aFiles'] as $aFile ){
						if( preg_match( '/^(https?|ftp):\\/\\//', $aFile['sFileName'] ) && is_file( DIR_FILES . basename( $aFile['sFileName'] ) ) ) $aFile['sFileName'] = basename( $aFile['sFileName'] );
						$aFile['iPage'] = $aPage['iPage'];
						$oDB->save( DB_PAGES_FILES, $aFile );
					}
				}
				$aPagesIds[$aPage['iPageXML']] = $aPage['iPage'];
				$oSubpagesNode = $xPath->query( 'subpages', $oPageNode )->item( 0 );
				subpages_recurency( $xml, $oSubpagesNode, $xPath, $aPage['iPage'] );
			}
		}
	}
	if( isset( $_FILES['xml'] ) && isset( $_POST['iStore'] ) ){
		$time = microtime( true );
		$xml = new DOMDocument( '1.0', 'utf-8' );
		$tmp = $_FILES['xml']['tmp_name'];
		if( preg_match( '/\\.zip$/', $_FILES['xml']['name'] ) ){
			$zip = new ZipArchive();
			$err = $zip->open( $tmp );
			if( $err === true ){
				$tmp = $zip->getFromIndex( 0 );
				$xml->loadXML( $tmp );
			} else{
				die( 'Error in ZIP archive: ' . $err );
			}
		} else{
			$xml->load( $tmp );
		}
		$xPath = new DOMXPath( $xml );
		$sXmlFileVer = xPathVal( $xPath, '/shop/@ver' );
		if( $sXmlFileVer > $sXmlVer ) die( 'Niekompatybilna wersja pliku XML (' . $sXmlFileVer . ', wymagana ' . $sXmlVer . ') - nie można zaimportować!' );
		$aPagesIds = Array( );
		$oPagesNode = $xPath->query( '/shop/pages' )->item( 0 );
		subpages_recurency( $xml, $oPagesNode, $xPath );
		$aProductsIds = Array( );
		$aProductsRelated = Array( );
		$oProductsNode = $xPath->query( '/shop/products' )->item( 0 );
		$iProductsSum = 0;
		$iProductsNew = 0;
		$iProductsAkt = 0;
		for( $i = 0;$i < $oProductsNode->childNodes->length;$i++ ){
			$oProductNode = $oProductsNode->childNodes->item( $i );
			$cdata = $xPath->query( 'name', $oProductNode )->item( 0 );
			if( $cdata->childNodes->length > 0 ){
				$aProduct = Array( 'sName' => $cdata->childNodes->item( 0 )->data );
				$iProductXML = xPathVal( $xPath, '@id', $oProductNode );
				$aProduct['iPosition'] = xPathVal( $xPath, '@position', $oProductNode );
				$aProduct['fPrice'] = xPathVal( $xPath, 'price', $oProductNode );
				$aProduct['fPriceOld'] = xPathVal( $xPath, 'price_old', $oProductNode );
				$aProduct['fBuyPrice'] = xPathVal( $xPath, 'price_buy', $oProductNode );
				$aProduct['fPriceTimeValue'] = xPathVal( $xPath, 'time_price', $oProductNode );
				$aProduct['iPriceTimeFrom'] = (int)abs( dateToTime( xPathVal( $xPath, 'time_price/@from', $oProductNode ) ) );
				$aProduct['iPriceTimeTo'] = (int)abs( dateToTime( xPathVal( $xPath, 'time_price/@to', $oProductNode ) ) );
				$aProduct['iCurrencyDependent'] = xPathVal( $xPath, 'price/@currency_dependent', $oProductNode );
				$aProduct['iVat'] = xPathVal( $xPath, 'vat', $oProductNode );
				$aDescriptions = $xPath->query( 'description', $oProductNode );
				for( $j = 0;$j < $aDescriptions->length;$j++ ){
					$cdata = null;
					foreach( $aDescriptions->item( $j )->childNodes as $node ){
						if( get_class( $node ) == 'DOMCdataSection' ){
							$cdata = $node;
							break;
						}
					}
					if( isset( $cdata ) ){
						$type = xPathVal( $xPath, '@type', $aDescriptions->item( $j ) );
						if( $type == 'full' ) $aProduct['sDescriptionFull'] = $cdata->data;
						elseif( $type == 'short' ) $aProduct['sDescriptionShort'] = $cdata->data;
						else die( 'Nieznany typ dla pola product/description (' . $type . ')!' );
					}
				}
				$aTabs = $xPath->query( 'tab', $oProductNode );
				for( $j = 0;$j < $aTabs->length;$j++ ){
					$cdata = null;
					foreach( $aTabs->item( $j )->childNodes as $node ){
						if( get_class( $node ) == 'DOMCdataSection' ){
							$cdata = $node;
							break;
						}
					}
					if( isset( $cdata ) ){
						$type = xPathVal( $xPath, '@type', $aTabs->item( $j ) );
						if( is_numeric( $type ) ) $aProduct['aTabs'][$type] = $cdata->data;
						else die( 'Nieznany typ dla pola product/tab (' . $type . ')!' );
					}
				}
				$aOptions = $xPath->query( 'options/option', $oProductNode );
				for( $j = 0;$j < $aOptions->length;$j++ ){
					$name = xPathVal( $xPath, '@name', $aOptions->item( $j ) );
					$value = xPathVal( $xPath, '@value', $aOptions->item( $j ) );
					if( isset( $aProductOptions[$name] ) ) $aProduct[$aProductOptions[$name]] = $value;
					else die( 'Nieznana opcja product/options/option (' . $name . ')!' );
				}
				$aOptions = $xPath->query( 'seo/option', $oProductNode );
				for( $j = 0;$j < $aOptions->length;$j++ ){
					$name = xPathVal( $xPath, '@name', $aOptions->item( $j ) );
					$value = xPathVal( $xPath, '@value', $aOptions->item( $j ) );
					if( isset( $aProductSeo[$name] ) ) $aProduct[$aProductSeo[$name]] = $value;
					else die( 'Nieznana opcja product/seo/option (' . $name . ')!' );
				}
				$aFiles = $xPath->query( 'files/file', $oProductNode );
				for( $j = 0;$j < $aFiles->length;$j++ ){
					$aPhoto = Array( );
					$aPhoto['sFileName'] = xPathVal( $xPath, '@href', $aFiles->item( $j ) );
					$aPhoto['iPhoto'] = xPathVal( $xPath, '@image', $aFiles->item( $j ) );
					$aPhoto['iType'] = xPathVal( $xPath, '@display', $aFiles->item( $j ) );
					$aPhoto['iPosition'] = xPathVal( $xPath, '@position', $aFiles->item( $j ) );
					$aPhoto['sDescription'] = xPathVal( $xPath, '@description', $aFiles->item( $j ) );
					$aProduct['aFiles'][] = $aPhoto;
				}
				$aPages = $xPath->query( 'pages/page', $oProductNode );
				for( $j = 0;$j < $aPages->length;$j++ ){
					$aProduct['aPages'][] = Array( 'iPage' => $aPagesIds[xPathVal( $xPath, '@id', $aPages->item( $j ) ) ], 'iMainCategory' => xPathVal( $xPath, '@main', $aPages->item( $j ) ), );
				}
				$aRelatedGroups = $xPath->query( 'related', $oProductNode );
				for( $j = 0;$j < $aRelatedGroups->length;$j++ ){
					$type = xPathVal( $xPath, '@type', $aRelatedGroups->item( $j ) );
					$aRelated = $xPath->query( 'product', $aRelatedGroups->item( $j ) );
					for( $k = 0;$k < $aRelated->length;$k++ ){
						$aProduct['aRelated'][$type][] = xPathVal( $xPath, '@id', $aRelated->item( $k ) );
					}
				}
				if( !empty( $aProduct['sProducer'] ) ){
					$aProduct['iProducer'] = $oDB->executeSQL( 'SELECT `iProducer` FROM `' . $oDB->throwTableName( DB_PRODUCERS ) . '` WHERE `sName` = \'' . $oDB->escape( $aProduct['sProducer'] ) . '\'', true, DataBase::SINGLE_VALUE );
					if( empty( $aProduct['iProducer'] ) ) $aProduct['iProducer'] = $oDB->save( DB_PRODUCERS, Array( 'sName' => $aProduct['sProducer'], 'iPosition' => 0 ) );
				}
				
				$aAttributes = $xPath->query( 'attributes/attribute', $oProductNode );
				for( $k = 0;$k < $aAttributes->length;$k++ ){
					$name = xPathVal( $xPath, '@name', $aAttributes->item( $k ) );
					$value = xPathVal( $xPath, '@value', $aAttributes->item( $k ) );
					$aAttribute = Array( );
					$aAttribute['iAttribute'] = $oDB->executeSQL( 'SELECT `iAttribute` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES ) . '` WHERE `sName` LIKE \'' . $oDB->escape( $name ) . '\'', true, DataBase::SINGLE_VALUE );
					if( !( $aAttribute['iAttribute'] ) ) $aAttribute['iAttribute'] = $oDB->executeSQL( 'SELECT `alt`.`iAttribute` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_ALT ) . '` `alt` WHERE `alt`.`sName` LIKE \'' . $oDB->escape( $name ) . '\'', true, DataBase::SINGLE_VALUE );
					if( !( $aAttribute['iAttribute'] ) ) $aAttribute['iAttribute'] = $oDB->save( DB_ATTRIBUTES, Array( 'sName' => $name ) );
					$aAttribute['iAttributeValue'] = $oDB->executeSQL( 'SELECT `iAttributeValue` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` WHERE `iAttribute` = ' . $aAttribute['iAttribute'] . ' AND `sValue` LIKE \'' . $oDB->escape( $value ) . '\'', true, DataBase::SINGLE_VALUE );
					if( !( $aAttribute['iAttributeValue'] ) ) $aAttribute['iAttributeValue'] = $oDB->executeSQL( 'SELECT `alt`.`iAttributeValue` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_ALT_VALUES ) . '` `alt` INNER JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` `av` USING( `iAttributeValue` ) WHERE `av`.`iAttribute` = ' . $aAttribute['iAttribute'] . ' AND `alt`.`sValue` LIKE \'' . $oDB->escape( $value ) . '\'', true, DataBase::SINGLE_VALUE );
					if( !( $aAttribute['iAttributeValue'] ) ) $aAttribute['iAttributeValue'] = $oDB->save( DB_ATTRIBUTES_VALUES, Array( 'sValue' => $value, 'iAttribute' => $aAttribute['iAttribute'] ) );
					$aProduct['aProductAttributes'][$aAttribute['iAttribute']][] = $aAttribute['iAttributeValue'];
				}
				
				$aVariants = $xPath->query( 'variants/variant', $oProductNode );
				for( $j = 0;$j < $aVariants->length;$j++ ){
					$oVariant = $aVariants->item( $j );
					$aVariant = Array( );
					$aVariant['iStock'] = xPathVal( $xPath, '@stock', $oVariant );
					$aVariant['sEan'] = xPathVal( $xPath, '@ean', $oVariant );
					$aVariant['sOuterId'] = xPathVal( $xPath, '@outerid', $oVariant );
					$aVariant['fPrice'] = xPathVal( $xPath, 'price', $oVariant );
					$aVariant['fPriceOld'] = xPathVal( $xPath, 'price_old', $oVariant );
					$aVariant['fPriceTimeValue'] = xPathVal( $xPath, 'time_price', $oVariant );
					$aVariant['iVat'] = xPathVal( $xPath, 'vat', $oVariant );
					$aOptions = $xPath->query( 'options/option', $oVariant );
					for( $k = 0;$k < $aOptions->length;$k++ ){
						$name = xPathVal( $xPath, '@name', $aOptions->item( $k ) );
						$value = xPathVal( $xPath, '@value', $aOptions->item( $k ) );
						if( isset( $aVariantOptions[$name] ) ) $aVariant[$aVariantOptions[$name]] = $value;
						else die( 'Nieznana opcja product/variants/variant/options/option (' . $name . ' ' . $k . '@wariant ' . $aVariant['sOuterId'] . ')!' );
					}
					foreach( $aDefaultVariantOptionValues as $sOption => $mValue ){
						if( !isset( $aVariant[$aVariantOptions[$sOption]] ) ) $aVariant[$aVariantOptions[$sOption]] = $mValue;
					}
					$aAttributes = $xPath->query( 'attributes/attribute', $oVariant );
					for( $k = 0;$k < $aAttributes->length;$k++ ){
						$name = xPathVal( $xPath, '@name', $aAttributes->item( $k ) );
						$value = xPathVal( $xPath, '@value', $aAttributes->item( $k ) );
						$aAttribute = Array( );
						$aAttribute['iAttribute'] = $oDB->executeSQL( 'SELECT `iAttribute` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES ) . '` WHERE `sName` LIKE \'' . $oDB->escape( $name ) . '\'', true, DataBase::SINGLE_VALUE );
						if( !( $aAttribute['iAttribute'] ) ) $aAttribute['iAttribute'] = $oDB->executeSQL( 'SELECT `alt`.`iAttribute` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_ALT ) . '` `alt` WHERE `alt`.`sName` LIKE \'' . $oDB->escape( $name ) . '\'', true, DataBase::SINGLE_VALUE );
						if( !( $aAttribute['iAttribute'] ) ) $aAttribute['iAttribute'] = $oDB->save( DB_ATTRIBUTES, Array( 'sName' => $name ) );
						$aAttribute['iAttributeValue'] = $oDB->executeSQL( 'SELECT `iAttributeValue` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` WHERE `iAttribute` = ' . $aAttribute['iAttribute'] . ' AND `sValue` LIKE \'' . $oDB->escape( $value ) . '\'', true, DataBase::SINGLE_VALUE );
						if( !( $aAttribute['iAttributeValue'] ) ) $aAttribute['iAttributeValue'] = $oDB->executeSQL( 'SELECT `alt`.`iAttributeValue` FROM `' . $oDB->throwTableName( DB_ATTRIBUTES_ALT_VALUES ) . '` `alt` INNER JOIN `' . $oDB->throwTableName( DB_ATTRIBUTES_VALUES ) . '` `av` USING( `iAttributeValue` ) WHERE `av`.`iAttribute` = ' . $aAttribute['iAttribute'] . ' AND `alt`.`sValue` LIKE \'' . $oDB->escape( $value ) . '\'', true, DataBase::SINGLE_VALUE );
						if( !( $aAttribute['iAttributeValue'] ) ) $aAttribute['iAttributeValue'] = $oDB->save( DB_ATTRIBUTES_VALUES, Array( 'sValue' => $value, 'iAttribute' => $aAttribute['iAttribute'] ) );
						$aVariant['aAttributes'][] = $aAttribute['iAttributeValue'];
					}
					$aProduct['aVariants'][] = $aVariant;
				}
				$aAdvsearcher = $xPath->query( 'advsearcher', $oProductNode );
				for( $k = 0;$k < $aAdvsearcher->length;$k++ ){
					$aAdvsearcherValue = explode( ' &raquo; ', xPathVal( $xPath, '.', $aAdvsearcher->item( $k ) ) );
					$iAdvsearcherValue = null;
					while( !empty( $aAdvsearcherValue ) ){
						$sAdvsearcherValue = array_shift( $aAdvsearcherValue );
						if( empty( $sAdvsearcherValue ) ) continue;
						$iAdvsearcherValue = $oDB->executeSQL( 'SELECT `iValue` FROM `' . $oDB->throwTableName( DB_ADVSEARCHER_VALUES ) . '` WHERE `sValue` = \'' . $oDB->escape( $sAdvsearcherValue ) . '\' AND `iParentValue` ' . ( empty( $iAdvsearcherValue ) ? 'IS NULL' : ' = ' . intval( $iAdvsearcherValue ) ), true, DataBase::SINGLE_VALUE );
						if( empty( $iAdvsearcherValue ) ) $iAdvsearcherValue = saveAdvsearcherValue( Array( 'sValue' => $sAdvsearcherValue, 'iParentValue' => $iAdvsearcherValue ) );
					}
					$aProduct['aAdvsearcher'][] = $iAdvsearcherValue;
				}
				if( !empty( $aProduct['sProductIndex'] ) ){
					$aProduct['iProduct'] = $oDB->executeSQL( 'SELECT `iProduct` FROM `' . $oDB->throwTableName( DB_PRODUCTS ) . '` WHERE `sProductIndex` LIKE \'' . $oDB->escape( $aProduct['sProductIndex'] ) . '\'', true, DataBase::SINGLE_VALUE );
					if( !empty( $aProduct['iProduct'] ) ) $aProduct['bUpdate'] = true;
				}
				if( $aProduct['bUpdate'] ) $iProductsAkt++;
				else $iProductsNew++;
				$iProductsSum++;
				if( !isset( $aProduct['iProduct'] ) ){
					foreach( $aDefaultProductOptionValues as $sOption => $mValue ){
						if( !isset( $aProduct[$aProductOptions[$sOption]] ) ) $aProduct[$aProductOptions[$sOption]] = $mValue;
					}
				}
				$aProduct['iTime'] = (int)abs( ( !empty( $aProduct['sDate'] ) ) ? dateToTime( $aProduct['sDate'] ) : time( ) );
				if( empty( $aProduct['iVat'] ) ){
					$aProduct['iVat'] = 1;
				}
				$aProduct['iProduct'] = $oDB->save( DB_PRODUCTS, $aProduct, 'iProduct' );
				$oDB->save( DB_PRODUCTS_EXT, $aProduct, 'iProduct' );
				$aProductsIds[$iProductXML] = $aProduct['iProduct'];
				foreach( $aProduct['aVariants'] as $aVariant ){
					$aVariant['iProduct'] = $aProduct['iProduct'];
					$sIndex = null;
					if( $aProduct['bUpdate'] && !empty( $aVariant['sOuterId'] ) ){
						$aVariant['iProductVariant'] = $oDB->executeSQL( 'SELECT `iProductVariant` FROM ' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . ' WHERE `sOuterId` LIKE \'' . $oDB->escape( $aVariant['sOuterId'] ) . '\' AND `iProduct` = ' . intval( $aVariant['iProduct'] ), true, DataBase::SINGLE_VALUE );
						if( !empty( $aVariant['iProductVariant'] ) ){
							$sIndex = 'iProductVariant';
							if( is_array( $aVariant['aAttributes'] ) ){
								$oDB->delete( DB_PRODUCTS_ATTRIBUTES, Array( 'iProductVariant' => $aVariant['iProductVariant'] ) );
							}
						}
					}
					$aVariant['iProductVariant'] = $oDB->save( DB_PRODUCTS_VARIANTS, $aVariant, $sIndex );
					$iStock = $aVariant['iStock'];
					if( is_numeric( $iStock ) ){
						if( !$oDB->update( DB_STORES_PRODUCTS, Array( 'iStock' => intval( $iStock ) ), Array( 'iProductVariant' => intval( $aVariant['iProductVariant'] ), 'iStore' => intval( $_POST['iStore'] ) ) ) ){
							$oDB->save( DB_STORES_PRODUCTS, Array( 'iStock' => intval( $iStock ), 'iProductVariant' => intval( $aVariant['iProductVariant'] ), 'iStore' => intval( $_POST['iStore'] ) ) );
						}
					} else{
						$oDB->executeSQL( 'DELETE FROM `' . $oDB->throwTableName( DB_STORES_PRODUCTS ) . '` WHERE `iStore` = ' . intval( $_POST['iStore'] ) . ' AND `iProductVariant` = ' . intval( $aVariant['iProductVariant'] ) );
					}
					if( is_array( $aVariant['aAttributes'] ) ) foreach( $aVariant['aAttributes'] as $iAttributeValue ){
						$oDB->save( DB_PRODUCTS_ATTRIBUTES, Array( 'iProductVariant' => $aVariant['iProductVariant'], 'iAttributeValue' => $iAttributeValue ) );
					}
				}
				if( is_array( $aProduct['aPages'] ) ){
					$oDB->delete( DB_PRODUCTS_PAGES, Array( 'iProduct' => $aProduct['iProduct'] ) );
					foreach( $aProduct['aPages'] as $aPage ){
						$aPage['iProduct'] = $aProduct['iProduct'];
						$oDB->save( DB_PRODUCTS_PAGES, $aPage );
					}
				}
				if( is_array( $aProduct['aRelated'] ) ){
					$oDB->delete( DB_PRODUCTS_RELATED, Array( 'iProduct' => $aProduct['iProduct'] ) );
					foreach( $aProduct['aRelated'] as $iBox => $aRelatedGroup ){
						foreach( $aRelatedGroup as $iRelated ){
							$aProductsRelated[$aProduct['iProduct']][$iBox][] = $iRelated;
							//$oDB->save( DB_PRODUCTS_RELATED, Array( 'iProduct' => $aProduct['iProduct'], 'iRelated' => $iRelated, 'iBox' => $iBox ) );
							
						}
					}
				}
				if( is_array( $aProduct['aTabs'] ) ) foreach( $aProduct['aTabs'] as $aTab['iTab'] => $aTab['sContent'] ){
					$aTab['iProduct'] = $aProduct['iProduct'];
					$oDB->delete( DB_PRODUCTS_TABS, Array( 'iProduct' => $aTab['iProduct'], 'iTab' => $aTab['iTab'] ) );
					$oDB->save( DB_PRODUCTS_TABS, $aTab );
				}
				if( is_array( $aProduct['aFiles'] ) ){
					$oDB->delete( DB_PRODUCTS_FILES, Array( 'iProduct' => $aProduct['iProduct'] ) );
					foreach( $aProduct['aFiles'] as $aFile ){
						if( preg_match( '/^(https?|ftp):\\/\\//', $aFile['sFileName'] ) && is_file( DIR_FILES . basename( $aFile['sFileName'] ) ) ) $aFile['sFileName'] = basename( $aFile['sFileName'] );
						$aFile['iProduct'] = $aProduct['iProduct'];
						$oDB->save( DB_PRODUCTS_FILES, $aFile );
					}
				}
				if( is_array( $aProduct['aAdvsearcher'] ) ){
					$oDB->delete( DB_ADVSEARCHER_PRODUCTS, Array( 'iProduct' => $aProduct['iProduct'] ) );
					foreach( $aProduct['aAdvsearcher'] as $iAdvsearcher ){
						$oDB->save( DB_ADVSEARCHER_PRODUCTS, Array( 'iProduct' => $aProduct['iProduct'], 'iValue' => $iAdvsearcher ) );
					}
				}
				if( is_array( $aProduct['aProductAttributes'] ) ){
					foreach( $aProduct['aProductAttributes'] as $iAttribute => $aValues ){
						foreach( $aValues as $iValue ){
							$oDB->save( DB_PRODUCTS_ATTRIBUTES_CONST, Array( 'iProduct' => $aProduct['iProduct'], 'iAttributeValue' => $iValue, 'iAttribute' => $iAttribute ) );
						}
					}
				}
			}
		}
		//Dodawanie powiązań między produktami
		foreach( $aProductsRelated as $aRelProduct['iProduct'] => $aRelated ){
			foreach( $aRelated as $aRelProduct['iBox'] => $aRelated1 ){
				foreach( $aRelated1 as $aRelProduct['iRelated'] ){
					$aRelProduct['iRelated'] = $aProductsIds[$aRelProduct['iRelated']];
					$oDB->save( DB_PRODUCTS_RELATED, $aRelProduct );
				}
			}
		}
		if( function_exists( 'getrusage' ) ){
			$dat = getrusage( );
			$iTime = $dat["ru_utime.tv_sec"] + $dat["ru_utime.tv_usec"] / 1000000;
		} else{
			$iTime = microtime( true ) - $iTimeStart;
		}
		$iPhotosToImport = $oDB->executeSQL( 'SELECT COUNT( `sFileName` ) FROM ( SELECT DISTINCT `sFileName` FROM `' . $oDB->throwTableName( DB_PRODUCTS_FILES ) . '` WHERE `sFileName` LIKE \'http://%\' OR `sFileName` LIKE \'https://%\' UNION SELECT DISTINCT `sFileName` FROM `' . $oDB->throwTableName( DB_PAGES_FILES ) . '` WHERE `sFileName` LIKE \'http://%\' OR `sFileName` LIKE \'https://%\' ) `tmp`', true, DataBase::SINGLE_VALUE );
		$oTpl->assign( 'iMemory', memory_get_peak_usage( true ) );
		$oTpl->assign( 'iTime', $iTime );
		$oTpl->assign( 'iProductsSum', $iProductsSum );
		$oTpl->assign( 'iProductsAkt', $iProductsAkt );
		$oTpl->assign( 'iProductsNew', $iProductsNew );
		$oTpl->assign( 'iPhotosToImport', $iPhotosToImport );
		$content.= $oTpl->parse( 'message_done_import.tpl' );
	} else{
		$oTpl->assign( 'aStores', $oDB->throwFileArraySmall( DB_STORES, 'iStore', 'sName', 'iPriority' ) );
		$content.= $oTpl->parse( 'migrate_xmlimportexport.tpl' );
	}
} elseif( $a == 'photos' ){
	$sql = 'SELECT `sFileName` FROM( SELECT DISTINCT `sFileName` FROM `' . $oDB->throwTableName( DB_PRODUCTS_FILES ) . '` WHERE `sFileName` LIKE \'http://%\' OR `sFileName` LIKE \'https://%\' UNION SELECT DISTINCT `sFileName` FROM `' . $oDB->throwTableName( DB_PAGES_FILES ) . '` WHERE `sFileName` LIKE \'http://%\' OR `sFileName` LIKE \'https://%\' ) `tmp` LIMIT 10';
	$aPhotos = $oDB->executeSQL( $sql, true, DataBase::SINGLE_COLUMN );
	if( count( $aPhotos ) > 0 ){
		foreach( $aPhotos as &$sPhoto ){
			if( is_file( DIR_FILES . basename( $sPhoto ) ) ){
				$oDB->update( DB_PAGES_FILES, Array( 'sFileName' => basename( $sPhoto ) ), Array( 'sFileName' => $sPhoto ) );
				$oDB->update( DB_PRODUCTS_FILES, Array( 'sFileName' => basename( $sPhoto ) ), Array( 'sFileName' => $sPhoto ) );
			} elseif( preg_match( '|^(https?)://([^/:]+)(:([0-9]+))?(/.*)$|', $sPhoto, $aMatches ) ){
				$req_hdr = false;
//
//				$res_hdr = false;
//				$sFileContent = http_request( 'GET', $aMatches[2], ( empty( $aMatches[4] ) ? 80 : $aMatches[4] ), $aMatches[5], array( ), array( ), array( ), array( ), 1000, $req_hdr, $res_hdr );
//				file_put_contents( DIR_FILES . basename( $sPhoto ), $sFileContent );
//				$oDB->update( DB_PAGES_FILES, Array( 'sFileName' => basename( $sPhoto ) ), Array( 'sFileName' => $sPhoto ) );
//				$oDB->update( DB_PRODUCTS_FILES, Array( 'sFileName' => basename( $sPhoto ) ), Array( 'sFileName' => $sPhoto ) );
				$sFileContent = file_get_contents( $sPhoto );
//				$sFileContent = http_request( 'GET', $aMatches[2], ( empty( $aMatches[4] ) ? 80 : $aMatches[4] ), $aMatches[5], array( ), array( ), array( ), array( ), 1000, $req_hdr, $res_hdr );
				if( !empty( $sFileContent ) ){
					file_put_contents( DIR_FILES . strtolower( basename( $sPhoto ) ), $sFileContent );
					$oDB->update( DB_PAGES_FILES, Array( 'sFileName' => strtolower( basename( $sPhoto ) ) ), Array( 'sFileName' => $sPhoto ) );
					$oDB->update( DB_PRODUCTS_FILES, Array( 'sFileName' => strtolower( basename( $sPhoto ) ) ), Array( 'sFileName' => $sPhoto ) );
				} else{
//					var_dump( 'GET', $aMatches[2], ( empty( $aMatches[4] ) ? 80 : $aMatches[4] ), $aMatches[5], array( ), array( ), array( ), array( ), 1000, $req_hdr, $res_hdr );
//					var_dump( $sFileContent );
					echo ( 'Błąd pobierania pliku - pusta zawartość: ' .$sPhoto. "<br />");
					$oDB->executeSQL( 'DELETE FROM `' . $oDB->throwTableName( DB_PAGES_FILES ) . '` WHERE `sFileName` = \'' . $oDB->escape( $sPhoto ) . '\'' );
					$oDB->executeSQL( 'DELETE FROM `' . $oDB->throwTableName( DB_PRODUCTS_FILES ) . '` WHERE `sFileName` = \'' . $oDB->escape( $sPhoto ) . '\'' );
				}
			}
		}
		echo ( '<html><head><meta http-equiv="refresh" content="0;url=admin.php?p=migrate-photos" /><title>Czekaj...</title></head><body>Czekaj...</body></html>' );
		exit;
	} else{
		$content.= $oTpl->parse( 'message_done.tpl' );
	}
} elseif( $a == 'import_newsletter' && !isset( $_FILES['csv_file'] ) ){
	$content.= $oTpl->parse( 'migrate_newsletterimport.tpl' );
} elseif( $a == 'import_newsletter' && isset( $_FILES['csv_file'] ) ){
	$aEmails = file_get_contents( $_FILES['csv_file']['tmp_name'] );
	$aEmails = preg_split( '/\s+/', $aEmails );
	foreach( $aEmails as $sEmail ){
		if( !empty( $sEmail ) ){
			$oDB->executeSQL( 'INSERT IGNORE INTO `' . $oDB->throwTableName( DB_NEWSLETTER ) . '` ( `sEmail` ) VALUES ( \'' . $oDB->escape( $sEmail ) . '\' )' );
		}
	}
	$content .= $oTpl->parse( 'message_done_back.tpl' );
} elseif( $a == 'export_newsletter' ){
	header( 'Content-type: text/csv' );
	header( 'Content-Disposition: attachment; filename=newsletter.csv;' );
	$aNewsletters = $oDB->executeSQL( 'SELECT `sEmail` FROM `' . $oDB->throwTableName( DB_NEWSLETTER ) . '`', true, DataBase::SINGLE_COLUMN );
	foreach( $aNewsletters as $sEmail ){
		echo( $sEmail . "\r\n" );
	}
	exit;
}
?>