Skip to content

Instantly share code, notes, and snippets.

@jaseclamp
Created April 15, 2013 05:55
Show Gist options
  • Save jaseclamp/5385976 to your computer and use it in GitHub Desktop.
Save jaseclamp/5385976 to your computer and use it in GitHub Desktop.
Migrates data from Pinnacle Cart to Magento. Put this script in your Magento root and edit DB connection details to point to Pinnacle Cart site. This is script 2 of 3.
<?php
//Migrate data from Pinnacle Cart to Magento Part TWO
require_once 'app/Mage.php';
Mage::app(0); // best to leave as default as prods are created in admin and you can apply to stores as needed
include_once('simple_html_dom.php');
include_once('import-filter.php');
//connect to your pinnacle cart database
mysql_connect("host", "name", "pass") or die(mysql_error());
//your pinnacle cart database name
mysql_select_db("db") or die(mysql_error());
//collect product and brand information and create a magento product field array.
//This query could also be used to generate a CSV import file.
//note the below assumes you're not managing stock.
$query = "
SELECT replace(p.`product_id`,',','') as sku,
'1' as store,
'Default' as attribute_set,
'simple' as type,
'' as category,
'' as root_category,
'base' as websites,
'' as color,
'' as cost,
'' as country_of_manufacture,
p.`added` as created_at,
'' as custom_design,
'' as custom_design_from,
'' as custom_design_to,
'' as custom_layout_update,
p.`description` as description,
'1' as enable_googlecheckout,
'' as gallery,
'' as gift_message_available,
'0' as has_options,
concat('/',replace(lower(p.`product_id`),'/','_'),'.jpg') as image,
'' as image_label,
'' as manufacturer,
'' as media_gallery,
p.`meta_description` as meta_description,
p.`meta_keywords` as meta_keyword,
p.`meta_title` as meta_title,
'' as minimal_price,
'' as msrp,
'Use config' as msrp_display_actual_price_type,
'Use config' as msrp_enabled,
p.`title` as name,
'' as news_from_date,
'' as news_to_date,
'Block after Info Column' as options_container,
'' as page_layout,
p.`price2` as price,
'0' as required_options,
p.`overview` as short_description,
concat('/',replace(lower(p.`product_id`),'/','_'),'.jpg') as small_image,
'' as small_image_label,
'' as special_from_date,
p.`price` as special_price,
'2015-12-31 00:00:00' as special_to_date, #note this is an arbitrary date
replace(replace(
p.`is_visible`,'Yes','Enabled'),
'No','Disabled') as status,
'Taxable Goods' as tax_class_id,
'' as thumbnail,
'' as thumbnail_label,
now() as updated_at,
lower(
concat(
replace(replace(replace(replace(replace(replace(replace(
p.`title`,' ','-'),
'(',''),
')',''),
'/',''),
',',''),
'&',''),
'--','-'),
'-' ,p.`pid` )) as url_key, #note that you'll have to strip the '-cid' from inline links later
lower(
concat(
replace(replace(replace(replace(replace(replace(replace(
p.`title`,' ','-'),
'(',''),
')',''),
'/',''),
',',''),
'&',''),
'--','-'),
'-' ,p.`pid`, '.html' )) as url_path,
'Catalog, Search' as visibility,
p.`weight` as weight,
'0.0000' as qty, #we're adjusting this later from our ERP system
'0.0000' as min_qty,
'1' as use_config_min_qty,
'0' as is_qty_decimal,
'0' as backorders,
'1' as use_config_backorders,
'1.0000' as min_sale_qty,
'1' as use_config_min_sale_qty,
'0.0000' as max_sale_qty,
'1' as use_config_max_sale_qty,
'1' as is_in_stock,
'' as notify_stock_qty,
'1' as use_config_notify_stock_qty,
'0' as manage_stock,
'1' as use_config_manage_stock,
'1' as stock_status_changed_auto,
'1' as use_config_qty_increments,
'0,0000' as qty_increments,
'1' as use_config_enable_qty_inc,
'0' as enable_qty_increments,
'0' as is_decimal_divided,
'' as links_related_sku,
'' as links_related_position,
'' as links_crosssell_sku,
'' as links_crosssell_position,
'' as links_upsell_sku,
'' as links_upsell_position,
'' as associated_sku,
'' as associated_default_qty,
'' as associated_position,
'' as tier_price_website,
'' as tier_price_customer_group,
'' as tier_price_qty,
'' as tier_price_price,
'' as group_price_website,
'' as group_price_customer_group,
'' as group_price_price,
'' as media_attribute_id,
'' as media_image,
'' as media_lable,
'' as media_position,
'' as media_is_disabled,
m.`manufacturer_name` as manufacturer,
p.`pid` as id #note this is not a magento field and can be removed for csv
FROM `products` p
left join `manufacturers` m on m.`manufacturer_id` = p.`manufacturer_id`
#WHERE p.`is_active` = 'Yes'
#WHERE p.`pid` = '111'
order by p.`pid` ASC";
//uncomment the above to leave out disabled products
$result = mysql_query( $query ) or die(mysql_error());
//this function is from pinnacle . it makes a url key in case we need it
function getProductUrl($title, $pid, $parent="0"){
$_title = "";
for($i = 0; $i<strlen($title); $i++){
$c = $title[$i];
if(ereg("[0-9a-zA-Z]", $title[$i])){
$_title = $_title.$c;
}
else{
$_title = $_title."_";
}
$_title = str_replace("__", "_", $_title);
}
if(strlen($_title) > 0){
$_title = $_title[0] == "_" ? substr($_title, 1, strlen($_title) - 1) : $_title;
$_title = $_title[strlen($_title) - 1] == "_" ? substr($_title, 0, strlen($_title) - 1) : $_title;
}
else{
$_title = "product";
}
return $settings["GlobalHttpUrl"]."/products/".$_title."-".$pid."-".$parent.".html";
}
function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
function addAttributeValue($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
if(!attributeValueExists($arg_attribute, $arg_value))
{
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
}
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return attributeValueExists($arg_attribute, $arg_value);
}
function getAttributeValue($arg_attribute, $arg_value)
{
$id = attributeValueExists($arg_attribute, $arg_value); //ask magento if the color 'blue' is already an attribute, if it does, return its attribute_id
if($id) //if the color value 'blue' does exist in magento already simply set
{
return $id;
}
else //the color value 'blue' doesn't exist in magento, so add it, then set it
{
return addAttributeValue($arg_attribute, $arg_value);
}
}
function checkImage($image) {
//checks if the file is a browser compatible image
$mimes = array('image/gif','image/jpeg','image/pjpeg','image/png');
//get mime type
$mime = getimagesize($image);
$mime = $mime['mime'];
$extensions = array('jpg','png','gif','jpeg');
$extension = strtolower( pathinfo( $image, PATHINFO_EXTENSION ) );
if ( in_array( $extension , $extensions ) AND in_array( $mime, $mimes ) ) return TRUE;
else return FALSE;
}
echo "<pre>";
while ($prod = mysql_fetch_assoc($result)) {
echo "Working on: ".$prod['sku']."<Br>\n";
//has it already been created?
$product = Mage::getModel('catalog/product')->loadByAttribute( 'sku', $prod['sku'] );
//lets make it new
if (!$product) { $product = new Mage_Catalog_Model_Product(); $product->setSku($prod['sku']); }
$product->setUrlKey($prod['url_key']);
$product->setUrlPath($prod['url_path']);
$product->setMetaKeyword($prod['meta_keyword']);
$product->setMetaDescription($prod['meta_description']);
//the getAttributeValue will either return the brand's id or if the brand doesn't exist, it will create it and return the id
if ($prod['manufacturer']) $product->setManufacturer( getAttributeValue('Manufacturer', $prod['manufacturer'] ) );
$product->setAttributeSetId(4); //4 is Default.. maybe we'll update these later
$product->setTypeId('simple');
//append attributes to product name if it's a part
$product->setName( $prod['name'] );
//lets get the categories that this produc sit's in...
//this assumes you've already imported categories if not
//RUN THE CATEGORIES SCRIPT FIRST!!!!!
$result2 = mysql_query("Select c.`key_name` from `products_categories` p left join `catalog` c on c.`cid` = p.`cid`
where p.`pid` = ".$prod['id'] ) or die(mysql_error());
while ($aloc = mysql_fetch_assoc($result2)) {
$catname = strtolower( str_replace("_","-",$aloc['key_name'] ) );
$catname = str_replace("&","",$catname);
$catname = str_replace(" ","-",$catname);
$catname = str_replace("--","-",$catname);
$catname = str_replace("--","-",$catname);
$catname = trim($catname,"- ");
$category = Mage::getModel('catalog/category')->loadByAttribute( 'url_key', $catname );
if ($category){
$categories[]=$category->getId();
}else{
echo "Category ".$catname." not found<Br>";
}
}
$product->setCategoryIds($categories);
$product->setWebsiteIDs(array(1,2)); # Website id, my is 1 (default frontend)
//we need to do a lot of cleaning of the description before we set it...
//we're going to adjust internal product links
//we're going to handle inline images
$html = str_get_html( $prod['description'] );
$query = '';
if (method_exists($html,"find")) foreach( $html->find('a') as $link ) {
if (strpos($link->href,"/products/")!==FALSE) {
$thelink = pathinfo($link->href);
if ($thelink['extension']!='pdf') {
//strip all but the last bit
$thelink = $thelink['filename'].$thelink['extension'];
$thelink = strtolower($thelink);
//strip off category id if exists
$thelink = preg_replace('/(-[0-9]+)-[0-9]+/','\1',$thelink);
//convert underscores to dashes
$thelink = str_replace('_','-',$thelink);
$link->href = $thelink;
}
}
}
//now lets fix up inline images
//move all your images to media/wysiwyg!!!!!
if (method_exists($html,"find")) foreach( $html->find('img') as $link ) {
$thelink = pathinfo($link->src);
$thelink = $thelink["filename"].".".$thelink["extension"];
if (file_exists('/home/madison/public_html/catalogue/media/wysiwyg/'.str_replace('%20',' ',$thelink) ))
{
$thelink = '{{media url="wysiwyg/'.$thelink.'"}}';
$link->src = $thelink;
}
}
if (method_exists($html,"find")) {
$html->load($html->save());
$thedescription = $html->save();
} else {
$thedescription = $prod['description'];
}
//set the description back with fixes
//filter text makes sure TM symbols and the like are set to their equivalent html entities
$product->setDescription( filterText( $thedescription ) );
$product->setShortDescription( filterText( $prod['short_description'] ) );
$product->setPrice($prod['price']);
$product->setSpecialPrice($prod['special_price']);
$product->setWeight($prod['weight']);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
if ($prod['status'] == 'Enabled') $product->setStatus(1);
else $product->setStatus(2);
$product->setTaxClassId(2); //taxable goods
//new lets do the pictures.
//you have to move all your pinnacle images into /media/import!!!!!!!!!
$image = dirname(__FILE__)."/media/import".$prod['image'];
//echo $image; die;
$product->setMediaGallery(array('images'=>array (), 'values'=>array ()));
if (file_exists($image)) if ( checkImage($image) ) {
$product->setStoreId(0); //unless you set this you can't set the default views below
$product->addImageToMediaGallery( $image, array('image','thumbnail','small_image'), false, false);
}else{
echo $image." does not exist<br>";
}
//import extra images...
unset($result2);
$result2 = mysql_query("
SELECT i.iid, i.pid, i.width, i.height, p.product_id, i.type
FROM `products_images` i
LEFT JOIN products p ON p.pid = i.pid
where p.`pid` = ".$prod['id']) or die(mysql_error());
if (mysql_num_rows($result2)) while($images = mysql_fetch_assoc( $result2 ) )
{
$image = dirname(__FILE__)."/media/import/secondary/".$images['iid'].".".$images['type'];
if (file_exists($image)) if ( checkImage($image) ) {
$product->addImageToMediaGallery( $image, '' ,false, false);
}else{
echo $image." does not exist<br>";
}
}
//now lets set custom options if they exist...
unset($result2);
$result2 = mysql_query("
SELECT *
FROM `products_attributes`
WHERE is_active = \"Yes\" AND `pid` = '".$prod['id'] ."';") or die(mysql_error());
if (mysql_num_rows($result2)) while($opts = mysql_fetch_assoc( $result2 ) ) {
$options[] = array(
'title' => $opts['caption'],
'type' => 'drop_down',
'is_require' => 0,
'sort_order' => 0,
'is_delete' => 0,
'previous_group' => '',
'previous_type' => '',
'values' => array()
);
$values = explode("\n",$opts['options']);
foreach ($values as $value) {
$count++;
$title = preg_replace('/\([^\)]*\)/','',$value);
$res = preg_match('/\([^0-9]?(?<price>[0-9]+)[^)]*?\)/',$value,$matches);
if ($res) $price = $matches['price'];
else $price = 0;
$price_type = ((strpos($value,'%')!==FALSE)?'percent':'fixed');
$options[count($options) - 1]['values'][] = array(
'title' => $title,
'price' => number_format($price,4,'.',''),
'price_type' => $price_type,
'sku' => '',
'is_delete' => 0,
'option_type_id' => - 1 ,
'sort_order' => $count
);
}
if(!$product->getOptionsReadonly()) {
$product->hasOptions(1);
$product->setCanSaveCustomOptions(true);
$product->setProductOptions($options);
}
}
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 0
));
try {
if (!$product->getId()) $product->save();
else $product->getResource()->save($product);
echo "Created: ".$prod['sku']."<br>\n";
}
catch (Exception $ex) {
print_r($ex);
die;
}
//we need to set stock using the stock model or else these products will not be compatible with mass update attributes in the admin
if (!($stockItem = $product->getStockItem())) {
$stockItem = Mage::getModel('cataloginventory/stock_item');
$stockItem->assignProduct($product)
->setData('stock_id', 1)
->setData('store_id', 1);
}
//we're setting to zero now as we'll update this later.
$stock['qty'] = 0;
$stock['is_in_stock'] = 1;
$stock['use_config_manage_stock'] = 1;
foreach($stock as $field => $value) {
$stockItem->setData($field, $value?$value:0);
}
$stockItem->save();
unset($product,$stockItem,$stock,$resource,$writeConnection,$options,$title,$price_type,$count,$res,$result2,$image,$html,$link,$thelink,$filePath,$data,$catname
,$category,$categories,$fileconfig,$thepath,$query,$thedescription,$params);
}
?>
@PardeepGrover
Copy link

Hi,

thats very usefull code and saved my lot of time.I want to migrate orders from pinnacle cart to magento.

is there any script that can help me for migration of pinnacle orders to magento.
Any help will be appreciated..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment