public function saveAnimalAction()
 {
     $request = $this->getRequest()->getPost();
     $leiloeiro = Mage::getModel('leilao/leiloeiro')->getCurrentLeiloeiroSession();
     $leiloeiro_product = Mage::getModel('leilao/product');
     $product = new Mage_Catalog_Model_Product();
     $product->setAttributeSetId(4);
     // #4 is for default
     $product->setTypeId('simple');
     $product->setName($request['name']);
     $product->setDescription($request['description']);
     $product->setShortDescription('Short description here');
     $product->setSku(time());
     $product->setWeight(1.0);
     $product->setStatus(1);
     $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
     //4
     $product->setPrice($request['price']);
     // # Set some price
     $product->setTaxClassId(0);
     // # default tax class
     $product->setStockData(array('is_in_stock' => 1, 'qty' => 1));
     //$product->setCategoryIds(array(27)); // # some cat id's,
     $product->setWebsiteIDs(array(1));
     // # Website id, 1 is default
     //Default Magento attribute
     $product->setCreatedAt(strtotime('now'));
     //print_r($product);
     try {
         $product->save();
         $leiloeiro_product->setData('id_leiloeiro', $leiloeiro->getData('entity_id'));
         $leiloeiro_product->setData('id_product', $product->getId());
         $leiloeiro_product->save();
         echo "Product Created";
     } catch (Exception $ex) {
         //Handle the error
         echo "Product Creation Failed";
     }
 }
 public function CreateGeneralProducts()
 {
     try {
         $parent_category = Mage::getStoreConfig('oscommerceimportconf/mageconfiguration/conf_category', Mage::app()->getStore());
         $storeId = Mage::getStoreConfig('oscommerceimportconf/mageconfiguration/conf_website', Mage::app()->getStore());
         $AttributeSetId = Mage::getStoreConfig('oscommerceimportconf/mageconfiguration/conf_attribute', Mage::app()->getStore());
         /////////////////////////////////////////////////////////////////////////////////////
         // Create Custom Product for Import Shipping
         /////////////////////////////////////////////////////////////////////////////////////
         $pro_Model = 'osc-shipping';
         $pro_Name = 'Shipping';
         $oProduct = Mage::getModel("catalog/product")->getCollection()->setStoreId($storeId)->addAttributeToSelect("sku")->addFieldToFilter("sku", array('eq' => $pro_Model))->getFirstItem();
         if (sizeof($oProduct->getData()) == 0) {
             $product = new Mage_Catalog_Model_Product();
             // Build the product
             $product->setSku($pro_Model);
             $product->setAttributeSetId($AttributeSetId);
             $product->setTypeId('simple');
             $product->setName($pro_Name);
             $product->setCategoryIds($parent_category);
             $product->setWebsiteIDs(array($storeId));
             $product->setDescription('-');
             $product->setShortDescription('-');
             $product->setPrice(0);
             $product->setWeight(0);
             $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
             $product->setStatus(1);
             $product->setTaxClassId(0);
             # My default tax class
             $product->setStockData(array('is_in_stock' => 1, 'qty' => 10000));
             $product->setCreatedAt(strtotime('now'));
             $product->save();
         }
         /////////////////////////////////////////////////////////////////////////////////////
         // Create Custom Product for Import Discount
         /////////////////////////////////////////////////////////////////////////////////////
         $pro_Model = 'osc-discount';
         $pro_Name = 'Discount';
         $oProduct = Mage::getModel("catalog/product")->getCollection()->setStoreId($storeId)->addAttributeToSelect("sku")->addFieldToFilter("sku", array('eq' => $pro_Model))->getFirstItem();
         if (sizeof($oProduct->getData()) == 0) {
             $product = new Mage_Catalog_Model_Product();
             // Build the product
             $product->setSku($pro_Model);
             $product->setAttributeSetId($AttributeSetId);
             $product->setTypeId('simple');
             $product->setName($pro_Name);
             $product->setCategoryIds($parent_category);
             $product->setWebsiteIDs(array($storeId));
             $product->setDescription('-');
             $product->setShortDescription('-');
             $product->setPrice(0);
             $product->setWeight(0);
             $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
             $product->setStatus(1);
             $product->setTaxClassId(0);
             # My default tax class
             $product->setStockData(array('is_in_stock' => 1, 'qty' => 10000));
             $product->setCreatedAt(strtotime('now'));
             $product->save();
         }
         /////////////////////////////////////////////////////////////////////////////////////
         // Create Custom Product for Import Taxes
         /////////////////////////////////////////////////////////////////////////////////////
         $pro_Model = 'osc-tax';
         $pro_Name = 'Tax';
         $oProduct = Mage::getModel("catalog/product")->getCollection()->setStoreId($storeId)->addAttributeToSelect("sku")->addFieldToFilter("sku", array('eq' => $pro_Model))->getFirstItem();
         if (sizeof($oProduct->getData()) == 0) {
             $product = new Mage_Catalog_Model_Product();
             // Build the product
             $product->setSku($pro_Model);
             $product->setAttributeSetId($AttributeSetId);
             $product->setTypeId('simple');
             $product->setName($pro_Name);
             $product->setCategoryIds($parent_category);
             $product->setWebsiteIDs(array($storeId));
             $product->setDescription('-');
             $product->setShortDescription('-');
             $product->setPrice(0);
             $product->setWeight(0);
             $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
             $product->setStatus(1);
             $product->setTaxClassId(0);
             # My default tax class
             $product->setStockData(array('is_in_stock' => 1, 'qty' => 10000));
             $product->setCreatedAt(strtotime('now'));
             $product->save();
         }
         /////////////////////////////////////////////////////////////////////////////////////
         // Create Custom Product for Import Other
         /////////////////////////////////////////////////////////////////////////////////////
         $pro_Model = 'osc-other';
         $pro_Name = 'Other Charges';
         $oProduct = Mage::getModel("catalog/product")->getCollection()->setStoreId($storeId)->addAttributeToSelect("sku")->addFieldToFilter("sku", array('eq' => $pro_Model))->getFirstItem();
         if (sizeof($oProduct->getData()) == 0) {
             $product = new Mage_Catalog_Model_Product();
             // Build the product
             $product->setSku($pro_Model);
             $product->setAttributeSetId($AttributeSetId);
             $product->setTypeId('simple');
             $product->setName($pro_Name);
             $product->setCategoryIds($parent_category);
             $product->setWebsiteIDs(array($storeId));
             $product->setDescription('-');
             $product->setShortDescription('-');
             $product->setPrice(1);
             $product->setWeight(0);
             $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
             $product->setStatus(1);
             $product->setTaxClassId(0);
             # My default tax class
             $product->setStockData(array('is_in_stock' => 1, 'qty' => 10000));
             $product->setCreatedAt(strtotime('now'));
             $product->save();
         }
     } catch (Exception $ex) {
         //echo $ex->getMessage();
         Mage::getSingleton('core/session')->setErrorMSG('Creating Import Products: ' . $pro_Name . ' - ' . $ex->getMessage());
     }
 }
 public function createBundleProduct(&$item, $asid)
 {
     $attributeSetModel = Mage::getModel('eav/entity_attribute_set');
     $attributeSetModel->load($asid);
     if (count($attributeSetModel) > 0) {
         $p_status = (string) $item->isActive == 'Y' ? 1 : 2;
         $p_taxclass = (string) $item->isTaxable == 'Y' ? 2 : 0;
         $product = new Mage_Catalog_Model_Product();
         $product->setTypeId('bundle');
         $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
         //New and created data code start
         $format = 'Y-m-d H:i:s';
         $catalogNewproductDays = Mage::getStoreConfig('catalog/newproduct/days', Mage::app()->getStore());
         if (!empty($catalogNewproductDays) && $catalogNewproductDays >= 0) {
             $currenDateTime = date("Y-m-d H:i:s", Mage::getModel('core/date')->timestamp(time()));
             $new_from_date = date($format, strtotime('1 days' . $currenDateTime));
             $new_to_date = date($format, strtotime($catalogNewproductDays . ' days' . $new_from_date));
             $product->setNewsFromDate($new_from_date);
             $product->setNewsToDate($new_to_date);
         }
         if ($product->getCreatedTime == NULL || $product->getUpdateTime() == NULL) {
             $product->setCreatedTime($currenDateTime)->setUpdateTime($currenDateTime);
         }
         //New and created data code end
         $product->setSku((string) $item->id);
         //Product custom id
         $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
         $product->setStoreIDs(array($this->_store_id));
         // Default store id .
         $product->setAttributeSetId($asid);
         $product->setData('name', (string) $item->name);
         $product->setPrice((double) $item->price);
         $splAmt = (array) $item->specialPrice->amount;
         if (isset($item->specialPrice->amount) && $item->specialPrice->amount != NULL) {
             if (!empty($splAmt)) {
                 $product->setSpecialPrice((double) $item->specialPrice->amount);
             }
             //special price in form 11.22
         }
         $fromDate = (array) $item->specialPrice->fromDateTime;
         if (isset($item->specialPrice->fromDateTime) && $item->specialPrice->fromDateTime != NULL) {
             if (!empty($fromDate)) {
                 $product->setSpecialFromDate(Mage::helper('customimport')->getCurrentLocaleDateTime($item->specialPrice->fromDateTime));
             }
             //special price from (MM-DD-YYYY)
         }
         $toDate = (array) $item->specialPrice->toDateTime;
         if (isset($item->specialPrice->toDateTime) && $item->specialPrice->toDateTime != NULL) {
             if (!empty($toDate)) {
                 $product->setSpecialToDate(Mage::helper('customimport')->getCurrentLocaleDateTime($item->specialPrice->toDateTime));
             }
             //special price to (MM-DD-YYYY)
         }
         $product->setWeight((double) $item->weight);
         $product->setStatus($p_status);
         $product->setTaxClassId($p_taxclass);
         $product->setDescription((string) $item->longDescription);
         $product->setShortDescription((string) $item->shortDescription);
         $product->setMetaTitle((string) $item->pageTitle);
         $product->setMetaKeyword((string) $item->metaKeywords);
         $product->setMetaDescription((string) $item->metaDescription);
         $product->setExternalImage((string) $item->originalImageUrl);
         $product->setExternalSmallImage((string) $item->largeImageUrl);
         $product->setExternalThumbnail((string) $item->smallImageUrl);
         $product->setShipmentType(0);
         //shipment type (0 - together, 1 - separately
         try {
             Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
             $product->save();
             $stockItem = Mage::getModel('cataloginventory/stock_item');
             $stockItem->assignProduct($product);
             $stockItem->setData('stock_id', (int) 1);
             $stockItem->setData('use_config_manage_stock', (int) 1);
             $stockItem->setData('min_qty', (int) 0);
             $stockItem->setData('is_decimal_divided', (int) 0);
             $stockItem->setData('qty', (int) 0);
             $stockItem->setData('use_config_min_qty', 1);
             $stockItem->setData('use_config_backorders', 1);
             $stockItem->setData('min_sale_qty', 1);
             $stockItem->setData('use_config_min_sale_qty', 1);
             $stockItem->setData('use_config_max_sale_qty', 1);
             $stockItem->setData('is_in_stock', 1);
             $stockItem->setData('use_config_notify_stock_qty', 1);
             // Added Manage Stock Functionality
             // Manage Stock
             $inventory = $item->inventory;
             $manageItem = (string) strtoupper($inventory->manageStock);
             if ($manageItem == 'N') {
                 $stockItem->setData('use_config_manage_stock', 0);
                 $stockItem->setData('manage_stock', 0);
             }
             $stockItem->save();
             $stockStatus = Mage::getModel('cataloginventory/stock_status');
             $stockStatus->assignProduct($product);
             $stockStatus->saveProductStatus($product->getId(), 1);
         } catch (Exception $e) {
             $this->customHelper->reportError($e->getMessage());
             $this->customHelper->sendLogEmail($this->logPath);
         }
     } else {
         $this->customHelper->reportError($this->customHelper->__('Attribute set ID # %s is missing. Hence skipped product # %s', $asid, $item->id));
     }
 }
Example #4
0
 public function addProduct($data)
 {
     $product = new Mage_Catalog_Model_Product();
     // Build the product
     $setId = Mage::getResourceModel('eav/entity_attribute_set_collection')->setEntityTypeFilter($this->typeId)->addFilter('attribute_set_name', $this->attributeSet['name'])->getFirstItem()->getId();
     // firstItem becouse of filter ($this->typeId) and filter ('attribute_set_name') design single attribute set.
     $product->setSku($data['sku']);
     $product->setAttributeSetId($setId);
     # 9 is for default
     $product->setTypeId('simple');
     $product->setName($data['name']);
     $product->setWebsiteIDs(array(1));
     //only array!!!!!  # Website id, 1 is default
     $product->setStoreIDs(array(0, 1));
     $product->setDescription($data['description']);
     $product->setShortDescription($data['short_description']);
     $product->setPrice($data['price']);
     # Set some price
     $product->setWeight($data['weight']);
     $product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
     $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
     $product->setTaxClassId(0);
     # default tax class
     if ($catId = $this->getCategoryIdByName($this->categoryName)) {
         $product->setCategoryIds(array($catId));
         # some cat id's,
     }
     $product->setStockData(array('is_in_stock' => 1, 'qty' => $data['qty']));
     $product->setCreatedAt(strtotime('now'));
     try {
         $product->save();
         echo "product created. ID: {$product->getId()} \n";
     } catch (Exception $ex) {
         zend_debug::dump($ex->getMessage());
     }
 }
