/** * Migrates data from old format to new one. * @param array $orders * @return bool migration product status: success or not */ public function migrate($orders) { $wpdb = $this->wp->getWPDB(); // Open transaction for save migration products $var_autocommit_sql = $wpdb->get_var("SELECT @@AUTOCOMMIT"); try { $this->checkSql(); $wpdb->query("SET AUTOCOMMIT=0"); $this->checkSql(); $wpdb->query("START TRANSACTION"); $this->checkSql(); // Register order status taxonomy to fetch old statuses $this->wp->registerTaxonomy('shop_order_status', array('shop_order'), array('hierarchical' => true, 'update_count_callback' => '_update_post_term_count', 'labels' => array('name' => __('Order statuses', 'jigoshop'), 'singular_name' => __('Order status', 'jigoshop'), 'search_items' => __('Search Order statuses', 'jigoshop'), 'all_items' => __('All Order statuses', 'jigoshop'), 'parent_item' => __('Parent Order status', 'jigoshop'), 'parent_item_colon' => __('Parent Order status:', 'jigoshop'), 'edit_item' => __('Edit Order status', 'jigoshop'), 'update_item' => __('Update Order status', 'jigoshop'), 'add_new_item' => __('Add New Order status', 'jigoshop'), 'new_item_name' => __('New Order status Name', 'jigoshop')), 'public' => false, 'show_ui' => false, 'show_in_nav_menus' => false, 'query_var' => true, 'rewrite' => false)); for ($i = 0, $endI = count($orders); $i < $endI;) { $order = $orders[$i]; // Update central order data $status = $this->wp->getTheTerms($order->ID, 'shop_order_status'); $this->checkSql(); if (!empty($status)) { $status = $this->_transformStatus($status[0]->slug); } else { $status = Status::PENDING; } $query = $wpdb->prepare("UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d", $status, $order->ID); $wpdb->query($query); $this->checkSql(); $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'number', $order->ID)); $this->checkSql(); $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'updated_at', time())); $this->checkSql(); // Update columns do { switch ($orders[$i]->meta_key) { case '_js_completed_date': $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_key = %s, meta_value = %d WHERE meta_id = %d", 'completed_at', strtotime($orders[$i]->meta_value), $orders[$i]->meta_id)); $this->checkSql(); break; case 'order_key': $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_key = %s WHERE meta_id = %d", 'key', $orders[$i]->meta_id)); $this->checkSql(); break; case 'order_data': $data = unserialize($orders[$i]->meta_value); $data = $this->_fetchOrderData($data); // Migrate customer if ($this->customer == null) { $customer = $this->wp->getPostMeta($order->ID, 'customer', true); $this->customer = $customer; } $this->customer = $this->_migrateCustomer($this->customer, $data); $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'customer', serialize(serialize($this->customer)))); $this->checkSql(); // Migrate coupons $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'coupons', serialize($data['order_discount_coupons']))); // TODO: HERE $this->checkSql(); // Migrate shipping method try { $method = $this->shippingService->get($data['shipping_method']); $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'shipping', serialize(array('method' => $method->getState(), 'price' => $data['order_shipping'], 'rate' => '')))); $this->checkSql(); } catch (Exception $e) { $this->messages->addWarning(sprintf(__('Shipping method "%s" not found. Order with ID "%d" has no shipping method now.'), $data['shipping_method'], $order->ID)); } // Migrate payment method try { $method = $this->paymentService->get($data['payment_method']); $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'payment', $method->getId())); $this->checkSql(); } catch (Exception $e) { $this->messages->addWarning(sprintf(__('Payment method "%s" not found. Order with ID "%d" has no payment method now.'), $data['payment_method'], $order->ID)); } // Migrate order totals $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'subtotal', $data['order_subtotal'])); $this->checkSql(); $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'discount', $data['order_discount'])); $this->checkSql(); $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'total', $data['order_total'])); $this->checkSql(); // TODO: Add new meta for shipping total price /*$wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", $order->ID, 'shipping', $data['order_shipping'] )); $this->checkSql();*/ break; case 'customer_user': if ($this->customer == null) { $customer = $this->wp->getPostMeta($order->ID, 'customer', true); if ($customer !== false) { /** @var Customer $customer */ $customer = maybe_unserialize(maybe_unserialize($customer)); if (!$customer) { $customer = new Customer(); } } else { $customer = new Customer(); } $this->customer = $customer; } /** @var \WP_User $user */ if (($user = $this->wp->getUserBy('id', $orders[$i]->meta_value)) !== false) { $this->checkSql(); $this->customer->setId($user->ID); $this->customer->setLogin($user->get('login')); $this->customer->setEmail($user->get('user_email')); $this->customer->setName($user->get('display_name')); $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = %d WHERE post_id = %d AND meta_key = %s", serialize(serialize($this->customer)), $orders[$i]->meta_id, 'customer')); $this->checkSql(); $userId = $orders[$i]->meta_value; } else { $userId = 0; $guest = new Customer\Guest(); $guest->setBillingAddress($this->customer->getBillingAddress()); $guest->setShippingAddress($this->customer->getShippingAddress()); $this->customer = $guest; } $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %d)", $order->ID, 'customer_id', $userId)); break; case 'order_items': $data = unserialize($orders[$i]->meta_value); $globalTaxRate = 0.0; foreach ($data as $itemData) { /** @var Product $product */ $itemData = $this->_fetchItemData($itemData); $product = null; $productGetId = null; if ($wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE ID = %d", $itemData['id'])) > 0) { $product = $this->productService->find($itemData['id']); $productGetId = $product->getId(); } $tax = 0.0; $taxRate = 0; if ($itemData['qty'] == 0) { $itemData['qty'] = 1; } $price = $itemData['cost'] / $itemData['qty']; if (!empty($itemData['taxrate']) && $itemData['taxrate'] > 0) { $tax = $price * $itemData['taxrate'] / 100; $taxRate = $itemData['taxrate']; } else { if (isset($itemData['cost_inc_tax']) && $itemData['cost'] < $itemData['cost_inc_tax']) { $tax = ($itemData['cost_inc_tax'] - $itemData['cost']) / $itemData['qty']; $taxRate = $tax / $itemData['cost']; } } $globalTaxRate += $taxRate; $productGetType = false; if ($productGetId == null) { if (isset($itemData['variation_id']) && !empty($itemData['variation_id'])) { $productGetType = Product\Variable::TYPE; } else { $productGetType = Product\Simple::TYPE; } } else { $productGetType = $product->getType(); } $insertOrderData = array('order_id' => $order->ID, 'product_type' => $productGetType, 'title' => $itemData['name'], 'price' => $price, 'tax' => $tax, 'quantity' => $itemData['qty'], 'cost' => $itemData['cost']); if ($productGetId != null) { $insertOrderData['product_id'] = $productGetId; } $wpdb->insert($wpdb->prefix . 'jigoshop_order_item', $insertOrderData); $this->checkSql(); $itemId = $wpdb->insert_id; if (isset($itemData['variation_id']) && !empty($itemData['variation_id']) && ($productGetId == null || $product instanceof Product\Variable)) { $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}jigoshop_order_item_meta (item_id, meta_key, meta_value) VALUES (%d, %s, %s)", $itemId, 'variation_id', $itemData['variation_id'])); $this->checkSql(); if ($productGetId !== null) { /** @var Product\Variable\Variation $variationProduct */ /** @var Product\Variable $product */ $variationProduct = $product->getVariation($itemData['variation_id']); if (is_array($itemData['variation']) && $variationProduct && $variationProduct instanceof Product\Variable\Variation) { foreach ($itemData['variation'] as $variation => $variationValue) { $variation = str_replace('tax_', '', $variation); $attribute = $this->getAttribute($variationProduct, $variation); if ($attribute === null) { $this->messages->addWarning(sprintf(__('Attribute "%s" not found for variation ID "%d".', 'jigoshop'), $variation, $variationProduct->getId())); continue; } $option = $this->getAttributeOption($attribute, $variationValue); if ($option === null) { $this->messages->addWarning(sprintf(__('Attribute "%s" option "%s" not found for variation ID "%d".', 'jigoshop'), $variation, $variationValue, $variationProduct->getId())); continue; } $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}jigoshop_order_item_meta (item_id, meta_key, meta_value) VALUES (%d, %s, %s)", $itemId, $attribute->getAttribute()->getId(), $option->getId())); $this->checkSql(); } } } } } $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->prefix}jigoshop_order_tax (order_id, label, tax_class, rate, is_compound) VALUES (%d, %s, %s, %d, %d)", $order->ID, __('Standard', 'jigoshop'), 'standard', $globalTaxRate / (count($data) == 0 ? 1 : count($data)), false)); $this->checkSql(); break; } $i++; } while ($i < $endI && $orders[$i]->ID == $order->ID); } // commit sql transation and restore value of autocommit $wpdb->query("COMMIT"); $wpdb->query("SET AUTOCOMMIT=" . $var_autocommit_sql); return true; } catch (Exception $e) { // rollback sql transation and restore value of autocommit if (WP_DEBUG) { \Monolog\Registry::getInstance(JIGOSHOP_LOGGER)->addDebug($e); } $wpdb->query("ROLLBACK"); $wpdb->query("SET AUTOCOMMIT=" . $var_autocommit_sql); Migration::saveLog(__('Migration orders end with error: ', 'jigoshop') . $e); return false; } }
/** * Migrates data from old format to new one. * @param array $products * @return bool migration product status: success or not */ public function migrate($products) { $wpdb = $this->wp->getWPDB(); // Open transaction for save migration products $var_autocommit_sql = $wpdb->get_var("SELECT @@AUTOCOMMIT"); try { $this->checkSql(); $wpdb->query("SET AUTOCOMMIT=0"); $this->checkSql(); $wpdb->query("START TRANSACTION"); $this->checkSql(); // Register product type taxonomy to fetch old product types $this->wp->registerTaxonomy('product_type', array('product'), array('hierarchical' => false, 'show_ui' => false, 'query_var' => true, 'show_in_nav_menus' => false)); $this->checkSql(); if ($this->wp->getOption('jigoshop_migration_product_first', false) == false) { // Update product_cat into product_category $wpdb->query($wpdb->prepare("UPDATE {$wpdb->term_taxonomy} SET taxonomy = %s WHERE taxonomy = %s", array('product_category', 'product_cat'))); $this->checkSql(); $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = %s WHERE meta_key = %s AND meta_value = %s", array('product_category', '_menu_item_object', 'product_cat'))); $this->checkSql(); foreach ($wpdb->get_results("SELECT * FROM {$wpdb->prefix}jigoshop_termmeta", ARRAY_A) as $termMeta) { $wpdb->insert($wpdb->prefix . 'jigoshop_term_meta', $termMeta); } $this->wp->updateOption('jigoshop_migration_product_first', true); } $productIds = array(); $attributes = array(); $productAttributes = array(); $globalAttributes = array(); foreach ($wpdb->get_results("SELECT * FROM {$wpdb->prefix}jigoshop_attribute_taxonomies") as $attribute) { $this->checkSql(); $globalAttributes[$this->wp->getHelpers()->sanitizeTitle($attribute->attribute_name)] = $attribute; } foreach ($wpdb->get_results("SELECT id AS attribute_id, slug AS attribute_name, label AS attribute_label, type AS attribute_type FROM {$wpdb->prefix}jigoshop_attribute") as $attribute) { $this->checkSql(); $globalAttributes[$attribute->attribute_name] = $attribute; } for ($i = 0, $endI = count($products); $i < $endI;) { $product = $products[$i]; $productIds[] = $product->ID; $productAttributes[$product->ID] = array('attributes' => array(), 'variations' => array()); // Add product types $types = $this->wp->getTheTerms($product->ID, 'product_type'); $this->checkSql(); $productType = Product\Simple::TYPE; if (is_array($types)) { if (!in_array($types[0]->slug, array(Product\Simple::TYPE, Product\Virtual::TYPE, Product\Downloadable::TYPE, Product\External::TYPE, Product\Variable::TYPE))) { Migration::saveLog(sprintf(__('We detected a product <a href="%s" target="_blank">(#%d) %s </a> of type "subscription" - this type is not supported by Jigoshop without an additional plugin. We changed its type to "simple" and set it as private.', 'jigoshop'), get_permalink($product->ID), $product->ID, get_the_title($product->ID), $types[0]->slug)); $wpdb->query($wpdb->prepare("UPDATE {$wpdb->posts} SET post_status = 'private' WHERE ID = %d", $product->ID)); $types[0]->slug = 'simple'; } $productType = $types[0]->slug; $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} VALUES (NULL, %d, %s, %s)", array($product->ID, 'type', $types[0]->slug))); $this->checkSql(); } $regularPrice = 0.0; $taxClasses = array(); // Update columns do { // Sales support if ($products[$i]->meta_key == 'sale_price' && !empty($products[$i]->meta_value)) { $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES (%d, %s, %s)", array($product->ID, 'sales_enabled', true))); $this->checkSql(); } // Product attributes support if ($products[$i]->meta_key == 'product_attributes') { $attributeData = unserialize($products[$i]->meta_value); if (is_array($attributeData)) { foreach ($attributeData as $slug => $source) { if (empty($source['value'])) { continue; } $changeLocalToGlobal = isset($source['variation']) && $source['variation'] == true && $source['is_taxonomy'] != true && $productType == Product\Variable::TYPE; $productAttributes[$product->ID]['attributes'][$slug] = array('is_visible' => $source['visible'], 'is_variable' => isset($source['variation']) && $source['variation'] == true, 'values' => $changeLocalToGlobal ? str_replace(',', '|', $source['value']) : $source['value']); if (!isset($attributes[$slug])) { $type = isset($globalAttributes[$slug]) ? $this->_getAttributeType($globalAttributes[$slug]) : Text::TYPE; if ($changeLocalToGlobal) { $type = Multiselect::TYPE; } $label = isset($globalAttributes[$slug]) ? !empty($globalAttributes[$slug]->attribute_label) ? $globalAttributes[$slug]->attribute_label : $globalAttributes[$slug]->attribute_name : $source['name']; $attribute = $this->productService->createAttribute($type); $attribute->setSlug($slug); $attribute->setLabel($label); $attribute->setLocal($source['is_taxonomy'] != true && $changeLocalToGlobal != true); if ($changeLocalToGlobal) { foreach (explode('|', $productAttributes[$product->ID]['attributes'][$slug]['values']) as $attributeOption) { $option = new Option(); $option->setLabel($attributeOption); $option->setValue(sanitize_title($attributeOption)); $attribute->addOption($option); } $productAttributes[$product->ID]['attributes'][$slug]['values'] = array_map(function ($item) { return sanitize_title($item); }, explode('|', $productAttributes[$product->ID]['attributes'][$slug]['values'])); } $attributes[$slug] = $attribute; } } } } // Product variation data if ($products[$i]->meta_key == 'variation_data') { $variations = unserialize($products[$i]->meta_value); foreach ($variations as $variation => $value) { $productAttributes[$product->ID]['variations'][str_replace('tax_', '', $variation)] = sanitize_title($value); } } $key = $this->_transformKey($products[$i]->meta_key); if ($key !== null) { $value = $this->_transform($products[$i]->meta_key, $products[$i]->meta_value); if ($key == 'regular_price') { $regularPrice = $value; } if ($key == 'tax_classes') { $taxClasses = $value; } $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = %s, meta_key = %s WHERE meta_id = %d", array($value, $key, $products[$i]->meta_id))); $this->checkSql(); } $i++; } while ($i < $endI && $products[$i]->ID == $product->ID); // Update regular price if it includes tax if (!empty($this->taxes)) { $taxClasses = maybe_unserialize($taxClasses); foreach ($taxClasses as $taxClass) { if (isset($this->taxes['__compound__' . $taxClass])) { $regularPrice = $regularPrice / (100 + $this->taxes['__compound__' . $taxClass]['rate']) * 100; } } foreach ($taxClasses as $taxClass) { if (isset($this->taxes[$taxClass])) { $regularPrice = $regularPrice / (100 + $this->taxes[$taxClass]['rate']) * 100; } } $wpdb->query($wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = %s WHERE meta_key = %s AND post_id = %d", array($regularPrice, 'regular_price', $product->ID))); $this->checkSql(); } } foreach ($globalAttributes as $slug => $attributeData) { if (isset($attributes[$slug])) { continue; } $type = $this->_getAttributeType($attributeData); $label = !empty($attributeData->attribute_label) ? $attributeData->attribute_label : $attributeData->attribute_name; $attribute = $this->productService->createAttribute($type); $attribute->setSlug($slug); $attribute->setLabel($label); $attribute->setLocal(false); $attributes[$slug] = $attribute; } foreach ($attributes as $slug => $attribute) { /** @var $attribute Product\Attribute */ $antiDuplicateAttributes = unserialize($this->wp->getOption('jigoshop_attributes_anti_duplicate', serialize(array()))); if (!isset($antiDuplicateAttributes[$attribute->getSlug()]) || $attribute->isLocal()) { if (!$attribute->isLocal()) { // Fetch options if attribute is a taxonomy $options = $wpdb->get_results("\n\t\t\t\t\t\tSELECT t.name, t.slug FROM {$wpdb->terms} t\n\t\t\t\t\t\t\tLEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = t.term_id\n\t\t\t\t\t\t WHERE tt.taxonomy = 'pa_{$slug}'\n\t\t\t\t \t "); $this->checkSql(); $createdOptions = array(); foreach ($options as $source) { $option = new Option(); $option->setLabel($source->name); $option->setValue($source->slug); $attribute->addOption($option); $createdOptions[] = $source->slug; } } $this->productService->saveAttribute($attribute); $this->checkSql(); if (!$attribute->isLocal()) { $antiDuplicateAttributes[$attribute->getSlug()] = $attribute->getId(); $this->wp->updateOption('jigoshop_attributes_anti_duplicate', serialize($antiDuplicateAttributes)); $this->checkSql(); } } else { //merge attributes $attribute = $this->productService->getAttribute($antiDuplicateAttributes[$attribute->getSlug()]); if ($attribute instanceof Product\Attribute) { $savedOptions = array_map(function ($item) { return $item->getValue(); }, $attribute->getOptions()); foreach ($attributes[$slug]->getOptions() as $option) { if (!in_array($option->getValue(), $savedOptions)) { $attribute->addOption($option); } } $attributes[$slug] = $attribute; $this->productService->saveAttribute($attribute); } } // Add attribute to the products if ($attribute instanceof Product\Attribute) { foreach ($productIds as $id) { if (isset($productAttributes[$id]['attributes'][$attribute->getSlug()])) { $data = $productAttributes[$id]['attributes'][$attribute->getSlug()]; $value = array(); if (is_array($data['values'])) { foreach ($attribute->getOptions() as $option) { /** @var $option Option */ if (in_array($option->getValue(), $data['values'])) { $value[] = $option->getId(); } } } if (empty($value)) { $value = $data['values']; } $wpdb->insert($wpdb->prefix . 'jigoshop_product_attribute', array('product_id' => $id, 'attribute_id' => $attribute->getId(), 'value' => is_array($value) ? join('|', $value) : $value)); $this->checkSql(); $query = array('product_id' => $id, 'attribute_id' => $attribute->getId(), 'meta_key' => 'is_visible', 'meta_value' => $data['is_visible']); $wpdb->insert($wpdb->prefix . 'jigoshop_product_attribute_meta', $query); $this->checkSql(); if ($data['is_variable']) { $query = array('product_id' => $id, 'attribute_id' => $attribute->getId(), 'meta_key' => 'is_variable', 'meta_value' => true); $wpdb->insert($wpdb->prefix . 'jigoshop_product_attribute_meta', $query); $this->checkSql(); } } } } } foreach ($productIds as $id) { foreach ($productAttributes[$id]['variations'] as $taxonomy => $value) { if (!isset($attributes[$taxonomy])) { continue; } $attribute = $attributes[$taxonomy]; $option = $this->_findOption($attribute->getOptions(), $value); $query = array('variation_id' => $id, 'attribute_id' => $attribute->getId(), 'value' => $option); $wpdb->insert($wpdb->prefix . 'jigoshop_product_variation_attribute', $query); $this->checkSql(); } } // Add found tax classes $currentTaxClasses = $this->options->get('tax.classes'); $currentTaxClassesKeys = array_map(function ($item) { return $item['class']; }, $currentTaxClasses); $this->taxClasses = array_filter(array_unique($this->taxClasses), function ($item) use($currentTaxClassesKeys) { return !in_array($item, $currentTaxClassesKeys); }); foreach ($this->taxClasses as $class) { $currentTaxClasses[] = array('label' => ucfirst($class), 'class' => $class); } $this->options->update('tax.classes', $currentTaxClasses); // commit sql transation and restore value of autocommit $wpdb->query("COMMIT"); $wpdb->query("SET AUTOCOMMIT=" . $var_autocommit_sql); return true; } catch (Exception $e) { // rollback sql transation and restore value of autocommit if (WP_DEBUG) { \Monolog\Registry::getInstance(JIGOSHOP_LOGGER)->addDebug($e); } $wpdb->query("ROLLBACK"); $wpdb->query("SET AUTOCOMMIT=" . $var_autocommit_sql); Migration::saveLog(__('Migration products end with error: ', 'jigoshop') . $e); return false; } }
public function addTaxonomy(Taxonomy $taxonomy) { $this->taxonomies[] = $taxonomy; $this->wp->registerTaxonomy($taxonomy->getName(), $taxonomy->getPostTypes(), $taxonomy->getDefinition()); }