magento import products

piaoling  2011-08-16 11:39:31

<?php

define('DIRNAME', dirname(__FILE__));

require dirname(__FILE__) . '/../../app/Mage.php';
require_once dirname(__FILE__) . '/../setting/classes/debug.php';
require_once dirname(__FILE__) . '/../setting/classes/tool.php';
require_once dirname(__FILE__) .DS.'classes'.DS.'media.php';
require_once dirname(__FILE__) .DS.'classes'.DS.'product.php';
require_once dirname(__FILE__) .DS.'classes'.DS.'price.php';
require_once dirname(__FILE__) .DS.'classes'.DS.'converAttribute.php';

define('FILE_TREATMENT', DIRNAME.DS.getMapsConfig()->import_products->FOLDER_TREATMENT_NAME.DS );
define('FILE_ARCHIVES', DIRNAME.DS.getMapsConfig()->import_products->FOLDER_ARCHIVES_NAME.DS );
define('FILE_LOGS', DIRNAME.DS.getMapsConfig()->import_products->FOLDER_LOG_NAME.DS );
define('TIMEZONE',getMapsConfig()->global_config->TIMEZONE);
date_default_timezone_set (TIMEZONE);
define('CURRENT_TIME',date("Ymd_His") );

Mage::app();
Mage::register('isSecureArea', true, true);

$globalArray=array();
$typeArray=array();

