public function map()
 {
     //Always print debug information. Issue #80
     $this->debug = true;
     $updateAll = (bool) Mage::getStoreConfig('webtoprint/settings/refresh-templates');
     $action = $this->getAction();
     $assignToParents = (bool) $action->getParam('assign-to-parents');
     $categoryMappingStore = $action->getParam('category-mapping-store');
     unset($action);
     $categoryMappingStore = Mage::app()->getStore($categoryMappingStore);
     if (!$categoryMappingStore->getId()) {
         $categoryMappingStore = null;
     }
     $cataloguesMapping = null;
     $helper = Mage::helper('webtoprint/category');
     $templates = Mage::getModel('webtoprint/template')->getCollection()->load();
     foreach ($templates as $template) {
         $product_model = Mage::getModel('catalog/product');
         if ($product_id = $product_model->getIdBySku($template->getGuid())) {
             $this->debug("Product {$template->getGuid()} already exists");
             $product = $product_model->load($product_id);
             if (!$product->getWebtoprintTemplate()) {
                 $this->debug("Product {$template->getGuid()} doesn't have web-to-print attribute.");
                 Mage::register('webtoprint-template-changed', true);
                 $product->setSku("{$template->getGuid()}-rename-me")->setRequiredOptions(true)->setWebtoprintTemplate($template->getGuid())->save();
                 Mage::unregister('webtoprint-template-changed');
                 $this->debug("Web-to-print attribute was added to product {$template->getGuid()}");
             } else {
                 $this->debug("SKU of product {$template->getGuid()} is equal to its web-to-print attribute");
                 Mage::register('webtoprint-template-changed', true);
                 $product->setSku("{$template->getGuid()}-rename-me")->setRequiredOptions(true)->save();
                 Mage::unregister('webtoprint-template-changed');
                 $this->debug("SKU of product {$template->getGuid()} was changed.");
             }
         } else {
             $products = $product_model->getCollection()->addAttributeToFilter('webtoprint_template', array('eq' => $template->getGuid()))->load();
             if (!(bool) $template->getExist()) {
                 if (count($products) == 0) {
                     $template->delete();
                     continue;
                 }
                 $behaviour = (int) Mage::getStoreConfig('webtoprint/settings/templates-removing-behaviour');
                 if ($behaviour == ZetaPrints_WebToPrint_Model_System_Config_Source_TemplateDeletingBehaviour::NONE) {
                     foreach ($products as $product) {
                         $full_product = $product_model->load($product->getId());
                         $this->debug("Template for product {$full_product->getWebtoprintTemplate()} was removed");
                         Mage::register('webtoprint-template-changed', true);
                         $full_product->setRequiredOptions(false)->setWebtoprintTemplate('');
                         Mage::dispatchEvent('webtoprint_product_update', array('product' => $full_product, 'template' => zetaprints_parse_template_details(new SimpleXMLElement($template->getXml())), 'params' => array('process-quantities' => $this->_isProcessQuantities())));
                         $full_product->save();
                         Mage::unregister('webtoprint-template-changed');
                         $this->debug("Product {$full_product->getSku()} was unlinked from the template");
                     }
                     $template->delete();
                 } elseif ($behaviour == ZetaPrints_WebToPrint_Model_System_Config_Source_TemplateDeletingBehaviour::DELETE) {
                     foreach ($products as $product) {
                         $full_product = $product_model->load($product->getId());
                         $this->debug("Template for product {$full_product->getWebtoprintTemplate()} was removed");
                         $full_product->delete();
                         $this->debug("Product {$product->getSku()} was removed");
                     }
                     $template->delete();
                 } else {
                     if ($behaviour >= 0) {
                         $category = Mage::getModel('catalog/category')->load($behaviour);
                         if (!$category->getId()) {
                             $this->warning('Category doesn\'t exist. Check configuration.');
                             continue;
                         }
                         foreach ($products as $product) {
                             $full_product = $product_model->load($product->getId());
                             $this->debug("Template for product {$full_product->getWebtoprintTemplate()} was removed");
                             Mage::register('webtoprint-template-changed', true);
                             $full_product->setCategoryIds(array($behaviour))->setRequiredOptions(false)->setWebtoprintTemplate('');
                             Mage::dispatchEvent('webtoprint_product_update', array('product' => $full_product, 'template' => zetaprints_parse_template_details(new SimpleXMLElement($template->getXml())), 'params' => array('process-quantities' => $this->_isProcessQuantities())));
                             $full_product->save();
                             Mage::unregister('webtoprint-template-changed');
                             $this->debug("Product {$product->getSku()} was moved to category {$category->getName()}");
                         }
                         $template->delete();
                     }
                 }
             } else {
                 foreach ($products as $product) {
                     if ($updateAll || strtotime($product->getUpdatedAt()) <= strtotime($template->getDate())) {
                         $full_product = $product_model->load($product->getId());
                         $this->debug("Template for product {$full_product->getWebtoprintTemplate()} changed");
                         Mage::register('webtoprint-template-changed', true);
                         //Mark product as changed and then save it.
                         $full_product->setDataChanges(true);
                         $templateDetails = zetaprints_parse_template_details(new SimpleXMLElement($template->getXml()));
                         if ($cataloguesMapping === null) {
                             $cataloguesMapping = array();
                             $url = Mage::getStoreConfig('webtoprint/settings/url');
                             $key = Mage::getStoreConfig('webtoprint/settings/key');
                             $catalogues = zetaprints_get_list_of_catalogs($url, $key);
                             foreach ($catalogues as $catalogue) {
                                 $cataloguesMapping[$catalogue['guid']] = $catalogue['title'];
                             }
                             unset($catalogues, $catalogue, $url, $key);
                         }
                         $templateDetails['catalogue'] = $cataloguesMapping[$template->getCatalogGuid()];
                         $categoryIds = $helper->getCategoriesIds($templateDetails, $assignToParents, $categoryMappingStore);
                         if ($categoryIds) {
                             $full_product->setCategoryIds($categoryIds);
                         }
                         Mage::dispatchEvent('webtoprint_product_update', array('product' => $full_product, 'template' => $templateDetails, 'params' => array('process-quantities' => $this->_isProcessQuantities())));
                         $full_product->save();
                         Mage::unregister('webtoprint-template-changed');
                         $this->debug("Product {$full_product->getWebtoprintTemplate()} was succesfully updated");
                     }
                 }
             }
         }
     }
 }
 public function map()
 {
     //Always print debug information. Issue #80
     $this->debug = true;
     $this->warning('Product type: ' . $this->getAction()->getParam('product-type', 'simple'));
     if (!($assignToWebsites = $this->_getWebsitesForAssign())) {
         return;
     }
     //Get all web-to-print templates
     $templates = Mage::getModel('webtoprint/template')->getCollection()->load();
     //Get all products
     $products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('webtoprint_template')->load();
     //If there're products then...
     if ($has_products = (bool) count($products)) {
         //... create array to store used web-to-print template GUIDs
         $used_templates = array();
         //For every product...
         foreach ($products as $product) {
             //... remember its ID
             $used_templates[$product->getId()] = null;
             //And if it has web-to-print attribute set then...
             if ($product->hasWebtoprintTemplate() && $product->getWebtoprintTemplate()) {
                 //... also remember the value of the attribute
                 $used_templates[$product->getWebtoprintTemplate()] = null;
             }
         }
     }
     unset($products);
     // Get ID of source product if present and try to load source product
     $sourceId = $this->getAction()->getParam('source-product-id');
     $sourceProduct = null;
     if ($sourceId) {
         $sourceProduct = Mage::getModel('catalog/product')->load($sourceId);
         if ($sourceProduct->getId()) {
             $this->warning('Base product: ' . $sourceProduct->getName());
             $sourceProduct->getCategoryIds();
             $sourceProduct->setId(null);
             $sourceData = $sourceProduct->getData();
             $sourceData['stock_item'] = null;
             $sourceData['url_key'] = null;
         } else {
             $sourceProduct = null;
         }
     }
     $url = Mage::getStoreConfig('webtoprint/settings/url');
     $key = Mage::getStoreConfig('webtoprint/settings/key');
     $_catalogues = zetaprints_get_list_of_catalogs($url, $key);
     $cataloguesMapping = array();
     foreach ($_catalogues as $_catalogue) {
         $cataloguesMapping[$_catalogue['guid']] = $_catalogue['title'];
     }
     $_catalogues = array();
     $categoryMappingStore = $this->getAction()->getParam('category-mapping-store');
     $categoryMappingStore = Mage::app()->getStore($categoryMappingStore);
     $assignToParents = (bool) $this->getAction()->getParam('assign-to-parents');
     if (!$categoryMappingStore->getId()) {
         $categoryMappingStore = null;
     }
     $useProductPopulateDefaults = Mage::getStoreConfig('webtoprint/settings/products-populate-defaults');
     $_defaultCategory = array();
     $helper = Mage::helper('webtoprint/category');
     $line = 0;
     $number_of_templates = count($templates);
     $number_of_created_products = 0;
     foreach ($templates as $template) {
         $line++;
         if ($has_products) {
             if (array_key_exists($template->getGuid(), $used_templates)) {
                 $this->debug("{$line}. Product {$template->getGuid()} already exists");
                 continue;
             }
         }
         if (!$sourceProduct) {
             $product_model = Mage::getModel('catalog/product');
             $product_model->setWebsiteIds($assignToWebsites)->setAttributeSetId($product_model->getDefaultAttributeSetId())->setTypeId($this->getAction()->getParam('product-type', 'simple'))->setStatus(Mage_Catalog_Model_Product_Status::STATUS_DISABLED)->setVisibility(0);
             if ($useProductPopulateDefaults) {
                 $product_model->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)->setWeight(0)->setPrice(0)->setTaxClassId(0);
             }
             $templateDetails = zetaprints_parse_template_details(new SimpleXMLElement($template->getXml()));
             $templateDetails['catalogue'] = $cataloguesMapping[$template->getCatalogGuid()];
             $categoryIds = $helper->getCategoriesIds($templateDetails, $assignToParents, $categoryMappingStore);
             if (!$categoryIds && $useProductPopulateDefaults) {
                 $categoryIds = $this->_getDefaultCategoryId();
             }
             $product_model->setCategoryIds($categoryIds);
         } else {
             $product_model = $sourceProduct;
             $product_model->setOrigData()->setData($sourceData);
         }
         $product_model->setSku(zetaprints_generate_guid() . '-rename-me')->setName($template->getTitle())->setDescription($template->getDescription())->setShortDescription($template->getDescription())->setRequiredOptions(true)->setWebtoprintTemplate($template->getGuid());
         Mage::dispatchEvent('webtoprint_product_create', array('product' => $product_model, 'template' => $templateDetails, 'params' => array('process-quantities' => $this->_isProcessQuantities())));
         try {
             $product_model->save();
         } catch (Exception $e) {
             $this->error("{$line}. Error creating product from template: {$template->getGuid()}");
             $this->error($e->getMessage());
             continue;
         }
         $stock_item = Mage::getModel('cataloginventory/stock_item');
         $stock_item->setStockId(1)->setUseConfigManageStock(0)->setProduct($product_model)->save();
         $this->debug("{$line}. Product for template {$template->getGuid()} was created.");
         $number_of_created_products++;
         unset($product_model);
         unset($stock_item);
     }
     $this->notice("Number of templates: {$number_of_templates}");
     $this->notice("Number of created products: {$number_of_created_products}");
     $this->warning('Warning: products were created with general set of properties. Update other product properties using bulk edit to make them operational.');
 }
 public function parse()
 {
     $url = Mage::getStoreConfig('webtoprint/settings/url');
     $key = Mage::getStoreConfig('webtoprint/settings/key');
     //Always print debug information. Issue #80
     $this->debug = true;
     if ($url) {
         $this->notice("ZetaPrints URL: {$url}");
     } else {
         $this->error("ZetaPrints URL is empty");
     }
     if ($key) {
         $this->notice('ZetaPrints API Key: ' . substr($key, 0, 6) . '&hellip;');
     } else {
         $this->error("ZetaPrints API Key is empty");
     }
     $refresh_templates = (bool) Mage::getStoreConfig('webtoprint/settings/refresh-templates');
     if ($refresh_templates) {
         $this->warning('Refresh all templates');
     }
     $catalogs = zetaprints_get_list_of_catalogs($url, $key);
     if ($catalogs === null) {
         $this->error('Error in parsing catalogs detailes xml');
         return;
     } else {
         if (is_string($catalogs)) {
             $this->error("Error in receiving catalogs: {$catalogs}");
             return;
         }
     }
     if (!count($catalogs)) {
         $this->warning('No catalogs');
         return;
     }
     $total_number_of_catalogs = 0;
     $number_of_ignored_catalogs = 0;
     $total_number_of_templates = 0;
     $number_of_added_templates = 0;
     $number_of_uptodate_templates = 0;
     $number_of_updated_templates = 0;
     $number_of_removed_templates = 0;
     $number_of_ignored_templates = 0;
     $line = 0;
     $all_template_guids = array();
     foreach ($catalogs as $catalog) {
         $total_number_of_catalogs++;
         $templates = zetaprints_get_templates_from_catalog($url, $key, $catalog['guid']);
         if ($templates === null) {
             $this->error("Error in parsing templates detailes xml from catalog {$catalog['title']}");
             $number_of_ignored_catalogs++;
             continue;
         } else {
             if (is_string($templates)) {
                 $this->error("Error in receiving list of templates for catalog {$catalog['title']}: {$templates}");
                 $number_of_ignored_catalogs++;
                 continue;
             }
         }
         if (!count($templates)) {
             $this->warning("No templates in catalog {$catalog['title']}");
             $number_of_ignored_catalogs++;
             continue;
         }
         $total_number_of_templates += count($templates);
         foreach ($templates as $template) {
             $line++;
             $all_template_guids[$template['guid']] = $template['guid'];
             $template_array = zetaprints_get_template_detailes($url, $key, $template['guid']);
             if (!$template_array) {
                 $this->error("{$line}. Error in receiving or parsing detailes of template {$template['guid']}. Leaving the template unmodified.");
                 continue;
             }
             $has_fields = false;
             foreach ($template_array['pages'] as $page) {
                 if (isset($page['images']) || isset($page['fields'])) {
                     $has_fields = true;
                     break;
                 }
             }
             $template['public'] = $catalog['public'];
             $templates_collection = Mage::getModel('webtoprint/template')->getCollection()->get_by_guid($template['guid'])->load();
             if ($templates_collection->getSize() == 1) {
                 foreach ($templates_collection as $template_model) {
                     if (!$has_fields) {
                         $template_model->setExist(false)->save();
                         $number_of_removed_templates++;
                         $this->warning("{$line}. Template {$template['guid']} has no variable fields. Template will be deleted.");
                         continue;
                     }
                     if (strtotime($template['date']) > strtotime($template_model->getDate()) || $refresh_templates || (int) $template_model->getPublic() != $template['public']) {
                         $this->debug("{$line}. Template {$template['guid']} is outdated");
                         $template['xml'] = zetaprints_get_template_details_as_xml($url, $key, $template['guid']);
                         if (!$template['xml']) {
                             $this->error("{$line}. Error in receiving detailes for template {$template['guid']}. Leaving the template unmodified.");
                             continue;
                         }
                         $template_model->addData($template)->save();
                         $number_of_updated_templates++;
                     } else {
                         $number_of_uptodate_templates++;
                         $this->debug("{$line}. Template {$template['guid']} is up to date");
                     }
                 }
             } else {
                 if (!$has_fields) {
                     $this->warning("{$line}. Template {$template['guid']} has no variable fields. Ignored.");
                     $number_of_ignored_templates++;
                     continue;
                 }
                 $template['xml'] = zetaprints_get_template_details_as_xml($url, $key, $template['guid']);
                 if (!$template['xml']) {
                     $this->error("{$line}. Error in receiving detailes for template {$template['guid']}. Passing the template.");
                     $number_of_ignored_templates++;
                     continue;
                 }
                 $template_model = Mage::getModel('webtoprint/template');
                 $template_model->addData($template)->save();
                 if ($template_model->getId()) {
                     $number_of_added_templates++;
                     $this->notice("{$line}. Template {$template['guid']} is succesfully added.");
                 }
             }
         }
     }
     $templates_collection = Mage::getModel('webtoprint/template')->getCollection()->load();
     foreach ($templates_collection as $template) {
         if (!isset($all_template_guids[$template->getGuid()])) {
             $number_of_removed_templates += 1;
             $template->setExist(false)->save();
         }
     }
     $this->notice("Total number of catalogs: {$total_number_of_catalogs}");
     $this->notice("Number of ignored catalogs: {$number_of_ignored_catalogs}");
     $this->notice("Total number of templates: {$total_number_of_templates}");
     $this->notice("Number of added templates: {$number_of_added_templates}");
     $this->notice("Number of up to date templates: {$number_of_uptodate_templates}");
     $this->notice("Number of updated templates: {$number_of_updated_templates}");
     $this->notice("Number of ignored templates: {$number_of_ignored_templates}");
     $this->notice("Number of removed templates: {$number_of_removed_templates}");
     if ($number_of_added_templates > 0) {
         $this->notice('Run ZetaPrints product creation profile to create products for new templates automatically. Read <a href="http://www.zetaprints.com/magentohelp/">www.zetaprints.com/magentohelp/</a> for more info on product creation.');
     }
 }
 public function parse()
 {
     $url = Mage::getStoreConfig('webtoprint/settings/url');
     $key = Mage::getStoreConfig('webtoprint/settings/key');
     //Always print debug information. Issue #80
     $this->debug = true;
     if ($url) {
         $this->notice("ZetaPrints URL: {$url}");
     } else {
         $this->error("ZetaPrints URL is empty");
     }
     if ($key) {
         $this->notice('ZetaPrints API Key: ' . substr($key, 0, 6) . '&hellip;');
     } else {
         $this->error("ZetaPrints API Key is empty");
     }
     $catalogs = zetaprints_get_list_of_catalogs($url, $key);
     if ($catalogs === null) {
         $this->error('Error in parsing catalogs detailes xml');
         return;
     } else {
         if (is_string($catalogs)) {
             $this->error("Error in receiving catalogs: {$catalogs}");
             return;
         }
     }
     if (!count($catalogs)) {
         $this->warning('No catalogs');
         return;
     }
     $isCreateSubCategories = $this->getAction()->getParam('create-subcategories', 'false') == 'true';
     $total_number_of_catalogs = 0;
     $number_of_ignored_catalogs = 0;
     $number_of_created_catalogues = 0;
     $number_of_not_created_catalogues = 0;
     $line = 0;
     $helper = Mage::helper('webtoprint/category');
     foreach ($catalogs as $catalog) {
         $total_number_of_catalogs++;
         if ($catalog['templates'] == 0) {
             $this->warning("No templates in catalog {$catalog['title']}");
             $number_of_ignored_catalogs++;
             continue;
         }
         $category = $helper->getCategory($catalog['title'], true);
         if (!($category && $category->getId())) {
             $this->notice("Can't create catalogue '{$catalog['title']}'");
             $number_of_not_created_catalogues++;
             continue;
         }
         if ($isCreateSubCategories) {
             foreach (explode(',', $catalog['keywords']) as $name) {
                 if (!$name) {
                     continue;
                 }
                 $total_number_of_catalogs++;
                 $subCategory = $helper->getCategory($name, true, $category);
                 if (!$subCategory && !$subCategory->getId()) {
                     $this->notice("Can't create catalogue '{$catalog['title']}/{$name}'");
                     $number_of_not_created_catalogues++;
                     continue;
                 }
                 $this->notice("Catalogue '{$catalog['title']}/{$name}' was created sucessfully");
                 $number_of_created_catalogues++;
             }
         }
         $this->notice("Catalogue '{$catalog['title']}' was created sucessfully");
         $number_of_created_catalogues++;
     }
     $this->notice("Total number of catalogs: {$total_number_of_catalogs}");
     $this->notice("Number of ignored catalogs: {$number_of_ignored_catalogs}");
     $this->notice("Number of created catalogues: {$number_of_created_catalogues}");
     $this->notice("Number of not created catalogues: {$number_of_not_created_catalogues}");
 }