<?php
/**
 * Maintenance model
 *
 * @package 	CSVIVirtueMart
 * @author 		Roland Dalmulder
 * @link 		http://www.csvimproved.com
 * @copyright 	Copyright (C) 2006 - 2012 RolandD Cyber Produksi
 * @license 	GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 * @version 	$Id: maintenance.php 1892 2012-02-11 11:01:09Z RolandD $
 */

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

jimport( 'joomla.application.component.model' );

/**
 * Maintenance Model
 *
 * @package CSVIVirtueMart
 */
class CsvivirtuemartModelMaintenance extends JModel {

	/** @var array contains the categories in the system */
	var $_categories = array();

	/** @var array contains a list of levels deep per category */
	var $_catlevels = array();

	/** @var array contains a list of subcategories per category */
	var $_catpaths = array();

	/**
	 * Prepare maintenance
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.3
	 */
	public function getPrepareMaintenance() {
		// Start the log
		$csvilog = new CsviLog();
		$import_id = $csvilog->setId();
		$csvilog->SetAction('Maintenance');
		$csvilog->SetActionType(JRequest::getCmd('task').'_LABEL');
		JRequest::setVar('import_id', $import_id);
		JRequest::setVar('csvilog', $csvilog);
	}

	/**
	 * Finish up maintenance
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.3
	 */
	public function getFinishProcess() {
		// Store the log
		$model_log = $this->getModel('log');
		$model_log->getStoreLogResults();
	}

	/**
	 * Create a proxy for including other models
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		protected
	 * @param
	 * @return
	 * @since 		3.0
	 */
	protected function getModel($model) {
		return $this->getInstance($model, 'CsvivirtuemartModel');
	}

	/**
	 * Empty VirtueMart tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo 		Write out product type tables that get deleted
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getEmptyDatabase() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$linenumber = 1;

		// Empty all the necessary tables
		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_price`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product price table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_PRICE_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_PRICE_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_mf_xref`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product manufacturer link table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_MANUFACTURER_LINK_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_MANUFACTURER_LINK_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_attribute`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product attribute table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_ATTRIBUTE_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_ATTRIBUTE_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_category`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty category table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_CATEGORY_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_CATEGORY_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_category_xref`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty category link table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_CATEGORY_LINK_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_CATEGORY_LINK_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_attribute_sku`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty attribute for parent products table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_ATTRIBUTE_FOR_PARENT_PRODUCTS_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_ATTRIBUTE_FOR_PARENT_PRODUCTS_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_category_xref`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product category link table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_CATEGORY_LINK_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_CATEGORY_LINK_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_discount`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product discount table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_DISCOUNT_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_DISCOUNT_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_type`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product type table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TYPE_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TYPE_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_type_parameter`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product type parameter table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TYPE_PARAMETER_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TYPE_PARAMETER_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_product_type_xref`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product type link table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TYPE_LINK_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_TYPE_LINK_TABLE_HAS_NOT_BEEN_EMPTIED'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_relations`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product relations table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_RELATIONS_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_RELATIONS_TABLE_HAS_NOT_BEEN_EMPTIED'));

		// Get the lowest manufacturer ID
		$q = "SELECT MIN(manufacturer_id) AS mf_id FROM ".$db->nameQuote('#__vm_manufacturer');
		$db->setQuery($q);
		$mf_id = $db->loadResult();

		// Delete anything higher than the lowest ID
		$csvilog->setLinenumber($linenumber++);
		$q = "DELETE FROM `#__vm_manufacturer` WHERE manufacturer_id > ".$mf_id;
		$db->setQuery($q);
		$csvilog->addDebug('Empty manufacturer table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_MANUFACTURER_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_MANUFACTURER_TABLE_HAS_NOT_BEEN_EMPTIED'));

		// Optimize the table
		$csvilog->setLinenumber($linenumber++);
		$q =  "OPTIMIZE TABLE ".$db->nameQuote('#__vm_manufacturer');
		$db->setQuery($q);
		if ($db->query()) $csvilog->AddStats('information', JText::_('COM_CSVIVIRTUEMART_MANUFACTURER_TABLE_HAS_BEEN_OPTIMIZED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_MANUFACTURER_TABLE_HAS_NOT_BEEN_OPTIMIZED'));
		// Reset the auto increment
		$csvilog->setLinenumber($linenumber++);
		$q = "ALTER TABLE ".$db->nameQuote('#__vm_manufacturer')." AUTO_INCREMENT = ".($mf_id+1);
		if ($db->query()) $csvilog->AddStats('information', JText::_('COM_CSVIVIRTUEMART_MANUFACTURER_AUTO_INCREMENT_RESET'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_MANUFACTURER_AUTO_INCREMENT_NOT_RESET'));

		$csvilog->setLinenumber($linenumber++);
		$q = "TRUNCATE TABLE `#__vm_product_files`;";
		$db->setQuery($q);
		$csvilog->addDebug('Empty product files table', true);
		if ($db->query()) $csvilog->AddStats('empty', JText::_('COM_CSVIVIRTUEMART_PRODUCT_FILES_TABLE_HAS_BEEN_EMPTIED'));
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_PRODUCT_FILES_TABLE_HAS_NOT_BEEN_EMPTIED'));

		// Check if there are any product type tables created, if so, remove them
		$q = "SHOW TABLES LIKE '%vm_product_type_%'";
		$db->setQuery($q);
		$tables = $db->loadResultArray();
		$config = new JConfig;
		foreach ($tables as $key => $tablename) {
			if (stristr('0123456789', substr($tablename, -1))) {
				$csvilog->setLinenumber($linenumber++);
				$q_drop = "DROP TABLE ".$db->nameQuote($tablename);
				$db->setQuery($q_drop);
				$csvilog->addDebug(JText::sprintf('COM_CSVIVIRTUEMART_DEBUG_DELETE_PRODUCT_TYPE_NAME_TABLE', $tablename, true));
				if ($db->query()) $csvilog->AddStats('deleted', JText::sprintf('COM_CSVIVIRTUEMART_PRODUCT_TYPE_NAME_TABLE_DELETED', $tablename));
				else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_PRODUCT_TYPE_NAME_TABLE_NOT_DELETED', $tablename));
			}
		}

		// Store the log count
		$linenumber--;
		JRequest::setVar('logcount', $linenumber);
		return true;
	}

	/**
	* Optimize CSVI VirtueMart and VirtueMart tables
	*
	* @todo clean up messages
	*/
	public function getOptimizeTables() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$linenumber = 1;
		$tables = array();
		$tables[] = '#__csvivirtuemart_available_fields';
		$tables[] = '#__csvivirtuemart_template_fields';
		$tables[] = '#__csvivirtuemart_template_types';
		$tables[] = '#__csvivirtuemart_templates';
		$tables[] = '#__csvivirtuemart_logs';
		$tables[] = '#__csvivirtuemart_log_details';
		$tables[] = '#__vm_product';
		$tables[] = '#__vm_product_price';
		$tables[] = '#__vm_product_mf_xref';
		$tables[] = '#__vm_product_attribute';
		$tables[] = '#__vm_category';
		$tables[] = '#__vm_category_xref';
		$tables[] = '#__vm_product_attribute_sku';
		$tables[] = '#__vm_product_category_xref';
		$tables[] = '#__vm_product_discount';
		$tables[] = '#__vm_product_type';
		$tables[] = '#__vm_product_type_parameter';
		$tables[] = '#__vm_product_product_type_xref';
		$tables[] = '#__vm_product_relations';
		$tables[] = '#__vm_manufacturer';