try {
        $dotXmlFiles = array();
    
        $websiteArray=getWebsiteArray();
        foreach ( $websiteArray as $website ){
            
            if(is_dir(FILE_TREATMENT . $website)){
                
               $websiteId = Mage::getModel('core/website')->load($website)->getId();
               if(is_null($websiteId)){
                    debug("The website "$website" does not exist, ignore that folder");
                    Mage::log("The website "$website" does not exist, ignore that folder");
                    continue;
                }
                
                $dir2 = dir(FILE_TREATMENT . $website);
                while (false !== ($entryFile = $dir2->read())) {
                     if(strpos($entryFile, '.xml'))
                          $dotXmlFiles[] = $entryFile . '#' . $website;
                     }
                $dir2->close();
            }else{
                debug("The website "$website" does not exist, ignore that folder");
                Mage::log("The website "$website" does not exist, ignore that folder");
            }
        }
        
        
        foreach($dotXmlFiles as $key => $val){
            $temp = explode('#', $val);
            $dotXmlFiles[$key] = $temp[1].'/'.$temp[0];
        }

        date_default_timezone_set (TIMEZONE);
        foreach ( $dotXmlFiles as $xmlFileOri) {
           
            $tempstrict = explode('/', $xmlFileOri); // to avoid 'Stricts mode' errors
            $website = current($tempstrict);
            $websiteId = Mage::getModel('core/website')->load($website)->getId();
           
            Mage::unregister( "current_website_id" );
            Mage::register( "current_website_id",$websiteId );
           
            if(!is_dir(FILE_LOGS . $website)){
                mkdir(FILE_LOGS . $website, 0777);
            }
            if(!is_dir(FILE_ARCHIVES . $website)){
                mkdir(FILE_ARCHIVES . $website, 0777);
            }
           
            $tempstrict = explode('.', $xmlFileOri); // to avoid 'Stricts mode' errors
           
               $log_content = '';
               $hasError = false;
        
            writeLog("START: import_product.php /maps/product/upload/$xmlFileOri");

            $xmlFile = FILE_TREATMENT.$xmlFileOri;

            //file exists
            if(!file_exists($xmlFile)){
                throw new Exception("File {$XmlFile} doesn't exist");
            }

            try{
                $xmlRoot = new SimpleXMLIterator($xmlFile, null, true);
            }
            catch(Exception $e){
                writeLog("File format error, could not parse ".$xmlFile." as XML", true);
                fclose ($fp);
                continue;
            }
           
            // --------------
           
            $products_tobe_imported = array();
            $xmlRoot->rewind();
            $xmlProducts = $xmlRoot->current();
            for( $xmlProducts->rewind(); $xmlProducts->valid(); $xmlProducts->next() ) {
                $secondLevel = $xmlProducts->current();

                $secondLevelTemp= $xmlProducts->current();
                $maxNumTagLien=array();
               
                //if found sku in this array, set attribute "visibility" to 1
                $attributeVisibilityArray=array();
               
               
                for( $secondLevelTemp->rewind(); $secondLevelTemp->valid(); $secondLevelTemp->next() ) {
                    $thirdLevel = $secondLevel->current();
                    $thirdLevelName = $thirdLevel->getName();
                }
               
               
                for( $secondLevel->rewind(); $secondLevel->valid(); $secondLevel->next() ) {
                    $thirdLevel = $secondLevel->current();
                    $thirdLevelName = $thirdLevel->getName();
                   
                   
                   
                    $attributeSet =  (string)$thirdLevel['type'];
                   
                        /*
                         * PM="true".
                         *  if import a product when @PM='true', the attribute "visibility"
                         *   should be "Not Visible Individually"(value of 1)
                         */
                     if( isset( $thirdLevel['PM'] ) && $thirdLevel['PM']=="true" ){
                        $visibilityFlag=true;
                     }
                     else
                     {
                         $visibilityFlag=false;
                     }
                   
                    $setId = getAttributeSetIdByName($attributeSet);
                    if(!$setId ){
                        writeLog("The attribute set "$attributeSet" does not exist in Magento, ignore importing product",  true);
                        continue;
                    }
                   
                    $product_type = '';    
                    //make product type
                    if($thirdLevelName == 'PM'){
                        $product_type = Mage_Catalog_Model_Product_Type::TYPE_GROUPED;
                    }
                    elseif($thirdLevelName == 'ARTICLE'){
                        $product_type = Mage_Catalog_Model_Product_Type::TYPE_SIMPLE;
                    }
                   
                    // handle products in node PMS or ARTICLES
                    $attribute_codes = array();
                    $attribute_codes['type'] = $product_type;
                    $globalArray[(string)$thirdLevel->CODEMAPS]= (string)$thirdLevel['refmaps'];
                    $typeArray[(string)$thirdLevel->CODEMAPS]= $product_type;
                    
                    if( $visibilityFlag==true  ){
                         $attributeVisibilityArray[]=(string)$thirdLevel->CODEMAPS;
                    }
                        
                    
                    for($thirdLevel->rewind(); $thirdLevel->valid(); $thirdLevel->next()){
                        
                        if($thirdLevel->key() == 'ATTRIBUTS_PARENTS'){
                            debug('Parsing ATTRIBUTS_PARENTS for ARTICLE SKU='.$thirdLevel->CODEMAPS);
                            $fourthLevel = $thirdLevel->current();
                            
                            // We have an ATTRIBUTS_PARENTS tag, we look for children tags with the attribute "attribute_regroupement"
                            for( $fourthLevel->rewind(); $fourthLevel->valid(); $fourthLevel->next() ){
                                $current = $fourthLevel->current();
                                $is_regroupement = false;
                                foreach($current->attributes() as $k => $v){
                                    if ((string)$k == 'attribute_regroupement' && (string)$v == 'true'){
                                        $is_regroupement = true;
                                        break;
                                    }
                                }
                                if (!$is_regroupement) // No such attribute found, trying the next tag inside ATTRIBUTS_PARENTS
                                    continue;
                                    
                                if(!array_key_exists($fourthLevel->key(), $attribute_codes)){
                                    // Still making sure we don't override previous stuff
                                    $attribute_codes[$fourthLevel->key()] = $fourthLevel->getChildren();
                                    debug('> We got extra attribute '.$fourthLevel->key().' from ATTRIBUTS_PARENTS');
                                }
                            }
                        }elseif(!array_key_exists($thirdLevel->key(), $attribute_codes)){
                            $attribute_codes[$thirdLevel->key()] = $thirdLevel->getChildren();
                        }
                    }
                    if(!empty($attributeSet)){
                        $products_tobe_imported[] = array($attributeSet => $attribute_codes);
                    }
                }
               
               
            }
                   
            // This line is very important. The key point is Mage_Core_Controller_Front_Action cannot be used to save products.
            Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);            
           
            if(!empty($products_tobe_imported)){
                $updateCnt = 0;
                $createCnt = 0;
                $allowedCode = array('type', 'MEDIAS', 'QUANTITEVENTEMIN','QTARDI','QTARSEUIL','INDISPOVENTE', 'SEUILSTOCK', 'COARET', 'PRIX', 'REGROUPEMENTS');
               
                foreach($products_tobe_imported as $product){
                    importProduct($product, $websiteId);
                }
               
                writeLog("$createCnt product(s) is(are) created successfully.");
                writeLog("$updateCnt product(s) is(are) updated successfully.");
            }
            $tempstrict = explode('.', $xmlFileOri); // to avoid strict mode errors
            rename(FILE_TREATMENT.$xmlFileOri, FILE_ARCHIVES . current($tempstrict). '_'.time()."_done.xml");
            writeLog("$xmlFileOri succesfully moved to /maps/products/traites/". current($tempstrict). "_done.xml");
            writeLog("END: import_product.php: $xmlFileOri");
           
            if($hasError && $log_content != ''){
                   sendEmail($log_content);
            }
        }
       
}
catch (Exception $e) {
    debug(__LINE__.PHP_EOL.$e->getMessage());
    debug(debug_backtrace());
    Mage::log($e->getMessage());
    exit(1);
}
 

类别 :  magento(258)  |  浏览(3480)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: