config->table_prefix}products ( item_ID int(4) NOT NULL auto_increment, item_SKU varchar(20) NOT NULL default '', item_name varchar(255) NOT NULL default '', item_description text NOT NULL, item_price float NOT NULL default 0.0, item_shipping float NOT NULL default 0.0, item_category varchar(255) NOT NULL default '', item_stock int(4) NOT NULL default 1, item_image varchar(255) NOT NULL default 'noimage.gif', PRIMARY KEY (item_ID), UNIQUE KEY item_SKU (item_SKU), KEY item_name (item_name) ); CREATE TABLE {$this->config->table_prefix}orders ( order_ID int(4) NOT NULL auto_increment, order_name varchar(255) NOT NULL default '', order_address text NOT NULL, order_date datetime NOT NULL, order_phone varchar(255) NOT NULL default '', order_email varchar(255) NOT NULL default '', order_IP varchar(15) NOT NULL default '', order_order text NOT NULL, order_cost float NOT NULL default 0.0, order_shipping float NOT NULL default 0.0, order_shipby varchar(255) NOT NULL default '', order_payby varchar(255) NOT NULL default '', order_trans_ID varchar(255) NOT NULL default '', order_status int(4) NOT NULL default 0, order_shipdate date, PRIMARY KEY (order_ID), KEY order_name (order_name), KEY order_trans_ID (order_trans_ID) ); "; return parent::upgrade($queries, true, false); } } // Extend microsession to enable non-WordPress authentication class microshopsession extends microsession { function do_auth($user, $pass) { if($this->config->UseWordPressDB) { return parent::do_auth($user, $pass, $this->config->minuserlevel); } else { return $pass == md5(md5($this->config->adminpassword)); } } } class microshoprewrite extends microrewrite { function init_rules() { global $config, $tableexists; $this->rules['actions'] = array('/^\/([^\/]+)\/?$/', 'action'); $this->rules['categories'] = array('/^\/(category)\/([^\/]+)\/?$/', 'action,category'); $this->rules['prodids'] = array('/^\/(edititem|stocktoggle)\/([0-9]+)\/?$/', 'action,prodid'); $this->rules['itemsku'] = array('/^\/(add2cart)\/([^\/]+)\/?$/', 'action,itemsku'); $this->rules['delete'] = array('/^\/(deleteitem)\/([^\/]+)\/?$/', 'action,delete'); $this->rules['vieworders'] = array('/^\/(vieworders)\/(all|unpaid|paid|shipped|caution)\/?$/', 'action,orders'); /* // Sub-pages... Future? $this->rules['pages'] = array('/^\/([a-z:0-9_\\-\/\\s.!]+)\/?/i', 'page'); $this->rules['pageactions'] = array('/^\/([a-z:0-9_\\-\/\\s.!]+)\/(view|edit|move|delete|image|media|upload|logout|rebuild|history|rss)(?:\/([0-9]+))?\/?$/i', 'page,action,tag'); */ $this->links['action'] = '/%action%'; $this->links['action_category'] = '/%action%/%category%'; $this->links['action_prodid'] = '/%action%/%prodid%'; $this->links['action_itemsku'] = '/%action%/%itemsku%'; $this->links['action_delete'] = '/%action%/%delete%'; $this->links['action_vieworders'] = '/%action%/%orders%'; } } class microshop { var $us_states; var $shipping_methods; var $payment_methods; var $config; var $db; var $session; var $enable_logging = false; var $specialmessage = ''; var $templates = array(); var $verified_callback; function microshop() { $this->us_states = array( 'AK'=>'Alaska', 'AL'=>'Alabama', 'AR'=>'Arkansas', 'AZ'=>'Arizona', 'CA'=>'California', 'CO'=>'Colorada', 'CT'=>'Conneticut', 'DC'=>'District of Colombia', 'DE'=>'Delaware', 'FL'=>'Florida', 'GA'=>'Georgia', 'HI'=>'Hawaii', 'IA'=>'Iowa', 'ID'=>'Idaho', 'IL'=>'Illinois', 'IN'=>'Indiana', 'KS'=>'Kansas', 'KY'=>'Kentucky', 'LA'=>'Louisiana', 'MA'=>'Massachusetts', 'MD'=>'Maryland', 'ME'=>'Maine', 'MI'=>'Michigan', 'MN'=>'Minnesota', 'MO'=>'Missouri', 'MS'=>'Mississippi', 'MT'=>'Montana', 'NC'=>'North Carolina', 'ND'=>'North Dakota', 'NE'=>'Nebraska', 'NH'=>'New Hampshire', 'NJ'=>'New Jersey', 'NM'=>'New Mexico', 'NV'=>'Nevada', 'NY'=>'New York', 'OH'=>'Ohio', 'OK'=>'Oklahoma', 'OR'=>'Oregon', 'PA'=>'Pennsylvania', 'RI'=>'Rhode Island', 'SC'=>'South Carolina', 'SD'=>'South Dakota', 'TN'=>'Tennessee', 'TX'=>'Texas', 'UT'=>'Utah', 'VI'=>'Virgin Islands', 'VT'=>'Vermont', 'VA'=>'Virginia', 'WA'=>'Washington', 'WI'=>'Wisconsin', 'WV'=>'West Virginia', 'WY'=>'Wyoming', ); /** Shipping Methods **/ // Add a new line for each shipping method: //$this->add_shipping_calc( NAME_OF_METHOD, CALLBACK_FUNCTION ); $this->add_shipping_calc('Total Up Shipping', array(&$this, 'calc_shipping_total')); //$this->add_shipping_calc('ODS Airborne', array(&$this, 'calc_shipping_one_max')); //$this->add_shipping_calc('UPS Ground', array(&$this, 'calc_shipping_upsground')); $this->add_shipping_calc('Pick up at store', array(&$this, 'calc_shipping_pickup')); // Add a new line for each payment method: //$this->add_payment_method( NAME_OF_METHOD, CALLBACK_FUNCTION ); $this->add_payment_method('Paypal', array(&$this, 'payment_paypal')); $this->add_payment_method('Check or Money Order', array(&$this, 'payment_check')); $this->config = new microshopconfig(__FILE__); $this->db = new microshopdb(&$this->config); $this->session = new microshopsession('microshop' . md5($this->config->shopname)); $this->rewrite = new microshoprewrite($this->config->baselocation, $this->config->baselocation_ssl, $this->config->linkstruct=='Friendly'); $this->session->config = &$this->config; $this->get_templates(); } function currency_to_symbol() { switch($this->config->currency) { case 'USD': return '$'; case 'GBP': return '£'; case 'EUR': return '€'; } } function add_shipping_calc($description, $callback) { $this->shipping_methods[$description] = $callback; } function add_payment_method($description, $callback) { $this->payment_methods[$description] = $callback; } // This function displays a product table row function product_row($item, $quantity=false) { $template = $this->templates['item_row']; $t = new microtemplate($template); $t->set_field('SKU', $item->item_SKU); $t->set_field('category_URL', $this->rewrite->get_link(array('category'=>$item->item_category, 'action'=>'category'))); $t->set_field('category', $item->item_category); $t->set_field('name', $item->item_name); if(substr($item->item_image, 0, 7) == 'http://') { $t->set_field('image_URL', $item->item_image); $t->set_field('has_image', true); } else if($item->item_image == '') { $t->set_field('image_URL', "{$this->config->image_url}/noimage.gif"); } else { $t->set_field('image_URL', "{$this->config->image_url}/{$item->item_image}"); $t->set_field('has_image', true); } $t->set_field('description', $item->item_description); if($item->item_stock > 0) $t->set_field('in_stock', $item->item_stock); if($this->session->is_auth()) $t->set_field('is_auth', true); $t->set_field('edit_URL', $this->rewrite->get_link(array('action'=>'edititem', 'prodid'=>$item->item_ID))); $t->set_field('stocktoggle_URL', $this->rewrite->get_link(array('action'=>'stocktoggle', 'prodid'=>$item->item_ID))); $t->set_field('price', number_format($item->item_price, 2)); if($quantity) $t->set_field('set_quantity', true); $t->set_field('quantity', @$this->session->cart[$item->item_SKU]); if(@$this->session->cart[$item->item_SKU] > 0) $t->set_field('in_cart', true); $t->set_field('cart_URL', $this->rewrite->get_link(array('action'=>'showcart'))); $t->set_field('add_item_URL', $this->rewrite->get_link(array('action'=>'add2cart', 'itemsku'=>$item->item_SKU))); $t->set_field('delete_URL', $this->rewrite->get_link(array('action'=>'deleteitem', 'delete'=>$item->item_SKU))); $t->set_field('currency', $this->currency_to_symbol()); echo $t->render(); } // Add one function for each shipping method to calculate shipping cost: function calc_shipping_total($shippingfees, &$message) { /* This function sums the item_shipping value of each product and returns it as the shipping cost. You can convert this function to use the item_shipping field as a weight, then compare the weight to a table for your shipping method to calculate the total cost. */ $message = $this->currency_to_symbol() . number_format(array_sum($shippingfees), 2); return array_sum($shippingfees); } function calc_shipping_one_max($shippingfees, &$message) { $count = count($shippingfees) - 1; $max = array_reduce($shippingfees, create_function('$a,$b', 'return (($a > $b) ? $a : $b);')); $shipping = $max + $count; $message = $this->currency_to_symbol() . number_format($shipping, 2); return $shipping; } function calc_shipping_upsground($shippingfees, &$message) { global $config; require_once("ups.php"); $rate = new Ups; $rate->upsProduct("GND"); // See upsProduct() function for codes $rate->origin($this->config->shipfrom, "US"); // Use ISO country codes! $rate->dest($_REQUEST['zipcode'], "US"); // Use ISO country codes! $rate->rate("CC"); // See the rate() function for codes $rate->container("CP"); // See the container() function for codes $rate->weight(round(array_sum($shippingfees))); $rate->rescom("RES"); // See the rescom() function for codes $quote = $rate->getQuote(); if(is_numeric($quote)) { $message = $this->currency_to_symbol() . number_format($quote, 2); return $quote; } else { $message = "Need zip code"; return 0; } } function calc_shipping_pickup($shippingfees, &$message) { $message = 'Free!'; return 0; } function page_header() { echo ' ' . $this->config->shopname . ' '; } function page_footer() { echo ' '; } function show_panel() { if($this->session->auth_form()) { $userlogin = $this->config->UseWordPressDB ? "You are logged in as the WordPress user '{$this->session->session_username}'." : "You are logged in using the password stored in the shop config."; echo "

