private function save_variation_meta($id, $data)
 {
     $product_meta = get_product_meta($id, 'product_metadata', true);
     if (!is_array($product_meta)) {
         $product_meta = array();
     }
     $product_meta = $this->merge_meta_deep($product_meta, $data['product_metadata']);
     // convert to pound to maintain backward compat with shipping modules
     if (isset($data['product_metadata']['weight']) || isset($data['product_metadata']['weight_unit'])) {
         $product_meta['weight'] = wpsc_convert_weight($product_meta['weight'], $product_meta['weight_unit'], 'pound', true);
     }
     update_product_meta($id, 'product_metadata', $product_meta);
     if (isset($data['price'])) {
         update_product_meta($id, 'price', wpsc_string_to_float($data['price']));
     }
     if (isset($data['sale_price'])) {
         $sale_price = wpsc_string_to_float($data['sale_price']);
         if (is_numeric($sale_price)) {
             update_product_meta($id, 'special_price', wpsc_string_to_float($data['sale_price']));
         } else {
             update_product_meta($id, 'special_price', '');
         }
     }
     if (isset($data['sku'])) {
         update_product_meta($id, 'sku', $data['sku']);
     }
     if (isset($data['stock'])) {
         if (is_numeric($data['stock'])) {
             update_product_meta($id, 'stock', (int) $data['stock']);
         } else {
             update_product_meta($id, 'stock', '');
         }
     }
 }
Example #2
0
function nzshpcrt_install()
{
    global $wpdb, $user_level, $wp_rewrite, $wp_version;
    $table_name = $wpdb->prefix . "product_list";
    //$log_table_name = $wpdb->prefix . "sms_log";
    if ($wp_version < 2.1) {
        get_currentuserinfo();
        if ($user_level < 8) {
            return;
        }
    }
    $first_install = false;
    $result = mysql_list_tables(DB_NAME);
    $tables = array();
    while ($row = mysql_fetch_row($result)) {
        $tables[] = $row[0];
    }
    if (!in_array($table_name, $tables)) {
        $first_install = true;
    }
    if (get_option('wpsc_version') == null) {
        add_option('wpsc_version', WPSC_VERSION, 'wpsc_version', 'yes');
    }
    // Table structure for table `".$wpdb->prefix."also_bought_product`
    $num = 0;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . "also_bought_product";
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "also_bought_product` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`selected_product` bigint(20) unsigned NOT NULL default '0',\n\t\t`associated_product` bigint(20) unsigned NOT NULL default '0',\n\t\t`quantity` int(10) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."cart_contents`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'cart_contents';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "cart_contents` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`prodid` bigint(20) unsigned NOT NULL default '0',\n\t\t`purchaseid` bigint(20) unsigned NOT NULL default '0',\n\t\t`price` varchar(128) NOT NULL default '0',\n\t\t`pnp` varchar(128) NOT NULL default '0',\n\t\t`gst` varchar(128) NOT NULL default '0',\n\t\t`quantity` int(10) unsigned NOT NULL default '0',\n\t\t`donation` varchar(1) NOT NULL default '0',\n\t\t`no_shipping` varchar(1) NOT NULL default '0',\n\t\t`files` TEXT NOT NULL default '',\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."cart_item_extras`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'cart_item_extras';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "cart_item_extras` (\n\t\t`id` int(11) NOT NULL auto_increment,\n\t\t`cart_id` int(11) NOT NULL,\n\t\t`extra_id` int(11) NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."cart_item_variations`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'cart_item_variations';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "cart_item_variations` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`cart_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`variation_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`value_id` bigint(20) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."collect_data_forms`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'collect_data_forms';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "collect_data_forms` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`name` varchar(255) NOT NULL default '',\n\t\t`type` varchar(64) NOT NULL default '',\n\t\t`mandatory` varchar(1) NOT NULL default '0',\n\t\t`display_log` char(1) NOT NULL default '0',\n\t\t`default` varchar(128) NOT NULL default '0',\n\t\t`active` varchar(1) NOT NULL default '1',\n\t\t`order` int(10) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `order` (`order`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."currency_list`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'currency_list';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "currency_list` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`country` varchar(255) NOT NULL default '',\n\t\t`isocode` char(2) default NULL,\n\t\t`currency` varchar(255) NOT NULL default '',\n\t\t`symbol` varchar(10) NOT NULL default '',\n\t\t`symbol_html` varchar(10) NOT NULL default '',\n\t\t`code` char(3) NOT NULL default '',\n\t\t`has_regions` char(1) NOT NULL default '0',\n\t\t`tax` varchar(8) NOT NULL default '',\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."download_status`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'download_status';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "download_status` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`fileid` bigint(20) unsigned NOT NULL default '0',\n\t\t`purchid` bigint(20) unsigned NOT NULL default '0',\n\t\t`uniqueid` varchar(64) default NULL,\n\t\t`downloads` int(11) NOT NULL default '0',\n\t\t`ip_number` varchar(255) NOT NULL default '',\n\t\t`active` varchar(1) NOT NULL default '0',\n\t\t`datetime` datetime NOT NULL,\n\t\tPRIMARY KEY  (`id`),\n\t\tUNIQUE KEY `uniqueid` (`uniqueid`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."extras_values`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'extras_values';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "extras_values` (\n\t\t`id` int(11) NOT NULL auto_increment,\n\t\t`name` varchar(128) NOT NULL,\n\t\t`extras_id` int(11) NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."extras_values_associations`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'extras_values_associations';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "extras_values_associations` (\n\t\t`id` int(11) NOT NULL auto_increment,\n\t\t`product_id` int(11) NOT NULL,\n\t\t`value_id` int(11) NOT NULL,\n\t\t`price` varchar(20) NOT NULL,\n\t\t`visible` varchar(1) NOT NULL,\n\t\t`extras_id` int(11) NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."item_category_associations`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'item_category_associations';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "item_category_associations` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`product_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`category_id` bigint(20) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tUNIQUE KEY `product_id` (`product_id`,`category_id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."product_brands`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_brands';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_brands` (\n\t\t`id` bigint(20) NOT NULL auto_increment,\n\t\t`name` text NOT NULL,\n\t\t`description` text NOT NULL,\n\t\t`active` varchar(1) NOT NULL default '1',\n\t\t`order` bigint(20) unsigned NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."product_categories`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_categories';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_categories` (\n\t\t`id` bigint(20) NOT NULL auto_increment,\n\t\t`group_id` BIGINT( 20 ) UNSIGNED NOT NULL,\n\t\t`name` text NOT NULL,\n\t\t`nice-name` varchar(255) NOT NULL,\n\t\t`description` text NOT NULL,\n\t\t`image` text NOT NULL,\n\t\t`fee` varchar(1) NOT NULL default '0',\n\t\t`active` varchar(1) NOT NULL default '1',\n\t\t`category_parent` bigint(20) unsigned default '0',\n\t\t`order` bigint(20) unsigned NOT NULL,\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `group_id` (`group_id`),\n\t\tKEY `nice-name` (`nice-name`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."product_extra`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_extra';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_extra` (\n\t\t`id` int(11) NOT NULL auto_increment,\n\t\t`name` varchar(128) NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."product_files`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_files';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_files` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`filename` varchar(255) NOT NULL default '',\n\t\t`mimetype` varchar(128) NOT NULL default '',\n\t\t`idhash` varchar(45) NOT NULL default '',\n\t\t`preview` varchar(255) NOT NULL default '',\n\t\t`preview_mimetype` varchar(128) NOT NULL default '',\n\t\t`date` varchar(255) NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."product_images`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_images';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_images` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`product_id` bigint(20) unsigned NOT NULL,\n\t\t`image` varchar(255) NOT NULL,\n\t\t`width` mediumint(8) unsigned NOT NULL,\n\t\t`height` mediumint(8) unsigned NOT NULL,\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `product_id` (`product_id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."product_list`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_list';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_list` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`name` text NOT NULL,\n\t\t`description` longtext NOT NULL,\n\t\t`additional_description` longtext NOT NULL,\n\t\t`price` varchar(20) NOT NULL default '0',\n\t\t`weight` int(11) NOT NULL default '0',\n\t\t`weight_unit` varchar(10) NOT NULL,\n\t\t`pnp` varchar(20) NOT NULL default '0',\n\t\t`international_pnp` varchar(20) NOT NULL default '0',\n\t\t`file` bigint(20) unsigned NOT NULL,\n\t\t`image` text NOT NULL,\n\t\t`category` bigint(20) unsigned NOT NULL default '0',\n\t\t`brand` bigint(20) unsigned NOT NULL default '0',\n\t\t`quantity_limited` varchar(1) NOT NULL,\n\t\t`quantity` int(10) unsigned NOT NULL default '0',\n\t\t`special` varchar(1) NOT NULL default '0',\n\t\t`special_price` varchar(20) NOT NULL default '0',\n\t\t`display_frontpage` varchar(1) NOT NULL default '0',\n\t\t`notax` varchar(1) NOT NULL default '0',\n\t\t`active` varchar(1) NOT NULL default '1',\n\t\t`donation` varchar(1) NOT NULL default '0',\n\t\t`no_shipping` varchar(1) NOT NULL default '0',\n\t\t`thumbnail_image` text,\n\t\t`thumbnail_state` int(11) NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."product_order`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_order';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_order` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`category_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`product_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`order` bigint(20) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tUNIQUE KEY `category_id` (`category_id`,`product_id`),\n\t\tKEY `order` (`order`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."product_rating`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_rating';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_rating` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`ipnum` varchar(30) NOT NULL default '',\n\t\t`productid` bigint(20) unsigned NOT NULL default '0',\n\t\t`rated` tinyint(1) NOT NULL default '0',\n\t\t`time` bigint(20) unsigned NOT NULL,\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."product_variations`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'product_variations';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "product_variations` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`name` varchar(128) NOT NULL default '',\n\t\t`variation_association` bigint(20) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `variation_association` (`variation_association`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."purchase_logs`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'purchase_logs';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "purchase_logs` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`totalprice` varchar(128) NOT NULL default '0',\n\t\t`statusno` smallint(6) NOT NULL default '0',\n\t\t`sessionid` varchar(255) NOT NULL default '',\n\t\t`transactid` varchar(255) NOT NULL default '',\n\t\t`authcode` varchar(255) NOT NULL default '',\n\t\t`downloadid` bigint(20) unsigned NOT NULL default '0',\n\t\t`processed` bigint(20) unsigned NOT NULL default '1',\n\t\t`user_ID` bigint(20) unsigned default NULL,\n\t\t`date` varchar(255) NOT NULL default '',\n\t\t`gateway` varchar(64) NOT NULL default '',\n\t\t`billing_country` char(6) NOT NULL default '',\n\t\t`shipping_country` char(6) NOT NULL default '',\n\t\t`base_shipping` varchar(128) NOT NULL default '0',\n\t\t`email_sent` char(1) NOT NULL default '0',\n\t\t`discount_value` varchar(32) NOT NULL default '0',\n\t\t`discount_data` text NOT NULL,\n\t\t`track_id` varchar(50) default NULL default '',\n\t\t`shipping_region` char(6) NOT NULL default '',\n\t\t`find_us` varchar(255) NOT NULL  default '',\n\t\t`engravetext` varchar(255) default NULL,\n\t\t`closest_store` varchar(255) default NULL,\n\t\t`google_order_number` varchar(20) NOT NULL default '',\n\t\t`google_user_marketing_preference` varchar(10) NOT NULL default '',\n\t\t`google_status` longtext NOT NULL,\n\t\tPRIMARY KEY  (`id`),\n\t\tUNIQUE KEY `sessionid` (`sessionid`),\n\t\tKEY `gateway` (`gateway`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."purchase_statuses`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'purchase_statuses';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "purchase_statuses` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`name` varchar(128) NOT NULL default '',\n\t\t`active` varchar(1) NOT NULL default '0',\n\t\t`colour` varchar(6) NOT NULL default '',\n\t\tPRIMARY KEY  (`id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."region_tax`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'region_tax';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "region_tax` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`country_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`name` varchar(64) NOT NULL default '',\n\t\t`code` char(2) NOT NULL default '',\n\t\t`tax` float NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `country_id` (`country_id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."submited_form_data`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'submited_form_data';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "submited_form_data` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`log_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`form_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`value` varchar(255) NOT NULL default '',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `log_id` (`log_id`,`form_id`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."variation_associations`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'variation_associations';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "variation_associations` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`type` varchar(64) NOT NULL default '',\n\t\t`name` varchar(128) NOT NULL default '',\n\t\t`associated_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`variation_id` bigint(20) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `associated_id` (`associated_id`),\n\t\tKEY `variation_id` (`variation_id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."variation_priceandstock`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'variation_priceandstock';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "variation_priceandstock` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`product_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`variation_id_1` bigint(20) unsigned NOT NULL default '0',\n\t\t`variation_id_2` bigint(20) unsigned NOT NULL default '0',\n\t\t`stock` bigint(20) unsigned NOT NULL default '0',\n\t\t`price` varchar(32) NOT NULL default '0',\n\t\t`file` varchar(1) NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `product_id` (`product_id`),\n\t\tKEY `variation_id_1` (`variation_id_1`,`variation_id_2`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."variation_values`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'variation_values';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "variation_values` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`name` varchar(128) NOT NULL default '',\n\t\t`variation_id` bigint(20) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `variation_id` (`variation_id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."variation_values_associations`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'variation_values_associations';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "variation_values_associations` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`product_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`value_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`quantity` int(11) NOT NULL default '0',\n\t\t`price` varchar(32) NOT NULL default '0',\n\t\t`visible` varchar(1) NOT NULL default '0',\n\t\t`variation_id` bigint(20) unsigned NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `product_id` (`product_id`,`value_id`,`variation_id`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."wpsc_coupon_codes`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'wpsc_coupon_codes';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "wpsc_coupon_codes` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`coupon_code` varchar(255) default NULL,\n\t\t`value` bigint(20) unsigned NOT NULL default '0',\n\t\t`is-percentage` char(1) NOT NULL default '0',\n\t\t`use-once` char(1) NOT NULL default '0',\n\t\t`is-used` char(1) NOT NULL default '0',\n\t\t`active` char(1) NOT NULL default '1',\n\t\t`every_product` varchar(255) NOT NULL,\n\t\t`start` datetime NOT NULL,\n\t\t`expiry` datetime NOT NULL,\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `coupon_code` (`coupon_code`),\n\t\tKEY `active` (`active`),\n\t\tKEY `start` (`start`),\n\t\tKEY `expiry` (`expiry`)\n\t) TYPE=MyISAM ;\n\t";
    // Table structure for table `".$wpdb->prefix."wpsc_logged_subscriptions`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'wpsc_logged_subscriptions';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "wpsc_logged_subscriptions` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`cart_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`user_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`length` varchar(64) NOT NULL default '0',\n\t\t`start_time` varchar(64) NOT NULL default '0',\n\t\t`active` varchar(1) NOT NULL default '0',\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `cart_id` (`cart_id`),\n\t\tKEY `user_id` (`user_id`),\n\t\tKEY `start_time` (`start_time`)\n\t) TYPE=MyISAM;\n\t";
    // Table structure for table `".$wpdb->prefix."wpsc_productmeta`
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'wpsc_productmeta';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "wpsc_productmeta` (\n\t\t`id` bigint(20) unsigned NOT NULL auto_increment,\n\t\t`product_id` bigint(20) unsigned NOT NULL default '0',\n\t\t`meta_key` varchar(255) default NULL,\n\t\t`meta_value` longtext,\n\t\tPRIMARY KEY  (`id`),\n\t\tKEY `product_id` (`product_id`),\n\t\tKEY `meta_key` (`meta_key`)\n\t) TYPE=MyISAM ;\n\t";
    $num++;
    $wpsc_tables[$num]['table_name'] = $wpdb->prefix . 'wpsc_categorisation_groups';
    $wpsc_tables[$num]['table_sql'] = "CREATE TABLE `" . $wpdb->prefix . "wpsc_categorisation_groups` (\n  `id` bigint(20) unsigned NOT NULL auto_increment,\n  `name` varchar(255) NOT NULL,\n  `description` text NOT NULL,\n  `active` varchar(1) NOT NULL default '1',\n  `default` varchar(1) NOT NULL default '0',\n  PRIMARY KEY  (`id`),\n  KEY `group_name` (`name`)\n) ENGINE=MyISAM ;\n\t";
    // and here is where the tables are added to the database, fairly simple, if it doesnt find the table, it makes it
    foreach ($wpsc_tables as $wpsc_table) {
        if (!$wpdb->get_var("SHOW TABLES LIKE '{$wpsc_table['table_name']}'")) {
            $wpdb->query($wpsc_table['table_sql']);
        }
    }
    wpsc_create_upload_directories();
    require dirname(__FILE__) . "/currency_list.php";
    /*
    Updates from old versions, 
    */
    if (get_option('wpsc_version') <= 3.5) {
        include_once 'updates/update-to-3.5.0.php';
    }
    //
    //   if((get_option('wpsc_version') < 3.5 ) || ((get_option('wpsc_version') == 3.5 ) && (get_option('wpsc_minor_version') <= 2))) {
    include_once 'updates/update-to-3.5.2.php';
    //     }
    include_once 'updates/update-to-3.5.2.php';
    include_once 'updates/update-to-3.6.0.php';
    include_once 'updates/update-to-3.6.4.php';
    /* all code to add new database tables and columns must be above here */
    if (get_option('wpsc_version') < WPSC_VERSION || get_option('wpsc_version') == WPSC_VERSION && get_option('wpsc_minor_version') < WPSC_MINOR_VERSION) {
        update_option('wpsc_version', WPSC_VERSION);
        update_option('wpsc_minor_version', WPSC_MINOR_VERSION);
    }
    $currency_data = $wpdb->get_var("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "currency_list`");
    if ($currency_data == 0) {
        $currency_array = explode("\n", $currency_sql);
        foreach ($currency_array as $currency_row) {
            $wpdb->query($currency_row);
        }
    }
    $add_initial_category = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "product_categories`;", ARRAY_A);
    if ($add_initial_category[0]['count'] == 0) {
        $wpdb->query("INSERT INTO `{$wpdb->prefix}wpsc_categorisation_groups` (`id`, `name`, `description`, `active`, `default`) VALUES (1, 'Categories', 'Product Categories', '1', '1')");
        $wpdb->query("INSERT INTO `{$wpdb->prefix}wpsc_categorisation_groups` (`id`, `name`, `description`, `active`, `default`) VALUES (2, 'Brands', 'Product Brands', '1', '0')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "product_categories` (`group_id`, `name` , `description`, `active`) VALUES ('1', '" . TXT_WPSC_EXAMPLECATEGORY . "', '" . TXT_WPSC_EXAMPLEDETAILS . "', '1');");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "product_categories` (`group_id`, `name` , `description`, `active`) VALUES ('2', '" . TXT_WPSC_EXAMPLEBRAND . "', '" . TXT_WPSC_EXAMPLEDETAILS . "', '1');");
    }
    $purchase_statuses_data = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "purchase_statuses`", ARRAY_A);
    if ($purchase_statuses_data[0]['count'] == 0) {
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "purchase_statuses` (`name` , `active` , `colour` ) \n    VALUES\n    ('" . TXT_WPSC_RECEIVED . "', '1', ''),\n    ('" . TXT_WPSC_ACCEPTED_PAYMENT . "', '1', ''),\n    ('" . TXT_WPSC_JOB_DISPATCHED . "', '1', ''),\n    ('" . TXT_WPSC_PROCESSED . "', '1', '');");
    }
    $check_category_assoc = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "item_category_associations`;", ARRAY_A);
    if ($check_category_assoc[0]['count'] == 0) {
        $sql = "SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `active`=1";
        $product_list = $wpdb->get_results($sql, ARRAY_A);
        foreach ((array) $product_list as $product) {
            $results = $wpdb->query("INSERT INTO `" . $wpdb->prefix . "item_category_associations` (`product_id` , `category_id` ) VALUES ('" . $product['id'] . "', '" . $product['category'] . "');");
        }
    }
    $add_regions = $wpdb->get_var("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "region_tax`");
    // exit($add_regions);
    if ($add_regions < 1) {
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Alberta', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'British Columbia', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Manitoba', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'New Brunswick', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Newfoundland', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Northwest Territories', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Nova Scotia', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Nunavut', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Ontario', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Prince Edward Island', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Quebec', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Saskatchewan', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '100', 'Yukon', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Alabama', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Alaska', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Arizona', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Arkansas', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'California', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Colorado', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Connecticut', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Delaware', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Florida', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Georgia', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Hawaii', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Idaho', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Illinois', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Indiana', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Iowa', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Kansas', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Kentucky', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Louisiana', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Maine', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Maryland', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Massachusetts', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Michigan', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Minnesota', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Mississippi', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Missouri', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Montana', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Nebraska', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Nevada', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'New Hampshire', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'New Jersey', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'New Mexico', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'New York', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'North Carolina', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'North Dakota', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Ohio', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Oklahoma', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Oregon', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Pennsylvania', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Rhode Island', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'South Carolina', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'South Dakota', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Tennessee', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Texas', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Utah', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Vermont', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Virginia', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Washington', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Washington DC', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'West Virginia', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Wisconsin', '0.00')");
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "region_tax` ( `country_id` , `name` , `tax` ) VALUES ( '136', 'Wyoming', '0.00')");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'AL' WHERE `name` IN('Alabama')LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'AK' WHERE `name` IN('Alaska') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'AZ' WHERE `name` IN('Arizona') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'AR' WHERE `name` IN('Arkansas') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'CA' WHERE `name` IN('California') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'CO' WHERE `name` IN('Colorado') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'CT' WHERE `name` IN('Connecticut') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'DE' WHERE `name` IN('Delaware') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'FL' WHERE `name` IN('Florida') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'GA' WHERE `name` IN('Georgia')  LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'HI' WHERE `name` IN('Hawaii')  LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'ID' WHERE`name` IN('Idaho')  LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'IL' WHERE `name` IN('Illinois')  LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'IN' WHERE `name` IN('Indiana')  LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'IA' WHERE `name` IN('Iowa')  LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'KS' WHERE `name` IN('Kansas')  LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'KY' WHERE `name` IN('Kentucky') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'LA' WHERE `name` IN('Louisiana') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'ME' WHERE `name` IN('Maine') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'MD' WHERE `name` IN('Maryland') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'MA' WHERE `name` IN('Massachusetts') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'MI' WHERE `name` IN('Michigan') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'MN' WHERE `name` IN('Minnesota') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'MS' WHERE `name` IN('Mississippi') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'MO' WHERE `name` IN('Missouri') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'MT' WHERE `name` IN('Montana') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'NE' WHERE `name` IN('Nebraska') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'NV' WHERE `name` IN('Nevada') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'NH' WHERE `name` IN('New Hampshire') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'NJ' WHERE `name` IN('New Jersey') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'NM' WHERE `name` IN('New Mexico') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'NY' WHERE `name` IN('New York') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'NC' WHERE `name` IN('North Carolina') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'ND' WHERE `name` IN('North Dakota') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'OH' WHERE `name` IN('Ohio') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'OK' WHERE `name` IN('Oklahoma') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'OR' WHERE `name` IN('Oregon') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'PA' WHERE `name` IN('Pennsylvania') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'RI' WHERE `name` IN('Rhode Island') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'SC' WHERE `name` IN('South Carolina') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'SD' WHERE `name` IN('South Dakota') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'TN' WHERE `name` IN('Tennessee') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'TX' WHERE `name` IN('Texas') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'UT' WHERE `name` IN('Utah') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'VT' WHERE `name` IN('Vermont') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'VA' WHERE `name` IN('Virginia') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'WA' WHERE `name` IN('Washington') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'DC' WHERE `name` IN('Washington DC') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'WV' WHERE `name` IN('West Virginia') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'WI' WHERE `name` IN('Wisconsin') LIMIT 1 ;");
        $wpdb->query("UPDATE `" . $wpdb->prefix . "region_tax` SET `code` = 'WY' WHERE `name` IN('Wyoming') LIMIT 1 ;");
    }
    $data_forms = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "collect_data_forms`", ARRAY_A);
    if ($data_forms[0]['count'] == 0) {
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "collect_data_forms` ( `name`, `type`, `mandatory`, `display_log`, `default`, `active`, `order`) VALUES ( '" . TXT_WPSC_YOUR_BILLING_CONTACT_DETAILS . "', 'heading', '0', '0', '', '1', 1),\n\t( '" . TXT_WPSC_FIRSTNAME . "', 'text', '1', '1', '', '1', 2),\n\t( '" . TXT_WPSC_LASTNAME . "', 'text', '1', '1', '', '1', 3),\n\t( '" . TXT_WPSC_ADDRESS . "', 'address', '1', '0', '', '1', 4),\n\t( '" . TXT_WPSC_CITY . "', 'city', '1', '0', '', '1', 5),\n\t( '" . TXT_WPSC_COUNTRY . "', 'country', '1', '0', '', '1', 7),\n\t( '" . TXT_WPSC_POSTAL_CODE . "', 'text', '0', '0', '', '1', 8),\n\t( '" . TXT_WPSC_EMAIL . "', 'email', '1', '1', '', '1', 9),\n\t( '" . TXT_WPSC_DELIVER_TO_A_FRIEND . "', 'heading', '0', '0', '', '1', 10),\n\t( '" . TXT_WPSC_FIRSTNAME . "', 'text', '0', '0', '', '1', 11),\n\t( '" . TXT_WPSC_LASTNAME . "', 'text', '0', '0', '', '1', 12),\n\t( '" . TXT_WPSC_ADDRESS . "', 'address', '0', '0', '', '1', 13),\n\t( '" . TXT_WPSC_CITY . "', 'city', '0', '0', '', '1', 14),\n\t( '" . TXT_WPSC_STATE . "', 'text', '0', '0', '', '1', 15),\n\t( '" . TXT_WPSC_COUNTRY . "', 'delivery_country', '0', '0', '', '1', 16),\n\t( '" . TXT_WPSC_POSTAL_CODE . "', 'text', '0', '0', '', '1', 17);");
        update_option('country_form_field', $country_form_id[0]['id']);
        update_option('email_form_field', $email_form_id[0]['id']);
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "collect_data_forms` ( `name`, `type`, `mandatory`, `display_log`, `default`, `active`, `order` ) VALUES ( '" . TXT_WPSC_PHONE . "', 'text', '1', '0', '', '1', '8');");
    }
    $product_brands_data = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "product_brands`", ARRAY_A);
    if ($product_brands_data[0]['count'] == 0) {
        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "product_brands` ( `name`, `description`, `active`, `order`) VALUES ( '" . TXT_WPSC_EXAMPLEBRAND . "','" . TXT_WPSC_EXAMPLEDETAILS . "', '1', '0');");
    }
    add_option('show_thumbnails', 1, TXT_WPSC_SHOWTHUMBNAILS, "yes");
    add_option('product_image_width', '', TXT_WPSC_PRODUCTIMAGEWIDTH, 'yes');
    add_option('product_image_height', '', TXT_WPSC_PRODUCTIMAGEHEIGHT, 'yes');
    add_option('category_image_width', '', TXT_WPSC_CATEGORYIMAGEWIDTH, 'yes');
    add_option('category_image_height', '', TXT_WPSC_CATEGORYIMAGEHEIGHT, 'yes');
    add_option('product_list_url', '', TXT_WPSC_PRODUCTLISTURL, 'yes');
    add_option('shopping_cart_url', '', TXT_WPSC_SHOPPINGCARTURL, 'yes');
    add_option('checkout_url', '', TXT_WPSC_CHECKOUTURL, 'yes');
    add_option('transact_url', '', TXT_WPSC_TRANSACTURL, 'yes');
    add_option('payment_gateway', '', TXT_WPSC_PAYMENTGATEWAY, 'yes');
    if (function_exists('register_sidebar')) {
        add_option('cart_location', '4', TXT_WPSC_CARTLOCATION, 'yes');
    } else {
        add_option('cart_location', '1', TXT_WPSC_CARTLOCATION, 'yes');
    }
    if (function_exists('register_sidebar')) {
        add_option('cart_location', '4', TXT_WPSC_CARTLOCATION, 'yes');
    } else {
        add_option('cart_location', '1', TXT_WPSC_CARTLOCATION, 'yes');
    }
    //add_option('show_categorybrands', '0', TXT_WPSC_SHOWCATEGORYBRANDS, 'yes');
    add_option('currency_type', '156', TXT_WPSC_CURRENCYTYPE, 'yes');
    add_option('currency_sign_location', '3', TXT_WPSC_CURRENCYSIGNLOCATION, 'yes');
    add_option('gst_rate', '1', TXT_WPSC_GSTRATE, 'yes');
    add_option('max_downloads', '1', TXT_WPSC_MAXDOWNLOADS, 'yes');
    add_option('display_pnp', '1', TXT_WPSC_DISPLAYPNP, 'yes');
    add_option('display_specials', '1', TXT_WPSC_DISPLAYSPECIALS, 'yes');
    add_option('do_not_use_shipping', '0', 'do_not_use_shipping', 'yes');
    add_option('postage_and_packaging', '0', TXT_WPSC_POSTAGEAND_PACKAGING, 'yes');
    add_option('purch_log_email', '', TXT_WPSC_PURCHLOGEMAIL, 'yes');
    add_option('return_email', '', TXT_WPSC_RETURNEMAIL, 'yes');
    add_option('terms_and_conditions', '', TXT_WPSC_TERMSANDCONDITIONS, 'yes');
    add_option('google_key', 'none', TXT_WPSC_GOOGLEMECHANTKEY, 'yes');
    add_option('google_id', 'none', TXT_WPSC_GOOGLEMECHANTID, 'yes');
    add_option('default_brand', 'none', TXT_WPSC_DEFAULTBRAND, 'yes');
    add_option('wpsc_default_category', 'none', TXT_WPSC_DEFAULTCATEGORY, 'yes');
    add_option('product_view', 'default', "", 'yes');
    add_option('add_plustax', 'default', "", '1');
    add_option('nzshpcrt_first_load', '0', "", 'yes');
    if (!(get_option('show_categorybrands') > 0 && get_option('show_categorybrands') < 3)) {
        update_option('show_categorybrands', 2);
    }
    //add_option('show_categorybrands', '0', TXT_WPSC_SHOWCATEGORYBRANDS, 'yes');
    /* PayPal options */
    add_option('paypal_business', '', TXT_WPSC_PAYPALBUSINESS, 'yes');
    add_option('paypal_url', '', TXT_WPSC_PAYPALURL, 'yes');
    //update_option('paypal_url', "https://www.sandbox.paypal.com/xclick");
    add_option('paypal_multiple_business', '', TXT_WPSC_PAYPALBUSINESS, 'yes');
    if (get_option('paypal_multiple_url') == null) {
        add_option('paypal_multiple_url', '', TXT_WPSC_PAYPALURL, 'yes');
        update_option('paypal_multiple_url', "https://www.paypal.com/cgi-bin/webscr");
    }
    add_option('product_ratings', '0', TXT_WPSC_SHOWPRODUCTRATINGS, 'yes');
    if (get_option('wpsc_selected_theme') == '') {
        add_option('wpsc_selected_theme', 'default', 'Selected Theme', 'yes');
        update_option('wpsc_selected_theme', "default");
    }
    if (!get_option('product_image_height')) {
        update_option('product_image_height', '96');
        update_option('product_image_width', '96');
    }
    if (!get_option('category_image_height')) {
        update_option('category_image_height', '96');
        update_option('category_image_width', '96');
    }
    if (!get_option('single_view_image_height')) {
        update_option('single_view_image_height', '128');
        update_option('single_view_image_width', '128');
    }
    wpsc_product_files_htaccess();
    /*
     * This part creates the pages and automatically puts their URLs into the options page.
     * As you can probably see, it is very easily extendable, just pop in your page and the deafult content in the array and you are good to go.
     */
    $post_date = date("Y-m-d H:i:s");
    $post_date_gmt = gmdate("Y-m-d H:i:s");
    $num = 0;
    $pages[$num]['name'] = 'products-page';
    $pages[$num]['title'] = TXT_WPSC_PRODUCTSPAGE;
    $pages[$num]['tag'] = '[productspage]';
    $pages[$num]['option'] = 'product_list_url';
    $num++;
    $pages[$num]['name'] = 'checkout';
    $pages[$num]['title'] = TXT_WPSC_CHECKOUT;
    $pages[$num]['tag'] = '[shoppingcart]';
    $pages[$num]['option'] = 'shopping_cart_url';
    //   $num++;
    //   $pages[$num]['name'] = 'enter-details';
    //   $pages[$num]['title'] = TXT_WPSC_ENTERDETAILS;
    //   $pages[$num]['tag'] = '[checkout]';
    //   $pages[2$num]['option'] = 'checkout_url';
    $num++;
    $pages[$num]['name'] = 'transaction-results';
    $pages[$num]['title'] = TXT_WPSC_TRANSACTIONRESULTS;
    $pages[$num]['tag'] = '[transactionresults]';
    $pages[$num]['option'] = 'transact_url';
    $num++;
    $pages[$num]['name'] = 'your-account';
    $pages[$num]['title'] = TXT_WPSC_YOUR_ACCOUNT;
    $pages[$num]['tag'] = '[userlog]';
    $pages[$num]['option'] = 'user_account_url';
    $newpages = false;
    $i = 0;
    $post_parent = 0;
    foreach ($pages as $page) {
        $check_page = $wpdb->get_row("SELECT * FROM `" . $wpdb->posts . "` WHERE `post_content` LIKE '%" . $page['tag'] . "%' LIMIT 1", ARRAY_A);
        if ($check_page == null) {
            if ($i == 0) {
                $post_parent = 0;
            } else {
                $post_parent = $first_id;
            }
            if ($wp_version >= 2.1) {
                $sql = "INSERT INTO " . $wpdb->posts . "\n        (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_type)\n        VALUES\n        ('1', '{$post_date}', '{$post_date_gmt}', '" . $page['tag'] . "', '', '" . $page['title'] . "', '', 'publish', 'closed', 'closed', '', '" . $page['name'] . "', '', '', '{$post_date}', '{$post_date_gmt}', '{$post_parent}', '0', 'page')";
            } else {
                $sql = "INSERT INTO " . $wpdb->posts . "\n        (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order)\n        VALUES\n        ('1', '{$post_date}', '{$post_date_gmt}', '" . $page['tag'] . "', '', '" . $page['title'] . "', '', 'static', 'closed', 'closed', '', '" . $page['name'] . "', '', '', '{$post_date}', '{$post_date_gmt}', '{$post_parent}', '0')";
            }
            $wpdb->query($sql);
            $post_id = $wpdb->insert_id;
            if ($i == 0) {
                $first_id = $post_id;
            }
            $wpdb->query("UPDATE {$wpdb->posts} SET guid = '" . get_permalink($post_id) . "' WHERE ID = '{$post_id}'");
            update_option($page['option'], get_permalink($post_id));
            if ($page['option'] == 'shopping_cart_url') {
                update_option('checkout_url', get_permalink($post_id));
            }
            $newpages = true;
            $i++;
        }
    }
    if ($newpages == true) {
        wp_cache_delete('all_page_ids', 'pages');
        $wp_rewrite->flush_rules();
    }
    /* adds nice names for permalinks for products */
    $check_product_names = $wpdb->get_results("SELECT `" . $wpdb->prefix . "product_list`.`id`, `" . $wpdb->prefix . "product_list`.`name`, `" . $wpdb->prefix . "wpsc_productmeta`.`meta_key` FROM `" . $wpdb->prefix . "product_list` LEFT JOIN `" . $wpdb->prefix . "wpsc_productmeta` ON `" . $wpdb->prefix . "product_list`.`id` = `" . $wpdb->prefix . "wpsc_productmeta`.`product_id` WHERE (`" . $wpdb->prefix . "wpsc_productmeta`.`meta_key` IN ('url_name') AND  `" . $wpdb->prefix . "wpsc_productmeta`.`meta_value` IN (''))  OR ISNULL(`" . $wpdb->prefix . "wpsc_productmeta`.`meta_key`)");
    if ($check_product_names != null) {
        $sql_query = "SELECT `id`, `name` FROM `" . $wpdb->prefix . "product_list` WHERE `active` IN('1')";
        $sql_data = $wpdb->get_results($sql_query, ARRAY_A);
        foreach ((array) $sql_data as $datarow) {
            $tidied_name = trim($datarow['name']);
            $tidied_name = strtolower($tidied_name);
            $url_name = preg_replace(array("/(\\s)+/", "/[^\\w-]+/"), array("-", ''), $tidied_name);
            $similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`meta_value`, '{$url_name}', '')) AS `max_number` FROM `" . $wpdb->prefix . "wpsc_productmeta` WHERE `meta_key` LIKE 'url_name' AND `meta_value` REGEXP '^({$url_name}){1}(\\d)*\$' ", ARRAY_A);
            $extension_number = '';
            if ($similar_names['count'] > 0) {
                $extension_number = (int) $similar_names['max_number'] + 1;
            }
            if (get_product_meta($datarow['id'], 'url_name') != false) {
                $current_url_name = get_product_meta($datarow['id'], 'url_name');
                if ($current_url_name[0] != $url_name) {
                    $url_name .= $extension_number;
                    update_product_meta($datarow['id'], 'url_name', $url_name);
                }
            } else {
                $url_name .= $extension_number;
                add_product_meta($datarow['id'], 'url_name', $url_name, true);
            }
        }
    }
    /* adds nice names for permalinks for categories */
    $check_category_names = $wpdb->get_results("SELECT DISTINCT `nice-name` FROM `" . $wpdb->prefix . "product_categories` WHERE `nice-name` IN ('') AND `active` IN ('1')");
    if ($check_category_names != null) {
        $sql_query = "SELECT `id`, `name` FROM `" . $wpdb->prefix . "product_categories` WHERE `active` IN('1')";
        $sql_data = $wpdb->get_results($sql_query, ARRAY_A);
        foreach ((array) $sql_data as $datarow) {
            $tidied_name = trim($datarow['name']);
            $tidied_name = strtolower($tidied_name);
            $url_name = preg_replace(array("/(\\s)+/", "/[^\\w-]+/"), array("-", ''), $tidied_name);
            $similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`nice-name`, '{$url_name}', '')) AS `max_number` FROM `" . $wpdb->prefix . "product_categories` WHERE `nice-name` REGEXP '^({$url_name}){1}(\\d)*\$' ", ARRAY_A);
            $extension_number = '';
            if ($similar_names['count'] > 0) {
                $extension_number = (int) $similar_names['max_number'] + 1;
            }
            $url_name .= $extension_number;
            $wpdb->query("UPDATE `" . $wpdb->prefix . "product_categories` SET `nice-name` = '{$url_name}' WHERE `id` = '" . $datarow['id'] . "' LIMIT 1 ;");
        }
        $wp_rewrite->flush_rules();
    }
    /* Moves images to thumbnails directory */
    // this code should no longer be needed, as most people will be using a sufficiently new version
    $image_dir = WPSC_FILE_PATH . "/images/";
    $product_images = WPSC_IMAGE_DIR;
    $product_thumbnails = WPSC_THUMBNAIL_DIR;
    if (!is_dir($product_thumbnails)) {
        @mkdir($product_thumbnails, 0775);
    }
    $product_list = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `image` != ''", ARRAY_A);
    foreach ((array) $product_list as $product) {
        if (!glob($product_thumbnails . $product['image'])) {
            $new_filename = $product['id'] . "_" . $product['image'];
            if (file_exists($image_dir . $product['image'])) {
                copy($image_dir . $product['image'], $product_thumbnails . $new_filename);
                if (file_exists($product_images . $product['image'])) {
                    copy($product_images . $product['image'], $product_images . $new_filename);
                }
                $wpdb->query("UPDATE `" . $wpdb->prefix . "product_list` SET `image` = '" . $new_filename . "' WHERE `id`='" . $product['id'] . "' LIMIT 1");
            } else {
                $imagedir = $product_thumbnails;
                $name = $new_filename;
                $new_image_path = $product_images . $product['image'];
                $imagepath = $product['image'];
                $height = get_option('product_image_height');
                $width = get_option('product_image_width');
                if (file_exists($product_images . $product['image'])) {
                    include "extra_image_processing.php";
                    copy($product_images . $product['image'], $product_images . $new_filename);
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "product_list` SET `image` = '" . $new_filename . "' WHERE `id`='" . $product['id'] . "' LIMIT 1");
                }
            }
        }
    }
    // */
}
Example #3
0
/**
 * wpsc_ajax_ie_save save changes made using inline edit
 *
 * @public
 *
 * @3.8
 * @returns nothing
 */
