Skip to content

Instantly share code, notes, and snippets.

@tamr
Last active June 14, 2017 22:04
Show Gist options
  • Save tamr/99a1aee73ad5bd062fce30a98aae6a0c to your computer and use it in GitHub Desktop.
Save tamr/99a1aee73ad5bd062fce30a98aae6a0c to your computer and use it in GitHub Desktop.
opencart 1.5 Miinto.com Product feed
<?php
ini_set('display_errors', 0);
ini_set('max_execution_time', 0);
ini_set('memory_limit', -1);
ignore_user_abort(1);
function getProductFilters() {
global $db;
$result = array();
$query = $db->query("SELECT a.product_id, a.filter_id, b.filter_group_id, b.name AS filter_value, c.name AS filter_name
FROM ". DB_PREFIX ."product_filter a
LEFT JOIN ". DB_PREFIX ."filter_description b ON a.filter_id = b.filter_id
LEFT JOIN ". DB_PREFIX ."filter_group_description c ON b.filter_group_id = c.filter_group_id
WHERE b.language_id = 2
AND c.language_id = 2
AND c.name IN ('Kleur', 'Maat')
ORDER BY a.product_id ASC, b.filter_group_id");
foreach ($query->rows as $key => $value) {
$result['product_'. $value['product_id']][$value['filter_name']][] = $value['filter_value'];
}
return $result;
}
function getProductCategories() {
global $db;
$result = array();
$query = $db->query("SELECT category_id, name FROM ". DB_PREFIX ."category_description WHERE language_id = 2");
foreach ($query->rows as $key => $value) {
$result['category_'. $value['category_id']] = $value['name'];
}
return $result;
}
function getProductImage($str) {
$host = $_SERVER['HTTP_HOST'];
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http';
$ext = pathinfo($str, PATHINFO_EXTENSION);
$src = explode('.', $str);
array_pop($src);
$resized_image = $src[0] .'-800x800.'. $ext;
if(file_exists('../image/cache/'. $resized_image)) {
$image_link = $protocol. '://'. $host .'/image/cache/'. $resized_image;
} else {
$image_link = $protocol. '://'. $host .'/image/'. $str;
}
return str_replace(' ', '%20', $image_link);
}
$cache_file = 'miinto.tsv';
$timeout = isset($_GET['debug']) ? 0 : 600;
if (!isset($_GET['debug']) && file_exists($cache_file) && (filemtime($cache_file) > (time() - $timeout))) {
$tsv = file_get_contents($cache_file);
} else {
require_once '../config.php';
require_once '../vqmod/vqmod.php';
VQMod::bootup();
require_once VQMod::modCheck(DIR_SYSTEM .'startup.php');
require_once VQMod::modCheck(DIR_SYSTEM .'library/customer.php');
require_once VQMod::modCheck(DIR_SYSTEM .'library/currency.php');
require_once VQMod::modCheck(DIR_SYSTEM .'library/tax.php');
require_once VQMod::modCheck(DIR_SYSTEM .'library/weight.php');
require_once VQMod::modCheck(DIR_SYSTEM .'library/length.php');
$registry = new Registry();
$loader = new Loader($registry);
$registry->set('load', $loader);
$request = new Request();
$registry->set('request', $request);
$cache = new Cache('file');
$registry->set('cache', $cache);
$config = new Config();
$registry->set('config', $config);
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
$query = $db->query("SELECT * FROM ". DB_PREFIX ."setting WHERE store_id = '0'");
foreach ($query->rows as $setting) {
if (!$setting['serialized']) {
$config->set($setting['key'], $setting['value']);
} else {
$config->set($setting['key'], unserialize($setting['value']));
}
}
$session = new Session();
$registry->set('session', $session);
$languages = array();
$query = $db->query("SELECT * FROM ". DB_PREFIX ."language");
foreach ($query->rows as $result) $languages[$result['code']] = $result;
$config->set('config_language_id', $languages[$config->get('config_language')]['language_id']);
$language = new Language($languages[$config->get('config_language')]['directory']);
$language->load($languages[$config->get('config_language')]['filename']);
$registry->set('language', $language);
$registry->set('customer', new Customer($registry));
$loader->model('catalog/product');
$loader->model('tool/image');
$registry->set('currency', new Currency($registry));
$registry->set('tax', new Tax($registry));
$registry->set('weight', new Weight($registry));
$registry->set('length', new Length($registry));
$model = $registry->get('model_catalog_product');
$resize = $registry->get('model_tool_image');
/**
* Init
*/
$filters = getProductFilters();
$categories = getProductCategories();
$products = $model->getProducts(array('start' => 0, 'limit' => 9000)); //array('nolimit' => true)
// http://developer.miinto.com/?page=feed
// https://support.google.com/merchants/answer/188494?hl=en
$headers = array(
'gtin',
//'id', // optional // product_id
'item_group_id',
'title', // name
'description', //description
'price', // price
'sale_price', // price
'brand', // manufacturer_id || manufacturer
'product_type',
'gender', // optional
'color',
'size',
'c:stock_level:integer', // quantity
'availability', // optional // stock_status
'image_link', // image
'additional_image_link', // optional
);
$products_data = array();
foreach ($products as $item) {
$product_data = array();
$product_data['item_group_id'] = $item['product_id'];
$product_data['title'] = trim($item['name']);
$product_data['brand'] = $item['manufacturer'];
$product_data['gender'] = 'Female';
$product_data['availability'] = $item['quantity'] > 0 ? 'in stock' : 'out of stock';
$product_data['c:stock_level:integer'] = $item['quantity'];
// Description
$description = trim(str_replace(array('&nbsp;', "\n", "\r", "\r\n"), ' ', strip_tags(html_entity_decode($item['description']))));
$product_data['description'] = $description !== '' ? '"'.$description.'"' : '';
// Price
$price = $registry->get('currency')->format($registry->get('tax')->calculate($item['price'], $item['tax_class_id'], $config->get('config_tax')));
if ((float) $item['special']) {
$sale_price = $registry->get('currency')->format($registry->get('tax')->calculate($item['special'], $item['tax_class_id'], $config->get('config_tax')));
} else {
$sale_price = $price;
}
$product_data['price'] = $price != '' ? str_replace(',', '', $price) : '';
$product_data['sale_price'] = $sale_price != '' ? str_replace(',', '', $sale_price) : '';
// Image
if(isset($item['image']) && $item['image'] !== '') {
$product_data['image_link'] = trim(getProductImage($item['image']));
} else {
$product_data['image_link'] = '';
}
// Extra images
$extra_images = $model->getProductImages($item['product_id']);
$additional_image_links = '';
foreach ($extra_images as $extra_image) {
$additional_image_links .= getProductImage($extra_image['image']) .',';
}
$product_data['additional_image_link'] = rtrim($additional_image_links, ',') !== '' ? rtrim($additional_image_links, ',') : '';
// Color
if(isset($filters['product_'. $item['product_id']]['Kleur'])) {
$colors = [];
$colorsArray = $filters['product_'. $item['product_id']]['Kleur'];
foreach ($colorsArray as $ckey => $color) {
$split_colors = explode('/', $color);
foreach($split_colors as $kkv)
$colors[] = trim($kkv);
}
$colors = array_unique($colors);
sort($colors);
$product_data['color'] = !empty($colors) ? rtrim(join('/', $colors), '/') : '';
}
// Categories
$product_category = $model->getCategories($item['product_id']);
$product_categories = '';
foreach ($product_category as $product_key => $product_value) {
$category_name = $categories['category_'.$product_value['category_id']];
if(strtolower(substr($category_name, 0, 7)) === 'landing') continue;
$product_categories .= trim($category_name) .',';
}
$product_data['product_type'] = rtrim($product_categories, ',') !== '' ? rtrim(str_replace(',', '>', $product_categories), '>') : '';
// Variations
foreach ($model->getProductOptions($item['product_id']) as $options) {
foreach ($options['option_value'] as $okey => $ovalue) {
if($ovalue['quantity'] > 0) {
$product_data['gtin'] = '1'. substr(str_pad($ovalue['product_option_value_id'], 7, '0', STR_PAD_LEFT), 0, 7);
//$product_data['id'] = $sku;
$product_data['size'] = $ovalue['name'];
$products_data[] = $product_data;
}
}
}
}
/**
* Debug
*/
if(isset($_GET['debug'])) {
echo '<pre>';
print_r($products_data);
die;
}
/**
* Output
*/
$tsv = implode("\t", $headers) . "\n";
foreach ($products_data as $key => $value) {
$product_array = array_merge(array_flip($headers), $value);
$tsv .= implode("\t", array_values($product_array)) ."\n";
}
file_put_contents($cache_file, $tsv, LOCK_EX);
}
header("Content-type: text/tab-separated-values; charset=utf-8");
header('Content-Disposition: attachment;filename=miinto.tsv');
die($tsv);
<?php
ini_set('display_errors', 0);
ini_set('max_execution_time', 0);
ini_set('memory_limit', -1);
require_once('../admin/config.php');
require_once(DIR_SYSTEM . 'startup.php');
require_once(DIR_DATABASE . 'mysql.php');
$miinto_url = 'https://www.miinto.nl';
$miinto_key = '';
$registry = new Registry();
$obj = new Loader($registry);
$registry->set('load', $obj);
$config = new Config();
$registry->set('config', $config);
$db = new DB('mysqli', DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
$query = $db->query('SELECT * FROM ' . DB_PREFIX . 'setting');
foreach ($query->rows as $setting) {
$config->set($setting['key'], $setting['value']);
}
$registry->set('cache', new Cache());
$query = $db->query("SELECT language_id FROM ". DB_PREFIX ."language WHERE code = '". $config->get('config_language') ."'");
$language_id = $query->row['language_id'];
$config->set('config_language_id', $language_id);
$config->set('config_store_id', 0);
$obj->load->model('sale/order');
$order = $registry->get('model_sale_order');
$obj->load->model('catalog/product');
$model = $registry->get('model_catalog_product');
function request($request, $method = null) {
global $miinto_url, $miinto_key;
$result = [];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $miinto_url. $request);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $miinto_key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
if ($method)
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
$output = curl_exec($ch);
if (curl_error($ch)) {
echo 'error:' . curl_error($ch);
}
if ($output !== false && strpos($output, '{') !== false) {
$result = json_decode($output, true);
}
curl_close($ch);
return !empty($result) ? $result : false;
}
function tree_view($arr){
$result = '<ul>';
if (is_array($arr)){
foreach ($arr as $key=>$val){
if (is_array($val)){
$result .= '<li>' . $key . ' => ' . tree_view($val) . '</li>';
} else {
$result .= '<li>' . $key . ' => ' . $val . '</li>';
}
}
}
$result .= '</ul>';
return $result;
}
function getCountryByName($str = '') {
global $db;
if (!$str) return '150';
$query = $db->query("SELECT country_id FROM ". DB_PREFIX ."country WHERE name = '". $str. "'");
return $query->row['country_id'];
}
function getProductID($id) {
global $db;
$query = $db->query('SELECT * FROM '. DB_PREFIX .'product_option_value WHERE product_option_value_id = '. $id);
return $query->rows[0];
}
function getOptionName($id) {
global $db;
$query = $db->query('SELECT name FROM '. DB_PREFIX .'option_value_description WHERE option_value_id = '. $id);
return $query->row['name'];
}
function myocbov($id) {
global $db;
$query = $db->query('SELECT sku FROM '. DB_PREFIX .'myoc_bov WHERE product_option_value_id = '. $id);
return $query->row['sku'];
}
function checkExists($orderid) {
global $db;
$query = $db->query('SELECT count(1) as cnt FROM miinto WHERE orderid = '. intval($orderid));
return $query->row['cnt'];
}
function logOrder($orderid, $splitid) {
global $db;
$db->query('INSERT INTO miinto (orderid, splitid) VALUES ('. intval($orderid) .', '. intval($splitid) .')');
}
function getTemplate() {
return array(
'order_product' => array(),
'store_id' => '0',
'customer' => '',
'customer_id' => '',
'customer_group_id' => '1',
'firstname' => '',
'lastname' => '',
'email' => '',
'telephone' => '',
'fax' => '',
'payment_address' => '0',
'payment_firstname' => '',
'payment_lastname' => '',
'payment_company' => '',
'payment_company_id' => '',
'payment_tax_id' => '',
'payment_address_1' => '',
'payment_address_2' => '',
'payment_city' => '',
'payment_postcode' => '',
'payment_country_id' => '',
'payment_zone_id' => '0',
'shipping_address' => '0',
'shipping_firstname' => '',
'shipping_lastname' => '',
'shipping_company' => '',
'shipping_address_1' => '',
'shipping_address_2' => '',
'shipping_city' => '',
'shipping_postcode' => '',
'shipping_country_id' => '',
'shipping_zone_id' => '0',
'product' => '',
'product_id' => '',
'quantity' => '1',
'to_name' => '',
'to_email' => '',
'from_name' => '',
'from_email' => '',
'voucher_theme_id' => '8',
'message' => '',
'amount' => '',
'shipping' => '',
'shipping_method' => '',
'shipping_code' => '',
'payment' => '',
'payment_method' => '',
'payment_code' => '',
'coupon' => '',
'voucher' => '',
'reward' => '',
'order_status_id' => '101',
'comment' => '',
'affiliate' => '',
'affiliate_id' => '',
);
}
$getData = request('/api/order/pending');
if (isset($getData['data']) && empty($getData['data']))
die('No pending orders were found.');
foreach ($getData['data'] as $ok => $orderData) {
if (checkExists($orderData['OrderId'])) continue;
$data = getTemplate();
$total = $shipping = 0;
$name = explode(' ', $orderData['BillingAddress']['Name'], 2);
$data['firstname'] = $name[0];
$data['lastname'] = $name[1];
$data['email'] = $orderData['BillingAddress']['Email'];
$data['telephone'] = $orderData['BillingAddress']['Phone'];
$data['payment_firstname'] = $name[0];
$data['payment_lastname'] = $name[1];
$data['payment_address_1'] = $orderData['BillingAddress']['Street'];
$data['payment_postcode'] = $orderData['BillingAddress']['Postcode'];
$data['payment_city'] = $orderData['BillingAddress']['City'];
$data['payment_country_id'] = getCountryByName($orderData['BillingAddress']['Country']);
$name = explode(' ', $orderData['ShippingAddress']['Name'], 2);
$data['shipping_firstname'] = $name[0];
$data['shipping_lastname'] = $name[1];
$data['shipping_address_1'] = $orderData['ShippingAddress']['Street'];
$data['shipping_postcode'] = $orderData['ShippingAddress']['Postcode'];
$data['shipping_city'] = $orderData['ShippingAddress']['City'];
$data['shipping_country_id'] = getCountryByName($orderData['ShippingAddress']['Country']);
foreach ($orderData['Lines'] as $pk => $productData) {
$option_id = intval(substr($productData['Gtin'], 1));
$productInfo = getProductID($option_id);
$product = $model->getProduct($productInfo['product_id']);
foreach ($model->getProductOptions($productInfo['product_id']) as $options) {
if ($option_id != $productInfo['product_option_value_id']) continue;
$productArray = array();
$productArray['order_product_id'] = '';
$productArray['product_id'] = $productInfo['product_id'];
$productArray['name'] = $product['name'];
$productArray['order_option'][0] = array();
$productArray['order_option'][0]['order_option_id'] = 'undefined';
$productArray['order_option'][0]['product_option_id'] = $productInfo['product_option_id'];
$productArray['order_option'][0]['product_option_value_id'] = $productInfo['product_option_value_id'];
$productArray['order_option'][0]['name'] = $options['name'];
$productArray['order_option'][0]['type'] = $options['type'];
$productArray['order_option'][0]['value'] = getOptionName($productInfo['option_value_id']). ' ['. myocbov($option_id) .']';
$productArray['model'] = $product['model'];
$productArray['quantity'] = $productData['Quantity'];
$productArray['price'] = $productData['SalePrice'];
$productArray['total'] = $productData['SalePrice'];
$productArray['tax'] = '';
$productArray['reward'] = '';
$total += floatval($productData['SalePrice']);
$shipping += floatval($orderData['ShippingCost']);
}
array_push($data['order_product'], $productArray);
}
$data['comment'] = '<b>Miinto raw data:</b>'. tree_view($orderData);
$data['order_total'] = array(
array(
'order_total_id' => '',
'code' => 'sub_total',
'title' => 'Subtotaal',
'text' => $total,
'value' => $total,
'sort_order' => '1',
),
array(
'order_total_id' => '',
'code' => 'automatic_shipping',
'title' => 'Miinto shipping',
'text' => $shipping,
'value' => $shipping,
'sort_order' => '4',
),
array(
'order_total_id' => '',
'code' => 'total',
'title' => 'Totaal',
'text' => $total,
'value' => $total,
'sort_order' => '13',
),
);
$order->addOrder($data);
logOrder($orderData['OrderId'], $orderData['SplitId']);
request('/api/order/'.$orderData['SplitId'].'/accept', 'put');
}
$count = count($arr['data']);
if ($count > 0)
echo $count .' orders successfully processed';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment