/**
 * wpsc_convert_products_to_posts function.
 *
 * @access public
 * @return void
 */
function wpsc_convert_products_to_posts()
{
    global $wpdb, $user_ID;
    // Select all products
    $wpsc_update = WPSC_Update::get_instance();
    if (!empty($wpdb->charset)) {
        $charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}";
    }
    if (!empty($wpdb->collate)) {
        $charset_collate .= " COLLATE {$wpdb->collate}";
    }
    if (!($offset = get_transient('wpsc_update_product_offset'))) {
        $offset = 0;
    }
    $limit = 90;
    $sql = "\n\t\tSELECT * FROM " . WPSC_TABLE_PRODUCT_LIST . "\n\t\tWHERE active = '1'\n\t\tLIMIT %d, %d\n\t";
    $post_created = get_transient('wpsc_update_current_product');
    $total = $wpdb->get_var("SELECT COUNT(*) FROM " . WPSC_TABLE_PRODUCT_LIST . " WHERE active='1'");
    $progress = new WPSC_Update_Progress($total);
    while (true) {
        $product_data = $wpdb->get_results($wpdb->prepare($sql, $offset, $limit), ARRAY_A);
        $i = $offset;
        if (empty($product_data)) {
            break;
        }
        foreach ((array) $product_data as $product) {
            $wpsc_update->check_timeout('</div>');
            $post_id = 0;
            // if a product is in the middle of being converted
            if ($post_created && !empty($post_created['original_id']) && $post_created['original_id'] == $product['id']) {
                $post_id = $post_created['post_id'];
            }
            $sku = old_get_product_meta($product['id'], 'sku', true);
            if ($post_id == 0) {
                $post_status = "publish";
                if ($product['publish'] != 1) {
                    $post_status = "draft";
                }
                //check the product added time with the current time to make sure its not out - this aviods the future post status
                $product_added_time = strtotime($product['date_added']);
                $current_time = time();
                $post_date = $product['date_added'];
                if ((int) $current_time < (int) $product_added_time) {
                    $post_date = date("Y-m-d H:i:s");
                }
                $product_post_values = array('post_author' => $user_ID, 'post_date' => $post_date, 'post_content' => $product['description'], 'post_excerpt' => $product['additional_description'], 'post_title' => $product['name'], 'post_status' => $post_status, 'post_type' => "wpsc-product", 'post_name' => $product['name']);
                $product['order'] = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\tSELECT `order` FROM " . WPSC_TABLE_PRODUCT_ORDER . "\n\t\t\t\t\tWHERE product_id = %d\n\t\t\t\t", $product['id']));
                $product_post_values['menu_order'] = $product['order'];
                $post_id = wp_insert_post($product_post_values);
                $post_created = array('original_id' => $product['id'], 'post_id' => $post_id);
                set_transient('wpsc_update_current_product', $post_created, 604800);
            }
            $product_meta_sql = $wpdb->prepare("\n\t\t\t\tSELECT \tIF( ( `custom` != 1\t),\n\t\t\t\t\t\tCONCAT( '_wpsc_', `meta_key` ) ,\n\t\t\t\t\t`meta_key`\n\t\t\t\t\t) AS `meta_key`,\n\t\t\t\t\t`meta_value`\n\t\t\t\tFROM `" . WPSC_TABLE_PRODUCTMETA . "`\n\t\t\t\tWHERE `product_id` = %d\n\t\t\t\tAND `meta_value` != ''", $product['id']);
            $product_meta = $wpdb->get_results($product_meta_sql, ARRAY_A);
            $post_data = array();
            foreach ($product_meta as $k => $pm) {
                if ($pm['meta_value'] == 'om') {
                    $pm['meta_value'] = 1;
                }
                $pm['meta_value'] = maybe_unserialize($pm['meta_value']);
                if (strpos($pm['meta_key'], '_wpsc_') === 0) {
                    $post_data['_wpsc_product_metadata'][$pm['meta_key']] = $pm['meta_value'];
                } else {
                    update_post_meta($post_id, $pm['meta_key'], $pm['meta_value']);
                }
            }
            $post_data['_wpsc_original_id'] = (int) $product['id'];
            $post_data['_wpsc_price'] = (double) $product['price'];
            $post_data['_wpsc_special_price'] = $post_data['_wpsc_price'] - (double) $product['special_price'];
            // special price get stored in a weird way in 3.7.x
            $post_data['_wpsc_stock'] = (double) $product['quantity'];
            $post_data['_wpsc_is_donation'] = $product['donation'];
            $post_data['_wpsc_sku'] = $sku;
            if ((bool) $product['quantity_limited'] != true) {
                $post_data['_wpsc_stock'] = false;
            }
            unset($post_data['_wpsc_limited_stock']);
            $post_data['_wpsc_product_metadata']['is_stock_limited'] = (int) (bool) $product['quantity_limited'];
            // Product Weight
            $post_data['_wpsc_product_metadata']['weight'] = wpsc_convert_weight($product['weight'], $product['weight_unit'], "pound", true);
            $post_data['_wpsc_product_metadata']['weight_unit'] = $product['weight_unit'];
            $post_data['_wpsc_product_metadata']['display_weight_as'] = $product['weight_unit'];
            $post_data['_wpsc_product_metadata']['has_no_shipping'] = (int) (bool) $product['no_shipping'];
            $post_data['_wpsc_product_metadata']['shipping'] = array('local' => $product['pnp'], 'international' => $product['international_pnp']);
            $post_data['_wpsc_product_metadata']['quantity_limited'] = (int) (bool) $product['quantity_limited'];
            $post_data['_wpsc_product_metadata']['special'] = (int) (bool) $product['special'];
            if (isset($post_data['meta'])) {
                $post_data['_wpsc_product_metadata']['notify_when_none_left'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['notify_when_none_left'];
                $post_data['_wpsc_product_metadata']['unpublish_when_none_left'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'];
            }
            $post_data['_wpsc_product_metadata']['no_shipping'] = (int) (bool) $product['no_shipping'];
            foreach ($post_data as $meta_key => $meta_value) {
                // prefix all meta keys with _wpsc_
                update_post_meta($post_id, $meta_key, $meta_value);
            }
            // get the wordpress upload directory data
            $wp_upload_dir_data = wp_upload_dir();
            $wp_upload_basedir = $wp_upload_dir_data['basedir'];
            $category_ids = array();
            $category_data = $wpdb->get_col("SELECT `category_id` FROM `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "` WHERE `product_id` IN ('{$product['id']}')");
            foreach ($category_data as $old_category_id) {
                $category_ids[] = wpsc_get_meta($old_category_id, 'category_id', 'wpsc_old_category');
            }
            wp_set_product_categories($post_id, $category_ids);
            $product_data = get_post($post_id);
            $image_data_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PRODUCT_IMAGES . "` WHERE `product_id` = %d ORDER BY `image_order` ASC", $product['id']);
            $image_data = $wpdb->get_results($image_data_sql, ARRAY_A);
            foreach ((array) $image_data as $image_row) {
                $wpsc_update->check_timeout('</div>');
                // Get the image path info
                $image_pathinfo = pathinfo($image_row['image']);
                // use the path info to clip off the file extension
                $image_name = basename($image_pathinfo['basename'], ".{$image_pathinfo['extension']}");
                // construct the full image path
                $full_image_path = WPSC_IMAGE_DIR . $image_row['image'];
                $attached_file_path = str_replace($wp_upload_basedir . "/", '', $full_image_path);
                $upload_dir = wp_upload_dir();
                $new_path = $upload_dir['path'] . '/' . $image_name . '.' . $image_pathinfo['extension'];
                if (is_file($full_image_path)) {
                    copy($full_image_path, $new_path);
                } else {
                    continue;
                }
                // construct the full image url
                $subdir = $upload_dir['subdir'] . '/' . $image_name . '.' . $image_pathinfo['extension'];
                $subdir = substr($subdir, 1);
                $attachment_id_sql = $wpdb->prepare("SELECT `ID` FROM `{$wpdb->posts}` WHERE `post_title` = %s AND `post_parent` = %d LIMIT 1", $image_name, $post_id);
                $attachment_id = (int) $wpdb->get_var($attachment_id_sql);
                // get the image MIME type
                $mime_type_data = wpsc_get_mimetype($full_image_path, true);
                if ((int) $attachment_id == 0) {
                    // construct the image data array
                    $image_post_values = array('post_author' => $user_ID, 'post_parent' => $post_id, 'post_date' => $product_data->post_date, 'post_content' => $image_name, 'post_title' => $image_name, 'post_status' => "inherit", 'post_type' => "attachment", 'post_name' => sanitize_title($image_name), 'post_mime_type' => $mime_type_data['mime_type'], 'menu_order' => absint($image_row['image_order']), 'guid' => $new_path);
                    $attachment_id = wp_insert_post($image_post_values);
                }
                update_attached_file($attachment_id, $new_path);
                wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $new_path));
            }
            $i++;
            $progress->update($i);
            set_transient('wpsc_update_product_offset', $i, 604800);
        }
        $offset += $limit;
    }
    //Just throwing the payment gateway update in here because it doesn't really warrant it's own function :)
    $custom_gateways = get_option('custom_gateway_options');
    array_walk($custom_gateways, "wpec_update_gateway");
    update_option('custom_gateway_options', $custom_gateways);
}
Exemple #2
0
/**
 * Save a downloadable file to a product
 *
 * @since 3.8.9
 * @access private
 *
 * @uses $wpdb                          WordPress database object for use in queries
 * @uses _wpsc_create_ajax_nonce()      Creates nonce for an ajax action
 * @uses wpsc_get_mimetype()            Returns mimetype of file
 * @uses wp_insert_post()               Inserts post to WordPress database
 * @uses wp_nonce_url()                 Retrieve URL with nonce added to URL query.
 * @uses wpsc_convert_bytes()           Formats bytes
 * @uses wpsc_get_extension()           Gets extension of file
 * @uses esc_attr()                     Escapes HTML attributes
 * @uses _x()                           Retrieve translated string with gettext context
 *
 * @return array|WP_Error Response args if successful, WP_Error if otherwise.
 */
function _wpsc_ajax_upload_product_file()
{
    global $wpdb;
    $product_id = absint($_POST["product_id"]);
    $output = '';
    $delete_nonce = _wpsc_create_ajax_nonce('delete_file');
    foreach ($_POST["select_product_file"] as $selected_file) {
        // if we already use this file, there is no point doing anything more.
        $sql = $wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE post_type = 'wpsc-product-file' AND post_title = %s", $selected_file);
        // TODO it's safer to select by post ID, in that case we will use get_posts()
        $file_post_data = $wpdb->get_row($sql, ARRAY_A);
        $selected_file_path = WPSC_FILE_DIR . basename($selected_file);
        $file_url = WPSC_FILE_URL . basename($selected_file);
        $file_size = filesize($selected_file_path);
        if (empty($file_post_data)) {
            $type = wpsc_get_mimetype($selected_file_path);
            $attachment = array('post_mime_type' => $type, 'post_parent' => $product_id, 'post_title' => $selected_file, 'post_content' => '', 'post_type' => "wpsc-product-file", 'post_status' => 'inherit');
            $id = wp_insert_post($attachment);
        } else {
            // already attached
            if ($file_post_data['post_parent'] == $product_id) {
                continue;
            }
            $type = $file_post_data["post_mime_type"];
            $url = $file_post_data["guid"];
            $title = $file_post_data["post_title"];
            $content = $file_post_data["post_content"];
            // Construct the attachment
            $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => absint($product_id), 'post_title' => $title, 'post_content' => $content, 'post_type' => "wpsc-product-file", 'post_status' => 'inherit');
            // Save the data
            $id = wp_insert_post($attachment);
        }
        $deletion_url = wp_nonce_url("admin.php?wpsc_admin_action=delete_file&amp;file_name={$attachment['post_title']}&amp;product_id={$product_id}", 'delete_file_' . $attachment['post_title']);
        $output .= '<tr class="wpsc_product_download_row">';
        $output .= '<td style="padding-right: 30px;">' . $attachment['post_title'] . '</td>';
        $output .= '<td>' . wpsc_convert_byte($file_size) . '</td>';
        $output .= '<td>.' . wpsc_get_extension($attachment['post_title']) . '</td>';
        $output .= "<td><a data-file-name='" . esc_attr($attachment['post_title']) . "' data-product-id='" . esc_attr($product_id) . "' data-nonce='" . esc_attr($delete_nonce) . "' class='file_delete_button' href='{$deletion_url}' >" . _x('Delete', 'Digital Download UI row', 'wpsc') . "</a></td>";
        $output .= '<td><a href=' . $file_url . '>' . _x('Download', 'Digital Download UI row', 'wpsc') . '</a></td>';
        $output .= '</tr>';
    }
    return array('content' => $output);
}
/**
 * wpsc_item_reassign_file function
 *
 * @param integer product ID
 * @param string the selected file name;
 */
function wpsc_item_reassign_file($product_id, $selected_files)
{
    global $wpdb;
    $product_file_list = array();
    // initialise $idhash to null to prevent issues with undefined variables and error logs
    $idhash = null;
    $args = array('post_type' => 'wpsc-product-file', 'post_parent' => $product_id, 'numberposts' => -1, 'post_status' => 'any');
    $attached_files = (array) get_posts($args);
    foreach ($attached_files as $key => $attached_file) {
        $attached_files_by_file[$attached_file->post_title] = $attached_files[$key];
    }
    /* if we are editing, grab the current file and ID hash */
    if (!$selected_files) {
        // unlikely that anyone will ever upload a file called .none., so its the value used to signify clearing the product association
        return null;
    }
    foreach ($selected_files as $selected_file) {
        // if we already use this file, there is no point doing anything more.
        $file_is_attached = false;
        $selected_file_path = WPSC_FILE_DIR . basename($selected_file);
        if (isset($attached_files_by_file[$selected_file])) {
            $file_is_attached = true;
        }
        if ($file_is_attached == false) {
            $type = wpsc_get_mimetype($selected_file_path);
            $attachment = array('post_mime_type' => $type, 'post_parent' => $product_id, 'post_title' => $selected_file, 'post_content' => '', 'post_type' => "wpsc-product-file", 'post_status' => 'inherit');
            wp_insert_post($attachment);
        } else {
            $product_post_values = array('ID' => $attached_files_by_file[$selected_file]->ID, 'post_status' => 'inherit');
            wp_update_post($product_post_values);
        }
    }
    foreach ($attached_files as $attached_file) {
        if (!in_array($attached_file->post_title, $selected_files)) {
            $product_post_values = array('ID' => $attached_file->ID, 'post_status' => 'draft');
            wp_update_post($product_post_values);
        }
    }
    return $fileid;
}
/**
 * wpsc_item_add_preview_file function 
 *
 * @param integer product ID
 * @param array the preview file array from $_FILES
 */