Example #5
0
 public function importProducts($products, $storeId, $store)
 {
     Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
     if (!empty($products)) {
         foreach ($products as $_product) {
             $update = false;
             if ($_product["code"]) {
                 $sku = $_product["code"];
             } elseif ($_product["code2"]) {
                 $sku = $_product["code2"];
             } else {
                 $sku = $_product["code3"];
             }
             $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
             if (!$product) {
                 $product = Mage::getModel('catalog/product')->load($_product["productID"]);
                 if (!$product->getName()) {
                     $product = new Mage_Catalog_Model_Product();
                     $product->setId($_product["productID"]);
                     Mage::helper('Erply')->log("Creating new product: " . $_product["productID"]);
                 } else {
                     Mage::helper('Erply')->log("Editing old product: " . $_product["productID"]);
                     $update = true;
                 }
             } else {
                 $update = true;
             }
             if ($_product["displayedInWebshop"] == 0) {
                 if ($update) {
                     try {
                         $product->delete();
                         Mage::helper('Erply')->log("Delete existing product which should be in webshop id: " . $_product["productID"] . " - sku: " . $sku);
                     } catch (Exception $e) {
                         Mage::helper('Erply')->log("Failed to delete product with message: " . $e->getMessage());
                     }
                 }
                 continue;
             }
             $product->setStoreId($storeId);
             // product does not exist so we will be creating a new one.
             $product->setIsMassupdate(true);
             $product->setExcludeUrlRewrite(true);
             $product->setTypeId('simple');
             $product->setWeight(1.0);
             $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
             $product->setStatus(1);
             $product->setSku($sku);
             $product->setTaxClassId(0);
             // set the rest of the product information here that can be set on either new/update
             if (!$update) {
                 $product->setAttributeSetId((int) Mage::getStoreConfig('eepohs_erply/product/attribute_set', $storeId));
                 // the product attribute set to use
             }
             $product->setName($_product["name"]);
             $category = Mage::getModel('catalog/category')->load($_product["groupID"]);
             if ($category->getName()) {
                 $product->setCategoryIds(array($_product["groupID"]));
                 // array of categories it will relate to
             }
             if (Mage::app()->isSingleStoreMode()) {
                 $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsiteId()));
             } else {
                 $product->setWebsiteIds(array($store->getWebsiteId()));
             }
             $product->setBatchPrices(array());
             $product->setStockPriorities(array());
             //$product->setPrice($_product["price"]);
             // set the product images as such
             // $image is a full path to the image. I found it to only work when I put all the images I wanted to import into the {magento_path}/media/catalog/products - I just created my own folder called import and it read from those images on import.
             //        $image = '/path/to/magento/media/catalog/products/import/image.jpg';
             //
             //        $product->setMediaGallery (array('images'=>array (), 'values'=>array ()));
             //        $product->addImageToMediaGallery ($image, array ('image'), false, false);
             //        $product->addImageToMediaGallery ($image, array ('small_image'), false, false);
             //        $product->addImageToMediaGallery ($image, array ('thumbnail'), false, false);
             // setting custom attributes. for example for a custom attribute called special_attribute
             // special_attribute will be used on all examples below for the various attribute types
             //$product->setSpecialAttribute('value here');
             // setting a Yes/No Attribute
             //        $product->setSpecialField(1);
             // setting a Selection Attribute
             //$product->setSpecialAttribute($idOfAttributeOption); //specify the ID of the attribute option, eg you creteated an option called Blue in special_attribute it was assigned an ID of some number. Use that number.
             // setting a Mutli-Selection Attribute
             //$data['special_attribute'] = '101 , 102 , 103'; // coma separated string of option IDs. As ID , ID (mind the spaces before and after coma, it worked for me like that)
             //        $product->setData($data);
             if (isset($_product["attributes"])) {
                 $erplyAttributes = $_product["attributes"];
                 $mapping = unserialize(Mage::getStoreConfig('eepohs_erply/product/attributes', $storeId));
                 if (!empty($erplyAttributes) && !empty($mapping)) {
                     $mappings = array();
                     foreach ($mapping as $map) {
                         $mappings[$map["erply_attribute"]] = $map["magento_attribute"];
                     }
                     foreach ($erplyAttributes as $attribute) {
                         if (in_array($attribute["attributeName"], array_keys($mappings))) {
                             if ($attribute["attributeValue"]) {
                                 $product->setData($mappings[$attribute["attributeName"]], $attribute["attributeValue"]);
                             }
                         }
                     }
                 }
             }
             $product->save();
             Mage::helper('Erply')->log("Added: " . $product->getSku());
         }
     }
 }
Example #6
0
 protected function _createProducts($productsToCreateCount)
 {
     $skus = array();
     $initialProductCount = $this->_getProductCount();
     $randValues = array('general_name' => 'crife_Simple Product Required', 'general_sku' => 'wkdov_simple_sku_req_zuknf');
     // Set an Admin Session
     Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
     Mage::getSingleton('core/session', array('name' => 'adminhtml'));
     $userModel = Mage::getModel('admin/user');
     $userModel->setUserId(1);
     $session = Mage::getSingleton('admin/session');
     $session->setUser($userModel);
     $session->setAcl(Mage::getResourceModel('admin/acl')->loadAcl());
     for ($c = 0; $c < $productsToCreateCount; $c++) {
         array_walk_recursive($randValues, array($this, 'randomizeData'), array('general_name', 'general_sku'));
         $newProduct = new Mage_Catalog_Model_Product();
         $newProduct->setTypeId('simple');
         $newProduct->setCategoryIds(array(42));
         $newProduct->setWebsiteIDs(array(1));
         $newProduct->setWeight('1.000');
         $newProduct->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
         $newProduct->setStatus(1);
         $newProduct->setSku($randValues['general_sku']);
         $newProduct->setTaxClassId(0);
         $newProduct->setStoreId(Mage::app()->getStore()->getId());
         $newProduct->setAttributeSetId(9);
         $newProduct->setName($randValues['general_name']);
         $newProduct->setDescription('Description');
         $newProduct->setShortDescription('Short Description');
         $newProduct->setPrice(9.99);
         $newProduct->setStockData(array('is_in_stock' => 1, 'qty' => 99999));
         $newProduct->setCreatedAt(strtotime('now'));
         $newProduct->save();
         $skus[] = $randValues['general_sku'];
     }
     $finalProductCount = $this->_getProductCount();
     $this->assertEquals($productsToCreateCount, $finalProductCount - $initialProductCount);
     return $skus;
 }