{$this->config->shopname} Control Panel

{$userlogin}

MicroShop version:" . MICROSHOP_VERSION . "

"; } } function show_install() { if(!$this->db->table_exists($this->config->table_prefix . 'products') || $this->session->auth_form()) { if($this->config->write_post()) { $this->db = new microshopdb(&$this->config); echo "

Database Upgrades

\n"; $upgrades = $this->db->upgrade(); echo "
\n"; } echo "

Return to the rewrite->get_link(array('action'=>'panel')) . "\">Control Panel.

\n"; echo "

Shop Configuration

\n"; $this->config->editform(true); echo '

Return to the shop

'; } } function show_default() { $categories = $this->db->get_results("select * from {$this->config->table_prefix}products group by item_category order by item_category;"); if(count($categories) > 1) { echo "

Product Categories

\n"; echo "\n"; foreach($categories as $category) { echo "\n"; echo "\n"; echo "\n"; $this->product_row($category); echo "\n"; echo "\n"; echo "\n"; } echo "
Category: rewrite->get_link(array('category'=>$category->item_category, 'action'=>'category')) . "\">{$category->item_category}
See more in rewrite->get_link(array('category'=>$category->item_category, 'action'=>'category')) . "\">{$category->item_category}
\n"; echo "
" . $this->linkasbutton($this->rewrite->get_link(array('action'=>'viewcart')), 'View Shopping Cart'); if($this->session->is_auth()) echo $this->linkasbutton($this->rewrite->get_link(array('action'=>'panel')), 'Control Panel'); echo "
"; return true; } else { return false; } } function show_category($catname = '', $isdefault = false) { $qpage = isset($_REQUEST['catpage']) ? $_REQUEST['catpage'] - 1 : 0; $page = $qpage * $this->config->itemsperpage; $displaycat = ($catname == '' ) ? 'All Products' : "{$catname} - Product Listing"; $catname = ($catname == '' ) ? '1' : "item_category = '{$catname}'"; $products = $this->db->get_results("select * from {$this->config->table_prefix}products WHERE {$catname} order by item_name LIMIT {$page}, {$this->config->itemsperpage};"); $productcount = $this->db->get_var("select count(item_ID) as ttl from {$this->config->table_prefix}products WHERE {$catname};"); $pages = ceil($productcount / $this->config->itemsperpage); for($z=1;$z<=$pages;$z++) { if($z != $qpage + 1) { $pagebar .= "rewrite->get_link('catpage', $z) . "\">[{$z}] "; } else { $pagebar .= "[{$z}] "; } } $pagebar = $pagebar == '' ? "Page: [1]" : "Page: {$pagebar}"; echo "