function wpsc_item_add_preview_file($product_id, $preview_file)
{
    global $wpdb;
    $current_file_id = $wpdb->get_var("SELECT `file` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id` = '{$product_id}' LIMIT 1");
    $file_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id`='{$current_file_id}' LIMIT 1", ARRAY_A);
    if (apply_filters('wpsc_filter_file', $preview_file['tmp_name'])) {
        //echo "test?";
        if (function_exists("make_mp3_preview")) {
            if ($mimetype == "audio/mpeg" && !isset($preview_file['tmp_name'])) {
                // if we can generate a preview file, generate it (most can't due to sox being rare on servers and sox with MP3 support being even rarer), thus this needs to be enabled by editing code
                make_mp3_preview(WPSC_FILE_DIR . $idhash, WPSC_PREVIEW_DIR . $idhash . ".mp3");
                $preview_filepath = WPSC_PREVIEW_DIR . $idhash . ".mp3";
            } else {
                if (file_exists($preview_file['tmp_name'])) {
                    $preview_filename = basename($preview_file['name']);
                    $preview_mimetype = wpsc_get_mimetype($preview_file['tmp_name']);
                    copy($preview_file['tmp_name'], WPSC_PREVIEW_DIR . $preview_filename);
                    $preview_filepath = WPSC_PREVIEW_DIR . $preview_filename;
                    $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_FILES . "` SET `preview` = '" . $wpdb->escape($preview_filename) . "', `preview_mimetype` = '" . $preview_mimetype . "' WHERE `id` = '{$file_data['id']}' LIMIT 1");
                    //exit("UPDATE `".WPSC_TABLE_PRODUCT_FILES."` SET `preview` = '".$wpdb->escape($preview_filename)."', `preview_mimetype` = '".$preview_mimetype."' WHERE `id` = '{$file_data['id']}' LIMIT 1");
                }
            }
            $stat = stat(dirname($preview_filepath));
            $perms = $stat['mode'] & 0666;
            @chmod($preview_filepath, $perms);
        }
        //exit("<pre>".print_r($preview_file,true)."</pre>");
        return $fileid;
    } else {
        return $selected_files;
    }
}
function old_wpsc_item_reassign_file($selected_product_file, $mode = 'add')
{
    global $wpdb;
    // initialise $idhash to null to prevent issues with undefined variables and error logs
    $idhash = null;
    if ($mode == 'edit') {
        /* if we are editing, grab the current file and ID hash */
        $product_id = (int) $_POST['prodid'];
        if ($selected_product_file == '.none.') {
            // unlikely that anyone will ever upload a file called .none., so its the value used to signify clearing the product association
            $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_LIST . "` SET `file` = '0' WHERE `id` = '{$product_id}' LIMIT 1");
            return null;
        }
        // if we already use this file, there is no point doing anything more.
        $current_fileid = $wpdb->get_var("SELECT `file` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id` = '{$product_id}' LIMIT 1", ARRAY_A);
        if ($current_fileid > 0) {
            $current_file_data = $wpdb->get_row("SELECT `id`,`idhash` FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `id` = '{$current_fileid}' LIMIT 1", ARRAY_A);
            if (basename($selected_product_file) == $file_data['idhash']) {
                return $current_fileid;
            }
        }
    }
    $selected_product_file = basename($selected_product_file);
    if (file_exists(WPSC_FILE_DIR . $selected_product_file)) {
        $timestamp = time();
        $file_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `idhash` IN('" . $wpdb->escape($selected_product_file) . "') LIMIT 1", ARRAY_A);
        $fileid = (int) $file_data['id'];
        if ($fileid < 1) {
            // if the file does not have a database row, add one.
            $mimetype = wpsc_get_mimetype(WPSC_FILE_DIR . $selected_product_file);
            $filename = $idhash = $selected_product_file;
            $timestamp = time();
            $wpdb->query("INSERT INTO `" . WPSC_TABLE_PRODUCT_FILES . "` ( `filename`  , `mimetype` , `idhash` , `date` ) VALUES ( '{$filename}', '{$mimetype}', '{$idhash}', '{$timestamp}');");
            $fileid = $wpdb->get_var("SELECT `id` FROM `" . WPSC_TABLE_PRODUCT_FILES . "` WHERE `date` = '{$timestamp}' AND `filename` IN ('{$filename}')");
        }
        if ($mode == 'edit') {
            //if we are editing, update the file ID in the product row, this cannot be done for add because the row does not exist yet.
            $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_LIST . "` SET `file` = '{$fileid}' WHERE `id` = '{$product_id}' LIMIT 1");
        }
    }
    return $fileid;
}
Exemple #6
0
 // 		}
 // 	}
 /* handle editing file uploads here */
 if (!empty($_FILES['file']['name'])) {
     $fileid = wpsc_item_process_file('edit');
     $file = $fileid;
 } else {
     if ($_POST['select_product_file'] != '') {
         $fileid = wpsc_item_reassign_file($_POST['select_product_file'], 'edit');
         $file = $fileid;
     }
 }
 if (file_exists($_FILES['preview_file']['tmp_name'])) {
     $fileid = $wpdb->get_var("SELECT `file` FROM `" . $wpdb->prefix . "product_list` WHERE `id` = '{$id}' LIMIT 1");
     copy($_FILES['preview_file']['tmp_name'], WPSC_PREVIEW_DIR . basename($_FILES['preview_file']['name']));
     $mimetype = wpsc_get_mimetype(WPSC_PREVIEW_DIR . basename($_FILES['preview_file']['name']));
     $wpdb->query("UPDATE `" . $wpdb->prefix . "product_files` SET `preview` = '" . $wpdb->escape(basename($_FILES['preview_file']['name'])) . "', `preview_mimetype` = '" . $mimetype . "' WHERE `id` = '{$fileid}' LIMIT 1");
 }
 /* Handle new image uploads here */
 $image = wpsc_item_process_image();
 if (is_numeric($_POST['prodid'])) {
     if (($_POST['image_resize'] == 1 || $_POST['image_resize'] == 2) && $image == '') {
         /*  resize the image if directed to do so and no new image is supplied  */
         $image_data = $wpdb->get_row("SELECT `id`,`image` FROM `" . $wpdb->prefix . "product_list` WHERE `id`=" . $_POST['prodid'] . " LIMIT 1", ARRAY_A);
         // prevent images from being replaced by those from other products
         $check_multiple_use = $wpdb->get_var("SELECT COUNT(`image`) AS `count` FROM `" . $wpdb->prefix . "product_list` WHERE `image`='" . $image_data['image'] . "'");
         if ($check_multiple_use > 1) {
             $new_filename = $image_data['id'] . "_" . $image_data['image'];
             if (file_exists(WPSC_THUMBNAIL_DIR . $image_data['image']) && $image_data['image'] != null) {
                 copy(WPSC_THUMBNAIL_DIR . $image_data['image'], WPSC_THUMBNAIL_DIR . $new_filename);
             }
Exemple #7
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['mime'][] = 'image/svg+xml';
     $accepted_file_types['ext'][] = 'jpeg';
     $accepted_file_types['ext'][] = 'jpg';
     $accepted_file_types['ext'][] = 'gif';
     $accepted_file_types['ext'][] = 'png';
     //$accepted_file_types['ext'][] = 'svg';
     $can_have_uploaded_image = get_product_meta($this->product_id, 'can_have_uploaded_image');
     if ($can_have_uploaded_image == 'on') {
         $mime_type_data = wpsc_get_mimetype($file_data['tmp_name'], true);
         $name_parts = explode('.', basename($file_data['name']));
         $extension = array_pop($name_parts);
         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'];
         }
         //echo( "<pre>".print_r($mime_type_data,true)."</pre>" );
         //exit( "<pre>".print_r($file_data,true)."</pre>" );
         if ((array_search($mime_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);
             }
             //exit($file_data['name']);
             $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' => $mime_type, "unique_id" => $unique_id);
             }
         }
     }
 }
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>");
    }
}
Exemple #9
0
function prod_upload()
{
    global $wpdb;
    $product_id = absint($_POST["product_id"]);
    foreach ($_POST["select_product_file"] as $selected_file) {
        // if we already use this file, there is no point doing anything more.
        $sql = $wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE post_type = 'wpsc-product-file' AND post_title = %s", $selected_file);
        // TODO it's safer to select by post ID, in that case we will use get_posts()
        $file_post_data = $wpdb->get_row($sql, ARRAY_A);
        $selected_file_path = WPSC_FILE_DIR . basename($selected_file);
        if (isset($attached_files_by_file[$selected_file])) {
            $file_is_attached = true;
        }
        //if(is_file($selected_file_path)) {
        if (empty($file_post_data)) {
            $type = wpsc_get_mimetype($selected_file_path);
            $attachment = array('post_mime_type' => $type, 'post_parent' => $product_id, 'post_title' => $selected_file, 'post_content' => '', 'post_type' => "wpsc-product-file", 'post_status' => 'inherit');
            $id = wp_insert_post($attachment);
        } else {
            $type = $file_post_data["post_mime_type"];
            $url = $file_post_data["guid"];
            $title = $file_post_data["post_title"];
            $content = $file_post_data["post_content"];
            // Construct the attachment
            $attachment = array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => absint($product_id), 'post_title' => $title, 'post_content' => $content, 'post_type' => "wpsc-product-file", 'post_status' => 'inherit');
            // Save the data
            $id = wp_insert_post($attachment);
        }
        //}
        echo "{$id}\n";
    }
}
Exemple #10
0
/**
 * wpsc_convert_products_to_posts function.
 * 
 * @access public
 * @return void
 */