function wpsc_ajax_ie_save()
{
    $product_post_type = get_post_type_object('wpsc-product');
    if (!current_user_can($product_post_type->cap->edit_posts)) {
        echo '({"error":"' . __('Error: you don\'t have required permissions to edit this product', 'wpsc') . '", "id": "' . $_POST['id'] . '"})';
        die;
    }
    $product = array('ID' => $_POST['id'], 'post_title' => $_POST['title']);
    $id = wp_update_post($product);
    if ($id > 0) {
        //need parent meta to know which weight unit we are using
        $post = get_post($id);
        $parent_meta = get_product_meta($post->post_parent, 'product_metadata', true);
        $product_meta = get_product_meta($product['ID'], 'product_metadata', true);
        if (is_numeric($_POST['weight']) || empty($_POST['weight'])) {
            $product_meta['weight'] = wpsc_convert_weight($_POST['weight'], $parent_meta['weight_unit'], 'pound', true);
            $product_meta['weight_unit'] = $parent_meta['weight_unit'];
        }
        update_product_meta($product['ID'], 'product_metadata', $product_meta);
        update_product_meta($product['ID'], 'price', (double) $_POST['price']);
        update_product_meta($product['ID'], 'special_price', (double) $_POST['special_price']);
        update_product_meta($product['ID'], 'sku', $_POST['sku']);
        if (!is_numeric($_POST['stock'])) {
            update_product_meta($product['ID'], 'stock', '');
        } else {
            update_product_meta($product['ID'], 'stock', absint($_POST['stock']));
        }
        $post = get_post($id);
        $meta = get_product_meta($id, 'product_metadata', true);
        $price = get_product_meta($id, 'price', true);
        $special_price = get_product_meta($id, 'special_price', true);
        $sku = get_product_meta($id, 'sku', true);
        $sku = $sku ? $sku : __('N/A', 'wpsc');
        $stock = get_product_meta($id, 'stock', true);
        $stock = $stock === '' ? __('N/A', 'wpsc') : $stock;
        $results = array('id' => $id, 'title' => $post->post_title, 'weight' => wpsc_convert_weight($meta['weight'], 'pound', $parent_meta['weight_unit']), 'price' => wpsc_currency_display($price), 'special_price' => wpsc_currency_display($special_price), 'sku' => $sku, 'stock' => $stock);
        echo '(' . json_encode($results) . ')';
        die;
    } else {
        echo '({"error":"' . __('Error updating product', 'wpsc') . '", "id": "' . $_POST['id'] . '"})';
    }
    die;
}
Example #4
0
function wpsc_product_image_html($image_name, $product_id)
{
    global $wpdb, $wp_query;
    if (is_numeric($wp_query->query_vars['product_category'])) {
        $category_id = (int) $wp_query->query_vars['product_category'];
    } else {
        if (is_numeric($_GET['category'])) {
            $category_id = (int) $_GET['category'];
        } else {
            $category_id = (int) get_option('wpsc_default_category');
        }
    }
    $product['height'] = get_product_meta($id, 'thumbnail_height');
    $product['width'] = get_product_meta($id, 'thumbnail_width');
    $use_thumbnail_image = 'false';
    if ($product['height'] > $category['height'] || $product['width'] > $category['width']) {
        $use_thumbnail_image = 'true';
    }
    //list($category['height'], $category['width']) =
    if ($category_id > 0) {
        $category = $wpdb->get_row("SELECT `image_height` AS `height`, `image_width` AS `width` FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` WHERE `id` IN ('{$category_id}') LIMIT 1", ARRAY_A);
    }
    // if there is a height, width, and imagePNG function
    if ($category['height'] != null && $category['width'] != null && function_exists('ImagePNG')) {
        $image_path = "index.php?productid=" . $product_id . "&amp;thumbnail=" . $use_thumbnail_image . "&amp;width=" . $category['width'] . "&amp;height=" . $category['height'] . "";
    } else {
        $image_path = WPSC_THUMBNAIL_URL . $image_name;
        if (is_ssl()) {
            $image_path = str_replace("http://", "https://", $image_path);
        }
    }
    return $image_path;
}
Example #5
0
function wpsc_update_files()
{
    global $wpdb, $user_ID;
    $product_files = $wpdb->get_results("SELECT * FROM " . WPSC_TABLE_PRODUCT_FILES . "");
    $wpsc_update = WPSC_Update::get_instance();
    foreach ($product_files as $product_file) {
        $wpsc_update->check_timeout();
        $variation_post_ids = array();
        if (!empty($product_file->product_id)) {
            $product_post_id = (int) $wpdb->get_var($wpdb->prepare("SELECT `post_id` FROM `{$wpdb->postmeta}` WHERE meta_key = %s AND `meta_value` = %d LIMIT 1", '_wpsc_original_id', $product_file->product_id));
        } else {
            $product_post_id = (int) $wpdb->get_var("SELECT `id` FROM " . WPSC_TABLE_PRODUCT_LIST . " WHERE file=" . $product_file->id);
            $product_post_id = (int) $wpdb->get_var($wpdb->prepare("SELECT `post_id` FROM `{$wpdb->postmeta}` WHERE meta_key = %s AND `meta_value` = %d LIMIT 1", '_wpsc_original_id', $product_post_id));
        }
        $variation_items = $wpdb->get_col("SELECT `id` FROM " . WPSC_TABLE_VARIATION_PROPERTIES . " WHERE `file` = '{$product_file->id}'");
        if (count($variation_items) > 0) {
            $variation_post_ids = $wpdb->get_col("SELECT `post_id` FROM `{$wpdb->postmeta}` WHERE meta_key = '_wpsc_original_variation_id' AND `meta_value` IN(" . implode(", ", $variation_items) . ")");
        }
        $attachment_template = array('post_mime_type' => $product_file->mimetype, 'post_title' => $product_file->filename, 'post_name' => $product_file->idhash, 'post_content' => '', 'post_parent' => $product_post_id, 'post_type' => "wpsc-product-file", 'post_status' => 'inherit');
        $file_id = wpsc_get_meta($product_file->id, '_new_file_id', 'wpsc_files');
        if ($file_id == null && count($variation_post_ids) == 0) {
            $file_data = $attachment_template;
            $file_data['post_parent'] = $product_post_id;
            $new_file_id = wp_insert_post($file_data);
            wpsc_update_meta($product_file->id, '_new_file_id', $new_file_id, 'wpsc_files');
        }
        if (count($variation_post_ids) > 0) {
            foreach ($variation_post_ids as $variation_post_id) {
                $old_file_id = get_product_meta($variation_post_id, 'old_file_id', true);
                if ($old_file_id == null) {
                    $file_data = $attachment_template;
                    $file_data['post_parent'] = $variation_post_id;
                    $new_file_id = wp_insert_post($file_data);
                    update_product_meta($variation_post_id, 'old_file_id', $product_file->id, 'wpsc_files');
                }
            }
        }
        if (!empty($product_file->preview)) {
            $preview_template = array('post_mime_type' => $product_file->preview_mimetype, 'post_title' => $product_file->preview, 'post_name' => $product_file->filename, 'post_content' => '', 'post_parent' => $new_file_id, 'post_type' => "wpsc-product-preview", 'post_status' => 'inherit');
            wp_insert_post($preview_template);
        }
    }
    $download_ids = $wpdb->get_col("SELECT `id` FROM " . WPSC_TABLE_DOWNLOAD_STATUS . "");
    foreach ($download_ids as $download_id) {
        if (wpsc_get_meta($download_id, '_is_legacy', 'wpsc_downloads') !== 'false') {
            wpsc_update_meta($download_id, '_is_legacy', 'true', 'wpsc_downloads');
        }
    }
}
/**
 * wpsc the variation stock function
 * @return mixed - Stock level for the variation or FALSE if it can't be calculated
 */