{$displaycat}

\n"; echo "
{$pagebar}
\n"; echo "\n"; foreach($products as $product) { $this->product_row($product); } echo "
\n"; echo "
{$pagebar}
\n"; echo '
' . $this->linkasbutton($this->rewrite->get_link(array('action'=>'showcart')), 'View Shopping Cart'); if(!$isdefault) echo $this->linkasbutton($this->rewrite->get_link(array()), 'Show Categories'); if($this->session->is_auth()) echo $this->linkasbutton($this->rewrite->get_link(array('action'=>'panel')), 'Control Panel'); echo "
"; } function handle_cart() { switch(@$_POST['cartaction']) { case 'Check Out': $this->show_checkout(); break; case 'Update Cart': $this->update_cart(); default: $this->show_cart(); } } function show_cart() { echo "

Your Shopping Cart

\n"; if($this->specialmessage != '') echo "
{$this->specialmessage}
"; echo "
rewrite->get_link(array('action'=>'showcart')) . "\">"; if(is_array($this->session->cart) && count($this->session->cart) > 0) { echo "\n"; foreach($this->session->cart as $item_SKU => $quantity) { $dbitem = $this->db->get_row("SELECT * FROM {$this->config->table_prefix}products WHERE item_SKU = '{$item_SKU}'"); $total += $dbitem->item_price * $quantity; $shipping += $dbitem->item_shipping * $quantity; $this->product_row($dbitem, true); } echo "\n"; echo "\n"; echo "\n"; echo "
Subtotal: " . $this->currency_to_symbol() . number_format($total, 2) . "
Shipping & handling: to be determined
Total: " . $this->currency_to_symbol() . number_format($total, 2) . " + shipping
\n"; echo ''; echo ''; } else { echo "

Your cart is empty.

"; } echo "
"; echo $this->linkasbutton($this->rewrite->get_link(array()), 'Continue Shopping'); } function show_add2cart() { if(isset($_REQUEST['itemsku'])) { $this->session->cart[$_REQUEST['itemsku']] += 1; } $this->session->save(); if(!$this->config->addshowcart) { header("Location: {$_SERVER['HTTP_REFERER']}#product_{$_REQUEST['itemsku']}"); echo "

Return to shop

"; return true; } $this->specialmessage = "Item Added to Cart"; return false; } function update_cart() { if(isset($_POST['quantity'])) { foreach($_POST['quantity'] as $key => $value) { $this->session->cart[$key] = $value; if($value <= 0) { unset($this->session->cart[$key]); } } $this->specialmessage = "Shopping Cart Updated"; } $this->session->save(); } function show_deleteitem($sku) { if($this->session->auth_form()) { if(isset($_REQUEST['confirmdelete'])) { $this->db->query("DELETE FROM {$this->config->table_prefix}products WHERE item_SKU = '{$sku}' LIMIT 1;"); echo "
Item Deleted
"; } else { $item = $this->db->get_row("SELECT * FROM {$this->config->table_prefix}products WHERE item_SKU = '{$sku}' LIMIT 1;"); echo "
rewrite->get_link(array('action'=>'deleteitem','delete'=>$sku)) . "\">

Are you sure that you want to delete this item from the shop:

Item Name:
{$item->item_name}
Item SKU:
{$sku}
"; } echo $this->linkasbutton($this->rewrite->get_link(array('action'=>'panel')), 'Control Panel'); } } function show_edititem($doadd = false) { if($this->session->auth_form()) { if(isset($_POST['act'])) { if($_POST['prodid'] == -1) { if($_POST['generateSKU'] == 'true') { $wrds = explode(' ', $_POST['item_name']); $wrds = strtolower(implode(array_map(create_function('$a', 'return substr($a, 0, 3);'), $wrds))); $sku = dechex(rand(1048576, 16777215)); $skuid = 0; do { $sku = $wrds . (++$skuid); } while ($this->db->get_row("SELECT * FROM {$this->config->table_prefix}products WHERE item_SKU = '{$sku}';")); } else { $sku = $_POST['item_SKU']; } $qry = "INSERT INTO {$this->config->table_prefix}products (item_name, item_SKU, item_category, item_description, item_price, item_shipping, item_stock, item_image) VALUES ("; $qry .= "'{$_POST['item_name']}', "; $qry .= "'{$sku}', "; $qry .= "'{$_POST['item_category']}', "; $qry .= "'{$_POST['item_description']}', "; $qry .= "{$_POST['item_price']}, "; $qry .= "{$_POST['item_shipping']}, "; if(isset($_POST['item_stock']) && ($_POST['item_stock'] == 1)) { $qry .= "1, "; } else { $qry .= "0, "; } $qry .= "'{$_POST['item_image']}');"; if(!$this->db->query($qry)) { $this->db->get_error(true); } else { $action = 'edititem'; $_REQUEST['prodid'] = $this->db->insert_id; $this->specialmessage = 'Product added to database.'; } } else { $qry = "UPDATE {$this->config->table_prefix}products SET "; $qry .= "item_name = '{$_POST['item_name']}', "; $qry .= "item_SKU = '{$_POST['item_SKU']}', "; $qry .= "item_category = '{$_POST['item_category']}', "; $qry .= "item_description = '{$_POST['item_description']}', "; $qry .= "item_price = {$_POST['item_price']}, "; $qry .= "item_shipping = {$_POST['item_shipping']}, "; if(isset($_POST['item_stock']) && ($_POST['item_stock'] == 1)) { $qry .= "item_stock = 1, "; } else { $qry .= "item_stock = 0, "; } $qry .= "item_image = '{$_POST['item_image']}'"; $qry .= "WHERE item_ID = {$_POST['prodid']} LIMIT 1;"; if(!$this->db->query($qry)) { $this->db->get_error(true); } else { $this->specialmessage = 'Product definition updated.'; } } } if($doadd) { echo "

Add Item

Enter values for all fields and click Submit to add a new product to the shop.

"; $act = "Add"; $prodid = '-1'; } else { echo "

Edit Item

Modify the values for any fields and click Submit to update the product in the shop.

"; $act = "Update"; $prodid = $_REQUEST['prodid']; $item = $this->db->get_row("SELECT * FROM {$this->config->table_prefix}products WHERE item_ID = {$prodid}"); } if($this->specialmessage != '') echo "
{$this->specialmessage}
"; echo "
rewrite->get_link(array('action'=>'additem')) . "\">
Item Name:
item_name}\" />
Item SKU (must be unique):
"; if($doadd) { echo " item_SKU}\" />
"; } else { echo "item_SKU}\" />"; } echo "
Category:
Description:
Price:
item_price}\" />
Shipping:
item_shipping}\" />
In Stock:
item_stock == 1?' checked="checked"':'') . " />
Product Image URL:
item_image}\" />
"; echo "
" . $this->linkasbutton($this->rewrite->get_link(array('action'=>'viewcart')), 'View Shopping Cart'); echo $this->linkasbutton($this->rewrite->get_link(array('action'=>'panel')), 'Control Panel'); echo "
"; } } function toggle_stock($prodid) { if($this->session->auth_form()) { if($this->db->query("UPDATE {$this->config->table_prefix}products SET item_stock = 1 - item_stock WHERE item_ID = {$prodid} LIMIT 1;")) header("location: {$_SERVER['HTTP_REFERER']}"); else $this->db->get_error(true); } } function show_order() { if($this->session->auth_form()) { if(isset($_REQUEST['order'])) { if(isset($_REQUEST['newstatus'])) { $this->db->query("UPDATE {$this->config->table_prefix}orders SET order_status = {$_REQUEST['newstatus']} WHERE order_trans_ID = '{$_REQUEST['order']}';"); $this->specialmessage = "
Status Updated.
"; if($_POST['newstatus'] == 4) { $this->db->query("UPDATE {$this->config->table_prefix}orders SET order_shipdate = now() WHERE order_trans_ID = '{$_REQUEST['order']}';"); $this->specialmessage = "
Status and Ship Date Updated.
"; } } echo "

View Order

{$this->specialmessage}
rewrite->get_link(array('action'=>'vieworders', 'orders'=>'all')) . "\">All rewrite->get_link(array('action'=>'vieworders', 'orders'=>'unpaid')) . "\">Unpaid rewrite->get_link(array('action'=>'vieworders', 'orders'=>'paid')) . "\">Paid rewrite->get_link(array('action'=>'vieworders', 'orders'=>'shipped')) . "\">Shipped rewrite->get_link(array('action'=>'vieworders', 'orders'=>'caution')) . "\">Caution
"; if($order = $this->db->get_row("SELECT * FROM {$this->config->table_prefix}orders WHERE order_trans_ID = '{$_REQUEST['order']}';")) { $address = implode("
", explode("\n", $order->order_address)); $order_order = implode("
", explode("\n", $order->order_order)); $options[] = ''; $options[] = ''; $options[] = ''; $options[] = ''; $options[] = ''; $options[] = ''; $options[] = ''; $options = implode("\n", $options); echo "
Trans #:
{$order->order_trans_ID}
Order Date:
{$order->order_date}
Name:
{$order->order_name}
Address:
{$address}
Email:
{$order->order_email}
IP Address:
{$order->order_IP}
Phone:
{$order->order_phone}
Items Ordered:
{$order_order}
Subtotal:
" . $this->currency_to_symbol() . number_format($order->order_cost, 2) . "
Shipping:
" . $this->currency_to_symbol() . number_format($order->order_shipping, 2) . "
Total:
" . $this->currency_to_symbol() . number_format($order->order_cost + $order->order_shipping, 2) . "
Ship Via:
{$order->order_shipby}
Pay By:
{$order->order_payby}
Ship Date:
{$order->order_shipdate}
"; } else { echo "

No order exists with that transaction ID.

"; } } } } function show_orders($orders) { if($this->session->auth_form()) { if(isset($_POST['trans'])) { $deleted = 0; foreach($_POST['trans'] as $transid) { $this->db->query("DELETE FROM {$this->config->table_prefix}orders WHERE order_trans_ID = '{$transid}'"); $deleted++; } $this->specialmessage = "
Deleted {$deleted} orders
"; } if($orders) { $qtype = $orders; } else { $qtype = 'paid'; } $newstatus = -1; $link_status = array('all'=>'', 'unpaid'=>'', 'paid'=>'', 'shipped'=>'', 'caution'=>''); $link_status[$qtype] = ' class="selected" '; switch($qtype) { case 'all': $qry = "SELECT * FROM {$this->config->table_prefix}orders;"; break; case 'unpaid': $qry = "SELECT * FROM {$this->config->table_prefix}orders WHERE order_status = 1 OR order_status = 2 ORDER BY order_date;"; $newstatus = 3; $newstatustext = 'paid'; break; case 'paid': $qry = "SELECT * FROM {$this->config->table_prefix}orders WHERE order_status = 3 ORDER BY order_date;"; $newstatus = 4; $newstatustext = 'shipped'; break; case 'shipped': $qry = "SELECT * FROM {$this->config->table_prefix}orders WHERE order_status = 4 ORDER BY order_date;"; break; case 'caution': $qry = "SELECT * FROM {$this->config->table_prefix}orders WHERE order_status IN (0, 5, 6) ORDER BY order_date;"; $newstatus = 3; $newstatustext = 'paid'; break; } echo "

View {$qtype} Orders

{$this->specialmessage}
rewrite->get_link(array('action'=>'vieworders', 'orders'=>'all')) . "\" {$link_status['all']}>All rewrite->get_link(array('action'=>'vieworders', 'orders'=>'unpaid')) . "\" {$link_status['unpaid']}>Unpaid rewrite->get_link(array('action'=>'vieworders', 'orders'=>'paid')) . "\" {$link_status['paid']}>Paid rewrite->get_link(array('action'=>'vieworders', 'orders'=>'shipped')) . "\" {$link_status['shipped']}>Shipped rewrite->get_link(array('action'=>'vieworders', 'orders'=>'caution')) . "\" {$link_status['caution']}>Caution
"; $orders = $this->db->get_results($qry); if($orders) { echo "
"; foreach($orders as $order) { $alternate = $alternate == 'even_row' ? 'even_row' : 'odd_row'; switch($order->order_status) { case 0: $status = 'Incomplete'; break; case 1: $status = 'Waiting for PayPal'; break; case 2: $status = 'Waiting for Check'; break; case 3: $status = 'Payment Received'; break; case 4: $status = 'Shipped'; break; case 5: $status = 'PayPal Pending'; break; case 6: $status = 'PayPal Failed'; break; } echo " "; } echo "
order_trans_ID}\" /> Trans #: rewrite->get_link(array('action'=>'vieworder', 'order'=>$order->order_trans_ID))."\">{$order->order_trans_ID} "; if($newstatus != -1) echo "rewrite->get_link(array('action'=>'vieworder', 'order'=>$order->order_trans_ID, 'newstatus'=>$newstatus))."\">[make {$newstatustext}]"; echo "
{$order->order_date} order_email}?subject=Order from {$this->config->shopname}: {$order->order_trans_ID}&body=Regarding the order placed {$order->order_date}:\">{$order->order_name} {$order->order_order} {$status}
"; echo "
"; } else { echo "

No orders qualify under this criteria ('{$qtype}').

\n"; } echo $this->linkasbutton($this->rewrite->get_link(array('action'=>'panel')), 'Control Panel'); } } function show_checkout2() { if(!( $_POST['cust_name'] == '' || $_POST['address'] == '' || $_POST['city'] == '' || $_POST['state'] == '' || !preg_match('/^[0-9]{5}(-[0-9]{4})?$/', $_POST['zipcode']) || !preg_match('/[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}/i', $_POST['email']) || !preg_match('/\\(?[0-9]{3}\\)?[-. ]*[0-9]{3}[-. ]*[0-9]{4}/', $_POST['phone']) )) { //Form submission success echo "

Verify Order

Please verify your order below. If something is incorrect, click the Back button in your browser to make changes.

"; echo "

Shipping and Payment Details:

Pay by:
{$_REQUEST['payby']}
Ship by:
{$_REQUEST['shipby']}
Name:
{$_REQUEST['cust_name']}
Address:
{$_REQUEST['address']}
City:
{$_REQUEST['city']}
State:
{$this->us_states[$_REQUEST['state']]}
Zip Code:
{$_REQUEST['zipcode']}
Phone Number:
{$_REQUEST['phone']}
Email:
{$_REQUEST['email']}
"; echo "

Order Information

\n\n"; echo "

Subtotal: " . $this->currency_to_symbol() . number_format($total, 2) . "

\n"; $scost = call_user_func_array($this->shipping_methods[$_REQUEST['shipby']], array($shipping_items, &$message)); echo "

Shipping & Handling: " . $this->currency_to_symbol() . number_format($scost, 2) . "

\n"; echo "

Order Total: " . $this->currency_to_symbol() . number_format($total + $scost, 2) . "

\n"; echo "
rewrite->get_link(array('action'=> 'pay')) . "\">\n"; foreach($_POST as $key=>$value) { echo "\n"; } echo "\n
\n"; return true; } $this->specialmessage = 'Please fill out all fields completely.'; if($_POST['cust_name'] == '') $this->specialmessage .= '
Please include your name.'; if($_POST['address'] == '') $this->specialmessage .= '
Please include your address.'; if($_POST['city'] == '') $this->specialmessage .= '
Please include your city.'; if($_POST['state'] == '') $this->specialmessage .= '
Please include your state.'; if(!preg_match('/^[0-9]{5}(-[0-9]{4})?$/', $_POST['zipcode'])) $this->specialmessage .= '
Please include a valid zip code.'; if(!preg_match('/[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}/i', $_POST['email'])) $this->specialmessage .= '
Please include a valid email.'; if(!preg_match('/\\(?[0-9]{3}\\)?[-. ]*[0-9]{3}[-. ]*[0-9]{4}/', $_POST['phone'])) $this->specialmessage .= '
Please include a valid phone number.'; return false; } function show_checkout() { echo "

Checkout - Payment and Shipping Info

"; if($this->specialmessage != '') echo "
{$this->specialmessage}
"; echo "

" . str_replace("\n", '
', $this->config->checkoutmessage) . "

rewrite->get_link(array('action'=>'checkout2')) . "\">

Please select your payment method:

Please select your shipping method:

Please provide your shipping information:

Name:
Address:
City:
State:
Zip Code:
Phone Number:
Email:
"; } function pay() { if(!(is_array($this->session->cart) && count($this->session->cart))) { die('fail');header('location: ' . $this->rewrite->get_link(array('action'=>'showcart'))); } // Insert a record into the purchase table. $address = "{$_REQUEST['address']}\n{$_REQUEST['city']}, {$_REQUEST['state']}\n{$_REQUEST['zipcode']}"; $order = ''; foreach($this->session->cart as $item_SKU => $quantity) { $dbitem = $this->db->get_row("SELECT * FROM {$this->config->table_prefix}products WHERE item_SKU = '{$item_SKU}'"); $cost += $dbitem->item_price * $quantity; for($z=1;$z<=$quantity;$z++) $shipping_items[] = $dbitem->item_shipping; $order .= "{$quantity} x {$dbitem->item_name} ({$item_SKU}) @ " . $this->currency_to_symbol() . number_format($dbitem->item_price, 2) . "\n"; } $shipping = call_user_func_array($this->shipping_methods[$_REQUEST['shipby']], array($shipping_items, $message)); $txnumber = date('Y') . sprintf('%02s%02s', dechex(intval(date('z'))), dechex($this->db->get_var("SELECT count(order_ID) FROM {$this->config->table_prefix}orders WHERE date(order_date) = date(now())"))); $qry = "INSERT INTO {$this->config->table_prefix}orders (order_name, order_address, order_phone, order_email, order_IP, order_date, order_order, order_cost, order_shipping, order_shipby, order_payby, order_trans_ID, order_status) values ("; $qry .= "'{$_REQUEST['cust_name']}', "; $qry .= "'{$address}', "; $qry .= "'{$_REQUEST['phone']}', "; $qry .= "'{$_REQUEST['email']}', "; $qry .= "'{$_SERVER['REMOTE_ADDR']}', "; $qry .= "now(), "; $qry .= "'". $order ."', "; $qry .= "{$cost}, "; $qry .= "{$shipping}, "; $qry .= "'{$_REQUEST['shipby']}', "; $qry .= "'{$_REQUEST['payby']}', "; $qry .= "'" . $txnumber . "', "; $qry .= "0);"; if(!$this->db->query($qry)) { die($this->db->get_error()); } $insertid = $this->db->insert_id(); /* $txnumber = base_convert($insertid * 7 + 531309907, 10, 16); //Unique alphanumeric trans IDs that are not sequential if(!$this->db->query("UPDATE {$this->config->table_prefix}orders set order_trans_ID = '{$txnumber}' WHERE order_ID = {$insertid};")) { die($this->db->get_error()); } */ call_user_func_array($this->payment_methods[$_REQUEST['payby']], array($cost, $shipping, $txnumber)); } function payment_paypal($cost, $shipping, $txnumber) { $completed = str_replace('&', '%26', str_replace('?', '%3F', $this->rewrite->get_link(array('action'=>'completed', 'trans'=>$txnumber)))); $cancelled = str_replace('&', '%26', str_replace('?', '%3F', $this->rewrite->get_link(array('action'=>'cancelled', 'trans'=>$txnumber)))); $notify_url = str_replace('&', '%26', str_replace('?', '%3F', $this->config->notify_url)); if($notify_url == '') $notify_url = 'http://' . $_SERVER['HTTP_HOST'] . str_replace('&', '%26', str_replace('?', '%3F', $this->rewrite->get_link(array('action'=>'paypalverify', 'trans'=>$txnumber)))); $payurl = "https://www.{$this->config->sandbox}paypal.com/xclick/business="; //Use this one for actual transactions $payurl .= $this->config->paypal_account; //PayPal payee email $payurl .= "&item_name=Order+at+" . urlencode($this->config->shopname); // Puchased thing shown at PayPal $payurl .= "&item_number={$txnumber}"; // Item number, used transaction ID. $payurl .= "&amount=" . $cost; //Item price $payurl .= "&shipping=" . $shipping; //Item shipping $payurl .= "&no_shipping=1"; $payurl .= "&return=" . "http://{$_SERVER['HTTP_HOST']}{$completed}"; $payurl .= "&cancel_return=" . "http://{$_SERVER['HTTP_HOST']}{$cancelled}"; $payurl .= "¬ify_url={$notify_url}"; $payurl .= "&no_note=1"; $payurl .= "¤cy_code=" . $this->config->currency; //Curency Used $payurl .= "&lc=US"; //Language Locale $payurl .= "&rm=2"; //Return method 1=get, 2=post //die($payurl); header("Location: {$payurl}"); } function payment_check($cost, $shipping, $txnumber) { echo "

