shop.balmet.com

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

openbay.php (26049B)


      1 <?php
      2 class ModelExtensionOpenBayOpenbay extends Model {
      3 	private $url = 'https://account.openbaypro.com/';
      4 	private $error;
      5 	private $branch_version = 6;
      6 
      7 	public function patch() {
      8 
      9 	}
     10 
     11 	public function updateTest() {
     12 		$this->error = array();
     13 
     14 		$this->openbay->log('Starting update test');
     15 
     16 		if (!function_exists("exception_error_handler")) {
     17 			function exception_error_handler($errno, $errstr, $errfile, $errline ) {
     18 				throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
     19 			}
     20 		}
     21 
     22 		set_error_handler('exception_error_handler');
     23 
     24 		// create a tmp folder
     25 		if (!is_dir(DIR_DOWNLOAD . '/tmp')) {
     26 			try {
     27 				mkdir(DIR_DOWNLOAD . '/tmp');
     28 			} catch(ErrorException $ex) {
     29 				$this->error[] = $ex->getMessage();
     30 			}
     31 		}
     32 
     33 		// create tmp file
     34 		try {
     35 			$tmp_file = fopen(DIR_DOWNLOAD . '/tmp/test_file.php', 'w+');
     36 		} catch(ErrorException $ex) {
     37 			$this->error[] = $ex->getMessage();
     38 		}
     39 
     40 		// open and write over tmp file
     41 		try {
     42 			$output  = '<?php' . "\n";
     43 			$output  .= '$test = \'12345\';' . "\n";
     44 			$output  .= 'echo $test;' . "\n";
     45 
     46 			fwrite($tmp_file, $output);
     47 			fclose($tmp_file);
     48 		} catch(ErrorException $ex) {
     49 			$this->error[] = $ex->getMessage();
     50 		}
     51 
     52 		// try and read the file
     53 
     54 		// remove tmp file
     55 		try {
     56 			unlink(DIR_DOWNLOAD . '/tmp/test_file.php');
     57 		} catch(ErrorException $ex) {
     58 			$this->error[] = $ex->getMessage();
     59 		}
     60 
     61 		// delete tmp folder
     62 		try {
     63 			rmdir(DIR_DOWNLOAD . '/tmp');
     64 		} catch(ErrorException $ex) {
     65 			$this->error[] = $ex->getMessage();
     66 		}
     67 
     68 		// reset to the OC error handler
     69 		restore_error_handler();
     70 
     71 		$this->openbay->log('Finished update test');
     72 
     73 		if (!$this->error) {
     74 			$this->openbay->log('Finished update test - no errors');
     75 			return array('error' => 0, 'response' => '', 'percent_complete' => 20, 'status_message' => $this->language->get('text_check_new'));
     76 		} else {
     77 			$this->openbay->log('Finished update test - errors: ' . print_r($this->error));
     78 			return array('error' => 1, 'response' => $this->error);
     79 		}
     80 	}
     81 
     82 	public function updateCheckVersion($beta = 0) {
     83 		$current_version = $this->config->get('feed_openbaypro_version');
     84 
     85 		$this->openbay->log('Start check version, beta: ' . $beta . ', current: ' . $current_version);
     86 
     87 		$post = array('version' => $this->branch_version, 'beta' => $beta);
     88 
     89 		$data = $this->call('update/version/', $post);
     90 
     91 		if ($this->lasterror == true) {
     92 			$this->openbay->log('Check version error: ' . $this->lastmsg);
     93 
     94 			return array('error' => 1, 'response' => $this->lastmsg . ' (' . VERSION . ')');
     95 		} else {
     96 			if ($data['version'] > $current_version) {
     97 				$this->openbay->log('Check version new available: ' . $data['version']);
     98 				return array('error' => 0, 'response' => $data['version'], 'percent_complete' => 40, 'status_message' => $this->language->get('text_downloading'));
     99 			} else {
    100 				$this->openbay->log('Check version - already latest');
    101 				return array('error' => 1, 'response' => $this->language->get('text_version_ok') . $current_version);
    102 			}
    103 		}
    104 	}
    105 
    106 	public function updateDownload($beta = 0) {
    107 		$this->openbay->log('Downloading');
    108 
    109 		$local_file = DIR_DOWNLOAD . '/openbaypro_update.zip';
    110 		$handle = fopen($local_file, "w+");
    111 
    112 		$post = array('version' => $this->branch_version, 'beta' => $beta);
    113 
    114 		$defaults = array(
    115 			CURLOPT_POST => 1,
    116 			CURLOPT_HEADER => 0,
    117 			CURLOPT_URL => $this->url . 'update/download/',
    118 			CURLOPT_USERAGENT => 'OpenBay Pro update script',
    119 			CURLOPT_FRESH_CONNECT => 1,
    120 			CURLOPT_RETURNTRANSFER => 1,
    121 			CURLOPT_FORBID_REUSE => 1,
    122 			CURLOPT_TIMEOUT => 0,
    123 			CURLOPT_SSL_VERIFYPEER => 0,
    124 			CURLOPT_SSL_VERIFYHOST => 0,
    125 			CURLOPT_POSTFIELDS => http_build_query($post, '', "&"),
    126 			CURLOPT_FILE => $handle
    127 		);
    128 
    129 		$curl = curl_init();
    130 		curl_setopt_array($curl, $defaults);
    131 		curl_exec($curl);
    132 
    133 		$curl_error = curl_error ($curl);
    134 
    135 		$this->openbay->log('Download errors: ' . $curl_error);
    136 
    137 		curl_close($curl);
    138 
    139 		return array('error' => 0, 'response' => $curl_error, 'percent_complete' => 60, 'status_message' => $this->language->get('text_extracting'));
    140 	}
    141 
    142 	public function updateExtract() {
    143 		$this->error = array();
    144 
    145 		$web_root = preg_replace('/system\/$/', '', DIR_SYSTEM);
    146 
    147 		if (!function_exists("exception_error_handler")) {
    148 			function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    149 				throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    150 			}
    151 		}
    152 
    153 		set_error_handler('exception_error_handler');
    154 
    155 		try {
    156 			$zip = new ZipArchive();
    157 
    158 			if ($zip->open(DIR_DOWNLOAD . 'openbaypro_update.zip')) {
    159 				$zip->extractTo($web_root);
    160 				$zip->close();
    161 			} else {
    162 				$this->openbay->log('Unable to extract update files');
    163 
    164 				$this->error[] = $this->language->get('text_fail_patch');
    165 			}
    166 		} catch(ErrorException $ex) {
    167 			$this->openbay->log('Unable to extract update files');
    168 			$this->error[] = $ex->getMessage();
    169 		}
    170 
    171 		// reset to the OC error handler
    172 		restore_error_handler();
    173 
    174 		if (!$this->error) {
    175 			return array('error' => 0, 'response' => '', 'percent_complete' => 80, 'status_message' => $this->language->get('text_remove_files'));
    176 		} else {
    177 			return array('error' => 1, 'response' => $this->error);
    178 		}
    179 	}
    180 
    181 	public function updateRemove($beta = 0) {
    182 		$this->error = array();
    183 
    184 		$web_root = preg_replace('/system\/$/', '', DIR_SYSTEM);
    185 
    186 		if (!function_exists("exception_error_handler")) {
    187 			function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    188 				throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    189 			}
    190 		}
    191 
    192 		$this->openbay->log('Get files to remove, beta: ' . $beta);
    193 
    194 		$post = array('beta' => $beta);
    195 
    196 		$files = $this->call('update/getRemoveList/', $post);
    197 
    198 		$this->openbay->log("Remove Files: " . print_r($files, 1));
    199 
    200 		if (!empty($files['asset']) && is_array($files['asset'])) {
    201 			foreach($files['asset'] as $file) {
    202 				$filename = $web_root . implode('/', $file['locations']['location']) . '/' . $file['name'];
    203 
    204 				if (file_exists($filename)) {
    205 					try {
    206 						unlink($filename);
    207 					} catch(ErrorException $ex) {
    208 						$this->openbay->log('Unable to remove file: ' . $filename . ', ' . $ex->getMessage());
    209 						$this->error[] = $filename;
    210 					}
    211 				}
    212 			}
    213 		}
    214 
    215 		// reset to the OC error handler
    216 		restore_error_handler();
    217 
    218 		if (!$this->error) {
    219 			return array('error' => 0, 'response' => '', 'percent_complete' => 90, 'status_message' => $this->language->get('text_running_patch'));
    220 		} else {
    221 			$response_error = '<p>' . $this->language->get('error_file_delete') . '</p>';
    222 			$response_error .= '<ul>';
    223 
    224 			foreach($this->error as $error_file) {
    225 				$response_error .= '<li>' . $error_file . '</li>';
    226 			}
    227 
    228 			$response_error .= '</ul>';
    229 
    230 			return array('error' => 1, 'response' => $response_error, 'percent_complete' => 90, 'status_message' => $this->language->get('text_running_patch'));
    231 		}
    232 	}
    233 
    234 	public function updateUpdateVersion($beta = 0) {
    235         $this->openbay->log('Updating the version in settings');
    236 
    237 		$post = array('version' => $this->branch_version, 'beta' => $beta);
    238 
    239 		$data = $this->call('update/version/', $post);
    240 
    241 		if ($this->lasterror == true) {
    242 			$this->openbay->log('Update version error: ' . $this->lastmsg);
    243 
    244 			return array('error' => 1, 'response' => $this->lastmsg . ' (' . VERSION . ')');
    245 		} else {
    246             $this->load->model('setting/setting');
    247 
    248 			$settings = $this->model_setting_setting->getSetting('feed_openbaypro');
    249 
    250 			$settings['feed_openbaypro_version'] = $data['version'];
    251 
    252 			$this->model_setting_setting->editSetting('feed_openbaypro', $settings);
    253 
    254 			return array('error' => 0, 'response' => $data['version'], 'percent_complete' => 100, 'status_message' => $this->language->get('text_updated_ok') . $data['version']);
    255 		}
    256 	}
    257 
    258 	public function setUrl($url) {
    259 		$this->url = $url;
    260 	}
    261 
    262 	public function getNotifications() {
    263 		$data = $this->call('update/getNotifications/');
    264 		return $data;
    265 	}
    266 
    267 	public function version() {
    268 		$data = $this->call('update/getStableVersion/');
    269 
    270 		if ($this->lasterror == true) {
    271 			$data = array(
    272 				'error' => true,
    273 				'msg' => $this->lastmsg . ' (' . VERSION . ')',
    274 			);
    275 
    276 			return $data;
    277 		} else {
    278 			return $data;
    279 		}
    280 	}
    281 
    282 	public function faqGet($route) {
    283 		if ($this->faqIsDismissed($route) != true) {
    284 			$data = $this->call('faq/get/', array('route' => $route));
    285 
    286 			return $data;
    287 		} else {
    288 			return false;
    289 		}
    290 	}
    291 
    292 	public function faqIsDismissed($route) {
    293 		$this->faqDbTableCheck();
    294 
    295 		$sql = $this->db->query("SELECT * FROM `" . DB_PREFIX . "openbay_faq` WHERE `route` = '" . $this->db->escape($route) . "'");
    296 
    297 		if ($sql->num_rows > 0) {
    298 			return true;
    299 		} else {
    300 			return false;
    301 		}
    302 	}
    303 
    304 	public function faqDismiss($route) {
    305 		$this->faqDbTableCheck();
    306 		$this->db->query("INSERT INTO `" . DB_PREFIX . "openbay_faq` SET `route` = '" . $this->db->escape($route) . "'");
    307 	}
    308 
    309 	public function faqClear() {
    310 		$this->faqDbTableCheck();
    311 		$this->db->query("TRUNCATE `" . DB_PREFIX . "openbay_faq`");
    312 	}
    313 
    314 	public function faqDbTableCheck() {
    315 		if (!$this->openbay->testDbTable(DB_PREFIX . "openbay_faq")) {
    316 			$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "openbay_faq` (`id` int(11) NOT NULL AUTO_INCREMENT,`route` text NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
    317 		}
    318 	}
    319 
    320 	public function requirementTest() {
    321 		$error = array();
    322 
    323 		// check for mkdir enabled
    324 		if (!function_exists('mkdir')) {
    325 			$error[] = $this->language->get('error_mkdir');
    326 		}
    327 
    328 		if (!function_exists('openssl_encrypt')) {
    329 			$error[] = $this->language->get('error_openssl_encrypt');
    330 		}
    331 
    332 		if (!function_exists('openssl_decrypt')) {
    333 			$error[] = $this->language->get('error_openssl_decrypt');
    334 		}
    335 
    336 		if (!function_exists('fopen')) {
    337 			$error[] = $this->language->get('error_fopen');
    338 		}
    339 
    340 		if (!function_exists('set_time_limit')) {
    341 			$error[] = $this->language->get('error_fopen');
    342 		}
    343 
    344         if (!ini_get('allow_url_fopen')) {
    345             $error[] = $this->language->get('error_url_fopen');
    346         }
    347 
    348         if (!extension_loaded('curl')) {
    349 			$error[] = $this->language->get('error_curl');
    350 		}
    351 
    352 		if (!extension_loaded('zip')) {
    353 			$error[] = $this->language->get('error_zip');
    354 		}
    355 
    356 		if (!function_exists('mb_detect_encoding')) {
    357 			$error[] = $this->language->get('error_mbstring');
    358 		}
    359 
    360 		return $error;
    361 	}
    362 
    363 	private function call($call, array $post = null, array $options = array(), $content_type = 'json') {
    364 		$data = array(
    365 			'language' => $this->config->get('openbay_language'),
    366 			'server' => 1,
    367 			'domain' => HTTP_CATALOG,
    368 			'openbay_version' => (int)$this->config->get('feed_openbaypro_version'),
    369 			'data' => $post,
    370 			'content_type' => $content_type,
    371 			'ocversion' => VERSION
    372 		);
    373 
    374 		$useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
    375 
    376 		$defaults = array(
    377 			CURLOPT_POST => 1,
    378 			CURLOPT_HEADER => 0,
    379 			CURLOPT_URL => $this->url . $call,
    380 			CURLOPT_USERAGENT => $useragent,
    381 			CURLOPT_FRESH_CONNECT => 1,
    382 			CURLOPT_RETURNTRANSFER => 1,
    383 			CURLOPT_FORBID_REUSE => 1,
    384 			CURLOPT_TIMEOUT => 0,
    385 			CURLOPT_SSL_VERIFYPEER => 0,
    386 			CURLOPT_SSL_VERIFYHOST => 0,
    387 			CURLOPT_POSTFIELDS => http_build_query($data, '', "&")
    388 		);
    389 
    390 		$curl = curl_init();
    391 		curl_setopt_array($curl, ($options + $defaults));
    392 		$result = curl_exec($curl);
    393 		curl_close($curl);
    394 
    395 		if ($content_type == 'json') {
    396 			$encoding = mb_detect_encoding($result);
    397 
    398 			/* some json data may have BOM due to php not handling types correctly */
    399 			if ($encoding == 'UTF-8') {
    400 				$result = preg_replace('/[^(\x20-\x7F)]*/', '', $result);
    401 			}
    402 
    403 			$result = json_decode($result, 1);
    404 			$this->lasterror = $result['error'];
    405 			$this->lastmsg = $result['msg'];
    406 
    407 			if (!empty($result['data'])) {
    408 				return $result['data'];
    409 			} else {
    410 				return false;
    411 			}
    412 		} elseif ($content_type == 'xml') {
    413 			$result = simplexml_load_string($result);
    414 			$this->lasterror = $result->error;
    415 			$this->lastmsg = $result->msg;
    416 
    417 			if (!empty($result->data)) {
    418 				return $result->data;
    419 			} else {
    420 				return false;
    421 			}
    422 		}
    423 	}
    424 
    425 	public function getTotalProducts($data = array()) {
    426 		$sql = "SELECT COUNT(DISTINCT p.product_id) AS total FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)";
    427 
    428 		if (!empty($data['filter_category'])) {
    429 			$sql .= " LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id)";
    430 		}
    431 
    432 		if ($data['filter_market_name'] == 'ebay') {
    433 			$sql .= " LEFT JOIN `" . DB_PREFIX . "ebay_listing` `ebay` ON (`p`.`product_id` = `ebay`.`product_id`)";
    434 
    435 			if ($data['filter_market_id'] == 0) {
    436 				$sql .= " LEFT JOIN (SELECT product_id, IF( SUM( `status` ) = 0, 0, 1 ) AS 'listing_status' FROM " . DB_PREFIX . "ebay_listing GROUP BY product_id ) ebay2 ON (p.product_id = ebay2.product_id)";
    437 			}
    438 		}
    439 
    440 		if ($data['filter_market_name'] == 'amazon') {
    441 			if ($data['filter_market_id'] <= 4) {
    442 				$sql .= " LEFT JOIN " . DB_PREFIX . "amazon_product ap ON p.product_id = ap.product_id";
    443 			} else {
    444 				$sql .= " LEFT JOIN " . DB_PREFIX . "amazon_product_link apl ON p.product_id = apl.product_id";
    445 			}
    446 
    447 			$amazon_status = array(
    448 				1 => 'saved',
    449 				2 => 'uploaded',
    450 				3 => 'ok',
    451 				4 => 'error',
    452 				5 => 'amazon_linked',
    453 				6 => 'amazon_not_linked',
    454 			);
    455 		}
    456 
    457 		$sql .= " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
    458 
    459 		if (!empty($data['filter_category'])) {
    460 			if ($data['filter_category'] == 'none') {
    461 				$sql .= " AND p2c.category_id IS NULL";
    462 			} else {
    463 				$sql .= " AND p2c.category_id = '" . (int)$data['filter_category'] . "'";
    464 			}
    465 		}
    466 
    467 		if ($data['filter_market_name'] == 'ebay') {
    468 			if ($data['filter_market_id'] == 0) {
    469 				$sql .= " AND (ebay.ebay_listing_id IS NULL OR ebay2.listing_status = 0)";
    470 			} else {
    471 				$sql .= " AND (ebay.ebay_listing_id IS NOT NULL AND ebay.status = 1)";
    472 			}
    473 		}
    474 
    475 		if ($data['filter_market_name'] == 'amazon') {
    476 			if ($data['filter_market_id'] == 0) {
    477 				$sql .= " AND ap.product_id IS NULL ";
    478 			} elseif ($data['filter_market_id'] == 5) {
    479 				$sql .= " AND apl.id IS NOT NULL";
    480 			} elseif ($data['filter_market_id'] == 6) {
    481 				$sql .= " AND apl.id IS NULL";
    482 			} else {
    483 				$sql .= " AND FIND_IN_SET('" . $this->db->escape($amazon_status[$data['filter_market_id']]) . "', ap.`status`) != 0";
    484 			}
    485 		}
    486 
    487 		if (!empty($data['filter_name'])) {
    488 			$sql .= " AND pd.name LIKE '%" . $this->db->escape($data['filter_name']) . "%'";
    489 		}
    490 
    491 		if (!empty($data['filter_model'])) {
    492 			$sql .= " AND p.model LIKE '%" . $this->db->escape($data['filter_model']) . "%'";
    493 		}
    494 
    495 		if (!empty($data['filter_price'])) {
    496 			$sql .= " AND p.price >= '" . (double)$data['filter_price'] . "'";
    497 		}
    498 
    499 		if (!empty($data['filter_price_to'])) {
    500 			$sql .= " AND p.price <= '" . (double)$data['filter_price_to'] . "'";
    501 		}
    502 
    503 		if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
    504 			$sql .= " AND p.quantity >= '" . $this->db->escape($data['filter_quantity']) . "'";
    505 		}
    506 
    507 		if (isset($data['filter_quantity_to']) && !is_null($data['filter_quantity_to'])) {
    508 			$sql .= " AND p.quantity <= '" . $this->db->escape($data['filter_quantity_to']) . "'";
    509 		}
    510 
    511 		if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
    512 			$sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
    513 		}
    514 
    515 		if (isset($data['filter_sku']) && !is_null($data['filter_sku'])) {
    516 			$sql .= " AND p.sku != ''";
    517 		}
    518 
    519 		if (isset($data['filter_desc']) && !is_null($data['filter_desc'])) {
    520 			$sql .= " AND pd.description != ''";
    521 		}
    522 
    523 		if (isset($data['filter_manufacturer']) && !is_null($data['filter_manufacturer'])) {
    524 			$sql .= " AND p.manufacturer_id = '" . (int)$data['filter_manufacturer'] . "'";
    525 		}
    526 
    527 		$query = $this->db->query($sql);
    528 
    529 		return $query->row['total'];
    530 	}
    531 
    532 	public function getProducts($data = array()) {
    533 		$sql = "SELECT p.*, pd.* FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id)";
    534 
    535 		if (!empty($data['filter_category'])) {
    536 			$sql .= " LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (p.product_id = p2c.product_id)";
    537 		}
    538 
    539 		if ($data['filter_market_name'] == 'ebay') {
    540 			$sql .= " LEFT JOIN `" . DB_PREFIX . "ebay_listing` `ebay` ON (`p`.`product_id` = `ebay`.`product_id`)";
    541 
    542 			if ($data['filter_market_id'] == 0) {
    543 				$sql .= " LEFT JOIN (SELECT product_id, IF( SUM( `status` ) = 0, 0, 1 ) AS 'listing_status' FROM " . DB_PREFIX . "ebay_listing GROUP BY product_id ) ebay2 ON (p.product_id = ebay2.product_id)";
    544 			}
    545 		}
    546 
    547 		if ($data['filter_market_name'] == 'amazon') {
    548 			if ($data['filter_market_id'] <= 4) {
    549 				$sql .= " LEFT JOIN " . DB_PREFIX . "amazon_product ap ON p.product_id = ap.product_id";
    550 			} elseif ($data['filter_market_id'] <= 6) {
    551 				$sql .= " LEFT JOIN " . DB_PREFIX . "amazon_product_link apl ON p.product_id = apl.product_id";
    552 			}
    553 
    554 			$amazon_status = array(
    555 				1 => 'saved',
    556 				2 => 'uploaded',
    557 				3 => 'ok',
    558 				4 => 'error',
    559 			);
    560 		}
    561 
    562 		if ($data['filter_market_name'] == 'amazonus') {
    563 			if ($data['filter_market_id'] <= 4) {
    564 				$sql .= " LEFT JOIN " . DB_PREFIX . "amazonus_product ap ON p.product_id = ap.product_id";
    565 			} elseif ($data['filter_market_id'] <= 6) {
    566 				$sql .= " LEFT JOIN " . DB_PREFIX . "amazonus_product_link apl ON p.product_id = apl.product_id";
    567 			}
    568 
    569 			$amazonus_status = array(
    570 				1 => 'saved',
    571 				2 => 'uploaded',
    572 				3 => 'ok',
    573 				4 => 'error',
    574 			);
    575 		}
    576 
    577 		$sql .= " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
    578 
    579 		if (!empty($data['filter_category'])) {
    580 			if ($data['filter_category'] == 'none') {
    581 				$sql .= " AND p2c.category_id IS NULL";
    582 			} else {
    583 				$sql .= " AND p2c.category_id = '" . (int)$data['filter_category'] . "'";
    584 			}
    585 		}
    586 
    587 		if ($data['filter_market_name'] == 'ebay') {
    588 			if ($data['filter_market_id'] == 0) {
    589 				$sql .= " AND (ebay.ebay_listing_id IS NULL OR ebay2.listing_status = 0)";
    590 			} else {
    591 				$sql .= " AND (ebay.ebay_listing_id IS NOT NULL AND ebay.status = 1)";
    592 			}
    593 		}
    594 
    595 		if ($data['filter_market_name'] == 'amazon') {
    596 			if ($data['filter_market_id'] == 0) {
    597 				$sql .= " AND ap.product_id IS NULL ";
    598 			} elseif ($data['filter_market_id'] == 5) {
    599 				$sql .= " AND apl.id IS NOT NULL";
    600 			} elseif ($data['filter_market_id'] == 6) {
    601 				$sql .= " AND apl.id IS NULL";
    602 			} else {
    603 				$sql .= " AND FIND_IN_SET('" . $this->db->escape($amazon_status[$data['filter_market_id']]) . "', ap.`status`) != 0";
    604 			}
    605 		}
    606 
    607 		if ($data['filter_market_name'] == 'amazonus') {
    608 			if ($data['filter_market_id'] == 0) {
    609 				$sql .= " AND ap.product_id IS NULL ";
    610 			} elseif ($data['filter_market_id'] == 5) {
    611 				$sql .= " AND apl.id IS NOT NULL";
    612 			} elseif ($data['filter_market_id'] == 6) {
    613 				$sql .= " AND apl.id IS NULL";
    614 			} else {
    615 				$sql .= " AND FIND_IN_SET('" . $this->db->escape($amazonus_status[$data['filter_market_id']]) . "', ap.`status`) != 0";
    616 			}
    617 		}
    618 
    619 		if (!empty($data['filter_name'])) {
    620 			$sql .= " AND pd.name LIKE '" . $this->db->escape($data['filter_name']) . "%'";
    621 		}
    622 
    623 		if (!empty($data['filter_model'])) {
    624 			$sql .= " AND p.model LIKE '" . $this->db->escape($data['filter_model']) . "%'";
    625 		}
    626 
    627 		if (!empty($data['filter_price'])) {
    628 			$sql .= " AND p.price >= '" . (double)$data['filter_price'] . "'";
    629 		}
    630 
    631 		if (!empty($data['filter_price_to'])) {
    632 			$sql .= " AND p.price <= '" . (double)$data['filter_price_to'] . "'";
    633 		}
    634 
    635 		if (isset($data['filter_quantity']) && !is_null($data['filter_quantity'])) {
    636 			$sql .= " AND p.quantity >= '" . $this->db->escape($data['filter_quantity']) . "'";
    637 		}
    638 
    639 		if (isset($data['filter_quantity_to']) && !is_null($data['filter_quantity_to'])) {
    640 			$sql .= " AND p.quantity <= '" . $this->db->escape($data['filter_quantity_to']) . "'";
    641 		}
    642 
    643 		if (isset($data['filter_status']) && !is_null($data['filter_status'])) {
    644 			$sql .= " AND p.status = '" . (int)$data['filter_status'] . "'";
    645 		}
    646 
    647 		if (isset($data['filter_sku']) && !is_null($data['filter_sku'])) {
    648 			$sql .= " AND p.sku != ''";
    649 		}
    650 
    651 		if (isset($data['filter_desc']) && !is_null($data['filter_desc'])) {
    652 			$sql .= " AND pd.description != ''";
    653 		}
    654 
    655 		if (isset($data['filter_manufacturer']) && !is_null($data['filter_manufacturer'])) {
    656 			$sql .= " AND p.manufacturer_id = '" . (int)$data['filter_manufacturer'] . "'";
    657 		}
    658 
    659 		$sql .= " GROUP BY p.product_id";
    660 
    661 		$sort_data = array(
    662 			'pd.name',
    663 			'p.model',
    664 			'p.price',
    665 			'p.quantity',
    666 			'p.status',
    667 			'p.sort_order'
    668 		);
    669 
    670 		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
    671 			$sql .= " ORDER BY " . $data['sort'];
    672 		} else {
    673 			$sql .= " ORDER BY pd.name";
    674 		}
    675 
    676 		if (isset($data['order']) && ($data['order'] == 'DESC')) {
    677 			$sql .= " DESC";
    678 		} else {
    679 			$sql .= " ASC";
    680 		}
    681 
    682 		if (isset($data['start']) || isset($data['limit'])) {
    683 			if ($data['start'] < 0) {
    684 				$data['start'] = 0;
    685 			}
    686 
    687 			if ($data['limit'] < 1) {
    688 				$data['limit'] = 20;
    689 			}
    690 
    691 			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
    692 		}
    693 
    694 		$query = $this->db->query($sql);
    695 
    696 		return $query->rows;
    697 	}
    698 
    699 	public function addOrderHistory($order_id, $data, $api_login) {
    700 		$defaults = array(
    701 			CURLOPT_HEADER => false,
    702 			CURLOPT_USERAGENT => $this->request->server['HTTP_USER_AGENT'],
    703 			CURLOPT_SSL_VERIFYPEER => 0,
    704 			CURLOPT_SSL_VERIFYHOST => 0,
    705 			CURLOPT_FORBID_REUSE => true,
    706 			CURLOPT_RETURNTRANSFER => true,
    707 			CURLOPT_URL => HTTPS_CATALOG . 'index.php?route=api/order/history&order_id=' . $order_id . '&token=' . $api_login['token'],
    708 			CURLOPT_POST => true,
    709 			CURLOPT_POSTFIELDS => http_build_query($data, '', "&"),
    710 			CURLOPT_TIMEOUT => 60,
    711 			CURLOPT_COOKIE => "PHPSESSID=" . $api_login['session_id'],
    712 		);
    713 
    714 		// Set SSL if required
    715 		if (substr(HTTPS_CATALOG, 0, 5) == 'https') {
    716 			$defaults[CURLOPT_PORT] = 443;
    717 		}
    718 
    719 		$curl = curl_init();
    720 		curl_setopt_array($curl, $defaults);
    721 		$result = curl_exec($curl);
    722 		curl_close($curl);
    723 
    724 		$result = json_decode($result, 1);
    725 
    726 		return $result;
    727 	}
    728 
    729 	public function apiLogin($key) {
    730 		$defaults = array(
    731 			CURLOPT_HEADER => true,
    732 			CURLINFO_HEADER_OUT => true,
    733 			CURLOPT_USERAGENT => $this->request->server['HTTP_USER_AGENT'],
    734 			CURLOPT_SSL_VERIFYPEER => 0,
    735 			CURLOPT_SSL_VERIFYHOST => 0,
    736 			CURLOPT_RETURNTRANSFER => true,
    737 			CURLOPT_URL => HTTPS_CATALOG . 'index.php?route=api/login',
    738 			CURLOPT_POST => true,
    739 			CURLOPT_POSTFIELDS => http_build_query(array('key' => $key)),
    740 			CURLOPT_TIMEOUT => 60,
    741 		);
    742 
    743 		// Set SSL if required
    744 		if (substr(HTTPS_CATALOG, 0, 5) == 'https') {
    745 			$defaults[CURLOPT_PORT] = 443;
    746 		}
    747 
    748 		$curl = curl_init();
    749 		curl_setopt_array($curl, $defaults);
    750 		$result = curl_exec($curl);
    751 		$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    752 		curl_close($curl);
    753 
    754 		$header = substr($result, 0, $header_size);
    755 		$body = substr($result, $header_size);
    756 
    757 		$json = json_decode($body, true);
    758 
    759 		preg_match_all("/^Set-cookie: (.*?);/ism", $header, $cookies);
    760 		foreach( $cookies[1] as $cookie ){
    761 			$buffer_explode = strpos($cookie, "=");
    762 			$header_cookies[ substr($cookie,0,$buffer_explode) ] = substr($cookie,$buffer_explode+1);
    763 		}
    764 
    765 		if (isset($json['success']) && isset($header_cookies['PHPSESSID'])) {
    766 			$response = [
    767 				'token' => $json['token'],
    768 				'session_id' => $header_cookies['PHPSESSID']
    769 			];
    770 		} else {
    771 			$response['error'] = $json['error'];
    772 		}
    773 
    774 		return $response;
    775 	}
    776 
    777     public function storeImage($filename, $width, $height, $sub_directory = '') {
    778         /**
    779          * This method should be used to save images for the marketplaces where the image will be used in a listing template.
    780          * It will save to a dedicated folder in the /images location and not the /cache folder.
    781          * This is due to people clearing the cache folder - only to realise all remotely references images are now gone.
    782          */
    783 
    784 		if (!is_file(DIR_IMAGE . $filename) || substr(str_replace('\\', '/', realpath(DIR_IMAGE . $filename)), 0, strlen(DIR_IMAGE)) != DIR_IMAGE) {
    785 			return;
    786 		}
    787 
    788 		$extension = pathinfo($filename, PATHINFO_EXTENSION);
    789 
    790 		$image_old = $filename;
    791 
    792 		$new_path = 'openbay_template_images/';
    793 		if ($sub_directory != '') {
    794             $new_path = $new_path . '/' .$sub_directory . '/';
    795         }
    796 
    797 		$image_new = $new_path . utf8_substr($filename, 0, utf8_strrpos($filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
    798 
    799 		if (!is_file(DIR_IMAGE . $image_new) || (filemtime(DIR_IMAGE . $image_old) > filemtime(DIR_IMAGE . $image_new))) {
    800 			list($width_orig, $height_orig, $image_type) = getimagesize(DIR_IMAGE . $image_old);
    801 
    802 			if (!in_array($image_type, array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF))) {
    803 				return DIR_IMAGE . $image_old;
    804 			}
    805 
    806 			$path = '';
    807 
    808 			$directories = explode('/', dirname($image_new));
    809 
    810 			foreach ($directories as $directory) {
    811 				$path = $path . '/' . $directory;
    812 
    813 				if (!is_dir(DIR_IMAGE . $path)) {
    814 					@mkdir(DIR_IMAGE . $path, 0777);
    815 				}
    816 			}
    817 
    818 			if ($width_orig != $width || $height_orig != $height) {
    819 				$image = new Image(DIR_IMAGE . $image_old);
    820 				$image->resize($width, $height);
    821 				$image->save(DIR_IMAGE . $image_new);
    822 			} else {
    823 				copy(DIR_IMAGE . $image_old, DIR_IMAGE . $image_new);
    824 			}
    825 		}
    826 
    827 		if ($this->request->server['HTTPS']) {
    828 			return HTTPS_CATALOG . 'image/' . $image_new;
    829 		} else {
    830 			return HTTP_CATALOG . 'image/' . $image_new;
    831 		}
    832 	}
    833 }