Пример #1
0
	/**
	 * Delivers order export files to the browser
	 *
	 * @since 1.1
	 *
	 * @return void
	 **/
	function export_purchases () {
		if (!current_user_can('ecart_financials') || !current_user_can('ecart_export_orders')) exit();

		if (!isset($_POST['settings']['purchaselog_columns'])) {
			$Purchase = Purchase::exportcolumns();
			$Purchased = Purchased::exportcolumns();
			$_POST['settings']['purchaselog_columns'] =
			 	array_keys(array_merge($Purchase,$Purchased));
			$_POST['settings']['purchaselog_headers'] = "on";
		}
		$this->Settings->saveform();

		$format = $this->Settings->get('purchaselog_format');
		if (empty($format)) $format = 'tab';

		switch ($format) {
			case "csv": new PurchasesCSVExport(); break;
			case "xls": new PurchasesXLSExport(); break;
			case "iif": new PurchasesIIFExport(); break;
			default: new PurchasesTabExport();
		}
		exit();

	}
Пример #2
0
	/**
	 * Generates a Purchase record from the order
	 *	 
	 * @since 1.1
	 *
	 * @return void
	 **/
	function purchase () {
		global $Ecart;

		// Need a transaction ID to create a purchase
		if (empty($this->txnid)) return false;

		// Lock for concurrency protection
		$this->lock();

		$Purchase = new Purchase($this->txnid,'txnid');
		if (!empty($Purchase->id)) {
			$this->unlock();
			$Ecart->resession();

			$this->purchase = $Purchase->id;
			if ($this->purchase !== false)
				ecart_redirect(ecarturl(false,'thanks'));

		}

		// WordPress account integration used, customer has no wp user
		if ("wordpress" == $this->accounts && empty($this->Customer->wpuser)) {
			if ( $wpuser = get_current_user_id() ) $this->Customer->wpuser = $wpuser; // use logged in WordPress account
			else $this->Customer->create_wpuser(); // not logged in, create new account
		}

		// New customer, save hashed password
		if (!$this->Customer->exists() && !empty($this->Customer->password)) {
			$this->Customer->id = false;
			if (ECART_DEBUG) new EcartError('Creating new Ecart customer record','new_customer',ECART_DEBUG_ERR);
			if ("ecart" == $this->accounts) $this->Customer->notification();
			$this->Customer->password = wp_hash_password($this->Customer->password);
		} else unset($this->Customer->password); // Existing customer, do not overwrite password field!

		$this->Customer->save();

		$this->Billing->customer = $this->Customer->id;
		$this->Billing->card = substr($this->Billing->card,-4);
		$paycard = Lookup::paycard($this->Billing->cardtype);
		$this->Billing->cardtype = !$paycard?$this->Billing->cardtype:$paycard->name;
		$this->Billing->cvv = false;
		$this->Billing->save();

		// Card data is truncated, switch the cart to normal mode
		$Ecart->Shopping->secured(false);

		if (!empty($this->Shipping->address)) {
			$this->Shipping->customer = $this->Customer->id;
			$this->Shipping->save();
		}

		$base = $Ecart->Settings->get('base_operations');

		$promos = array();
		foreach ($this->Cart->discounts as &$promo) {
			$promos[$promo->id] = $promo->name;
			$promo->uses++;
		}

		$Purchase = new Purchase();
		$Purchase->copydata($this);
		$Purchase->copydata($this->Customer);
		$Purchase->copydata($this->Billing);
		$Purchase->copydata($this->Shipping,'ship');
		$Purchase->copydata($this->Cart->Totals);
		$Purchase->customer = $this->Customer->id;
		$Purchase->billing = $this->Billing->id;
		$Purchase->shipping = $this->Shipping->id;
		$Purchase->taxing = ($base['vat'])?'inclusive':'exclusive';
		$Purchase->promos = $promos;
		$Purchase->freight = $this->Cart->Totals->shipping;
		$Purchase->ip = $Ecart->Shopping->ip;
		$Purchase->save();
		$this->unlock();
		Promotion::used(array_keys($promos));

		foreach($this->Cart->contents as $Item) {
			$Purchased = new Purchased();
			$Purchased->copydata($Item);
			$Purchased->price = $Item->option->id;
			$Purchased->purchase = $Purchase->id;
			if (!empty($Purchased->download)) $Purchased->keygen();
			$Purchased->save();
			if ($Item->inventory) $Item->unstock();
		}

		$this->purchase = $Purchase->id;
		$Ecart->Purchase = &$Purchase;

		if (ECART_DEBUG) new EcartError('Purchase '.$Purchase->id.' was successfully saved to the database.',false,ECART_DEBUG_ERR);

		do_action('ecart_order_notifications');

		do_action_ref_array('ecart_order_success',array(&$Ecart->Purchase));
	}
 /**
  * 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&reg; Excel.xls', 'Shopp'), 'iif' => __('Intuit&reg; 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 process()
 {
     global $Shopp;
     if (empty($_POST)) {
         new ShoppError(__('Payment could not be confirmed, this order cannot be processed.', 'Shopp'), '2co_transaction_error', SHOPP_COMM_ERR);
         exit;
     }
     session_unset();
     session_destroy();
     // Load the cart for the correct order
     $Shopp->Cart = new Cart();
     $Shopp->Cart->session = $_POST['vendor_order_id'];
     session_start();
     $Shopp->Cart->load($Shopp->Cart->session);
     if ($this->settings['verify'] == "on" && !$this->validate($_POST['key'])) {
         new ShoppError(__('The order submitted to 2Checkout could not be verified.', 'Shopp'), '2co_validation_error', SHOPP_TRXN_ERR);
         exit;
     }
     if ($_POST['credit_card_processed'] == "N") {
         new ShoppError(__('The payment failed. Please try your order again with a different payment method.', 'Shopp'), '2co_processing_error', SHOPP_TRXN_ERR);
         exit;
     }
     if (!$Shopp->Cart->validorder()) {
         new ShoppError(__('There is not enough customer information to process the order.', 'Shopp'), 'invalid_order', SHOPP_TRXN_ERR);
         exit;
     }
     $Order = $Shopp->Cart->data->Order;
     $Order->Totals = $Shopp->Cart->data->Totals;
     $Order->Items = $Shopp->Cart->contents;
     $Order->Cart = $Shopp->Cart->session;
     $Order->Customer->save();
     $Order->Billing->customer = $Order->Customer->id;
     $Order->Billing->cardtype = "2Checkout";
     $Order->Billing->save();
     $Order->Shipping->customer = $Order->Customer->id;
     $Order->Shipping->save();
     $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($Order->Totals);
     $Purchase->freight = $Order->Totals->shipping;
     $Purchase->gateway = "2Checkout";
     $Purchase->transtatus = "CHARGED";
     $Purchase->transactionid = $_POST['order_number'];
     $Purchase->ip = $Shopp->Cart->ip;
     $Purchase->save();
     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();
         }
     }
     return $Purchase;
 }
 /**
  * lookups ()
  * Provides fast db lookups with as little overhead as possible */
 function lookups($wp)
 {
     $db =& DB::get();
     // Grab query requests from permalink rewriting query vars
     $admin = false;
     $download = isset($wp->query_vars['shopp_download']) ? $wp->query_vars['shopp_download'] : '';
     $lookup = isset($wp->query_vars['shopp_lookup']) ? $wp->query_vars['shopp_lookup'] : '';
     // Admin Lookups
     if (isset($_GET['page']) && $_GET['page'] == "shopp-lookup") {
         $admin = true;
         $image = $_GET['id'];
         $download = $_GET['download'];
     }
     if (!empty($download)) {
         $lookup = "download";
     }
     if (empty($lookup)) {
         $lookup = isset($_GET['lookup']) ? $_GET['lookup'] : '';
     }
     switch ($lookup) {
         case "purchaselog":
             if (!defined('WP_ADMIN') || !is_user_logged_in() || !current_user_can('manage_options')) {
                 die('-1');
             }
             $db =& DB::get();
             if (!isset($_POST['settings']['purchaselog_columns'])) {
                 $_POST['settings']['purchaselog_columns'] = array_keys(array_merge($Purchase, $Purchased));
                 $_POST['settings']['purchaselog_headers'] = "on";
             }
             $this->Flow->settings_save();
             $format = $this->Settings->get('purchaselog_format');
             if (empty($format)) {
                 $format = 'tab';
             }
             switch ($format) {
                 case "csv":
                     new PurchasesCSVExport();
                     break;
                 case "xls":
                     new PurchasesXLSExport();
                     break;
                 case "iif":
                     new PurchasesIIFExport();
                     break;
                 default:
                     new PurchasesTabExport();
             }
             exit;
             break;
         case "customerexport":
             if (!defined('WP_ADMIN') || !is_user_logged_in() || !current_user_can('manage_options')) {
                 die('-1');
             }
             $db =& DB::get();
             if (!isset($_POST['settings']['customerexport_columns'])) {
                 $Customer = Customer::exportcolumns();
                 $Billing = Billing::exportcolumns();
                 $Shipping = Shipping::exportcolumns();
                 $_POST['settings']['customerexport_columns'] = array_keys(array_merge($Customer, $Billing, $Shipping));
                 $_POST['settings']['customerexport_headers'] = "on";
             }
             $this->Flow->settings_save();
             $format = $this->Settings->get('customerexport_format');
             if (empty($format)) {
                 $format = 'tab';
             }
             switch ($format) {
                 case "csv":
                     new CustomersCSVExport();
                     break;
                 case "xls":
                     new CustomersXLSExport();
                     break;
                 default:
                     new CustomersTabExport();
             }
             exit;
             break;
         case "receipt":
             if (!defined('WP_ADMIN') || !is_user_logged_in() || !current_user_can('manage_options')) {
                 die('-1');
             }
             if (preg_match("/\\d+/", $_GET['id'])) {
                 $this->Cart->data->Purchase = new Purchase($_GET['id']);
                 $this->Cart->data->Purchase->load_purchased();
             } else {
                 die('-1');
             }
             echo "<html><head>";
             echo '<style type="text/css">body { padding: 20px; font-family: Arial,Helvetica,sans-serif; }</style>';
             echo "<link rel='stylesheet' href='" . SHOPP_TEMPLATES_URI . "/shopp.css' type='text/css' />";
             echo "</head><body>";
             echo $this->Flow->order_receipt();
             if (isset($_GET['print']) && $_GET['print'] == 'auto') {
                 echo '<script type="text/javascript">window.onload = function () { window.print(); window.close(); }</script>';
             }
             echo "</body></html>";
             exit;
             break;
         case "zones":
             $zones = $this->Settings->get('zones');
             if (isset($_GET['country'])) {
                 echo json_encode($zones[$_GET['country']]);
             }
             exit;
             break;
         case "shipcost":
             @session_start();
             $this->ShipCalcs = new ShipCalcs($this->path);
             if (isset($_GET['method'])) {
                 $this->Cart->data->Order->Shipping->method = $_GET['method'];
                 $this->Cart->retotal = true;
                 $this->Cart->updated();
                 $this->Cart->totals();
                 echo json_encode($this->Cart->data->Totals);
             }
             exit;
             break;
         case "category-menu":
             echo $this->Flow->category_menu();
             exit;
             break;
         case "category-products-menu":
             echo $this->Flow->category_products();
             exit;
             break;
         case "spectemplate":
             $db = DB::get();
             $table = DatabaseObject::tablename(Category::$table);
             $result = $db->query("SELECT specs FROM {$table} WHERE id='{$_GET['cat']}' AND spectemplate='on'");
             echo json_encode(unserialize($result->specs));
             exit;
             break;
         case "optionstemplate":
             $db = DB::get();
             $table = DatabaseObject::tablename(Category::$table);
             $result = $db->query("SELECT options,prices FROM {$table} WHERE id='{$_GET['cat']}' AND variations='on'");
             if (empty($result)) {
                 exit;
             }
             $result->options = unserialize($result->options);
             $result->prices = unserialize($result->prices);
             foreach ($result->options as &$menu) {
                 foreach ($menu['options'] as &$option) {
                     $option['id'] += $_GET['cat'];
                 }
             }
             foreach ($result->prices as &$price) {
                 $optionids = explode(",", $price['options']);
                 foreach ($optionids as &$id) {
                     $id += $_GET['cat'];
                 }
                 $price['options'] = join(",", $optionids);
                 $price['optionkey'] = "";
             }
             echo json_encode($result);
             exit;
             break;
         case "newproducts-rss":
             $NewProducts = new NewProducts(array('show' => 5000));
             header("Content-type: application/rss+xml; charset=utf-8");
             echo shopp_rss($NewProducts->rss());
             exit;
             break;
         case "category-rss":
             $this->catalog($wp);
             header("Content-type: application/rss+xml; charset=utf-8");
             echo shopp_rss($this->Category->rss());
             exit;
             break;
         case "download":
             if (empty($download)) {
                 break;
             }
             if ($admin) {
                 $Asset = new Asset($download);
             } else {
                 $db = DB::get();
                 $pricetable = DatabaseObject::tablename(Purchase::$table);
                 $pricetable = DatabaseObject::tablename(Price::$table);
                 $assettable = DatabaseObject::tablename(Asset::$table);
                 require_once "core/model/Purchased.php";
                 $Purchased = new Purchased($download, "dkey");
                 $Purchase = new Purchase($Purchased->purchase);
                 $target = $db->query("SELECT target.* FROM {$assettable} AS target LEFT JOIN {$pricetable} AS pricing ON pricing.id=target.parent AND target.context='price' WHERE pricing.id={$Purchased->price} AND target.datatype='download'");
                 $Asset = new Asset();
                 $Asset->populate($target);
                 $forbidden = false;
                 // Purchase Completion check
                 if ($Purchase->transtatus != "CHARGED" && !SHOPP_PREPAYMENT_DOWNLOADS) {
                     new ShoppError(__('This file cannot be downloaded because payment has not been received yet.', 'Shopp'), 'shopp_download_limit');
                     $forbidden = true;
                 }
                 // Account restriction checks
                 if ($this->Settings->get('account_system') != "none" && (!$this->Cart->data->login || $this->Cart->data->Order->Customer->id != $Purchase->customer)) {
                     new ShoppError(__('You must login to access this download.', 'Shopp'), 'shopp_download_limit', SHOPP_ERR);
                     header('Location: ' . $this->link('account'));
                     exit;
                 }
                 // Download limit checking
                 if ($this->Settings->get('download_limit') && $Purchased->downloads + 1 > $this->Settings->get('download_limit')) {
                     new ShoppError(__('This file can no longer be downloaded because the download limit has been reached.', 'Shopp'), 'shopp_download_limit');
                     $forbidden = true;
                 }
                 // Download expiration checking
                 if ($this->Settings->get('download_timelimit') && $Purchased->created + $this->Settings->get('download_timelimit') < mktime()) {
                     new ShoppError(__('This file can no longer be downloaded because it has expired.', 'Shopp'), 'shopp_download_limit');
                     $forbidden = true;
                 }
                 // IP restriction checks
                 if ($this->Settings->get('download_restriction') == "ip" && !empty($Purchase->ip) && $Purchase->ip != $_SERVER['REMOTE_ADDR']) {
                     new ShoppError(__('The file cannot be downloaded because this computer could not be verified as the system the file was purchased from.', 'Shopp'), 'shopp_download_limit');
                     $forbidden = true;
                 }
                 do_action_ref_array('shopp_download_request', array(&$Purchased));
             }
             if ($forbidden) {
                 header("Status: 403 Forbidden");
                 return;
             }
             if ($Asset->download($download)) {
                 $Purchased->downloads++;
                 $Purchased->save();
                 do_action_ref_array('shopp_download_success', array(&$Purchased));
                 exit;
             }
             break;
     }
 }
Пример #6
0
	function PurchasesExport () {
		global $Ecart;

		$this->purchase_cols = Purchase::exportcolumns();
		$this->purchased_cols = Purchased::exportcolumns();
		$this->defined = array_merge($this->purchase_cols,$this->purchased_cols);

		$this->sitename = get_bloginfo('name');
		$this->headings = ($Ecart->Settings->get('purchaselog_headers') == "on");
		$this->selected = $Ecart->Settings->get('purchaselog_columns');
		$this->date_format = get_option('date_format');
		$this->time_format = get_option('time_format');
		$Ecart->Settings->save('purchaselog_lastexport',mktime());
	}
 /**
  * order()
  * Handles new order notifications from Google */
 function order($XML)
 {
     global $Shopp;
     $db = DB::get();
     // Check if this is a Shopp order or not
     $origin = $XML->getElementContent('shopping-cart-agent');
     if (empty($origin) || substr($origin, 0, strpos("/", SHOPP_GATEWAY_USERAGENT)) == SHOPP_GATEWAY_USERAGENT) {
         return true;
     }
     $buyer = $XML->getElement('buyer-billing-address');
     $buyer = $buyer['CHILDREN'];
     $Customer = new Customer();
     $name = $XML->getElement('structured-name');
     $Customer->firstname = $buyer['structured-name']['CHILDREN']['first-name']['CONTENT'];
     $Customer->lastname = $buyer['structured-name']['CHILDREN']['last-name']['CONTENT'];
     if (empty($name)) {
         $name = $buyer['contact-name']['CONTENT'];
         $names = explode(" ", $name);
         $Customer->firstname = $names[0];
         $Customer->lastname = $names[count($names) - 1];
     }
     $Customer->email = $buyer['email']['CONTENT'];
     $Customer->phone = $buyer['phone']['CONTENT'];
     $Customer->save();
     $Billing = new Billing();
     $Billing->customer = $Customer->id;
     $Billing->address = $buyer['address1']['CONTENT'];
     $Billing->xaddress = $buyer['address2']['CONTENT'];
     $Billing->city = $buyer['city']['CONTENT'];
     $Billing->state = $buyer['region']['CONTENT'];
     $Billing->country = $buyer['country-code']['CONTENT'];
     $Billing->postcode = $buyer['postal-code']['CONTENT'];
     $Billing->save();
     $shipto = $XML->getElement('buyer-shipping-address');
     $shipto = $shipto['CHILDREN'];
     $Shipping = new Shipping();
     $Shipping->customer = $Customer->id;
     $Shipping->address = $shipto['address1']['CONTENT'];
     $Shipping->xaddress = $shipto['address2']['CONTENT'];
     $Shipping->city = $shipto['city']['CONTENT'];
     $Shipping->state = $shipto['region']['CONTENT'];
     $Shipping->country = $shipto['country-code']['CONTENT'];
     $Shipping->postcode = $shipto['postal-code']['CONTENT'];
     $Shipping->save();
     $Purchase = new Purchase();
     $Purchase->customer = $Customer->id;
     $Purchase->billing = $Billing->id;
     $Purchase->shipping = $Shipping->id;
     $Purchase->copydata($Customer);
     $Purchase->copydata($Billing);
     $Purchase->copydata($Shipping, 'ship');
     $Purchase->freight = $XML->getElementContent('shipping-cost');
     $Purchase->tax = $XML->getElementContent('total-tax');
     $Purchase->total = $XML->getElementContent('order-total');
     $Purchase->subtotal = $Purchase->total - $Purchase->frieght - $Purchase->tax;
     $Purchase->gateway = "Google Checkout";
     $Purchase->transactionid = $XML->getElementContent('google-order-number');
     $Purchase->transtatus = $XML->getElementContent('financial-order-state');
     $Purchase->ip = $XML->getElementContent('customer-ip');
     $orderdata = $XML->getElement('shopp-order-data');
     $data = array();
     if (is_array($orderdata) && count($orderdata) > 0) {
         foreach ($orderdata as $input) {
             $data[$input['ATTRS']['name']] = $input['CONTENT'];
         }
     }
     $Purchase->data = $data;
     $Purchase->save();
     $items = $XML->getElement('item');
     if (key($items) === "CHILDREN") {
         $items = array($items);
     }
     foreach ($items as $item) {
         $xml = $item['CHILDREN'];
         $itemdata = $xml['merchant-private-item-data']['CHILDREN'];
         $inputdata = $itemdata['shopp-item-data-list']['CHILDREN']['shopp-item-data'];
         $data = array();
         if (is_array($inputdata) && count($inputdata) > 0) {
             foreach ($inputdata as $input) {
                 $data[$input['ATTRS']['name']] = $input['CONTENT'];
             }
         }
         $Product = new Product($itemdata['shopp-product-id']['CONTENT']);
         $Item = new Item($Product, $itemdata['shopp-price-id']['CONTENT'], false, $data);
         $Item->quantity($xml['quantity']['CONTENT']);
         $Purchased = new Purchased();
         $Purchased->copydata($Item);
         $Purchased->purchase = $Purchase->id;
         if (!empty($Purchased->download)) {
             $Purchased->keygen();
         }
         $Purchased->save();
         if ($Item->inventory) {
             $Item->unstock();
         }
     }
 }
 function process()
 {
     global $Shopp;
     if (!isset($Shopp->Cart->data->PayPalExpress->token) && !isset($Shopp->Cart->data->PayPalExpress->payerid)) {
         return false;
     }
     $_ = $this->headers();
     $_['METHOD'] = "DoExpressCheckoutPayment";
     $_['PAYMENTACTION'] = "Sale";
     $_['TOKEN'] = $Shopp->Cart->data->PayPalExpress->token;
     $_['PAYERID'] = $Shopp->Cart->data->PayPalExpress->payerid;
     // Transaction
     $_ = array_merge($_, $this->purchase());
     $this->transaction = $this->encode($_);
     $result = $this->send();
     if (!$result) {
         new ShoppError(__('No response was received from PayPal. The order cannot be processed.', 'Shopp'), 'paypalexpress_noresults', SHOPP_COMM_ERR);
     }
     if (!$Shopp->Cart->validorder()) {
         new ShoppError(__('There is not enough customer information to process the order.', 'Shopp'), 'invalid_order', SHOPP_TRXN_ERR);
         return false;
     }
     // If the transaction is a success, get the transaction details,
     // build the purchase receipt, save it and return it
     if (strtolower($result->ack) == "success") {
         $_ = $this->headers();
         $_['METHOD'] = "GetTransactionDetails";
         $_['TRANSACTIONID'] = $this->Response->transactionid;
         $this->transaction = $this->encode($_);
         $result = $this->send();
         if (!$result) {
             new ShoppError(__('Details for the order were not provided by PayPal.', 'Shopp'), 'paypalexpress_notrxn_details', SHOPP_COMM_ERR);
             return false;
         }
         $Order = $Shopp->Cart->data->Order;
         $Order->Totals = $Shopp->Cart->data->Totals;
         $Order->Items = $Shopp->Cart->contents;
         $Order->Cart = $Shopp->Cart->session;
         $authentication = $Shopp->Settings->get('account_system');
         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->cardtype = "PayPal";
         $Order->Billing->save();
         $Order->Shipping->customer = $Order->Customer->id;
         $Order->Shipping->save();
         $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($Order->Totals);
         $Purchase->freight = $Order->Totals->shipping;
         $Purchase->gateway = "PayPal Express";
         $Purchase->transactionid = $this->Response->transactionid;
         $Purchase->transtatus = $this->status[$this->Response->paymentstatus];
         $Purchase->ip = $Shopp->Cart->ip;
         $Purchase->fees = $this->Response->feeamt;
         $Purchase->save();
         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();
             }
         }
         return $Purchase;
     }
     // Fail by default
     return false;
 }
 function order()
 {
     global $Shopp;
     $txnstatus = false;
     $ipnstatus = $this->verifyipn();
     // Validate the order notification
     if ($ipnstatus != "VERIFIED") {
         $txnstatus = $ipnstatus;
         new ShoppError('An unverifiable order notification was received from PayPal. Possible fraudulent order attempt! The order will be created, but the order payment status must be manually set to "Charged" when the payment can be verified.', 'paypal_txn_verification', SHOPP_TRXN_ERR);
     }
     if (!$txnstatus) {
         $txnstatus = $this->status[$_POST['payment_status']];
     }
     $Order = $Shopp->Cart->data->Order;
     $Order->Totals = $Shopp->Cart->data->Totals;
     $Order->Items = $Shopp->Cart->contents;
     $Order->Cart = $Shopp->Cart->session;
     if (SHOPP_DEBUG) {
         new ShoppError('IPN notification validated.', false, SHOPP_DEBUG_ERR);
     }
     // Transaction successful, save the order
     $authentication = $Shopp->Settings->get('account_system');
     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) {
             $user = get_userdata($Order->Customer->wpuser);
             $Order->Customer->wpuser = $user->ID;
             if (SHOPP_DEBUG) {
                 new ShoppError('Customer logged in, linking Shopp customer account to existing WordPress account.', false, SHOPP_DEBUG_ERR);
             }
         }
         // 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) && isset($Order->Customer->password)) {
         $Order->Customer->password = wp_hash_password($Order->Customer->password);
     }
     $Order->Customer->save();
     $Order->Billing->customer = $Order->Customer->id;
     $Order->Billing->cardtype = "PayPal";
     $Order->Billing->save();
     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;
     }
     $Purchase = new Purchase();
     $Purchase->customer = $Order->Customer->id;
     $Purchase->billing = $Order->Billing->id;
     $Purchase->shipping = $Order->Shipping->id;
     $Purchase->data = $Order->data;
     $Purchase->promos = $Promos;
     $Purchase->copydata($Order->Customer);
     $Purchase->copydata($Order->Billing);
     $Purchase->copydata($Order->Shipping, 'ship');
     $Purchase->copydata($Shopp->Cart->data->Totals);
     $Purchase->freight = $Shopp->Cart->data->Totals->shipping;
     $Purchase->gateway = "PayPal" . (isset($_POST['test_ipn']) && $_POST['test_ipn'] == "1" ? " Sandbox" : "");
     $Purchase->transactionid = $_POST['txn_id'];
     $Purchase->transtatus = $txnstatus;
     $Purchase->fees = $_POST['mc_fee'];
     $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();
         }
     }
     // Empty cart on successful order
     $Shopp->Cart->unload();
     session_destroy();
     // Start new cart session
     $Shopp->Cart = new Cart();
     session_start();
     // Keep the user loggedin
     if ($Shopp->Cart->data->login) {
         $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'));
     }
     shopp_redirect($Shopp->link('receipt', false));
 }