Plugin Directory

Changeset 1912126


Ignore:
Timestamp:
07/20/2018 10:47:08 AM (8 years ago)
Author:
alexwing
Message:
  • Fix import orders status to wc-completed
  • Fix import category images url
Location:
woo-oscommerce-sync/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • woo-oscommerce-sync/trunk/readme.txt

    r1907590 r1912126  
    55Requires at least: 3.5.1
    66Tested up to: 4.9.4–es_ES
    7 Stable tag: 2.0.3
     7Stable tag: 2.0.4
    88License: AGPLv3.0 or later
    99License URI: http://opensource.org/licenses/AGPL-3.0
     
    7070
    7171== Changelog ==
     72= 2.0.4 =
     73* Add field for custom images directory on osCommerce
     74* Fix debug mode on images delete
     75
    7276= 2.0.3 =
    7377* Fix import orders status to wc-completed
  • woo-oscommerce-sync/trunk/woocommerce-osc-sync.php

    r1907590 r1912126  
    1616
    1717function otw_plugin_scripts() {
    18      if (is_admin()) {
    19           wp_enqueue_script('admin_js_bootstrap', plugins_url('js/bootstrap.min.js', __FILE__), false, '3.3.7', false);
    20           wp_enqueue_style('admin_css_bootstrap', plugins_url('css/bootstrap.min.css', __FILE__), true, '3.3.7', 'all');
    21      }
     18    if (is_admin()) {
     19        wp_enqueue_script('admin_js_bootstrap', plugins_url('js/bootstrap.min.js', __FILE__), false, '3.3.7', false);
     20        wp_enqueue_style('admin_css_bootstrap', plugins_url('css/bootstrap.min.css', __FILE__), true, '3.3.7', 'all');
     21    }
    2222}
    2323
     
    2525if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    2626
    27      function otw_submenu_page() {
    28           add_submenu_page('woocommerce', 'osCommerce Sync', 'osCommerce Sync', 'manage_options', 'woocommerce-osc-sync', 'otw_submenu_page_callback');
    29      }
    30 
    31      function otw_cartesian_product($a) {
    32           $result = array(array());
    33           foreach ($a as $k => $list) {
    34                $_tmp = array();
    35                foreach ($result as $result_item) {
    36                     foreach ($list as $list_item) {
    37                          $_tmp[] = array_merge($result_item, array($k => $list_item));
    38                     }
    39                }
    40                $result = $_tmp;
    41           }
    42           return $result;
    43      }
    44 
    45      function otw_import_image($url) {
    46           $attach_id = 0;
    47           $wp_upload_dir = wp_upload_dir();
    48 
    49           $filename = $wp_upload_dir['path'] . '/' . sanitize_file_name(basename($url));
    50 
    51           if (file_exists($filename)) {
    52                $url = $filename;
    53           } else {
    54                //Encode the URL
    55                $base = basename($url);
    56                $url = str_replace($base, urlencode($base), $url);
    57           }
    58 
    59           if ($f = @file_get_contents($url)) {
    60                file_put_contents($filename, $f);
    61 
    62                $wp_filetype = wp_check_filetype(basename($filename), null);
    63 
    64                $attachment = array(
    65                    'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
    66                    'post_mime_type' => $wp_filetype['type'],
    67                    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
    68                    'post_content' => '',
    69                    'post_status' => 'inherit'
    70                );
    71                $attach_id = wp_insert_attachment($attachment, $filename, 37);
    72                require_once(ABSPATH . 'wp-admin/includes/image.php');
    73                $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
    74                wp_update_attachment_metadata($attach_id, $attach_data);
    75           }
    76           return $attach_id;
    77      }
    78 
    79      function otw_run_cats($parent = 0, $parent_term_id = 0) {
    80           global $wpdb, $lang, $oscdb, $import_cat_counter;
    81 
    82 
    83           $sql = "SELECT c.*,
     27    function otw_submenu_page() {
     28        add_submenu_page('woocommerce', 'osCommerce Sync', 'osCommerce Sync', 'manage_options', 'woocommerce-osc-sync', 'otw_submenu_page_callback');
     29    }
     30
     31    function otw_cartesian_product($a) {
     32        $result = array(array());
     33        foreach ($a as $k => $list) {
     34            $_tmp = array();
     35            foreach ($result as $result_item) {
     36                foreach ($list as $list_item) {
     37                    $_tmp[] = array_merge($result_item, array($k => $list_item));
     38                }
     39            }
     40            $result = $_tmp;
     41        }
     42        return $result;
     43    }
     44
     45    function otw_import_image($url) {
     46        $attach_id = 0;
     47        $wp_upload_dir = wp_upload_dir();
     48
     49        $filename = $wp_upload_dir['path'] . '/' . sanitize_file_name(basename($url));
     50
     51        if (file_exists($filename)) {
     52            $url = $filename;
     53        } else {
     54            //Encode the URL
     55            $base = basename($url);
     56            $url = str_replace($base, urlencode($base), $url);
     57        }
     58
     59        if ($f = @file_get_contents($url)) {
     60            file_put_contents($filename, $f);
     61
     62            $wp_filetype = wp_check_filetype(basename($filename), null);
     63
     64            $attachment = array(
     65                'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
     66                'post_mime_type' => $wp_filetype['type'],
     67                'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
     68                'post_content' => '',
     69                'post_status' => 'inherit'
     70            );
     71            $attach_id = wp_insert_attachment($attachment, $filename, 37);
     72            require_once(ABSPATH . 'wp-admin/includes/image.php');
     73            $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
     74            wp_update_attachment_metadata($attach_id, $attach_data);
     75        }
     76        return $attach_id;
     77    }
     78
     79    function otw_run_cats($parent = 0, $parent_term_id = 0) {
     80        global $wpdb, $lang, $oscdb, $import_cat_counter;
     81
     82
     83        $sql = "SELECT c.*,
    8484               cd.*
    8585               FROM categories c,
    8686               categories_description cd
    8787               WHERE c.categories_id=cd.categories_id " . $lang . " AND c.parent_id='" . (int) $parent . "'";
    88           //otw_log("importCategories", "Sql: " . $sql);
    89           $categories = $oscdb->get_results($sql, ARRAY_A);
    90           if (!empty($categories)) {
    91                otw_log("importCategories", "Categories total: " . count($categories));
    92                foreach ($categories as $category) {
    93                     if (!is_wp_error($category)) {
    94                          $term = term_exists($category['categories_name'], 'product_cat', (int) $parent_term_id); // array is returned if taxonomy is given
    95                          if ((int) $term['term_id'] == 0) {
    96                               otw_log("importCategories", "New Categorie: " . json_encode($category));
    97                               $term = wp_insert_term(
    98                                       $category['categories_name'], // the term
    99                                       'product_cat', // the taxonomy
    100                                       array(
    101                                   //'description'=> $category['categories_id'],
    102                                   'parent' => $parent_term_id
    103                                       )
    104                               );
    105                               delete_option('product_cat_children'); // clear the cache
    106 
    107                               $attach_id = 0;
    108                               if ($category['categories_image'] != '') {
    109                                    if (esc_url($_POST['store_url'])) {
    110                                         //otw_log("importCategories", "Image: " . rtrim($_POST['store_url'], '/') . '/image/' . urlencode($category['categories_image']));
    111                                         $url = rtrim($_POST['store_url'], '/') . '/image/' . urlencode($category['categories_image']);
    112                                         $attach_id = otw_import_image($url);
    113                                    }
    114                               }
    115                               add_woocommerce_term_meta($term['term_id'], 'order', $category['sort_order']);
    116                               add_woocommerce_term_meta($term['term_id'], 'display_type', '');
    117                               add_woocommerce_term_meta($term['term_id'], 'thumbnail_id', (int) $attach_id);
    118                               add_woocommerce_term_meta($term['term_id'], 'osc_id', $category['categories_id']);
    119                               otw_run_cats($category['categories_id'], $term['term_id']);
    120                               $import_cat_counter ++;
    121                          } else {
    122                               otw_log("importCategories", "Edit Categorie: " . json_encode($category));
    123                               otw_run_cats($category['categories_id'], $term['term_id']);
    124                          }
    125                     }
    126                }
    127           }
    128      }
    129 
    130      function otw_submenu_page_callback() {
    131           global $debug, $output, $wpdb, $oscdb, $lang, $import_cat_counter, $import_prod_counter, $import_img_counter, $import_gallery_counter;
    132 
    133           if (isset($_POST['sync_submit']) && wp_verify_nonce($_POST['sync_submit'], 'otw_sync') && !empty($_POST)) {
    134                if (isset($_POST['debug'])) {
    135                     $debug = true;
    136                } else {
    137                     $debug = false;
    138                }
    139                if (isset($_POST['lang'])) {
    140                     if (!empty($_POST['lang'])) {
    141                          $lang = ' AND language_id=' . (int) sanitize_text_field($_POST['lang']);
     88        //otw_log("importCategories", "Sql: " . $sql);
     89        $categories = $oscdb->get_results($sql, ARRAY_A);
     90        if (!empty($categories)) {
     91            otw_log("importCategories", "Categories total: " . count($categories));
     92            foreach ($categories as $category) {
     93                if (!is_wp_error($category)) {
     94                    $term = term_exists($category['categories_name'], 'product_cat', (int) $parent_term_id); // array is returned if taxonomy is given
     95                    if ((int) $term['term_id'] == 0) {
     96                        otw_log("importCategories", "New Categorie: " . json_encode($category));
     97                        $term = wp_insert_term(
     98                                $category['categories_name'], // the term
     99                                'product_cat', // the taxonomy
     100                                array(
     101                            //'description'=> $category['categories_id'],
     102                            'parent' => $parent_term_id
     103                                )
     104                        );
     105                        delete_option('product_cat_children'); // clear the cache
     106
     107                        $attach_id = 0;
     108                        if ($category['categories_image'] != '') {
     109                            if (esc_url($_POST['store_url'])) {
     110
     111                                if (!empty($_POST['images_url'])) {
     112                                    //otw_log("importCategories", "Image: " . rtrim($_POST['store_url'], '/') . '/image/' . urlencode($category['categories_image']));
     113                                    $url = rtrim($_POST['store_url'], '/') . '/' . rtrim($_POST['store_url'], '/') . '/' . urlencode($category['categories_image']);
     114                                } else {                                                                                   //otw_log("importCategories", "Image: " . rtrim($_POST['store_url'], '/') . '/image/' . urlencode($category['categories_image']));
     115                                    $url = rtrim($_POST['store_url'], '/') . '/image/' . urlencode($category['categories_image']);
     116                                }
     117
     118                                $attach_id = otw_import_image($url);
     119                            }
     120                        }
     121                        add_woocommerce_term_meta($term['term_id'], 'order', $category['sort_order']);
     122                        add_woocommerce_term_meta($term['term_id'], 'display_type', '');
     123                        add_woocommerce_term_meta($term['term_id'], 'thumbnail_id', (int) $attach_id);
     124                        add_woocommerce_term_meta($term['term_id'], 'osc_id', $category['categories_id']);
     125                        otw_run_cats($category['categories_id'], $term['term_id']);
     126                        $import_cat_counter ++;
    142127                    } else {
    143                          $lang = ' AND language_id=3';
    144                     }
    145                } else {
     128                        otw_log("importCategories", "Edit Categorie: " . json_encode($category));
     129                        otw_run_cats($category['categories_id'], $term['term_id']);
     130                    }
     131                }
     132            }
     133        }
     134    }
     135
     136    function otw_submenu_page_callback() {
     137        global $debug, $output, $wpdb, $oscdb, $lang, $import_cat_counter, $import_prod_counter, $import_img_counter, $import_gallery_counter;
     138
     139        if (isset($_POST['sync_submit']) && wp_verify_nonce($_POST['sync_submit'], 'otw_sync') && !empty($_POST)) {
     140            if (isset($_POST['debug'])) {
     141                $debug = true;
     142            } else {
     143                $debug = false;
     144            }
     145            if (isset($_POST['lang'])) {
     146                if (!empty($_POST['lang'])) {
     147                    $lang = ' AND language_id=' . (int) sanitize_text_field($_POST['lang']);
     148                } else {
    146149                    $lang = ' AND language_id=3';
    147                }
    148 
    149                $oscdb = new wpdb(sanitize_text_field(trim($_POST['store_user'])), trim(sanitize_text_field($_POST['store_pass'])), trim(sanitize_text_field($_POST['store_dbname'])), trim(sanitize_text_field($_POST['store_host'])));
    150                if ($oscdb->ready) {
    151                     ob_start();
    152                     // echo '<p>Starting...<em>(If the page stops loading or shows a timeout error, then just refresh the page and the importer will continue where it left off.  If you are using a shared server and are importing a lot of products you may need to refresh several times)</p>';
    153                     // Do customer import
    154 
    155                     if ((int) $_POST['dtype']['customers'] == 1) {
    156                          otw_log_delete("importCustomer");
    157                          otw_log("importCustomer", "Start Import");
    158                          $country_data = $oscdb->get_results("SELECT * FROM countries", ARRAY_A);
    159                          $countries_id = array();
    160                          foreach ($country_data as $cdata) {
    161                               $countries_id[$cdata['countries_id']] = $cdata;
    162                          }
    163                          $zones = array();
    164                          $zone_data = $oscdb->get_results("SELECT zone_id, zone_code FROM zones", ARRAY_A);
    165                          foreach ($zone_data as $z) {
    166                               $zones[$z['zone_id']] = $z['zone_code'];
    167                          }
    168                          $sql = "SELECT c.customers_id,
     150                }
     151            } else {
     152                $lang = ' AND language_id=3';
     153            }
     154
     155            $oscdb = new wpdb(sanitize_text_field(trim($_POST['store_user'])), trim(sanitize_text_field($_POST['store_pass'])), trim(sanitize_text_field($_POST['store_dbname'])), trim(sanitize_text_field($_POST['store_host'])));
     156            if ($oscdb->ready) {
     157                ob_start();
     158                // echo '<p>Starting...<em>(If the page stops loading or shows a timeout error, then just refresh the page and the importer will continue where it left off.  If you are using a shared server and are importing a lot of products you may need to refresh several times)</p>';
     159                // Do customer import
     160
     161                if ((int) $_POST['dtype']['customers'] == 1) {
     162                    otw_log_delete("importCustomer");
     163                    otw_log("importCustomer", "Start Import");
     164                    $country_data = $oscdb->get_results("SELECT * FROM countries", ARRAY_A);
     165                    $countries_id = array();
     166                    foreach ($country_data as $cdata) {
     167                        $countries_id[$cdata['countries_id']] = $cdata;
     168                    }
     169                    $zones = array();
     170                    $zone_data = $oscdb->get_results("SELECT zone_id, zone_code FROM zones", ARRAY_A);
     171                    foreach ($zone_data as $z) {
     172                        $zones[$z['zone_id']] = $z['zone_code'];
     173                    }
     174                    $sql = "SELECT c.customers_id,
    169175                              c.customers_firstname,
    170176                              c.customers_lastname,
     
    183189                              INNER JOIN address_book ab ON  c.customers_id=ab.customers_id AND c.customers_default_address_id=ab.address_book_id
    184190                              ";
    185                          if ($customers = $oscdb->get_results($sql, ARRAY_A)) {
    186                               otw_log("importCustomer", "Customers total: " . count($customers));
    187                               foreach ($customers as $customer) {
    188                                    otw_log("importCustomer", "Customer import: " . json_encode($customer));
    189                                    if (!email_exists($customer['customers_email_address'])) {
    190                                         $original = strtolower(preg_replace("/[^A-Za-z0-9]/", '', $customer['customers_firstname'] . $customer['customers_lastname']));
    191                                         $user_name = $original;
    192 
    193                                         $i = 1;
    194                                         while ($user_id = username_exists($user_name)) {
    195                                              $user_name = $original . $i;
    196                                              $i++;
    197                                         }
    198 
    199                                         $random_password = wp_generate_password();
    200                                         $user_id = wp_create_user($user_name, $random_password, $customer['customers_email_address']);
    201 
    202                                         $data = array('first_name' => $customer['customers_firstname'],
    203                                             'last_name' => $customer['customers_lastname'],
    204                                             'billing_country' => $countries_id[$customer['entry_country_id']]['countries_iso_code_2'],
    205                                             'billing_first_name' => $customer['entry_firstname'],
    206                                             'billing_last_name' => $customer['entry_lastname'],
    207                                             'billing_address_1' => $customer['entry_street_address'],
    208                                             'billing_address_2' => $customer['entry_suburb'],
    209                                             'billing_city' => $customer['entry_city'],
    210                                             'billing_state' => ($customer['entry_state'] != '' ? $customer['entry_state'] : $zones[$customer['entry_zone_id']]),
    211                                             'billing_postcode' => $customer['entry_postcode'],
    212                                             'billing_email' => $customer['customers_email_address'],
    213                                             'billing_phone' => $customer['customers_telephone'],
    214                                             'shipping_country' => $countries_id[$customer['entry_country_id']]['countries_iso_code_2'],
    215                                             'shipping_first_name' => $customer['entry_firstname'],
    216                                             'shipping_last_name' => $customer['entry_lastname'],
    217                                             'shipping_address_1' => $customer['entry_street_address'],
    218                                             'shipping_address_2' => $customer['entry_suburb'],
    219                                             'shipping_city' => $customer['entry_city'],
    220                                             'shipping_state' => ($customer['entry_state'] != '' ? $customer['entry_state'] : $zones[$customer['entry_zone_id']]),
    221                                             'shipping_postcode' => $customer['entry_postcode'],
    222                                             'osc_id' => $customer['customers_id']);
    223                                         foreach ($data as $k => $v) {
    224                                              update_user_meta($user_id, $k, $v);
    225                                         }
    226 
    227                                         if ($user_id > 1) {
    228                                              wp_update_user(array('ID' => $user_id, 'role' => 'customer'));
    229                                         }
    230 
    231                                         $import_customer_counter++;
    232                                    }
    233                               }
    234                          }
    235                          otw_log("importCustomer", "End Import");
    236                     }
    237                     if ((int) $_POST['dtype']['categories'] == 1) {
    238                          otw_log_delete("importCategories");
    239                          otw_log("importCategories", "Start Import");
    240                          otw_run_cats();
    241                          otw_log("importCategories", "End Import");
    242                     }
    243                     if ((int) $_POST['dtype']['products'] == 1) {
    244                          otw_log_delete("importProduct");
    245                          otw_log("importProduct", "Start Import");
    246                          otw_log("importProduct", "Lang: " . $lang);
    247 
    248                          if (isset($_POST['offset'])) {
    249                               $offset = (int) sanitize_text_field($_POST['offset']);
    250                          } else {
    251                               $offset = 0;
    252                          }
    253 
    254                          if (isset($_POST['limit'])) {
    255                               $limit = (int) sanitize_text_field($_POST['limit']);
    256                          } else {
    257                               $limit = 0;
    258                          }
    259                          //otw_run_cats();
    260                          // Get all categories by OSC cat ID
    261                          $categories = array();
    262                          $terms = get_terms('product_cat', array('hide_empty' => 0));
    263                          foreach ($terms as $term) {
    264                               $o = get_woocommerce_term_meta($term->term_id, 'osc_id', true);
    265                               $categories[$o] = (int) $term->term_id;
    266                          }
    267                          $sql = "
     191                    if ($customers = $oscdb->get_results($sql, ARRAY_A)) {
     192                        otw_log("importCustomer", "Customers total: " . count($customers));
     193                        foreach ($customers as $customer) {
     194                            otw_log("importCustomer", "Customer import: " . json_encode($customer));
     195                            if (!email_exists($customer['customers_email_address'])) {
     196                                $original = strtolower(preg_replace("/[^A-Za-z0-9]/", '', $customer['customers_firstname'] . $customer['customers_lastname']));
     197                                $user_name = $original;
     198
     199                                $i = 1;
     200                                while ($user_id = username_exists($user_name)) {
     201                                    $user_name = $original . $i;
     202                                    $i++;
     203                                }
     204
     205                                $random_password = wp_generate_password();
     206                                $user_id = wp_create_user($user_name, $random_password, $customer['customers_email_address']);
     207
     208                                $data = array('first_name' => $customer['customers_firstname'],
     209                                    'last_name' => $customer['customers_lastname'],
     210                                    'billing_country' => $countries_id[$customer['entry_country_id']]['countries_iso_code_2'],
     211                                    'billing_first_name' => $customer['entry_firstname'],
     212                                    'billing_last_name' => $customer['entry_lastname'],
     213                                    'billing_address_1' => $customer['entry_street_address'],
     214                                    'billing_address_2' => $customer['entry_suburb'],
     215                                    'billing_city' => $customer['entry_city'],
     216                                    'billing_state' => ($customer['entry_state'] != '' ? $customer['entry_state'] : $zones[$customer['entry_zone_id']]),
     217                                    'billing_postcode' => $customer['entry_postcode'],
     218                                    'billing_email' => $customer['customers_email_address'],
     219                                    'billing_phone' => $customer['customers_telephone'],
     220                                    'shipping_country' => $countries_id[$customer['entry_country_id']]['countries_iso_code_2'],
     221                                    'shipping_first_name' => $customer['entry_firstname'],
     222                                    'shipping_last_name' => $customer['entry_lastname'],
     223                                    'shipping_address_1' => $customer['entry_street_address'],
     224                                    'shipping_address_2' => $customer['entry_suburb'],
     225                                    'shipping_city' => $customer['entry_city'],
     226                                    'shipping_state' => ($customer['entry_state'] != '' ? $customer['entry_state'] : $zones[$customer['entry_zone_id']]),
     227                                    'shipping_postcode' => $customer['entry_postcode'],
     228                                    'osc_id' => $customer['customers_id']);
     229                                foreach ($data as $k => $v) {
     230                                    update_user_meta($user_id, $k, $v);
     231                                }
     232
     233                                if ($user_id > 1) {
     234                                    wp_update_user(array('ID' => $user_id, 'role' => 'customer'));
     235                                }
     236
     237                                $import_customer_counter++;
     238                            }
     239                        }
     240                    }
     241                    otw_log("importCustomer", "End Import");
     242                }
     243                if ((int) $_POST['dtype']['categories'] == 1) {
     244                    otw_log_delete("importCategories");
     245                    otw_log("importCategories", "Start Import");
     246                    otw_run_cats();
     247                    otw_log("importCategories", "End Import");
     248                }
     249                if ((int) $_POST['dtype']['products'] == 1) {
     250                    otw_log_delete("importProduct");
     251                    otw_log("importProduct", "Start Import");
     252                    otw_log("importProduct", "Lang: " . $lang);
     253
     254                    if (isset($_POST['offset'])) {
     255                        $offset = (int) sanitize_text_field($_POST['offset']);
     256                    } else {
     257                        $offset = 0;
     258                    }
     259
     260                    if (isset($_POST['limit'])) {
     261                        $limit = (int) sanitize_text_field($_POST['limit']);
     262                    } else {
     263                        $limit = 0;
     264                    }
     265                    //otw_run_cats();
     266                    // Get all categories by OSC cat ID
     267                    $categories = array();
     268                    $terms = get_terms('product_cat', array('hide_empty' => 0));
     269                    foreach ($terms as $term) {
     270                        $o = get_woocommerce_term_meta($term->term_id, 'osc_id', true);
     271                        $categories[$o] = (int) $term->term_id;
     272                    }
     273                    $sql = "
    268274                    SELECT p.*, pd.*,
    269275                     p2c.categories_id
     
    276282                   
    277283                    ";
    278                          if (!empty($limit)) {
    279                               $sql.= "LIMIT " . $limit . " OFFSET " . $offset;
    280                               otw_log("importProduct", "Offset: " . $offset . " Limit:" . $limit);
    281                          }
    282                          // Import the products
    283 
    284 
    285                          if ($products = $oscdb->get_results($sql, ARRAY_A)) {
    286                               otw_log("importProduct", "Products origin total: " . count($products));
    287                               foreach ($products as $product) {
    288 
    289                                    $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
    290                                        'meta_query' => array(
    291                                            array(
    292                                                'key' => 'osc_id',
    293                                                'value' => $product['products_id'],
    294                                            )
    295                                    )));
    296                                    //otw_log("importProduct", "exist".json_encode($existing_product));
    297                                    if (empty($existing_product) && !empty($product['products_name'])) {
    298                                         otw_log("importProduct", json_encode($product));
    299                                         $product_id = wp_insert_post(array(
    300                                             'post_title' => $product['products_name'],
    301                                             'post_content' => $product['products_description'],
     284                    if (!empty($limit)) {
     285                        $sql .= "LIMIT " . $limit . " OFFSET " . $offset;
     286                        otw_log("importProduct", "Offset: " . $offset . " Limit:" . $limit);
     287                    }
     288                    // Import the products
     289
     290
     291                    if ($products = $oscdb->get_results($sql, ARRAY_A)) {
     292                        otw_log("importProduct", "Products origin total: " . count($products));
     293                        foreach ($products as $product) {
     294
     295                            $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
     296                                'meta_query' => array(
     297                                    array(
     298                                        'key' => 'osc_id',
     299                                        'value' => $product['products_id'],
     300                                    )
     301                            )));
     302                            //otw_log("importProduct", "exist".json_encode($existing_product));
     303                            if (empty($existing_product) && !empty($product['products_name'])) {
     304                                otw_log("importProduct", json_encode($product));
     305                                $product_id = wp_insert_post(array(
     306                                    'post_title' => $product['products_name'],
     307                                    'post_content' => $product['products_description'],
     308                                    'post_status' => 'publish',
     309                                    'post_type' => 'product',
     310                                    'post_author' => 1
     311                                ));
     312                                update_post_meta($product_id, 'osc_id', $product['products_id']);
     313                                wp_set_object_terms($product_id, 'simple', 'product_type');
     314                                wp_set_object_terms($product_id, (int) $categories[$product['categories_id']], 'product_cat');
     315                                update_post_meta($product_id, '_sku', $product['products_model']);
     316                                update_post_meta($product_id, '_regular_price', $product['products_price']);
     317                                update_post_meta($product_id, '_price', $product['products_price']);
     318                                update_post_meta($product_id, '_visibility', 'visible');
     319                                update_post_meta($product_id, '_stock_status', ($product['products_status'] ? 'instock' : 'outofstock'));
     320                                update_post_meta($product_id, '_manage_stock', '1');
     321                                update_post_meta($product_id, '_stock', $product['products_quantity']);
     322                                $import_prod_counter++;
     323
     324                                if ($special = $oscdb->get_row("SELECT specials_new_products_price, expires_date FROM specials WHERE status=1 AND products_id='" . $product_id . "' LIMIT 1", ARRAY_A)) {
     325                                    update_post_meta($product_id, '_sale_price', $special['specials_new_products_price']);
     326                                    $special['expires_date'] = strtotime($special['expires_date']);
     327                                    if ($special['expires_date'] > time()) {
     328                                        update_post_meta($product_id, '_sale_price_dates_to', date("Y-m-d", $special['expires_date']));
     329                                        update_post_meta($product_id, '_sale_price_dates_from', date("Y-m-d"));
     330                                    }
     331                                }
     332                                /*
     333                                  $attach_id = 0;
     334                                  if($product['products_image'] != ''){
     335                                  $url = rtrim($_POST['store_url'],'/').'/images/'.urlencode($product['products_image']);
     336                                  $attach_id = otw_import_image($url);
     337                                  }
     338                                  if($attach_id > 0){
     339                                  set_post_thumbnail($product_id, $attach_id);
     340                                  }
     341                                 */
     342                                // Handle attributes
     343                                if ($attributes = $oscdb->get_results("SELECT po.products_options_name, pov.products_options_values_name FROM products_attributes pa, products_options po, products_options_values pov WHERE pa.products_id='" . $product['products_id'] . "' AND  pov.products_options_values_id = pa.options_values_id AND pov.language_id=po.language_id AND pa.options_id=products_options_id", ARRAY_A)) {
     344                                    wp_set_object_terms($product_id, 'variable', 'product_type');
     345
     346                                    $attrib_array = array();
     347                                    $attrib_combo = array();
     348                                    $max_price = $product['products_price'];
     349                                    $min_price = $product['products_price'];
     350                                    foreach ($attributes as $attribute) {
     351                                        $slug = sanitize_title($attribute['products_options_name']);
     352                                        $attrib_array[$slug] = array('name' => $attribute['products_options_name'],
     353                                            'value' => ltrim($attrib_array[$slug]['value'] . ' | ' . $attribute['products_options_values_name'], ' | '),
     354                                            'position' => 0,
     355                                            'is_visible' => 1,
     356                                            'is_variation' => 1,
     357                                            'is_taxonomy' => 0);
     358                                        $attrib_combo[$slug][] = array($attribute['products_options_values_name'], ($attribute['price_prefix'] == '-' ? '-' : '') . $attribute['options_values_price']);
     359                                    }
     360                                    // Now it gets tricky...
     361                                    $combos = otw_cartesian_product($attrib_combo);
     362                                    foreach ($combos as $combo) {
     363                                        $variation_id = wp_insert_post(array(
     364                                            'post_title' => 'Product ' . $product_id . ' Variation',
     365                                            'post_content' => '',
    302366                                            'post_status' => 'publish',
    303                                             'post_type' => 'product',
    304                                             'post_author' => 1
     367                                            'post_type' => 'product_variation',
     368                                            'post_author' => 1,
     369                                            'post_parent' => $product_id
    305370                                        ));
    306                                         update_post_meta($product_id, 'osc_id', $product['products_id']);
    307                                         wp_set_object_terms($product_id, 'simple', 'product_type');
    308                                         wp_set_object_terms($product_id, (int) $categories[$product['categories_id']], 'product_cat');
    309                                         update_post_meta($product_id, '_sku', $product['products_model']);
    310                                         update_post_meta($product_id, '_regular_price', $product['products_price']);
    311                                         update_post_meta($product_id, '_price', $product['products_price']);
    312                                         update_post_meta($product_id, '_visibility', 'visible');
    313                                         update_post_meta($product_id, '_stock_status', ($product['products_status'] ? 'instock' : 'outofstock'));
    314                                         update_post_meta($product_id, '_manage_stock', '1');
    315                                         update_post_meta($product_id, '_stock', $product['products_quantity']);
    316                                         $import_prod_counter++;
    317 
    318                                         if ($special = $oscdb->get_row("SELECT specials_new_products_price, expires_date FROM specials WHERE status=1 AND products_id='" . $product_id . "' LIMIT 1", ARRAY_A)) {
    319                                              update_post_meta($product_id, '_sale_price', $special['specials_new_products_price']);
    320                                              $special['expires_date'] = strtotime($special['expires_date']);
    321                                              if ($special['expires_date'] > time()) {
    322                                                   update_post_meta($product_id, '_sale_price_dates_to', date("Y-m-d", $special['expires_date']));
    323                                                   update_post_meta($product_id, '_sale_price_dates_from', date("Y-m-d"));
    324                                              }
     371
     372                                        $opt_price = $product['products_price'];
     373
     374                                        $special_price = $special['specials_new_products_price'];
     375
     376                                        foreach ($combo as $k => $v) {
     377                                            update_post_meta($variation_id, 'attribute_' . $k, $v[0]);
     378                                            $opt_price += $v[1];
     379                                            $special_price += $v[1];
    325380                                        }
    326                                         /*
    327                                           $attach_id = 0;
    328                                           if($product['products_image'] != ''){
    329                                           $url = rtrim($_POST['store_url'],'/').'/images/'.urlencode($product['products_image']);
    330                                           $attach_id = otw_import_image($url);
    331                                           }
    332                                           if($attach_id > 0){
    333                                           set_post_thumbnail($product_id, $attach_id);
    334                                           }
    335                                          */
    336                                         // Handle attributes
    337                                         if ($attributes = $oscdb->get_results("SELECT po.products_options_name, pov.products_options_values_name FROM products_attributes pa, products_options po, products_options_values pov WHERE pa.products_id='" . $product['products_id'] . "' AND  pov.products_options_values_id = pa.options_values_id AND pov.language_id=po.language_id AND pa.options_id=products_options_id", ARRAY_A)) {
    338                                              wp_set_object_terms($product_id, 'variable', 'product_type');
    339 
    340                                              $attrib_array = array();
    341                                              $attrib_combo = array();
    342                                              $max_price = $product['products_price'];
    343                                              $min_price = $product['products_price'];
    344                                              foreach ($attributes as $attribute) {
    345                                                   $slug = sanitize_title($attribute['products_options_name']);
    346                                                   $attrib_array[$slug] = array('name' => $attribute['products_options_name'],
    347                                                       'value' => ltrim($attrib_array[$slug]['value'] . ' | ' . $attribute['products_options_values_name'], ' | '),
    348                                                       'position' => 0,
    349                                                       'is_visible' => 1,
    350                                                       'is_variation' => 1,
    351                                                       'is_taxonomy' => 0);
    352                                                   $attrib_combo[$slug][] = array($attribute['products_options_values_name'], ($attribute['price_prefix'] == '-' ? '-' : '') . $attribute['options_values_price']);
    353                                              }
    354                                              // Now it gets tricky...
    355                                              $combos = otw_cartesian_product($attrib_combo);
    356                                              foreach ($combos as $combo) {
    357                                                   $variation_id = wp_insert_post(array(
    358                                                       'post_title' => 'Product ' . $product_id . ' Variation',
    359                                                       'post_content' => '',
    360                                                       'post_status' => 'publish',
    361                                                       'post_type' => 'product_variation',
    362                                                       'post_author' => 1,
    363                                                       'post_parent' => $product_id
    364                                                   ));
    365 
    366                                                   $opt_price = $product['products_price'];
    367 
    368                                                   $special_price = $special['specials_new_products_price'];
    369 
    370                                                   foreach ($combo as $k => $v) {
    371                                                        update_post_meta($variation_id, 'attribute_' . $k, $v[0]);
    372                                                        $opt_price += $v[1];
    373                                                        $special_price += $v[1];
    374                                                   }
    375                                                   update_post_meta($variation_id, '_sku', $product['products_model']);
    376                                                   update_post_meta($variation_id, '_regular_price', $opt_price);
    377                                                   update_post_meta($variation_id, '_price', $opt_price);
    378                                                   update_post_meta($variation_id, '_thumbnail_id', 0);
    379                                                   update_post_meta($variation_id, '_stock', $product['products_quantity']);
    380                                                   if ($special) {
    381                                                        update_post_meta($variation_id, '_sale_price', $special_price);
    382                                                        if ($special['expires_date'] > time()) {
    383                                                             update_post_meta($variation_id, '_sale_price_dates_to', date("Y-m-d", $special['expires_date']));
    384                                                             update_post_meta($variation_id, '_sale_price_dates_from', date("Y-m-d"));
    385                                                        }
    386                                                   }
    387                                                   if ($opt_price > $max_price) {
    388                                                        $max_price = $opt_price;
    389                                                   }
    390                                                   if ($opt_price < $min_price) {
    391                                                        $min_price = $opt_price;
    392                                                   }
    393                                              }
    394 
    395                                              update_post_meta($product_id, '_product_attributes', $attrib_array);
    396                                              update_post_meta($product_id, '_max_variation_regular_price', $max_price);
    397                                              update_post_meta($product_id, '_min_variation_regular_price', $min_price);
    398                                              update_post_meta($product_id, '_max_variation_price', $max_price);
    399                                              update_post_meta($product_id, '_min_variation_price', $min_price);
     381                                        update_post_meta($variation_id, '_sku', $product['products_model']);
     382                                        update_post_meta($variation_id, '_regular_price', $opt_price);
     383                                        update_post_meta($variation_id, '_price', $opt_price);
     384                                        update_post_meta($variation_id, '_thumbnail_id', 0);
     385                                        update_post_meta($variation_id, '_stock', $product['products_quantity']);
     386                                        if ($special) {
     387                                            update_post_meta($variation_id, '_sale_price', $special_price);
     388                                            if ($special['expires_date'] > time()) {
     389                                                update_post_meta($variation_id, '_sale_price_dates_to', date("Y-m-d", $special['expires_date']));
     390                                                update_post_meta($variation_id, '_sale_price_dates_from', date("Y-m-d"));
     391                                            }
    400392                                        }
    401                                    }
    402                               }
    403                          }
    404                          otw_log("importProduct", "End Import");
    405                     }
    406 
    407                     if ((int) $_POST['dtype']['delete'] == 1) {
    408                          otw_log("importDelete", "Start Import");
    409                          // Delete post thumbs and gallery asociation
    410                          if ($products = $oscdb->get_results("SELECT * FROM products", ARRAY_A)) {
    411                               foreach ($products as $product) {
    412                                    $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
    413                                        'meta_query' => array(
    414                                            array(
    415                                                'key' => 'osc_id',
    416                                                'value' => $product['products_id'],
    417                                            )
    418                                    )));
    419                                    if (!empty($existing_product)) {
    420                                         otw_log("importDelete", "Delete: " . json_encode($existing_product));
    421                                         $product_id = $existing_product[0]->ID;
    422                                         $attach_id = -1;
    423                                         delete_post_thumbnail($product_id);
    424                                         delete_post_meta($product_id, '_product_image_gallery', '');
    425                                    }
    426                               }
    427                          }
    428                          otw_log("importDelete", "End Import");
    429                     }
    430 
    431 
    432                     if ((int) $_POST['dtype']['image'] == 1) {
    433                          otw_log_delete("importImage");
    434                          otw_log("importImage", "Start Import");
    435                          // Import the IMAGES
    436                          if ($products = $oscdb->get_results("SELECT * FROM products", ARRAY_A)) {
    437                               foreach ($products as $product) {
    438                                    $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
    439                                        'meta_query' => array(
    440                                            array(
    441                                                'key' => 'osc_id',
    442                                                'value' => $product['products_id'],
    443                                            )
    444                                    )));
    445                                    //IF PROBLEMS UPDATES IN DATABASE AND RENAME FILES               
    446                                    /* update products set products_image = replace(products_image, ' ', '-');
    447                                      update products set products_image = replace(products_image, '(', '-');
    448                                      update products set products_image = replace(products_image, ')', '-');
    449                                      update products set products_image = replace(products_image, '+', '-'); */
    450                                    if (!empty($existing_product)) {
    451                                         $product_id = $existing_product[0]->ID;
    452                                         $attach_id = 0;
    453                                         if ($product['products_image'] != '') {
    454                                              if (esc_url($_POST['store_url'])) {
    455                                                   $url = rtrim($_POST['store_url'], '/') . '/images/' . ($product['products_image']);
    456 
    457                                                   global $wpdb;
    458                                                   $filename = ($product['products_image']);
    459                                                   $image_src = $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($filename);
    460                                                   $query = "SELECT ID FROM {$wpdb->posts} WHERE guid like '%$image_src'";
    461                                                   //echo $query;
    462                                                   $count = $wpdb->get_var($query);
    463                                                   if ($count != 0 && $count != null) {
    464                                                        //otw_log ("importImage","Product image: ".$_POST['store_url'], '/' . '/images/' . $product['products_image']);
    465                                                        $attach_id = $count;
    466                                                        //echo ("Product Exist: " . $existing_product[0] -> ID . " Media Exist" . $attach_id ." [".$product['products_image']."]</br>");
    467                                                        otw_log("importImage", "Image edit: " . $existing_product[0]->ID . " New Media [" . $url . "]");
    468                                                   } else {
    469                                                        $import_img_counter++;
    470                                                        $attach_id = otw_import_image($url);
    471                                                        otw_log("importImage", "Image new: " . $existing_product[0]->ID . " New Media [" . $url . "]");
    472                                                   }
    473                                              }
     393                                        if ($opt_price > $max_price) {
     394                                            $max_price = $opt_price;
    474395                                        }
    475                                         if ($attach_id > 0) {
    476                                              set_post_thumbnail($product_id, $attach_id);
     396                                        if ($opt_price < $min_price) {
     397                                            $min_price = $opt_price;
    477398                                        }
    478                                    }
    479                               }
    480                          }
    481                          otw_log("importImage", "End Import");
    482                     }
    483 
    484                     if ((int) $_POST['dtype']['gallery'] == 1) {
    485                          otw_log_delete("importGallery");
    486                          otw_log("importGallery", "Start Import");
    487                          // Import the IMAGES
    488                          if ($products = $oscdb->get_results("SELECT * FROM products_images ORDER BY sort_order,image", ARRAY_A)) {
    489                               foreach ($products as $product) {
    490                                    $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
    491                                        'meta_query' => array(
    492                                            array(
    493                                                'key' => 'osc_id',
    494                                                'value' => $product['products_id'],
    495                                            )
    496                                    )));
    497 
    498                                    //IF PROBLEMS UPDATES IN DATABASE AND RENAME FILES
    499                                    /* update products_images set image = replace(image, ' ', '-');
    500                                      update products_images set image = replace(image, '(', '-');
    501                                      update products_images set image = replace(image, ')', '-');
    502                                      update products_images set image = replace(image, '+', '-'); */
    503                                    if (!empty($existing_product)) {
    504                                         $product_id = $existing_product[0]->ID;
    505                                         $attach_id = 0;
    506                                         if ($product['image'] != '') {
    507                                              if (esc_url($_POST['store_url'])) {
    508                                                   $url = rtrim($_POST['store_url'], '/') . '/images/' . ($product['image']);
    509 
    510                                                   global $wpdb;
    511                                                   $filename = ($product['image']);
    512                                                   $image_src = $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($filename);
    513                                                   $query = "SELECT ID FROM {$wpdb->posts} WHERE guid like '%$image_src'";
    514                                                   $count = $wpdb->get_var($query);
    515                                                   if ($count != 0 && $count != null) {
    516                                                        $attach_id = $count;
    517                                                        otw_log("importGallery", "Image edit: " . $existing_product[0]->ID . " New Media [" . $url . "]");
    518                                                   } else {
    519                                                        $import_gallery_counter++;
    520                                                        $attach_id = otw_import_image($url);
    521                                                        otw_log("importGallery", "Image new: " . $existing_product[0]->ID . " New Media [" . $url . "]");
    522                                                   }
    523                                              }
     399                                    }
     400
     401                                    update_post_meta($product_id, '_product_attributes', $attrib_array);
     402                                    update_post_meta($product_id, '_max_variation_regular_price', $max_price);
     403                                    update_post_meta($product_id, '_min_variation_regular_price', $min_price);
     404                                    update_post_meta($product_id, '_max_variation_price', $max_price);
     405                                    update_post_meta($product_id, '_min_variation_price', $min_price);
     406                                }
     407                            }
     408                        }
     409                    }
     410                    otw_log("importProduct", "End Import");
     411                }
     412
     413                if ((int) $_POST['dtype']['delete'] == 1) {
     414                    otw_log("importDelete", "Start delete");
     415                    // Delete post thumbs and gallery asociation
     416                    if ($products = $oscdb->get_results("SELECT * FROM products", ARRAY_A)) {
     417                        foreach ($products as $product) {
     418                            $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
     419                                'meta_query' => array(
     420                                    array(
     421                                        'key' => 'osc_id',
     422                                        'value' => $product['products_id'],
     423                                    )
     424                            )));
     425                            if (!empty($existing_product)) {
     426                                otw_log("importDelete", "Delete image " . $product['products_image']);
     427                                $product_id = $existing_product[0]->ID;
     428                                $attach_id = -1;
     429                                delete_post_thumbnail($product_id);
     430                                delete_post_meta($product_id, '_product_image_gallery', '');
     431                            }
     432                        }
     433                    }
     434                    otw_log("importDelete", "End delete");
     435                }
     436
     437
     438                if ((int) $_POST['dtype']['image'] == 1) {
     439                    otw_log_delete("importImage");
     440                    otw_log("importImage", "Start Import");
     441                    // Import the IMAGES
     442                    if ($products = $oscdb->get_results("SELECT * FROM products", ARRAY_A)) {
     443                        foreach ($products as $product) {
     444                            $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
     445                                'meta_query' => array(
     446                                    array(
     447                                        'key' => 'osc_id',
     448                                        'value' => $product['products_id'],
     449                                    )
     450                            )));
     451                            //IF PROBLEMS UPDATES IN DATABASE AND RENAME FILES             
     452                            /* update products set products_image = replace(products_image, ' ', '-');
     453                              update products set products_image = replace(products_image, '(', '-');
     454                              update products set products_image = replace(products_image, ')', '-');
     455                              update products set products_image = replace(products_image, '+', '-'); */
     456                            if (!empty($existing_product)) {
     457                                $product_id = $existing_product[0]->ID;
     458                                $attach_id = 0;
     459                                if ($product['products_image'] != '') {
     460                                    if (esc_url($_POST['store_url'])) {
     461
     462                                        if (!empty($_POST['images_url'])) {
     463                                            $url = rtrim($_POST['store_url'], '/') . '/' . rtrim($_POST['store_url'], '/') . '/' . ($product['products_image']);
     464                                        } else {                                                                                   //otw_log("importCategories", "Image: " . rtrim($_POST['store_url'], '/') . '/image/' . urlencode($category['categories_image']));
     465                                            $url = rtrim($_POST['store_url'], '/') . '/images/' . ($product['products_image']);
    524466                                        }
    525                                         if ($attach_id > 0) {
    526 
    527                                              update_post_meta($product_id, '_product_image_gallery', $attach_id);
     467                                        $url = rtrim($_POST['store_url'], '/') . '/images/' . ($product['products_image']);
     468
     469                                        global $wpdb;
     470                                        $filename = ($product['products_image']);
     471                                        $image_src = $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($filename);
     472                                        $query = "SELECT ID FROM {$wpdb->posts} WHERE guid like '%$image_src'";
     473                                        //echo $query;
     474                                        $count = $wpdb->get_var($query);
     475                                        if ($count != 0 && $count != null) {
     476                                            //otw_log ("importImage","Product image: ".$_POST['store_url'], '/' . '/images/' . $product['products_image']);
     477                                            $attach_id = $count;
     478                                            //echo ("Product Exist: " . $existing_product[0] -> ID . " Media Exist" . $attach_id ." [".$product['products_image']."]</br>");
     479                                            otw_log("importImage", "Image edit: " . $existing_product[0]->ID . " New Media [" . $url . "]");
     480                                        } else {
     481                                            $import_img_counter++;
     482                                            $attach_id = otw_import_image($url);
     483                                            otw_log("importImage", "Image new: " . $existing_product[0]->ID . " New Media [" . $url . "]");
    528484                                        }
    529                                    }
    530                               }
    531                          }
    532                          otw_log("importGallery", "End Import");
    533                     }
    534                     if ((int) $_POST['dtype']['orders'] == 1) {
    535                          otw_log_delete("importOrders");
    536                          otw_log("importOrders", "Start Import");
    537                          $customers = $wpdb->get_results("SELECT ID FROM $wpdb->users", ARRAY_A);
    538                          $customer_id = array();
    539                          foreach ($customers as $c) {
    540                               $osc_id = get_user_meta($c['ID'], 'osc_id', true);
    541                               $customer_id[$osc_id] = $c['ID'];
    542                          }
    543 
    544                          $product_id = array();
    545                          $products_query = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_type='product'", ARRAY_A);
    546                          foreach ($products_query as $p) {
    547                               $osc_id = get_post_meta($p['ID'], 'osc_id', true);
    548                               $product_id[$osc_id] = $p['ID'];
    549                          }
    550 
    551 
    552                          $country_data = $oscdb->get_results("SELECT * FROM countries", ARRAY_A);
    553                          $countries_name = array();
    554                          foreach ($country_data as $cdata) {
    555                               $countries_name[$cdata['countries_name']] = $cdata;
    556                          }
    557 
    558                          if ($orders = $oscdb->get_results("SELECT * FROM orders ORDER BY orders_id", ARRAY_A)) {
    559                               foreach ($orders as $order) {
    560                                    $existing_order = get_posts(array('post_type' => 'shop_order', 'posts_per_page' => 1, 'post_status' => 'any',
    561                                        'meta_query' => array(
    562                                            array(
    563                                                'key' => 'osc_id',
    564                                                'value' => $order['orders_id'],
    565                                            )
    566                                    )));
    567                                    if (empty($existing_order)) {
    568                                         $totals = array();
    569                                         if ($total_query = $oscdb->get_results("SELECT * FROM orders_total WHERE orders_id='" . $order['orders_id'] . "'", ARRAY_A)) {
    570                                              foreach ($total_query as $t) {
    571                                                   $totals[$t['class']] = $t;
    572                                              }
     485                                    }
     486                                }
     487                                if ($attach_id > 0) {
     488                                    set_post_thumbnail($product_id, $attach_id);
     489                                }
     490                            }
     491                        }
     492                    }
     493                    otw_log("importImage", "End Import");
     494                }
     495
     496                if ((int) $_POST['dtype']['gallery'] == 1) {
     497                    otw_log_delete("importGallery");
     498                    otw_log("importGallery", "Start Import");
     499                    // Import the IMAGES
     500                    if ($products = $oscdb->get_results("SELECT * FROM products_images ORDER BY sort_order,image", ARRAY_A)) {
     501                        foreach ($products as $product) {
     502                            $existing_product = get_posts(array('post_type' => 'product', 'posts_per_page' => 1, 'post_status' => 'any',
     503                                'meta_query' => array(
     504                                    array(
     505                                        'key' => 'osc_id',
     506                                        'value' => $product['products_id'],
     507                                    )
     508                            )));
     509
     510                            //IF PROBLEMS UPDATES IN DATABASE AND RENAME FILES
     511                            /* update products_images set image = replace(image, ' ', '-');
     512                              update products_images set image = replace(image, '(', '-');
     513                              update products_images set image = replace(image, ')', '-');
     514                              update products_images set image = replace(image, '+', '-'); */
     515                            if (!empty($existing_product)) {
     516                                $product_id = $existing_product[0]->ID;
     517                                $attach_id = 0;
     518                                if ($product['image'] != '') {
     519                                    if (esc_url($_POST['store_url'])) {
     520
     521                                        if (!empty($_POST['images_url'])) {
     522                                            $url = rtrim($_POST['store_url'], '/') . '/' . rtrim($_POST['store_url'], '/') . '/' . ($product['image']);
     523                                        } else {                                                                                 
     524                                            $url = rtrim($_POST['store_url'], '/') . '/images/' . ($product['image']);
    573525                                        }
    574526
    575                                         $order_key = 'order_' . wp_generate_password(13);
    576 
    577                                         $data = array('post_type' => 'shop_order',
    578                                             'post_date' => $order['date_purchased'],
    579                                             'post_author' => $customer_id[$order['customers_id']],
    580                                             'post_password' => $order_key,
    581                                             'post_title' => 'Order &ndash; ' . date("M d, Y @ h:i A", strtotime($order['date_purchased'])),
    582                                             'post_status' => 'wc-completed'
     527                                        global $wpdb;
     528                                        $filename = ($product['image']);
     529                                        $image_src = $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path($filename);
     530                                        $query = "SELECT ID FROM {$wpdb->posts} WHERE guid like '%$image_src'";
     531                                        $count = $wpdb->get_var($query);
     532                                        if ($count != 0 && $count != null) {
     533                                            $attach_id = $count;
     534                                            otw_log("importGallery", "Image edit: " . $existing_product[0]->ID . " New Media [" . $url . "]");
     535                                        } else {
     536                                            $import_gallery_counter++;
     537                                            $attach_id = otw_import_image($url);
     538                                            otw_log("importGallery", "Image new: " . $existing_product[0]->ID . " New Media [" . $url . "]");
     539                                        }
     540                                    }
     541                                }
     542                                if ($attach_id > 0) {
     543
     544                                    update_post_meta($product_id, '_product_image_gallery', $attach_id);
     545                                }
     546                            }
     547                        }
     548                    }
     549                    otw_log("importGallery", "End Import");
     550                }
     551                if ((int) $_POST['dtype']['orders'] == 1) {
     552                    otw_log_delete("importOrders");
     553                    otw_log("importOrders", "Start Import");
     554                    $customers = $wpdb->get_results("SELECT ID FROM $wpdb->users", ARRAY_A);
     555                    $customer_id = array();
     556                    foreach ($customers as $c) {
     557                        $osc_id = get_user_meta($c['ID'], 'osc_id', true);
     558                        $customer_id[$osc_id] = $c['ID'];
     559                    }
     560
     561                    $product_id = array();
     562                    $products_query = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_type='product'", ARRAY_A);
     563                    foreach ($products_query as $p) {
     564                        $osc_id = get_post_meta($p['ID'], 'osc_id', true);
     565                        $product_id[$osc_id] = $p['ID'];
     566                    }
     567
     568
     569                    $country_data = $oscdb->get_results("SELECT * FROM countries", ARRAY_A);
     570                    $countries_name = array();
     571                    foreach ($country_data as $cdata) {
     572                        $countries_name[$cdata['countries_name']] = $cdata;
     573                    }
     574
     575                    if ($orders = $oscdb->get_results("SELECT * FROM orders ORDER BY orders_id", ARRAY_A)) {
     576                        foreach ($orders as $order) {
     577                            $existing_order = get_posts(array('post_type' => 'shop_order', 'posts_per_page' => 1, 'post_status' => 'any',
     578                                'meta_query' => array(
     579                                    array(
     580                                        'key' => 'osc_id',
     581                                        'value' => $order['orders_id'],
     582                                    )
     583                            )));
     584                            if (empty($existing_order)) {
     585                                $totals = array();
     586                                if ($total_query = $oscdb->get_results("SELECT * FROM orders_total WHERE orders_id='" . $order['orders_id'] . "'", ARRAY_A)) {
     587                                    foreach ($total_query as $t) {
     588                                        $totals[$t['class']] = $t;
     589                                    }
     590                                }
     591
     592                                $order_key = 'order_' . wp_generate_password(13);
     593
     594                                $data = array('post_type' => 'shop_order',
     595                                    'post_date' => $order['date_purchased'],
     596                                    'post_author' => $customer_id[$order['customers_id']],
     597                                    'post_password' => $order_key,
     598                                    'post_title' => 'Order &ndash; ' . date("M d, Y @ h:i A", strtotime($order['date_purchased'])),
     599                                    'post_status' => 'wc-completed'
     600                                );
     601                                otw_log("importOrders", "Header: " . json_encode($data));
     602                                $order_id = wp_insert_post($data);
     603
     604
     605                                $billing_namebits = explode(' ', $order['billing_name']);
     606                                $billing_firstname = $billing_namebits[0];
     607                                $billing_lastname = trim(str_replace($billing_namebits[0], '', $order['billing_name']));
     608
     609                                $shipping_namebits = explode(' ', $order['delivery_name']);
     610                                $shipping_firstname = $shipping_namebits[0];
     611                                $shipping_lastname = trim(str_replace($shipping_namebits[0], '', $order['delivery_name']));
     612
     613                                $meta_data = array('_billing_address_1' => $order['billing_street_address'],
     614                                    '_billing_address_2' => $order['billing_suburb'],
     615                                    '_wpas_done_all' => 1,
     616                                    '_billing_country' => $countries_name[$order['billing_country']]['countries_iso_code_2'],
     617                                    '_billing_first_name' => $billing_firstname,
     618                                    '_billing_last_name' => $billing_lastname,
     619                                    '_billing_company' => $order['billing_company'],
     620                                    '_billing_city' => $order['billing_city'],
     621                                    '_billing_state' => $order['billing_state'],
     622                                    '_billing_postcode' => $order['billing_postcode'],
     623                                    '_billing_phone' => $order['customers_telephone'],
     624                                    '_billing_email' => $order['customers_email_address'],
     625                                    '_shipping_country' => $countries_name[$order['delivery_country']]['countries_iso_code_2'],
     626                                    '_shipping_first_name' => $shipping_firstname,
     627                                    '_shipping_last_name' => $shipping_lastname,
     628                                    '_shipping_company' => $order['delivery_company'],
     629                                    '_shipping_address_1' => $order['delivery_street_address'],
     630                                    '_shipping_address_2' => $order['delivery_suburb'],
     631                                    '_shipping_city' => $order['delivery_city'],
     632                                    '_shipping_state' => $order['delivery_state'],
     633                                    '_shipping_postcode' => $order['delivery_postcode'],
     634                                    '_shipping_method_title' => $totals['ot_shipping']['title'],
     635                                    '_payment_method_title' => $order['payment_method'],
     636                                    '_order_shipping' => $totals['ot_shipping']['value'],
     637                                    '_order_discount' => $totals['ot_coupon']['value'] + $totals['ot_discount']['value'],
     638                                    '_order_tax' => $totals['ot_tax']['value'],
     639                                    '_order_shipping_tax' => 0,
     640                                    '_order_total' => $totals['ot_total']['value'],
     641                                    '_order_key' => $order_key,
     642                                    '_customer_user' => $customer_id[$order['customers_id']],
     643                                    '_order_currency' => $order['currency'],
     644                                    '_prices_include_tax' => 'no',
     645                                    'osc_id' => $order['orders_id']);
     646                                otw_log("importOrders", "address: " . json_encode($meta_data));
     647                                foreach ($meta_data as $k => $v) {
     648                                    update_post_meta($order_id, $k, $v);
     649                                }
     650
     651                                $order_import_counter++;
     652
     653                                if ($order_products = $oscdb->get_results("SELECT * FROM orders_products WHERE orders_id='" . $order['orders_id'] . "'", ARRAY_A)) {
     654                                    foreach ($order_products as $product) {
     655                                        $item_id = woocommerce_add_order_item($order_id, array(
     656                                            'order_item_name' => $product['products_name'],
     657                                            'order_item_type' => 'line_item'
     658                                        ));
     659
     660                                        if ($item_id) {
     661                                            $item_meta = array('_qty' => $product['products_quantity'],
     662                                                '_product_id' => $product_id[$product['products_id']],
     663                                                '_line_subtotal' => $product['final_price'] * $product['products_quantity'],
     664                                                '_line_total' => $product['final_price'] * $product['products_quantity']);
     665
     666                                            otw_log("importOrders", "product: " . json_encode($item_meta));
     667                                            foreach ($item_meta as $k => $v) {
     668                                                woocommerce_add_order_item_meta($item_id, $k, $v);
     669                                            }
     670                                        }
     671                                    }
     672                                }
     673                            }
     674                        }
     675                    }
     676                    otw_log("importOrders", "End Import");
     677                }
     678
     679
     680                if ((int) $_POST['dtype']['pages'] == 1) {
     681                    $page_import_counter = 0;
     682                    if ($information_table = $oscdb->get_results("SHOW TABLES LIKE 'information'", ARRAY_A)) {
     683                        if ($information_pages = $oscdb->get_results("SELECT * FROM information", ARRAY_A)) {
     684                            foreach ($information_pages as $information) {
     685                                $existing_page = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_type='page' AND LOWER(post_title)='" . strtolower(esc_sql($information['information_title'])) . "'", ARRAY_A);
     686                                if (!$existing_page) {
     687                                    $existing_page = get_posts(array('post_type' => 'page', 'posts_per_page' => 1, 'post_status' => 'any',
     688                                        'meta_query' => array(
     689                                            array(
     690                                                'key' => 'osc_id',
     691                                                'value' => $information['information_id'],
     692                                            )
     693                                    )));
     694                                    if (!$existing_page) {
     695                                        $data = array('post_type' => 'page',
     696                                            'post_title' => $information['information_title'],
     697                                            'post_content' => $information['information_description'],
     698                                            'post_status' => 'publish'
    583699                                        );
    584                                         otw_log("importOrders", "Header: " . json_encode($data));
    585                                         $order_id = wp_insert_post($data);
    586 
    587 
    588                                         $billing_namebits = explode(' ', $order['billing_name']);
    589                                         $billing_firstname = $billing_namebits[0];
    590                                         $billing_lastname = trim(str_replace($billing_namebits[0], '', $order['billing_name']));
    591 
    592                                         $shipping_namebits = explode(' ', $order['delivery_name']);
    593                                         $shipping_firstname = $shipping_namebits[0];
    594                                         $shipping_lastname = trim(str_replace($shipping_namebits[0], '', $order['delivery_name']));
    595 
    596                                         $meta_data = array('_billing_address_1' => $order['billing_street_address'],
    597                                             '_billing_address_2' => $order['billing_suburb'],
    598                                             '_wpas_done_all' => 1,
    599                                             '_billing_country' => $countries_name[$order['billing_country']]['countries_iso_code_2'],
    600                                             '_billing_first_name' => $billing_firstname,
    601                                             '_billing_last_name' => $billing_lastname,
    602                                             '_billing_company' => $order['billing_company'],
    603                                             '_billing_city' => $order['billing_city'],
    604                                             '_billing_state' => $order['billing_state'],
    605                                             '_billing_postcode' => $order['billing_postcode'],
    606                                             '_billing_phone' => $order['customers_telephone'],
    607                                             '_billing_email' => $order['customers_email_address'],
    608                                             '_shipping_country' => $countries_name[$order['delivery_country']]['countries_iso_code_2'],
    609                                             '_shipping_first_name' => $shipping_firstname,
    610                                             '_shipping_last_name' => $shipping_lastname,
    611                                             '_shipping_company' => $order['delivery_company'],
    612                                             '_shipping_address_1' => $order['delivery_street_address'],
    613                                             '_shipping_address_2' => $order['delivery_suburb'],
    614                                             '_shipping_city' => $order['delivery_city'],
    615                                             '_shipping_state' => $order['delivery_state'],
    616                                             '_shipping_postcode' => $order['delivery_postcode'],
    617                                             '_shipping_method_title' => $totals['ot_shipping']['title'],
    618                                             '_payment_method_title' => $order['payment_method'],
    619                                             '_order_shipping' => $totals['ot_shipping']['value'],
    620                                             '_order_discount' => $totals['ot_coupon']['value'] + $totals['ot_discount']['value'],
    621                                             '_order_tax' => $totals['ot_tax']['value'],
    622                                             '_order_shipping_tax' => 0,
    623                                             '_order_total' => $totals['ot_total']['value'],
    624                                             '_order_key' => $order_key,
    625                                             '_customer_user' => $customer_id[$order['customers_id']],
    626                                             '_order_currency' => $order['currency'],
    627                                             '_prices_include_tax' => 'no',
    628                                             'osc_id' => $order['orders_id']);
    629                                         otw_log("importOrders", "address: " . json_encode($meta_data));
    630                                         foreach ($meta_data as $k => $v) {
    631                                              update_post_meta($order_id, $k, $v);
    632                                         }
    633 
    634                                         $order_import_counter++;
    635 
    636                                         if ($order_products = $oscdb->get_results("SELECT * FROM orders_products WHERE orders_id='" . $order['orders_id'] . "'", ARRAY_A)) {
    637                                              foreach ($order_products as $product) {
    638                                                   $item_id = woocommerce_add_order_item($order_id, array(
    639                                                       'order_item_name' => $product['products_name'],
    640                                                       'order_item_type' => 'line_item'
    641                                                   ));
    642 
    643                                                   if ($item_id) {
    644                                                        $item_meta = array('_qty' => $product['products_quantity'],
    645                                                            '_product_id' => $product_id[$product['products_id']],
    646                                                            '_line_subtotal' => $product['final_price'] * $product['products_quantity'],
    647                                                            '_line_total' => $product['final_price'] * $product['products_quantity']);
    648 
    649                                                        otw_log("importOrders", "product: " . json_encode($item_meta));
    650                                                        foreach ($item_meta as $k => $v) {
    651                                                             woocommerce_add_order_item_meta($item_id, $k, $v);
    652                                                        }
    653                                                   }
    654                                              }
    655                                         }
    656                                        
    657                                        
    658                                    }
    659                               }
    660                          }
    661                          otw_log("importOrders", "End Import");
    662                     }
    663 
    664 
    665                     if ((int) $_POST['dtype']['pages'] == 1) {
    666                          $page_import_counter = 0;
    667                          if ($information_table = $oscdb->get_results("SHOW TABLES LIKE 'information'", ARRAY_A)) {
    668                               if ($information_pages = $oscdb->get_results("SELECT * FROM information", ARRAY_A)) {
    669                                    foreach ($information_pages as $information) {
    670                                         $existing_page = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_type='page' AND LOWER(post_title)='" . strtolower(esc_sql($information['information_title'])) . "'", ARRAY_A);
    671                                         if (!$existing_page) {
    672                                              $existing_page = get_posts(array('post_type' => 'page', 'posts_per_page' => 1, 'post_status' => 'any',
    673                                                  'meta_query' => array(
    674                                                      array(
    675                                                          'key' => 'osc_id',
    676                                                          'value' => $information['information_id'],
    677                                                      )
    678                                              )));
    679                                              if (!$existing_page) {
    680                                                   $data = array('post_type' => 'page',
    681                                                       'post_title' => $information['information_title'],
    682                                                       'post_content' => $information['information_description'],
    683                                                       'post_status' => 'publish'
    684                                                   );
    685                                                   $page_id = wp_insert_post($data);
    686                                                   update_post_meta($page_id, 'osc_id', $information['information_id']);
    687                                                   $page_import_counter++;
    688                                              }
    689                                         }
    690                                    }
    691                               }
    692                          } else {
    693                               echo '<p class="notice">The information (pages) table does not exist in this osCommerce installation.</p>';
    694                          }
    695                     }
    696                     $output = ob_get_contents();
    697                     ob_end_clean();
    698                     $success = true;
    699                } else {
    700                     echo '<p class="notice">Could not connect to the osCommerce database</p>';
    701                }
    702           }
    703           ?>
    704           <form method="post" action="">
    705 
    706               <?php
    707               wp_nonce_field('otw_sync', 'sync_submit');
    708               if ($success) {
    709                    ?>
    710                    <div class="row">
    711                        <div class="col-lg-12">
    712                            <div class="alert alert-success">
    713                                <h3>The oscommerce data was successfully imported</h3>
    714                                <?php
    715                                if ((int) $_POST['dtype']['customers'] == 1) {
    716                                     echo '<p>Customers Imported: ' . $import_customer_counter . '</p>';
    717                                }
    718                                if ((int) $_POST['dtype']['orders'] == 1) {
    719                                     echo '<p>Orders Imported: ' . $order_import_counter . '</p>';
    720                                }
    721                                if ((int) $_POST['dtype']['categories'] == 1) {
    722                                     echo '<p>Categories Imported: ' . $import_cat_counter . '</p>';
    723                                }
    724                                if ((int) $_POST['dtype']['products'] == 1) {
    725                                     echo '<p>Products Imported: ' . $import_prod_counter . '</p>';
    726                                }
    727                                if ((int) $_POST['dtype']['image'] == 1) {
    728                                     echo '<p>Images Imported: ' . $import_img_counter . '</p>';
    729                                }
    730                                if ((int) $_POST['dtype']['gallery'] == 1) {
    731                                     echo '<p>Images gallery Imported: ' . $import_gallery_counter . '</p>';
    732                                }
    733                                if ((int) $_POST['dtype']['pages'] == 1) {
    734                                     echo '<p>Pages Imported: ' . $page_import_counter . '</p>';
    735                                }
    736                                ?>
    737                            </div>
    738                        </div>
    739                    </div>
    740                    <?php
    741               }
    742               ?>
    743               <div class="row">
    744                   <div class="col-md-6 form-control" style="background-color: #f1f1f1">
    745                       <h3>Import data from osCommerce</h3>
    746                       <p>For big products database can import in steps</p>     
    747                       <p><label class="control-label">Debug: <input type="checkbox" name="debug" value="1"  <?php
    748                           if ($_POST['debug']) {
    749                                echo " checked ";
    750                           }
    751                           ?>></label><small>(Display and save a log file in WordPress root folder)</small></p>
    752                       <p><label class="control-label">Language (Id from osCommerce lang table): <input type="text" name="lang" value="<?php echo sanitize_text_field($_POST['lang']); ?>"></label></p>
    753                       <p><label class="control-label">Offset (Last product imported): <input type="text" name="offset" value="<?php echo sanitize_text_field($_POST['offset']); ?>"></label></p>
    754                       <p><label class="control-label">Limit (how many produts imported): <input type="text" name="limit" value="<?php echo sanitize_text_field($_POST['limit']); ?>"></label></p>
    755                       <p>Enter your oscommerce database information (you will need remote access to your oscommerce database)</p>
    756                       <p><label class="control-label">osCommerce store URL: <input type="text" name="store_url" value="<?php echo sanitize_text_field($_POST['store_url']); ?>"></label></p>
    757                       <p><label class="control-label">osCommerce Database Host: <input type="text" name="store_host" value="localhost"></label></p>
    758                       <p><label class="control-label">osCommerce Database User: <input type="text" name="store_user" value="<?php echo sanitize_text_field($_POST['store_user']); ?>"></label></p>
    759                       <p><label class="control-label">osCommerce Database Password: <input type="text" name="store_pass" value="<?php echo sanitize_text_field($_POST['store_pass']); ?>"></label></p>
    760                       <p><label class="control-label">osCommerce Database Name: <input type="text" name="store_dbname" value="<?php echo sanitize_text_field($_POST['store_dbname']); ?>"></label></p>
    761                   </div>
    762                   <div class="col-md-6 form-control" style="background-color: #f1f1f1">
    763                       <h3>Data to Import:</h3>
    764                       <h5>It is recommended to follow the order of the list</h5>
    765                       <label class="control-label"><input type="checkbox" name="dtype[customers]" value="1" <?php
    766                           if ((int) $_POST['dtype']['customers']) {
    767                                echo " checked ";
    768                           }
    769                           ?>>Customers (passwords will not be transferred)</label><br>
    770 
    771                       <label class="control-label"><input type="checkbox" name="dtype[categories]" value="1" <?php
    772                           if ((int) $_POST['dtype']['categories']) {
    773                                echo " checked ";
    774                           }
    775                           ?>>Categories</label><br>
    776                       <label class="control-label"><input type="checkbox" name="dtype[products]" value="1"  <?php
    777                           if ((int) $_POST['dtype']['products']) {
    778                                echo " checked ";
    779                           }
    780                           ?>>Products</label><br>
    781                       <label class="control-label"><input type="checkbox" name="dtype[delete]" value="1"  <?php
    782                           if ((int) $_POST['dtype']['delete']) {
    783                                echo " checked ";
    784                           }
    785                           ?>>Products delete images </label><br>
    786                       <label class="control-label"><input type="checkbox" name="dtype[image]" value="1"  <?php
    787                           if ((int) $_POST['dtype']['image']) {
    788                                echo " checked ";
    789                           }
    790                           ?>>Products Prefered image</label><br>
    791                       <label class="control-label"><input type="checkbox" name="dtype[gallery]" value="1"  <?php
    792                           if ((int) $_POST['dtype']['gallery']) {
    793                                echo " checked ";
    794                           }
    795                           ?>>Products gallery</label><br>
    796                       <label class="control-label"><input type="checkbox" name="dtype[orders]" value="1" <?php
    797                           if ((int) $_POST['dtype']['orders']) {
    798                                echo " checked ";
    799                           }
    800                           ?>>Orders</label><br>
    801                       <label class="control-label"><input type="checkbox" name="dtype[pages]" value="1"  <?php
    802                           if ((int) $_POST['dtype']['pages']) {
    803                                echo " checked ";
    804                           }
    805                           ?>>Information Pages</label>
    806                      
    807                       <p><input type="submit" value="Import Data" class="button button-primary button-large"></p>
    808                   </div>
    809               </div>
    810           </form>
    811           <?php
    812           if ($output) {
    813                echo '<div class="col-md-12"><h3>Debug</h3><pre style="padding:10px;max-height:300px;overflow-y:auto;background-color:#cdcdcd;">';
    814                echo $output;
    815                echo '</pre></div>';
    816           }
    817      }
    818 
    819      add_action('admin_menu', 'otw_submenu_page', 99);
     700                                        $page_id = wp_insert_post($data);
     701                                        update_post_meta($page_id, 'osc_id', $information['information_id']);
     702                                        $page_import_counter++;
     703                                    }
     704                                }
     705                            }
     706                        }
     707                    } else {
     708                        echo '<p class="notice">The information (pages) table does not exist in this osCommerce installation.</p>';
     709                    }
     710                }
     711                $output = ob_get_contents();
     712                ob_end_clean();
     713                $success = true;
     714            } else {
     715                echo '<p class="notice">Could not connect to the osCommerce database</p>';
     716            }
     717        }
     718        ?>
     719        <form method="post" action="">
     720
     721            <?php
     722            wp_nonce_field('otw_sync', 'sync_submit');
     723            if ($success) {
     724                ?>
     725                <div class="row">
     726                    <div class="col-lg-12">
     727                        <div class="alert alert-success">
     728                            <h3>The oscommerce data was successfully imported</h3>
     729                            <?php
     730                            if ((int) $_POST['dtype']['customers'] == 1) {
     731                                echo '<p>Customers Imported: ' . $import_customer_counter . '</p>';
     732                            }
     733                            if ((int) $_POST['dtype']['orders'] == 1) {
     734                                echo '<p>Orders Imported: ' . $order_import_counter . '</p>';
     735                            }
     736                            if ((int) $_POST['dtype']['categories'] == 1) {
     737                                echo '<p>Categories Imported: ' . $import_cat_counter . '</p>';
     738                            }
     739                            if ((int) $_POST['dtype']['products'] == 1) {
     740                                echo '<p>Products Imported: ' . $import_prod_counter . '</p>';
     741                            }
     742                            if ((int) $_POST['dtype']['image'] == 1) {
     743                                echo '<p>Images Imported: ' . $import_img_counter . '</p>';
     744                            }
     745                            if ((int) $_POST['dtype']['gallery'] == 1) {
     746                                echo '<p>Images gallery Imported: ' . $import_gallery_counter . '</p>';
     747                            }
     748                            if ((int) $_POST['dtype']['pages'] == 1) {
     749                                echo '<p>Pages Imported: ' . $page_import_counter . '</p>';
     750                            }
     751                            ?>
     752                        </div>
     753                    </div>
     754                </div>
     755                <?php
     756            }
     757            ?>
     758            <div class="row">
     759                <div class="col-md-6 form-control" style="background-color: #f1f1f1">
     760                    <h3>Import data from osCommerce</h3>
     761                    <p>For big products database can import in steps</p>       
     762                    <p><label class="control-label">Debug: <input type="checkbox" name="debug" value="1"  <?php
     763                            if ($_POST['debug']) {
     764                                echo " checked ";
     765                            }
     766                            ?>></label><small>(Display and save a log file in WordPress root folder)</small></p>
     767                    <p><label class="control-label">Language (Id from osCommerce lang table): <input type="text" name="lang" value="<?php echo sanitize_text_field($_POST['lang']); ?>"></label></p>
     768                    <p><label class="control-label">Offset (Last product imported): <input type="text" name="offset" value="<?php echo sanitize_text_field($_POST['offset']); ?>"></label></p>
     769                    <p><label class="control-label">Limit (how many produts imported): <input type="text" name="limit" value="<?php echo sanitize_text_field($_POST['limit']); ?>"></label></p>
     770                    <p>Enter your oscommerce database information (you will need remote access to your oscommerce database)</p>
     771                    <p><label class="control-label">osCommerce store URL: <input type="text" name="store_url" value="<?php echo sanitize_text_field($_POST['store_url']); ?>"></label><label class="control-label">&nbsp;&nbsp;&nbsp;Images directory: <small>(empty directory "/image") </small><input type="text" name="images_url" value="<?php echo sanitize_text_field($_POST['images_url']); ?>"></label></p>
     772                    <p><label class="control-label">osCommerce Database Host: <input type="text" name="store_host" value="localhost"></label></p>
     773                    <p><label class="control-label">osCommerce Database User: <input type="text" name="store_user" value="<?php echo sanitize_text_field($_POST['store_user']); ?>"></label></p>
     774                    <p><label class="control-label">osCommerce Database Password: <input type="text" name="store_pass" value="<?php echo sanitize_text_field($_POST['store_pass']); ?>"></label></p>
     775                    <p><label class="control-label">osCommerce Database Name: <input type="text" name="store_dbname" value="<?php echo sanitize_text_field($_POST['store_dbname']); ?>"></label></p>
     776                </div>
     777                <div class="col-md-6 form-control" style="background-color: #f1f1f1">
     778                    <h3>Data to Import:</h3>
     779                    <h5>It is recommended to follow the order of the list</h5>
     780                    <label class="control-label"><input type="checkbox" name="dtype[customers]" value="1" <?php
     781                        if ((int) $_POST['dtype']['customers']) {
     782                            echo " checked ";
     783                        }
     784                        ?>>Customers (passwords will not be transferred)</label><br>
     785
     786                    <label class="control-label"><input type="checkbox" name="dtype[categories]" value="1" <?php
     787                        if ((int) $_POST['dtype']['categories']) {
     788                            echo " checked ";
     789                        }
     790                        ?>>Categories</label><br>
     791                    <label class="control-label"><input type="checkbox" name="dtype[products]" value="1"  <?php
     792                        if ((int) $_POST['dtype']['products']) {
     793                            echo " checked ";
     794                        }
     795                        ?>>Products</label><br>
     796                    <label class="control-label"><input type="checkbox" name="dtype[delete]" value="1"  <?php
     797                        if ((int) $_POST['dtype']['delete']) {
     798                            echo " checked ";
     799                        }
     800                        ?>>Products delete images </label><br>
     801                    <label class="control-label"><input type="checkbox" name="dtype[image]" value="1"  <?php
     802                        if ((int) $_POST['dtype']['image']) {
     803                            echo " checked ";
     804                        }
     805                        ?>>Products Prefered image</label><br>
     806                    <label class="control-label"><input type="checkbox" name="dtype[gallery]" value="1"  <?php
     807                        if ((int) $_POST['dtype']['gallery']) {
     808                            echo " checked ";
     809                        }
     810                        ?>>Products gallery</label><br>
     811                    <label class="control-label"><input type="checkbox" name="dtype[orders]" value="1" <?php
     812                        if ((int) $_POST['dtype']['orders']) {
     813                            echo " checked ";
     814                        }
     815                        ?>>Orders</label><br>
     816                    <label class="control-label"><input type="checkbox" name="dtype[pages]" value="1"  <?php
     817                        if ((int) $_POST['dtype']['pages']) {
     818                            echo " checked ";
     819                        }
     820                        ?>>Information Pages</label>
     821
     822                    <p><input type="submit" value="Import Data" class="button button-primary button-large"></p>
     823                </div>
     824            </div>
     825        </form>
     826        <?php
     827        if ($output) {
     828            echo '<div class="col-md-12"><h3>Debug</h3><pre style="padding:10px;max-height:300px;overflow-y:auto;background-color:#cdcdcd;">';
     829            echo $output;
     830            echo '</pre></div>';
     831        }
     832    }
     833
     834    add_action('admin_menu', 'otw_submenu_page', 99);
    820835}
    821836
    822837// function remove Log
    823838function otw_log_delete($log) {
    824      @unlink(get_home_path() . $log . '.log');
     839    @unlink(get_home_path() . $log . '.log');
    825840}
    826841
    827842// function write Log
    828843function otw_log($log, $data) {
    829      global $debug;
    830      if ($debug) {
    831           $fp = fopen(get_home_path() . $log . '.log', 'a+');
    832           fwrite($fp, date('Y-m-d H:i:s') . ' ' . $data . "\r\n");
    833           fclose($fp);
    834           echo "$data" . PHP_EOL;
    835      }
     844    global $debug;
     845    if ($debug) {
     846        $fp = fopen(get_home_path() . $log . '.log', 'a+');
     847        fwrite($fp, date('Y-m-d H:i:s') . ' ' . $data . "\r\n");
     848        fclose($fp);
     849        echo "$data" . PHP_EOL;
     850    }
    836851}
    837852?>
Note: See TracChangeset for help on using the changeset viewer.