function wpsc_convert_products_to_posts()
{
    global $wpdb, $user_ID;
    // Select all products
    $product_data = $wpdb->get_results("SELECT `" . WPSC_TABLE_PRODUCT_LIST . "`. * , `" . WPSC_TABLE_PRODUCT_ORDER . "`.order FROM `" . WPSC_TABLE_PRODUCT_LIST . "` LEFT JOIN `" . WPSC_TABLE_PRODUCT_ORDER . "` ON `" . WPSC_TABLE_PRODUCT_LIST . "`.id = `" . WPSC_TABLE_PRODUCT_ORDER . "`.product_id WHERE `" . WPSC_TABLE_PRODUCT_LIST . "`.`active` IN ( '1' )\nGROUP BY " . WPSC_TABLE_PRODUCT_LIST . ".id", ARRAY_A);
    foreach ((array) $product_data as $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['id']));
        $sku = old_get_product_meta($product['id'], 'sku', true);
        if ($post_id == 0) {
            $post_status = "publish";
            if ($product['publish'] != 1) {
                $post_status = "draft";
            }
            //check the product added time with the current time to make sure its not out - this aviods the future post status
            $product_added_time = strtotime($product['date_added']);
            $current_time = time();
            $post_date = $product['date_added'];
            if ((int) $current_time < (int) $product_added_time) {
                $post_date = date("Y-m-d H:i:s");
            }
            $product_post_values = array('post_author' => $user_ID, 'post_date' => $post_date, 'post_content' => $product['description'], 'post_excerpt' => $product['additional_description'], 'post_title' => $product['name'], 'post_status' => $post_status, 'post_type' => "wpsc-product", 'post_name' => sanitize_title($product['name']), 'menu_order' => $product['order']);
            $post_id = wp_insert_post($product_post_values);
        }
        $product_meta = $wpdb->get_results("\n\t\t\tSELECT \tIF( ( `custom` != 1\t),\n\t\t\t\t\tCONCAT( '_wpsc_', `meta_key` ) ,\n\t\t\t\t`meta_key`\n\t\t\t\t) AS `meta_key`,\n\t\t\t\t`meta_value`\n\t\t\tFROM `" . WPSC_TABLE_PRODUCTMETA . "`\n\t\t\tWHERE `product_id` = " . $product['id'] . "\n\t\t\tAND `meta_value` != ''", ARRAY_A);
        $post_data = array();
        foreach ($product_meta as $k => $pm) {
            if ($pm['meta_value'] == 'om') {
                $pm['meta_value'] = 1;
            }
            $pm['meta_value'] = maybe_unserialize($pm['meta_value']);
            if (strpos($pm['meta_key'], '_wpsc_') === 0) {
                $post_data['_wpsc_product_metadata'][$pm['meta_key']] = $pm['meta_value'];
            } else {
                update_post_meta($post_id, $pm['meta_key'], $pm['meta_value']);
            }
        }
        $post_data['_wpsc_original_id'] = (int) $product['id'];
        $post_data['_wpsc_price'] = (double) $product['price'];
        $post_data['_wpsc_special_price'] = (double) $product['special_price'];
        $post_data['_wpsc_stock'] = (double) $product['quantity'];
        $post_data['_wpsc_is_donation'] = $product['donation'];
        $post_data['_wpsc_sku'] = $sku;
        if ((bool) $product['quantity_limited'] != true) {
            $post_data['_wpsc_stock'] = false;
        }
        unset($post_data['_wpsc_limited_stock']);
        $post_data['_wpsc_product_metadata']['is_stock_limited'] = (int) (bool) $product['quantity_limited'];
        // Product Weight
        $post_data['_wpsc_product_metadata']['weight'] = wpsc_convert_weight($product['weight'], $product['weight_unit'], "pound", true);
        $post_data['_wpsc_product_metadata']['weight_unit'] = $product['weight_unit'];
        $post_data['_wpsc_product_metadata']['display_weight_as'] = $product['weight_unit'];
        $post_data['_wpsc_product_metadata']['has_no_shipping'] = (int) (bool) $product['no_shipping'];
        $post_data['_wpsc_product_metadata']['shipping'] = array('local' => $product['pnp'], 'international' => $product['international_pnp']);
        $post_data['_wpsc_product_metadata']['quantity_limited'] = (int) (bool) $product['quantity_limited'];
        $post_data['_wpsc_product_metadata']['special'] = (int) (bool) $product['special'];
        if (isset($post_data['meta'])) {
            $post_data['_wpsc_product_metadata']['unpublish_when_none_left'] = (int) (bool) $post_data['meta']['_wpsc_product_metadata']['unpublish_when_none_left'];
        }
        $post_data['_wpsc_product_metadata']['no_shipping'] = (int) (bool) $product['no_shipping'];
        foreach ($post_data as $meta_key => $meta_value) {
            // prefix all meta keys with _wpsc_
            update_post_meta($post_id, $meta_key, $meta_value);
        }
        // get the wordpress upload directory data
        $wp_upload_dir_data = wp_upload_dir();
        $wp_upload_basedir = $wp_upload_dir_data['basedir'];
        $category_ids = array();
        $category_data = $wpdb->get_col("SELECT `category_id` FROM `" . WPSC_TABLE_ITEM_CATEGORY_ASSOC . "` WHERE `product_id` IN ('{$product['id']}')");
        foreach ($category_data as $old_category_id) {
            $category_ids[] = wpsc_get_meta($old_category_id, 'category_id', 'wpsc_old_category');
        }
        wp_set_product_categories($post_id, $category_ids);
        $product_data = get_post($post_id);
        $image_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_IMAGES . "` WHERE `product_id` IN ('{$product['id']}') ORDER BY `image_order` ASC", ARRAY_A);
        foreach ((array) $image_data as $image_row) {
            // Get the image path info
            $image_pathinfo = pathinfo($image_row['image']);
            // use the path info to clip off the file extension
            $image_name = basename($image_pathinfo['basename'], ".{$image_pathinfo['extension']}");
            // construct the full image path
            $full_image_path = WPSC_IMAGE_DIR . $image_row['image'];
            $attached_file_path = str_replace($wp_upload_basedir . "/", '', $full_image_path);
            $upload_dir = wp_upload_dir();
            $new_path = $upload_dir['path'] . '/' . $image_name . '.' . $image_pathinfo['extension'];
            if (is_file($full_image_path)) {
                copy($full_image_path, $new_path);
            } else {
                continue;
            }
            // construct the full image url
            $subdir = $upload_dir['subdir'] . '/' . $image_name . '.' . $image_pathinfo['extension'];
            $subdir = substr($subdir, 1);
            $attachment_id = (int) $wpdb->get_var("SELECT `ID` FROM `{$wpdb->posts}` WHERE `post_title` IN('{$image_name}') AND `post_parent` IN('{$post_id}') LIMIT 1");
            // get the image MIME type
            $mime_type_data = wpsc_get_mimetype($full_image_path, true);
            if ((int) $attachment_id == 0) {
                // construct the image data array
                $image_post_values = array('post_author' => $user_ID, 'post_parent' => $post_id, 'post_date' => $product_data->post_date, 'post_content' => $image_name, 'post_title' => $image_name, 'post_status' => "inherit", 'post_type' => "attachment", 'post_name' => sanitize_title($image_name), 'post_mime_type' => $mime_type_data['mime_type'], 'menu_order' => absint($image_row['image_order']), 'guid' => $new_path);
                $attachment_id = wp_insert_post($image_post_values);
            }
            $image_size_data = @getimagesize($full_image_path);
            $image_metadata = array('width' => $image_size_data[0], 'height' => $image_size_data[1], 'file' => $subdir);
            update_post_meta($attachment_id, '_wp_attached_file', $subdir);
            update_post_meta($attachment_id, '_wp_attachment_metadata', $image_metadata);
        }
    }
    //Just throwing the payment gateway update in here because it doesn't really warrant it's own function :)
    $custom_gateways = get_option('custom_gateway_options');
    array_walk($custom_gateways, "wpec_update_gateway");
    update_option('custom_gateway_options', $custom_gateways);
}