Example #7
0
// Build the product
$product->setSku($sku);
$product->setAttributeSetId($setId);
# 9 is for default
$product->setTypeId('simple');
$product->setName('Lens 1');
$product->setCategoryIds(array(3));
# some cat id's,
$product->setWebsiteIDs(array(0, 1));
//only array!!!!!  # Website id, 1 is default
$product->setStoreIDs(array(0, 1));
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setPrice(39.99);
# Set some price
$product->setWeight(4.0);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$product->setTaxClassId(0);
# default tax class
$product->setStockData(array('is_in_stock' => 1, 'qty' => 99999));
$product->setCreatedAt(strtotime('now'));
try {
    $product->save();
    echo "product created";
} catch (Exception $ex) {
    zend_debug::dump($ex->getMessage());
}
echo date("\nY-d-m H:i:s\n");
?>
 
Example #8
0
 public function testGetWeight()
 {
     $this->assertEmpty($this->_model->getWeight());
     $this->_model->setWeight(10.22);
     $this->assertEquals(10.22, $this->_model->getWeight());
 }
Example #9
0
 public function importProducts()
 {
     $queue = Mage::getModel('Erply/Queue')->loadActive('erply_product_import');
     $params = array();
     if ($queue) {
         $runEvery = Mage::getStoreConfig('eepohs_erply/queue/run_every', $queue->getStoreId());
         $loops = $queue->getLoopsPerRun();
         $pageSize = $queue->getRecordsPerRun();
         $recordsLeft = $queue->getTotalRecords() - $pageSize * $queue->getLastPageNo();
         if ($queue->getChangedSince()) {
             $params = array('changedSince' => $queue->getChangedSince());
         }
         if ($loops * $pageSize > $recordsLeft) {
             $loops = ceil($recordsLeft / $pageSize);
             $queue->setStatus(0);
         } else {
             $thisRunTime = strtotime($queue->getScheduledAt());
             $newRunTime = strtotime('+' . $runEvery . 'minute', $thisRunTime);
             $scheduleDateTime = date('Y-m-d H:i:s', $newRunTime);
             Mage::getModel('Erply/Cron')->addCronJob('erply_product_import', $scheduleDateTime);
             $queue->setScheduledAt($scheduleDateTime);
         }
         $loops--;
         $firstPage = $queue->getLastPageNo() + 1;
         $queue->setLastPageNo($firstPage + $loops);
         $queue->setUpdatedAt(date('Y-m-d H:i:s', time()));
         $queue->save();
         $this->verifyUser($queue->getStoreId());
         $store = Mage::getModel('core/store')->load($queue->getStoreId());
         for ($i = $firstPage; $i <= $firstPage + $loops; $i++) {
             $parameters = array_merge(array('recordsOnPage' => $pageSize, 'pageNo' => $i), $params);
             Mage::helper('Erply')->log("Erply request: ");
             Mage::helper('Erply')->log($parameters);
             $result = $this->sendRequest('getProducts', $parameters);
             $return = "";
             Mage::helper('Erply')->log("Erply product import:");
             Mage::helper('Erply')->log($result);
             $output = json_decode($result, true);
             $start = time();
             foreach ($output["records"] as $_product) {
                 if ($_product["code2"]) {
                     $sku = $_product["code2"];
                 } elseif ($_product["code"]) {
                     $sku = $_product["code"];
                 } else {
                     $sku = $_product["code3"];
                 }
                 $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
                 if (!$product) {
                     $product = Mage::getModel('catalog/product')->load($_product["productID"]);
                     if (!$product->getName()) {
                         $product = new Mage_Catalog_Model_Product();
                         $product->setId($_product["productID"]);
                         Mage::helper('Erply')->log("Creating new product: " . $_product["productID"]);
                     } else {
                         Mage::helper('Erply')->log("Editing old product: " . $_product["productID"]);
                     }
                 }
                 // product does not exist so we will be creating a new one.
                 $product->setIsMassupdate(true);
                 $product->setExcludeUrlRewrite(true);
                 $product->setTypeId('simple');
                 $product->setWeight(1.0);
                 $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
                 $product->setStatus(1);
                 $product->setSku($sku);
                 $product->setTaxClassId(0);
                 //                    if (Mage::app()->isSingleStoreMode()) {
                 //                        $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsiteId()));
                 //                    }
                 //                    else {
                 //                        $product->setWebsiteIds(array(Mage::getModel('core/store')->load($queue->getStoreId())->getWebsiteId()));
                 //                    }
                 //                    $product->setStoreIDs(array($queue->getStoreId()));  // your store ids
                 //                    $product->setStockData(array(
                 //                        'is_in_stock' => 1,
                 //                        'qty' => 99999,
                 //                        'manage_stock' => 0,
                 //                    ));
                 // set the rest of the product information here that can be set on either new/update
                 $product->setAttributeSetId(4);
                 // the product attribute set to use
                 $product->setName($_product["name"]);
                 $product->setCategoryIds(array($_product["groupID"]));
                 // array of categories it will relate to
                 if (Mage::app()->isSingleStoreMode()) {
                     $product->setWebsiteIds(array(Mage::app()->getStore($queue->getStoreId())->getWebsiteId()));
                 } else {
                     $product->setWebsiteIds(array($store->getWebsiteId()));
                 }
                 $product->setDescription($_product["longdesc"]);
                 $product->setShortDescription($_product["description"]);
                 $product->setPrice($_product["price"]);
                 // set the product images as such
                 // $image is a full path to the image. I found it to only work when I put all the images I wanted to import into the {magento_path}/media/catalog/products - I just created my own folder called import and it read from those images on import.
                 //        $image = '/path/to/magento/media/catalog/products/import/image.jpg';
                 //
                 //        $product->setMediaGallery (array('images'=>array (), 'values'=>array ()));
                 //        $product->addImageToMediaGallery ($image, array ('image'), false, false);
                 //        $product->addImageToMediaGallery ($image, array ('small_image'), false, false);
                 //        $product->addImageToMediaGallery ($image, array ('thumbnail'), false, false);
                 // setting custom attributes. for example for a custom attribute called special_attribute
                 // special_attribute will be used on all examples below for the various attribute types
                 //$product->setSpecialAttribute('value here');
                 // setting a Yes/No Attribute
                 //        $product->setSpecialField(1);
                 // setting a Selection Attribute
                 //$product->setSpecialAttribute($idOfAttributeOption); //specify the ID of the attribute option, eg you creteated an option called Blue in special_attribute it was assigned an ID of some number. Use that number.
                 // setting a Mutli-Selection Attribute
                 //$data['special_attribute'] = '101 , 102 , 103'; // coma separated string of option IDs. As ID , ID (mind the spaces before and after coma, it worked for me like that)
                 //        $product->setData($data);
                 $product->save();
                 Mage::helper('Erply')->log("Added: " . $product->getSku());
             }
             unset($output);
         }
     }
 }