function wpsc_the_variation_stock()
{
    global $wpsc_variations;
    if ($wpsc_variations->variation_count > 0) {
        $product_id = get_the_ID();
        $wpq = array('variations' => $wpsc_variations->variation->slug, 'post_status' => 'inherit', 'post_type' => 'wpsc-product', 'post_parent' => $product_id);
        $query = new WP_Query($wpq);
        // Should never happen
        if ($query->post_count != 1) {
            return false;
        }
        // Get the stock count
        $vp_id = $query->posts[0]->ID;
        $stock = get_product_meta($vp_id, "stock");
        $stock[0] = apply_filters('wpsc_product_variation_stock', $stock[0], $id);
        $output = $stock[0];
    } else {
        return false;
    }
    return $output;
}
Example #7
0
function wpsc_recreate_product_url_names()
{
    if (!current_user_can('manage_options')) {
        wp_die("You don't look like an administrator.");
    }
    global $wpdb;
    $product_data = $wpdb->get_results("SELECT `id`, `name` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `active` IN ('1')", ARRAY_A);
    echo "<pre>";
    foreach ($product_data as $product_row) {
        $product_id = $product_row['id'];
        $tidied_name = trim($product_row['name']);
        $tidied_name = strtolower($tidied_name);
        $url_name = sanitize_title($tidied_name);
        echo "<strong>Product {$product_id}:</strong> {$product_row['name']}\n";
        echo "Originally Proposed Name: {$url_name}\n";
        $similar_names = (array) $wpdb->get_col("SELECT `meta_value` FROM `" . WPSC_TABLE_PRODUCTMETA . "` WHERE `product_id` NOT IN('{$product_id}}') AND `meta_key` IN ('url_name') AND `meta_value` REGEXP '^(" . $wpdb->escape(preg_quote($url_name)) . "){1}[[:digit:]]*\$' ");
        if (array_search($url_name, $similar_names) !== false) {
            // If it is, try to add a number to the end, if that is taken, try the next highest number...
            $i = 0;
            do {
                $i++;
                if ($i > 100) {
                    break;
                }
                echo "Proposed Name #{$i}: " . ($url_name . $i) . "\n";
            } while (array_search($url_name . $i, $similar_names) !== false);
            // Concatenate the first number found that wasn't taken
            $url_name .= $i;
        }
        echo "Accepted Name: {$url_name}\n";
        $existing_name = get_product_meta($product_id, 'url_name', true);
        if (is_array($existing_name)) {
            $existing_name = array_pop($existing_name);
        }
        if ($existing_name != $url_name) {
            update_product_meta($product_id, 'url_name', $url_name);
        }
        echo "\n\n\n";
    }
}
function wpsc_update_alt_product_currency($product_id, $newCurrency, $newPrice)
{
    global $wpdb;
    $old_curr = get_product_meta($product_id, 'currency', true);
    $sql = $wpdb->prepare("SELECT `isocode` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`= %d", $newCurrency);
    $isocode = $wpdb->get_var($sql);
    $newCurrency = 'currency';
    $old_curr[$isocode] = $newPrice;
    if ($newPrice != '' && $newPrice > 0.0) {
        update_product_meta($product_id, $newCurrency, $old_curr);
    } else {
        if ((empty($old_curr[$isocode]) || 0.0 == $old_curr[$isocode]) && is_array($old_curr)) {
            unset($old_curr[$isocode]);
        }
        update_product_meta($product_id, $newCurrency, $old_curr);
    }
}
Example #9
0
function wpsc_you_save($args = null)
{
    $defaults = array('product_id' => false, 'type' => "percentage", 'variations' => false);
    $args = wp_parse_args($args, $defaults);
    extract($args, EXTR_SKIP);
    global $wpdb;
    if (!$product_id) {
        if (function_exists('wpsc_the_product_id')) {
            //select the variation ID with lowest price
            $product_id = $wpdb->get_var('SELECT `posts`.`id` FROM ' . $wpdb->posts . ' `posts` JOIN ' . $wpdb->postmeta . ' `postmeta` ON `posts`.`id` = `postmeta`.`post_id` WHERE `posts`.`post_parent` = ' . wpsc_the_product_id() . ' AND `posts`.`post_type` = "wpsc-product" AND `posts`.`post_status` = "inherit" AND `postmeta`.`meta_key`="_wpsc_price" ORDER BY (`postmeta`.`meta_value`)+0 ASC LIMIT 1');
            if (!$product_id) {
                $product_id = wpsc_the_product_id();
            }
        }
    }
    if (!$product_id) {
        return 0;
    }
    if ($variations) {
        $sale_price = wpsc_calculate_price((int) $_POST['product_id'], $variations, true);
    } else {
        $sale_price = get_product_meta($product_id, 'special_price', true);
    }
    //if sale price is zero, false, or anything similar - return false
    if (!$sale_price) {
        return 0;
    }
    if ($variations) {
        $regular_price = wpsc_calculate_price((int) $_POST['product_id'], $variations, false);
    } else {
        $regular_price = get_product_meta($product_id, 'price', true);
    }
    //if actual price is zero, false, or something similar, or is less than sale price - return false
    if (!$regular_price || !($sale_price < $regular_price)) {
        return 0;
    }
    switch ($type) {
        case "amount":
            return $regular_price - $sale_price;
            break;
        default:
            if (number_format(($regular_price - $sale_price) / $regular_price * 100, 2) == 100) {
                return 99.98999999999999;
            } else {
                return number_format(($regular_price - $sale_price) / $regular_price * 100, 2);
            }
    }
}
Example #10
0
 /**
  * save to database method
  * @access public
  *
  * @param integer purchase log id
  */
 function save_to_db($purchase_log_id)
 {
     global $wpdb, $wpsc_shipping_modules;
     if ($method === null) {
         $method = $this->cart->selected_shipping_method;
     }
     if (method_exists($wpsc_shipping_modules[$method], "get_item_shipping")) {
         $shipping = $wpsc_shipping_modules[$this->cart->selected_shipping_method]->get_item_shipping($this);
     }
     if ($this->cart->has_total_shipping_discount()) {
         $shipping = 0;
     }
     if ($this->apply_tax == true && wpsc_tax_isincluded() == false) {
         if (is_numeric($this->custom_tax_rate)) {
             $tax_rate = $this->custom_tax_rate;
         } else {
             $tax_rate = $this->cart->tax_percentage;
         }
         $tax = $this->unit_price * ($tax_rate / 100);
     } else {
         $tax = 0;
         $tax_rate = 0;
     }
     $wpdb->query($wpdb->prepare("INSERT INTO `" . WPSC_TABLE_CART_CONTENTS . "` (`prodid`, `name`, `purchaseid`, `price`, `pnp`,`tax_charged`, `gst`, `quantity`, `donation`, `no_shipping`, `custom_message`, `files`, `meta`) VALUES ('%d', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%d', '0', '%s', '%s', NULL)", $this->product_id, $this->product_name, $purchase_log_id, $this->unit_price, (double) $shipping, (double) $tax, (double) $tax_rate, $this->quantity, $this->is_donation, $this->custom_message, serialize($this->custom_file)));
     $cart_id = $wpdb->get_var("SELECT LAST_INSERT_ID() AS `id` FROM `" . WPSC_TABLE_CART_CONTENTS . "` LIMIT 1");
     foreach ((array) $this->variation_data as $variation_row) {
         $wpdb->query("INSERT INTO `" . WPSC_TABLE_CART_ITEM_VARIATIONS . "` ( `cart_id` , `variation_id` , `value_id` ) VALUES ( '" . $cart_id . "', '" . $variation_row['variation_id'] . "', '" . $variation_row['id'] . "' );");
     }
     $downloads = get_option('max_downloads');
     if ($this->is_downloadable == true) {
         //$product_files = $wpdb->get_row("SELECT `meta_value` FROM `".WPSC_TABLE_PRODUCTMETA."` WHERE `product_id` = '".$this->product_id."' AND `meta_key` = 'product_files'", ARRAY_A);
         //$product_files = unserialize($product_files["meta_value"]);
         $product_files = get_product_meta($this->product_id, 'product_files');
         if ($this->file_id != null) {
             // if the file is downloadable, check that the file is real
             if ($wpdb->get_var("SELECT `id` FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id` IN ('{$this->file_id}')")) {
                 $unique_id = sha1(uniqid(mt_rand(), true));
                 $wpdb->query("INSERT INTO `" . WPSC_TABLE_DOWNLOAD_STATUS . "` (`product_id` , `fileid` , `purchid` , `cartid`, `uniqueid`, `downloads` , `active` , `datetime` ) VALUES ( '{$this->product_id}', '{$this->file_id}', '{$purchase_log_id}', '{$cart_id}', '{$unique_id}', '{$downloads}', '0', NOW( ));");
             }
         } else {
             foreach ($product_files as $file) {
                 // if the file is downloadable, check that the file is real
                 if ($wpdb->get_var("SELECT `id` FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id` IN ('{$file}')")) {
                     $unique_id = sha1(uniqid(mt_rand(), true));
                     $wpdb->query("INSERT INTO `" . WPSC_TABLE_DOWNLOAD_STATUS . "` (`product_id` , `fileid` , `purchid` , `cartid`, `uniqueid`, `downloads` , `active` , `datetime` ) VALUES ( '{$this->product_id}', '{$file}', '{$purchase_log_id}', '{$cart_id}', '{$unique_id}', '{$downloads}', '0', NOW( ));");
                 }
             }
         }
     }
     do_action('wpsc_save_cart_item', $cart_id, $this->product_id);
 }
Example #11
0
function wpsc_install()
{
    global $wpdb, $user_level, $wp_rewrite, $wp_version;
    $table_name = $wpdb->prefix . "wpsc_product_list";
    $first_install = false;
    $result = mysql_list_tables(DB_NAME);
    $tables = array();
    while ($row = mysql_fetch_row($result)) {
        $tables[] = $row[0];
    }
    if (!in_array($table_name, $tables)) {
        $first_install = true;
        add_option('wpsc_purchaselogs_fixed', true);
    }
    if (get_option('wpsc_version') == null) {
        add_option('wpsc_version', WPSC_VERSION, 'wpsc_version', 'yes');
    }
    // run the create or update code here.
    wpsc_create_or_update_tables();
    wpsc_create_upload_directories();
    /* all code to add new database tables and columns must be above here */
    if (get_option('wpsc_version') < WPSC_VERSION || get_option('wpsc_version') == WPSC_VERSION && get_option('wpsc_minor_version') < WPSC_MINOR_VERSION) {
        update_option('wpsc_version', WPSC_VERSION);
        update_option('wpsc_minor_version', WPSC_MINOR_VERSION);
    }
    $add_initial_category = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "`;", ARRAY_A);
    if ($add_initial_category[0]['count'] == 0) {
        $wpdb->query("INSERT INTO `" . WPSC_TABLE_CATEGORISATION_GROUPS . "` (`id`, `name`, `description`, `active`, `default`) VALUES (1, 'Categories', 'Product Categories', '1', '1')");
        $wpdb->query("INSERT INTO `" . WPSC_TABLE_CATEGORISATION_GROUPS . "` (`id`, `name`, `description`, `active`, `default`) VALUES (2, 'Brands', 'Product Brands', '1', '0')");
        $wpdb->query("INSERT INTO `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` (`group_id`, `name` , `description`, `active`) VALUES ('1', '" . TXT_WPSC_EXAMPLECATEGORY . "', '" . TXT_WPSC_EXAMPLEDETAILS . "', '1');");
        $wpdb->query("INSERT INTO `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` (`group_id`, `name` , `description`, `active`) VALUES ('2', '" . TXT_WPSC_EXAMPLEBRAND . "', '" . TXT_WPSC_EXAMPLEDETAILS . "', '1');");
    }
    $purchase_statuses_data = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . WPSC_TABLE_PURCHASE_STATUSES . "`", ARRAY_A);
    if ($purchase_statuses_data[0]['count'] == 0) {
        $wpdb->query("INSERT INTO `" . WPSC_TABLE_PURCHASE_STATUSES . "` (`name` , `active` , `colour` ) \n    VALUES\n    ('" . TXT_WPSC_RECEIVED . "', '1', ''),\n    ('" . TXT_WPSC_ACCEPTED_PAYMENT . "', '1', ''),\n    ('" . TXT_WPSC_JOB_DISPATCHED . "', '1', ''),\n    ('" . TXT_WPSC_PROCESSED . "', '1', '');");
    }
    $check_category_assoc = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "`;", ARRAY_A);
    if ($check_category_assoc[0]['count'] == 0) {
        $sql = "SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `active`=1";
        $product_list = $wpdb->get_results($sql, ARRAY_A);
        foreach ((array) $product_list as $product) {
            $results = $wpdb->query("INSERT INTO `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "` (`product_id` , `category_id` ) VALUES ('" . $product['id'] . "', '" . $product['category'] . "');");
        }
    }
    add_option('show_thumbnails', 1, TXT_WPSC_SHOWTHUMBNAILS, "yes");
    add_option('product_image_width', '', TXT_WPSC_PRODUCTIMAGEWIDTH, 'yes');
    add_option('product_image_height', '', TXT_WPSC_PRODUCTIMAGEHEIGHT, 'yes');
    add_option('category_image_width', '', TXT_WPSC_CATEGORYIMAGEWIDTH, 'yes');
    add_option('category_image_height', '', TXT_WPSC_CATEGORYIMAGEHEIGHT, 'yes');
    add_option('product_list_url', '', TXT_WPSC_PRODUCTLISTURL, 'yes');
    add_option('shopping_cart_url', '', TXT_WPSC_SHOPPINGCARTURL, 'yes');
    add_option('checkout_url', '', TXT_WPSC_CHECKOUTURL, 'yes');
    add_option('transact_url', '', TXT_WPSC_TRANSACTURL, 'yes');
    add_option('payment_gateway', '', TXT_WPSC_PAYMENTGATEWAY, 'yes');
    if (function_exists('register_sidebar')) {
        add_option('cart_location', '4', TXT_WPSC_CARTLOCATION, 'yes');
    } else {
        add_option('cart_location', '1', TXT_WPSC_CARTLOCATION, 'yes');
    }
    if (function_exists('register_sidebar')) {
        add_option('cart_location', '4', TXT_WPSC_CARTLOCATION, 'yes');
    } else {
        add_option('cart_location', '1', TXT_WPSC_CARTLOCATION, 'yes');
    }
    //add_option('show_categorybrands', '0', TXT_WPSC_SHOWCATEGORYBRANDS, 'yes');
    add_option('currency_type', '156', TXT_WPSC_CURRENCYTYPE, 'yes');
    add_option('currency_sign_location', '3', TXT_WPSC_CURRENCYSIGNLOCATION, 'yes');
    add_option('gst_rate', '1', TXT_WPSC_GSTRATE, 'yes');
    add_option('max_downloads', '1', TXT_WPSC_MAXDOWNLOADS, 'yes');
    add_option('display_pnp', '1', TXT_WPSC_DISPLAYPNP, 'yes');
    add_option('display_specials', '1', TXT_WPSC_DISPLAYSPECIALS, 'yes');
    add_option('do_not_use_shipping', '0', 'do_not_use_shipping', 'yes');
    add_option('postage_and_packaging', '0', TXT_WPSC_POSTAGEAND_PACKAGING, 'yes');
    add_option('purch_log_email', '', TXT_WPSC_PURCHLOGEMAIL, 'yes');
    add_option('return_email', '', TXT_WPSC_RETURNEMAIL, 'yes');
    add_option('terms_and_conditions', '', TXT_WPSC_TERMSANDCONDITIONS, 'yes');
    add_option('google_key', 'none', TXT_WPSC_GOOGLEMECHANTKEY, 'yes');
    add_option('google_id', 'none', TXT_WPSC_GOOGLEMECHANTID, 'yes');
    add_option('default_brand', 'none', TXT_WPSC_DEFAULTBRAND, 'yes');
    add_option('wpsc_default_category', 'all', TXT_WPSC_DEFAULTCATEGORY, 'yes');
    add_option('product_view', 'default', "", 'yes');
    add_option('add_plustax', 'default', "", '1');
    add_option('nzshpcrt_first_load', '0', "", 'yes');
    if (!(get_option('show_categorybrands') > 0 && get_option('show_categorybrands') < 3)) {
        update_option('show_categorybrands', 2);
    }
    //add_option('show_categorybrands', '0', TXT_WPSC_SHOWCATEGORYBRANDS, 'yes');
    /* PayPal options */
    add_option('paypal_business', '', TXT_WPSC_PAYPALBUSINESS, 'yes');
    add_option('paypal_url', '', TXT_WPSC_PAYPALURL, 'yes');
    add_option('paypal_ipn', '1', TXT_WPSC_PAYPALURL, 'yes');
    //update_option('paypal_url', "https://www.sandbox.paypal.com/xclick");
    add_option('paypal_multiple_business', '', TXT_WPSC_PAYPALBUSINESS, 'yes');
    if (get_option('paypal_multiple_url') == null) {
        add_option('paypal_multiple_url', TXT_WPSC_PAYPALURL, 'yes');
        update_option('paypal_multiple_url', "https://www.paypal.com/cgi-bin/webscr");
    }
    add_option('product_ratings', '0', TXT_WPSC_SHOWPRODUCTRATINGS, 'yes');
    add_option('wpsc_email_receipt', TXT_WPSC_DEFAULT_PURCHASE_RECEIPT, 'yes');
    add_option('wpsc_email_admin', TXT_WPSC_DEFAULT_PURCHASE_REPORT, 'yes');
    if (get_option('wpsc_selected_theme') == '') {
        add_option('wpsc_selected_theme', 'default', 'Selected Theme', 'yes');
        update_option('wpsc_selected_theme', "default");
    }
    if (!get_option('product_image_height')) {
        update_option('product_image_height', '96');
        update_option('product_image_width', '96');
    }
    if (!get_option('category_image_height')) {
        update_option('category_image_height', '96');
        update_option('category_image_width', '96');
    }
    if (!get_option('single_view_image_height')) {
        update_option('single_view_image_height', '128');
        update_option('single_view_image_width', '128');
    }
    if (!get_option('wpsc_gallery_image_height')) {
        update_option('wpsc_gallery_image_height', '96');
        update_option('wpsc_gallery_image_width', '96');
    }
    if (!is_array(get_option('custom_gateway_options'))) {
        update_option('custom_gateway_options', array('testmode'));
    }
    add_option("wpsc_category_url_cache", array(), '', 'yes');
    wpsc_product_files_htaccess();
    /*
     * This part creates the pages and automatically puts their URLs into the options page.
     * As you can probably see, it is very easily extendable, just pop in your page and the deafult content in the array and you are good to go.
     */
    $post_date = date("Y-m-d H:i:s");
    $post_date_gmt = gmdate("Y-m-d H:i:s");
    $num = 0;
    $pages[$num]['name'] = 'products-page';
    $pages[$num]['title'] = TXT_WPSC_PRODUCTSPAGE;
    $pages[$num]['tag'] = '[productspage]';
    $pages[$num]['option'] = 'product_list_url';
    $num++;
    $pages[$num]['name'] = 'checkout';
    $pages[$num]['title'] = TXT_WPSC_CHECKOUT;
    $pages[$num]['tag'] = '[shoppingcart]';
    $pages[$num]['option'] = 'shopping_cart_url';
    //   $num++;
    //   $pages[$num]['name'] = 'enter-details';
    //   $pages[$num]['title'] = TXT_WPSC_ENTERDETAILS;
    //   $pages[$num]['tag'] = '[checkout]';
    //   $pages[2$num]['option'] = 'checkout_url';
    $num++;
    $pages[$num]['name'] = 'transaction-results';
    $pages[$num]['title'] = TXT_WPSC_TRANSACTIONRESULTS;
    $pages[$num]['tag'] = '[transactionresults]';
    $pages[$num]['option'] = 'transact_url';
    $num++;
    $pages[$num]['name'] = 'your-account';
    $pages[$num]['title'] = TXT_WPSC_YOUR_ACCOUNT;
    $pages[$num]['tag'] = '[userlog]';
    $pages[$num]['option'] = 'user_account_url';
    $newpages = false;
    $i = 0;
    $post_parent = 0;
    foreach ($pages as $page) {
        $check_page = $wpdb->get_row("SELECT * FROM `" . $wpdb->posts . "` WHERE `post_content` LIKE '%" . $page['tag'] . "%'  AND `post_type` NOT IN('revision') LIMIT 1", ARRAY_A);
        if ($check_page == null) {
            if ($i == 0) {
                $post_parent = 0;
            } else {
                $post_parent = $first_id;
            }
            if ($wp_version >= 2.1) {
                $sql = "INSERT INTO " . $wpdb->posts . "\n        (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_type)\n        VALUES\n        ('1', '{$post_date}', '{$post_date_gmt}', '" . $page['tag'] . "', '', '" . $page['title'] . "', '', 'publish', 'closed', 'closed', '', '" . $page['name'] . "', '', '', '{$post_date}', '{$post_date_gmt}', '{$post_parent}', '0', 'page')";
            } else {
                $sql = "INSERT INTO " . $wpdb->posts . "\n        (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order)\n        VALUES\n        ('1', '{$post_date}', '{$post_date_gmt}', '" . $page['tag'] . "', '', '" . $page['title'] . "', '', 'static', 'closed', 'closed', '', '" . $page['name'] . "', '', '', '{$post_date}', '{$post_date_gmt}', '{$post_parent}', '0')";
            }
            $wpdb->query($sql);
            $post_id = $wpdb->insert_id;
            if ($i == 0) {
                $first_id = $post_id;
            }
            $wpdb->query("UPDATE {$wpdb->posts} SET guid = '" . get_permalink($post_id) . "' WHERE ID = '{$post_id}'");
            update_option($page['option'], get_permalink($post_id));
            if ($page['option'] == 'shopping_cart_url') {
                update_option('checkout_url', get_permalink($post_id));
            }
            $newpages = true;
            $i++;
        }
    }
    if ($newpages == true) {
        wp_cache_delete('all_page_ids', 'pages');
        $wp_rewrite->flush_rules();
    }
    /* adds nice names for permalinks for products */
    $check_product_names = $wpdb->get_results("SELECT `" . WPSC_TABLE_PRODUCT_LIST . "`.`id`, `" . WPSC_TABLE_PRODUCT_LIST . "`.`name`, `" . WPSC_TABLE_PRODUCTMETA . "`.`meta_key` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` LEFT JOIN `" . WPSC_TABLE_PRODUCTMETA . "` ON `" . WPSC_TABLE_PRODUCT_LIST . "`.`id` = `" . WPSC_TABLE_PRODUCTMETA . "`.`product_id` WHERE (`" . WPSC_TABLE_PRODUCTMETA . "`.`meta_key` IN ('url_name') AND  `" . WPSC_TABLE_PRODUCTMETA . "`.`meta_value` IN (''))  OR ISNULL(`" . WPSC_TABLE_PRODUCTMETA . "`.`meta_key`)", ARRAY_A);
    if ($check_product_names != null) {
        foreach ((array) $check_product_names as $datarow) {
            $tidied_name = trim($datarow['name']);
            $tidied_name = strtolower($tidied_name);
            $url_name = sanitize_title($tidied_name);
            $similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`meta_value`, '{$url_name}', '')) AS `max_number` FROM `" . WPSC_TABLE_PRODUCTMETA . "` WHERE `meta_key` LIKE 'url_name' AND `meta_value` REGEXP '^({$url_name}){1}(\\d)*\$' ", ARRAY_A);
            $extension_number = '';
            if ($similar_names['count'] > 0) {
                $extension_number = (int) $similar_names['max_number'] + 1;
            }
            if (get_product_meta($datarow['id'], 'url_name') != false) {
                $current_url_name = get_product_meta($datarow['id'], 'url_name');
                if ($current_url_name != $url_name) {
                    $url_name .= $extension_number;
                    update_product_meta($datarow['id'], 'url_name', $url_name);
                }
            } else {
                $url_name .= $extension_number;
                add_product_meta($datarow['id'], 'url_name', $url_name, true);
            }
        }
    }
    /* adds nice names for permalinks for categories */
    $check_category_names = $wpdb->get_results("SELECT DISTINCT `nice-name` FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` WHERE `nice-name` IN ('') AND `active` IN ('1')");
    if ($check_category_names != null) {
        $sql_query = "SELECT `id`, `name` FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` WHERE `active` IN('1')";
        $sql_data = $wpdb->get_results($sql_query, ARRAY_A);
        foreach ((array) $sql_data as $datarow) {
            $tidied_name = trim($datarow['name']);
            $tidied_name = strtolower($tidied_name);
            $url_name = sanitize_title($tidied_name);
            $similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`nice-name`, '{$url_name}', '')) AS `max_number` FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` WHERE `nice-name` REGEXP '^({$url_name}){1}(\\d)*\$' ", ARRAY_A);
            $extension_number = '';
            if ($similar_names['count'] > 0) {
                $extension_number = (int) $similar_names['max_number'] + 1;
            }
            $url_name .= $extension_number;
            $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` SET `nice-name` = '{$url_name}' WHERE `id` = '" . $datarow['id'] . "' LIMIT 1 ;");
        }
        $wp_rewrite->flush_rules();
    }
    /* Moves images to thumbnails directory */
    // this code should no longer be needed, as most people will be using a sufficiently new version
    $image_dir = WPSC_FILE_PATH . "/images/";
    $product_images = WPSC_IMAGE_DIR;
    $product_thumbnails = WPSC_THUMBNAIL_DIR;
    if (!is_dir($product_thumbnails)) {
        @mkdir($product_thumbnails, 0775);
    }
    $product_list = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `image` != ''", ARRAY_A);
    foreach ((array) $product_list as $product) {
        if (!glob($product_thumbnails . $product['image'])) {
            $new_filename = $product['id'] . "_" . $product['image'];
            if (file_exists($image_dir . $product['image'])) {
                copy($image_dir . $product['image'], $product_thumbnails . $new_filename);
                if (file_exists($product_images . $product['image'])) {
                    copy($product_images . $product['image'], $product_images . $new_filename);
                }
                $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_LIST . "` SET `image` = '" . $new_filename . "' WHERE `id`='" . $product['id'] . "' LIMIT 1");
            } else {
                $imagedir = $product_thumbnails;
                $name = $new_filename;
                $new_image_path = $product_images . $product['image'];
                $imagepath = $product['image'];
                $height = get_option('product_image_height');
                $width = get_option('product_image_width');
                if (file_exists($product_images . $product['image'])) {
                    include "extra_image_processing.php";
                    copy($product_images . $product['image'], $product_images . $new_filename);
                    $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_LIST . "` SET `image` = '" . $new_filename . "' WHERE `id`='" . $product['id'] . "' LIMIT 1");
                }
            }
        }
    }
    // */
}
Example #12
0
/* adds nice names for permalinks for products */
$check_product_names = $wpdb->get_results("SELECT `" . $wpdb->prefix . "product_list`.`id`, `" . $wpdb->prefix . "product_list`.`name`, `" . $wpdb->prefix . "wpsc_productmeta`.`meta_key` FROM `" . $wpdb->prefix . "product_list` LEFT JOIN `" . $wpdb->prefix . "wpsc_productmeta` ON `" . $wpdb->prefix . "product_list`.`id` = `" . $wpdb->prefix . "wpsc_productmeta`.`product_id` WHERE (`" . $wpdb->prefix . "wpsc_productmeta`.`meta_key` IN ('url_name') AND  `" . $wpdb->prefix . "wpsc_productmeta`.`meta_value` IN (''))  OR ISNULL(`" . $wpdb->prefix . "wpsc_productmeta`.`meta_key`)");
if ($check_product_names != null) {
    $sql_query = "SELECT `id`, `name` FROM `" . $wpdb->prefix . "product_list` WHERE `active` IN('1')";
    $sql_data = $wpdb->get_results($sql_query, ARRAY_A);
    foreach ((array) $sql_data as $datarow) {
        $tidied_name = trim($datarow['name']);
        $tidied_name = strtolower($tidied_name);
        $url_name = preg_replace(array("/(\\s)+/", "/[^\\w-]+/"), array("-", ''), $tidied_name);
        $similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`meta_value`, '{$url_name}', '')) AS `max_number` FROM `" . $wpdb->prefix . "wpsc_productmeta` WHERE `meta_key` LIKE 'url_name' AND `meta_value` REGEXP '^({$url_name}){1}(\\d)*\$' ", ARRAY_A);
        $extension_number = '';
        if ($similar_names['count'] > 0) {
            $extension_number = (int) $similar_names['max_number'] + 1;
        }
        if (get_product_meta($datarow['id'], 'url_name') != false) {
            $current_url_name = get_product_meta($datarow['id'], 'url_name');
            if ($current_url_name != $url_name) {
                $url_name .= $extension_number;
                update_product_meta($datarow['id'], 'url_name', $url_name);
            }
        } else {
            $url_name .= $extension_number;
            add_product_meta($datarow['id'], 'url_name', $url_name, true);
        }
    }
}
/* creates table to store data on what was bought with what however many times */
if ($wpdb->get_var("SHOW TABLES LIKE '" . $wpdb->prefix . "also_bought_product'") != $wpdb->prefix . "also_bought_product") {
    $wpsc_also_bought_product = "CREATE TABLE `" . $wpdb->prefix . "also_bought_product` (\n  `id` bigint(20) unsigned NOT NULL auto_increment,\n  `selected_product` bigint(20) unsigned NOT NULL default '0',\n  `associated_product` bigint(20) unsigned NOT NULL default '0',\n  `quantity` int(10) unsigned NOT NULL default '0',\n  PRIMARY KEY  (`id`)\n) TYPE=MyISAM;";
    $wpdb->query($wpsc_also_bought_product);
}
function nzshpcrt_submit_checkout()
{
    /*
     * This is the function used for handling the submitted checkout page
     */
    global $wpdb, $nzshpcrt_gateways, $user_ID;
    session_start();
    if (get_option('permalink_structure') != '') {
        $seperator = "?";
    } else {
        $seperator = "&";
    }
    if ($_POST['submitwpcheckout'] == 'true') {
        $check_checkout_page = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->posts . "` WHERE `post_content` LIKE '%[checkout]%' LIMIT 1");
        if (is_numeric($check_checkout_page)) {
            $returnurl = "Location: " . get_option('shopping_cart_url') . $seperator . "total=" . $_GET['total'];
        } else {
            $returnurl = "Location: " . get_option('shopping_cart_url');
        }
        $_SESSION['collected_data'] = $_POST['collected_data'];
        $find_us = $_POST['how_find_us'];
        if (!($_POST['engrave1'] == '' && $_POST['engrave2'] == '')) {
            $engrave = $wpdb->escape($_POST['engrave1'] . "," . $_POST['engrave2']);
        }
        $any_bad_inputs = false;
        foreach ($_POST['collected_data'] as $value_id => $value) {
            $form_sql = "SELECT * FROM `" . $wpdb->prefix . "collect_data_forms` WHERE `id` = '{$value_id}' LIMIT 1";
            $form_data = $wpdb->get_results($form_sql, ARRAY_A);
            $form_data = $form_data[0];
            /*
            if($_POST['collected_data'][get_option('paypal_form_address')] != '')
            {
            $map_data['address'] = addslashes($_POST['collected_data'][get_option('paypal_form_address')]);
            }
            if($_POST['collected_data'][get_option('paypal_form_city')] != '')
            {
            $map_data['city'] = addslashes($_POST['collected_data'][get_option('paypal_form_city')]); 
            }
            if(preg_match("/^[a-zA-Z]{2}$/",$_SESSION['selected_country']))
            {
            $map_data['country'] = $_SESSION['selected_country'];
            }
            $map_data['zipcode']='';
            $map_data['radius'] = '50000';
            $map_data['state'] = '';
            $map_data['submit'] = 'Find Store';
            		
            $i=0;
            if (function_exists('getdistance')) {
            	$maps = getdistance($map_data);
            	while($rows = mysql_fetch_array($maps)) {
            		if ($i==0) {
            			$closest_store = $rows[5];
            		}
            		$i++;
            	}
            }
            //$wpdb->query("UPDATE `".$wpdb->prefix."purchase_logs` SET `closest_store` = '".$closest_store."' WHERE `id` = '".$log_id."' LIMIT 1 ;");
            */
            $bad_input = false;
            if ($form_data['mandatory'] == 1 || $form_data['type'] == "coupon") {
                switch ($form_data['type']) {
                    case "email":
                        if (!preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-.]+\\.[a-zA-Z]{2,5}\$/", $value)) {
                            $any_bad_inputs = true;
                            $bad_input = true;
                        }
                        break;
                    case "delivery_country":
                        break;
                    case "country":
                        break;
                    default:
                        if ($value == null) {
                            $any_bad_inputs = true;
                            $bad_input = true;
                        }
                        break;
                }
                /*
                if($form_data['type'] == "coupon") {
                	if($value != '') { // only act if data has been entered
                		$coupon_sql = "SELECT * FROM `".$wpdb->prefix."wpsc_coupon_codes` WHERE `coupon_code` = '".$value."' AND `active` = '1' LIMIT 1";
                		$coupon_data = $wpdb->get_results($coupon_sql,ARRAY_A);
                		if($coupon_data == null) {
                			$any_bad_inputs = true;
                			$bad_input = true;
                			}
                		}
                	}
                */
                if ($bad_input === true) {
                    switch ($form_data['name']) {
                        case TXT_WPSC_FIRSTNAME:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDNAME . "";
                            break;
                        case TXT_WPSC_LASTNAME:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDSURNAME . "";
                            break;
                        case TXT_WPSC_EMAIL:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDEMAILADDRESS . "";
                            break;
                        case TXT_WPSC_ADDRESS1:
                        case TXT_WPSC_ADDRESS2:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDADDRESS . "";
                            break;
                        case TXT_WPSC_CITY:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDCITY . "";
                            break;
                        case TXT_WPSC_PHONE:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDPHONENUMBER . "";
                            break;
                        case TXT_WPSC_COUNTRY:
                            $bad_input_message .= TXT_WPSC_PLEASESELECTCOUNTRY . "";
                            break;
                            //             case TXT_WPSC_COUPON:
                            //             $bad_input_message .= TXT_WPSC_COUPON_DOESNT_EXIST . "";
                            //             break;
                        //             case TXT_WPSC_COUPON:
                        //             $bad_input_message .= TXT_WPSC_COUPON_DOESNT_EXIST . "";
                        //             break;
                        default:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALID . " " . strtolower($form_data['name']) . ".";
                            break;
                    }
                    $bad_input_message .= "\n\r";
                }
            }
        }
        // this here section handles uploading files specified by the user for products
        $accepted_file_types['mime'][] = 'image/jpeg';
        $accepted_file_types['mime'][] = 'image/gif';
        $accepted_file_types['mime'][] = 'image/png';
        $accepted_file_types['ext'][] = 'jpeg';
        $accepted_file_types['ext'][] = 'jpg';
        $accepted_file_types['ext'][] = 'gif';
        $accepted_file_types['ext'][] = 'png';
        foreach ($_SESSION['nzshpcrt_cart'] as $key => $item) {
            $can_have_uploaded_image = get_product_meta($item->product_id, 'can_have_uploaded_image', true);
            if ($can_have_uploaded_image[0] == 'on') {
                $file_data['name'] = basename($_FILES['uploaded_image']['name'][$key]);
                $file_data['type'] = $_FILES['uploaded_image']['type'][$key];
                $file_data['tmp_name'] = $_FILES['uploaded_image']['tmp_name'][$key];
                $file_data['error'] = $_FILES['uploaded_image']['error'][$key];
                $file_data['size'] = $_FILES['uploaded_image']['size'][$key];
                $mime_type_data = wpsc_get_mimetype($file_data['tmp_name'], true);
                $name_parts = explode('.', basename($file_data['name']));
                $extension = array_pop($name_parts);
                echo $extension . "<br />";
                if ($mime_type_data['is_reliable'] == true) {
                    $mime_type = $mime_type_data['mime_type'];
                } else {
                    // if we can't use what PHP provides us with, we have to trust the user as there aren't really any other choices.
                    $mime_type = $file_data['type'];
                }
                if (array_search($mime_type, $accepted_file_types['mime']) !== false && array_search($extension, $accepted_file_types['ext']) !== false) {
                    if (is_file(WPSC_USER_UPLOADS_DIR . $file_data['name'])) {
                        $name_parts = explode('.', basename($file_data['name']));
                        $extension = array_pop($name_parts);
                        $name_base = implode('.', $name_parts);
                        $file_data['name'] = null;
                        $num = 2;
                        //  loop till we find a free file name, first time I get to do a do loop in yonks
                        do {
                            $test_name = "{$name_base}-{$num}.{$extension}";
                            if (!file_exists(WPSC_USER_UPLOADS_DIR . $test_name)) {
                                $file_data['name'] = $test_name;
                            }
                            $num++;
                        } while ($file_data['name'] == null);
                    }
                    //exit($file_data['name']);
                    if (move_uploaded_file($file_data['tmp_name'], WPSC_USER_UPLOADS_DIR . $file_data['name'])) {
                        $_SESSION['nzshpcrt_cart'][$key]->file_data = array('file_name' => $file_data['name'], 'mime_type' => $mime_type);
                    }
                }
            }
        }
        //echo("<pre>".print_r($_FILES,true)."</pre>");
        //exit("<pre>".print_r($_SESSION['nzshpcrt_cart'],true)."</pre>");
        foreach ((array) $_SESSION['nzshpcrt_cart'] as $item) {
            //exit("------><pre>".print_r((array)$_SESSION['nzshpcrt_cart'],1)."</pre>");
            $in_stock = check_in_stock($item->product_id, $item->product_variations, $item->quantity);
            if (get_option('checkbox_variation') == '1') {
                $in_stock = true;
            }
            if ($in_stock == false) {
                $bad_input_message .= TXT_WPSC_ITEM_GONE_OUT_OF_STOCK . "";
                $bad_input_message .= "\n\r";
                $any_bad_inputs = true;
                break;
            }
        }
        if (get_option('custom_gateway_options') == null) {
            $bad_input_message .= TXT_WPSC_PROCESSING_PROBLEM . "";
            $bad_input_message .= "\n\r";
            $any_bad_inputs = true;
        }
        list($bad_input_message, $any_bad_inputs) = apply_filters('wpsc_additional_checkout_checks', array($bad_input_message, $any_bad_inputs));
        //exit("<pre>".print_r($bad_input_message, true)."</pre>");
        if ($any_bad_inputs === true) {
            $_SESSION['nzshpcrt_checkouterr'] = nl2br($bad_input_message);
            header($returnurl);
            exit;
        }
        $cart = $_SESSION['nzshpcrt_cart'];
        $_SESSION['checkoutdata'] = $_POST;
        if ($_POST['agree'] != 'yes') {
            $_SESSION['nzshpcrt_checkouterr'] = TXT_WPSC_PLEASEAGREETERMSANDCONDITIONS;
            header($returnurl);
            exit;
        }
        if ($cart == null) {
            $_SESSION['nzshpcrt_checkouterr'] = TXT_WPSC_NOTHINGINYOURSHOPPINGCART;
            header($returnurl);
            exit;
        }
        $sessionid = mt_rand(100, 999) . time();
        if (!(is_numeric($user_ID) && $user_ID > 0)) {
            $user_ID = 'null';
        }
        if (isset($_SESSION['usps_shipping']) && is_numeric($_SESSION['usps_shipping'])) {
            $base_shipping = $_SESSION['usps_shipping'];
        } else {
            $base_shipping = nzshpcrt_determine_base_shipping(0, $_SESSION['delivery_country']);
        }
        //clear the coupon
        //$_SESSION['coupon_num'] = '';
        //insert the record into the purchase log table
        //exit("----->". $_SESSION['delivery_country']);
        $price = nzshpcrt_overall_total_price($_SESSION['selected_country'], false);
        $sql = "INSERT INTO `" . $wpdb->prefix . "purchase_logs` ( `totalprice` , `sessionid` , `date`, `billing_country`, `shipping_country`,`base_shipping`,`shipping_region`, `user_ID`, `discount_value`, `discount_data`, `find_us`, `engravetext`, `google_status`) VALUES ( '" . $wpdb->escape($price) . "', '" . $sessionid . "', '" . time() . "', '" . $_SESSION['selected_country'] . "', '" . $_SESSION['delivery_country'] . "', '" . $base_shipping . "','" . $_SESSION['selected_region'] . "' , '" . (int) $user_ID . "' , '" . (double) $_SESSION['wpsc_discount'] . "', '" . $wpdb->escape($_SESSION['coupon_num']) . "', '', '{$engrave}', ' ')";
        //exit($sql);
        $wpdb->query($sql);
        $email_user_detail = '';
        $log_id = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->prefix . "purchase_logs` WHERE `sessionid` IN('" . $sessionid . "') LIMIT 1");
        foreach ($_POST['collected_data'] as $value_id => $value) {
            $wpdb->query("INSERT INTO `" . $wpdb->prefix . "submited_form_data` ( `log_id` , `form_id` , `value` ) VALUES ( '" . $log_id . "', '" . $value_id . "', '" . $value . "');");
        }
        if (function_exists("nzshpcrt_user_log")) {
            if ($wpdb->get_var("SHOW TABLES LIKE '" . $wpdb->prefix . "usermeta'")) {
                $saved_data_sql = "SELECT * FROM `" . $wpdb->prefix . "usermeta` WHERE `user_id` = '" . $user_ID . "' AND `meta_key` = 'wpshpcrt_usr_profile';";
                $saved_data = $wpdb->get_row($saved_data_sql, ARRAY_A);
                $new_meta_data = serialize($_POST['collected_data']);
                if ($saved_data != null) {
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "usermeta` SET `meta_value` =  '{$new_meta_data}' WHERE `user_id` IN ('{$user_ID}') AND `meta_key` IN ('wpshpcrt_usr_profile');");
                } else {
                    if (is_numeric($user_ID)) {
                        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "usermeta` ( `user_id` , `meta_key` , `meta_value` ) VALUES ( " . $user_ID . ", 'wpshpcrt_usr_profile', '{$new_meta_data}');");
                    }
                }
            }
        }
        $downloads = get_option('max_downloads');
        $also_bought = array();
        $all_donations = true;
        $all_no_shipping = true;
        foreach ($cart as $cart_item) {
            $row = $cart_item->product_id;
            $quantity = $cart_item->quantity;
            $variations = $cart_item->product_variations;
            $extras = $cart_item->extras;
            // serialize file data
            if (is_array($cart_item->file_data)) {
                $file_data = $wpdb->escape(serialize($cart_item->file_data));
            } else {
                $file_data = '';
            }
            /* creates an array of purchased items for logging further on */
            if (isset($also_bought[$cart_item->product_id])) {
                $also_bought[$cart_item->product_id]++;
            } else {
                $also_bought[$cart_item->product_id] = 1;
            }
            $product_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id` = '{$row}' LIMIT 1", ARRAY_A);
            if ($product_data['file'] > 0) {
                $unique_id = sha1(uniqid(mt_rand(), true));
                $wpdb->query("INSERT INTO `" . $wpdb->prefix . "download_status` ( `fileid` , `purchid` , `uniqueid`, `downloads` , `active` , `datetime` ) VALUES ( '" . $product_data['file'] . "', '" . $log_id . "', '" . $unique_id . "', '{$downloads}', '0', NOW( ));");
            }
            if ($product_data['donation'] == 1) {
                $price = $cart_item->donation_price;
                $gst = 0;
                $donation = 1;
            } else {
                $price = calculate_product_price($row, $variations);
                if ($product_data['notax'] != 1) {
                    $price = nzshpcrt_calculate_tax($price, $_SESSION['selected_country'], $_SESSION['selected_region']);
                    if (get_option('base_country') == $_SESSION['selected_country']) {
                        $country_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "currency_list` WHERE `isocode` IN('" . get_option('base_country') . "') LIMIT 1", ARRAY_A);
                        if ($country_data['has_regions'] == 1) {
                            if (get_option('base_region') == $_SESSION['selected_region']) {
                                $region_data = $wpdb->get_row("SELECT `" . $wpdb->prefix . "region_tax`.* FROM `" . $wpdb->prefix . "region_tax` WHERE `" . $wpdb->prefix . "region_tax`.`country_id` IN('" . $country_data['id'] . "') AND `" . $wpdb->prefix . "region_tax`.`id` IN('" . get_option('base_region') . "') ", ARRAY_A);
                            }
                            $gst = $region_data['tax'];
                        } else {
                            $gst = $country_data['tax'];
                        }
                    }
                } else {
                    $gst = 0;
                }
                $donation = 0;
                $all_donations = false;
            }
            if ($product_data['no_shipping'] != 1) {
                $all_no_shipping = false;
            }
            $country = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "submited_form_data` WHERE `log_id`='" . $log_id . "' AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1", ARRAY_A);
            $country = $country[0]['value'];
            $country_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "currency_list` WHERE `isocode` IN('" . get_option('base_country') . "') LIMIT 1", ARRAY_A);
            $shipping = nzshpcrt_determine_item_shipping($row, 1, $_SESSION['delivery_country']);
            $cartsql = "INSERT INTO `" . $wpdb->prefix . "cart_contents` ( `prodid` , `purchaseid`, `price`, `pnp`, `gst`, `quantity`, `donation`, `no_shipping`, `files` ) VALUES ('" . $row . "', '" . $log_id . "','" . $price . "','" . $shipping . "', '" . $gst . "','" . $quantity . "', '" . $donation . "', '" . $product_data['no_shipping'] . "', '{$file_data}')";
            //exit($cartsql);
            $wpdb->query($cartsql);
            $cart_id = $wpdb->get_results("SELECT LAST_INSERT_ID() AS `id` FROM `" . $wpdb->prefix . "product_variations` LIMIT 1", ARRAY_A);
            $cart_id = $cart_id[0]['id'];
            $extra_var = '';
            if ($variations != null) {
                $extra_var .= '[';
                $i = 0;
                foreach ($variations as $variation => $value) {
                    $wpdb->query("INSERT INTO `" . $wpdb->prefix . "cart_item_variations` ( `cart_id` , `variation_id` , `value_id` ) VALUES ( '" . $cart_id . "', '" . $variation . "', '" . $value . "' );");
                    $i++;
                    if ($i == 1) {
                        $extra_var .= $value;
                    } else {
                        $extra_var .= "," . $value;
                    }
                }
            }
            $j = 0;
            $extra_var .= '],[';
            if ($extras != null) {
                foreach ($extras as $extra) {
                    $wpdb->query("INSERT INTO `" . $wpdb->prefix . "cart_item_extras` ( `cart_id` , `extra_id`) VALUES ( '" . $cart_id . "', '" . $extra . "');");
                    $name = $wpdb->get_var("SELECT name FROM " . $wpdb->prefix . "extras_values WHERE id={$extra}");
                    $j++;
                    if ($j == 1) {
                        $extra_var .= $name;
                    } else {
                        $extra_var .= "," . $name;
                    }
                }
                $extra_var .= ']';
            }
            /*
            	if (function_exists('sendemailstostores')) {
            		if ($_POST['pickupordelivery']==1){
            			$delivery = "Pick Up";
            		} else {
            			$delivery = "Delivery";
            		}
            		$chosen_store = $_POST['chosen_store'];
            		$email_sql = "SELECT * FROM locations WHERE storename='".$chosen_store."'";
            		$email_data = $wpdb->get_results($email_sql,ARRAY_A);
            		
            		$email_message = "Order: ".$product_data['name']." with additional variations : ".$extra_var."<br>";
            		$email_message .= "<br>";
            		$email_message .= "Delivery/Pick Up:".$delivery;
            		$email_message .= "<br>";
            		$email_message .= "Customer detail: <br>";
            		$email_message .= "Name:". $_POST['collected_data'][get_option('paypal_form_first_name')]." ".$_POST['collected_data'][get_option('paypal_form_last_name')]."<br>";
            		$email_message .= "Address: ".$map_data['address']."<br>";
            		$email_message .= "City:".$map_data['city'];
            		sendemailstostores($email_data[0]['url'],'New Order',$email_message);
            	}*/
            /*
             * This code decrements the stock quantitycart_item_variations`
             */
            if (is_array($variations)) {
                $variation_values = array_values($variations);
            }
            //$debug .= "<pre>".print_r($variations,true)."</pre>";
            if ($product_data['quantity_limited'] == 1) {
                switch (count($variation_values)) {
                    case 2:
                        $variation_stock_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "variation_priceandstock` WHERE `product_id` = '" . $product_data['id'] . "' AND (`variation_id_1` = '" . $variation_values[0] . "' AND `variation_id_2` = '" . $variation_data[1] . "') OR (`variation_id_1` = '" . $variation_values[1] . "' AND `variation_id_2` = '" . $variation_values[0] . "') LIMIT 1", ARRAY_A);
                        //$debug .= "<pre>".print_r($variation_stock_data,true)."</pre>";
                        $wpdb->query("UPDATE `" . $wpdb->prefix . "variation_priceandstock` SET `stock` = '" . ($variation_stock_data['stock'] - $quantity) . "'  WHERE `id` = '" . $variation_stock_data['id'] . "' LIMIT 1", ARRAY_A);
                        break;
                    case 1:
                        $variation_stock_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "variation_priceandstock` WHERE `product_id` = '" . $product_data['id'] . "' AND (`variation_id_1` = '" . $variation_values[0] . "' AND `variation_id_2` = '0') LIMIT 1", ARRAY_A);
                        //$debug .= "<pre>".print_r($variation_stock_data,true)."</pre>";
                        $wpdb->query("UPDATE `" . $wpdb->prefix . "variation_priceandstock` SET `stock` = '" . ($variation_stock_data['stock'] - $quantity) . "'  WHERE `id` = '" . $variation_stock_data['id'] . "' LIMIT 1", ARRAY_A);
                        break;
                    default:
                        /* normal form of decrementing stock */
                        $wpdb->query("UPDATE `" . $wpdb->prefix . "product_list` SET `quantity`='" . ($product_data['quantity'] - $quantity) . "' WHERE `id`='" . $product_data['id'] . "' LIMIT 1");
                        break;
                }
            }
        }
        $unneeded_value = null;
        //this is only used to store the quantity for the item we are working on, so that we can get the array key
        $assoc_quantity = null;
        foreach ($also_bought as $selected_product => $unneeded_value) {
            foreach ($also_bought as $associated_product => $assoc_quantity) {
                if ($selected_product == $associated_product) {
                    continue;
                    //don't want to associate products with themselves
                }
                $check_assoc = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->prefix . "also_bought_product` WHERE `selected_product` IN('{$selected_product}') AND `associated_product` IN('{$associated_product}') LIMIT 1");
                if (isset($check_assoc) && $check_assoc > 0) {
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "also_bought_product` SET `quantity` = (`quantity` + {$assoc_quantity}) WHERE `id` = '{$check_assoc}' LIMIT 1;");
                } else {
                    $wpdb->query("INSERT INTO `" . $wpdb->prefix . "also_bought_product` ( `selected_product` , `associated_product` , `quantity` ) VALUES ( '{$selected_product}', '" . $associated_product . "', '" . $assoc_quantity . "' );");
                }
            }
        }
        do_action('wpsc_submit_checkout', $log_id);
        //mail( get_option('purch_log_email'),('debug from '.date("d/m/Y H:i:s")), $debug);
        $curgateway = get_option('payment_gateway');
        //	if (get_option('custom_gateway')) {
        $selected_gateways = get_option('custom_gateway_options');
        if (count($selected_gateways) > 1) {
            if (in_array($_POST['custom_gateway'], (array) $selected_gateways)) {
                $curgateway = $_POST['custom_gateway'];
            } else {
                $curgateway = get_option('payment_gateway');
            }
        } else {
            if (count($selected_gateways) == 1) {
                $curgateway = array_pop($selected_gateways);
            }
        }
        //} else {
        //	$curgateway = get_option('payment_gateway');
        //}
        if (get_option('permalink_structure') != '') {
            $seperator = "?";
        } else {
            $seperator = "&";
        }
        if ($_POST['payment_method'] == 2 && get_option('payment_method') == 2 || get_option('payment_method') == 3) {
            foreach ($nzshpcrt_gateways as $gateway) {
                if ($gateway['internalname'] == 'testmode') {
                    $gateway_used = $gateway['internalname'];
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "purchase_logs` SET `gateway` = '" . $gateway_used . "' WHERE `id` = '" . $log_id . "' LIMIT 1 ;");
                    $gateway['function']($seperator, $sessionid);
                }
            }
        } else {
            foreach ($nzshpcrt_gateways as $gateway) {
                if ($gateway['internalname'] == $curgateway) {
                    $gateway_used = $gateway['internalname'];
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "purchase_logs` SET `gateway` = '" . $gateway_used . "' WHERE `id` = '" . $log_id . "' LIMIT 1 ;");
                    $gateway['function']($seperator, $sessionid);
                }
            }
        }
        $_SESSION['coupon_num'] = '';
        //exit("<pre>".print_r($nzshpcrt_gateways,true)."</pre>");
    }
}
function wpsc_purchaselog_details_SKU()
{
    global $purchlogitem;
    //	exit('<pre>'.print_r($purchlogitem->purchitem,true).'</pre>');
    $meta_value = get_product_meta($purchlogitem->purchitem->prodid, 'sku');
    if ($meta_value == '') {
        return 'N/A';
    } else {
        return $meta_value;
    }
}
Example #15
0
function wpsc_purchase_log_csv()
{
    global $wpdb, $wpsc_gateways;
    get_currentuserinfo();
    $count = 0;
    if ('key' == $_REQUEST['rss_key'] && current_user_can('manage_options')) {
        if (isset($_REQUEST['start_timestamp']) && isset($_REQUEST['end_timestamp'])) {
            $start_timestamp = $_REQUEST['start_timestamp'];
            $end_timestamp = $_REQUEST['end_timestamp'];
            $start_end_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `date` BETWEEN '%d' AND '%d' ORDER BY `date` DESC";
            $start_end_sql = apply_filters('wpsc_purchase_log_start_end_csv', $start_end_sql);
            $data = $wpdb->get_results($wpdb->prepare($start_end_sql, $start_timestamp, $end_timestamp), ARRAY_A);
            $csv_name = 'Purchase Log ' . date("M-d-Y", $start_timestamp) . ' to ' . date("M-d-Y", $end_timestamp) . '.csv';
        } elseif (isset($_REQUEST['m'])) {
            $year = (int) substr($_REQUEST['m'], 0, 4);
            $month = (int) substr($_REQUEST['m'], -2);
            $month_year_sql = "\n\t\t\t\tSELECT *\n\t\t\t\tFROM " . WPSC_TABLE_PURCHASE_LOGS . "\n\t\t\t\tWHERE YEAR(FROM_UNIXTIME(date)) = %d AND MONTH(FROM_UNIXTIME(date)) = %d\n\t\t\t";
            $month_year_sql = apply_filters('wpsc_purchase_log_month_year_csv', $month_year_sql);
            $data = $wpdb->get_results($wpdb->prepare($month_year_sql, $year, $month), ARRAY_A);
            $csv_name = 'Purchase Log ' . $month . '/' . $year . '.csv';
        } else {
            $sql = apply_filters('wpsc_purchase_log_month_year_csv', "SELECT * FROM " . WPSC_TABLE_PURCHASE_LOGS);
            $data = $wpdb->get_results($sql, ARRAY_A);
            $csv_name = "All Purchase Logs.csv";
        }
        $form_sql = "SELECT * FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `active` = '1' AND `type` != 'heading' ORDER BY `checkout_order` DESC;";
        $form_data = $wpdb->get_results($form_sql, ARRAY_A);
        $csv = 'Purchase ID, Price, Firstname, Lastname, Email, Order Status, Data, ';
        $headers = "\"Purchase ID\",\"Purchase Total\",";
        //capture the headers
        $headers2 = "\"Payment Gateway\",";
        $headers2 .= "\"Payment Status\",\"Purchase Date\",";
        $output = '';
        foreach ((array) $data as $purchase) {
            $form_headers = '';
            $output .= "\"" . $purchase['id'] . "\",";
            //Purchase ID
            $output .= "\"" . $purchase['totalprice'] . "\",";
            //Purchase Total
            foreach ((array) $form_data as $form_field) {
                $form_headers .= "\"" . $form_field['unique_name'] . "\",";
                $collected_data_sql = "SELECT * FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id` = '" . $purchase['id'] . "' AND `form_id` = '" . $form_field['id'] . "' LIMIT 1";
                $collected_data = $wpdb->get_results($collected_data_sql, ARRAY_A);
                $collected_data = $collected_data[0];
                $output .= "\"" . $collected_data['value'] . "\",";
                // get form fields
            }
            if (isset($wpsc_gateways[$purchase['gateway']]) && isset($wpsc_gateways[$purchase['gateway']]['display_name'])) {
                $output .= "\"" . $wpsc_gateways[$purchase['gateway']]['display_name'] . "\",";
            } else {
                $output .= "\"\",";
            }
            $status_name = wpsc_find_purchlog_status_name($purchase['processed']);
            $output .= "\"" . $status_name . "\",";
            //get purchase status
            $output .= "\"" . date("jS M Y", $purchase['date']) . "\",";
            //date
            $cartsql = "SELECT `prodid`, `quantity`, `name` FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase['id'] . "";
            $cart = $wpdb->get_results($cartsql, ARRAY_A);
            if ($count < count($cart)) {
                $count = count($cart);
            }
            // Go through all products in cart and display quantity and sku
            foreach ((array) $cart as $item) {
                $skuvalue = get_product_meta($item['prodid'], 'sku', true);
                if (empty($skuvalue)) {
                    $skuvalue = __('N/A', 'wpsc');
                }
                $output .= "\"" . $item['quantity'] . " x " . str_replace('"', '\\"', $item['name']) . "\"";
                $output .= "," . $skuvalue . ",";
            }
            $output .= "\n";
            // terminates the row/line in the CSV file
        }
        // Get the most number of products and create a header for them
        $headers3 = "";
        for ($i = 0; $i < $count; $i++) {
            $headers3 .= "\"Quantity - Product Name \", \" SKU \"";
            if ($i < $count - 1) {
                $headers3 .= ",";
            }
        }
        $headers = apply_filters('wpsc_purchase_log_csv_headers', $headers . $form_headers . $headers2 . $headers3, $data, $form_data);
        $output = apply_filters('wpsc_purchase_log_csv_output', $output, $data, $form_data);
        header('Content-Type: text/csv');
        header('Content-Disposition: inline; filename="' . $csv_name . '"');
        echo $headers . "\n" . $output;
        exit;
    }
}
function wpsc_add_product($product_values)
{
    global $wpdb;
    // takes an array, inserts it into the database as a product
    $success = false;
    $insertsql = "INSERT INTO `" . WPSC_TABLE_PRODUCT_LIST . "` SET";
    $insertsql .= "`name` = '" . $wpdb->escape($product_values['name']) . "',";
    $insertsql .= "`description`  = '" . $wpdb->escape($product_values['description']) . "',";
    $insertsql .= "`additional_description`  = '" . $wpdb->escape($product_values['additional_description']) . "',";
    $insertsql .= "`price` = '" . $wpdb->escape($product_values['price']) . "',";
    $insertsql .= "`quantity_limited` = '" . $wpdb->escape($product_values['quantity_limited']) . "',";
    $insertsql .= "`quantity` = '" . $wpdb->escape($product_values['quantity']) . "',";
    $insertsql .= "`special` = '" . $wpdb->escape($product_values['special']) . "',";
    $insertsql .= "`special_price` = '" . $wpdb->escape($product_values['special_price']) . "',";
    $insertsql .= "`weight` = '" . $wpdb->escape($product_values['weight']) . "',";
    $insertsql .= "`weight_unit` = '" . $wpdb->escape($product_values['weight_unit']) . "',";
    $insertsql .= "`no_shipping` = '" . $wpdb->escape($product_values['no_shipping']) . "',";
    $insertsql .= "`pnp` = '" . $wpdb->escape($product_values['pnp']) . "',";
    $insertsql .= "`international_pnp` = '" . $wpdb->escape($product_values['international_pnp']) . "',";
    $insertsql .= "`donation` = '" . $wpdb->escape($product_values['donation']) . "',";
    $insertsql .= "`display_frontpage` = '" . $wpdb->escape($product_values['display_frontpage']) . "',";
    $insertsql .= "`notax` = '" . $wpdb->escape($product_values['notax']) . "',";
    $insertsql .= "`image` = '0',";
    $insertsql .= "`file` = '0',";
    $insertsql .= "`thumbnail_state` = '0' ;";
    //Insert the data
    if ($wpdb->query($insertsql)) {
        // if we succeeded, we have a product id, we wants it for the next stuff
        $product_id = $wpdb->get_var("SELECT LAST_INSERT_ID() AS `id` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` LIMIT 1");
        // add the tags
        if (function_exists('wp_insert_term')) {
            product_tag_init();
            $tags = $product_values['product_tag'];
            if ($tags != "") {
                $tags = explode(',', $tags);
                foreach ($tags as $tag) {
                    $tt = wp_insert_term((string) $tag, 'product_tag');
                }
                $return = wp_set_object_terms($product_id, $tags, 'product_tag');
            }
        }
        $image = wpsc_item_process_image($product_id, $product_values['image_path'], basename($product_values['image_path']), $product_values['width'], $product_values['height'], $product_values['image_resize']);
        if ($image != null) {
            $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_LIST . "` SET `image` = '" . $wpdb->escape($image) . "' WHERE `id`='" . $product_id . "' LIMIT 1");
        }
        // add the product meta values
        if ($product_values['productmeta_values'] != null) {
            foreach ((array) $product_values['productmeta_values'] as $key => $value) {
                if (get_product_meta($product_id, $key) != false) {
                    update_product_meta($product_id, $key, $value);
                } else {
                    add_product_meta($product_id, $key, $value);
                }
            }
        }
        // and the custom meta values
        if ($product_values['new_custom_meta'] != null) {
            foreach ((array) $product_values['new_custom_meta']['name'] as $key => $name) {
                $value = $product_values['new_custom_meta']['value'][(int) $key];
                if ($name != '' && $value != '') {
                    add_product_meta($product_id, $name, $value, false, true);
                }
            }
        }
        // Add the tidy url name
        $tidied_name = trim($product_values['name']);
        $tidied_name = strtolower($tidied_name);
        $url_name = sanitize_title($tidied_name);
        $similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`meta_value`, '" . $wpdb->escape($url_name) . "', '')) AS `max_number` FROM `" . WPSC_TABLE_PRODUCTMETA . "` WHERE `meta_key` IN ('url_name') AND `meta_value` REGEXP '^(" . $wpdb->escape($url_name) . "){1}(\\d)*\$' ", ARRAY_A);
        $extension_number = '';
        if ($similar_names['count'] > 0) {
            $extension_number = (int) $similar_names['max_number'] + 1;
        }
        $url_name .= $extension_number;
        add_product_meta($product_id, 'url_name', $url_name, true);
        // Add the varations and associated values
        $variations_procesor = new nzshpcrt_variations();
        if ($product_values['variation_values'] != null) {
            $variations_procesor->add_to_existing_product($product_id, $product_values['variation_values']);
        }
        if ($product_values['variation_priceandstock'] != null) {
            $variations_procesor->update_variation_values($product_id, $product_values['variation_priceandstock']);
        }
        // Add the selelcted categories
        $item_list = '';
        if (count($product_values['category']) > 0) {
            foreach ($product_values['category'] as $category_id) {
                $category_id = (int) $category_id;
                $check_existing = $wpdb->get_var("SELECT `id` FROM `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "` WHERE `product_id` = " . $product_id . " AND `category_id` = '{$category_id}' LIMIT 1");
                if ($check_existing == null) {
                    $wpdb->query("INSERT INTO `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "` ( `product_id` , `category_id` ) VALUES ( '" . $product_id . "', '" . $category_id . "');");
                }
            }
        }
        $success = true;
    }
    return $success;
}
Example #17
0
 /**
  * user provided file method
  * @access public
  * @param string shipping method
  * @return boolean true on sucess, false on failure
  */
 function save_provided_file($file_data)
 {
     global $wpdb;
     $accepted_file_types['mime'][] = 'image/jpeg';
     $accepted_file_types['mime'][] = 'image/gif';
     $accepted_file_types['mime'][] = 'image/png';
     $accepted_file_types['mime'][] = 'image/pjpeg';
     // Added for IE compatibility
     $accepted_file_types['mime'][] = 'image/x-png';
     // Added for IE compatibility
     $accepted_file_types['ext'][] = 'jpeg';
     $accepted_file_types['ext'][] = 'jpg';
     $accepted_file_types['ext'][] = 'gif';
     $accepted_file_types['ext'][] = 'png';
     $can_have_uploaded_image = get_product_meta($this->product_id, 'product_metadata', true);
     $product = get_post($this->product_id);
     if (0 != $product->post_parent) {
         $product = get_post($product->post_parent);
         $can_have_uploaded_image = get_product_meta($product->ID, 'product_metadata', true);
     }
     $can_have_uploaded_image = $can_have_uploaded_image['can_have_uploaded_image'];
     if ('on' == $can_have_uploaded_image || 1 == $can_have_uploaded_image) {
         $name_parts = explode('.', basename($file_data['name']));
         $extension = array_pop($name_parts);
         if ((array_search($file_data['type'], $accepted_file_types['mime']) !== false || get_option('wpsc_check_mime_types') == 1) && array_search($extension, $accepted_file_types['ext']) !== false) {
             if (is_file(WPSC_USER_UPLOADS_DIR . $file_data['name'])) {
                 $name_parts = explode('.', basename($file_data['name']));
                 $extension = array_pop($name_parts);
                 $name_base = implode('.', $name_parts);
                 $file_data['name'] = null;
                 $num = 2;
                 //  loop till we find a free file name, first time I get to do a do loop in yonks
                 do {
                     $test_name = "{$name_base}-{$num}.{$extension}";
                     if (!file_exists(WPSC_USER_UPLOADS_DIR . $test_name)) {
                         $file_data['name'] = $test_name;
                     }
                     $num++;
                 } while ($file_data['name'] == null);
             }
             $unique_id = sha1(uniqid(rand(), true));
             if (move_uploaded_file($file_data['tmp_name'], WPSC_USER_UPLOADS_DIR . $file_data['name'])) {
                 $this->custom_file = array('file_name' => $file_data['name'], 'mime_type' => $file_data['type'], 'unique_id' => $unique_id);
             }
         }
     }
 }