Pay By Check

"; echo "

Thank you for your order!

Please print out this invoice and send it with your payment to:

" . str_replace("\n", '
', $this->config->payment_location) . "

Please allow time for your payment to arrive and clear before expecting delivery.

"; echo "

Shipping and Payment Details:

Pay by:
{$_REQUEST['payby']}
Ship by:
{$_REQUEST['shipby']}
Name:
{$_REQUEST['cust_name']}
Address:
{$_REQUEST['address']}
City:
{$_REQUEST['city']}
State:
{$this->us_states[$_REQUEST['state']]}
Zip Code:
{$_REQUEST['zipcode']}
Phone Number:
{$_REQUEST['phone']}
Email:
{$_REQUEST['email']}
"; echo "

Order Information

\n\n"; echo "

Subtotal: " . $this->currency_to_symbol() . number_format($cost, 2) . "

\n"; echo "

Shipping & Handling: " . $this->currency_to_symbol() . number_format($shipping, 2) . "

\n"; echo "

Order Total: " . $this->currency_to_symbol() . number_format($cost + $shipping, 2) . "

\n"; $this->db->query("UPDATE {$this->config->table_prefix}orders SET order_status = 2 WHERE order_trans_ID = '{$txnumber}'"); $this->sendinvoice($txnumber, 0); $this->session->cart = array(); $this->session->save(); } function show_completed() { echo "

Order Complete!

Thank you for your order! You should receive a receipt for this order by email shortly.

"; $this->db->query("UPDATE {$this->config->table_prefix}orders SET order_status = 1 WHERE order_status = 0 AND order_trans_ID = '{$_REQUEST['trans']}'"); $this->sendinvoice($_REQUEST['trans'], 1); $this->session->cart = array(); $this->session->save(); } function show_cancelled() { echo "

Order Cancelled!

Your order was not completed. Please review the items in your rewrite->get_link(array('action'=>'showcart')) . "\">shopping cart and checkout again to place your order.

