<?php
ini_set('max_execution_time', 900);//max execution time increased to 15 minutes
global $opencart_version;
$opencart_version = (int)str_replace('.','',VERSION);
require_once(DIR_SYSTEM . 'library/user.php');
class ControllerModuleNicoimport extends Controller
{
	private $group_code = 'group';
	public $db_link = NULL;
	
	function grab_image($url,$saveto){
		//error_log($url . "\n\n", 3, '/home/store/logs/opencart.log');
		$ch = curl_init ($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
		if (!$raw=curl_exec($ch)) {$this->sendChunk('<span style="color:red">failed download ' . $url . '</span>');return false;}
		curl_close ($ch);
		if(file_exists($saveto)){
			unlink($saveto);
		}
		
		if (!file_exists(dirname($saveto))) mkdir(dirname($saveto));
		
		if (!$fp = fopen($saveto,'x')) return false;
		fwrite($fp, $raw);
		fclose($fp);
		//$this->sendChunk($url . ' ok');
		return true;
	}

	function disable_module($module_name)
	{
		global $db;
		if (substr($module_name, 0, 4) == 'nico') 
		{
	//		echo 'DELETE  FROM ' . DB_PREFIX . 'extension WHERE `code` = \'' . $module_name . '\'';
			$query = $db->query('DELETE  FROM ' . DB_PREFIX . 'extension WHERE `code` = \'' . $module_name . '\''); 
		}
		return $query = $db->query('DELETE  FROM ' . DB_PREFIX . 'setting WHERE `' . $this->group_code . '` = \'' . $module_name . '\'');
	}
	
	function disable_module2010($module_name)
	{
		global $db;
		return $query = $db->query('DELETE  FROM ' . DB_PREFIX . 'module WHERE `code` = \'' . $module_name . '\'');
	}

	
	function set_module_layout($module_name, $config)
	{
		global $db;
		//delete old layout configuration
		$query = $db->query('DELETE  FROM ' . DB_PREFIX . 'layout_module WHERE `code` LIKE \'' . $module_name . '.%\''); 
		
		$modules = $config;
		//$modules = unserialize($config);
		$i=0;
		foreach ($modules as $instance) 
		{
			$i++;
			$layout_id = $instance['layout_id'];
			$code = $module_name . '.' . $i;
			$position = $instance['position'];
			$sort_order = isset($instance['sort_order'])?$instance['sort_order']:'0';
			$query = $db->query('INSERT INTO `'. DB_PREFIX . 'layout_module`  (`layout_id`, `code`, `position`, `sort_order`)  VALUES( \'' . $layout_id . '\', \'' . $code . '\', \'' . $position . '\', \'' . $sort_order . '\')');		
		}
	}


	function install_module2010($module_name, $config)
	{
		global $db;
		if (is_array($config))
		foreach ($config as $nr => $module)
		{
			
	//		$this->disable_module($module_name);
			$query = $db->query('SELECT module_id FROM `'. DB_PREFIX . 'module`  WHERE code = \'' . $module_name . '\' AND name =\''. $nr . '\'');
			if ($query->num_rows == 0)
			{
				$query = $db->query('SELECT extension_id FROM `'. DB_PREFIX . 'extension`  WHERE code = \'' . $module_name . '\' AND type =\'module\'');
				if ($query->num_rows == 0)
				{
				$query = $db->query('INSERT INTO `'. DB_PREFIX . 'extension`  (`type`, `code`)  VALUES( \'module\', \'' . $module_name . '\')');
				}				
				
				$module['name'] = $nr;
				$config = serialize($module);
				$query = $db->query('INSERT INTO `'. DB_PREFIX . 'module`  (`name`, `code`, `setting`)  VALUES( \'' . $nr . '\', \'' . $module_name . '\', \'' . $db->escape($config) . '\')');
				$module_id= $db->getLastId();
			
				$layout_id = $module['layout_id'];
				$code = $module_name . '.' . $module_id;
				$position = $module['position'];
				$sort_order = isset($module['sort_order'])?$module['sort_order']:'0';
				$query = $db->query('INSERT INTO `'. DB_PREFIX . 'layout_module`  (`layout_id`, `code`, `position`, `sort_order`)  VALUES( \'' . $layout_id . '\', \'' . $code . '\', \'' . $position . '\', \'' . $sort_order . '\')');		
			}

		} else $this->sendChunk('Config empty for ' . $module_name);
	}

	function install_module($module_name, $config)
	{
		global $db;
		$config = serialize($config);
				
		$this->disable_module($module_name);
		$query = $db->query('SELECT extension_id FROM `'. DB_PREFIX . 'extension`  WHERE `type` = \'module\' AND code = \'' . $module_name . '\'');
		if ($query->num_rows == 0)
		{
			$query = $db->query('INSERT INTO `'. DB_PREFIX . 'extension`  (`type`, `code`)  VALUES(\'module\', \'' . $module_name . '\')');
			$query = $db->query('INSERT INTO `'. DB_PREFIX . 'setting`  (`' . $this->group_code . '`, `key`, `value`, `serialized`)  VALUES( \'' . $module_name . '\', \'' . $module_name . '_status\', \'1\', 0)  ON DUPLICATE KEY UPDATE `value` = \'1\'');
		}
		//echo 'INSERT INTO `'. DB_PREFIX . 'setting`  (`group`, `key`, `value`)  VALUES( \'' . $module_name . '\', \'' . $module_name . '_module\', \'' . $config . '\')  ON DUPLICATE KEY UPDATE `value` = \'' . $config . '\'';
		//if ($module_name == 'nicomegamenu') error_log($config  . ' ----------------- '  . $db->escape($config) . "\n\n", 3, '/home/store/logs/opencart.log'); 
		$query = $db->query('INSERT INTO `'. DB_PREFIX . 'setting`  (`' . $this->group_code . '`, `key`, `value`, `serialized`)  VALUES( \'' . $module_name . '\', \'' . $module_name . '_module\', \'' . $db->escape($config) . '\', 1)  ON DUPLICATE KEY UPDATE `value` = \'' . $db->escape($config)  . '\'');
	}

	function sendChunk($chunk)
	{
		//echo sprintf("%x\r\n", strlen($chunk));
		echo $chunk;
		echo "\r\n";
		echo "</br>";

		@flush();
		//@ob_flush();
	}

	public function index() 
	{
		header('Content-Type: text/html; charset=utf-8');
/*
		// All streams should be uncached
		header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
		header('Pragma: no-cache');
		header('Expires: Fri, 01 Jan 1990 00:00:00 GMT');

		// Of course the official chunked header
		header('Transfer-Encoding: chunked');

		// Again a magic tweak for browsers, otherwise they won't stream...
		header('X-Content-Type-Options: nosniff');

		// Protect our streams from xss attacks
		header('X-XSS-Protection: 1; mode=block');

		header( 'Content-Encoding: none; ' );
*/
		ini_set('zlib.output_compression', 0);
		ini_set('implicit_flush', 1);

		flush();

		ob_implicit_flush(1);


		//make sure import is not stopped if it takes longer than 30/limit sec
		if (!set_time_limit(900))
		{
			$this->sendChunk('Notice: Time limit increase failed');
		}
				
		$user = new User($this->registry);
		if (!$user->hasPermission('modify', 'design/layout')) die('Permission denied, first login with admin user in opencart admin.');		

		global $db, $opencart_version;
		// $db = $registry->get('db', $db);
		// Database
		if (!$db) 
		{
			$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
			//$registry->set('db', $db);
		}
		
		$db_property = false;
		$db_property = function ($db) {
			if (isset($db->db)) return $db->db;
		};

		if (method_exists('Closure', 'bind')) 
		$db_property = @Closure::bind($db_property, null, $db);

		if ($db_property)
		{
			$db_property = $db_property($db);

			if (is_object($db_property) &&  strpos(get_class($db_property), 'MySQL'))
			{
				$db_link = function ($db) {
					return $db->link;
				};

				$db_link = Closure::bind($db_link, null, $db_property);
				$this->db_link = $db_link($db_property);
				if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();
			}
		}

		$key = trim($_GET['purchase_key']);
		$store_path = $_GET['store'];

		$ch = curl_init('http://' . $store_path . '/import.php');

		$data = array('store' => $store_path, 'purchase_key' => $key);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_VERBOSE, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$verbose = fopen('php://temp', 'rw+');
		curl_setopt($ch, CURLOPT_STDERR, $verbose);

		$import = curl_exec($ch);

		if ($import === FALSE) {
			printf("cUrl error (#%d): %s<br>\n", curl_errno($ch),
				   htmlspecialchars(curl_error($ch)));

			rewind($verbose);
			$verboseLog = stream_get_contents($verbose);

			echo "<pre>", htmlspecialchars($verboseLog), "</pre>\n";
			die();
		}

		curl_close($ch);
		
		$this->sendChunk('Opencart ' . $opencart_version);
		
		if ($opencart_version > 2000)
		{
			$this->group_code = 'code';
		}

		//$import = file_get_contents('http://x-shop.nicolette.ro/import.php');
		$data = unserialize($import);
		?>
		<style>
		body {
			font-family: Sans-serif;
			font-size: 12px;
		}
		</style>
		<?php
		if (isset($data['error'])) die($data['error']);
		if (isset($data['message'])) $this->sendChunk($data['message']);
		
		if (isset($_GET['module_configuration']))
		foreach ($data['disable_modules'] as $module_name)  
		{
			if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();
			
			$this->sendChunk('Configuring ' . $module_name);
			if ($opencart_version > 2000 && $module_name != 'nicocontrolpanel')
			{
				$this->disable_module2010($module_name);
			} else
			{
			$this->disable_module($module_name);
			}
		}    

		if ($opencart_version > 1564)
		{
			if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();
			
			$query = $db->query('SELECT layout_id FROM `'. DB_PREFIX . 'layout`  WHERE `layout_id` = \'99999\'');
			if ($query->num_rows == 0)
			{
				$query = $db->query('INSERT INTO `'. DB_PREFIX . 'layout`  (`layout_id`, `name`)  VALUES(\'99999\', \'All pages\')');
			}
		}

		//error_log(print_r($data,1) . "\n\n", 3, '/home/store/logs/opencart.log'); 
		$modules_count = 0;
		if (isset($_GET['module_configuration']))
		foreach ($data['modules'] as $module_name => $config)  
		{
			$this->sendChunk('Installing ' . $module_name);
			//if ($module_name == 'nicomegamenu') error_log($config  . ' ----------------- '  . base64_decode($config) . "\n\n", 3, '/home/store/logs/opencart.log'); 
			$config = base64_decode($config);
			//if ($module_name  == 'nicocustomproducts')  error_log($config, 3, '/home/store/logs/opencart.log');
			if ($opencart_version > 1564)
			{
				$config = preg_replace_callback('@s:(\d+):"(data/[^"]*)@', function($matches) 
				{
					$return =  str_replace(array($matches[1], 'data/'),array($matches[1] + 3, 'catalog/'),$matches[0]);
					return $return;
				}, $config);
			} else
			{
				$config = preg_replace_callback('@s:(\d+):"(catalog/[^"]*)@', function($matches) 
				{
					return str_replace(array($matches[1], 'catalog'),array($matches[1] - 3, 'data/'),$matches[0]);
				}, $config);
			}
			
			//json
			if ($config)
			{
			$config = unserialize($config);
			foreach($config as $key => &$value)
			{
				if ($opencart_version > 1564)
				{
					$value = str_replace('data/','catalog/', $value);
				} else
				{
					$value = str_replace('catalog/','data/', $value);
				}
			}
			
			} else $this->sendChunk('Config empty for ' . $module_name);
			
			$permission_modules[] = 'module/' . $module_name;
			$modules_count++;
			
			if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();
			
			if ($opencart_version > 2000 && $module_name != 'nicocontrolpanel')
			{
				$this->install_module2010($module_name, $config);
			} else
			{
				$this->install_module($module_name, $config);
				if ($opencart_version > 1564 && $module_name != 'nicocontrolpanel')
				{
					$this->set_module_layout($module_name, $config);
				}
			}
		}

		$this->sendChunk('Set modules permission');
		if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();

		$query = $db->query('SELECT permission FROM `'. DB_PREFIX . 'user_group`  WHERE `user_group_id` = 1 LIMIT 1');

		if (isset($query->rows[0][0]) && $query->rows[0][0] !== NULL) $permission = $query->rows[0][0];
		else if (isset($query->rows[0]['permission']) && $query->rows[0]['permission'] !== NULL) $permission = $query->rows[0]['permission'];

		$permission = unserialize($permission);

		if (is_array($permission) && is_array($permission_modules))
		{
			$access_ok = false;
			$modify_ok = false;

			$access = array_unique(array_merge($permission['access'], $permission_modules));
			
			if (is_array($access) && count($access) > $modules_count)
			{
				$permission['access'] = $access;
				$access_ok = true;
			}
			
			$modify = array_unique(array_merge($permission['modify'], $permission_modules));

			if (is_array($modify)  && count($access) > $modules_count)
			{
				$permission['modify'] = $modify;
				$modify_ok = true;
			}
			
			if ($modify_ok && $access_ok)
			{
				if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();
				//$db->ping();
				$query = $db->query('UPDATE `'. DB_PREFIX . 'user_group` SET permission = \''.  $db->escape(serialize($permission))  .'\' WHERE `user_group_id` = 1');
			}
		}

		if (isset($_GET['download_images']))
		foreach($data['images'] as $image)
		{
			$this->sendChunk('Downloading ' . $image);

			if ($opencart_version > 1564)
			{
			$image_path = str_replace('data/', 'catalog/', $image);
			} else
			{
			$image_path = str_replace('catalog/', 'data/', $image);
			}

			
			$this->grab_image('http://' . $_GET['store'] . '/image/' . $image, DIR_IMAGE . $image_path);
		}

		if (isset($_GET['store_configuration']))
		foreach($data['setting'] as $key => $value)
		{
			if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();
			
			if ($opencart_version > 1564)
			{
			$value = str_replace('data/', 'catalog/', $value);
			} else
			{
			$value = str_replace('catalog/', 'data/', $value);
			}
			//$db->ping();
			$query = $db->query('INSERT INTO  ' . DB_PREFIX . 'setting (`' . $this->group_code . '`,`key`,`value`) VALUES (\'config\',\''.$key.'\', \'' . $db->escape($value) . '\') ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)');
			//$query = $db->query('UPDATE `'. DB_PREFIX . 'setting` SET `value` = \'' .  $db->escape($value) . '\' WHERE `key` = \'' . $key . '\'');
		}

		//import images

		if (isset($_GET['product_images']))
		foreach($data['products'] as $id => $product)
		{
			if ($this->db_link && method_exists($this->db_link,'ping')) $this->db_link->ping();
			
			if ($opencart_version > 1564)
			{
			$image_path = str_replace('data/', 'catalog/', $product['image']);
			} else
			{
			$image_path = str_replace('catalog/', 'data/', $product['image']);
			}
			
			$this->sendChunk('Product image ' . $id);
			//$db->ping();
			$query = $db->query("UPDATE `" . DB_PREFIX . "product` SET image='" . $db->escape($image_path) . "' WHERE product_id = $id");
		}
		
		$css_dir = DIR_TEMPLATE . '/'. $this->config->get('config_template') . '/css';
		$js_dir = DIR_TEMPLATE . '/'. $this->config->get('config_template') . '/js';
		
		if (!is_writable($css_dir))
		{
			if (!@chmod($css_dir, 0777)) $this->sendChunk('Notice: css folder write permission failed, css concatenation will not work, to enable js concatenation set write permission (0777) for ' . $js_dir);
		} else
		{
			$this->sendChunk('css folder writable - OK');
		}

		if (!is_writable($js_dir))
		{
			if (!@chmod($js_dir, 0777))	$this->sendChunk('Notice: js folder write permission failed, js concatenation will not work, to enable js concatenation set write permission (0777) for ' . $js_dir);
		} else
		{
			$this->sendChunk('js folder writable - OK');
		}

		
		$this->sendChunk('<strong>Import complete</strong>');

	}
}