function wpsc_main_product_image_menu($product_id)
{
    global $wpdb;
    $thumbnail_state = 0;
    if ($product_id > 0) {
        $main_image = $wpdb->get_row("SELECT `images`.*,  `product`.`thumbnail_state` FROM `" . WPSC_TABLE_PRODUCT_IMAGES . "` AS `images` JOIN `" . WPSC_TABLE_PRODUCT_LIST . "` AS `product` ON `product`.`image` = `images`.`id`  WHERE `product`.`id` = '{$product_id}' LIMIT 1", ARRAY_A);
        $thumbnail_state = $main_image['thumbnail_state'];
    } else {
        $thumbnail_state = 1;
    }
    $sendback = wp_get_referer();
    $presentation_link = add_query_arg('page', 'wpsc-settings', $sendback);
    $presentation_link = add_query_arg('tab', 'presentation#thumb_settings', $presentation_link);
    $thumbnail_image_height = get_product_meta($product_id, 'thumbnail_height');
    $thumbnail_image_width = get_product_meta($product_id, 'thumbnail_width');
    // 	echo $thumbnail_image_height;
    // 	echo "|";
    // 	echo $thumbnail_image_width;
    ob_start();
    ?>
	<div class='image_settings_box'>
		<div class='upper_settings_box'>
			<div class='upper_image'><img src='<?php 
    echo WPSC_URL;
    ?>
/images/pencil.png' alt='' /></div>
			<div class='upper_txt'><?php 
    _e('Thumbnail Settings');
    ?>
<a class='closeimagesettings'>X</a></div>
		</div>

		<div class='lower_settings_box'>
			<input type='hidden' id='current_thumbnail_image' name='current_thumbnail_image' value='S' />
			<ul>		

				<li>
					<input type='radio' name='gallery_resize' value='1' id='gallery_resize1' class='image_resize' onclick='image_resize_extra_forms(this)' /> <label for='gallery_resize1'><?php 
    echo TXT_WPSC_USEDEFAULTSIZE;
    ?>
(<a href='<?php 
    echo $presentation_link;
    ?>
' title='<?php 
    echo TXT_WPSC_SETONSETTINGS;
    ?>
'><?php 
    echo get_option('product_image_height');
    ?>
&times;<?php 
    echo get_option('product_image_width');
    ?>
px</a>)
					</label>

				</li>
				
				<li>
					<input type='radio' <?php 
    echo $thumbnail_state != 2 ? "checked='checked'" : "";
    ?>
 name='gallery_resize' value='0' id='gallery_resize0' class='image_resize' onclick='image_resize_extra_forms(this)' /> <label for='gallery_resize0'> <?php 
    echo TXT_WPSC_DONOTRESIZEIMAGE;
    ?>
</label><br />
				</li>
				
				<li>
					<input type='radio' <?php 
    echo $thumbnail_state == 2 ? "checked='checked'" : "";
    ?>
  name='gallery_resize' value='2' id='gallery_resize2' class='image_resize' onclick='image_resize_extra_forms(this)' /> <label for='gallery_resize2'><?php 
    echo TXT_WPSC_USESPECIFICSIZE;
    ?>
 </label>
					<div class='heightWidth image_resize_extra_forms' <?php 
    echo $thumbnail_state == 2 ? "style='display: block;'" : "";
    ?>
>
						<input id='gallery_image_width' type='text' size='4' name='gallery_width' value='<?php 
    echo $thumbnail_image_width;
    ?>
' /><label for='gallery_image_width'><?php 
    echo TXT_WPSC_PXWIDTH;
    ?>
</label>
						<input id='gallery_image_height' type='text' size='4' name='gallery_height' value='<?php 
    echo $thumbnail_image_height;
    ?>
' /><label for='gallery_image_height'><?php 
    echo TXT_WPSC_PXHEIGHT;
    ?>
 </label>
					</div>
				</li>

				<li>
					<input type='radio'  name='gallery_resize' value='3' id='gallery_resize3' class='image_resize'  onclick='image_resize_extra_forms(this)' /> <label for='gallery_resize3'> <?php 
    echo TXT_WPSC_SEPARATETHUMBNAIL;
    ?>
</label><br />
					<div class='browseThumb image_resize_extra_forms'>
						<input type='file' name='gallery_thumbnailImage' size='15' value='' />
					</div>
				</li>
				<li>
				<a href='<?php 
    echo htmlentities("admin.php?wpsc_admin_action=crop_image&imagename=" . $main_image['image'] . "&imgheight=" . $image_data[1] . "&imgwidth=" . $image_data[0] . "&width=630&height=500&product_id=" . $product_id);
    ?>
' title='Crop Image' class='thickbox'>Crop This Image Using jCrop</a>

				</li>
				<li>
					<a href='#' class='delete_primary_image delete_button'>Delete this Image</a>
				</li>

			</ul>
		</div>
	</div>
	<a class='editButton'>Edit   <img src='<?php 
    echo WPSC_URL;
    ?>
/images/pencil.png' alt='' /></a>
	<?php 
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
/**
 * Spits out the current products details in a table row for manage products page and variations on edit product page.
 * @access public
 *
 * @deprecated since 3.8.9
 * @since 3.8
 * @param $product (Object), $parent_product (Int) Note: I believe parent_product is unused
 */
function wpsc_product_row(&$product, $parent_product = null)
{
    _wpsc_deprecated_function(__FUNCTION__, '3.8.9');
    global $mode, $current_user, $wpsc_products;
    //is this good practice? <*****@*****.**>
    static $rowclass, $object_terms_cache = array();
    // store terms associated with variants inside a cache array. This only requires 1 DB query.
    if (empty($object_terms_cache)) {
        $ids = wp_list_pluck($wpsc_products, 'ID');
        $object_terms = wp_get_object_terms($ids, 'wpsc-variation', array('fields' => 'all_with_object_id'));
        foreach ($object_terms as $term) {
            if (!array_key_exists($term->object_id, $object_terms_cache)) {
                $object_terms_cache[$term->object_id] = array();
            }
            $object_terms_cache[$term->object_id][$term->parent] = $term->name;
        }
    }
    $global_product = $product;
    setup_postdata($product);
    $product_post_type_object = get_post_type_object('wpsc-product');
    $current_user_can_edit_this_product = current_user_can($product_post_type_object->cap->edit_post, $product->ID);
    $rowclass = 'alternate' == $rowclass ? '' : 'alternate';
    $post_owner = $current_user->ID == $product->post_author ? 'self' : 'other';
    $edit_link = get_edit_post_link($product->ID);
    if (isset($object_terms_cache[$product->ID])) {
        ksort($object_terms_cache[$product->ID]);
        $title = implode(', ', $object_terms_cache[$product->ID]);
    } else {
        $title = get_the_title($product->ID);
    }
    if (empty($title)) {
        $title = __('(no title)', 'wp-e-commerce');
    }
    ?>

	<tr id='post-<?php 
    echo $product->ID;
    ?>
' class='<?php 
    echo trim($rowclass . ' author-' . $post_owner . ' status-' . $product->post_status);
    ?>
 iedit <?php 
    if (get_option('wpsc_sort_by') == 'dragndrop') {
        echo 'product-edit';
    }
    ?>
' valign="top">
	<?php 
    $posts_columns = get_column_headers('wpsc-product_variants');
    if (empty($posts_columns)) {
        $posts_columns = array('image' => '', 'title' => __('Name', 'wp-e-commerce'), 'weight' => __('Weight', 'wp-e-commerce'), 'stock' => __('Stock', 'wp-e-commerce'), 'price' => __('Price', 'wp-e-commerce'), 'sale_price' => __('Sale Price', 'wp-e-commerce'), 'SKU' => __('SKU', 'wp-e-commerce'), 'hidden_alerts' => '');
    }
    foreach ($posts_columns as $column_name => $column_display_name) {
        $attributes = "class=\"{$column_name} column-{$column_name}\"";
        switch ($column_name) {
            case 'date':
                /* !date case */
                if ('0000-00-00 00:00:00' == $product->post_date && 'date' == $column_name) {
                    $t_time = $h_time = __('Unpublished', 'wp-e-commerce');
                    $time_diff = 0;
                } else {
                    $t_time = get_the_time(__('Y/m/d g:i:s A', 'wp-e-commerce'));
                    $m_time = $product->post_date;
                    $time = get_post_time('G', true, $post);
                    $time_diff = time() - $time;
                    if ($time_diff > 0 && $time_diff < 24 * 60 * 60) {
                        $h_time = sprintf(__('%s ago', 'wp-e-commerce'), human_time_diff($time));
                    } else {
                        $h_time = mysql2date(__('Y/m/d', 'wp-e-commerce'), $m_time);
                    }
                }
                echo '<td ' . $attributes . '>';
                if ('excerpt' == $mode) {
                    echo apply_filters('post_date_column_time', $t_time, $post, $column_name, $mode);
                } else {
                    echo '<abbr title="' . $t_time . '">' . apply_filters('post_date_column_time', $h_time, $post, $column_name, $mode) . '</abbr>';
                }
                echo '<br />';
                if ('publish' == $product->post_status) {
                    _e('Published', 'wp-e-commerce');
                } elseif ('future' == $product->post_status) {
                    if ($time_diff > 0) {
                        echo '<strong class="attention">' . __('Missed schedule', 'wp-e-commerce') . '</strong>';
                    } else {
                        _e('Scheduled', 'wp-e-commerce');
                    }
                } else {
                    _e('Last Modified', 'wp-e-commerce');
                }
                echo '</td>';
                break;
            case 'title':
                /* !title case */
                $attributes = 'class="post-title column-title"';
                $edit_link = wp_nonce_url($edit_link, 'edit-product_' . $product->ID);
                ?>
		<td <?php 
                echo $attributes;
                ?>
>
			<strong>
			<?php 
                if ($current_user_can_edit_this_product && $product->post_status != 'trash') {
                    ?>
				<span><a class="row-title" href="<?php 
                    echo esc_url($edit_link);
                    ?>
" title="<?php 
                    echo esc_attr(sprintf(__('Edit &#8220;%s&#8221;', 'wp-e-commerce'), $title));
                    ?>
"><?php 
                    echo esc_html($title);
                    ?>
</a></span>
				<?php 
                    if ($parent_product) {
                        ?>
					<a href="<?php 
                        echo esc_url($edit_link);
                        ?>
" title="<?php 
                        echo esc_attr(sprintf(__('Edit &#8220;%s&#8221;', 'wp-e-commerce'), $title));
                        ?>
"><?php 
                        echo esc_html($title);
                        ?>
</a>

				<?php 
                    }
                    ?>
			<?php 
                } else {
                    echo esc_html($title);
                }
                _post_states($product);
                $product_alert = apply_filters('wpsc_product_alert', array(false, ''), $product);
                if (!empty($product_alert['messages'])) {
                    $product_alert['messages'] = implode("\n", (array) $product_alert['messages']);
                }
                if ($product_alert['state'] === true) {
                    ?>
				<img alt='<?php 
                    echo $product_alert['messages'];
                    ?>
' title='<?php 
                    echo $product_alert['messages'];
                    ?>
' class='product-alert-image' src='<?php 
                    echo WPSC_CORE_IMAGES_URL;
                    ?>
/product-alert.jpg' alt='' />
				<?php 
                }
                // If a product alert has stuff to display, show it.
                // Can be used to add extra icons etc
                if (!empty($product_alert['display'])) {
                    echo $product_alert['display'];
                }
                ?>
			</strong>
			<?php 
                $has_var = '';
                if (!$parent_product && wpsc_product_has_children($product->ID)) {
                    $has_var = 'wpsc_has_variation';
                }
                $actions = array();
                if ($current_user_can_edit_this_product && 'trash' != $product->post_status) {
                    $actions['edit'] = '<a class="edit-product" href="' . $edit_link . '" title="' . esc_attr__('Edit this product', 'wp-e-commerce') . '">' . __('Edit', 'wp-e-commerce') . '</a>';
                    //commenting this out for now as we are trying new variation ui quick edit boxes are open by default so we dont need this link.
                    //$actions['quick_edit'] = "<a class='wpsc_editinline ".$has_var."' title='".esc_attr(__('Quick Edit', 'wp-e-commerce'))."' href='#'>".__('Quick Edit', 'wp-e-commerce')."</a>";
                }
                $actions = apply_filters('post_row_actions', $actions, $product);
                $action_count = count($actions);
                $i = 0;
                echo '<div class="row-actions">';
                foreach ($actions as $action => $link) {
                    ++$i;
                    $i == $action_count ? $sep = '' : ($sep = ' | ');
                    echo "<span class='{$action}'>{$link}{$sep}</span>";
                }
                echo '</div>';
                ?>
		</td>
		<?php 
                break;
            case 'image':
                /* !image case */
                ?>
			<td class="product-image ">
			<?php 
                $attachment_args = array('post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $product->ID, 'orderby' => 'menu_order', 'order' => 'ASC');
                if (isset($product->ID) && has_post_thumbnail($product->ID)) {
                    echo get_the_post_thumbnail($product->ID, 'admin-product-thumbnails');
                } else {
                    $image_url = WPSC_CORE_IMAGES_URL . "/no-image-uploaded.gif";
                    ?>
					<img title='<?php 
                    esc_attr_e('Drag to a new position', 'wp-e-commerce');
                    ?>
' src='<?php 
                    echo esc_url($image_url);
                    ?>
' alt='<?php 
                    echo esc_attr($title);
                    ?>
' width='38' height='38' />
			<?php 
                }
                ?>
			</td>
			<?php 
                break;
            case 'price':
                /* !price case */
                $price = get_product_meta($product->ID, 'price', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<?php 
                echo wpsc_currency_display($price);
                ?>
					<input type="text" class="wpsc_ie_field wpsc_ie_price" value="<?php 
                echo esc_attr($price);
                ?>
">
					<a href="<?php 
                echo $edit_link;
                ?>
/#wpsc_downloads"><?php 
                esc_html_e('Variant Download Files', 'wp-e-commerce');
                ?>
</a>
				</td>
			<?php 
                break;
            case 'weight':
                $product_data['meta'] = array();
                $product_data['meta'] = get_post_meta($product->ID, '');
                foreach ($product_data['meta'] as $meta_name => $meta_value) {
                    $product_data['meta'][$meta_name] = maybe_unserialize(array_pop($meta_value));
                }
                $product_data['transformed'] = array();
                if (!isset($product_data['meta']['_wpsc_product_metadata']['weight'])) {
                    $product_data['meta']['_wpsc_product_metadata']['weight'] = "";
                }
                if (!isset($product_data['meta']['_wpsc_product_metadata']['weight_unit'])) {
                    $product_data['meta']['_wpsc_product_metadata']['weight_unit'] = "";
                }
                $product_data['transformed']['weight'] = wpsc_convert_weight($product_data['meta']['_wpsc_product_metadata']['weight'], "pound", $product_data['meta']['_wpsc_product_metadata']['weight_unit'], false);
                $weight = $product_data['transformed']['weight'];
                if ($weight == '') {
                    $weight = '0';
                }
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo esc_html($weight);
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_weight" value="<?php 
                echo esc_attr($weight);
                ?>
">
					<a href="<?php 
                echo $edit_link;
                ?>
/#wpsc_tax"><?php 
                esc_html_e('Set Variant Tax', 'wp-e-commerce');
                ?>
</a>
				</td>
			<?php 
                break;
            case 'stock':
                $stock = get_post_meta($product->ID, '_wpsc_stock', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo $stock ? $stock : __('N/A', 'wp-e-commerce');
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_stock" value="<?php 
                echo esc_attr($stock);
                ?>
">
					<a href="<?php 
                echo $edit_link;
                ?>
/#wpsc_shipping"><?php 
                esc_html_e('Set Variant Shipping', 'wp-e-commerce');
                ?>
</a>
				</td>
	<?php 
                break;
            case 'categories':
                /* !categories case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><?php 
                $categories = get_the_product_category($product->ID);
                if (!empty($categories)) {
                    $out = array();
                    foreach ($categories as $c) {
                        $out[] = "<a href='admin.php?page=wpsc-edit-products&amp;category={$c->slug}'> " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'category', 'display')) . "</a>";
                    }
                    echo join(', ', $out);
                } else {
                    esc_html_e('Uncategorized', 'wp-e-commerce');
                }
                ?>
</td>
		<?php 
                break;
            case 'tags':
                /* !tags case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><?php 
                $tags = get_the_tags($product->ID);
                if (!empty($tags)) {
                    $out = array();
                    foreach ($tags as $c) {
                        $out[] = "<a href='edit.php?tag={$c->slug}'> " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'post_tag', 'display')) . "</a>";
                    }
                    echo join(', ', $out);
                } else {
                    esc_html_e('No Tags', 'wp-e-commerce');
                }
                ?>
</td>
		<?php 
                break;
            case 'SKU':
                $sku = get_post_meta($product->ID, '_wpsc_sku', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo $sku ? $sku : esc_html__('N/A', 'wp-e-commerce');
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_sku" value="<?php 
                echo esc_attr($sku);
                ?>
">
										<input type="hidden" class="wpsc_ie_id wpsc_ie_field" value="<?php 
                echo $product->ID;
                ?>
">
					<div class="wpsc_inline_actions"><input type="button" class="button-primary wpsc_ie_save" value="Save"><img src="<?php 
                echo admin_url('images/wpspin_light.gif');
                ?>
" class="loading_indicator"><br/></div>
				</td>
			<?php 
                break;
            case 'sale_price':
                $sale_price = get_post_meta($product->ID, '_wpsc_special_price', true);
                ?>
				<td  <?php 
                echo $attributes;
                ?>
>
					<span><?php 
                echo wpsc_currency_display($sale_price);
                ?>
</span>
					<input type="text" class="wpsc_ie_field wpsc_ie_special_price" value="<?php 
                echo esc_attr($sale_price);
                ?>
">
				</td>
			<?php 
                break;
            case 'comments':
                /* !comments case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><div class="post-com-count-wrapper">
		<?php 
                $pending_phrase = sprintf(__('%s pending', 'wp-e-commerce'), number_format($pending_comments));
                if ($pending_comments) {
                    echo '<strong>';
                }
                comments_number("<a href='edit-comments.php?p={$product->ID}' title='{$pending_phrase}' class='post-com-count'><span class='comment-count'>" . _x('0', 'comment count', 'wp-e-commerce') . '</span></a>', "<a href='edit-comments.php?p={$product->ID}' title='{$pending_phrase}' class='post-com-count'><span class='comment-count'>" . _x('1', 'comment count', 'wp-e-commerce') . '</span></a>', "<a href='edit-comments.php?p={$product->ID}' title='{$pending_phrase}' class='post-com-count'><span class='comment-count'>" . _x('%', 'comment count', 'wp-e-commerce') . '</span></a>');
                if ($pending_comments) {
                    echo '</strong>';
                }
                ?>
		</div></td>
		<?php 
                break;
            case 'author':
                /* !author case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><a href="edit.php?author=<?php 
                the_author_meta('ID');
                ?>
"><?php 
                the_author();
                ?>
</a></td>
		<?php 
                break;
            case 'control_view':
                /* !control view case */
                ?>
		<td><a href="<?php 
                the_permalink();
                ?>
" rel="permalink" class="view"><?php 
                esc_html_e('View', 'wp-e-commerce');
                ?>
</a></td>
		<?php 
                break;
            case 'control_edit':
                /* !control edit case */
                ?>
		<td><?php 
                if ($current_user_can_edit_this_product) {
                    echo "<a href='{$edit_link}' class='edit'>" . esc_html__('Edit', 'wp-e-commerce') . "</a>";
                }
                ?>
</td>
		<?php 
                break;
            case 'control_delete':
                /* !control delete case */
                ?>
		<td><?php 
                if ($current_user_can_edit_this_product) {
                    echo "<a href='" . wp_nonce_url("post.php?action=delete&amp;post={$id}", 'delete-post_' . $product->ID) . "' class='delete'>" . __('Delete', 'wp-e-commerce') . "</a>";
                }
                ?>
</td>
		<?php 
                break;
            case 'featured':
                /* !control featured case */
                ?>
			<td><?php 
                do_action('manage_posts_featured_column', $product->ID);
                ?>
</td>
		<?php 
                break;
            default:
                /* !default case */
                ?>
		<td <?php 
                echo $attributes;
                ?>
><?php 
                do_action('manage_posts_custom_column', $column_name, $product->ID);
                ?>
</td>
		<?php 
                break;
        }
    }
    ?>
	</tr>
<?php 
    $product = $global_product;
}
Example #20
0
function nzshpcrt_style()
{
    global $wpdb, $wp_query;
    return;
    if (function_exists('xili_display4mobile')) {
        //check for the function before using it
        if (xili_display4mobile() === true) {
            // instead of wrapping the whole block of code in brackets, resulting in mysterious brackets, simply break out of the function here.
            return null;
        }
    }
    if (is_numeric($_GET['category']) || is_numeric($wp_query->query_vars['product_category']) || is_numeric(get_option('wpsc_default_category'))) {
        if (is_numeric($wp_query->query_vars['product_category'])) {
            $category_id = $wp_query->query_vars['product_category'];
        } else {
            if (is_numeric($_GET['category'])) {
                $category_id = $_GET['category'];
            } else {
                $category_id = get_option('wpsc_default_category');
            }
        }
    }
    $category_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_CATEGORIES . "` WHERE `id`='{$category_id}' LIMIT 1", ARRAY_A);
    if ($category_data['display_type'] != '') {
        $display_type = $category_data['display_type'];
    } else {
        $display_type = get_option('product_view');
    }
    ?>
  <style type="text/css" media="screen">
  
	<?php 
    if (!defined('WPSC_DISABLE_IMAGE_SIZE_FIXES') || constant('WPSC_DISABLE_IMAGE_SIZE_FIXES') != true) {
        if ($display_type == 'default' || $display_type == '') {
            $thumbnail_width = get_option('product_image_width');
            if ($thumbnail_width <= 0) {
                $thumbnail_width = 96;
            }
            $thumbnail_height = get_option('product_image_height');
            if ($thumbnail_height <= 0) {
                $thumbnail_height = 96;
            }
            ?>
      div.default_product_display div.textcol{
        margin-left: <?php 
            echo $thumbnail_width + 10;
            ?>
px !important;
        _margin-left: <?php 
            echo $thumbnail_width / 2 + 5;
            ?>
px !important;
        min-height: <?php 
            echo $thumbnail_height;
            ?>
px;
        _height: <?php 
            echo $thumbnail_height;
            ?>
px;
      }
        
        
      div.default_product_display  div.textcol div.imagecol{
        position:absolute;
        top:0px;
        left: 0px;
        margin-left: -<?php 
            echo $thumbnail_width + 10;
            ?>
px !important;
      }
      
      div.default_product_display  div.textcol div.imagecol a img {
        width: <?php 
            echo $thumbnail_width;
            ?>
px;
        height: <?php 
            echo $thumbnail_height;
            ?>
px;
      }
      
    <?php 
        }
        $single_thumbnail_width = get_option('single_view_image_width');
        $single_thumbnail_height = get_option('single_view_image_height');
        if ($single_thumbnail_width <= 0) {
            $single_thumbnail_width = 128;
        }
        ?>
      div.single_product_display div.textcol{
        margin-left: <?php 
        echo $single_thumbnail_width + 10;
        ?>
px !important;
        _margin-left: <?php 
        echo $single_thumbnail_width / 2 + 5;
        ?>
px !important;
        min-height: <?php 
        echo $single_thumbnail_height;
        ?>
px;
        _height: <?php 
        echo $single_thumbnail_height;
        ?>
px;
      }
        
        
      div.single_product_display  div.textcol div.imagecol{
        position:absolute;
        top:0px;
        left: 0px;
        margin-left: -<?php 
        echo $single_thumbnail_width + 10;
        ?>
px !important;
      }
      
      div.single_product_display  div.textcol div.imagecol a img {
        width: <?php 
        echo $single_thumbnail_width;
        ?>
px;
        height: <?php 
        echo $single_thumbnail_height;
        ?>
px;
      }
      
    <?php 
        $product_ids = $wpdb->get_col("SELECT `id` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `thumbnail_state` IN(0,2,3)");
        foreach ($product_ids as $product_id) {
            $individual_thumbnail_height = get_product_meta($product_id, 'thumbnail_height');
            $individual_thumbnail_width = get_product_meta($product_id, 'thumbnail_width');
            if ($individual_thumbnail_height > $thumbnail_height) {
                echo "    div.default_product_display.product_view_{$product_id} div.textcol{\n\r";
                echo "            min-height: " . ($individual_thumbnail_height + 10) . "px !important;\n\r";
                echo "            _height: " . ($individual_thumbnail_height + 10) . "px !important;\n\r";
                echo "      }\n\r";
            }
            if ($individual_thumbnail_width > $thumbnail_width) {
                echo "      div.default_product_display.product_view_{$product_id} div.textcol{\n\r";
                echo "            margin-left: " . ($individual_thumbnail_width + 10) . "px !important;\n\r";
                echo "            _margin-left: " . ($individual_thumbnail_width / 2 + 5) . "px !important;\n\r";
                echo "      }\n\r";
                echo "      div.default_product_display.product_view_{$product_id}  div.textcol div.imagecol{\n\r";
                echo "            position:absolute;\n\r";
                echo "            top:0px;\n\r";
                echo "            left: 0px;\n\r";
                echo "            margin-left: -" . ($individual_thumbnail_width + 10) . "px !important;\n\r";
                echo "      }\n\r";
                echo "      div.default_product_display.product_view_{$product_id}  div.textcol div.imagecol a img{\n\r";
                echo "            width: " . $individual_thumbnail_width . "px;\n\r";
                echo "            height: " . $individual_thumbnail_height . "px;\n\r";
                echo "      }\n\r";
            }
        }
    }
    if (is_numeric($_GET['brand']) || get_option('show_categorybrands') == 3) {
        $brandstate = 'block';
        $categorystate = 'none';
    } else {
        $brandstate = 'none';
        $categorystate = 'block';
    }
    ?>
    div#categorydisplay{
    display: <?php 
    echo $categorystate;
    ?>
;
    }
    
    div#branddisplay{
    display: <?php 
    echo $brandstate;
    ?>
;
    }
  </style>
  <?php 
}
Example #21
0
function wpsc_purchase_log_csv()
{
    global $wpdb, $wpsc_gateways;
    get_currentuserinfo();
    $count = 0;
    if ('key' == $_REQUEST['rss_key'] && current_user_can('manage_options')) {
        if (isset($_REQUEST['start_timestamp']) && isset($_REQUEST['end_timestamp'])) {
            $start_timestamp = $_REQUEST['start_timestamp'];
            $end_timestamp = $_REQUEST['end_timestamp'];
            $start_end_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `date` BETWEEN '%d' AND '%d' ORDER BY `date` DESC";
            $start_end_sql = apply_filters('wpsc_purchase_log_start_end_csv', $start_end_sql);
            $data = $wpdb->get_results($wpdb->prepare($start_end_sql, $start_timestamp, $end_timestamp), ARRAY_A);
            /* translators: %1$s is "start" date, %2$s is "to" date */
            $csv_name = _x('Purchase Log %1$s to %2$s.csv', 'exported purchase log csv file name', 'wpsc');
            $csv_name = sprintf($csv_name, date("M-d-Y", $start_timestamp), date("M-d-Y", $end_timestamp));
        } elseif (isset($_REQUEST['m'])) {
            $year = (int) substr($_REQUEST['m'], 0, 4);
            $month = (int) substr($_REQUEST['m'], -2);
            $month_year_sql = "\n\t\t\t\tSELECT *\n\t\t\t\tFROM " . WPSC_TABLE_PURCHASE_LOGS . "\n\t\t\t\tWHERE YEAR(FROM_UNIXTIME(date)) = %d AND MONTH(FROM_UNIXTIME(date)) = %d\n\t\t\t\tORDER BY `id` DESC\n\t\t\t";
            $month_year_sql = apply_filters('wpsc_purchase_log_month_year_csv', $month_year_sql);
            $data = $wpdb->get_results($wpdb->prepare($month_year_sql, $year, $month), ARRAY_A);
            /* translators: %1$s is month, %2$s is year */
            $csv_name = _x('Purchase Log %1$s/%2$s.csv', 'exported purchase log csv file name', 'wpsc');
            $csv_name = sprintf($csv_name, $month, $year);
        } else {
            $sql = apply_filters('wpsc_purchase_log_month_year_csv', "SELECT * FROM " . WPSC_TABLE_PURCHASE_LOGS . " ORDER BY `id` DESC");
            $data = $wpdb->get_results($sql, ARRAY_A);
            $csv_name = _x("All Purchase Logs.csv", 'exported purchase log csv file name', 'wpsc');
        }
        $form_sql = "SELECT * FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `active` = '1' AND `type` != 'heading' ORDER BY `checkout_order` DESC;";
        $form_data = $wpdb->get_results($form_sql, ARRAY_A);
        $headers_array = array(_x('Purchase ID', 'purchase log csv headers', 'wpsc'), _x('Purchase Total', 'purchase log csv headers', 'wpsc'));
        $headers2_array = array(_x('Payment Gateway', 'purchase log csv headers', 'wpsc'), _x('Payment Status', 'purchase log csv headers', 'wpsc'), _x('Purchase Date', 'purchase log csv headers', 'wpsc'));
        $form_headers_array = array();
        $output = '';
        foreach ((array) $form_data as $form_field) {
            if (empty($form_field['unique_name'])) {
                $form_headers_array[] = $form_field['name'];
            } else {
                $prefix = false === strstr($form_field['unique_name'], 'billing') ? _x('Shipping ', 'purchase log csv header field prefix', 'wpsc') : _x('Billing ', 'purchase log csv header field prefix', 'wpsc');
                $form_headers_array[] = $prefix . $form_field['name'];
            }
        }
        foreach ((array) $data as $purchase) {
            $form_headers = '';
            $output .= "\"" . $purchase['id'] . "\",";
            //Purchase ID
            $output .= "\"" . $purchase['totalprice'] . "\",";
            //Purchase Total
            foreach ((array) $form_data as $form_field) {
                $collected_data_sql = "SELECT * FROM `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "` WHERE `log_id` = '" . $purchase['id'] . "' AND `form_id` = '" . $form_field['id'] . "' LIMIT 1";
                $collected_data = $wpdb->get_results($collected_data_sql, ARRAY_A);
                $collected_data = $collected_data[0];
                if (('billingstate' == $form_field['unique_name'] || 'shippingstate' == $form_field['unique_name']) && is_numeric($collected_data['value'])) {
                    $output .= "\"" . wpsc_get_state_by_id($collected_data['value'], 'code') . "\",";
                } else {
                    $output .= "\"" . str_replace(array("\r", "\r\n", "\n"), ' ', $collected_data['value']) . "\",";
                }
                // get form fields
            }
            if (isset($wpsc_gateways[$purchase['gateway']]) && isset($wpsc_gateways[$purchase['gateway']]['display_name'])) {
                $output .= "\"" . $wpsc_gateways[$purchase['gateway']]['display_name'] . "\",";
            } else {
                $output .= "\"\",";
            }
            $status_name = wpsc_find_purchlog_status_name($purchase['processed']);
            $output .= "\"" . $status_name . "\",";
            //get purchase status
            $output .= "\"" . date("jS M Y", $purchase['date']) . "\",";
            //date
            $cartsql = "SELECT `prodid`, `quantity`, `name` FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase['id'] . "";
            $cart = $wpdb->get_results($cartsql, ARRAY_A);
            if ($count < count($cart)) {
                $count = count($cart);
            }
            $items = count($cart);
            $i = 1;
            // Go through all products in cart and display quantity and sku
            foreach ((array) $cart as $item) {
                $skuvalue = get_product_meta($item['prodid'], 'sku', true);
                if (empty($skuvalue)) {
                    $skuvalue = __('N/A', 'wpsc');
                }
                $output .= "\"" . $item['quantity'] . "\",";
                $output .= "\"" . str_replace('"', '\\"', $item['name']) . "\",";
                if ($items <= 1) {
                    $output .= "\"" . $skuvalue . "\"";
                } elseif ($items > 1 && $i != $items) {
                    $output .= "\"" . $skuvalue . "\",";
                } else {
                    $output .= "\"" . $skuvalue . "\"";
                }
                $i++;
            }
            $output .= "\n";
            // terminates the row/line in the CSV file
        }
        // Get the most number of products and create a header for them
        $headers3 = array();
        for ($i = 0; $i < $count; $i++) {
            $headers3[] = _x('Quantity', 'purchase log csv headers', 'wpsc');
            $headers3[] = _x('Product Name', 'purchase log csv headers', 'wpsc');
            $headers3[] = _x('SKU', 'purchase log csv headers', 'wpsc');
        }
        $headers = '"' . implode('","', $headers_array) . '",';
        $form_headers = '"' . implode('","', $form_headers_array) . '",';
        $headers2 = '"' . implode('","', $headers2_array) . '",';
        $headers3 = '"' . implode('","', $headers3) . '"';
        $headers = apply_filters('wpsc_purchase_log_csv_headers', $headers . $form_headers . $headers2 . $headers3, $data, $form_data);
        $output = apply_filters('wpsc_purchase_log_csv_output', $output, $data, $form_data);
        do_action('wpsc_purchase_log_csv');
        header('Content-Type: text/csv');
        header('Content-Disposition: inline; filename="' . $csv_name . '"');
        echo $headers . "\n" . $output;
        exit;
    }
}
Example #22
0
function external_link($product_id)
{
    $link = get_product_meta($product_id, 'external_link', true);
    if (!stristr($link, 'http://')) {
        $link = 'http://' . $link;
    }
    $target = wpsc_product_external_link_target($product_id);
    $output .= "<input class='wpsc_buy_button' type='button' value='" . wpsc_product_external_link_text($product_id, __('Buy Now', 'wpsc')) . "' onclick='return gotoexternallink(\"{$link}\", \"{$target}\")'>";
    return $output;
}
    public function bulk_edit_column_sale_price()
    {
        $sale_price = get_product_meta($this->product_id, 'special_price', true);
        ?>
			<input class="wpsc-bulk-edit-fields" type="checkbox" name="wpsc_bulk_edit[fields][sale_price]" value="1" />
			<input tabindex="104" type="text" name="wpsc_bulk_edit[sale_price]" value="">
		<?php 
    }
Example #24
0
         }
     }
 }
 do_action('wpsc_product_form_submit', $product_id);
 /* Add or edit tidy url name */
 $tidied_name = trim($_POST['title']);
 $tidied_name = strtolower($tidied_name);
 $url_name = preg_replace(array("/(\\s)+/", "/[^\\w-]+/i"), array("-", ''), $tidied_name);
 $similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`meta_value`, '{$url_name}', '')) AS `max_number` FROM `" . $wpdb->prefix . "wpsc_productmeta` WHERE `meta_key` IN ('url_name') AND `meta_value` REGEXP '^({$url_name}){1}(\\d)*\$' ", ARRAY_A);
 $extension_number = '';
 if ($similar_names['count'] > 0) {
     $extension_number = (int) $similar_names['max_number'] + 1;
 }
 $stored_name = get_product_meta($_POST['prodid'], 'url_name', true);
 if (get_product_meta($_POST['prodid'], 'url_name', true) != false) {
     $current_url_name = get_product_meta($_POST['prodid'], 'url_name');
     if ($current_url_name[0] != $url_name) {
         $url_name .= $extension_number;
         update_product_meta($_POST['prodid'], 'url_name', $url_name);
     }
 } else {
     $url_name .= $extension_number;
     add_product_meta($_POST['prodid'], 'url_name', $url_name, true);
 }
 /* update thumbnail images */
 if (!($thumbnail_image == null && $_POST['image_resize'] == 3 && $_POST['current_thumbnail_image'] != null)) {
     if ($thumbnail_image != null) {
         $wpdb->query("UPDATE `" . $wpdb->prefix . "product_list` SET `thumbnail_image` = '" . $thumbnail_image . "' WHERE `id`='" . $_POST['prodid'] . "' LIMIT 1");
     }
 }
 $image_resize = $_POST['image_resize'];
function gateway_paypal_multiple($seperator, $sessionid)
{
    global $wpdb, $wpsc_cart;
    $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A);
    if ($purchase_log['totalprice'] == 0) {
        header("Location: " . get_option('transact_url') . $seperator . "sessionid=" . $sessionid);
        exit;
    }
    $cart_sql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`='" . $purchase_log['id'] . "'";
    $cart = $wpdb->get_results($cart_sql, ARRAY_A);
    //written by allen
    //exit("<pre>".print_r($cart,true)."</pre>");
    $member_subtype = get_product_meta($cart[0]['prodid'], 'is_permenant', true);
    $status = get_product_meta($cart[0]['prodid'], 'is_membership', true);
    $is_member = $status;
    $is_perm = $member_subtype;
    //end of written by allen
    $transact_url = get_option('transact_url');
    // paypal connection variables
    $data['business'] = get_option('paypal_multiple_business');
    $data['return'] = urlencode($transact_url . $seperator . "sessionid=" . $sessionid . "&gateway=paypal");
    $data['cancel_return'] = urlencode($transact_url);
    $data['notify_url'] = urlencode(get_option('siteurl') . "/?ipn_request=true");
    $data['rm'] = '2';
    //data['bn'] = 'Instinct-WP-e-commerce_ShoppingCart_EC';
    // look up the currency codes and local price
    $currency_code = $wpdb->get_results("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . get_option('currency_type') . "' LIMIT 1", ARRAY_A);
    $local_currency_code = $currency_code[0]['code'];
    $paypal_currency_code = get_option('paypal_curcode');
    if ($paypal_currency_code == '') {
        $paypal_currency_code = 'US';
    }
    //exit(get_option('currency_type'). " ".$paypal_currency_code);
    // Stupid paypal only accepts payments in one of 5 currencies. Convert from the currency of the users shopping cart to the curency which the user has specified in their paypal preferences.
    $curr = new CURRENCYCONVERTER();
    $data['currency_code'] = $paypal_currency_code;
    //   $data['lc'] = 'US';
    $data['lc'] = $paypal_currency_code;
    $data['bn'] = 'wp-e-commerce';
    if (get_option('address_override') == 1) {
        $data['address_override'] = '1';
    }
    if ((int) (bool) get_option('paypal_ship') == '1') {
        $data['no_shipping'] = '0';
        $data['address_override'] = '1';
    }
    $data['no_note'] = '1';
    switch ($paypal_currency_code) {
        case "JPY":
            $decimal_places = 0;
            break;
        case "HUF":
            $decimal_places = 0;
        default:
            $decimal_places = 2;
            break;
    }
    $i = 1;
    $all_donations = true;
    $all_no_shipping = true;
    $total = $wpsc_cart->calculate_total_price();
    $discount = $wpsc_cart->coupons_amount;
    //exit($discount);
    if ($discount > 0) {
        if ($paypal_currency_code != $local_currency_code) {
            $paypal_currency_productprice = $curr->convert($wpsc_cart->calculate_total_price(), $paypal_currency_code, $local_currency_code);
            $paypal_currency_shipping = $curr->convert($local_currency_shipping, $paypal_currency_code, $local_currency_code);
            $base_shipping = $curr->convert($wpsc_cart->calculate_total_shipping(), $paypal_currency_code, $local_currency_code);
            $tax_price = $curr->convert($item['tax_charged'], $paypal_currency_code, $local_currency_code);
        } else {
            $paypal_currency_productprice = $wpsc_cart->calculate_total_price();
            $paypal_currency_shipping = $local_currency_shipping;
            $base_shipping = $wpsc_cart->calculate_total_shipping();
            $tax_price = $item['tax_charged'];
        }
        $data['item_name_' . $i] = "Your Shopping Cart";
        $data['amount_' . $i] = number_format(sprintf("%01.2f", $paypal_currency_productprice), $decimal_places, '.', '');
        $data['quantity_' . $i] = 1;
        // $data['item_number_'.$i] = 0;
        $data['shipping_' . $i] = 0;
        $data['shipping2_' . $i] = 0;
        $data['handling_' . $i] = 0;
        $i++;
    } else {
        foreach ((array) $cart as $item) {
            $product_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='" . $item['prodid'] . "' LIMIT 1", ARRAY_A);
            $product_data = $product_data[0];
            if ((double) $item['price'] == 0) {
                continue;
            }
            $variation_count = count($product_variations);
            $local_currency_productprice = $item['price'];
            $local_currency_shipping = $item['pnp'] / $item['quantity'];
            if ($paypal_currency_code != $local_currency_code) {
                $paypal_currency_productprice = $curr->convert($local_currency_productprice, $paypal_currency_code, $local_currency_code);
                $paypal_currency_shipping = $curr->convert($local_currency_shipping, $paypal_currency_code, $local_currency_code);
                //	exit($paypal_currency_productprice . " " . $paypal_currency_shipping.' '.$local_currency_productprice . " " . $local_currency_code);
                $base_shipping = $curr->convert($wpsc_cart->calculate_base_shipping(), $paypal_currency_code, $local_currency_code);
                //exit($paypal_currency_productprice.' Local>'.$local_currency_productprice.' Base shp'.$base_shipping);
                $tax_price = $curr->convert($item['tax_charged'], $paypal_currency_code, $local_currency_code);
            } else {
                $paypal_currency_productprice = $local_currency_productprice;
                $paypal_currency_shipping = $local_currency_shipping;
                $base_shipping = $wpsc_cart->calculate_base_shipping();
                $tax_price = $item['tax_charged'];
            }
            //exit("<pre>".print_r(, true).'</pre>');
            $data['item_name_' . $i] = urlencode(stripslashes($item['name']));
            $data['amount_' . $i] = number_format(sprintf("%01.2f", $paypal_currency_productprice), $decimal_places, '.', '');
            $data['tax_' . $i] = number_format(sprintf("%01.2f", $tax_price), $decimal_places, '.', '');
            $data['quantity_' . $i] = $item['quantity'];
            $data['item_number_' . $i] = $product_data['id'];
            if ($item['donation'] != 1) {
                $all_donations = false;
                $data['shipping_' . $i] = number_format($paypal_currency_shipping, $decimal_places, '.', '');
                $data['shipping2_' . $i] = number_format($paypal_currency_shipping, $decimal_places, '.', '');
            } else {
                $data['shipping_' . $i] = number_format(0, $decimal_places, '.', '');
                $data['shipping2_' . $i] = number_format(0, $decimal_places, '.', '');
            }
            if ($product_data['no_shipping'] != 1) {
                $all_no_shipping = false;
            }
            $data['handling_' . $i] = '';
            $i++;
        }
    }
    $data['tax'] = '';
    //exit($base_shipping);
    if ($base_shipping > 0 && $all_donations == false && $all_no_shipping == false) {
        $data['handling_cart'] = number_format($base_shipping, $decimal_places, '.', '');
    }
    $data['custom'] = '';
    $data['invoice'] = $sessionid;
    // User details
    if ($_POST['collected_data'][get_option('paypal_form_first_name')] != '') {
        $data['first_name'] = urlencode($_POST['collected_data'][get_option('paypal_form_first_name')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_last_name')] != '') {
        $data['last_name'] = urlencode($_POST['collected_data'][get_option('paypal_form_last_name')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_address')] != '') {
        $address_rows = explode("\n\r", $_POST['collected_data'][get_option('paypal_form_address')]);
        $data['address1'] = urlencode(str_replace(array("\n", "\r"), '', $address_rows[0]));
        unset($address_rows[0]);
        if ($address_rows != null) {
            $data['address2'] = implode(", ", $address_rows);
        } else {
            $data['address2'] = '';
        }
    }
    if ($_POST['collected_data'][get_option('paypal_form_city')] != '') {
        $data['city'] = urlencode($_POST['collected_data'][get_option('paypal_form_city')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_state')] != '') {
        if (!is_array($_POST['collected_data'][get_option('paypal_form_state')])) {
            $data['state'] = urlencode($_POST['collected_data'][get_option('paypal_form_state')]);
        }
    }
    if ($_POST['collected_data'][get_option('paypal_form_country')] != '') {
        if (is_array($_POST['collected_data'][get_option('paypal_form_country')])) {
            $country = $_POST['collected_data'][get_option('paypal_form_country')][0];
            $id = $_POST['collected_data'][get_option('paypal_form_country')][1];
            $state = wpsc_get_state_by_id($id, 'code');
        } else {
            $country = $_POST['collected_data'][get_option('paypal_form_country')];
        }
        $data['country'] = urlencode($country);
        if ($state != '') {
            $data['state'] = $state;
        }
    }
    if (is_numeric($_POST['collected_data'][get_option('paypal_form_post_code')])) {
        $data['zip'] = urlencode($_POST['collected_data'][get_option('paypal_form_post_code')]);
    }
    // Change suggested by waxfeet@gmail.com, if email to be sent is not there, dont send an email address
    $email_data = $wpdb->get_results("SELECT `id`,`type` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `type` IN ('email') AND `active` = '1'", ARRAY_A);
    foreach ((array) $email_data as $email) {
        $data['email'] = $_POST['collected_data'][$email['id']];
    }
    if ($_POST['collected_data'][get_option('email_form_field')] != null && $data['email'] == null) {
        $data['email'] = $_POST['collected_data'][get_option('email_form_field')];
    }
    $data['upload'] = '1';
    $data['cmd'] = "_ext-enter";
    $data['redirect_cmd'] = "_cart";
    $data = apply_filters('wpsc_paypal_standard_post_data', $data);
    $datacount = count($data);
    $num = 0;
    //  exit('<pre>'.print_r($data,true).'</pre>');
    foreach ($data as $key => $value) {
        $amp = '&';
        $num++;
        if ($num == $datacount) {
            $amp = '';
        }
        //$output .= $key.'='.urlencode($value).$amp;
        $output .= $key . '=' . $value . $amp;
    }
    if (get_option('paypal_ipn') == 0) {
        //ensures that digital downloads still work for people without IPN, less secure, though
        //$wpdb->query("UPDATE `".WPSC_TABLE_PURCHASE_LOGS."` SET `processed` = '2' WHERE `sessionid` = ".$sessionid." LIMIT 1");
    }
    //written by allen
    if ($is_member == '1') {
        $membership_length = get_product_meta($cart[0]['prodid'], 'membership_length', true);
        if ($is_perm == '1') {
            $permsub = '&src=1';
        } else {
            $permsub = '';
        }
        $output = 'cmd=_xclick-subscriptions&currency_code=' . urlencode($data['currency_code']) . '&lc=' . urlencode($data['lc']) . '&business=' . urlencode($data['business']) . '&no_note=1&item_name=' . urlencode($data['item_name_1']) . '&return=' . urlencode($data['return']) . '&cancel_return=' . urlencode($data['cancel_return']) . $permsub . '&a3=' . urlencode($data['amount_1']) . '&p3=' . urlencode($membership_length['length']) . '&t3=' . urlencode(strtoupper($membership_length['unit']));
    }
    if (defined('WPSC_ADD_DEBUG_PAGE') and WPSC_ADD_DEBUG_PAGE == true) {
        echo "<a href='" . get_option('paypal_multiple_url') . "?" . $output . "'>Test the URL here</a>";
        echo "<pre>" . print_r($data, true) . "</pre>";
        // 	echo "<pre>".print_r($_POST,true)."</pre>";
        exit;
    }
    header("Location: " . get_option('paypal_multiple_url') . "?" . $output);
    exit;
}
function wpsc_select_product_file($product_id = null)
{
    global $wpdb;
    //return false;
    $product_id = absint($product_id);
    $file_list = wpsc_uploaded_files();
    $file_id = $wpdb->get_var("SELECT `file` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id` = '" . $product_id . "' LIMIT 1");
    //$product_files = $wpdb->get_row("SELECT `meta_value` FROM  `".WPSC_TABLE_PRODUCTMETA."` WHERE `product_id` = '".$product_id."' AND `meta_key` = 'product_files'", ARRAY_A);
    $product_files = get_product_meta($product_id, 'product_files');
    $output = "<span class='admin_product_notes select_product_note '>" . __('Choose a downloadable file for this product:', 'wpsc') . "</span><br>";
    $output .= "<div class='ui-widget-content multiple-select  " . (is_numeric($product_id) ? "edit_" : "") . "select_product_file'>";
    $num = 0;
    foreach ((array) $file_list as $file) {
        $num++;
        if (is_array($product_files)) {
            if (in_array($file['file_id'], $product_files)) {
                $checked_curr_file = "checked='checked'";
            } else {
                $checked_curr_file = "";
            }
        } else {
            if (is_numeric($file_id) && $file_id == $file['file_id']) {
                $checked_curr_file = "checked='checked'";
            } else {
                $checked_curr_file = "";
            }
        }
        $deletion_url = wp_nonce_url("admin.php?wpsc_admin_action=delete_file&amp;file_id=" . $file['file_id'], 'delete_file_' . absint($file['file_id']));
        $output .= "<p " . ($num % 2 > 0 ? '' : "class='alt'") . ">\n";
        $output .= "  <input type='checkbox' name='select_product_file[]' value='" . $file['real_filename'] . "' id='select_product_file_{$num}' " . $checked_curr_file . " />\n";
        $output .= "  <label for='select_product_file_{$num}'>" . $file['display_filename'] . "</label>\n";
        $output .= "  <a class='file_delete_button' href='{$deletion_url}'>\n";
        $output .= "    <img src='" . WPSC_URL . "/images/cross.png' />\n";
        $output .= "  </a>\n";
        $output .= "</p>\n";
    }
    $output .= "</div>";
    $output .= "<div class='" . (is_numeric($product_id) ? "edit_" : "") . "select_product_handle'><div></div></div>";
    $output .= "<script type='text/javascript'>\n\r";
    $output .= "var select_min_height = " . 25 * 3 . ";\n\r";
    $output .= "var select_max_height = " . 25 * ($num + 1) . ";\n\r";
    $output .= "</script>";
    return $output;
}
 function getQuote()
 {
     global $wpdb, $wpsc_cart;
     if ($this->base_country != 'AU' || strlen($this->base_zipcode) != 4 || !count($wpsc_cart->cart_items)) {
         return;
     }
     $dest = $_SESSION['wpsc_delivery_country'];
     $destzipcode = '';
     if (isset($_POST['zipcode'])) {
         $destzipcode = $_POST['zipcode'];
         $_SESSION['wpsc_zipcode'] = $_POST['zipcode'];
     } else {
         if (isset($_SESSION['wpsc_zipcode'])) {
             $destzipcode = $_SESSION['wpsc_zipcode'];
         }
     }
     if ($dest == 'AU' && strlen($destzipcode) != 4) {
         // Invalid Australian Post Code entered, so just return an empty set of quotes instead of wasting time contactin the Aus Post API
         return array();
     }
     /*
     3 possible scenarios:
     
     1.
     Cart consists of only item(s) that have "disregard shipping" ticked.
     
     In this case, WPEC doesn't mention shipping at all during checkout, and this shipping module probably won't be executed at all.
     
     Just in case it does get queried, we should still query the Australia Post API for valid shipping estimates,
     and then override the quoted price(s) to $0.00 so the customer is able to get free shipping.
     
     
     2.
     Cart consists of only item(s) where "disregard shipping" isn't ticked (ie. all item(s) attract shipping charges).
     
     In this case, we should query the Australia Post API as per normal.
     
     
     3.
     Cart consists of one or more "disregard shipping" product(s), and one or more other products that attract shipping charges.
     
     In this case, we should query the Aus Post API, only taking into account the product(s) that attract shipping charges.
     Products with "disregard shipping" ticked shouldn't have their weight or dimensions included in the quote.
     */
     // Obtain the total combined weight for all items(s) in the cart (excluding items that have the "Disregard Shipping for this product" option ticked)
     // Weight is in pounds but needs to be in grams
     $weight = floatval($wpsc_cart->calculate_total_weight(true) * 453.59237);
     // Calculate the total cart dimensions by adding the volume of each product then calculating the cubed root
     $volume = 0;
     // Total number of item(s) in the cart
     $numItems = count($wpsc_cart->cart_items);
     if ($numItems == 0) {
         // The customer's cart is empty. This probably shouldn't occur, but just in case!
         return array();
     }
     // Total number of item(s) that don't attract shipping charges.
     $numItemsWithDisregardShippingTicked = 0;
     foreach ($wpsc_cart->cart_items as $cart_item) {
         if (!$cart_item->uses_shipping) {
             // The "Disregard Shipping for this product" option is ticked for this item.
             // Don't include it in the shipping quote.
             $numItemsWithDisregardShippingTicked++;
             continue;
         }
         // If we are here then this item attracts shipping charges.
         $meta = get_product_meta($cart_item->product_id, 'dimensions');
         if ($meta && is_array($meta)) {
             $productVolume = 1;
             foreach (array('width', 'height', 'length') as $dimension) {
                 switch ($meta["{$dimension}_unit"]) {
                     // we need the units in mm
                     case 'cm':
                         // convert from cm to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 10);
                         break;
                     case 'meter':
                         // convert from m to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 1000);
                         break;
                     case 'in':
                         // convert from in to mm
                         $productVolume = $productVolume * (floatval($meta[$dimension]) * 25.4);
                         break;
                 }
             }
             $volume += floatval($productVolume);
         }
     }
     // Calculate the cubic root of the total volume, rounding up
     $cuberoot = ceil(pow($volume, 1 / 3));
     // Use default dimensions of 100mm if the volume is zero
     $height = 100;
     $width = 100;
     $length = 100;
     if ($cuberoot > 0) {
         $height = $width = $length = $cuberoot;
     }
     // As per http://auspost.com.au/personal/parcel-dimensions.html: if the parcel is box-shaped, both its length and width must be at least 15cm.
     if ($length < 150) {
         $length = 150;
     }
     if ($width < 150) {
         $width = 150;
     }
     // By default we should use Australia Post's quoted rate(s)
     $shippingPriceNeedsToBeZero = false;
     if ($numItemsWithDisregardShippingTicked == $numItems) {
         // The cart consists of entirely "disregard shipping" products, so the shipping quote(s) should be $0.00
         // Set the weight to 1 gram so that we can obtain valid Australia Post quotes (which we will then ignore the quoted price of)
         $weight = 1;
         $shippingPriceNeedsToBeZero = true;
     }
     // API Documentation: http://drc.edeliver.com.au/
     $url = "http://drc.edeliver.com.au/ratecalc.asp";
     $params = array('Pickup_Postcode' => $this->base_zipcode, 'Destination_Postcode' => $destzipcode, 'Quantity' => 1, 'Weight' => $weight, 'Height' => $height, 'Width' => $width, 'Length' => $length, 'Country' => $dest);
     // URL encode the parameters to prevent issues where postcodes contain spaces (eg London postcodes)
     $params = array_map('urlencode', $params);
     $url = add_query_arg($params, $url);
     $log = '';
     $methods = array();
     foreach ($this->services as $code => $service) {
         if (!$this->settings['services'][$code]) {
             continue;
         }
         $fullURL = add_query_arg('Service_Type', $code, $url);
         // This cache key should be unique for a cart with these contents and destination
         $cacheKey = 'wpec_auspost_quote_' . md5($fullURL);
         // See if this Australia Post quote is cached
         $cachedResult = get_transient($cacheKey);
         if (false === $cachedResult) {
             // Quote isn't cached -> query the Australia Post API and then cache the result for 10 minutes
             $response = wp_remote_get($fullURL);
             // Silently ignore any API server errors
             if (is_wp_error($response) || $response['response']['code'] != '200' || empty($response['body'])) {
                 continue;
             }
             if ($this->debug) {
                 $log .= "  {$fullURL}\n    " . $response['body'] . "\n";
             }
             $lines = explode("\n", $response['body']);
             foreach ($lines as $line) {
                 list($key, $value) = explode('=', $line);
                 $key = trim($key);
                 $value = trim($value);
                 switch ($key) {
                     case 'charge':
                         if ($shippingPriceNeedsToBeZero) {
                             // All shipping prices quoted should be zero
                             $methods[$code]['charge'] = 0.0;
                             $log .= "  NB: the price for the above quote has been overridden to \$0.00\n\n";
                         } else {
                             // Use the Australia Post quoted price
                             $methods[$code]['charge'] = floatval($value);
                         }
                         break;
                     case 'days':
                         $methods[$code]['days'] = floatval($value);
                         break;
                     case 'err_msg':
                         $methods[$code]['err_msg'] = trim($value);
                         break;
                 }
             }
             $methods[$code]['name'] = $this->services[$code];
             // Cache this quote for 10 minutes
             set_transient($cacheKey, $methods[$code], 600);
         } else {
             // This quote is cached so use that result instead
             $methods[$code] = $cachedResult;
         }
     }
     if ($this->debug && strlen($log)) {
         error_log('WP e-Commerce Australia Post shipping quotes for ' . site_url() . ":\n----------\n{$log}----------");
     }
     // Allow another WordPress plugin to override the quoted method(s)/amount(s)
     $methods = apply_filters('wpsc_australia_post_methods', $methods, $this->base_zipcode, $destzipcode, $dest, $weight);
     $quotedMethods = array();
     foreach ($methods as $code => $data) {
         // Only include methods with an OK response
         if ($data['err_msg'] != 'OK') {
             continue;
         }
         if ($data['days']) {
             // If the estimated number of days is specified, so include it in the quote
             $text = sprintf(_n('%1$s (estimated delivery time: %2$d business day)', '%1$s (estimated delivery time: %2$d business days)', $data['days'], 'wpsc'), $data['name'], $data['days']);
         } else {
             // No time estimate
             $text = $data['name'];
         }
         $quotedMethods[$text] = $data['charge'];
     }
     return $quotedMethods;
 }
Example #28
0
 /**
  * Builds a shipment object representing the cart contents from WPEC
  * @author Greg Gullett (greg@ecsquest.com)
  * @return ASHShipment
  */
 function get_shipment()
 {
     global $wpdb, $wpsc_cart;
     $shipment = new ASHShipment();
     if (!$wpsc_cart) {
         return $shipment;
     }
     foreach ($wpsc_cart->cart_items as $cart_item) {
         $package = new ASHPackage();
         //*** Set package dimensions ***\\
         $dimensions = get_product_meta($cart_item->product_id, 'dimensions');
         $dim_array = array();
         $dim_array["weight"] = $cart_item->weight;
         $dim_array["height"] = !empty($dimensions["height"]) && is_numeric($dimensions["height"]) ? $dimensions["height"] : 1;
         $dim_array["width"] = !empty($dimensions["width"]) && is_numeric($dimensions["width"]) ? $dimensions["width"] : 1;
         $dim_array["length"] = !empty($dimensions["length"]) && is_numeric($dimensions["length"]) ? $dimensions["length"] : 1;
         $package->set_dimensions($dim_array);
         //*** Set other meta ***\\
         $package->hazard = get_product_meta($cart_item->product_id, "ship_hazard") === FALSE ? FALSE : TRUE;
         $package->insurance = get_product_meta($cart_item->product_id, "ship_insurance");
         $package->insured_amount = get_product_meta($cart_item->product_id, "ship_insured_amount");
         $package->value = $cart_item->unit_price;
         $package->contents = $cart_item->product_name;
         if ($shipment->hazard === FALSE and $package->hazard === TRUE) {
             $shipment->set_hazard(TRUE);
         }
         $quantity = (int) $cart_item->quantity;
         for ($i = 1; $i <= $quantity; $i++) {
             $shipment->add_package($package);
         }
     }
     return $shipment;
 }
function wpsc_purchaselog_details_SKU()
{
    global $purchlogitem;
    $meta_value = wpsc_get_cart_item_meta($purchlogitem->purchitem->id, 'sku', true);
    if ($meta_value != null) {
        return esc_attr($meta_value);
    } else {
        $meta_value = get_product_meta($purchlogitem->purchitem->prodid, 'sku', true);
        if ($meta_value != null) {
            return esc_attr($meta_value);
        } else {
            return __('N/A', 'wpsc');
        }
    }
}
/**
 * wpsc_update_product_meta function
 *
 * @param integer product ID
 * @param string comma separated tags
 */
function wpsc_update_product_meta($product_id, $product_meta)
{
    if ($product_meta != null) {
        foreach ((array) $product_meta as $key => $value) {
            if (get_product_meta($product_id, $key) != false) {
                update_product_meta($product_id, $key, $value);
            } else {
                add_product_meta($product_id, $key, $value);
            }
        }
    }
}