"; $this->db->query("DELETE FROM {$this->config->table_prefix}orders WHERE order_status = 0 AND order_trans_ID = '{$_REQUEST['trans']}' LIMIT 1"); } function verify_paypal() { while (@ob_end_clean()); $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n"; $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; $header .= "Content-Length: " . strlen($req) . "\r\n\r\n"; $fp = fsockopen ("www.{$this->config->sandbox}paypal.com", 80, $errno, $errstr, 30); $postvars = array('item_name', 'item_number', 'payment_status', 'mc_gross', 'mc_currency', 'txn_id', 'receiver_email', 'payer_email'); foreach($postvars as $varname) { $$varname = $_POST[$varname]; } if (!$fp) { $this->outlog("Could not open route to Paypal"); } else { fputs ($fp, $header . $req); while (!feof($fp)) { $res = fgets ($fp, 1024); if (strcmp ($res, "VERIFIED") == 0) { $good_trans = ''; if($receiver_email != $this->config->paypal_account) { $good_trans .= "\nReceiver {$receiver_email} != Required: {$this->config->paypal_account}"; } if($trans = $this->db->get_row("SELECT * FROM {$this->config->table_prefix}orders WHERE order_trans_ID = '{$item_number}';")) { if($mc_gross != ($trans->order_cost + $trans->order_shipping)) { $good_trans .= "\nTrans Amount {$mc_gross} != Required: " . ($trans->order_cost + $trans->order_shipping); } if($good_trans == '') { switch(strtolower($payment_status)) { case 'completed': $this->db->query("UPDATE {$this->config->table_prefix}orders SET order_status = 3 WHERE order_trans_ID = '{$item_number}'"); $this->outlog("Completed: {$item_number}"); if(isset($this->verified_callback) && is_callable($this->verified_callback)) call_user_func_array($this->verified_callback, array('completed', $item_number)); else sendinvoice($item_number, 2); break; case 'pending': $this->db->query("UPDATE {$this->config->table_prefix}orders SET order_status = 5 WHERE order_trans_ID = '{$item_number}'"); $this->outlog("Pending: {$item_number}"); if(isset($this->verified_callback) && is_callable($this->verified_callback)) call_user_func_array($this->verified_callback, array('pending', $item_number)); break; case 'failed': $this->db->query("UPDATE {$this->config->table_prefix}orders SET order_status = 6 WHERE order_trans_ID = '{$item_number}'"); $this->outlog("Failed: {$item_number}"); if(isset($this->verified_callback) && is_callable($this->verified_callback)) call_user_func_array($this->verified_callback, array('failed', $item_number)); break; default: //Unknown status! $this->outlog("Unknown Status: $payment_status"); break; } } else { $this->outlog("PayPal transaction details don't match our records.{$good_trans}"); break; } } else { $this->outlog('No transaction in database'); } } else if (strcmp ($res, "INVALID") == 0) { $this->outlog('INVALID'); } } fclose ($fp); } die(); } function render() { if($this->config->displayaspage) $this->page_header(); $uri = parse_url($_SERVER['REQUEST_URI']); $shopurl = (($_SERVER["HTTPS"] == 'on')?$this->config->baselocation_ssl:$this->config->baselocation); echo '

' . $this->config->shopname . '

'; extract($this->rewrite->compact()); //owd($this->rewrite); $action = strtolower(str_replace(' ', '', $action)); if(!$this->db->table_exists($this->config->table_prefix . 'products') && $action != 'dbdebug') $action = 'install'; switch($action) { case 'panel': $this->show_panel(); break; case 'install': $this->show_install(); break; case 'additem': $this->show_edititem(true); break; case 'edititem': $this->show_edititem(); break; case 'deleteitem': $this->show_deleteitem($delete); break; case 'stocktoggle': $this->toggle_stock($prodid); break; case 'vieworder': $this->show_order(); break; case 'unpaidorders': $this->show_orders(); break; case 'vieworders': $this->show_orders($orders); break; case 'add2cart': if($this->show_add2cart()) break; case 'updatecart': case 'viewcart': // I keep using this instead of 'showcart'... Gah! case 'showcart': $this->handle_cart(); break; default: if(!$this->show_default()) $this->show_category(); break; case 'category': $this->show_category($category); break; case 'checkout2': if(!$this->show_checkout2()) $this->show_checkout(); break; case 'checkout': $this->show_checkout(); break; case 'pay': $this->pay(); break; case 'completed': $this->show_completed(); break; case 'cancelled': $this->show_cancelled(); break; case 'paypalverify': $this->verify_paypal(); break; } if($this->config->displayaspage) $this->page_footer(); } function outlog($s = '') { if($this->enable_logging) { $log = fopen(dirname(__FILE__) .'/outlog.txt', 'a'); fwrite($log, "\nTransaction @ ".date('Y-m-d h:i:s A')."\nResult:$s\n"); foreach($_POST as $key => $value) { fwrite($log, "$key := $value\n"); } fclose($log); //echo "logged $s"; } } function linkasbutton($url, $text, $echo = false) { return "
"; } function sendinvoice($trans, $paymentstate = 0, $emailto = '') { $qry = "SELECT * FROM {$this->config->table_prefix}orders WHERE order_trans_ID = '{$trans}' LIMIT 1"; $order = $this->db->get_row($qry); $t = new microtemplate($this->templates['order_email']); $t->set_field('shop_name', $this->config->shopname); $t->set_field('order', $order->order_order); $t->set_field('name', $order->order_name); $t->set_field('address', implode("\n ", explode("\n", $order->order_address))); $t->set_field('email', $order->order_email); $t->set_field('IP', $order->order_IP); $t->set_field('phone', $order->order_phone); $t->set_field('trans_ID', $order->order_trans_ID); $t->set_field('subtotal', number_format($order->order_cost,2)); $t->set_field('shipping', number_format($order->order_shipping,2)); $t->set_field('total', number_format($order->order_cost + $order->order_shipping, 2)); $t->set_field('payment_location', implode("\n ", explode("\n", $this->config->payment_location))); $t->set_field('currency', $this->currency_to_symbol()); switch($paymentstate) { case 0: $t->set_field('send_payment', true); break; case 1: $t->set_field('verify_payment', true); break; case 2: $t->set_field('order_shipping', true); break; } $msg = $t->render(); $email = $order->order_email; if($emailto != '') $email = $emailto; $headers = "From: {$this->config->shopname}<{$this->config->paypal_account}>"; mail($email, "Your purchase from {$this->config->shopname}", $msg, $headers); if($this->config->ccinvoice) { $msg = "This is a copy of an invoice sent to <{$order->order_email}>.\n\n{$msg}"; mail($this->config->paypal_account, "Purchase made from {$this->config->shopname}", $msg, $headers); } } function get_templates() { $this->templates['item_row'] = '
From:
In Stock
Out of Stock
[Edit this item]
[Toggle stock status]
[Delete this item]
Price:
Quantity:
You have in your shopping cart. Sorry, this item is out of stock.
'; $this->templates['order_email'] = 'Thank you for placing an order with ! Your order details follow. --------------------------------- Name: Address: Email: Phone: Trans#: --------------------------------- Items Ordered: --------------------------------- Subtotal: Shipping: TOTAL: Please send payment in the amount of $ with a copy of this invoice to: Your order will ship as soon as payment has been verified. We have received your payment and your order will ship shortly! Thank you for your business! '; } } if(!defined('ABSPATH')) { $shop = new Microshop(); $shop->render(); }