/blog/wp-content/plugins/shopp/core/Flow.php
PHP | 3010 lines | 2752 code | 198 blank | 60 comment | 225 complexity | 788fee78bad25f76bd4558933fed0612 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Flow handlers
- * Main flow handling for all request processing/handling
- *
- * @author Jonathan Davis
- * @version 1.0
- * @copyright Ingenesis Limited, 2 April, 2008
- * @package Shopp
- **/
- class Flow {
- var $Admin;
- var $Settings;
- var $basepath;
- var $baseuri;
- var $secureuri;
-
- function Flow (&$Core) {
- global $wp_version;
- $this->Settings = $Core->Settings;
- $this->Cart = $Core->Cart;
- $langpath = array(PLUGINDIR,$Core->directory,'lang');
- load_plugin_textdomain('Shopp',join(DIRECTORY_SEPARATOR,$langpath));
- $this->basepath = dirname(dirname(__FILE__));
- $this->uri = ((!empty($_SERVER['HTTPS']))?"https://":"http://").
- $_SERVER['SERVER_NAME'].str_replace("?".$_SERVER['QUERY_STRING'],"",$_SERVER['REQUEST_URI']);
- $this->secureuri = 'https://'.$_SERVER['SERVER_NAME'].$this->uri;
-
- $this->Admin = new stdClass();
- $this->Admin->orders = $Core->directory."-orders";
- $this->Admin->customers = $Core->directory."-customers";
- $this->Admin->editcustomer = $Core->directory."-customers-edit";
- $this->Admin->categories = $Core->directory."-categories";
- $this->Admin->editcategory = $Core->directory."-categories-edit";
- $this->Admin->products = $Core->directory."-products";
- $this->Admin->editproduct = $Core->directory."-products-edit";
- $this->Admin->promotions = $Core->directory."-promotions";
- $this->Admin->editpromo = $Core->directory."-promotions-edit";
- $this->Admin->settings = array(
- 'settings' => array($Core->directory."-settings",__('General','Shopp')),
- 'checkout' => array($Core->directory."-settings-checkout",__('Checkout','Shopp')),
- 'payments' => array($Core->directory."-settings-payments",__('Payments','Shopp')),
- 'shipping' => array($Core->directory."-settings-shipping",__('Shipping','Shopp')),
- 'taxes' => array($Core->directory."-settings-taxes",__('Taxes','Shopp')),
- 'presentation' => array($Core->directory."-settings-presentation",__('Presentation','Shopp')),
- 'system' => array($Core->directory."-settings-system",__('System','Shopp')),
- 'update' => array($Core->directory."-settings-update",__('Update','Shopp'))
- );
- $this->Admin->help = $Core->directory."-help";
- $this->Admin->welcome = $Core->directory."-welcome";
- $this->Admin->default = $this->Admin->orders;
-
- $this->Pages = $Core->Settings->get('pages');
- if (empty($this->Pages)) {
- $this->Pages = array();
- $this->Pages['catalog'] = array('name'=>'shop','title'=>'Shop','content'=>'[catalog]');
- $this->Pages['cart'] = array('name'=>'cart','title'=>'Cart','content'=>'[cart]');
- $this->Pages['checkout'] = array('name'=>'checkout','title'=>'Checkout','content'=>'[checkout]');
- $this->Pages['account'] = array('name'=>'account','title'=>'Your Orders','content'=>'[account]');
- }
- $this->Docs = array(
- 'orders' => 'Managing Orders',
- 'customers' => 'Managing Customers',
- 'promotions' => 'Running Sales & Promotions',
- 'editpromos' => 'Running Sales & Promotions',
- 'products' => 'Editing a Product',
- 'editproducts' => 'Editing a Product',
- 'categories' => 'Editing a Category',
- 'editcategory' => 'Editing a Category',
- 'settings' => 'General Settings',
- 'checkout' => 'Checkout Settings',
- 'payments' => 'Payments Settings',
- 'shipping' => 'Shipping Settings',
- 'taxes' => 'Taxes Settings',
- 'presentation' => 'Presentation Settings',
- 'system' => 'System Settings',
- 'update' => 'Update Settings'
- );
-
- $this->coremods = array("GoogleCheckout.php", "PayPalExpress.php",
- "TestMode.php", "FlatRates.php", "ItemQuantity.php",
- "OrderAmount.php", "OrderWeight.php");
- if (!defined('BR')) define('BR','<br />');
- // Overrideable macros
- if (!defined('SHOPP_USERLEVEL')) define('SHOPP_USERLEVEL',8);
- if (!defined('SHOPP_NOSSL')) define('SHOPP_NOSSL',false);
- if (!defined('SHOPP_PREPAYMENT_DOWNLOADS')) define('SHOPP_PREPAYMENT_DOWNLOADS',false);
- if (!defined('SHOPP_SESSION_TIMEOUT')) define('SHOPP_SESSION_TIMEOUT',7200);
- if (!defined('SHOPP_QUERY_DEBUG')) define('SHOPP_QUERY_DEBUG',false);
-
- define("SHOPP_WP27",(!version_compare($wp_version,"2.7","<")));
- define("SHOPP_DEBUG",($Core->Settings->get('error_logging') == 2048));
- define("SHOPP_PATH",$this->basepath);
- define("SHOPP_ADMINPATH",SHOPP_PATH."/core/ui");
- define("SHOPP_PLUGINURI",$Core->uri);
- define("SHOPP_DBSCHEMA",SHOPP_PATH."/core/model/schema.sql");
- define("SHOPP_TEMPLATES",($Core->Settings->get('theme_templates') != "off" &&
- is_dir($Core->Settings->get('theme_templates')))?
- $Core->Settings->get('theme_templates'):
- SHOPP_PATH.DIRECTORY_SEPARATOR."templates");
- define("SHOPP_TEMPLATES_URI",($Core->Settings->get('theme_templates') != "off" &&
- is_dir($Core->Settings->get('theme_templates')))?
- get_bloginfo('stylesheet_directory')."/shopp":
- $Core->uri."/templates");
- define("SHOPP_GATEWAYS",SHOPP_PATH.DIRECTORY_SEPARATOR."gateways".DIRECTORY_SEPARATOR);
- define("SHOPP_PERMALINKS",(get_option('permalink_structure') == "")?false:true);
-
- define("SHOPP_LOOKUP",(strpos($_SERVER['REQUEST_URI'],"images/") !== false ||
- strpos($_SERVER['REQUEST_URI'],"lookup=") !== false)?true:false);
- $this->uploadErrors = array(
- UPLOAD_ERR_INI_SIZE => __('The uploaded file exceeds the upload_max_filesize directive in PHP\'s configuration file','Shopp'),
- UPLOAD_ERR_FORM_SIZE => __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.','Shopp'),
- UPLOAD_ERR_PARTIAL => __('The uploaded file was only partially uploaded.','Shopp'),
- UPLOAD_ERR_NO_FILE => __('No file was uploaded.','Shopp'),
- UPLOAD_ERR_NO_TMP_DIR => __('The server\'s temporary folder is missing.','Shopp'),
- UPLOAD_ERR_CANT_WRITE => __('Failed to write the file to disk.','Shopp'),
- UPLOAD_ERR_EXTENSION => __('File upload stopped by extension.','Shopp'),
- );
- }
- function admin () {
- global $Shopp;
- $db =& DB::get();
- if (!defined('WP_ADMIN') || !isset($_GET['page'])) return;
- $Admin = $Shopp->Flow->Admin;
- $adminurl = $Shopp->wpadminurl."admin.php";
-
- $defaults = array(
- 'page' => false,
- 'deleting' => false,
- 'delete' => false,
- 'id' => false,
- 'save' => false,
- 'duplicate' => false,
- 'next' => false
- );
- $args = array_merge($defaults,$_REQUEST);
- extract($args,EXTR_SKIP);
- if (strstr($page,$Admin->categories)) {
-
- if ($page == "shopp-categories"
- && !empty($deleting)
- && !empty($delete)
- && is_array($delete)) {
- foreach($delete as $deletion) {
- $Category = new Category($deletion);
- $db->query("UPDATE $Category->_table SET parent=0 WHERE parent=$Category->id");
- $Category->delete();
- }
- $redirect = esc_url(add_query_arg(array_merge($_GET,array('delete[]'=>null,'deleting'=>null)),$adminurl));
- shopp_redirect($redirect);
- }
-
- if ($id && $id != "new")
- $Shopp->Category = new Category($id);
- else $Shopp->Category = new Category();
-
- if ($save) {
- $this->save_category($Shopp->Category);
- $this->Notice = '<strong>'.stripslashes($Shopp->Category->name).'</strong> '.__('has been saved.','Shopp');
- if ($next) {
- if ($next != "new")
- $Shopp->Category = new Category($next);
- else $Shopp->Category = new Category();
- } else {
- if (empty($id)) $id = $Shopp->Category->id;
- $Shopp->Category = new Category($id);
- }
-
- }
-
- } // end $Admin->categories
- if (strstr($page,$Admin->products)) {
- if ($page == "shopp-products"
- && !empty($deleting)
- && !empty($delete)
- && is_array($delete)) {
- foreach($delete as $deletion) {
- $Product = new Product($deletion);
- $Product->delete();
- }
- $redirect = esc_url(add_query_arg(array_merge($_GET,array('delete'=>null,'deleting'=>null)),$adminurl));
- shopp_redirect($redirect);
- exit();
- }
-
- if ($duplicate) {
- $Product = new Product();
- $Product->load($duplicate);
- $Product->duplicate();
- shopp_redirect(add_query_arg('page',$Admin->products,$adminurl));
- }
- if ($id && $id != "new") {
- $Shopp->Product = new Product($id);
- $Shopp->Product->load_data(array('prices','specs','categories','tags'));
- } else {
- $Shopp->Product = new Product();
- $Shopp->Product->published = "on";
- }
-
- if ($save) {
- $this->save_product($Shopp->Product);
- $this->Notice = '<strong>'.stripslashes($Shopp->Product->name).'</strong> '.__('has been saved.','Shopp');
-
- if ($next) {
- if ($next == "new") {
- $Shopp->Product = new Product();
- $Shopp->Product->published = "on";
- } else {
- $Shopp->Product = new Product($next);
- $Shopp->Product->load_data(array('prices','specs','categories','tags'));
- }
- } else {
- if (empty($id)) $id = $Shopp->Product->id;
- $Shopp->Product = new Product($id);
- $Shopp->Product->load_data(array('prices','specs','categories','tags'));
- }
- }
- } // end $Admin->products
-
- }
- function helpdoc ($menu,$page) {
- if (!isset($this->Docs[$menu])) return;
- $url = SHOPP_DOCS.str_replace("+","_",urlencode($this->Docs[$menu]));
- $link = htmlspecialchars($this->Docs[$menu]);
- $content = '<a href="'.$url.'" target="_blank">'.$link.'</a>';
- if ($menu == "orders" || $menu == "customers") {
- ob_start();
- include("{$this->basepath}/core/ui/help/$menu.php");
- $help = ob_get_contents();
- ob_end_clean();
- $content .= $help;
- }
-
- add_contextual_help($page,$content);
- }
- /**
- * Catalog flow handlers
- **/
- function catalog () {
- global $Shopp;
-
- if (SHOPP_DEBUG) new ShoppError('Displaying catalog page request: '.$_SERVER['REQUEST_URI'],'shopp_catalog',SHOPP_DEBUG_ERR);
-
- ob_start();
- switch ($Shopp->Catalog->type) {
- case "product":
- if (file_exists(SHOPP_TEMPLATES."/product-{$Shopp->Product->id}.php"))
- include(SHOPP_TEMPLATES."/product-{$Shopp->Product->id}.php");
- else include(SHOPP_TEMPLATES."/product.php"); break;
- case "category":
- if (isset($Shopp->Category->smart) &&
- file_exists(SHOPP_TEMPLATES."/category-{$Shopp->Category->slug}.php"))
- include(SHOPP_TEMPLATES."/category-{$Shopp->Category->slug}.php");
- elseif (isset($Shopp->Category->id) &&
- file_exists(SHOPP_TEMPLATES."/category-{$Shopp->Category->id}.php"))
- include(SHOPP_TEMPLATES."/category-{$Shopp->Category->id}.php");
- else include(SHOPP_TEMPLATES."/category.php"); break;
- default: include(SHOPP_TEMPLATES."/catalog.php"); break;
- }
- $content = ob_get_contents();
- ob_end_clean();
-
- $classes = $Shopp->Catalog->type;
- if (!isset($_COOKIE['shopp_catalog_view'])) {
- // No cookie preference exists, use shopp default setting
- $view = $Shopp->Settings->get('default_catalog_view');
- if ($view == "list") $classes .= " list";
- if ($view == "grid") $classes .= " grid";
- } else {
- if ($_COOKIE['shopp_catalog_view'] == "list") $classes .= " list";
- if ($_COOKIE['shopp_catalog_view'] == "grid") $classes .= " grid";
- }
-
- return apply_filters('shopp_catalog','<div id="shopp" class="'.$classes.'">'.$content.'<div class="clear"></div></div>');
- }
-
- /**
- * Shopping Cart flow handlers
- **/
- function cart ($attrs=array()) {
- $Cart = $this->Cart;
- ob_start();
- include(SHOPP_TEMPLATES."/cart.php");
- $content = ob_get_contents();
- ob_end_clean();
- return apply_filters('shopp_cart_template','<div id="shopp">'.$content.'</div>');
- }
- function shipping_estimate ($attrs) {
- $Cart = $this->Cart;
- ob_start();
- include(SHOPP_TEMPLATES."/shipping.php");
- $content = ob_get_contents();
- ob_end_clean();
- return $content;
- }
-
- /**
- * Checkout flow handlers
- **/
- function checkout () {
- global $Shopp;
- $Cart = $Shopp->Cart;
- $process = get_query_var('shopp_proc');
- $xco = get_query_var('shopp_xco');
- if (!empty($xco)) {
- $Shopp->gateway($xco);
- $Shopp->Gateway->actions();
- }
- switch ($process) {
- case "confirm-order": $content = $this->order_confirmation(); break;
- case "receipt": $content = $this->order_receipt(); break;
- default:
- ob_start();
- if ($Cart->data->Errors->exist(SHOPP_COMM_ERR)) {
- include(SHOPP_TEMPLATES."/errors.php");
- $Cart->data->Errors->reset();
- }
- if (!empty($xco)) {
-
- if (!empty($Shopp->Gateway)) {
- if ($Shopp->Gateway->checkout) include(SHOPP_TEMPLATES."/checkout.php");
- else {
- if ($Cart->data->Errors->exist(SHOPP_COMM_ERR))
- include(SHOPP_TEMPLATES."/errors.php");
- include(SHOPP_TEMPLATES."/summary.php");
- echo $Shopp->Gateway->tag('button');
- }
- } else include(SHOPP_TEMPLATES."/summary.php");
-
- } else include(SHOPP_TEMPLATES."/checkout.php");
- $content = ob_get_contents();
- ob_end_clean();
- unset($Cart->data->OrderError);
- }
-
- // Wrap with #shopp if not already wrapped
- if (strpos($content,'<div id="shopp">') === false)
- $content = '<div id="shopp">'.$content.'</div>';
-
- return apply_filters('shopp_checkout',$content);
- }
-
- function checkout_order_summary () {
- global $Shopp;
- $Cart = $Shopp->Cart;
- ob_start();
- include(SHOPP_TEMPLATES."/summary.php");
- $content = ob_get_contents();
- ob_end_clean();
-
- return apply_filters('shopp_order_summary',$content);
- }
-
- function secure_page_links ($linklist) {
- global $Shopp;
- $gateway = $Shopp->Settings->get('payment_gateway');
- if (strpos($gateway,"TestMode.php") !== false) return $linklist;
- $hrefs = array(
- 'checkout' => $Shopp->link('checkout'),
- 'account' => $Shopp->link('account')
- );
- if (empty($gateway)) return str_replace($hrefs['checkout'],$Shopp->link('cart'),$linklist);
- foreach ($hrefs as $href) {
- $secure_href = str_replace("http://","https://",$href);
- $linklist = str_replace($href,$secure_href,$linklist);
- }
- return $linklist;
- }
-
- /**
- * order()
- * Processes orders by passing transaction information to the active
- * payment gateway */
- function order ($gateway = false) {
- global $Shopp;
- $Cart = $Shopp->Cart;
- $db = DB::get();
-
- do_action('shopp_order_preprocessing');
- $Order = $Shopp->Cart->data->Order;
- $Order->Totals = $Shopp->Cart->data->Totals;
- $Order->Items = $Shopp->Cart->contents;
- $Order->Cart = $Shopp->Cart->session;
-
- if ($Shopp->Gateway && !$Cart->orderisfree()) {
- // Use an external checkout payment gateway
- if (SHOPP_DEBUG) new ShoppError('Processing order through a remote-payment gateway service.',false,SHOPP_DEBUG_ERR);
- $Purchase = $Shopp->Gateway->process();
- if (!$Purchase) {
- if (SHOPP_DEBUG) new ShoppError('The remote-payment gateway encountered an error.',false,SHOPP_DEBUG_ERR);
- $Shopp->Gateway->error();
- return false;
- }
- if (SHOPP_DEBUG) new ShoppError('Transaction successfully processed by remote-payment gateway service.',false,SHOPP_DEBUG_ERR);
- } else {
- // Use local payment gateway set in payment settings
-
- $gateway = $Shopp->Settings->get('payment_gateway');
-
- // Process a transaction if the order has a cost (is not free)
- if (!$Cart->orderisfree()) {
- if (!$Shopp->gateway($gateway)) return false;
- // Process the transaction through the payment gateway
- if (SHOPP_DEBUG) new ShoppError('Processing order through local-payment gateway service.',false,SHOPP_DEBUG_ERR);
- $processed = $Shopp->Gateway->process();
- // exit();
- // There was a problem processing the transaction,
- // grab the error response from the gateway so we can report it
- if (!$processed) {
- if (SHOPP_DEBUG) new ShoppError('The local-payment gateway encountered an error.',false,SHOPP_DEBUG_ERR);
- $Shopp->Gateway->error();
- return false;
- }
- $gatewaymeta = $this->scan_gateway_meta(SHOPP_GATEWAYS.$gateway);
- $gatewayname = $gatewaymeta->name;
- $transactionid = $Shopp->Gateway->transactionid();
-
- if (SHOPP_DEBUG) new ShoppError('Transaction '.$transactionid.' successfully processed by local-payment gateway service '.$gatewayname.'.',false,SHOPP_DEBUG_ERR);
-
- } else {
- if(!$Cart->validorder()){
- new ShoppError(__('There is not enough customer information to process the order.','Shopp'),'invalid_order',SHOPP_TRXN_ERR);
- return false;
- }
- $gatewayname = __('N/A','Shopp');
- $transactionid = __('(Free Order)','Shopp');
- }
- $authentication = $Shopp->Settings->get('account_system');
- // Transaction successful, save the order
- if ($authentication == "wordpress") {
- // Check if they've logged in
- // If the shopper is already logged-in, save their updated customer info
- if ($Shopp->Cart->data->login) {
- if (SHOPP_DEBUG) new ShoppError('Customer logged in, linking Shopp customer account to existing WordPress account.',false,SHOPP_DEBUG_ERR);
- get_currentuserinfo();
- global $user_ID;
- $Order->Customer->wpuser = $user_ID;
- }
-
- // Create WordPress account (if necessary)
- if (!$Order->Customer->wpuser) {
- if (SHOPP_DEBUG) new ShoppError('Creating a new WordPress account for this customer.',false,SHOPP_DEBUG_ERR);
- if(!$Order->Customer->new_wpuser()) new ShoppError(__('Account creation failed on order for customer id:' . $Order->Customer->id, "Shopp"), false,SHOPP_TRXN_ERR);
- }
- }
- // Create a WP-compatible password hash to go in the db
- if (empty($Order->Customer->id))
- $Order->Customer->password = wp_hash_password($Order->Customer->password);
- $Order->Customer->save();
- $Order->Billing->customer = $Order->Customer->id;
- $Order->Billing->card = substr($Order->Billing->card,-4);
- $Order->Billing->save();
- // Card data is truncated, switch the cart to normal mode
- if ($Shopp->Cart->secured() && is_shopp_secure())
- $Shopp->Cart->secured(false);
- if (!empty($Order->Shipping->address)) {
- $Order->Shipping->customer = $Order->Customer->id;
- $Order->Shipping->save();
- }
-
- $Promos = array();
- foreach ($Shopp->Cart->data->PromosApplied as $promo)
- $Promos[$promo->id] = $promo->name;
- if ($Shopp->Cart->orderisfree()) $orderisfree = true;
- else $orderisfree = false;
- $Purchase = new Purchase();
- $Purchase->customer = $Order->Customer->id;
- $Purchase->billing = $Order->Billing->id;
- $Purchase->shipping = $Order->Shipping->id;
- $Purchase->copydata($Order->Customer);
- $Purchase->copydata($Order->Billing);
- $Purchase->copydata($Order->Shipping,'ship');
- $Purchase->copydata($Shopp->Cart->data->Totals);
- $Purchase->data = $Order->data;
- $Purchase->promos = $Promos;
- $Purchase->freight = $Shopp->Cart->data->Totals->shipping;
- $Purchase->gateway = $gatewayname;
- $Purchase->transactionid = $transactionid;
- $Purchase->transtatus = "CHARGED";
- $Purchase->ip = $Shopp->Cart->ip;
- $Purchase->save();
- // echo "<pre>"; print_r($Purchase); echo "</pre>";
- foreach($Shopp->Cart->contents as $Item) {
- $Purchased = new Purchased();
- $Purchased->copydata($Item);
- $Purchased->purchase = $Purchase->id;
- if (!empty($Purchased->download)) $Purchased->keygen();
- $Purchased->save();
- if ($Item->inventory) $Item->unstock();
- }
- if (SHOPP_DEBUG) new ShoppError('Purchase '.$Purchase->id.' was successfully saved to the database.',false,SHOPP_DEBUG_ERR);
- }
-
- // Skip post order if no Purchase ID exists
- if (empty($Purchase->id)) return true;
- // Empty cart on successful order
- $Shopp->Cart->unload();
- session_destroy();
-
- // Start new cart session
- $Shopp->Cart = new Cart();
- session_start();
-
- // Keep the user logged in or log them in if they are a new customer
- if ($Shopp->Cart->data->login || $authentication != "none")
- $Shopp->Cart->loggedin($Order->Customer);
-
- // Save the purchase ID for later lookup
- $Shopp->Cart->data->Purchase = new Purchase($Purchase->id);
- $Shopp->Cart->data->Purchase->load_purchased();
- // // $Shopp->Cart->save();
-
- // Allow other WordPress plugins access to Purchase data to extend
- // what Shopp does after a successful transaction
- do_action_ref_array('shopp_order_success',array(&$Shopp->Cart->data->Purchase));
-
- // Send email notifications
- // notification(addressee name, email, subject, email template, receipt template)
- $Purchase->notification(
- "$Purchase->firstname $Purchase->lastname",
- $Purchase->email,
- __('Order Receipt','Shopp')
- );
- if ($Shopp->Settings->get('receipt_copy') == 1) {
- $Purchase->notification(
- '',
- $Shopp->Settings->get('merchant_email'),
- __('New Order','Shopp')
- );
- }
- $ssl = true;
- // Test Mode will not require encrypted checkout
- if (strpos($gateway,"TestMode.php") !== false
- || isset($_GET['shopp_xco'])
- || $orderisfree
- || SHOPP_NOSSL)
- $ssl = false;
- shopp_redirect($Shopp->link('receipt',$ssl));
- }
-
- // Display the confirm order screen
- function order_confirmation () {
- global $Shopp;
- $Cart = $Shopp->Cart;
-
- ob_start();
- include(SHOPP_TEMPLATES."/confirm.php");
- $content = ob_get_contents();
- ob_end_clean();
- return apply_filters('shopp_order_confirmation','<div id="shopp">'.$content.'</div>');
- }
- // Display a sales receipt
- function order_receipt ($template="receipt.php") {
- global $Shopp;
- $Cart = $Shopp->Cart;
-
- ob_start();
- include(trailingslashit(SHOPP_TEMPLATES).$template);
- $content = ob_get_contents();
- ob_end_clean();
- return apply_filters('shopp_order_receipt','<div id="shopp">'.$content.'</div>');
- }
-
- // Display an error page
- function error_page ($template="errors.php") {
- global $Shopp;
- $Cart = $Shopp->Cart;
-
- ob_start();
- include(trailingslashit(SHOPP_TEMPLATES).$template);
- $content = ob_get_contents();
- ob_end_clean();
- return apply_filters('shopp_errors_page','<div id="shopp">'.$content.'</div>');
- }
-
- /**
- * Orders admin flow handlers
- */
- function orders_list() {
- global $Shopp,$Orders;
- $db = DB::get();
-
- $defaults = array(
- 'page' => false,
- 'deleting' => false,
- 'selected' => false,
- 'update' => false,
- 'newstatus' => false,
- 'pagenum' => 1,
- 'per_page' => false,
- 'start' => '',
- 'end' => '',
- 'status' => false,
- 's' => '',
- 'range' => '',
- 'startdate' => '',
- 'enddate' => '',
- );
-
- $args = array_merge($defaults,$_GET);
- extract($args, EXTR_SKIP);
-
- if ( !current_user_can(SHOPP_USERLEVEL) )
- wp_die(__('You do not have sufficient permissions to access this page.','Shopp'));
- if ($page == "shopp-orders"
- && !empty($deleting)
- && !empty($selected)
- && is_array($selected)) {
- foreach($selected as $selection) {
- $Purchase = new Purchase($selection);
- $Purchase->load_purchased();
- foreach ($Purchase->purchased as $purchased) {
- $Purchased = new Purchased($purchased->id);
- $Purchased->delete();
- }
- $Purchase->delete();
- }
- }
- $statusLabels = $this->Settings->get('order_status');
- if (empty($statusLabels)) $statusLabels = array('');
- $txnStatusLabels = array(
- 'PENDING' => __('Pending','Shopp'),
- 'CHARGED' => __('Charged','Shopp'),
- 'REFUNDED' => __('Refunded','Shopp'),
- 'VOID' => __('Void','Shopp')
- );
- if ($update == "order"
- && !empty($selected)
- && is_array($selected)) {
- foreach($selected as $selection) {
- $Purchase = new Purchase($selection);
- $Purchase->status = $newstatus;
- $Purchase->save();
- }
- }
- $Purchase = new Purchase();
-
- if (!empty($start)) {
- $startdate = $start;
- list($month,$day,$year) = explode("/",$startdate);
- $starts = mktime(0,0,0,$month,$day,$year);
- }
- if (!empty($end)) {
- $enddate = $end;
- list($month,$day,$year) = explode("/",$enddate);
- $ends = mktime(23,59,59,$month,$day,$year);
- }
- $pagenum = absint( $pagenum );
- if ( empty($pagenum) )
- $pagenum = 1;
- if( !$per_page || $per_page < 0 )
- $per_page = 20;
- $start = ($per_page * ($pagenum-1));
-
- $where = '';
- if (!empty($status) || $status === '0') $where = "WHERE status='$status'";
-
- if (!empty($s)) {
- $s = stripslashes($s);
- if (preg_match_all('/(\w+?)\:(?="(.+?)"|(.+?)\b)/',$s,$props,PREG_SET_ORDER) > 0) {
- foreach ($props as $search) {
- $keyword = !empty($search[2])?$search[2]:$search[3];
- switch(strtolower($search[1])) {
- case "txn": $where .= (empty($where)?"WHERE ":" AND ")."transactionid='$keyword'"; break;
- case "gateway": $where .= (empty($where)?"WHERE ":" AND ")."gateway LIKE '%$keyword%'"; break;
- case "cardtype": $where .= ((empty($where))?"WHERE ":" AND ")."cardtype LIKE '%$keyword%'"; break;
- case "address": $where .= ((empty($where))?"WHERE ":" AND ")."(address LIKE '%$keyword%' OR xaddress='%$keyword%')"; break;
- case "city": $where .= ((empty($where))?"WHERE ":" AND ")."city LIKE '%$keyword%'"; break;
- case "province":
- case "state": $where .= ((empty($where))?"WHERE ":" AND ")."state='$keyword'"; break;
- case "zip":
- case "zipcode":
- case "postcode": $where .= ((empty($where))?"WHERE ":" AND ")."postcode='$keyword'"; break;
- case "country": $where .= ((empty($where))?"WHERE ":" AND ")."country='$keyword'"; break;
- }
- }
- if (empty($where)) $where .= ((empty($where))?"WHERE ":" AND ")." (id='$s' OR CONCAT(firstname,' ',lastname) LIKE '%$s%')";
- } elseif (strpos($s,'@') !== false) {
- $where .= ((empty($where))?"WHERE ":" AND ")." email='$s'";
- } else $where .= ((empty($where))?"WHERE ":" AND ")." (id='$s' OR CONCAT(firstname,' ',lastname) LIKE '%$s%')";
- }
- if (!empty($starts) && !empty($ends)) $where .= ((empty($where))?"WHERE ":" AND ").' (UNIX_TIMESTAMP(created) >= '.$starts.' AND UNIX_TIMESTAMP(created) <= '.$ends.')';
- $ordercount = $db->query("SELECT count(*) as total,SUM(total) AS sales,AVG(total) AS avgsale FROM $Purchase->_table $where ORDER BY created DESC");
- $query = "SELECT * FROM $Purchase->_table $where ORDER BY created DESC LIMIT $start,$per_page";
- $Orders = $db->query($query,AS_ARRAY);
- $num_pages = ceil($ordercount->total / $per_page);
- $page_links = paginate_links( array(
- 'base' => add_query_arg( 'pagenum', '%#%' ),
- 'format' => '',
- 'total' => $num_pages,
- 'current' => $pagenum
- ));
-
- $ranges = array(
- 'all' => __('Show All Orders','Shopp'),
- 'today' => __('Today','Shopp'),
- 'week' => __('This Week','Shopp'),
- 'month' => __('This Month','Shopp'),
- 'quarter' => __('This Quarter','Shopp'),
- 'year' => __('This Year','Shopp'),
- 'yesterday' => __('Yesterday','Shopp'),
- 'lastweek' => __('Last Week','Shopp'),
- 'last30' => __('Last 30 Days','Shopp'),
- 'last90' => __('Last 3 Months','Shopp'),
- 'lastmonth' => __('Last Month','Shopp'),
- 'lastquarter' => __('Last Quarter','Shopp'),
- 'lastyear' => __('Last Year','Shopp'),
- 'lastexport' => __('Last Export','Shopp'),
- 'custom' => __('Custom Dates','Shopp')
- );
-
- $exports = array(
- 'tab' => __('Tab-separated.txt','Shopp'),
- 'csv' => __('Comma-separated.csv','Shopp'),
- 'xls' => __('Microsoft® Excel.xls','Shopp'),
- 'iif' => __('Intuit® QuickBooks.iif','Shopp')
- );
-
- $formatPref = $Shopp->Settings->get('purchaselog_format');
- if (!$formatPref) $formatPref = 'tab';
-
- $columns = array_merge(Purchase::exportcolumns(),Purchased::exportcolumns());
- $selected = $Shopp->Settings->get('purchaselog_columns');
- if (empty($selected)) $selected = array_keys($columns);
-
- include("{$this->basepath}/core/ui/orders/orders.php");
- }
-
- function orders_list_columns () {
- shopp_register_column_headers('toplevel_page_shopp-orders', array(
- 'cb'=>'<input type="checkbox" />',
- 'order'=>__('Order','Shopp'),
- 'name'=>__('Name','Shopp'),
- 'destination'=>__('Destination','Shopp'),
- 'total'=>__('Total','Shopp'),
- 'txn'=>__('Transaction','Shopp'),
- 'date'=>__('Date','Shopp'))
- );
- }
-
- function order_manager () {
- global $Shopp;
- global $is_IIS;
- if ( !current_user_can(SHOPP_USERLEVEL) )
- wp_die(__('You do not have sufficient permissions to access this page.','Shopp'));
- if (preg_match("/\d+/",$_GET['id'])) {
- $Shopp->Cart->data->Purchase = new Purchase($_GET['id']);
- $Shopp->Cart->data->Purchase->load_purchased();
- } else $Shopp->Cart->data->Purchase = new Purchase();
-
- $Purchase = $Shopp->Cart->data->Purchase;
- $Customer = new Customer($Purchase->customer);
-
- if (!empty($_POST['update'])) {
- check_admin_referer('shopp-save-order');
-
- if ($_POST['transtatus'] != $Purchase->transtatus)
- do_action_ref_array('shopp_order_txnstatus_update',array(&$_POST['transtatus'],&$Purchase));
-
- $Purchase->updates($_POST);
- if ($_POST['notify'] == "yes") {
- $labels = $this->Settings->get('order_status');
-
- // Send the e-mail notification
- $notification = array();
- $notification['from'] = $Shopp->Settings->get('merchant_email');
- if($is_IIS) $notification['to'] = $Purchase->email;
- else $notification['to'] = "\"{$Purchase->firstname} {$Purchase->lastname}\" <{$Purchase->email}>";
- $notification['subject'] = __('Order Updated','Shopp');
- $notification['url'] = get_bloginfo('siteurl');
- $notification['sitename'] = get_bloginfo('name');
- if ($_POST['receipt'] == "yes")
- $notification['receipt'] = $this->order_receipt();
- $notification['status'] = strtoupper($labels[$Purchase->status]);
- $notification['message'] = wpautop($_POST['message']);
- shopp_email(SHOPP_TEMPLATES."/notification.html",$notification);
-
- }
-
- $Purchase->save();
- $updated = __('Order status updated.','Shopp');
- }
- $targets = $this->Settings->get('target_markets');
- $txnStatusLabels = array(
- 'PENDING' => __('Pending','Shopp'),
- 'CHARGED' => __('Charged','Shopp'),
- 'REFUNDED' => __('Refunded','Shopp'),
- 'VOID' => __('Void','Shopp')
- );
-
- $statusLabels = $this->Settings->get('order_status');
- if (empty($statusLabels)) $statusLabels = array('');
-
-
- $taxrate = 0;
- $base = $Shopp->Settings->get('base_operations');
- if ($base['vat']) $taxrate = $Shopp->Cart->taxrate();
-
-
- include("{$this->basepath}/core/ui/orders/order.php");
- }
-
- function order_status_counts () {
- $db = DB::get();
-
- $purchase_table = DatabaseObject::tablename(Purchase::$table);
- $labels = $this->Settings->get('order_status');
-
- if (empty($labels)) return false;
- $r = $db->query("SELECT status,COUNT(status) AS total FROM $purchase_table GROUP BY status ORDER BY status ASC",AS_ARRAY);
- $status = array();
- foreach ($r as $count) $status[$count->status] = $count->total;
- foreach ($labels as $id => $label) if (empty($status[$id])) $status[$id] = 0;
- return $status;
- }
-
- function account () {
- global $Shopp,$wp;
-
- if ($Shopp->Cart->data->login
- && isset($Shopp->Cart->data->Order->Customer))
- $Shopp->Cart->data->Order->Customer->management();
-
- if (isset($_GET['acct']) && $_GET['acct'] == "rp") $Shopp->Cart->data->Order->Customer->reset_password($_GET['key']);
- if (isset($_POST['recover-login'])) $Shopp->Cart->data->Order->Customer->recovery();
-
- ob_start();
- if (isset($wp->query_vars['shopp_download'])) include(SHOPP_TEMPLATES."/errors.php");
- elseif ($Shopp->Cart->data->login) include(SHOPP_TEMPLATES."/account.php");
- else include(SHOPP_TEMPLATES."/login.php");
- $content = ob_get_contents();
- ob_end_clean();
-
- return apply_filters('shopp_account_template','<div id="shopp">'.$content.'</div>');
-
- }
-
- function customers_list () {
- global $Shopp,$Customers,$wpdb;
- $db = DB::get();
-
- $defaults = array(
- 'page' => false,
- 'deleting' => false,
- 'selected' => false,
- 'update' => false,
- 'newstatus' => false,
- 'pagenum' => 1,
- 'per_page' => false,
- 'start' => '',
- 'end' => '',
- 'status' => false,
- 's' => '',
- 'range' => '',
- 'startdate' => '',
- 'enddate' => '',
- );
-
- $args = array_merge($defaults,$_GET);
- extract($args, EXTR_SKIP);
-
- if ($page == "shopp-customers"
- && !empty($deleting)
- && !empty($selected)
- && is_array($selected)) {
- foreach($selected as $deletion) {
- $Customer = new Customer($deletion);
- $Billing = new Billing($Customer->id,'customer');
- $Billing->delete();
- $Shipping = new Shipping($Customer->id,'customer');
- $Shipping->delete();
- $Customer->delete();
- }
- }
-
- if (!empty($_POST['save'])) {
- check_admin_referer('shopp-save-customer');
- if ($_POST['id'] != "new") {
- $Customer = new Customer($_POST['id']);
- $Billing = new Billing($Customer->id,'customer');
- $Shipping = new Shipping($Customer->id,'customer');
- } else $Customer = new Customer();
-
- $Customer->updates($_POST);
-
- if (!empty($_POST['new-password']) && !empty($_POST['confirm-password'])
- && $_POST['new-password'] == $_POST['confirm-password']) {
- $Customer->password = wp_hash_password($_POST['new-password']);
- if (!empty($Customer->wpuser)) wp_set_password($_POST['new-password'], $Customer->wpuser);
- }
-
- $Customer->save();
-
- $Billing->updates($_POST['billing']);
- $Billing->save();
- $Shipping->updates($_POST['shipping']);
- $Shipping->save();
- }
- $pagenum = absint( $pagenum );
- if ( empty($pagenum) )
- $pagenum = 1;
- if( !$per_page || $per_page < 0 )
- $per_page = 20;
- $index = ($per_page * ($pagenum-1));
-
- if (!empty($start)) {
- $startdate = $start;
- list($month,$day,$year) = explode("/",$startdate);
- $starts = mktime(0,0,0,$month,$day,$year);
- }
- if (!empty($end)) {
- $enddate = $end;
- list($month,$day,$year) = explode("/",$enddate);
- $ends = mktime(23,59,59,$month,$day,$year);
- }
-
- $customer_table = DatabaseObject::tablename(Customer::$table);
- $billing_table = DatabaseObject::tablename(Billing::$table);
- $purchase_table = DatabaseObject::tablename(Purchase::$table);
- $users_table = $wpdb->users;
-
- $where = '';
- if (!empty($s)) {
- $s = stripslashes($s);
- if (preg_match_all('/(\w+?)\:(?="(.+?)"|(.+?)\b)/',$s,$props,PREG_SET_ORDER)) {
- foreach ($props as $search) {
- $keyword = !empty($search[2])?$search[2]:$search[3];
- switch(strtolower($search[1])) {
- case "company": $where .= ((empty($where))?"WHERE ":" AND ")."c.company LIKE '%$keyword%'"; break;
- case "login": $where .= ((empty($where))?"WHERE ":" AND ")."u.user_login LIKE '%$keyword%'"; break;
- case "address": $where .= ((empty($where))?"WHERE ":" AND ")."(b.address LIKE '%$keyword%' OR b.xaddress='%$keyword%')"; break;
- case "city": $where .= ((empty($where))?"WHERE ":" AND ")."b.city LIKE '%$keyword%'"; break;
- case "province":
- case "state": $where .= ((empty($where))?"WHERE ":" AND ")."b.state='$keyword'"; break;
- case "zip":
- case "zipcode":
- case "postcode": $where .= ((empty($where))?"WHERE ":" AND ")."b.postcode='$keyword'"; break;
- case "country": $where .= ((empty($where))?"WHERE ":" AND ")."b.country='$keyword'"; break;
- }
- }
- } elseif (strpos($s,'@') !== false) {
- $where .= ((empty($where))?"WHERE ":" AND ")."c.email='$s'";
- } else $where .= ((empty($where))?"WHERE ":" AND ")." (c.id='$s' OR CONCAT(c.firstname,' ',c.lastname) LIKE '%$s%' OR c.company LIKE '%$s%')";
- }
- if (!empty($starts) && !empty($ends)) $where .= ((empty($where))?"WHERE ":" AND ").' (UNIX_TIMESTAMP(c.created) >= '.$starts.' AND UNIX_TIMESTAMP(c.created) <= '.$ends.')';
- $customercount = $db->query("SELECT count(*) as total FROM $customer_table AS c $where");
- $query = "SELECT c.*,b.city,b.state,b.country, u.user_login, SUM(p.total) AS total,count(distinct p.id) AS orders FROM $customer_table AS c LEFT JOIN $purchase_table AS p ON p.customer=c.id LEFT JOIN $billing_table AS b ON b.customer=c.id LEFT JOIN $users_table AS u ON u.ID=c.wpuser AND (c.wpuser IS NULL OR c.wpuser !=0) $where GROUP BY c.id ORDER BY c.created DESC LIMIT $index,$per_page";
- $Customers = $db->query($query,AS_ARRAY);
- $num_pages = ceil($customercount->total / $per_page);
- $page_links = paginate_links( array(
- 'base' => add_query_arg( 'pagenum', '%#%' ),
- 'format' => '',
- 'total' => $num_pages,
- 'current' => $pagenum
- ));
-
- $ranges = array(
- 'all' => __('Show New Customers','Shopp'),
- 'today' => __('Today','Shopp'),
- 'week' => __('This Week','Shopp'),
- 'month' => __('This Month','Shopp'),
- 'quarter' => __('This Quarter','Shopp'),
- 'year' => __('This Year','Shopp'),
- 'yesterday' => __('Yesterday','Shopp'),
- 'lastweek' => __('Last Week','Shopp'),
- 'last30' => __('Last 30 Days','Shopp'),
- 'last90' => __('Last 3 Months','Shopp'),
- 'lastmonth' => __('Last Month','Shopp'),
- 'lastquarter' => __('Last Quarter','Shopp'),
- 'lastyear' => __('Last Year','Shopp'),
- 'lastexport' => __('Last Export','Shopp'),
- 'custom' => __('Custom Dates','Shopp')
- );
-
- $exports = array(
- 'tab' => __('Tab-separated.txt','Shopp'),
- 'csv' => __('Comma-separated.csv','Shopp'),
- 'xls' => __('Microsoft® Excel.xls','Shopp')
- );
-
-
- $formatPref = $Shopp->Settings->get('customerexport_format');
- if (!$formatPref) $formatPref = 'tab';
-
- $columns = array_merge(Customer::exportcolumns(),Billing::exportcolumns(),Shipping::exportcolumns());
- $selected = $Shopp->Settings->get('customerexport_columns');
- if (empty($selected)) $selected = array_keys($columns);
-
- $authentication = $Shopp->Settings->get('account_system');
-
- include("{$this->basepath}/core/ui/customers/customers.php");
-
- }
-
- function customers_list_columns () {
- shopp_register_column_headers('shopp_page_shopp-customers', array(
- 'cb'=>'<input type="checkbox" />',
- 'name'=>__('Name','Shopp'),
- 'login'=>__('Login','Shopp'),
- 'email'=>__('Email','Shopp'),
- 'location'=>__('Location','Shopp'),
- 'orders'=>__('Orders','Shopp'),
- 'joined'=>__('Joined','Shopp'))
- );
-
- }
- function customer_editor_ui () {
- global $Shopp;
- include("{$this->basepath}/core/ui/customers/ui.php");
- }
-
- function customer_editor () {
- global $Shopp,$Customer;
-
- if ( !current_user_can(SHOPP_USERLEVEL) )
- wp_die(__('You do not have sufficient permissions to access this page.'));
- if ($_GET['id'] != "new") {
- $Customer = new Customer($_GET['id']);
- $Customer->Billing = new Billing($Customer->id,'customer');
- $Customer->Shipping = new Shipping($Customer->id,'customer');
- if (empty($Customer->id))
- wp_die(__('The requested customer record does not exist.','Shopp'));
- } else $Customer = new Customer();
- $countries = array(''=>'');
- $countrydata = $Shopp->Settings->get('countries');
- foreach ($countrydata as $iso => $c) {
- if (isset($_POST['settings']) && $_POST['settings']['base_operations']['country'] == $iso)
- $base_region = $c['region'];
- $countries[$iso] = $c['name'];
- }
- $Customer->countries = $countries;
- $regions = $Shopp->Settings->get('zones');
- $Customer->billing_states = array_merge(array(''),(array)$regions[$Customer->Billing->country]);
- $Customer->shipping_states = array_merge(array(''),(array)$regions[$Customer->Shipping->country]);
- include("{$this->basepath}/core/ui/customers/editor.php");
- }
-
- /**
- * Products admin flow handlers
- **/
- function products_list($workflow=false) {
- global $Products,$Shopp;
- $db = DB::get();
- if ( !current_user_can(SHOPP_USERLEVEL) )
- wp_die(__('You do not have sufficient permissions to access this page.'));
- $defaults = array(
- 'cat' => false,
- 'pagenum' => 1,
- 'per_page' => 20,
- 's' => '',
- 'sl' => '',
- 'matchcol' => ''
- );
-
- $args = array_merge($defaults,$_GET);
- extract($args,EXTR_SKIP);
- if (!$workflow) {
- if (empty($categories)) $categories = array('');
-
- $category_table = DatabaseObject::tablename(Category::$table);
- $query = "SELECT id,name,parent FROM $category_table ORDER BY parent,name";
- $categories = $db->query($query,AS_ARRAY);
- $categories = sort_tree($categories);
- if (empty($categories)) $categories = array();
-
- $categories_menu = '<option value="">'.__('View all categories','Shopp').'</option>';
- $categories_menu .= '<option value="-"'.($cat=='-'?' selected="selected"':'').'>'.__('Uncategorized','Shopp').'</option>';
- foreach ($categories as $category) {
- $padding = str_repeat(" ",$category->depth*3);
- if ($cat == $category->id) $categories_menu .= '<option value="'.$category->id.'" selected="selected">'.$padding.$category->name.'</option>';
- else $categories_menu .= '<option value="'.$category->id.'">'.$padding.$category->name.'</option>';
- }
- $inventory_filters = array(
- 'all' => __('View all products','Shopp'),
- 'is' => __('In stock','Shopp'),
- 'ls' => __('Low stock','Shopp'),
- 'oos' => __('Out-of-stock','Shopp'),
- 'ns' => __('Not stocked','Shopp')
- );
- $inventory_menu = menuoptions($inventory_filters,$sl,true);
- }
-
- $pagenum = absint( $pagenum );
- if ( empty($pagenum) )
- $pagenum = 1;
- if( !$per_page || $per_page < 0 )
- $per_page = 20;
- $start = ($per_page * ($pagenum-1));
-
- $pd = DatabaseObject::tablename(Product::$table);
- $pt = DatabaseObject::tablename(Price::$table);
- $catt = DatabaseObject::tablename(Category::$table);
- $clog = DatabaseObject::tablename(Catalog::$table);
- $orderby = "pd.created DESC";
-
- $where = "true";
- $having = "";
- if (!empty($s)) {
- if (strpos($s,"sku:") !== false) { // SKU search
- $where .= ' AND pt.sku="'.substr($s,4).'"';
- $orderby = "pd.name";
- } else { // keyword search
- $interference = array("'s","'",".","\"");
- $search = preg_replace('/(\s?)(\w+)(\s?)/','\1*\2*\3',str_replace($interference,"", stripslashes($s)));
- $match = "MATCH(pd.name,pd.summary,pd.description) AGAINST ('$search' IN BOOLEAN MODE)";
- $where .= " AND $match";
- $matchcol = ", $match AS score";
- $orderby = "score DESC";
- }
- }
- // if (!empty($cat)) $where .= " AND cat.id='$cat' AND (clog.category != 0 OR clog.id IS NULL)";
- if (!empty($cat)) {
- if ($cat == "-") {
- $having = "HAVING COUNT(cat.id) = 0";
- } else {
- $matchcol .= ", GROUP_CONCAT(DISTINCT cat.id ORDER BY cat.id SEPARATOR ',') AS catids";
- $where .= " AND (clog.category != 0 OR clog.id IS NULL)";
- $having = "HAVING FIND_IN_SET('$cat',catids) > 0";
- }
- }
- if (!empty($sl)) {
- switch($sl) {
- case "ns": $where .= " AND pt.inventory='off'"; break;
- case "oos":
- $where .= " AND (pt.inventory='on')";
- $having .= (empty($having)?"HAVING ":" AND ")."SUM(pt.stock) = 0";
- break;
- case "ls":
- $ls = $Shopp->Settings->get('lowstock_level');
- if (empty($ls)) $ls = '0';
- $where .= " AND (pt.inventory='on' AND pt.stock <= $ls AND pt.stock > 0)";
- break;
- case "is": $where .= " AND (pt.inventory='on' AND pt.stock > 0)";
- }
- }
-
- $base = $Shopp->Settings->get('base_operations');
- if ($base['vat']) $taxrate = $Shopp->Cart->taxrate();
- if (empty($taxrate)) $taxrate = 0;
-
- $columns = "SQL_CALC_FOUND_ROWS pd.id,pd.name,pd.slug,pd.featured,pd.variations,GROUP_CONCAT(DISTINCT cat.name ORDER BY cat.name SEPARATOR ', ') AS categories,if(pt.options=0,IF(pt.tax='off',pt.price,pt.price+(pt.price*$taxrate)),-1) AS mainprice,IF(MAX(pt.tax)='off',MAX(pt.price),MAX(pt.price+(pt.price*$taxrate))) AS maxprice,IF(MAX(pt.tax)='off',MIN(pt.price),MIN(pt.price+(pt.price*$taxrate))) AS minprice,IF(pt.inventory='on','on','off') AS inventory,ROUND(SUM(pt.stock)/count(DISTINCT clog.id),0) AS stock";
- if ($workflow) $columns = "pd.id";
- // Load the products
- $query = "SELECT $columns $matchcol FROM $pd AS pd LEFT JOIN $pt AS pt ON pd.id=pt.product AND pt.type != 'N/A' LEFT JOIN $clog AS clog ON pd.id=clog.product LEFT JOIN $catt AS cat ON cat.id=clog.category WHERE $where GROUP BY pd.id $having ORDER BY $orderby LIMIT $start,$per_page";
- $Products = $db->query($query,AS_ARRAY);
- $productcount = $db->query("SELECT FOUND_ROWS() as total");
- $num_pages = ceil($productcount->total / $per_page);
- $page_links = paginate_links( array(
- 'base' => add_query_arg(array("edit"=>null,'pagenum' => '%#%')),
- 'format' => '',
- 'total' => $num_pages,
- 'current' => $pagenum,
- ));
- if ($workflow) return $Products;
-
- include("{$this->basepath}/core/ui/products/products.php");
- }
- function products_list_columns () {
- shopp_register_column_headers('shopp_page_shopp-products', array(
- 'cb'=>'<input type="checkbox" />',
- 'name'=>__('Name','Shopp'),
- 'category'=>__('Category','Shopp'),
- 'price'=>__('Price','Shopp'),
- 'inventory'=>__('Inventory','Shopp'),
- 'featured'=>__('Featured','Shopp'))
- );
- }
-
- function product_shortcode ($atts) {
- global $Shopp;
- if (isset($atts['name'])) {
- $Shopp->Product = new Product($atts['name'],'name');
- } elseif (isset($atts['slug'])) {
- $Shopp->Product = new Product($atts['slug'],'slug');
- } elseif (isset($atts['id'])) {
- $Shopp->Product = new Product($atts['id']);
- } else return "";
-
- if (isset($atts['nowrap']) && value_is_true($atts['nowrap']))
- return $Shopp->Catalog->tag('product',$atts);
- else return '<div id="shopp">'.$Shopp->Catalog->tag('product',$atts).'<div class="clear"></div></div>';
- }
-
- function category_shortcode ($atts) {
- global $Shopp;
-
- $tag = 'category';
- if (isset($atts['name'])) {
- $Shopp->Category = new Category($atts['name'],'name');
- unset($atts['name']);
- } elseif (isset($atts['slug'])) {
- switch ($atts['slug']) {
- case SearchResults::$_slug: $tag = 'search-products'; unset($atts['slug']);
- break;
- case TagProducts::$_slug: $tag = 'tag-products'; unset($atts['slug']);
- break;
- case BestsellerProducts::$_slug: $tag = 'bestseller-products'; unset($atts['slug']);
- break;
- case CatalogProducts::$_slug: $tag = 'catalog-products'; unset($atts['slug']);
- break;
- case NewProducts::$_slug: $tag = 'new-products'; unset($atts['slug']);
- break;
- case FeaturedProducts::$_slug: $tag = 'featured-products'; unset($atts['slug']);
- break;
- case OnSaleProducts::$_slug: $tag = 'onsale-products'; unset($atts['slug']);
- break;
- case RandomProducts::$_slug: $tag = 'random-products'; unset($atts['slug']);
- break;
- }
- } elseif (isset($atts['id'])) {
- $Shopp->Category = new Category($atts['id']);
- unset($atts['id']);
- } else return "";
-
- if (isset($atts['nowrap']) && value_is_true($atts['nowrap']))
- return $Shopp->Catalog->tag($tag,$atts);
- else return '<div id="shopp">'.$Shopp->Catalog->tag($tag,$atts).'<div class="clear"></div></div>';
-
- }
-
- function maintenance_shortcode ($atts) {
- return '<div id="shopp" class="update"><p>The store is currently down for maintenance. We\'ll be back soon!</p><div class="clear"></div></div>';
- }
-
- function product_editor_ui () {
- global $Shopp;
- include("{$this->basepath}/core/ui/products/ui.php");
- }
- function product_editor() {
- global $Shopp;
- $db = DB::get();
-
- if ( !current_user_can(SHOPP_USERLEVEL) )
- wp_die(__('You do not have sufficient permissions to access this page.'));
- if (empty($Shopp->Product)) {
- $Product = new Product();
- $Product->published = "on";
- } else $Product = $Shopp->Product;
-
- // $Product->load_data(array('images'));
- // echo "<pre>"; print_r($Product->imagesets); echo "</pre>";
-
- $Product->slug = apply_filters('editable_slug',$Product->slug);
- $permalink = $Shopp->shopuri;
- require_once("{$this->basepath}/core/model/Asset.php");
- require_once("{$this->basepath}/core/model/Category.php");
- $Price = new Price();
- $priceTypes = array(
- array('value'=>'Shipped','label'=>__('Shipped','Shopp')),
- array('value'=>'Virtual','label'=>__('Virtual','Shopp')),
- array('value'=>'Download','label'=>__('Download','Shopp')),
- array('value'=>'Donation','label'=>__('Donation','Shopp')),
- array('value'=>'N/A','label'=>__('Disabled','Shopp')),
- );
-
- $workflows = array(
- "continue" => __('Continue Editing','Shopp'),
- "close" => __('Products Manager','Shopp'),
- "new" => __('New Product','Shopp'),
- "next" => __('Edit Next','Shopp'),
- "previous" => __('Edit Previous','Shopp')
- );
-
- $taglist = array();
- foreach ($Product->tags as $tag) $taglist[] = $tag->name;
- if ($Product->id) {
- $Assets = new Asset();
- $Images = $db->query("SELECT id,src,properties FROM $Assets->_table WHERE context='product' AND parent=$Product->id AND datatype='thumbnail' ORDER BY sortorder",AS_ARRAY);
- unset($Assets);
- }
- $shiprates = $this->Settings->get('shipping_rates');
- if (!empty($shiprates)) ksort($shiprates);
- $uploader = $Shopp->Settings->get('uploader_pref');
- if (!$uploader) $uploader = 'flash';
- $process = (!empty($Product->id)?$Product->id:'new');
- $_POST['action'] = add_query_arg(array_merge($_GET,array('page'=>$this->Admin->products)),$Shopp->wpadminurl."admin.php");
-
- include("{$this->basepath}/core/ui/products/editor.php");
- }
- function save_product($Product) {
- global $Shopp;
- $db = DB::get();
- check_admin_referer('shopp-save-product');
- if ( !current_user_can(SHOPP_USERLEVEL) )
- wp_die(__('You do not have sufficient permissions to access this page.'));
- $this->settings_save(); // Save workflow setting
- $base = $Shopp->Settings->get('base_operations');
- $taxrate = 0;
- if ($base['vat']) $taxrate = $Shopp->Cart->taxrate();
- if (!$_POST['options']) $Product->options = array();
- else $_POST['options'] = stripslashes_deep($_POST['options']);
- if (empty($Product->slug)) $Product->slug = sanitize_title_with_dashes($_POST['name']);
- // Check for an existing product slug
- $exclude_product = !empty($Product->id)?"AND id != $Product->id":"";
- $existing = $db->query("SELECT slug FROM $Product->_table WHERE slug='$Product->slug' $exclude_product LIMIT 1");
- if ($existing) {
- $suffix = 2;
- while($existing) {
- $altslug = substr($Product->slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
- $existing = $db->query("SELECT slug FROM $Product->_table WHERE slug='$altslug' $exclude_product LIMIT 1");
- $suffix++;
- }
- $Product->slug = $altslug;
- }
-
- if (isset($_POST['content'])) $_POST['description'] = $_POST['content'];
- $Product->updates($_POST,array('categories'));
- $Product->save();
- $Product->save_categories($_POST['categories']);
- $Product->save_tags(explode(",",$_POST['taglist']));
-
- if (!empty($_POST['price']) && is_array($_POST['price'])) {
- // Delete prices that were marked…
Large files files are truncated, but you can click here to view the full file