		foreach ($tables as $id => $tablename) {
			$csvilog->setLinenumber($linenumber++);
			$q =  "OPTIMIZE TABLE ".$tablename;
			$db->setQuery($q);
			if ($db->query()) $csvilog->AddStats('information', JText::sprintf('COM_CSVIVIRTUEMART_TABLE_HAS_BEEN_OPTIMIZED', substr($tablename, 3)));
			else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_TABLE_HAS_NOT_BEEN_OPTIMIZED', substr($tablename,3)));
		}
		// Store the log count
		$linenumber--;
		JRequest::setVar('logcount', $linenumber);
		return true;
	}

	/**
	 * Sorts all VirtueMart categories in alphabetical order
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return 		bool	true if categories are sorted | false if an error occured
	 * @since 		3.0
	 */
	public function getSortCategories() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');

		// Get all categories
		$query  = "SELECT LOWER(category_name) AS category_name, category_child_id as cid, category_parent_id as pid
				FROM #__vm_category, #__vm_category_xref
				WHERE #__vm_category.category_id=#__vm_category_xref.category_child_id ";

		// Execute the query
		$db->setQuery($query);

		$records = $db->loadObjectList();
		if (count($records) > 0) {
			$categories = array();

			// Group all categories together according to their level
			foreach ($records as $key => $record) {
				$categories[$record->pid][$record->cid] = $record->category_name;
			}

			// Sort the categories and store the item list
			foreach ($categories as $id => $category) {
				asort($category);
				$listorder = 1;
				foreach ($category as $category_id => $category_name) {
					// Store the new sort order
					$q = "UPDATE #__vm_category
						SET list_order = '".$listorder."'
						WHERE category_id = '".$category_id."'";
					$db->setQuery($q);
					$db->query();
					JRequest::setVar('currentline', JRequest::getInt('currentline', 0)+1);
					$csvilog->AddStats('information', JText::sprintf('COM_CSVIVIRTUEMART_SAVED_CATEGORY', $category_name ,$listorder));
					$listorder++;
				}
			}
		}
		else $csvilog->AddStats('information', JText::_('COM_CSVIVIRTUEMART_NO_CATEGORIES_FOUND'));
		return true;
	}

	/**
	 * Get the current size of the product name field
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return 		integer	the size of the longest product name
	 * @since 		3.0
	 */
	public function getSizeProductName() {
	 	$db = JFactory::getDBO();
	 	$q = "SELECT MAX(LENGTH(product_name)) FROM #__vm_product";
	 	$db->setQuery($q);
	 	$length = $db->loadResult();
	 	if (is_null($length)) $length = 0;
	 	return $length;
	}

	/**
	 * Adjust the size of the product name field
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getResizeProductName() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$q = "ALTER TABLE #__vm_product CHANGE `product_name` `product_name` VARCHAR(".JRequest::getInt('productnamefieldlength').") DEFAULT NULL NULL;";
		$db->setQuery($q);
		if ($db->query()) {
			$csvilog->AddStats('information', JText::sprintf('COM_CSVIVIRTUEMART_CHANGE_NAME_LENGTH_OK', JRequest::getInt('productnamefieldlength')));
			return true;
		}
		else {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_CHANGE_NAME_LENGTH_NOK', $db->getErrorMsg()));
			return false;
		}
	}

	/**
	 * Add exchange rates
	 * The eurofxref-daily.xml file is updated daily between 14:15 and 15:00 CET
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getExchangeRates() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$linenumber = 1;
		// Read eurofxref-daily.xml file in memory
		$XMLContent= file("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

		// Process the file
		if ($XMLContent) {
			// Empty table
			$q = "TRUNCATE TABLE `#__csvivirtuemart_currency`;";
			$db->setQuery($q);
			$db->query();

			// Add the Euro
			$q = "INSERT INTO #__csvivirtuemart_currency (currency_code, currency_rate)
				VALUES ('EUR', 1)";
			$db->setQuery($q);
			$db->query();

			$currencyCode = array();
			$rate = array();
			foreach ($XMLContent as $line) {
				if (preg_match("/currency='([[:alpha:]]+)'/",$line,$currencyCode)) {
					if (preg_match("/rate='([[:graph:]]+)'/",$line,$rate)) {
						$csvilog->setLinenumber($linenumber++);
						$q = "INSERT INTO #__csvivirtuemart_currency (currency_code, currency_rate)
							VALUES (".$db->Quote($currencyCode[1]).", ".$rate[1].")";
						$db->setQuery($q);
						if ($db->query()) {
							$rate_name = 'COM_CSVIVIRTUEMART_EXCHANGE_RATE_'.$currencyCode[1].'_ADDED';
							$csvilog->AddStats('added', JText::_($rate_name));
						}
						else $csvilog->AddStats('incorrect', JText::_($rate_name));
					}
				}
			}
		}
		else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_CANNOT_LOAD_EXCHANGERATE_FILE'));

		// Store the log count
		$linenumber--;
		JRequest::setVar('logcount', $linenumber);
	}

	/**
	 * Remove all categories that have no products
	 * Parent categories are only deleted if there are no more children left
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getRemoveEmptyCategories() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$this->getCategoryTreeModule();
		$catpaths = JRequest::getVar('categorypaths');
		arsort($this->_catlevels);
		foreach ($this->_catlevels as $catid => $nrlevels) {
			// Check if there are any products in the category
			$db->setQuery($this->getCatQuery($catid));
			if ($db->loadResult() > 0 && array_key_exists($catid, $catpaths)) {
				foreach ($catpaths[$catid] as $key => $level) {
					unset($catpaths[$level]);
					unset($this->_catlevels[$level]);
				}
				unset($catpaths[$catid]);
				unset($this->_catlevels[$catid]);
			}
			else {
				if (array_key_exists($catid, $catpaths)) {
					foreach ($catpaths[$catid] as $key => $level) {
						$db->setQuery($this->getCatQuery($level));
						if ($db->loadResult() > 0) {
							unset($catpaths[$level]);
							unset($this->_catlevels[$level]);
						}
					}
				}
			}
		}
		$delcats = array_keys($catpaths);
		if (!empty($delcats)) {
			// Remove all categories except the ones we have
			$q = "DELETE FROM #__vm_category
				WHERE category_id IN (".implode(', ', $delcats).")";
			$db->setQuery($q);
			if ($db->query()) $csvilog->AddStats('deleted', JText::_('COM_CSVIVIRTUEMART_MAINTENANCE_CATEGORIES_DELETED'));
			else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_MAINTENANCE_CATEGORIES_NOT_DELETED'));

			// Remove all category parent-child relations except the ones we have
			$q = "DELETE FROM #__vm_category_xref
				WHERE category_child_id IN (".implode(', ', $delcats).")";
			$db->setQuery($q);
			if ($db->query()) $csvilog->AddStats('deleted', JText::_('COM_CSVIVIRTUEMART_MAINTENANCE_CATEGORIES_XREF_DELETED'));
			else $csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_MAINTENANCE_CATEGORIES_XREF_NOT_DELETED'));
		}
		else $csvilog->AddStats('information', JText::_('COM_CSVIVIRTUEMART_NO_CATEGORIES_FOUND'));
	}

	/**
	 * Construct a query to count the number of references to a category
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return 		string	the query to count entries in a category
	 * @since 		3.0
	 */
	private function getCatQuery($catid) {
		return "SELECT COUNT(*)
			FROM #__vm_product_category_xref
			WHERE category_id = ".$catid;

	}

	/**
	 * Install default templates
	 *
	 * @copyright
	 * @author		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getInstallDefaultTemplates() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');

		// Get system limit values
		$max_execution_time = intval(ini_get('max_execution_time'));
		$memory_limit = intval(ini_get('memory_limit'));
		$post_max_size = intval(ini_get('post_max_size'));
		$upload_max_filesize = intval(ini_get('max_execution_time'));

		// Get the file paths
		$product_images = JPath::clean(JPATH_SITE.'/components/com_virtuemart/shop_image/product', '/');
		$category_images = JPath::clean(JPATH_SITE.'/components/com_virtuemart/shop_image/category','/');
		$media = JPath::clean(JPATH_SITE.'/media','/');
		$export_location = JPath::clean(JPATH_SITE,'/');

		$exampletemplates = array();
		$exampletemplates['csvi example google base export xml'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Google Base Export XML', '{\"export_type\":\"productexport\",\"export_fields\":{\"_selected_name\":[\"product_name\",\"product_url\",\"product_desc\",\"product_sku\",\"picture_url\",\"product_price\",\"custom\",\"manufacturer_name\",\"custom\",\"custom\",\"custom\",\"product_width\",\"custom\",\"custom\",\"custom\",\"custom\",\"custom\",\"custom\",\"product_weight\",\"product_length\",\"custom\",\"product_in_stock\",\"custom\",\"custom\",\"attribute\",\"custom\",\"custom_shipping\"],\"_column_header\":[\"title\",\"link\",\"description\",\"g:id\",\"g:image_link\",\"g:price\",\"g:condition\",\"g:brand\",\"g:condition\",\"g:payment_notes\",\"g:expiration_date\",\"g:width\",\"g:payment_accepted\",\"g:payment_accepted\",\"g:payment_accepted\",\"g:payment_accepted\",\"g:payment_accepted\",\"g:payment_accepted\",\"g:weight\",\"g:lenght\",\"g:price_type\",\"g:quantity\",\"g:tax_region\",\"g:tax_percent\",\"g:tech_spec_link\",\"g:pickup\",\"g:shipping\"],\"_default_value\":[\"\",\"http:\\/\\/www.example.com\\/\",\"\",\"\",\"\",\"\",\"new\",\"Not Available\",\"New\",\"30 Days Money Back Guarantee\",\"None\",\"Not Available\",\"Check\",\"Visa\",\"MasterCard\",\"AmericanExpress\",\"Paypal\",\"Money order\",\"Not Available\",\"Not Available\",\"Non Negotiable\",\"Not Available\",\"Florida\",\"6\",\"http:\\/\\/www.example.com\\/technical_specifications.html\",\"FALSE\",\"US:UPS Ground:5.00\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"xml\",\"export_site\":\"google\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"1\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";
		$exampletemplates['csvi example product import'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Product Import', '{\"import_type\":\"productimport\",\"import_fields\":{\"_selected_name\":[\"category_path\",\"product_availability\",\"product_available_date\",\"product_currency\",\"product_desc\",\"product_discount\",\"product_discount_date_end\",\"product_discount_date_start\",\"product_full_image\",\"product_name\",\"product_packaging\",\"product_parent_sku\",\"product_price\",\"product_publish\",\"product_s_desc\",\"product_sku\",\"product_special\",\"product_tax\",\"product_thumb_image\"],\"_default_value\":[\"\",\"\",\"\",\"EUR\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Y\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"loadfrom\":\"fromupload\",\"local_csv_file\":\"\",\"urlfile\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"ftpfile\":\"\",\"auto_detect_delimiters\":\"1\",\"category_separator\":\"\\/\",\"use_column_headers\":\"0\",\"skip_first_line\":\"1\",\"overwrite_existing_data\":\"1\",\"ignore_non_exist\":\"0\",\"skip_default_value\":\"0\",\"show_preview\":\"1\",\"collect_debug_info\":\"0\",\"refresh_xml_headers\":\"0\",\"xml_nodes_map\":\"<item \\/>\"},\"product\":{\"update_based_on\":\"product_sku\",\"unpublish_before_import\":\"0\",\"use_icecat\":\"0\"},\"category\":{\"append_categories\":\"0\"},\"image\":{\"auto_generate_image_name\":\"0\",\"type_generate_image_name\":\"product_sku\",\"auto_generate_image_name_ext\":\"jpg\",\"change_case\":\"none\",\"empty_image\":\"0\",\"keep_original\":\"0\",\"convert_type\":\"none\",\"save_images_on_server\":\"0\",\"full_resize\":\"0\",\"full_width\":\"\",\"full_height\":\"\",\"thumb_check_filetype\":\"0\",\"thumb_create\":\"0\",\"thumb_extension\":\"none\",\"thumb_width\":\"0\",\"thumb_height\":\"0\"},\"path\":{\"file_location_product_images\":\"".$product_images."\",\"file_location_category_images\":\"".$category_images."\",\"file_location_media\":\"".$media."\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\",\"post_max_size\":\"".$post_max_size."\",\"upload_max_filesize\":\"".$upload_max_filesize."\"},\"replacement_import_fields\":{\"_replace_type\":[]}}', 'import');";
		$exampletemplates['csvi example product export'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Product Export', '{\"export_type\":\"productexport\",\"export_fields\":{\"_selected_name\":[\"category_path\",\"product_availability\",\"product_available_date\",\"product_currency\",\"product_desc\",\"product_discount\",\"product_discount_date_end\",\"product_discount_date_start\",\"product_full_image\",\"product_name\",\"product_packaging\",\"product_parent_sku\",\"product_price\",\"product_publish\",\"product_s_desc\",\"product_sku\",\"product_special\",\"product_tax\",\"product_thumb_image\"],\"_column_header\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_default_value\":[\"\",\"\",\"\",\"EUR\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"Y\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"csv\",\"export_site\":\"\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"0\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";
		$exampletemplates['csvi example product files import'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Product Files Import', '{\"import_type\":\"productfilesimport\",\"import_fields\":{\"_selected_name\":[\"product_files_file_description\",\"product_files_file_name\",\"product_files_file_published\",\"product_files_file_title\",\"product_files_file_url\",\"product_sku\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"loadfrom\":\"fromupload\",\"local_csv_file\":\"\",\"urlfile\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"ftpfile\":\"\",\"auto_detect_delimiters\":\"1\",\"category_separator\":\"\\/\",\"use_column_headers\":\"0\",\"skip_first_line\":\"1\",\"overwrite_existing_data\":\"1\",\"ignore_non_exist\":\"0\",\"skip_default_value\":\"0\",\"show_preview\":\"1\",\"collect_debug_info\":\"0\",\"refresh_xml_headers\":\"0\",\"xml_nodes_map\":\"<item \\/>\"},\"product\":{\"update_based_on\":\"product_sku\",\"unpublish_before_import\":\"0\",\"use_icecat\":\"0\"},\"category\":{\"append_categories\":\"0\"},\"image\":{\"auto_generate_image_name\":\"0\",\"type_generate_image_name\":\"product_sku\",\"auto_generate_image_name_ext\":\"jpg\",\"change_case\":\"none\",\"empty_image\":\"0\",\"keep_original\":\"0\",\"convert_type\":\"none\",\"save_images_on_server\":\"0\",\"full_resize\":\"0\",\"full_width\":\"\",\"full_height\":\"\",\"thumb_check_filetype\":\"0\",\"thumb_create\":\"0\",\"thumb_extension\":\"none\",\"thumb_width\":\"0\",\"thumb_height\":\"0\"},\"path\":{\"file_location_product_images\":\"".$product_images."\",\"file_location_category_images\":\"".$category_images."\",\"file_location_media\":\"".$media."\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\",\"post_max_size\":\"".$post_max_size."\",\"upload_max_filesize\":\"".$upload_max_filesize."\"},\"replacement_import_fields\":{\"_replace_type\":[]}}', 'import');";
		$exampletemplates['csvi example product files export'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Product Files Export', '{\"export_type\":\"productfilesexport\",\"export_fields\":{\"_selected_name\":[\"product_files_file_description\",\"product_files_file_name\",\"product_files_file_published\",\"product_files_file_title\",\"product_files_file_url\",\"product_sku\"],\"_column_header\":[\"\",\"\",\"\",\"\",\"\",\"\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"csv\",\"export_site\":\"\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"0\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";
		$exampletemplates['csvi example multiple prices import'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Multiple Prices Import', '{\"import_type\":\"multiplepricesimport\",\"import_fields\":{\"_selected_name\":[\"product_sku\",\"product_currency\",\"price_quantity_start\",\"price_quantity_end\",\"product_price\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"loadfrom\":\"fromupload\",\"local_csv_file\":\"\",\"urlfile\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"ftpfile\":\"\",\"auto_detect_delimiters\":\"1\",\"category_separator\":\"\\/\",\"use_column_headers\":\"0\",\"skip_first_line\":\"1\",\"overwrite_existing_data\":\"1\",\"ignore_non_exist\":\"0\",\"skip_default_value\":\"0\",\"show_preview\":\"1\",\"collect_debug_info\":\"0\",\"refresh_xml_headers\":\"0\",\"xml_nodes_map\":\"<item \\/>\"},\"product\":{\"update_based_on\":\"product_sku\",\"unpublish_before_import\":\"0\",\"use_icecat\":\"0\"},\"category\":{\"append_categories\":\"0\"},\"image\":{\"auto_generate_image_name\":\"0\",\"type_generate_image_name\":\"product_sku\",\"auto_generate_image_name_ext\":\"jpg\",\"change_case\":\"none\",\"empty_image\":\"0\",\"keep_original\":\"0\",\"convert_type\":\"none\",\"save_images_on_server\":\"0\",\"full_resize\":\"0\",\"full_width\":\"\",\"full_height\":\"\",\"thumb_check_filetype\":\"0\",\"thumb_create\":\"0\",\"thumb_extension\":\"none\",\"thumb_width\":\"0\",\"thumb_height\":\"0\"},\"path\":{\"file_location_product_images\":\"".$product_images."\",\"file_location_category_images\":\"".$category_images."\",\"file_location_media\":\"".$media."\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\",\"post_max_size\":\"".$post_max_size."\",\"upload_max_filesize\":\"".$upload_max_filesize."\"},\"replacement_import_fields\":{\"_replace_type\":[]}}', 'import');";
		$exampletemplates['csvi example multiple prices export'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Multiple Prices Export', '{\"export_type\":\"multiplepricesexport\",\"export_fields\":{\"_selected_name\":[\"product_sku\",\"product_currency\",\"price_quantity_start\",\"price_quantity_end\",\"product_price\"],\"_column_header\":[\"\",\"\",\"\",\"\",\"\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"csv\",\"export_site\":\"\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"0\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";
		$exampletemplates['csvi example user info import'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example User Info Import', '{\"import_type\":\"userinfoimport\",\"import_fields\":{\"_selected_name\":[\"user_email\",\"address_type\",\"address_type_name\",\"shopper_group_name\",\"username\",\"first_name\",\"last_name\",\"password\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"loadfrom\":\"fromupload\",\"local_csv_file\":\"\",\"urlfile\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"ftpfile\":\"\",\"auto_detect_delimiters\":\"1\",\"category_separator\":\"\\/\",\"use_column_headers\":\"0\",\"skip_first_line\":\"1\",\"overwrite_existing_data\":\"1\",\"ignore_non_exist\":\"0\",\"skip_default_value\":\"0\",\"show_preview\":\"1\",\"collect_debug_info\":\"0\",\"refresh_xml_headers\":\"0\",\"xml_nodes_map\":\"<item \\/>\"},\"product\":{\"update_based_on\":\"product_sku\",\"unpublish_before_import\":\"0\",\"use_icecat\":\"0\"},\"category\":{\"append_categories\":\"0\"},\"image\":{\"auto_generate_image_name\":\"0\",\"type_generate_image_name\":\"product_sku\",\"auto_generate_image_name_ext\":\"jpg\",\"change_case\":\"none\",\"empty_image\":\"0\",\"keep_original\":\"0\",\"convert_type\":\"none\",\"save_images_on_server\":\"0\",\"full_resize\":\"0\",\"full_width\":\"\",\"full_height\":\"\",\"thumb_check_filetype\":\"0\",\"thumb_create\":\"0\",\"thumb_extension\":\"none\",\"thumb_width\":\"0\",\"thumb_height\":\"0\"},\"path\":{\"file_location_product_images\":\"".$product_images."\",\"file_location_category_images\":\"".$category_images."\",\"file_location_media\":\"".$media."\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\",\"post_max_size\":\"".$post_max_size."\",\"upload_max_filesize\":\"".$upload_max_filesize."\"},\"replacement_import_fields\":{\"_replace_type\":[]}}', 'import');";
		$exampletemplates['csvi example user info export'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example User Info Export', '{\"export_type\":\"userinfoexport\",\"export_fields\":{\"_selected_name\":[\"user_email\",\"address_type\",\"address_type_name\",\"shopper_group_name\",\"username\",\"first_name\",\"last_name\"],\"_column_header\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"csv\",\"export_site\":\"\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"0\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";
		$exampletemplates['csvi example manufacturer details import'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Manufacturer Details Import', '{\"import_type\":\"manufacturerimport\",\"import_fields\":{\"_selected_name\":[\"manufacturer_desc\",\"manufacturer_email\",\"manufacturer_name\",\"manufacturer_category_name\",\"manufacturer_url\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"loadfrom\":\"fromupload\",\"local_csv_file\":\"\",\"urlfile\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"ftpfile\":\"\",\"auto_detect_delimiters\":\"0\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"use_column_headers\":\"0\",\"skip_first_line\":\"1\",\"overwrite_existing_data\":\"1\",\"ignore_non_exist\":\"0\",\"skip_default_value\":\"0\",\"show_preview\":\"1\",\"collect_debug_info\":\"0\",\"refresh_xml_headers\":\"0\",\"xml_nodes_map\":\"<item \\/>\"},\"product\":{\"update_based_on\":\"product_sku\",\"unpublish_before_import\":\"0\",\"use_icecat\":\"0\"},\"category\":{\"append_categories\":\"0\"},\"image\":{\"auto_generate_image_name\":\"0\",\"type_generate_image_name\":\"product_sku\",\"auto_generate_image_name_ext\":\"jpg\",\"change_case\":\"none\",\"empty_image\":\"0\",\"keep_original\":\"0\",\"convert_type\":\"none\",\"save_images_on_server\":\"0\",\"full_resize\":\"0\",\"full_width\":\"\",\"full_height\":\"\",\"thumb_check_filetype\":\"0\",\"thumb_create\":\"0\",\"thumb_extension\":\"none\",\"thumb_width\":\"0\",\"thumb_height\":\"0\"},\"path\":{\"file_location_product_images\":\"".$product_images."\",\"file_location_category_images\":\"".$category_images."\",\"file_location_media\":\"".$media."\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\",\"post_max_size\":\"".$post_max_size."\",\"upload_max_filesize\":\"".$upload_max_filesize."\"},\"replacement_import_fields\":{\"_replace_type\":[]}}', 'import');";
		$exampletemplates['csvi example manufacturer details export'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Manufacturer Details Export', '{\"export_type\":\"manufacturerexport\",\"export_fields\":{\"_selected_name\":[\"manufacturer_desc\",\"manufacturer_email\",\"manufacturer_name\",\"manufacturer_category_name\",\"manufacturer_url\"],\"_column_header\":[\"\",\"\",\"\",\"\",\"\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"csv\",\"export_site\":\"\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"0\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";
		$exampletemplates['csvi example category details import'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Category Details Import', '{\"import_type\":\"categorydetailsimport\",\"import_fields\":{\"_selected_name\":[\"category_path\",\"category_description\",\"category_thumb_image\",\"category_full_image\",\"category_publish\",\"category_browsepage\",\"category_products_per_row\",\"category_flypage\",\"category_list_order\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"loadfrom\":\"fromupload\",\"local_csv_file\":\"\",\"urlfile\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"ftpfile\":\"\",\"auto_detect_delimiters\":\"0\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"use_column_headers\":\"0\",\"skip_first_line\":\"1\",\"overwrite_existing_data\":\"1\",\"ignore_non_exist\":\"0\",\"skip_default_value\":\"0\",\"show_preview\":\"1\",\"collect_debug_info\":\"0\",\"refresh_xml_headers\":\"0\",\"xml_nodes_map\":\"<item \\/>\"},\"product\":{\"update_based_on\":\"product_sku\",\"unpublish_before_import\":\"0\",\"use_icecat\":\"0\"},\"category\":{\"append_categories\":\"0\"},\"image\":{\"auto_generate_image_name\":\"0\",\"type_generate_image_name\":\"product_sku\",\"auto_generate_image_name_ext\":\"jpg\",\"change_case\":\"none\",\"empty_image\":\"0\",\"keep_original\":\"0\",\"convert_type\":\"none\",\"save_images_on_server\":\"0\",\"full_resize\":\"0\",\"full_width\":\"\",\"full_height\":\"\",\"thumb_check_filetype\":\"0\",\"thumb_create\":\"0\",\"thumb_extension\":\"none\",\"thumb_width\":\"0\",\"thumb_height\":\"0\"},\"path\":{\"file_location_product_images\":\"".$product_images."\",\"file_location_category_images\":\"".$category_images."\",\"file_location_media\":\"".$media."\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\",\"post_max_size\":\"".$post_max_size."\",\"upload_max_filesize\":\"".$upload_max_filesize."\"},\"replacement_import_fields\":{\"_replace_type\":[]}}', 'import');";
		$exampletemplates['csvi example category details export'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Category Details Export', '{\"export_type\":\"categorydetailsexport\",\"export_fields\":{\"_selected_name\":[\"category_path\",\"category_description\",\"category_thumb_image\",\"category_full_image\",\"category_publish\",\"category_browsepage\",\"category_products_per_row\",\"category_flypage\",\"category_list_order\"],\"_column_header\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"csv\",\"export_site\":\"\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"0\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";
		$exampletemplates['csvi example order import'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Order Import', '{\"import_type\":\"orderimport\",\"import_fields\":{\"_selected_name\":[\"user_id\",\"order_status_code\",\"order_total\",\"order_subtotal\",\"order_tax\",\"order_currency\",\"order_status\",\"first_name\",\"middle_name\",\"last_name\",\"address_1\",\"zip\",\"country_name\",\"payment_method_name\",\"order_date\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"loadfrom\":\"fromupload\",\"local_csv_file\":\"\",\"urlfile\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"ftpfile\":\"\",\"auto_detect_delimiters\":\"1\",\"category_separator\":\"\\/\",\"use_column_headers\":\"0\",\"skip_first_line\":\"1\",\"overwrite_existing_data\":\"1\",\"ignore_non_exist\":\"0\",\"skip_default_value\":\"0\",\"show_preview\":\"1\",\"collect_debug_info\":\"0\",\"refresh_xml_headers\":\"0\",\"xml_nodes_map\":\"<item \\/>\"},\"product\":{\"update_based_on\":\"product_sku\",\"unpublish_before_import\":\"0\",\"use_icecat\":\"0\"},\"category\":{\"append_categories\":\"0\"},\"image\":{\"auto_generate_image_name\":\"0\",\"type_generate_image_name\":\"product_sku\",\"auto_generate_image_name_ext\":\"jpg\",\"change_case\":\"none\",\"empty_image\":\"0\",\"keep_original\":\"0\",\"convert_type\":\"none\",\"save_images_on_server\":\"0\",\"full_resize\":\"0\",\"full_width\":\"\",\"full_height\":\"\",\"thumb_check_filetype\":\"0\",\"thumb_create\":\"0\",\"thumb_extension\":\"none\",\"thumb_width\":\"0\",\"thumb_height\":\"0\"},\"path\":{\"file_location_product_images\":\"".$product_images."\",\"file_location_category_images\":\"".$category_images."\",\"file_location_media\":\"".$media."\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\",\"post_max_size\":\"".$post_max_size."\",\"upload_max_filesize\":\"".$upload_max_filesize."\"},\"replacement_import_fields\":{\"_replace_type\":[]}}', 'import');";
		$exampletemplates['csvi example order export'] = "INSERT IGNORE INTO `#__csvivirtuemart_template_settings` (`name`, `settings`, `type`) VALUES ('CSVI Example Order Export', '{\"export_type\":\"orderexport\",\"export_fields\":{\"_selected_name\":[\"order_id\",\"full_name\",\"first_name\",\"product_name\",\"product_sku\",\"address_1\",\"country_name\",\"order_status_name\",\"order_item_currency\",\"address_type\",\"cdate\",\"mdate\",\"payment_method_name\",\"order_payment_number\",\"order_payment_expire\",\"order_total\",\"manufacturer_name\"],\"_column_header\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_default_value\":[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"],\"_process_field\":[\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\",\"1\"],\"_combine_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"],\"_sort_field\":[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]},\"general\":{\"exportto\":\"todownload\",\"localpath\":\"\",\"ftphost\":\"\",\"ftpport\":\"\",\"ftpusername\":\"\",\"ftppass\":\"\",\"ftproot\":\"\",\"export_filename\":\"\",\"export_file\":\"csv\",\"export_site\":\"\",\"field_delimiter\":\",\",\"text_enclosure\":\"\\\\\"\",\"category_separator\":\"\\/\",\"include_column_headers\":\"1\",\"signature\":\"0\",\"export_frontend\":\"0\",\"collect_debug_info\":\"0\",\"publish_state\":\"\",\"recordstart\":\"\",\"recordend\":\"\",\"groupby\":\"1\",\"vm_itemid\":\"1\",\"export_date_format\":\"d\\/m\\/Y H:i:s\",\"export_price_format_decimal\":\"2\",\"export_price_format_decsep\":\",\",\"export_price_format_thousep\":\".\",\"add_currency_to_price\":\"0\"},\"order\":{\"ordernostart\":\"\",\"ordernoend\":\"\",\"orderlist\":\"\",\"orderdatestart\":\"\",\"orderdateend\":\"\",\"ordermdatestart\":\"\",\"ordermdateend\":\"\",\"orderstatus\":[\"\"],\"orderpayment\":[\"\"],\"order_address\":\"\",\"ordercurrency\":[\"\"],\"orderpricestart\":\"\",\"orderpriceend\":\"\",\"orderuser\":[\"\"],\"orderproduct\":[\"\"]},\"orderitem\":{\"orderitemsnostart\":\"\",\"orderitemsnoend\":\"\",\"orderitemlist\":\"\",\"orderitemsdatestart\":\"\",\"orderitemsdateend\":\"\",\"orderitemsmdatestart\":\"\",\"orderitemsmdateend\":\"\",\"orderitemstatus\":[\"\"],\"orderitemcurrency\":[\"\"],\"orderitemspricestart\":\"\",\"orderitemspriceend\":\"\",\"orderitemproduct\":[\"\"]},\"product\":{\"exportsef\":\"1\",\"producturl_suffix\":\"\",\"featured\":\"0\",\"use_joomfish\":\"0\",\"productcategories\":[\"\"],\"incl_subcategory\":\"0\",\"productskufilter\":\"\",\"pricequantitystartfrom\":\"\",\"pricequantitystartto\":\"\",\"pricequantityendfrom\":\"\",\"pricequantityendto\":\"\",\"stocklevelstart\":\"\",\"stocklevelend\":\"\",\"targetcurrency\":\"\"},\"userinfo\":{\"userinfo_address\":\"\",\"vendors\":[\"\"],\"permissions\":[\"\"],\"userinfomdatestart\":\"\",\"userinfomdateend\":\"\"},\"layout\":{\"header\":\"\",\"body\":\"\",\"footer\":\"\"},\"email\":{\"export_email_addresses\":\"\",\"export_email_addresses_cc\":\"\",\"export_email_addresses_bcc\":\"\",\"export_email_subject\":\"\",\"export_email_body\":\"\"},\"limit\":{\"use_system_limits\":\"0\",\"max_execution_time\":\"".$max_execution_time."\",\"memory_limit\":\"".$memory_limit."\"},\"replacement_export_fields\":{\"_replace_type\":[]}}', 'export');";

		// List of standard templates
		$standardtemplates = array('csvi example google base export xml',
							'csvi example product import',
							'csvi example product export',
							'csvi example product files import',
							'csvi example product files export',
							'csvi example multiple prices import',
							'csvi example multiple prices export',
							'csvi example user info import',
							'csvi example user info export',
							'csvi example manufacturer details import',
							'csvi example manufacturer details export',
							'csvi example category details import',
							'csvi example category details export',
							'csvi example order import',
							'csvi example order export');

		// Get a list of templates
		$db->setQuery("SELECT LOWER(name) AS name FROM #__csvivirtuemart_template_settings");
		$db->query();
		$installedtemplates = $db->loadResultArray();

		if (!is_array($installedtemplates)) $installedtemplates = array();

		// Check if there are templates not yet
		$installtemplates = array_diff($standardtemplates, $installedtemplates);

		if (count($installtemplates) > 0) {
			$count = 0;
			$linenumber = 1;
			// Install the templates
			foreach ($installtemplates as $key => $name) {
				// Add the template
				if (isset($exampletemplates[$name])) {
					$csvilog->setLinenumber($linenumber++);
					$db->setQuery($exampletemplates[$name]);
					if (!$db->query()) {
						$csvilog->AddStats('incorrect', $db->getErrorMsg());
					}
					else {
						$csvilog->AddStats('added', ucwords($name));
						$count++;
					}
				}
			}
			$csvilog->setLinenumber($linenumber++);
			$csvilog->AddStats('added', JText::sprintf('COM_CSVIVIRTUEMART_EXAMPLE_TEMPLATE_INSTALLED', $count));
		}
		else $csvilog->AddStats('information', JText::_('COM_CSVIVIRTUEMART_NO_EXAMPLE_TEMPLATE_INSTALLED'));

		// Store the log count
		$linenumber--;
		JRequest::setVar('logcount', $linenumber);
	}

	/**
	 * Clean the CSVI VirtueMart cache
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getCleanTemp() {
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$folder = CSVIPATH_TMP;

		if (JFolder::exists($folder)) {
			// Delete all import files left behind in the folder
			JFile::delete(JFolder::files($folder, '.', false, true));

			// Delete all import folders left behind in the folder
			$folders = array();
			$folders = JFolder::folders($folder, '.', true, true, array('debug'));
			if (!empty($folders)) {
				foreach ($folders as $path) {
					JFolder::delete($path);
				}
			}

			// Load the files
			if (JFolder::exists(CSVIPATH_DEBUG)) {
				$files = JFolder::files(CSVIPATH_DEBUG, '.', false, true);
				if ($files) {
					// Remove any debug logs that are still there but not in the database
					$q = "SELECT CONCAT(".$db->Quote(CSVIPATH_DEBUG.'/com_csvivirtuemart.log.').", import_id, '.php') AS filename
						FROM #__csvivirtuemart_logs
						WHERE import_id > 0
						GROUP BY import_id";
					$db->setQuery($q);
					$ids = $db->loadResultArray();
					if (!is_array($ids)) $ids = (array)$ids;

					// Delete all obsolete files
					JFile::delete(array_diff($files, $ids));
				}
			}

			$csvilog->AddStats('deleted', JText::_('COM_CSVIVIRTUEMART_TEMP_CLEANED'));
		}
		else $csvilog->AddStats('information', JText::_('COM_CSVIVIRTUEMART_TEMP_PATH_NOT_FOUND'));
	}

	/**
	 * Export all VirtueMart tables
	 *
	 * @copyright
	 * @author  	RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getBackupVirtueMart() {
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');

		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$filepath = JPATH_ADMINISTRATOR.'/backups';
		$filename = 'virtuemart_'.time().'.sql';
		$file = $filepath.'/'.$filename;
		$sqlstring = '';
		$fp = fopen($file, "w+");
		if ($fp) {
			// Load a list of VirtueMart tables
			$q = "SHOW TABLES LIKE '".$db->_table_prefix."vm\_%'";
			$db->setQuery($q);
			$tables = $db->loadResultArray();
			$linenumber = 1;
			foreach ($tables as $table) {
				$csvilog->setLinenumber($linenumber);
				// Get the create table statement
				$q = "SHOW CREATE TABLE ".$table;
				$db->setQuery($q);
				$tcreate = $db->loadAssocList();
				$sqlstring .= "-- Table structure for table ".$db->nameQuote($table)."\n\n";
				$sqlstring .= $tcreate[0]['Create Table'].";\n\n";

				// Check if there is any data in the table
				$q = "SELECT COUNT(*) FROM ".$db->nameQuote($table);
				$db->setQuery($q);
				$count = $db->loadResult();

				if ($count > 0) {
					$sqlstring .= "-- Data for table ".$db->nameQuote($table)."\n\n";
					// Get the field names
					$q = "SHOW COLUMNS FROM ".$db->nameQuote($table);
					$db->setQuery($q);
					$fields = $db->loadObjectList();
					$sqlstring .= 'INSERT INTO '.$db->nameQuote($table).' (';
					foreach ($fields as $field) {
						$sqlstring .= $db->nameQuote($field->Field).',';
					}

					$sqlstring = substr(trim($sqlstring), 0, -1).") VALUES \n";
					$start = 0;
					while ($count > 0) {
						$q = "SELECT * FROM ".$table." LIMIT ".$start.", 50";
						$db->setQuery($q);
						$records = $db->loadAssocList();

						// Add the values
						foreach ($records as $record) {
							foreach ($record as $rkey => $value) {
								if (!is_numeric($value)) $record[$rkey] = $db->Quote($value);
								else $record[$rkey] = $value;
							}
							$sqlstring .= '('.implode(',', $record)."),\n";
						}
						$start += 50;
						$count -= 50;

						// Fix the end of the query
						if ($count < 1) $sqlstring = substr(trim($sqlstring), 0, -1).";\n";

						// Add a linebreak
						$sqlstring .= "\n\n";

						// Write the data to the file
						fwrite($fp, $sqlstring);

						// Empty the string
						$sqlstring = '';
					}
					// Update the log
					$csvilog->AddStats('added', JText::sprintf('COM_CSVIVIRTUEMART_BACKUP_COMPLETE_FOR', $table));
					$linenumber++;
				}
			}

			// Store the log count
			$linenumber--;
			JRequest::setVar('logcount', $linenumber);

			// Zip up the file
			jimport('joomla.filesystem.archive');
			$zip = JArchive::getAdapter('zip');
			$files = array();
			$files[] = array('name' => $filename, 'time' => filemtime($file), 'data' => JFile::read($file));
			if ($zip->create($filepath.'/'.$filename.'.zip', $files)) {

				// Close the file
				fclose($fp);

				// Remove the SQL file
				JFile::delete($file);

				// Add a download link for the backup
				$csvilog->setFilename(JHTML::link(JURI::root().'administrator/backups/'.$filename.'.zip', JText::_('COM_CSVIVIRTUEMART_BACKUP_DOWNLOAD_LINK')));
			}
			else {
				$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_BACKUP_NO_ZIP_CREATE'));
				$csvilog->setFilename($filepath.'/'.$filename);
			}
		}
		else {
			$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_COULD_NOT_OPEN_FILE', $file));
		}
	}

	/**
	 * This function is repsonsible for returning an array containing category information
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param
	 * @return
	 * @since 		2.3.6
	 */
	private function getCategoryTreeModule() {
		$database = JFactory::getDBO();

		// Get all categories
		$query  = "SELECT category_child_id AS cid, category_parent_id AS pid
			FROM #__vm_category, #__vm_category_xref
			WHERE #__vm_category.category_id=#__vm_category_xref.category_child_id";

		// Execute the query
		$database->setQuery( $query );
		$records = $database->loadObjectList();

		// Check if there are any records
		if (count($records[0]) == 0) {
			$this->_categories = false;
			return false;
		}
		else {
			$this->_categories = array();
			// Group all categories together according to their level
			foreach( $records as $id => $record ) {
				$this->_categories[$record->pid][$record->cid]["category_id"] = $record->pid;
				$this->_categories[$record->pid][$record->cid]["category_child_id"] = $record->cid;
			}
		}
		$this->CategoryPaths();
	}

	/**
	* Create an array of subcategories per category
	*
	* @author RolandD
	* @since 2.3.6
	* @access private
	*/
	private function CategoryPaths() {
		$catpath = array();
		krsort($this->_categories);
		foreach ($this->_categories as $pid => $categories) {
			foreach ($categories as $cid => $category) {
				$catpath[$cid] = $pid;
			}
		}
		foreach ($catpath as $cid => $value) {
			$catlevel = $value;
			$this->_catpaths[$cid][] = $catlevel;
			while ($catlevel > 0) {
				$this->_catpaths[$cid][] = $catpath[$catlevel];
				$catlevel = $catpath[$catlevel];
			}
		}

		foreach ($this->_catpaths as $cid => $paths) {
			$this->_catlevels[$cid] = count($paths);
		}
		asort($this->_catlevels);
		JRequest::setVar('categorypaths', $this->_catpaths);
	}

	/**
	 * Load the ICEcat index file
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return 		bool	true if index file is loaded | false if index file is not loaded
	 * @since 		3.0
	 */
	public function getIcecatIndex() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$settings = JRequest::getVar('settings');
		$username = $settings->getSetting('ice_username', false);
		$password = $settings->getSetting('ice_password', false);
		$loadremote_index = false;
		$loadremote_supplier = false;
		$icecat_options = JRequest::getVar('icecat', array());

		if (in_array('icecat_index', $icecat_options)) $load_index = true;
		else $load_index = false;
		if (in_array('icecat_supplier', $icecat_options)) $load_supplier = true;
		else $load_supplier = false;
		// Should we load the index file in 1 go
		$loadtype = JRequest::getBool('loadtype');
		// What to do next?
		$result = 'full';

		// Check if we have a username and password
		if ($username && $password) {

			// Joomla includes
			jimport('joomla.filesystem.folder');
			jimport('joomla.filesystem.file');
			jimport('joomla.filesystem.archive');

			// Check if the files are stored on the server
			$location = JRequest::getVar('icecatlocation');
			if ($load_index) {
				if (JFile::exists($location.'/icecat_index')) $icecat_index_file = $location.'/icecat_index';
				else if (JFile::exists($location.'/icecat_index.gzip')) $icecat_index_file = $location.'/icecat_index.gzip';
				else if (JFile::exists($location.'/icecat_index.zip')) $icecat_index_file = $location.'/icecat_index.zip';
				else $loadremote_index = true;
			}

			if ($load_supplier) {
				if (JFile::exists($location.'/icecat_supplier')) $icecat_supplier_file = $location.'/icecat_supplier';
				else if (JFile::exists($location.'/icecat_supplier.gzip')) $icecat_supplier_file = $location.'/icecat_supplier.gzip';
				else if (JFile::exists($location.'/icecat_supplier.zip')) $icecat_supplier_file = $location.'/icecat_supplier.zip';
				else $loadremote_supplier = true;
			}

			// Load the remote files if needed
			if ($loadremote_index || $loadremote_supplier) {
				// Context for retrieving files
				if (JRequest::getBool('icecat_gzip')) $gzip = "Accept-Encoding: gzip\r\n";
				else $gzip = '';
				$context = stream_context_create(array(
					'http' => array(
						'header'  => "Authorization: Basic " . base64_encode($username.':'.$password)."\r\n".
									$gzip
					)
				));

				if ($load_index && $loadremote_index) {
					// ICEcat index file
					$icecat_url = $settings->getSetting('ice_index', 'http://data.icecat.biz/export/freexml.int/INT/files.index.csv');

					// Load the index file from the ICEcat server to a local file
					$icecat_index_file = CSVIPATH_TMP.'/icecat_index';
					if (JRequest::getBool('icecat_gzip')) $icecat_index_file .= '.gzip';
					$fp_url = fopen($icecat_url, 'r', false, $context);
					$fp_local = fopen($icecat_index_file, 'w+');
					while($content = fread($fp_url,1024536)){
						fwrite($fp_local, $content);
					}
					fclose($fp_url);
					fclose($fp_local);
				}

				if ($load_supplier && $loadremote_supplier) {
					// Load the manufacturer data
					$icecat_mf = $settings->getSetting('ice_supplier', 'http://data.icecat.biz/export/freexml.int/INT/supplier_mapping.xml');

					// Load the index file from the ICEcat server to a local file
					$icecat_supplier_file = CSVIPATH_TMP.'/icecat_supplier';
					if (JRequest::getBool('icecat_gzip')) $icecat_supplier_file .= '.gzip';
					$fp_url = fopen($icecat_mf, 'r', false, $context);
					$fp_local = fopen($icecat_supplier_file, 'w+');
					while($content = fread($fp_url,1024536)){
						fwrite($fp_local, $content);
					}
					fclose($fp_url);
					fclose($fp_local);
				}
			}

			// Check if we need to unpack the files
			if ($load_index) {
				if (substr($icecat_index_file, -3) == 'zip') {
					if (!$this->_unpack($icecat_index_file, CSVIPATH_TMP)) {
						$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_ICECAT_INDEX_NOT_UNPACKED'));
						return 'cancel';
					}
					else $icecat_index_file = CSVIPATH_TMP.'/icecat_index';
				}
			}
			if ($load_supplier) {
				if (substr($icecat_supplier_file, -3) == 'zip') {
					if (!$this->_unpack($icecat_supplier_file, CSVIPATH_TMP)) {
						$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_ICECAT_SUPPLIER_NOT_UNPACKED'));
						return 'cancel';
					}
					else $icecat_supplier_file = CSVIPATH_TMP.'/icecat_supplier';
				}
			}

			if ($load_index) {
				// Empty the index table
				$q = "TRUNCATE TABLE ".$db->nameQuote('#__csvivirtuemart_icecat_index');
				$db->setQuery($q);
				$db->query();

				// Load the local file into the database
				if (!$loadtype) {
					$q = "LOAD DATA LOCAL INFILE ".$db->Quote($icecat_index_file)."
						INTO TABLE ".$db->nameQuote('#__csvivirtuemart_icecat_index')."
						IGNORE 1 LINES";
					$db->setQuery($q);
					if ($db->query()) $csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ICECAT_INDEX_LOADED'));
					else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_ICECAT_INDEX_NOT_LOADED', $db->getErrorMsg()));
				}
				else {
					// Need to redirect for the batch import
					$result = 'single';
				}
			}

			if ($load_supplier) {
				// Empty the supplier table
				$q = "TRUNCATE TABLE ".$db->nameQuote('#__csvivirtuemart_icecat_suppliers');
				$db->setQuery($q);
				$db->query();

				// Reset the supplier file
				$xmlstr = file_get_contents($icecat_supplier_file);
				$xml = new SimpleXMLElement($xmlstr);
				$supplier_data = array();
				foreach ($xml->SupplierMappings->children() as $key => $mapping) {
					foreach ($mapping->attributes() as $attr_name => $attr_value) {
						switch($attr_name) {
							case 'supplier_id':
								$supplier_id = $attr_value;
								break;
							case 'name':
								$supplier_data[] = '('.$db->Quote($supplier_id).','.$db->Quote($attr_value).')';
						}
					}
					foreach ($mapping->children() as $symbol) {
						$supplier_data[] = '('.$db->Quote($supplier_id).','.$db->Quote($symbol).')';
					}
				}

				$q = "INSERT IGNORE INTO ".$db->nameQuote('#__csvivirtuemart_icecat_suppliers')."
					VALUES ".implode(',', $supplier_data);
				$db->setQuery($q);
				if ($db->query()) $csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ICECAT_SUPPLIERS_LOADED'));
				else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_ICECAT_SUPPLIERS_NOT_LOADED', $db->getErrorMsg()));
			}
		}
		else {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_ICECAT_NO_USER_PASS'));
		}

		// See if we need to store some info
		if ($loadtype) {
			// Session init
			$session = JFactory::getSession();
			$option = JRequest::getVar('option');
			$session->set($option.'.csvilog', serialize($csvilog));
			$session->set($option.'.icecat_index_file', serialize($icecat_index_file));
			$session->set($option.'.icecat_records', serialize(JRequest::getInt('icecat_records')));
			$session->set($option.'.icecat_wait', serialize(JRequest::getInt('icecat_wait')));
		}
		return $result;
	}

	/**
	 * Load the ICEcat index in batches
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.3
	 */
	public function getIcecatSingle() {
		// Session init
		$session = JFactory::getSession();
		$option = JRequest::getVar('option');
		$csvilog = unserialize($session->get($option.'.csvilog'));
		$icecat_index_file = unserialize($session->get($option.'.icecat_index_file'));
		$totalrow = unserialize($session->get($option.'.icecat_rows'));
		$records = unserialize($session->get($option.'.icecat_records', 1000));
		$finished = false;
		$continue = true;

		// Sleep to please the server
		sleep(unserialize($session->get($option.'.icecat_wait', 5)));

		// Load the records line by line
		$db = JFactory::getDBO();

		$q = "INSERT INTO `#__csvivirtuemart_icecat_index` (`path`, `product_id`, `updated`, `quality`, `supplier_id`, `prod_id`, `catid`, `m_prod_id`, `ean_upc`, `on_market`, `country_market`, `model_name`, `product_view`, `high_pic`, `high_pic_size`, `high_pic_width`, `high_pic_height`) VALUES ";
		$lines = '';
		if (($handle = fopen($icecat_index_file, "r")) !== FALSE) {
			// Position pointers
			$row = 0;

			// Position file pointer
			$pointer = unserialize($session->get($option.'.icecat_position'));
			fseek($handle, $pointer);

			// Start processing
			while ($continue) {
				if ($row < $records) {
					$data = fgetcsv($handle, 1024, "\t");
					if ($data) {
						$row++;
						$lines .= '(';
						foreach ($data as $item) {
							$lines .= $db->Quote($item).',';
						}
						$lines = substr($lines, 0, -1);
						$lines .= '),';
					}
					else {
						$finished = true;
						$continue = false;
					}
				}
				else $continue = false;
			}
			// Store the data
			$lines = substr($lines, 0, -1);
			$db->setQuery($q.$lines);
			$db->query();

			// Information for reload
			JRequest::setVar('finished', $finished);
			$sumrows = $totalrow+$row;
			JRequest::setVar('linesprocessed', $sumrows);

			// Store for future use
			if (!$finished) {
				$session->set($option.'.csvilog', serialize($csvilog));
				$session->set($option.'.icecat_rows', serialize($sumrows));
				$session->set($option.'.icecat_position', serialize(ftell($handle)));
			}
			else {
				$csvilog->AddStats('added', JText::_('COM_CSVIVIRTUEMART_ICECAT_INDEX_LOADED'));

				// Store the log results
				JRequest::setVar('csvilog', $csvilog);
				$this->getFinishProcess();

				// Clear the session
				$session->set($option.'.icecat_index_file', serialize('0'));
				$session->set($option.'.icecat_rows', serialize('0'));
				$session->set($option.'.icecat_position', serialize('0'));
				$session->set($option.'.icecat_records', serialize('0'));
				$session->set($option.'.icecat_wait', serialize('0'));
				$session->set($option.'.csvilog', serialize('0'));

				// Set the run ID
				JRequest::setVar('run_id', $csvilog->getId());
			}

			fclose($handle);
		}
	}

	/**
	 * Unpack the ICEcat index files
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		private
	 * @param 		string	$archivename	the full path and name of the file to extract
	 * @param		string	$extractdir		the folder to copy the extracted file to
	 * @return 		bool	true on success | false on failure
	 * @since 		3.0
	 */
	private function _unpack($archivename, $extractdir) {
		$adapter = JArchive::getAdapter('gzip');
		if ($adapter)
		{
			$config = JFactory::getConfig();
			$tmpfname = $config->getValue('config.tmp_path').'/'.uniqid('gzip');
			$gzresult = $adapter->extract($archivename, $tmpfname);
			if (JError::isError($gzresult))
			{
				@unlink($tmpfname);
				return false;
			}

			$path = JPath::clean($extractdir);
			JFolder::create($path);
			$result = JFile::copy($tmpfname,$path.'/'.JFile::stripExt(basename(strtolower($archivename))));
			@unlink($tmpfname);
		}
		return true;
	}

	/**
	 * Backup templates
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getBackupTemplates() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$linenumber = 1;
		// Create the backup file
		$filepath = JPATH_ADMINISTRATOR.'/backups';
		$filename = 'csvivirtuemart_templates_'.date('Ymd', time()).'.csv';
		$file = $filepath.'/'.$filename;

		$fp = fopen($file, "w+");
		if ($fp) {
			$db->setQuery("SELECT ".$db->nameQuote('name').", ".$db->nameQuote('settings').", ".$db->nameQuote('type')." FROM #__csvivirtuemart_template_settings");
			$templates = $db->loadAssocList();
			foreach ($templates as $template) {
				$csvilog->setLinenumber($linenumber++);
				if (fputcsv($fp, $template)) $csvilog->AddStats('information', JText::sprintf('COM_CSVIVIRTUEMART_BACKUP_TEMPLATE', $template['name']));
				else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_BACKUP_NO_TEMPLATE', $template['name']));
			}
			fclose($fp);
			$csvilog->AddStats('information', JText::sprintf('COM_CSVIVIRTUEMART_BACKUP_TEMPLATE_PATH', $file));
		}
		else {
			$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_COULD_NOT_OPEN_FILE', $file));
		}

		// Store the log count
		$linenumber--;
		JRequest::setVar('logcount', $linenumber);
	}

	/**
	 * Restore templates
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.0
	 */
	public function getRestoreTemplates() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$linenumber = 1;
		jimport('joomla.filesystem.file');
		// Load the restore file
		$upload = JRequest::getVar('restore_file', '', 'files');
		if (empty($upload) || $upload['error'] > 0) $upload = JRequest::getVar('file', '', 'files');

		// Check if the file upload has an error
		if (empty($upload)) {
			$csvilog->AddStats('incorrect', JText::_('COM_CSVIVIRTUEMART_NO_UPLOADED_FILE_PROVIDED'));
			return false;
		}
		else if ($upload['error'] == 0) {
			if (is_uploaded_file($upload['tmp_name'])) {
				// Get some basic info
				$folder = CSVIPATH_TMP.'/'.time();
				$upload_parts = pathinfo($upload['name']);

				// Create the temp folder
				if (JFolder::create($folder)) {
					$this->folder = $folder;
					// Move the uploaded file to its temp location
					if (JFile::upload($upload['tmp_name'], $folder.'/'.$upload['name'])) {
						// Read the uploaded file
						$fp = fopen($folder.'/'.$upload['name'], "r");
						if ($fp) {
							while (($data = fgetcsv($fp, 0, ",")) !== FALSE) {
								$csvilog->setLinenumber($linenumber++);
								$db->setQuery("INSERT IGNORE INTO #__csvivirtuemart_template_settings (".$db->nameQuote('name').", ".$db->nameQuote('settings').", ".$db->nameQuote('type').")
											VALUES (".$db->Quote($data[0]).", ".$db->Quote($data[1]).", ".$db->Quote($data[2]).")");
								if ($db->query()) {
									$csvilog->AddStats('added', JText::sprintf('COM_CSVIVIRTUEMART_RESTORE_TEMPLATE', $data[0]));
								}
								else {
									$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_NO_RESTORE_TEMPLATE', $data[0]));
									$csvilog->AddStats('incorrect', $db->getQuery());
								}
							}

							fclose($fp);
						}
					}
				}
				else {
					$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_CANNOT_CREATE_UNPACK_FOLDER', $folder));
					return false;
				}
			}
			// Error warning cannot save uploaded file
			else {
				$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_NO_UPLOADED_FILE_PROVIDED', $upload['tmp_name']));
				return false;
			}
		}

		// Store the log count
		$linenumber--;
		JRequest::setVar('logcount', $linenumber);
	}

	/**
	 * Unpublish products in unpublished categories
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.5
	 */
	public function getUnpublishProductByCategory() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		// Get the IDs to unpublish
		$q = "SELECT #__vm_product.product_id
			FROM #__vm_product
			INNER JOIN #__vm_product_category_xref
			ON #__vm_product.product_id = #__vm_product_category_xref.product_id
			INNER JOIN #__vm_category
			ON #__vm_product_category_xref.category_id = #__vm_category.category_id
			WHERE #__vm_product.product_publish = 'Y'
			AND #__vm_category.category_publish = 'N'";
		$db->setQuery($q);
		$ids = $db->loadResultArray();

		if (!empty($ids)) {
			// Unpublish the IDs
			$q = "UPDATE #__vm_product SET product_publish = 'N' WHERE product_id IN (".implode(',', $ids).")";
			$db->setQuery($q);
			if ($db->query()) {
				$csvilog->AddStats('updated', JText::sprintf('COM_CSVIVIRTUEMART_PRODUCTS_UNPUBLISHED', $db->getAffectedRows()));
			}
			else {
				$csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_PRODUCTS_NOT_UNPUBLISHED', $db->getErrorMsg()));
			}
		}
		else $csvilog->AddStats('information', JText::_('COM_CSVIVIRTUEMART_PRODUCTS_NOT_FOUND'));
	}

	/**
	 * Remove all the CSVI VirtueMart backup tables
	 *
	 * @copyright
	 * @author 		RolandD
	 * @todo
	 * @see
	 * @access 		public
	 * @param
	 * @return
	 * @since 		3.5
	 */
	public function removeCsviTables() {
		$db = JFactory::getDBO();
		$csvilog = JRequest::getVar('csvilog');
		$db->setQuery("SHOW TABLES LIKE ".$db->Quote($db->_table_prefix.'csvivirtuemart_%'));
		$dbtables = $db->loadResultArray();

		if (!empty($dbtables)) {
			$tables = array();
			$tables[] = $db->_table_prefix.'csvivirtuemart_available_fields';
			$tables[] = $db->_table_prefix.'csvivirtuemart_currency';
			$tables[] = $db->_table_prefix.'csvivirtuemart_icecat_index';
			$tables[] = $db->_table_prefix.'csvivirtuemart_icecat_suppliers';
			$tables[] = $db->_table_prefix.'csvivirtuemart_logs';
			$tables[] = $db->_table_prefix.'csvivirtuemart_log_details';
			$tables[] = $db->_table_prefix.'csvivirtuemart_settings';
			$tables[] = $db->_table_prefix.'csvivirtuemart_template_settings';
			$tables[] = $db->_table_prefix.'csvivirtuemart_template_types';
			$tables[] = $db->_table_prefix.'csvivirtuemart_related_products';

			// Iterate through the tables to see wich one we can delete
			foreach ($dbtables as $tkey => $table) {
				if (in_array($table, $tables)) unset($dbtables[$tkey]);
			}

			// Drop the tables
			$q = "DROP TABLE ".implode(',', $dbtables);
			$db->setQuery($q);
			if ($db->query()) $csvilog->AddStats('deleted', JText::_('COM_CSVIVIRTUEMART_CSVITABLES_DELETED'));
			else $csvilog->AddStats('incorrect', JText::sprintf('COM_CSVIVIRTUEMART_CSVITABLES_NOT_DELETED', $db->getErrorMsg()));
		}
	}
}
?>