function createConfigurable($sku, $name, $optionId, $simpleProducts, $price, $brandId, $ageGroupId, $dimensions, $numPlayersId, $gameTime, $minNumPlayers, $shortDesc, $desc, $image1, $image2, $image3, $categoryId, $subCategoryId, $weight, $numPieces)
{
    try {
        $product = new Mage_Catalog_Model_Product();
        // Build the product
        $product->setSku($sku);
        $product->setAttributeSetId('13');
        # 9 is for default
        $product->setTypeId('configurable');
        $product->setName($name);
        $product->setCategoryIds(array(25));
        # some cat id's,
        $product->setWebsiteIDs(array(1));
        # Website id, 1 is default
        $product->setDescription($desc);
        $product->setShortDescription($shortDesc);
        $product->setPrice($price);
        # Set some price
        //Default Magento attribute
        //$product->setWeight($weight);
        echo '<br>' . $weight . '<br>';
        //$product->setWeight(0.2000);
        $product->setWeight(4.0);
        $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
        $product->setStatus(1);
        $product->setTaxClassId(0);
        # default tax class
        $product->setStockData(array('is_in_stock' => 1, 'qty' => 99999));
        $product->setCreatedAt(strtotime('now'));
        $product->setCategoryIds(array($categoryId, $subCategoryId));
        $product->setMetaDescription($shortDesc);
        $mediaAttribute = array('thumbnail', 'small_image', 'image');
        $imagePath1 = './media/import/' . $image1;
        $imagePath2 = './media/import/' . $image2;
        $imagePath3 = './media/import/' . $image3;
        //echo $imagePath1.'<br>'.$imagePath2.'<br>'.$imagePath3;die();
        if (!file_exists($imagePath1) && $imagePath1 != '') {
            if (file_exists('./media/import.bak/' . $image1)) {
                exec('cp media/import.bak/' . $image1 . ' media/import');
                $product->addImageToMediaGallery('./media/import/' . $image1, $mediaAttribute, true, false);
            } else {
                echo 'ERROR: file ' . $imagePath1 . ' does not exist.  SKU is: ' . $sku;
            }
        } elseif ($imagePath1 != '') {
            $product->addImageToMediaGallery($imagePath1, $mediaAttribute, true, false);
        }
        if (!file_exists($imagePath2) && $imagePath2 != '') {
            if (file_exists('./media/import.bak/' . $image2)) {
                exec('cp media/import.bak/' . $image2 . ' media/import');
                $product->addImageToMediaGallery('./media/import/' . $image2, null, true, false);
            } else {
                echo 'ERROR: file ' . $imagePath2 . ' does not exist.  SKU is: ' . $sku;
            }
        } elseif ($imagePath2 != '') {
            $product->addImageToMediaGallery($imagePath2, null, true, false);
        }
        if (!file_exists($imagePath3) && $imagePath3 != '') {
            if (file_exists('./media/import.bak/' . $image3)) {
                exec('cp media/import.bak/' . $image3 . ' media/import');
                $product->addImageToMediaGallery('./media/import/' . $image3, null, true, false);
            } else {
                echo 'ERROR: file ' . $imagePath3 . ' does not exist.  SKU is: ' . $sku;
            }
        } elseif ($imagePath3 != '') {
            $product->addImageToMediaGallery($imagePath3, null, true, false);
        }
        //custom attribute for gift wrapping
    } catch (Exception $exMain) {
        echo 'configurable main exception:<br><br>' . $exMain . '<br><br>';
    }
    try {
        $product->save();
        $_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
        $configId = $_product->getId();
        $resource = Mage::getSingleton('core/resource');
        $readCon = $resource->getConnection('core_read');
        $writeCon = $resource->getConnection('core_write');
        $table = 'catalog_product_super_attribute';
        if (!$writeCon) {
            die('Could not connect: ' . mysql_error());
        }
        //set gift wrap attribute:  super attribute id, configurable product id (auto-increment), normal attribute id, position (always 0 for one configurable option)
        $query = 'insert into catalog_product_super_attribute (product_id, attribute_id) values (' . $configId . ', 142 )';
        $writeCon->query($query);
        //i think this has to be set to create the associated products: configurable product id, associated simple product id  ...repeat as necessary (twice in this case)
        $simpleId1 = $simpleProducts[0]->getId();
        $simpleId2 = $simpleProducts[1]->getId();
        $query = 'insert into catalog_product_relation values (' . $configId . ', ' . $simpleId1 . ' )';
        $writeCon->query($query);
        $query = 'insert into catalog_product_relation values (' . $configId . ', ' . $simpleId2 . ' )';
        $writeCon->query($query);
        //set the link id between the configurable product and the associated simple product: link id, simple product, configurable product
        $query = 'insert into catalog_product_super_link (product_id, parent_id) values (' . $simpleId1 . ', ' . $configId . ')';
        $writeCon->query($query);
        $query = 'insert into catalog_product_super_link (product_id, parent_id) values (' . $simpleId2 . ', ' . $configId . ')';
        $writeCon->query($query);
        //get the superattribute id for the next write query
        $query = 'select product_super_attribute_id from catalog_product_super_attribute where product_id=' . $configId;
        $superAttrId = $readCon->fetchOne($query);
        $query = 'insert into catalog_product_super_attribute_pricing (product_super_attribute_id, value_index, is_percent, pricing_value, website_id) values (' . $superAttrId . ', 91, 0, 5.000, 0)';
        $writeCon->query($query);
        $_product->setData('brand', $brandId);
        $_product->setData('age_group', $ageGroupId);
        $_product->setData('dimensions', $dimensions);
        $_product->setData('num_players', $numPlayersId);
        $_product->setData('game_time', $gameTime);
        $_product->setData('min_num_players', $minNumPlayers);
        $_product->setData('num_pieces', $numPieces);
        //set cross sell products
        //$crossProduct = Mage::getModel('catalog/product')->load
        //$_product->setCrossSellLinkData(
        $_product->save();
    } catch (Exception $ex) {
        echo 'configurable save exception:<br><br>' . $ex;
    }
    /*$row1 = 1;
    		$handle1 = fopen("product_import_category_test.csv", "r");
    		while (($data1 = fgetcsv($handle1, 2000, ",")) !== FALSE)
    		{
    			$num1 = count($data1);
    			$row1++;
    			if($row1 != 2)
    			{
    				$sku = $data1[14];
    				echo $data1[19].'<br>';
    				$baseProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
    				$crossSellSkus = array();
    				$crossSellSkus = explode(',',$data1[19]);
    				var_dump($baseProduct);echo '<br>';var_dump($crossSellSkus);die();
    
    			}
    
    
    
    		}*/
}