예제 #1
0
 /**
  * An additional action that's called by this module when the above form is submitted.
  */
 public function ExportOrders()
 {
     // Load up the orders class
     $GLOBALS['ISC_CLASS_ADMIN_ORDERS'] = GetClass('ISC_ADMIN_ORDERS');
     // Get the value of the order status setting
     if ($this->GetValue('orderstatus') == 'shipped') {
         $_GET['orderStatus'] = 2;
     }
     $numOrders = 0;
     $ordersResult = $GLOBALS['ISC_CLASS_ADMIN_ORDERS']->_GetOrderList(0, 'orderid', 'desc', $numOrders, true);
     if ($numOrders == 0) {
         $GLOBALS['ISC_CLASS_ADMIN_ORDERS']->ManageOrders(GetLang('NoOrders'));
         return;
     }
     require_once ISC_BASE_PATH . '/lib/class.xml.php';
     $xml = new ISC_XML_PARSER();
     $tags = array();
     while ($order = $GLOBALS['ISC_CLASS_DB']->Fetch($ordersResult)) {
         $orderTags = array();
         $orderTags[] = $xml->MakeXMLTag('amount', number_format($order['ordtotalamount'], 2));
         $orderTags[] = $xml->MakeXMLTag('customer', $order['ordbillfirstname'] . ' ' . $order['ordbilllastname'], true);
         $orderTags[] = $xml->MakeXMLTag('date', CDate($order['orddate']), true);
         $attributes = array('orderid' => $order['orderid']);
         $tags[] = $xml->MakeXMLTag('order', implode('', $orderTags), false, $attributes);
     }
     @ob_end_clean();
     $xml->SendXMLHeader();
     $xml->SendXMLResponse($tags);
     exit;
 }
예제 #2
0
파일: data.php 프로젝트: eneiasramos/xmoney
 function data_changed($entry)
 {
     $text = $entry->get_text();
     if (strlen($text) && $this->field && $this->field_print) {
         $this->filter = $this->field . ' LIKE ' . String(CDate($text) . '%');
         $this->filter_print = $this->field_print . ' LIKE ' . String(CDate($text) . '%');
     } else {
         $this->filter = '';
         $this->filter_print = '';
     }
 }
예제 #3
0
 /**
  * Fetch the payment details (outstanding balance etc) for a specific vendor.
  */
 private function GetVendorPaymentDetails()
 {
     if (!isset($_REQUEST['vendorId'])) {
         exit;
     }
     $paymentClass = GetClass('ISC_ADMIN_VENDOR_PAYMENTS');
     $paymentDetails = $paymentClass->CalculateOutstandingVendorBalance($_REQUEST['vendorId']);
     $tags[] = $this->MakeXMLTag('status', 1);
     $tags[] = $this->MakeXMLTag('fromDate', CDate($paymentDetails['lastPaymentDate']), true);
     $tags[] = $this->MakeXMLTag('toDate', CDate(time()), true);
     $tags[] = $this->MakeXMLTag('outstandingBalance', FormatPrice($paymentDetails['outstandingBalance']), true);
     $tags[] = $this->MakeXMLTag('balanceForward', FormatPrice($paymentDetails['balanceForward']), true);
     $tags[] = $this->MakeXMLTag('profitMargin', FormatPrice($paymentDetails['profitMargin']), true);
     $tags[] = $this->MakeXMLTag('profitMarginPercentage', $paymentDetails['profitMarginPercentage'], true);
     $tags[] = $this->MakeXMLTag('totalOrders', FormatPrice($paymentDetails['totalOrders']), true);
     $this->SendXMLHeader();
     $this->SendXMLResponse($tags);
     exit;
 }
예제 #4
0
 /**
  * Generate the 'Quick View' for a particular request.
  *
  * @param int The request ID.
  * @return string The generated quick view for the request.
  */
 public function PreviewRequest()
 {
     if (!isset($_REQUEST['orderId'])) {
         exit;
     }
     $order = GetOrder($_REQUEST['orderId'], true);
     /*
     if(!isset($order['orderid']) || $order['ordisdigital'] == 1 || ($order['ordtotalqty']-$order['ordtotalshipped']) <= 0) {
     	exit;
     }
     */
     $GLOBALS['OrderId'] = $order['orderid'];
     $GLOBALS['OrderDate'] = CDate($order['orddate']);
     if (isset($_GET['templateId'])) {
         $templateId = $_GET['templateId'];
     } else {
         $templateId = 1;
     }
     $GLOBALS['TemplateId'] = $templateId;
     $GLOBALS['PreviewTemplate'] = $this->paserRequestTemplate($templateId);
     $GLOBALS['RemindMessage'] = GetLang('PreviewReviewIntro');
     $GLOBALS['ShowSendBtn'] = '';
     $query = "\n\t\t\tSELECT *\n\t\t\tFROM [|PREFIX|]requests\n\t\t\tWHERE orderid=" . $GLOBALS['OrderId'] . "\n\t\t";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     if ($row = $GLOBALS['ISC_CLASS_DB']->fetch($result)) {
         if ($row['requeststatus'] == 2) {
             $GLOBALS['ShowSendBtn'] = 'none';
             $GLOBALS['RemindMessage'] = GetLang('NoResendWarning');
         } else {
             $GLOBALS['RemindMessage'] = sprintf(GetLang('ResendWarning'), $row['requestdate'], $row['requestowner']);
             //$this->RecordReviewRequest($order['orderid'], true,$templateId,false);
         }
     } else {
         //$this->RecordReviewRequest($order['orderid'], true,$templateId,false);
     }
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate('requests.preview');
     return $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
 }
예제 #5
0
		private function ManageCustomersGrid(&$numCustomers)
		{
			// Show a list of customers in a table
			$page = 0;
			$start = 0;
			$numCustomers = 0;
			$numGroups = 0;
			$GLOBALS['CustomerGrid'] = "";
			$max = 0;

			if (GetConfig('CurrencyLocation') == 'right') {
				$GLOBALS['CurrencyTokenLeft'] = '';
				$GLOBALS['CurrencyTokenRight'] = GetConfig('CurrencyToken');
			} else {
				$GLOBALS['CurrencyTokenLeft'] = GetConfig('CurrencyToken');
				$GLOBALS['CurrencyTokenRight'] = '';
			}

			$this->_customerGroups = &$this->_GetGroupList($numGroups);

			if (!gzte11(ISC_MEDIUMPRINT) || $numGroups == 0) {
				$GLOBALS[base64_decode('SGlkZUdyb3Vw')] = "none";
			}

			// Is this a custom search?
			if (isset($_GET['searchId'])) {
				// Override custom search sort fields if we have a requested field
				if (isset($_GET['sortField'])) {
					$_REQUEST['sortField'] = $_GET['sortField'];
				}
				if (isset($_GET['sortOrder'])) {
					$_REQUEST['sortOrder'] = $_GET['sortOrder'];
				}
			}

			if (isset($_GET['searchQuery'])) {
				$GLOBALS['EscapedQuery'] = isc_html_escape($_GET['searchQuery']);
			}

			if (isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == "asc") {
				$sortOrder = "asc";
			}
			else {
				$sortOrder = "desc";
			}

			$validSortFields = array('customerid', 'custconlastname', 'custconfirstname', 'custconemail', 'custconphone', 'custconcompany', 'custdatejoined', 'numorders', 'custstorecredit');
			if (isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) {
				$sortField = $_REQUEST['sortField'];
				SaveDefaultSortField("ManageCustomers", $_REQUEST['sortField'], $sortOrder);
			} else {
				list($sortField, $sortOrder) = GetDefaultSortField("ManageCustomers", "customerid", $sortOrder);
			}

			$searchURL = $this->buildSearchUrlData($_GET, $sortField, $sortOrder);
			$this->buildLetterSearchUrlData($searchURL);

			$sortURL = $searchURL;
			unset($sortURL['sortField'], $sortURL['sortOrder']);


			if (isset($_GET['page'])) {
				$page = (int)$_GET['page'];
			}
			else {
				$page = 1;
			}

			if (isset($_GET['perpage'])) {
				$perPage = (int)$_GET['perpage'];
				SaveDefaultPerPage("ManageCustomers", $perPage);
			}
			else {
				$perPage = GetDefaultPerPage("ManageCustomers", ISC_CUSTOMERS_PER_PAGE);
			}

			// Limit the number of customers returned
			if ($page == 1) {
				$start = 1;
			}
			else {
				$start = ($page * $perPage) - ($perPage-1);
			}

			$start = $start-1;

			// Get the results for the query
			$customerResult = $this->_GetCustomerList($start, $sortField, $sortOrder, $numCustomers, $perPage);

			$GLOBALS['perPage'] = $perPage;
			$GLOBALS['numCustomers'] = $numCustomers;
			$GLOBALS['pageURL'] = "index.php?ToDo=viewCustomers&" . http_build_query($searchURL);
			$GLOBALS['currentPage'] = $page;

			$GLOBALS['SortField'] = $sortField;
			$GLOBALS['SortOrder'] = $sortOrder;

			$sortLinks = array(
				"CustId" => "customerid",
				"Name" => "custconlastname",
				"Email" => "custconemail",
				"Phone" => "custconphone",
				"StoreCredit" => "custstorecredit",
				"Date" => "custdatejoined",
				"NumOrders" => "numorders"
			);
			BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewCustomers&amp;".http_build_query($sortURL)."&amp;page=".$page, $sortField, $sortOrder);

			// Workout the maximum size of the array
			$max = $start + $perPage;

			if ($max > $GLOBALS["ISC_CLASS_DB"]->CountResult($customerResult)) {
				$max = $GLOBALS["ISC_CLASS_DB"]->CountResult($customerResult);
			}

			if (!empty($this->_customerGroups)) {
				$showGroups = true;
			}
			else {
				$showGroups = false;
			}

			if ($numCustomers > 0) {
				while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($customerResult)) {
					$GLOBALS['CustomerId'] = (int) $row['customerid'];
					$GLOBALS['Name'] = isc_html_escape($row['custfullname']);
					$GLOBALS['Email'] = sprintf("<a href='mailto:%s'>%s</a>", urlencode($row['custconemail']), isc_html_escape($row['custconemail']));

					if ($row['custconphone'] != "") {
						$GLOBALS['Phone'] = isc_html_escape($row['custconphone']);
					} else {
						$GLOBALS['Phone'] = GetLang('NA');
					}

					$GLOBALS['Group'] = "";
					if ($showGroups) {
						if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Customers)) {
							$GLOBALS['Group'] = $this->_BuildGroupDropdown($row['customerid'], $row['custgroupid'], $row['custfullname']);
						}
						elseif ($row['custgroupid']) {
							$GLOBALS['Group'] = $this->_customerGroups[$row['custgroupid']]['groupname'];
						}
					}

					if ($row['custconcompany'] != "") {
						$GLOBALS['Company'] = isc_html_escape($row['custconcompany']);
					} else {
						$GLOBALS['Company'] = GetLang('NA');
					}

					$GLOBALS['Date'] = CDate($row['custdatejoined']);
					$GLOBALS['NumOrders'] = (int) $row['numorders'];

					// Hide the plus symbol if the customer has no orders
					if ($row['numorders'] == 0) {
						$GLOBALS['HideExpand'] = "none";
					} else {
						$GLOBALS['HideExpand'] = "";
					}

					// If the customer has any notes, flag them
					$HasNotesClass = '';
					if($row['custnotes'] != '') {
						$HasNotesClass = 'HasNotes';
					}

					// Workout which links the user can have
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Customers)) {
						$GLOBALS['StoreCreditAmount'] = FormatPrice($row['custstorecredit'], false, false, false);
						$GLOBALS['StoreCredit'] = $this->template->render('Snippets/CustomerRowStoreCredit.html');
						$GLOBALS['LoginLink'] = "<a href='index.php?ToDo=loginCustomer&amp;customerId=" . $row['customerid'] . "' class='Action' target='_blank'>" . GetLang('CustomerLoginAsThem') . "</a>";
						$GLOBALS['ViewNotesLink'] = "<a href='#' class='" . $HasNotesClass . " ViewNotesLink' onclick='Customers.ViewNotes(".$row['customerid']."); return false;'>" . GetLang("CustomerNotesLink") . "</a>";
						$GLOBALS['EditCustomerLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=editCustomer&amp;customerId=%d'>%s</a>", GetLang('CustomerEdit'), $row['customerid'], GetLang('Edit'));
					} else {
						$GLOBALS['StoreCredit'] = FormatPrice($row['custstorecredit']);
						$GLOBALS['LoginLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('CustomerLoginAsThem'));
						$GLOBALS['ViewNotesLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('CustomerNotesLink'));
						$GLOBALS['EditCustomerLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit'));
					}

					$GLOBALS['CustomerGrid'] .= $this->template->render('customers.manage.row.tpl');
				}
			}
			else {
				if (isset($_REQUEST['letter'])) {
					$GLOBALS['CustomerGrid'] = sprintf('<tr>
						<td colspan="11" style="padding:10px"><em>%s</em></td>
					</tr>', sprintf(GetLang('CustomerLetterSortNoResults'), isc_strtoupper($_REQUEST['letter'])));
				}
			}

			return $this->template->render('customers.manage.grid.tpl');
		}
	/**
	 * Generates the HTML for a gift certificate using this theme.
	 *
	 * @param array gift certificate placeholder data
	 *
	 * @return string the generated gift certificate html
	 */
	public function generateGiftCertificateHTML($certificate)
	{
		$template = TEMPLATE::getInstance();

		if(!isset($GLOBALS['ShopPathNormal'])) {
			$GLOBALS['ShopPathNormal'] = $GLOBALS['ShopPath'];
		}

		// Fetch the store logo or store title
		if(GetConfig('UseAlternateTitle')) {
			$text = GetConfig('AlternateTitle');
		}
		else {
			$text = GetConfig('StoreName');
		}
		$text = explode(" ", $text, 2);
		$text[0] = "<span class=\"Logo1stWord\">".$text[0]."</span>";
		$GLOBALS['LogoText'] = implode(" ", $text);
		$GLOBALS['HeaderLogo'] = $template->GetSnippet("LogoText");

		// Set gift certificate details
		$GLOBALS['CharacterSet']=GetConfig('CharacterSet');
		$GLOBALS['GiftCertificateTo'] = isc_html_escape($certificate['giftcertto']);
		$GLOBALS['GiftCertificateToEmail'] = isc_html_escape($certificate['giftcerttoemail']);
		$GLOBALS['GiftCertificateFrom'] = isc_html_escape($certificate['giftcertfrom']);
		$GLOBALS['GiftCertificateFromEmail'] = isc_html_escape($certificate['giftcertfromemail']);
		$GLOBALS['GiftCertificateAmount'] = CurrencyConvertFormatPrice($certificate['giftcertamount']);
		$GLOBALS['GiftCertificateMessage'] = isc_html_escape($certificate['giftcertmessage']);
		$GLOBALS['GiftCertificateCode'] = isc_html_escape($certificate['giftcertcode']);
		if(isset($certificate['giftcertexpirydate']) && $certificate['giftcertexpirydate'] != 0) {
			$GLOBALS['GiftCertificateExpiryInfo'] = sprintf(GetLang('GiftCertificateExpiresOn'), CDate($certificate['giftcertexpirydate']));
		}
		else {
			$GLOBALS['GiftCertificateExpiryInfo'] = '';
		}

		// Build the html
		$html = $template->ParseTemplate(true, $this->getTemplateContents());

		return $html;
	}
예제 #7
0
 function grava_dados()
 {
     if (!$this->check_dados()) {
         return;
     }
     $db = new Database($this, false);
     if (!$db->link) {
         return;
     }
     $num_doc = $this->num_doc->get_text();
     $parcela = $this->parcela->get_text();
     $vencimento = CDate($this->vencimento->get_text());
     $valor = CommaToPoint($this->valor->get_text());
     $anotacoes = $this->anotacoes->get_text();
     if ($this->operacao == 'i') {
         $sql = 'call SP_Conta_Receber_Inc';
     } else {
         $sql = 'call SP_Conta_Receber_Alt';
     }
     $data = $sql . '(' . String($this->tipo_doc->CodTipoDoc) . ',' . String($this->filial->CodFilial) . ',' . String($this->clientes->CodCliente) . ',' . String($num_doc) . ',' . String($parcela) . ',' . String($vencimento) . ',' . String($valor) . ',' . String($anotacoes) . ',' . $GLOBALS['CodUsuario'] . ');';
     if (!$db->multi_query($data)) {
         return;
     }
     $line = $db->line();
     $db->free_result();
     new Message($this, $line['Mensagem']);
     return true;
 }
예제 #8
0
파일: orders.php 프로젝트: hungnv0789/vhtm
/**
 *	Send an email notification to a customer when the status of their order changes.
 *
 * @param int The ID of the order to email the invoice for.
 * @return boolean True if successful.
 */
function EmailOnStatusChange($orderId, $status)
{
	// Load the order
	$order = GetOrder($orderId);
	if (!$order) {
		return false;
	}

	// Load the customer we'll be contacting
	if ($order['ordcustid'] > 0) {
		$customer = GetCustomer($order['ordcustid']);
		$GLOBALS['ViewOrderStatusLink'] = '<a href="'.$GLOBALS['ShopPathSSL'].'/orderstatus.php">'.GetLang('ViewOrderStatus').'</a>';
	} else {
		$customer['custconemail'] = $order['ordbillemail'];
		$customer['custconfirstname'] = $order['ordbillfirstname'];
		$GLOBALS['ViewOrderStatusLink'] = '';
	}

	if (empty($customer['custconemail'])) {
		return;
	}

	// All prices in the emailed invoices will be shown in the default currency of the store
	$defaultCurrency = GetDefaultCurrency();

	$statusName = GetOrderStatusById($status);
	$GLOBALS['OrderStatusChangedHi'] = sprintf(GetLang('OrderStatusChangedHi'), isc_html_escape($customer['custconfirstname']));
	$GLOBALS['OrderNumberStatusChangedTo'] = sprintf(GetLang('OrderNumberStatusChangedTo'), $order['orderid'], $statusName);
	$GLOBALS['OrderTotal'] = FormatPrice($order['total_inc_tax'], false, true, false, $defaultCurrency, true);
	$GLOBALS['DatePlaced'] = CDate($order['orddate']);

	if ($order['orderpaymentmethod'] === 'giftcertificate') {
		$GLOBALS['PaymentMethod'] = GetLang('PaymentGiftCertificate');
	}
	else if ($order['orderpaymentmethod'] === 'storecredit') {
		$GLOBALS['PaymentMethod'] = GetLang('PaymentStoreCredit');
	}
	else {
		$GLOBALS['PaymentMethod'] = $order['orderpaymentmethod'];
	}

	$query = "
		SELECT COUNT(*)
		FROM [|PREFIX|]order_products
		WHERE ordprodtype='digital'
		AND orderorderid='".$GLOBALS['ISC_CLASS_DB']->Quote($orderId)."'
	";

	$numDigitalProducts = $GLOBALS['ISC_CLASS_DB']->FetchOne($query);

	$emailTemplate = FetchEmailTemplateParser();

	$GLOBALS['SNIPPETS']['CartItems'] = "";

	if (OrderIsComplete($status) && $numDigitalProducts > 0) {
		$query = "
			SELECT *
			FROM [|PREFIX|]order_products op INNER JOIN [|PREFIX|]products p ON (op.ordprodid = p.productid)
			WHERE ordprodtype='digital'
			AND orderorderid='".$GLOBALS['ISC_CLASS_DB']->Quote($orderId)."'
		";
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		while ($product_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			$GLOBALS['ProductOptions'] = '';
			$GLOBALS['ProductQuantity'] = $product_row['ordprodqty'];
			$GLOBALS['ProductName'] = isc_html_escape($product_row['ordprodname']);

			$GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');
			$DownloadItemEncrypted = $GLOBALS['ISC_CLASS_ACCOUNT']->EncryptDownloadKey($product_row['orderprodid'], $product_row['ordprodid'], $orderId, $order['ordtoken']);
			$GLOBALS['DownloadsLink'] = $GLOBALS['ShopPathSSL'].'/account.php?action=download_item&amp;data='.$DownloadItemEncrypted;

			$GLOBALS['SNIPPETS']['CartItems'] .= $emailTemplate->GetSnippet("StatusCompleteDownloadItem");
		}
	}

	$GLOBALS['SNIPPETS']['OrderTrackingLink'] = "";

	$shipments = $GLOBALS['ISC_CLASS_DB']->Query("
		SELECT shipmentid, shipdate, shiptrackno, shipping_module, shipmethod, shipcomments
		FROM [|PREFIX|]shipments
		WHERE shiporderid = " . (int)$orderId . "
		ORDER BY shipdate, shipmentid
	");

	$GLOBALS['TrackingLinkList'] = '';

	while($shipment = $GLOBALS['ISC_CLASS_DB']->Fetch($shipments)) {
		if (!$shipment['shiptrackno']) {
			continue;
		}

		GetModuleById('shipping', /** @var ISC_SHIPPING */$module, $shipment['shipping_module']);

		if ($module) {
			$link = $module->GetTrackingLink($shipment['shiptrackno']);
			if ($link) {
				$link = '<a href="' . isc_html_escape($link) . '" target="_blank">' . $shipment['shiptrackno'] . '</a>';
			} else {
				$link = $shipment['shiptrackno'];
			}
		} else {
			$link = $shipment['shiptrackno'];
		}

		if($shipment['shipmethod']) {
			$link .= ' (' . $shipment['shipmethod'] . ')';
		}

		if ($link) {
			$GLOBALS['TrackingLinkList'] .= '<li>' . $link . '</li>';
		}
	}

	if (empty($GLOBALS['TrackingLinkList'])) {
		$GLOBALS['TrackingLinkList'] = GetLang('NoTrackingNumbersYet');
	} else {
		$GLOBALS['TrackingLinkList'] = '<ul>' . $GLOBALS['TrackingLinkList'] . '</ul>';
	}

	// Set up tracking numbers for orders. Whilst we don't have tracking numbers
	// on orders any longer, this code is being kept for legacy reasons where
	// orders may already have a tracking number saved. To be removed in a future
	// version.
	if (!empty($order['ordtrackingno'])) {
		$GLOBALS['HideTrackingText'] = "";
		$GLOBALS['OrderTrackingNo'] = isc_html_escape($order['ordtrackingno']);

		// Let's instantiate an object for the shipper
		$shipper_object = false;
		if ($order['ordershipmodule'] != "" && GetModuleById('shipping', $shipper_object, $order['ordershipmodule'])) {
			// Does it have a link to track the order?
			if ($shipper_object->GetTrackingLink() != "") {
				// Show the tracking link
				$GLOBALS['TrackURL'] = $shipper_object->GetTrackingLink($order['ordtrackingno']);
				$GLOBALS['SNIPPETS']['OrderTrackingLink'] = $emailTemplate->GetSnippet("OrderTrackingLink");
			}
		}
	}

	if (empty($GLOBALS['SNIPPETS']['CartItems'])) {
		$emailTemplate->SetTemplate("order_status_email");
	} else {
		$emailTemplate->SetTemplate("order_status_downloads_email");
	}
	$message = $emailTemplate->ParseTemplate(true);

	// Create a new email API object to send the email
	$store_name = GetConfig('StoreName');
	$subject = GetLang('OrderStatusChangedSubject');

	require_once(ISC_BASE_PATH . "/lib/email.php");
	$obj_email = GetEmailClass();
	$obj_email->Set('CharSet', GetConfig('CharacterSet'));
	$obj_email->From(GetConfig('OrderEmail'), $store_name);
	$obj_email->Set('Subject', $subject);
	$obj_email->AddBody("html", $message);
	$obj_email->AddRecipient($customer['custconemail'], '', "h");
	$email_result = $obj_email->Send();

	if ($email_result['success']) {
		return true;
	}
	else {
		return false;
	}
}
예제 #9
0
 private function ManageCouponsGrid(&$numCoupons)
 {
     // Show a list of coupons in a table
     $page = 0;
     $start = 0;
     $numCoupons = 0;
     $numPages = 0;
     $GLOBALS['CouponGrid'] = "";
     $GLOBALS['Nav'] = "";
     $max = 0;
     if (isset($_GET['sortOrder']) && $_GET['sortOrder'] == 'desc') {
         $sortOrder = 'desc';
     } else {
         $sortOrder = "asc";
     }
     $sortLinks = array("Name" => "c.couponname", "Coupon" => "c.couponcode", "Discount" => "c.couponamount", "Expiry" => "c.couponexpires", "NumUses" => "c.couponnumuses", "Enabled" => "c.couponenabled");
     if (isset($_GET['sortField']) && in_array($_GET['sortField'], $sortLinks)) {
         $sortField = $_GET['sortField'];
         SaveDefaultSortField("ManageCoupons", $_REQUEST['sortField'], $sortOrder);
     } else {
         list($sortField, $sortOrder) = GetDefaultSortField("ManageCoupons", "c.couponid", $sortOrder);
     }
     if (isset($_GET['page'])) {
         $page = (int) $_GET['page'];
     } else {
         $page = 1;
     }
     $sortURL = sprintf("&sortField=%s&sortOrder=%s", $sortField, $sortOrder);
     $GLOBALS['SortURL'] = $sortURL;
     // Limit the number of questions returned
     if ($page == 1) {
         $start = 1;
     } else {
         $start = $page * ISC_COUPONS_PER_PAGE - (ISC_COUPONS_PER_PAGE - 1);
     }
     $start = $start - 1;
     // Get the results for the query
     $couponResult = $this->_GetCouponList($start, $sortField, $sortOrder, $numCoupons);
     $numPages = ceil($numCoupons / ISC_COUPONS_PER_PAGE);
     if ($numCoupons > ISC_COUPONS_PER_PAGE) {
         $GLOBALS['Nav'] = sprintf("(%s %d of %d) &nbsp;&nbsp;&nbsp;", GetLang('Page'), $page, $numPages);
         $GLOBALS['Nav'] .= BuildPagination($numCoupons, ISC_COUPONS_PER_PAGE, $page, sprintf("index.php?ToDo=viewCoupons%s", $sortURL));
     } else {
         $GLOBALS['Nav'] = "";
     }
     $GLOBALS['SortField'] = $sortField;
     BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewCoupons&amp;page=" . $page, $sortField, $sortOrder);
     $max = $start + ISC_COUPONS_PER_PAGE;
     if ($max > count($couponResult)) {
         $max = count($couponResult);
     }
     if ($numCoupons > 0) {
         // Display the coupons
         while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($couponResult)) {
             $GLOBALS['Name'] = isc_html_escape($row['couponname']);
             $GLOBALS['CouponId'] = (int) $row['couponid'];
             $GLOBALS['Coupon'] = isc_html_escape($row['couponcode']);
             if ($row['coupontype'] == 0) {
                 // Dollar value coupon code
                 $GLOBALS['Discount'] = sprintf("%s", FormatPrice($row['couponamount']));
             } else {
                 // Percentage value coupon code
                 $GLOBALS['Discount'] = sprintf("%s%%", number_format($row['couponamount'], GetConfig('DecimalPlaces'), GetConfig('DecimalToken'), GetConfig('ThousandsToken')));
             }
             if ($row['couponexpires'] > 0) {
                 $GLOBALS['Date'] = CDate($row['couponexpires']);
             } else {
                 $GLOBALS['Date'] = GetLang('NA');
             }
             if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Coupons)) {
                 $GLOBALS['EditCouponLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=editCoupon&amp;couponId=%d'>%s</a>", GetLang('CouponEdit'), $row['couponid'], GetLang('Edit'));
                 if ($row['couponenabled'] == 1) {
                     $GLOBALS['Enabled'] = sprintf("<a title='%s' href='index.php?ToDo=editCouponEnabled&amp;couponId=%d&amp;enabled=0'><img border='0' src='images/tick.gif'></a>", GetLang('ClickToDisableCoupon'), $row['couponid']);
                 } else {
                     $GLOBALS['Enabled'] = sprintf("<a title='%s' href='index.php?ToDo=editCouponEnabled&amp;couponId=%d&amp;enabled=1'><img border='0' src='images/cross.gif'></a>", GetLang('ClickToEnableCoupon'), $row['couponid']);
                 }
             } else {
                 $GLOBALS['EditCouponLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit'));
                 if ($row['couponenabled'] == 1) {
                     $GLOBALS['Enabled'] = '<img border="0" src="images/tick.gif" alt="tick" />';
                 } else {
                     $GLOBALS['Enabled'] = '<img border="0" src="images/cross.gif" alt="cross" />';
                 }
             }
             $GLOBALS['NumUses'] = number_format($row['couponnumuses']);
             $GLOBALS['ViewOrdersLink'] = '';
             if ($row['couponnumuses'] > 0) {
                 $GLOBALS['ViewOrdersLink'] = sprintf("&nbsp;&nbsp;&nbsp;<a href='index.php?ToDo=viewOrders&amp;couponCode=%s' title='%s'>%s</a>", $row['couponcode'], GetLang('ViewOrdersWithCoupon'), GetLang('ViewOrders'));
             }
             $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("coupons.manage.row");
             $GLOBALS['CouponGrid'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
         }
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("coupons.manage.grid");
         return $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
     }
 }
예제 #10
0
 public function ManageReviewsGrid(&$numReviews)
 {
     // Show a list of reviews in a table
     $page = 0;
     $start = 0;
     $numReviews = 0;
     $numPages = 0;
     $GLOBALS['ReviewGrid'] = "";
     $GLOBALS['Nav'] = "";
     $max = 0;
     $searchURL = '';
     $filterURL = '';
     //Added by Simha
     if (isset($_GET['brandid'])) {
         $filterURL .= "&amp;brandid=" . trim($_GET['brandid']) . "";
     }
     if (isset($_GET['seriesid'])) {
         $filterURL .= "&amp;seriesid=" . trim($_GET['seriesid']) . "";
     }
     //Added by Simha Ends
     //lguan_20100612: Category supporting in product rating
     if (isset($_GET['catid'])) {
         $filterURL .= "&amp;catid=" . trim($_GET['catid']) . "";
     }
     if (isset($_GET['subcatid'])) {
         $filterURL .= "&amp;subcatid=" . trim($_GET['subcatid']) . "";
     }
     //lguan_20100615: Append information for from and to
     if (isset($GLOBALS['FromStamp']) && is_numeric($GLOBALS['FromStamp'])) {
         $filterURL .= "&amp;from=" . isc_date('m/d/Y', $GLOBALS['FromStamp']) . "";
     }
     if (isset($GLOBALS['ToStamp']) && is_numeric($GLOBALS['ToStamp'])) {
         $filterURL .= "&amp;to=" . isc_date('m/d/Y', $GLOBALS['ToStamp']) . "";
     }
     if (isset($_GET['datetype'])) {
         $filterURL .= "&amp;datetype=" . $_GET['datetype'] . "";
     }
     //wiyin_20100628: get the review status
     if (isset($_GET['reviewStatus'])) {
         $GLOBALS['reviewStatus'] = (int) $_GET['reviewStatus'];
     }
     if (isset($_GET['ISSelectReplacement_category'])) {
         $cateList = $_GET['ISSelectReplacement_category'];
         if (is_array($cateList)) {
             if (!in_array(0, $cateList)) {
                 $GLOBALS['CateList'] = $cateList;
             }
         }
     }
     if (isset($_GET['searchQuery'])) {
         $query = $_GET['searchQuery'];
         $GLOBALS['Query'] = $query;
         $searchURL = sprintf("&amp;searchQuery=%s", urlencode($query));
     } else {
         $query = "";
         $GLOBALS['Query'] = "";
     }
     if (isset($_GET['sortOrder']) && $_GET['sortOrder'] == 'asc') {
         $sortOrder = 'asc';
     } else {
         $sortOrder = "desc";
     }
     $sortLinks = array("OrderId" => "r.orderid", "Review" => "r.revtitle", "Name" => "p.prodname", "By" => "r.revfromname", "Rating" => "r.revrating", "Date" => "r.revdate", "Status" => "r.revstatus", "RatingQuality" => "r.qualityrating", "RatingInstall" => "r.installrating", "RatingValue" => "r.valuerating", "RatingSupport" => "r.supportrating", "RatingDelivery" => "r.deliveryrating");
     if (isset($_GET['sortField']) && in_array($_GET['sortField'], $sortLinks)) {
         $sortField = $_GET['sortField'];
         SaveDefaultSortField("ManageReviews", $_REQUEST['sortField'], $sortOrder);
     } else {
         list($sortField, $sortOrder) = GetDefaultSortField("ManageReviews", "r.reviewid", $sortOrder);
     }
     if (isset($_GET['page'])) {
         $page = (int) $_GET['page'];
     } else {
         $page = 1;
     }
     $GLOBALS['Page'] = $page;
     $sortURL = sprintf("&sortField=%s&sortOrder=%s", $sortField, $sortOrder);
     $GLOBALS['SortURL'] = $sortURL;
     // Limit the number of questions returned
     if ($page == 1) {
         $start = 1;
     } else {
         $start = $page * ISC_REVIEWS_PER_PAGE - (ISC_REVIEWS_PER_PAGE - 1);
     }
     $start = $start - 1;
     // Get the results for the query
     $reviewResult = $this->_GetReviewList($query, $start, $sortField, $sortOrder, $numReviews);
     $numPages = ceil($numReviews / ISC_REVIEWS_PER_PAGE);
     // Add the "(Page x of n)" label
     if ($numReviews > ISC_REVIEWS_PER_PAGE) {
         $GLOBALS['Nav'] = sprintf("(%s %d of %d) &nbsp;&nbsp;&nbsp;", GetLang('Page'), $page, $numPages);
         $GLOBALS['Nav'] .= BuildPagination($numReviews, ISC_REVIEWS_PER_PAGE, $page, sprintf("index.php?ToDo=viewReviews%s%s%s", $sortURL, $filterURL, $searchURL));
     } else {
         $GLOBALS['Nav'] = "";
     }
     $GLOBALS['Nav'] = rtrim($GLOBALS['Nav'], ' |');
     $GLOBALS['SearchQuery'] = $query;
     $GLOBALS['SortField'] = $sortField;
     $GLOBALS['SortOrder'] = $sortOrder;
     BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewReviews&amp;" . $searchURL . "&amp;page=" . $page . $filterURL, $sortField, $sortOrder);
     // Workout the maximum size of the array
     $max = $start + ISC_REVIEWS_PER_PAGE;
     if ($max > $numReviews) {
         $max = $numReviews;
     }
     if ($numReviews > 0) {
         // Display the reviews
         while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($reviewResult)) {
             $GLOBALS['ReviewId'] = $row['reviewid'];
             $GLOBALS['ProdName'] = isc_html_escape($row['prodname']);
             $GLOBALS['ProdLink'] = ProdLink($row['prodname']);
             if (isc_strlen($row['revtext']) > 100) {
                 $GLOBALS['ReviewTitle'] = isc_html_escape(sprintf("%s...", isc_substr($row['revtitle'], 0, 100)));
             } else {
                 $GLOBALS['ReviewTitle'] = isc_html_escape($row['revtitle']);
             }
             //lguan_20100612: Show extra rating options
             $GLOBALS['Rating'] = $this->wrapRatingImages($row['revrating']);
             $GLOBALS['RatingQuality'] = $this->wrapRatingImages($row['qualityrating']);
             $GLOBALS['RatingInstall'] = $this->wrapRatingImages($row['installrating']);
             $GLOBALS['RatingValue'] = $this->wrapRatingImages($row['valuerating']);
             $GLOBALS['RatingSupport'] = $this->wrapRatingImages($row['supportrating']);
             $GLOBALS['RatingDelivery'] = $this->wrapRatingImages($row['deliveryrating']);
             if ($row['revfromname'] != "") {
                 $GLOBALS['PostedBy'] = isc_html_escape($row['revfromname']);
             } else {
                 $GLOBALS['PostedBy'] = GetLang('NA');
             }
             $GLOBALS['Date'] = CDate($row['revdate']);
             $GLOBALS['PreviewLink'] = sprintf("<a title='%s' href='javascript:PreviewReview(%d)'>%s</a>", GetLang('PreviewReview'), $row['reviewid'], GetLang('Preview'));
             if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Edit_Reviews)) {
                 $GLOBALS['EditLink'] = sprintf("<a title='%s' href='index.php?ToDo=editReview&amp;reviewId=%d'>%s</a>", GetLang('EditReview'), $row['reviewid'], GetLang('Edit'));
             } else {
                 $GLOBALS['EditLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit'));
             }
             switch ($row['revstatus']) {
                 case "0":
                     $GLOBALS['Status'] = GetLang('Pending');
                     break;
                 case "1":
                     $GLOBALS['Status'] = sprintf("<font color='green'>%s</font>", GetLang('Approved'));
                     break;
                 case "2":
                     $GLOBALS['Status'] = sprintf("<font color='red'>%s</font>", GetLang('Disapproved'));
                     break;
             }
             $revOrderid = $row['orderid'];
             //$orderInformations = $this->GetOrderInformationsByOrderId($revOrderid);
             if (is_numeric($revOrderid) && $revOrderid > 0 && isset($row["ordcustid"])) {
                 //viewOrders&orderId
                 $GLOBALS["OrderId"] = "<a href='index.php?ToDo=viewOrders&orderId=" . $row["orderid"] . "' >" . $row["orderid"] . "</a>";
             } else {
                 $GLOBALS["OrderId"] = "unknown";
             }
             $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("reviews.manage.row");
             $GLOBALS['ReviewGrid'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
         }
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("reviews.manage.grid");
         return $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
     }
 }
예제 #11
0
 /**
  * Generate the KPI table for orders, visitors, conversion rate etc.
  * Will use the time period from the request if one exists (GET or COOKIE)
  * or falls back to the last week.
  *
  * @return string The generated HTML for the performance indicators table.
  */
 public function GeneratePerformanceIndicatorsTable()
 {
     if (!$this->auth->HasPermission(AUTH_Statistics_Overview)) {
         return false;
     }
     // If we don't have a period coming in via the URL, use the default
     if (!isset($_GET['period'])) {
         // Is it set in a cookie?
         if (isset($_COOKIE['DashboardPerformanceIndicatorsPeriod'])) {
             $period = $_COOKIE['DashboardPerformanceIndicatorsPeriod'];
         } else {
             $period = 'week';
         }
     } else {
         $period = $_GET['period'];
     }
     // Determine for which dates we need to fetch the statistics
     switch ($period) {
         case 'week':
             $lastPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m'), isc_date('d') - 13, isc_date('y'));
             $thisPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m'), isc_date('d') - 6, isc_date('y'));
             break;
         case 'month':
             $lastPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m') - 2, isc_date('d'), isc_date('y'));
             $thisPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m') - 1, isc_date('d'), isc_date('y'));
             break;
         case 'year':
             $lastPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m'), isc_date('d'), isc_date('y') - 2);
             $thisPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m'), isc_date('d'), isc_date('y') - 1);
             break;
         default:
             $period = 'day';
             $lastPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m'), isc_date('d') - 1, isc_date('y'));
             $thisPeriodFrom = isc_gmmktime(0, 0, 0, isc_date('m'), isc_date('d'), isc_date('y'));
     }
     $this->template->Assign('LastPeriodHeader', GetLang('Last' . ucfirst($period)));
     $this->template->Assign('ThisPeriodHeader', GetLang('This' . ucfirst($period)));
     // Run up until 1 second before the current period. Subtracting 1 second allows us to generate displayable dates for the period.
     $lastPeriodTo = $thisPeriodFrom - 1;
     if ($period != 'day') {
         $this->template->Assign('LastPeriodDateRange', CDate($lastPeriodFrom) . ' - ' . CDate($lastPeriodTo));
         $this->template->Assign('ThisPeriodDateRange', CDate($thisPeriodFrom) . ' - ' . CDate(time()));
     } else {
         $this->template->Assign('LastPeriodDateRange', CDate($lastPeriodFrom));
         $this->template->Assign('ThisPeriodDateRange', CDate($thisPeriodFrom));
     }
     // Calculate the number of orders and the total revenue
     $vendorAdd = '';
     if ($this->auth->GetVendorId()) {
         $vendorAdd .= " AND ordvendorid='" . $this->auth->GetVendorId() . "'";
     }
     $query = "\n\t\t\tSELECT SUM(ordtotalamount) AS totalrevenue, COUNT(orderid) AS numorders\n\t\t\tFROM [|PREFIX|]orders\n\t\t\tWHERE ordstatus IN (" . implode(',', GetPaidOrderStatusArray()) . ") AND orddate >= '" . $lastPeriodFrom . "' AND orddate <= '" . $lastPeriodTo . "' " . $vendorAdd . "\n\t\t";
     $result = $this->db->Query($query);
     $lastPeriodOrderStats = $this->db->Fetch($result);
     $query = "\n\t\t\tSELECT SUM(ordtotalamount) AS totalrevenue, COUNT(orderid) AS numorders\n\t\t\tFROM [|PREFIX|]orders\n\t\t\tWHERE ordstatus IN (" . implode(',', GetPaidOrderStatusArray()) . ") AND orddate >= '" . $thisPeriodFrom . "' " . $vendorAdd . "\n\t\t";
     $result = $this->db->Query($query);
     $thisPeriodOrderStats = $this->db->Fetch($result);
     // Calculate the number of visitors
     if (!$this->auth->GetVendorId()) {
         $query = "\n\t\t\t\tSELECT SUM(numuniques)\n\t\t\t\tFROM [|PREFIX|]unique_visitors\n\t\t\t\tWHERE datestamp >= '" . $lastPeriodFrom . "' AND datestamp <= '" . $lastPeriodTo . "'\n\t\t\t";
         $lastPeriodVisitorStats = $this->db->FetchOne($query);
         $query = "\n\t\t\t\tSELECT SUM(numuniques)\n\t\t\t\tFROM [|PREFIX|]unique_visitors\n\t\t\t\tWHERE datestamp >= '" . $thisPeriodFrom . "'\n\t\t\t";
         $thisPeriodVisitorStats = $this->db->FetchOne($query);
         // Calculate the percentage change in visitors between the last period and the current period
         $visitorChange = $thisPeriodVisitorStats - $lastPeriodVisitorStats;
         $prefix = '';
         if ($visitorChange == 0) {
             $visitorChangePercent = 0;
         } else {
             if ($lastPeriodVisitorStats > 0) {
                 $visitorChangePercent = round($visitorChange / $lastPeriodVisitorStats * 100, 2);
             } else {
                 $visitorChangePercent = 100;
             }
         }
         if ($visitorChangePercent > 0) {
             $prefix = '+';
             $this->template->Assign('NumVisitorsChangeClass', 'Positive');
         } else {
             if ($visitorChangePercent < 0) {
                 $this->template->Assign('NumVisitorsChangeClass', 'Negative');
             }
         }
         $visitorChangePercent = $prefix . number_format($visitorChangePercent, 2) . '%';
         $this->template->Assign('LastPeriodNumVisitors', number_format($lastPeriodVisitorStats));
         $this->template->Assign('ThisPeriodNumVisitors', number_format($thisPeriodVisitorStats));
         $this->template->Assign('NumVisitorsChange', $visitorChangePercent);
         $lastConversion = 0;
         if ($lastPeriodVisitorStats > 0) {
             $lastConversion = $lastPeriodOrderStats['numorders'] / $lastPeriodVisitorStats * 100;
         }
         $this->template->Assign('LastPeriodConversionRate', number_format(round($lastConversion, 2), 2));
         $thisConversion = 0;
         if ($thisPeriodVisitorStats > 0) {
             $thisConversion = $thisPeriodOrderStats['numorders'] / $thisPeriodVisitorStats * 100;
         }
         $this->template->Assign('ThisPeriodConversionRate', number_format(round($thisConversion, 2), 2));
         // Calculate the difference between the two conversion dates to get the change
         $conversionChangePercent = $thisConversion - $lastConversion;
         $prefix = '';
         if ($conversionChangePercent > 0) {
             $prefix = '+';
             $this->template->Assign('ConversionChangeClass', 'Positive');
         } else {
             if ($conversionChangePercent < 0) {
                 $this->template->Assign('ConversionChangeClass', 'Negative');
             }
         }
         $conversionChangePercent = $prefix . number_format($conversionChangePercent, 2) . '%';
         $this->template->Assign('ConversionChange', $conversionChangePercent);
     } else {
         $this->template->Assign('HideConversionRate', 'display: none');
         $this->template->Assign('HideVisitorStats', 'display: none');
     }
     // Calculate the percentage change in revenue between the last period and the current period
     $revenueChange = $thisPeriodOrderStats['totalrevenue'] - $lastPeriodOrderStats['totalrevenue'];
     $prefix = '';
     if ($revenueChange == 0) {
         $revenueChangePercent = 0;
     } else {
         if ($lastPeriodOrderStats['totalrevenue'] > 0) {
             $revenueChangePercent = round($revenueChange / $lastPeriodOrderStats['totalrevenue'] * 100, 2);
         } else {
             $revenueChangePercent = 100;
         }
     }
     if ($revenueChangePercent > 0) {
         $prefix = '+';
         $this->template->Assign('TotalRevenueChangeClass', 'Positive');
     } else {
         if ($revenueChangePercent < 0) {
             $this->template->Assign('TotalRevenueChangeClass', 'Negative');
         }
     }
     $revenueChangePercent = $prefix . number_format($revenueChangePercent, 2) . '%';
     // Calculate the percentage change in the number of orders in the last period and the current period
     $numOrdersChange = $thisPeriodOrderStats['numorders'] - $lastPeriodOrderStats['numorders'];
     $prefix = '';
     if ($numOrdersChange == 0) {
         $numOrdersChangePercent = 0;
     } else {
         if ($lastPeriodOrderStats['numorders'] > 0) {
             $numOrdersChangePercent = round($numOrdersChange / $lastPeriodOrderStats['numorders'] * 100, 2);
         } else {
             $numOrdersChangePercent = 100;
         }
     }
     if ($numOrdersChangePercent > 0) {
         $prefix = '+';
         $this->template->Assign('NumOrdersChangeClass', 'Positive');
     } else {
         if ($numOrdersChangePercent < 0) {
             $this->template->Assign('NumOrdersChangeClass', 'Negative');
         }
     }
     $numOrdersChangePercent = $prefix . number_format($numOrdersChangePercent, 2) . '%';
     $this->template->Assign('LastPeriodRevenue', FormatPrice($lastPeriodOrderStats['totalrevenue']));
     $this->template->Assign('LastPeriodNumOrders', number_format($lastPeriodOrderStats['numorders']));
     $this->template->Assign('ThisPeriodRevenue', FormatPrice($thisPeriodOrderStats['totalrevenue']));
     $this->template->Assign('ThisPeriodNumOrders', number_format($thisPeriodOrderStats['numorders']));
     $this->template->Assign('TotalRevenueChange', $revenueChangePercent);
     $this->template->Assign('NumOrdersChange', $numOrdersChangePercent);
     // If they've just changed periods, store it in a cookie
     if (isset($_GET['period'])) {
         isc_setcookie('DashboardPerformanceIndicatorsPeriod', $period);
     }
     return $this->template->GetSnippet('DashboardPerformanceIndicators');
 }
예제 #12
0
 public function PreviewNews()
 {
     // Print a packing slip for an order
     ob_end_clean();
     if (isset($_GET['newsId'])) {
         $newsId = $_GET['newsId'];
         $newsId = (int) $newsId;
         // Get the details for this news post from the database
         $query = sprintf("select * from [|PREFIX|]news where newsid='%d'", $GLOBALS['ISC_CLASS_DB']->Quote($newsId));
         $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
         if ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) {
             $GLOBALS['Title'] = $row['newstitle'];
             $GLOBALS['Content'] = $row['newscontent'];
             $GLOBALS['NewsDate'] = CDate($row['newsdate']);
             $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("news.preview");
             $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
             die;
         } else {
             echo "<script type=\"text/javascript\">window.close();</script>";
         }
     } else {
         echo "<script type=\"text/javascript\">window.close();</script>";
     }
 }
예제 #13
0
 /**
  * Create the pending order in the database with the customers selected payment details, etc.
  *
  * @return array An array containing information about what needs to be done next.
  */
 public function SavePendingOrder()
 {
     $provider = null;
     $verifyPaymentProvider = true;
     $redirectToFinishOrder = false;
     $providerId = '';
     $pendingOrderResult = array();
     if (!isset($_SESSION['CHECKOUT']['PENDING_DATA'])) {
         return false;
     }
     // Did they agree to signup to any mailing lists?
     if (isset($_POST['join_mailing_list'])) {
         ISC_SetCookie("JOIN_MAILING_LIST", 1, time() + 3600 * 24 * 7);
     }
     if (isset($_POST['join_order_list'])) {
         ISC_SetCookie("JOIN_ORDER_LIST", 1, time() + 3600 * 24 * 7);
     }
     $orderTotal = $_SESSION['CHECKOUT']['PENDING_DATA']['ORDER_TOTAL'];
     $giftCertificateAmount = $_SESSION['CHECKOUT']['PENDING_DATA']['GIFTCERTIFICATE_AMOUNT'];
     $gatewayAmount = $_SESSION['CHECKOUT']['PENDING_DATA']['GATEWAY_AMOUNT'];
     $creditUsed = 0;
     $giftCertificates = array();
     // Find out what currency we are using. We'll need this later to display their previous orders in the currency that they have selected
     $selectedCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);
     if (isset($_SESSION['OFFERCART']['GIFTCERTIFICATES']) && is_array($_SESSION['OFFERCART']['GIFTCERTIFICATES'])) {
         $giftCertificates = $_SESSION['OFFERCART']['GIFTCERTIFICATES'];
         // Now we check that the gift certificates can actually be applied to the order
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES');
         $badCertificates = array();
         $remainingBalance = 0;
         $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->GiftCertificatesApplicableToOrder($orderTotal, $giftCertificates, $remainingBalance, $badCertificates);
         // One or more gift certificates were invalid so this order is now invalid
         if (count($badCertificates) > 0) {
             $badCertificatesList = '<strong>' . GetLang('BadGiftCertificates') . '</strong><ul>';
             foreach ($badCertificates as $code => $reason) {
                 if (is_array($reason) && $reason[0] == "expired") {
                     $reason = sprintf(GetLang('BadGiftCertificateExpired'), CDate($reason[1]));
                 } else {
                     $reason = GetLang('BadGiftCertificate' . ucfirst($reason));
                 }
                 $badCertificatesList .= sprintf("<li>%s - %s", isc_html_escape($code), $reason);
             }
             $badCertificatesList .= "</ul>";
             $pendingOrderResult = array('error' => GetLang('OrderContainedInvalidGiftCertificates'), 'errorDetails' => $badCertificatesList);
             return $pendingOrderResult;
         } else {
             if ($orderTotal == $giftCertificateAmount && $remainingBalance > 0) {
                 $pendingOrderResult = array('error' => GetLang('OrderTotalStillRemainingCertificates'));
                 return $pendingOrderResult;
             } else {
                 if ($orderTotal == $giftCertificateAmount) {
                     $providerId = 'giftcertificate';
                     $verifyPaymentProvider = false;
                     $redirectToFinishOrder = true;
                 }
             }
         }
     }
     // If the order total is 0, then we just forward the user on to the "Thank You" page and set the payment provider to ''
     if ($orderTotal == 0) {
         $providerId = '';
         $verifyPaymentProvider = false;
         $redirectToFinishOrder = true;
     }
     if ($verifyPaymentProvider) {
         if (isset($_POST['credit_checkout_provider']) && $_POST['credit_checkout_provider'] != "") {
             $_POST['checkout_provider'] = $_POST['credit_checkout_provider'];
         }
         $selected_provider = "";
         $providers = GetCheckoutModulesThatCustomerHasAccessTo(true);
         // If there's more than one, use the value they've chosen
         if (count($providers) > 1 && isset($_POST['checkout_provider']) || isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
             $selected_provider = $_POST['checkout_provider'];
         } else {
             if (count($providers) == 1) {
                 $selected_provider = $providers[0]['object']->GetId();
                 $_POST['checkout_provider'] = $selected_provider;
             } else {
                 $selected_provider = '';
             }
         }
         if (!isset($_POST['checkout_provider'])) {
             $_POST['checkout_provider'] = '';
         }
         // Are we using our store credit?
         $GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
         $customer = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerDataByToken();
         if (isset($_POST['store_credit']) && $_POST['store_credit'] == 1 && $customer['custstorecredit'] > 0) {
             // User has not chosen a payment provider and can't afford this order using only store credit, throw back as error
             if (!$_POST['checkout_provider'] && $customer['custstorecredit'] < $orderTotal) {
                 return false;
             } else {
                 $onlyCredit = false;
                 $updateExtra = '';
                 // If we're only using store credit
                 $creditToUse = $orderTotal - $giftCertificateAmount;
                 if ($customer['custstorecredit'] >= $creditToUse) {
                     // Set the checkout provider
                     $providerId = 'storecredit';
                     $verifyPaymentProvider = false;
                     $redirectToFinishOrder = true;
                     $creditUsed = $creditToUse;
                     $onlyCredit = true;
                 } else {
                     // Using all of our store credit to pay for this order and we owe more.
                     $creditUsed = $customer['custstorecredit'];
                     $gatewayAmount -= $creditUsed;
                 }
             }
         }
     }
     // Now with round 2, do we still need to verify the payment provider?
     if ($verifyPaymentProvider) {
         // If there's more than one provider and one wasn't selected on the order confirmation screen then there's a problem
         if ((count($providers) == 0 || count($providers) > 1 && !isset($_POST['checkout_provider'])) && !isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
             return false;
         }
         // Is the payment provider selected actually valid?
         if (!GetModuleById('checkout', $provider, $selected_provider)) {
             return false;
         }
         $providerId = $provider->GetId();
     }
     // Load up all of the data for the items in the cart
     $GLOBALS['ISC_CLASS_MAKEAOFFER'] = GetClass('ISC_MAKEAOFFER');
     $cartItems = $GLOBALS['ISC_CLASS_MAKEAOFFER']->api->GetProductsInCart();
     // OK, we're successful down to here - do they want to create an account?
     if (isset($_SESSION['CHECKOUT']['CREATE_ACCOUNT'])) {
         $accountDetails = $_SESSION['CHECKOUT']['ACCOUNT_DETAILS'];
         $token = GenerateCustomerToken();
         $customerData = array('email' => trim($accountDetails['email']), 'password' => $accountDetails['password'], 'firstname' => $accountDetails['firstname'], 'lastname' => $accountDetails['lastname'], 'company' => $accountDetails['company'], 'phone' => $accountDetails['phone'], 'token' => $token);
         //alandy modify.2011-5-20.
         /*$sql="select customerid from [|PREFIX|]customers where custconemail='".$accountDetails['email']."'";
         		$query=$GLOBALS['ISC_CLASS_DB']->Query($sql);
         		while($rs=$GLOBALS['ISC_CLASS_DB']->Fetch($query)){
         		    $GLOBALS['Hasemailflag']="yes";
         		      return array(
         				    'error' => GetLang('AccountInternalError')
         			    );
         			    
         	        }*/
         $cusquery = "SELECT customerid\n\t\t\t\tFROM [|PREFIX|]customers\n\t\t\t\tWHERE isguest = 1 AND LOWER(custconemail)='" . $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($customerData['email'])) . "'";
         $cusresult = $GLOBALS['ISC_CLASS_DB']->Query($cusquery);
         $cusrow = $GLOBALS['ISC_CLASS_DB']->Fetch($cusresult);
         $custId = $cusrow['customerid'];
         if ($custId == '') {
             // 20110613 johnny add ---- add flag for guest user email don't exist
             if ($_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
                 $customerData['isguest'] = 1;
             }
             $customerId = $GLOBALS['ISC_CLASS_CUSTOMER']->CreateCustomerAccount($customerData, false, $accountDetails['autoAccount']);
         } else {
             if (!$_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
                 $customerId = $GLOBALS['ISC_CLASS_CUSTOMER']->CreateCustomerAccount($customerData, true, $accountDetails['autoAccount']);
                 /* delet already exist guest account
                 			$entity = new ISC_ENTITY_CUSTOMER();
                 			$entity->delete($custId);
                 			*/
             } else {
                 $customerId = $custId;
                 // update guest account in customer table for guest user email exist
                 $GLOBALS['ISC_CLASS_DB']->Query("UPDATE [|PREFIX|]customers SET custconfirstname = '" . $customerData['firstname'] . "', custconlastname = '" . $customerData['lastname'] . "' WHERE customerid = {$customerId}");
             }
         }
         if (!$customerId) {
             return array('error' => GetLang('AccountInternalError'));
         }
         if (!$_SESSION['CHECKOUT']['PENDING_DATA']['GUEST_CHECKOUT']) {
             $GLOBALS['ISC_CLASS_CUSTOMER']->LoginCustomerById($customerId, true);
         }
         unset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']);
         unset($_SESSION['CHECKOUT']['ACCOUNT_DETAILS']);
         // Log the customer in
         @ob_end_clean();
     }
     if (isset($_COOKIE['SHOP_TOKEN'])) {
         $customerToken = $_COOKIE['SHOP_TOKEN'];
     } else {
         $customerToken = '';
     }
     $orderComments = '';
     if (isset($_REQUEST['ordercomments'])) {
         $orderComments = $_REQUEST['ordercomments'];
     }
     $checkoutSession = $_SESSION['CHECKOUT'];
     $pendingData = $checkoutSession['PENDING_DATA'];
     // Get a list of the vendors for all of the items in the cart, and loop through them
     // to build all of the pending orders
     $cartContent = $this->BreakdownCartByAddressVendorforshipping();
     //Changed to merging function by Simha
     $vendorOrderInfo = array();
     foreach ($cartContent as $vendorId => $addresses) {
         foreach ($addresses as $addressId => $products) {
             $allDigital = 1;
             $productArray = array();
             foreach ($products as $cartItemId => $product) {
                 // A physical product, mark as so
                 if ($product['data']['prodtype'] == PT_PHYSICAL) {
                     $allDigital = 0;
                 }
                 // Mark the quantity of this item
                 $productArray[$cartItemId] = $product['quantity'];
             }
             $vendorInfo = $pendingData['VENDORS'][$vendorId . '_' . $addressId];
             $vendorData = array('itemtotal' => $vendorInfo['ITEM_TOTAL'], 'taxcost' => $vendorInfo['TAX_COST'], 'taxname' => $vendorInfo['TAX_NAME'], 'taxrate' => $vendorInfo['TAX_RATE'], 'totalcost' => $vendorInfo['ORDER_TOTAL'], 'shippingcost' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['COST'], 'handlingcost' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['HANDLING'], 'shippingprovider' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['PROVIDER'], 'shippingmodule' => @$_SESSION['CHECKOUT']['SHIPPING'][$vendorId][$addressId]['MODULE'], 'isdigitalorder' => $allDigital, 'products' => $productArray);
             if ($addressId == 0) {
                 $addresses = $this->GetOrderShippingAddresses();
                 $vendorData['shippingaddress'] = $addresses[$addressId];
             } else {
                 $vendorData['shippingaddressid'] = $addressId;
             }
             // Shipping zones can be configured per vendor, so we need to be sure
             // to pass this along correctly too
             if (isset($vendorInfo['SHIPPING_ZONE'])) {
                 $shippingZone = GetShippingZoneById($vendorInfo['SHIPPING_ZONE']);
                 if (is_array($shippingZone)) {
                     $vendorData['ordshippingzoneid'] = $shippingZone['zoneid'];
                     $vendorData['ordshippingzone'] = $shippingZone['zonename'];
                 }
             }
             $vendorOrderInfo[$vendorId . '_' . $addressId] = $vendorData;
         }
     }
     // Set some defaults about the rest of the order
     $pendingOrder = array("customertoken" => $customerToken, 'paymentmethod' => $providerId, "storecreditamount" => $creditUsed, "giftcertificateamount" => $giftCertificateAmount, "giftcertificates" => $giftCertificates, "gatewayamount" => $gatewayAmount, 'totalincludestax' => $pendingData['TAX_INCLUDED'], "currencyid" => $selectedCurrency['currencyid'], "currencyexchangerate" => $selectedCurrency['currencyexchangerate'], 'ordercomments' => $orderComments, 'ipaddress' => GetIP(), 'vendorinfo' => $vendorOrderInfo);
     if (isset($customerId)) {
         $pendingOrder['customerid'] = $customerId;
     }
     // Determine the address ID we're using for billing
     if (is_array($_SESSION['CHECKOUT']['BILLING_ADDRESS'])) {
         $pendingOrder['billingaddress'] = $_SESSION['CHECKOUT']['BILLING_ADDRESS'];
     } else {
         $pendingOrder['billingaddressid'] = (int) $_SESSION['CHECKOUT']['BILLING_ADDRESS'];
     }
     if (isset($_POST['ordermessage'])) {
         $pendingOrder['ordermessage'] = $_POST['ordermessage'];
     } else {
         $pendingOrder['ordermessage'] = '';
     }
     /**
      * Save our custom fields. If we are creating a new account then split this up so the
      * account fields will go in the customers table and the rest will go in the orders table
      */
     if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['customer']) && isset($customerId) && isId($customerId)) {
         $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['customer']);
         if (isId($formSessionId)) {
             $updateData = array('customerid' => $customerId, 'email' => $customerData['email'], 'firstname' => $customerData['firstname'], 'lastname' => $customerData['lastname'], 'company' => $customerData['company'], 'phone' => $customerData['phone'], 'custformsessionid' => $formSessionId);
             $entity = new ISC_ENTITY_CUSTOMER();
             $entity->edit($updateData);
         }
     }
     /**
      * OK, now to store the custom address fields. Check here to see if we are not split
      * shipping (single order)
      */
     if (!isset($_SESSION['CHECKOUT']['IS_SPLIT_SHIPPING']) || !$_SESSION['CHECKOUT']['IS_SPLIT_SHIPPING']) {
         $pendingOrder['ordformsessionid'] = '';
         if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS'])) {
             /**
              * Save the billing
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && isset($pendingOrder['billingaddress']['saveAddress']) && $pendingOrder['billingaddress']['saveAddress']) {
                 $pendingOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']);
             }
             /**
              * Now for the shipping. Only save this once for all the shipping addresses
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'])) {
                 $shippSessId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping']);
                 foreach ($pendingOrder['vendorinfo'] as $vendorId => $vendorData) {
                     if (isset($vendorData['shippingaddress']['saveAddress']) && $vendorData['shippingaddress']['saveAddress']) {
                         $pendingOrder['vendorinfo'][$vendorId]['shippingaddress']['shipformsessionid'] = $shippSessId;
                     }
                 }
             }
             /**
              * Now the orders. This part is tricky because the billing and shipping information
              * have the same keys (same fields used in the frontend). We need to split them up
              * into separate billing and shipping information and then save it
              */
             if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'])) {
                 /**
                  * We create a map first so we can map the shipping information to its proper field
                  * ID
                  */
                 $billingKeys = array_keys($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']);
                 $fieldAddressMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_BILLING, $billingKeys);
                 /**
                  * OK, we have the map, now to split up the custom fields
                  */
                 $orderSessData = array();
                 foreach ($fieldAddressMap as $fieldId => $newShippingFieldId) {
                     $orderSessData[$fieldId] = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'][$fieldId];
                     if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'][$fieldId])) {
                         $orderSessData[$newShippingFieldId] = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['shipping'][$fieldId];
                     }
                 }
                 $pendingOrder['ordformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($orderSessData);
             }
         }
         /**
          * This is for split shipping. Loop through each address to get their default custom
          * field data, combine it with the billing custom field data, create the form session
          * record and then save that ID for each address
          */
     } else {
         $shippingAddresses = $this->GetOrderShippingAddresses();
         $origFormSessionData = array();
         if (isset($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing']) && is_array($_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'])) {
             $origFormSessionData = $_SESSION['CHECKOUT']['CUSTOM_FIELDS']['billing'];
         }
         foreach ($pendingOrder['vendorinfo'] as $vendorId => $vendorData) {
             $address = null;
             $orderSessData = array();
             if (array_key_exists($vendorData['shippingaddressid'], $shippingAddresses)) {
                 $address = $shippingAddresses[$vendorData['shippingaddressid']];
             }
             if (isset($address['shipformsessionid']) && isId($address['shipformsessionid'])) {
                 $shippingSessionData = $GLOBALS['ISC_CLASS_FORM']->getSavedSessionData($address['shipformsessionid']);
                 if (is_array($shippingSessionData)) {
                     /**
                      * Same deal with this save session data because the billing and shipping data
                      * use the same fields and therefore have the same keys
                      */
                     $billingKeys = array_keys($origFormSessionData);
                     $fieldAddressMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_BILLING, $billingKeys);
                     /**
                      * OK, we have the map, now to split up the custom fields
                      */
                     $orderSessData = array();
                     foreach ($fieldAddressMap as $fieldId => $newShippingFieldId) {
                         $orderSessData[$fieldId] = $origFormSessionData[$fieldId];
                         $orderSessData[$newShippingFieldId] = $shippingSessionData[$fieldId];
                     }
                 }
             }
             $newFormSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($orderSessData);
             if (isId($newFormSessionId)) {
                 $pendingOrder['vendorinfo'][$vendorId]['ordformsessionid'] = $newFormSessionId;
             }
         }
     }
     $pendingToken = CreateOrder($pendingOrder, $cartItems);
     // Try to add the record and if we can't then take them back to the shopping cart
     if (!$pendingToken) {
         return false;
     }
     // Persist the pending order token as a cookie for 24 hours
     ISC_SetCookie("SHOP_ORDER_TOKEN", $pendingToken, time() + 3600 * 24, true);
     $_COOKIE['SHOP_ORDER_TOKEN'] = $pendingToken;
     // Redirecting to finish order page?
     if ($redirectToFinishOrder) {
         return array('redirectToFinishOrder' => true);
     }
     $orderData = LoadPendingOrdersByToken($pendingToken);
     // Otherwise, the gateway want's to do something
     $provider->SetOrderData($orderData);
     // Is this an online payment provider? It would like to do something
     if ($provider->GetPaymentType() == PAYMENT_PROVIDER_ONLINE || method_exists($provider, "ShowPaymentForm")) {
         // Call the checkout process for the selected provider
         if (method_exists($provider, "ShowPaymentForm")) {
             return array('provider' => $provider, 'showPaymentForm' => true);
         } else {
             return array('provider' => $provider);
         }
     } else {
         return array('provider' => $provider);
     }
 }
예제 #14
0
    /**
     * Showing the customer review for the order.
     */
    public function ViewOrderReview()
    {
        if (!isset($_REQUEST['orderId'])) {
            exit;
        }
        $order = GetOrder($_REQUEST['orderId'], true);
        if (!isset($order['orderid']) || $order['ordisdigital'] == 1 || $order['ordtotalqty'] - $order['ordtotalshipped'] <= 0) {
            exit;
        }
        $GLOBALS['OrderId'] = $order['orderid'];
        $GLOBALS['OrderDate'] = CDate($order['orddate']);
        $GLOBALS['ReviewContent'] = '<tr><th>ProductId</th><th>ProductName</th><th>ReviewText</th><th>ReviewRating</th></tr>';
        $resultCnt = 0;
        $query = "\n                SELECT r.*, p.productid, p.prodname\n\t\t\t\tFROM [|PREFIX|]reviews r\n\t\t\t\tLEFT JOIN [|PREFIX|]products p ON (p.productid=r.revproductid)\n\t\t\t\tLEFT JOIN [|PREFIX|]order_products o ON (o.ordprodid=p.productid)\n\t\t\t\tWHERE o.orderorderid='" . $GLOBALS['OrderId'] . "'\n\t\t\t\tAND r.orderid='" . $GLOBALS['OrderId'] . "'\n\t\t\t\tAND r.reviewtype=1\n\t\t\t\tORDER BY revdate DESC";
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            if (isc_strlen($row['prodname']) > 100) {
                $prodName = isc_html_escape(sprintf("%s...", isc_substr($row['prodname'], 0, 100)));
            } else {
                $prodName = isc_html_escape($row['prodname']);
            }
            if (isc_strlen($row['revtext']) > 100) {
                $reviewText = isc_html_escape(sprintf("%s...", isc_substr($row['revtext'], 0, 100)));
            } else {
                if (isc_strlen($row['revtext']) == 0) {
                    $reviewText = '[no comment]';
                } else {
                    $reviewText = isc_html_escape($row['revtext']);
                }
            }
            $resultCnt++;
            $reviewRate = sprintf("<img width=\"64\" height=\"12\" src=\"%s/images/IcoRating%s.gif\" alt=\"\" />", $GLOBALS['TPL_PATH'], $row['revrating']);
            $GLOBALS['ReviewContent'] .= '<tr><td>' . $row['productid'] . '</td><td>' . $prodName . '</td><td>' . $reviewText . '</td><td>' . $reviewRate . '</td></tr>';
        }
        if ($resultCnt == 0) {
            $GLOBALS['ReviewContent'] = '<tr>
												<td class="ReviewContent">
													' . GetLang('NoReviewReceived') . '
												</td>
											 </tr>';
        }
        //$GLOBALS['ShowApprove'] = '';
        $GLOBALS['ShowApprove'] = 'none';
        $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate('order.review');
        return $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
    }
예제 #15
0
	/**
	 * Called by the export task at the end of an export. Updates the
	 * date and time of the last generated export if this is the active
	 * export task.
	 *
	 * @param object The job controller passed by the export task.
	 */
	public function exportEnd($controller)
	{
		if($this->getCurrentExportId() != $controller->getId())
			return;

		$date = CDate(time());
		$time = isc_date('h:i a', time());

		$this->setLastExportDetails($date, $time);
		$this->clearCurrentExportId();

		$this->logSuccess(
				getLang('ShoppingComparisonExportJobComplete',
					array("name" => $this->getName())
				)
		);
	}
 public function ManageReviewsGrid(&$numReviews)
 {
     // Show a list of reviews in a table
     $page = 0;
     $start = 0;
     $numReviews = 0;
     $numPages = 0;
     $GLOBALS['ReviewGrid'] = "";
     $GLOBALS['Nav'] = "";
     $max = 0;
     $searchURL = '';
     $filterURL = '';
     //Added by Simha
     if (isset($_GET['brandid'])) {
         $filterURL .= "&amp;brandid=" . trim($_GET['brandid']) . "";
     }
     if (isset($_GET['seriesid'])) {
         $filterURL .= "&amp;seriesid=" . trim($_GET['seriesid']) . "";
     }
     //Added by Simha Ends
     if (isset($_GET['searchQuery'])) {
         $query = $_GET['searchQuery'];
         $GLOBALS['Query'] = $query;
         $searchURL = sprintf("&amp;searchQuery=%s", urlencode($query));
     } else {
         $query = "";
         $GLOBALS['Query'] = "";
     }
     if (isset($_GET['sortOrder']) && $_GET['sortOrder'] == 'desc') {
         $sortOrder = 'asc';
     } else {
         $sortOrder = "desc";
     }
     $sortLinks = array("Review" => "r.revtitle", "Name" => "p.prodname", "By" => "r.revfromname", "Rating" => "r.revrating", "Date" => "r.revdate", "Status" => "r.revstatus");
     if (isset($_GET['sortField']) && in_array($_GET['sortField'], $sortLinks)) {
         $sortField = $_GET['sortField'];
         SaveDefaultSortField("ManageReviews", $_REQUEST['sortField'], $sortOrder);
     } else {
         list($sortField, $sortOrder) = GetDefaultSortField("ManageReviews", "r.reviewid", $sortOrder);
     }
     if (isset($_GET['page'])) {
         $page = (int) $_GET['page'];
     } else {
         $page = 1;
     }
     $GLOBALS['Page'] = $page;
     $sortURL = sprintf("&sortField=%s&sortOrder=%s", $sortField, $sortOrder);
     $GLOBALS['SortURL'] = $sortURL;
     // Limit the number of questions returned
     if ($page == 1) {
         $start = 1;
     } else {
         $start = $page * ISC_REVIEWS_PER_PAGE - (ISC_REVIEWS_PER_PAGE - 1);
     }
     $start = $start - 1;
     // Get the results for the query
     $reviewResult = $this->_GetReviewList($query, $start, $sortField, $sortOrder, $numReviews);
     $numPages = ceil($numReviews / ISC_REVIEWS_PER_PAGE);
     // Add the "(Page x of n)" label
     if ($numReviews > ISC_REVIEWS_PER_PAGE) {
         $GLOBALS['Nav'] = sprintf("(%s %d of %d) &nbsp;&nbsp;&nbsp;", GetLang('Page'), $page, $numPages);
         $GLOBALS['Nav'] .= BuildPagination($numReviews, ISC_REVIEWS_PER_PAGE, $page, sprintf("index.php?ToDo=viewReviews%s%s%s", $sortURL, $filterURL, $searchURL));
     } else {
         $GLOBALS['Nav'] = "";
     }
     $GLOBALS['Nav'] = rtrim($GLOBALS['Nav'], ' |');
     $GLOBALS['SearchQuery'] = $query;
     $GLOBALS['SortField'] = $sortField;
     $GLOBALS['SortOrder'] = $sortOrder;
     BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewReviews&amp;" . $searchURL . "&amp;page=" . $page . $filterURL, $sortField, $sortOrder);
     // Workout the maximum size of the array
     $max = $start + ISC_REVIEWS_PER_PAGE;
     if ($max > $numReviews) {
         $max = $numReviews;
     }
     if ($numReviews > 0) {
         // Display the reviews
         while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($reviewResult)) {
             $GLOBALS['ReviewId'] = $row['reviewid'];
             $GLOBALS['ProdName'] = isc_html_escape($row['prodname']);
             $GLOBALS['ProdLink'] = ProdLink($row['prodname']);
             if (isc_strlen($row['revtext']) > 100) {
                 $GLOBALS['ReviewTitle'] = isc_html_escape(sprintf("%s...", isc_substr($row['revtitle'], 0, 100)));
             } else {
                 $GLOBALS['ReviewTitle'] = isc_html_escape($row['revtitle']);
             }
             $GLOBALS['Rating'] = "";
             $ratingText = sprintf(GetLang('ReviewRated'), $row['revrating']);
             for ($r = 0; $r < $row['revrating']; $r++) {
                 $GLOBALS['Rating'] .= sprintf("<img title='%s' width='13' height='12' src='images/rating_on.gif'>", $ratingText);
             }
             for ($r = $row['revrating']; $r < 5; $r++) {
                 $GLOBALS['Rating'] .= sprintf("<img title='%s' width='13' height='12' src='images/rating_off.gif'>", $ratingText);
             }
             if ($row['revfromname'] != "") {
                 $GLOBALS['PostedBy'] = isc_html_escape($row['revfromname']);
             } else {
                 $GLOBALS['PostedBy'] = GetLang('NA');
             }
             $GLOBALS['Date'] = CDate($row['revdate']);
             $GLOBALS['PreviewLink'] = sprintf("<a title='%s' href='javascript:PreviewReview(%d)'>%s</a>", GetLang('PreviewReview'), $row['reviewid'], GetLang('Preview'));
             if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Edit_Reviews)) {
                 $GLOBALS['EditLink'] = sprintf("<a title='%s' href='index.php?ToDo=editReview&amp;reviewId=%d'>%s</a>", GetLang('EditReview'), $row['reviewid'], GetLang('Edit'));
             } else {
                 $GLOBALS['EditLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit'));
             }
             switch ($row['revstatus']) {
                 case "0":
                     $GLOBALS['Status'] = GetLang('Pending');
                     break;
                 case "1":
                     $GLOBALS['Status'] = sprintf("<font color='green'>%s</font>", GetLang('Approved'));
                     break;
                 case "2":
                     $GLOBALS['Status'] = sprintf("<font color='red'>%s</font>", GetLang('Disapproved'));
                     break;
             }
             $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("reviews.manage.row");
             $GLOBALS['ReviewGrid'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
         }
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("reviews.manage.grid");
         return $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
     }
 }
예제 #17
0
 function grava_dados()
 {
     if (!$this->check_dados()) {
         return;
     }
     $db = new Database($this, false);
     if (!$db->link) {
         return;
     }
     $usuario = $this->usuario->get_text();
     $nome = $this->nome->get_text();
     $senha = $this->senha->get_text();
     $endereco = $this->endereco->get_text();
     $bairro = $this->bairro->get_text();
     $cep = $this->cep->get_text();
     $cidade = $this->cidade->get_text();
     $cpf = $this->cpf->get_text();
     $rg = $this->rg->get_text();
     $dependentes = $this->dependentes->get_text();
     $filhos = $this->filhos->get_text();
     $cracha = $this->cracha->get_text();
     $email = $this->email->get_text();
     $tel = $this->tel->get_text();
     $cel = $this->cel->get_text();
     $data_nasc = CDate($this->data_nasc->get_text());
     $data_adm = CDate($this->data_adm->get_text());
     $data_homo = CDate($this->data_homo->get_text());
     $data_resc = CDate($this->data_resc->get_text());
     if ($this->operacao == 'i') {
         $sql = 'call SP_Usuario_Inc';
     } else {
         $sql = 'call SP_Usuario_Alt';
     }
     $data = $sql . '(' . String($this->CodUsuario) . ',' . String($this->filial->CodFilial) . ',' . String($this->estado->CodEstado) . ',' . String($this->est_civil->CodEstCivil) . ',' . String($this->perfil->CodPerfil) . ',' . String($usuario) . ',' . String($nome) . ',' . String($this->ativo->get_active()) . ',' . String($endereco) . ',' . String($bairro) . ',' . String($cep) . ',' . String($cidade) . ',' . String($cpf) . ',' . String($rg) . ',' . String($data_nasc) . ',' . String($this->sexo->CodSexo) . ',' . String($dependentes) . ',' . String($filhos) . ',' . String($this->depto->CodDepto) . ',' . String($this->cargo->CodCargo) . ',' . String($cracha) . ',' . String($tel) . ',' . String($cel) . ',' . String($email) . ',' . String($data_adm) . ',' . String($data_homo) . ',' . String($data_resc) . ',' . $GLOBALS['CodUsuario'] . ');';
     if (!$db->multi_query($data)) {
         return;
     }
     $line = $db->line();
     $CodUsuario = $line['CodUsuario'];
     $mensagem = $line['Mensagem'];
     // limpa BUFFER
     while ($db->line()) {
     }
     if ($this->alterar_senha->get_active()) {
         if (!$CodUsuario) {
             $CodUsuario = $this->CodUsuario;
         }
         $sql = ' UPDATE Tb_Usuarios SET Senha = ' . String(md5($usuario . '@' . $senha)) . ' WHERE Cod_S_Usuario = ' . $CodUsuario;
         $db->query($sql);
     }
     new Message($this, $mensagem);
     return true;
 }
예제 #18
0
	/**
	 * Show the form to create a new shipment from one or more items in an order.
	 */
	public function CreateShipment()
	{
		if(!isset($_REQUEST['orderId'])) {
			exit;
		}

		$order = GetOrder($_REQUEST['orderId']);
		if(!$order || !isset($order['orderid'])) {
			exit;
		}

		if ($order['ordisdigital'] == 1) {
			$this->template->display('modal.basic.tpl', array(
				'title' => GetLang('CreateShipmentFromOrder'),
				'message' => GetLang('DigitalOrderNoShipping'),
			));
			exit;
		}

		if ($order['ordtotalqty'] - $order['ordtotalshipped'] <= 0) {
			$this->template->display('modal.basic.tpl', array(
				'title' => GetLang('CreateShipmentFromOrder'),
				'message' => GetLang('AllItemsShipped'),
			));
			exit;
		}

		if(empty($_REQUEST['addressId'])) {
			$addressWhere = 'order_id='.$order['orderid'];
		}
		else {
			$addressWhere = 'order_id='.$order['orderid'].' AND id='.(int)$_REQUEST['addressId'];
		}

		// Fetch the address associated with this order
		$query = "
			SELECT *
			FROM [|PREFIX|]order_addresses
			WHERE ".$addressWhere."
			LIMIT 1
		";
		$result = $this->db->query($query);
		$address = $this->db->fetch($result);
		if(!$address) {
			exit;
		}
		$query = "
			SELECT *
			FROM [|PREFIX|]order_shipping
			WHERE order_address_id='".$address['id']."'
		";
		$result = $this->db->query($query);
		$shipping = $this->db->fetch($result);

		$this->template->assign('address', $address);
		$this->template->assign('shipping', $shipping);

		$shipmentModules = array();
		$shippingModules = getAvailableModules('shipping');
		foreach($shippingModules as $module) {
			$shipmentModules[$module['id']] = $module['object']->getName();
		}

		$this->template->assign('shippingModules', $shipmentModules);

		$GLOBALS['OrderId'] = $order['orderid'];
		$GLOBALS['OrderDate'] = CDate($order['orddate']);
		$GLOBALS['ShippingMethod'] = isc_html_escape($shipping['method']);
		$GLOBALS['OrderComments'] = isc_html_escape($order['ordcustmessage']);

		// Fetch out any items that have already been shipped for this order
		$shippedItems = array();
		$query = "
			SELECT itemid, itemqty, itemordprodid
			FROM [|PREFIX|]shipment_items i
			INNER JOIN [|PREFIX|]shipments s ON (
				s.shiporderid='".(int)$order['orderid']."' AND
				i.shipid=s.shipmentid
			)
			INNER JOIN [|PREFIX|]order_products op ON (op.orderprodid = i.itemordprodid)
			WHERE op.order_address_id='".$address['id']."'
		";

		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		while($shippedItem = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			if(!isset($shippedItems[$shippedItem['itemordprodid']])) {
				$shippedItems[$shippedItem['itemordprodid']] = 0;
			}
			$shippedItems[$shippedItem['itemordprodid']] += $shippedItem['itemqty'];
		}

		// OK, now loop through all of the items going to this address and see what we can ship
		$query = "
			SELECT *
			FROM [|PREFIX|]order_products
			WHERE order_address_id='".$address['id']."'
		";
		$result = $this->db->query($query);
		$GLOBALS['ProductList'] = '';
		while($product = $this->db->fetch($result)) {
			$shippableQuantity = $product['ordprodqty'];
			if(isset($shippedItems[$product['orderprodid']])) {
				$shippableQuantity = $product['ordprodqty'] - $shippedItems[$product['orderprodid']];
			}

			// Completely skip over this item if there's nothing to ship
			if($shippableQuantity <= 0 || $product['ordprodtype'] != 'physical') {
				continue;
			}

			$doneProducts = true;
			$GLOBALS['ProductName'] = isc_html_escape($product['ordprodname']);
			$GLOBALS['ProductId'] = $product['ordprodid'];

			$GLOBALS['HideGiftWrapping'] = 'display: none';
			$GLOBALS['WrappingName'] = '';
			$GLOBALS['WrappingMessage'] = '';
			if($product['ordprodwrapid'] > 0) {
				$GLOBALS['HideGiftWrapping'] = '';
				$GLOBALS['WrappingName'] = isc_html_escape($product['ordprodwrapname']);
				if($product['ordprodwrapmessage']) {
					$GLOBALS['WrappingMessage'] = nl2br(isc_html_escape($product['ordprodwrapmessage']));
				}
				else {
					$GLOBALS['HideGiftWrappingMessage'] = 'display: none';
				}
			}

			// Show the quantity as a dropdown
			if(GetConfig('TagCartQuantityBoxes') == 'dropdown') {
				$GLOBALS['QuantityInput'] = '<select class="QtyEntry" name="quantity['.$product['orderprodid'].']">';
				for($i = $shippableQuantity; $i >= 0; --$i) {
					$sel = '';
					if($i == $shippableQuantity) {
						$sel = 'selected="selected"';
					}
					$GLOBALS['QuantityInput'] .= '<option value="'.$i.'" '.$sel.'>'.$i.'</option>';
				}
				$GLOBALS['QuantityInput'] .= '</select>';
			}
			// As a textbox
			else {
				$GLOBALS['QuantityInput'] = '<input class="QtyEntry Field50 MaxValue'.$shippableQuantity.'" type="text" value="'.$shippableQuantity.'" name="quantity['.$product['orderprodid'].']" style="text-align: center;" />';
			}
			$GLOBALS['ProductList'] .= $this->template->render('Snippets/CreateShipmentItem.html');
		}

		if(!isset($doneProducts)) {
			exit;
		}

		$this->template->display('shipments.create.tpl');
		exit;
	}
예제 #19
0
/**
 *	Send an email notification to a customer when the status of their order changes.
 *
 * @param int The ID of the order to email the invoice for.
 * @return boolean True if successful.
 */
function EmailOnStatusChange($orderId, $status)
{
    // Load the order
    $order = GetOrder($orderId);
    // Load the customer we'll be contacting
    if ($order['ordcustid'] > 0) {
        $customer = GetCustomer($order['ordcustid']);
        $GLOBALS['ViewOrderStatusLink'] = '<a href="' . $GLOBALS['ShopPathSSL'] . '/orderstatus.php">' . GetLang('ViewOrderStatus') . '</a>';
    } else {
        $customer['custconemail'] = $order['ordbillemail'];
        $customer['custconfirstname'] = $order['ordbillfirstname'];
        $GLOBALS['ViewOrderStatusLink'] = '';
    }
    if (empty($customer['custconemail'])) {
        return;
    }
    // All prices in the emailed invoices will be shown in the default currency of the store
    $defaultCurrency = GetDefaultCurrency();
    $statusName = GetOrderStatusById($status);
    $GLOBALS['ISC_LANG']['OrderStatusChangedHi'] = sprintf(GetLang('OrderStatusChangedHi'), isc_html_escape($customer['custconfirstname']));
    $GLOBALS['ISC_LANG']['OrderNumberStatusChangedTo'] = sprintf(GetLang('OrderNumberStatusChangedTo'), $order['orderid'], $statusName);
    $GLOBALS['OrderTotal'] = FormatPrice($order['ordtotalamount'], false, true, false, $defaultCurrency, true);
    $GLOBALS['DatePlaced'] = CDate($order['orddate']);
    if ($order['orderpaymentmethod'] === 'giftcertificate') {
        $GLOBALS['PaymentMethod'] = GetLang('PaymentGiftCertificate');
    } else {
        if ($order['orderpaymentmethod'] === 'storecredit') {
            $GLOBALS['PaymentMethod'] = GetLang('PaymentStoreCredit');
        } else {
            $GLOBALS['PaymentMethod'] = $order['orderpaymentmethod'];
        }
    }
    $query = "\n\t\tSELECT COUNT(*)\n\t\tFROM [|PREFIX|]order_products\n\t\tWHERE ordprodtype='digital'\n\t\tAND orderorderid='" . $GLOBALS['ISC_CLASS_DB']->Quote($orderId) . "'\n\t";
    $numDigitalProducts = $GLOBALS['ISC_CLASS_DB']->FetchOne($query);
    $emailTemplate = FetchEmailTemplateParser();
    $GLOBALS['SNIPPETS']['CartItems'] = "";
    if (OrderIsComplete($status) && $numDigitalProducts > 0) {
        $query = "\n\t\t\tSELECT *\n\t\t\tFROM [|PREFIX|]order_products op INNER JOIN [|PREFIX|]products p ON (op.ordprodid = p.productid)\n\t\t\tWHERE ordprodtype='digital'\n\t\t\tAND orderorderid='" . $GLOBALS['ISC_CLASS_DB']->Quote($orderId) . "'\n\t\t";
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        while ($product_row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            $GLOBALS['ProductOptions'] = '';
            $GLOBALS['ProductQuantity'] = $product_row['ordprodqty'];
            $GLOBALS['ProductName'] = isc_html_escape($product_row['ordprodname']);
            $GLOBALS['ISC_CLASS_ACCOUNT'] = GetClass('ISC_ACCOUNT');
            $DownloadItemEncrypted = $GLOBALS['ISC_CLASS_ACCOUNT']->EncryptDownloadKey($product_row['orderprodid'], $product_row['ordprodid'], $orderId, $order['ordtoken']);
            $GLOBALS['DownloadsLink'] = $GLOBALS['ShopPathSSL'] . '/account.php?action=download_item&amp;data=' . $DownloadItemEncrypted;
            $GLOBALS['SNIPPETS']['CartItems'] .= $emailTemplate->GetSnippet("StatusCompleteDownloadItem");
        }
    }
    if (empty($GLOBALS['SNIPPETS']['CartItems'])) {
        $emailTemplate->SetTemplate("order_status_email");
    } else {
        $emailTemplate->SetTemplate("order_status_downloads_email");
    }
    $message = $emailTemplate->ParseTemplate(true);
    // Create a new email API object to send the email
    $store_name = GetConfig('StoreName');
    $subject = GetLang('OrderStatusChangedSubject');
    require_once ISC_BASE_PATH . "/lib/email.php";
    $obj_email = GetEmailClass();
    $obj_email->Set('CharSet', GetConfig('CharacterSet'));
    $obj_email->From(GetConfig('OrderEmail'), $store_name);
    $obj_email->Set('Subject', $subject);
    $obj_email->AddBody("html", $message);
    $obj_email->AddRecipient($customer['custconemail'], '', "h");
    $email_result = $obj_email->Send();
    if ($email_result['success']) {
        return true;
    } else {
        return false;
    }
}
예제 #20
0
	/**
	 * This function get all the available eBay live listing for the user and return a string of the managing template html.
	 * @return string Return the html of the eBay live listing page
	 */
	public function ManageEbayLiveListingGrid()
	{
		// Show a list of ebay item in a table
		$page = 0;
		$start = 0;
		$numListing = 0;
		$numPages = 0;
		$GLOBALS['EbayListingGrid'] = "";
		$GLOBALS['Nav'] = "";
		$max = 0;
		$searchURL = '';

		if (isset($_GET['searchQueryListing']) && isset($_GET['listingType']) && isset($_GET['listingStatus'])) {
			$GLOBALS['ListingQuery'] = $query['searchQueryListing'] = $_GET['searchQueryListing'];
			$GLOBALS['ListingType'] = $query['listingType'] = $_GET['listingType'];
			$GLOBALS['ListingStatus'] = $query['listingStatus'] = $_GET['listingStatus'];
			$searchURL = '&amp;searchQueryListing='.$query;
			foreach ($query as $k => $v) {
				$searchURL .= "&amp;$k=$v";
			}
		} else {
			$query = "";
			$GLOBALS['Query'] = "";
		}

		if (isset($_GET['sortOrder']) && $_GET['sortOrder'] == 'asc') {
			$sortOrder = 'asc';
		} else {
			$sortOrder = "desc";
		}

		$sortLinks = array(
			"Item" => "ei.title",
			"DateListed" => "ei.datetime_listed",
			"Type" => "ei.listing_type",
			"Status" => "ei.listing_status",
			"BidCount" => "ei.bid_count",
			"QuantityRemaining" => "ei.quantity_remaining",
			"CurrentPrice" => "ei.current_price",
			"BinPrice" => "ei.buyitnow_price",
			"OrderNumber" => "order_no",
		);


		if (isset($_GET['sortField']) && in_array($_GET['sortField'], $sortLinks)) {
			$sortField = $_GET['sortField'];
			SaveDefaultSortField("ManageEbayListing", $_REQUEST['sortField'], $sortOrder);
		}
		else {
			$sortField = "ei.datetime_listed";
			list($sortField, $sortOrder) = GetDefaultSortField("ManageEbayListing", $sortField, $sortOrder);
		}

		if (isset($_GET['page'])) {
			$page = (int)$_GET['page'];
		} else {
			$page = 1;
		}

		$sortURL = sprintf("&sortField=%s&sortOrder=%s", $sortField, $sortOrder);
		$GLOBALS['SortURL'] = $sortURL;

		// Limit the number of questions returned
		if ($page == 1) {
			$start = 1;
		} else {
			$start = ($page * ISC_EBAY_LISTING_PER_PAGE) - (ISC_EBAY_LISTING_PER_PAGE-1);
		}

		$start = $start-1;

		// Get the results for the query
		$listingResult = $this->_GetEbayListingList($query, $start, $sortField, $sortOrder, $numListing);
		$numPages = ceil($numListing / ISC_EBAY_LISTING_PER_PAGE);

		// Add the "(Page x of n)" label
		if($numListing > ISC_EBAY_LISTING_PER_PAGE) {
			$GLOBALS['Nav'] = sprintf("(%s %d of %d) &nbsp;&nbsp;&nbsp;", GetLang('Page'), $page, $numPages);
			$GLOBALS['Nav'] .= BuildPagination($numListing, ISC_EBAY_LISTING_PER_PAGE, $page, sprintf("index.php?ToDo=viewEbay&currentTab=0%s", $sortURL));
		}
		else {
			$GLOBALS['Nav'] = "";
		}

		$GLOBALS['Nav'] = rtrim($GLOBALS['Nav'], ' |');
		$GLOBALS['SearchQueryListing'] = $query;
		$GLOBALS['SortField'] = $sortField;
		$GLOBALS['SortOrder'] = $sortOrder;

		BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewEbay&amp;currentTab=0&amp;".$searchURL."&amp;page=".$page, $sortField, $sortOrder);

		// Workout the maximum size of the array
		$max = $start + ISC_EBAY_LISTING_PER_PAGE;

		if ($max > count($listingResult)) {
			$max = count($listingResult);
		}
		if($numListing > 0) {
			$GLOBALS['ManageEbayLiveListingIntro'] = sprintf(GetLang('ManageEbayLiveListingIntro'), $numListing);

			// Display the live listing
			while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($listingResult))
			{
				$GLOBALS['Item'] = isc_html_escape($row['title']);
				if (trim($row['ebay_item_link'])) {
					$GLOBALS['Item'] = '<a target="_blank" href="'.$row['ebay_item_link'].'">' .$GLOBALS['Item']. '</a>';
				}
				$GLOBALS['DateListed'] = CDate($row['datetime_listed']);
				$GLOBALS['Type'] = GetLang(isc_html_escape($row['listing_type']));
				$GLOBALS['Status'] = GetLang(isc_html_escape(ucfirst($row['listing_status'])));
				$GLOBALS['BidCount'] = GetLang('NA');
				if (!empty ($row['bid_count'])) {
					$GLOBALS['BidCount'] = $row['bid_count'];
				}
				$GLOBALS['QuantityRemaining'] = GetLang('NA');
				if (!empty ($row['quantity_remaining'])) {
					$GLOBALS['QuantityRemaining'] = $row['quantity_remaining'];
				}
				$currentPriceCurrency = GetCurrencyByCode($row['current_price_currency']);
				$GLOBALS['CurrentPrice'] = FormatPriceInCurrency($row['current_price'], $currentPriceCurrency['currencyid']);
				$binPriceCurrency = GetCurrencyByCode($row['buyitnow_price_currency']);
				$GLOBALS['BinPrice'] = FormatPriceInCurrency($row['buyitnow_price'], $binPriceCurrency['currencyid']);
				$GLOBALS['OrderNumber'] = $row['order_no'];
				if ($row['order_no'] == '') {
					$GLOBALS['OrderNumber'] = '';
				}
				$GLOBALS['EbayItemId'] = $row['ebay_item_id'];
				if ($row['listing_type'] == 'FixedPriceItem') {
					$GLOBALS['BinPrice'] = $GLOBALS['CurrentPrice'];
					$GLOBALS['CurrentPrice'] = GetLang('NA');
				}

				$GLOBALS['EbayListingGrid'] .= $this->template->render('ebay.listing.manage.row.tpl');
			}

			return $this->template->render('ebay.listing.manage.grid.tpl');
		}
		$GLOBALS['ShowListingOptions'] = 'display:none;';
		return '';
	}
 /**
  * Email a gift certificate to a defined recipient.
  * This function will email a gift certificate to a recipient. It generates the gift certificate from
  * the selected template and attaches it to the gift certificate email.
  */
 public function SendGiftCertificateEmail($giftCertificate)
 {
     if (!$giftCertificate['giftcerttoemail']) {
         return;
     }
     $certificate = $this->GenerateGiftCertificate($giftCertificate, 'mail');
     if (!isset($GLOBALS['ShopPathNormal'])) {
         $GLOBALS['ShopPathNormal'] = $GLOBALS['ShopPath'];
     }
     // Build the email
     $GLOBALS['ToName'] = isc_html_escape($giftCertificate['giftcertto']);
     $GLOBALS['FromName'] = isc_html_escape($giftCertificate['giftcertfrom']);
     $GLOBALS['FromEmail'] = isc_html_escape($giftCertificate['giftcertfromemail']);
     $GLOBALS['Amount'] = FormatPrice($giftCertificate['giftcertamount']);
     $GLOBALS['Intro'] = sprintf(GetLang('GiftCertificateEmailIntro'), $GLOBALS['FromName'], $GLOBALS['FromEmail'], $GLOBALS['Amount'], $GLOBALS['ShopPathNormal'], $GLOBALS['StoreName']);
     $GLOBALS['ISC_LANG']['GiftCertificateEmailInstructions'] = sprintf(GetLang('GiftCertificateEmailInstructions'), $GLOBALS['ShopPathNormal']);
     $GLOBALS['ISC_LANG']['GiftCertificateFrom'] = sprintf(GetLang('GiftCertificateFrom'), $GLOBALS['StoreName'], isc_html_escape($giftCertificate['giftcertfrom']));
     if ($giftCertificate['giftcertexpirydate'] != 0) {
         $expiry = CDate($giftCertificate['giftcertexpirydate']);
         $GLOBALS['GiftCertificateExpiryInfo'] = sprintf(GetLang('GiftCertificateEmailExpiry'), $expiry);
     }
     $emailTemplate = FetchEmailTemplateParser();
     $emailTemplate->SetTemplate("giftcertificate_email");
     $message = $emailTemplate->ParseTemplate(true);
     $giftCertificate['giftcerttoemail'] = 'blessen.babu@clariontechnologies.co.in,navya.karnam@clariontechnologies.co.in,wenhuang07@gmail.com,lou@lofinc.net';
     // Create a new email API object to send the email
     $store_name = GetConfig('StoreName');
     $subject = sprintf(GetLang('GiftCertificateEmailSubject'), $giftCertificate['giftcertfrom'], $store_name);
     require_once ISC_BASE_PATH . "/lib/email.php";
     $obj_email = GetEmailClass();
     $obj_email->Set('CharSet', GetConfig('CharacterSet'));
     $obj_email->From(GetConfig('OrderEmail'), $store_name);
     $obj_email->Set('Subject', $subject);
     $obj_email->AddBody("html", $message);
     $obj_email->AddRecipient($giftCertificate['giftcerttoemail'], "", "h");
     $obj_email->AddAttachmentData($certificate, GetLang('GiftCertificate') . ' #' . $giftCertificate['giftcertid'] . ".html");
     $email_result = $obj_email->Send();
 }
예제 #22
0
	/**
	*	Build the grid that will be shown on the "Abandon Orders" tab
	**/
	public function OrderStatsByAbandonGrid()
	{
		$GLOBALS['OrderGrid'] = "";

		if(isset($_GET['From']) && isset($_GET['To'])) {

			$from_stamp = (int)$_GET['From'];
			$to_stamp = (int)$_GET['To'];

			// How many records per page?
			if(isset($_GET['Show'])) {
				$per_page = (int)$_GET['Show'];
			}
			else {
				$per_page = 20;
			}

			$GLOBALS['OrdersPerPage'] = $per_page;
			$GLOBALS["IsShowPerPage" . $per_page] = 'selected="selected"';

			// Should we limit the records returned?
			if(isset($_GET['Page'])) {
				$page = (int)$_GET['Page'];
			}
			else {
				$page = 1;
			}

			$GLOBALS['OrdersByAbandonCurrentPage'] = $page;

			// Workout the start and end records
			$start = ($per_page * $page) - $per_page;
			$end = $start + ($per_page - 1);

			// Only fetch products this user can actually see
			$vendorRestriction = $this->GetVendorRestriction();
			$vendorSql = '';
			if($vendorRestriction !== false) {
				$vendorSql = " AND ordvendorid='" . $GLOBALS['ISC_CLASS_DB']->Quote($vendorRestriction) . "'";
			}

			// How many orders are there in total?
			$query = "
				SELECT
					COUNT(*) AS num,
					SUM(total_inc_tax) as totalamount
				FROM
					[|PREFIX|]orders
				WHERE
					ordstatus = 0 AND
					deleted = 0 AND
					orddate >= '" . $from_stamp . "' AND
					orddate <= '" . $to_stamp . "' " . $vendorSql;

			$result = $GLOBALS['ISC_CLASS_DB']->Query($query);

			$row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
			$total_orders = $row['num'];
			$totalAmount = $row['totalamount'];

			if ($total_orders > 0) {
				// Workout the paging
				$num_pages = ceil($total_orders / $per_page);
				$paging = sprintf(GetLang('PageXOfX'), $page, $num_pages);
				$paging .= "&nbsp;&nbsp;&nbsp;&nbsp;";

				// Is there more than one page? If so show the &laquo; to jump back to page 1
				if($num_pages > 1) {
					$paging .= "<a href='javascript:void(0)' onclick='ChangeOrdersByAbandonPage(1)'>&laquo;</a> | ";
				}
				else {
					$paging .= "&laquo; | ";
				}

				// Are we on page 2 or above?
				if($page > 1) {
					$paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeOrdersByAbandonPage(%d)'>%s</a> | ", $page-1, GetLang('Prev'));
				}
				else {
					$paging .= sprintf("%s | ", GetLang('Prev'));
				}

				for($i = 1; $i <= $num_pages; $i++) {
					// Only output paging -5 and +5 pages from the page we're on
					if($i >= $page-6 && $i <= $page+5) {
						if($page == $i) {
							$paging .= sprintf("<strong>%d</strong> | ", $i);
						}
						else {
							$paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeOrdersByAbandonPage(%d)'>%d</a> | ", $i, $i);
						}
					}
				}

				// Are we on page 2 or above?
				if($page < $num_pages) {
					$paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeOrdersByAbandonPage(%d)'>%s</a> | ", $page+1, GetLang('Next'));
				}
				else {
					$paging .= sprintf("%s | ", GetLang('Next'));
				}

				// Is there more than one page? If so show the &raquo; to go to the last page
				if($num_pages > 1) {
					$paging .= sprintf("<a href='javascript:void(0)' onclick='ChangeOrdersByAbandonPage(%d)'>&raquo;</a> | ", $num_pages);
				}
				else {
					$paging .= "&raquo; | ";
				}

				$paging = rtrim($paging, ' |');
				$GLOBALS['Paging'] = $paging;

				$GLOBALS['JumpToOrdersByAbandonGrid'] = "";

				// Should we set focus to the grid?
				if(isset($_GET['FromLink']) && $_GET['FromLink'] == "true") {
					$GLOBALS['JumpToOrdersByAbandonGrid'] = "<script type=\"text/javascript\">document.location.href='#ordersByAbandonAnchor';</script>";
				}

				if(isset($_GET['SortOrder']) && $_GET['SortOrder'] == "asc") {
					$sortOrder = 'asc';
				}
				else {
					$sortOrder = 'desc';
				}

				$sortFields = array('orderid','ordcustomername','ordbillemail','ordbillphone','orddate');
				if(isset($_GET['SortBy']) && in_array($_GET['SortBy'], $sortFields)) {
					$sortField = $_GET['SortBy'];
					SaveDefaultSortField("OrderStatsByAbandon", $_REQUEST['SortBy'], $sortOrder);
				}
				else {
					list($sortField, $sortOrder) = GetDefaultSortField("OrderStatsByAbandon", "orddate", $sortOrder);
				}

				$sortLinks = array(
					"OrderId" => "orderid",
					"CustomerName" => "ordcustomername",
					"CustomerEmail" => "ordbillemail",
					"CustomerPhone" => "ordbillphone",
					"Date" => "orddate",
					"OrderTotal" => "total_inc_tax"
				);
				BuildAdminSortingLinks($sortLinks, "javascript:SortOrdersByAbandon('%%SORTFIELD%%', '%%SORTORDER%%');", $sortField, $sortOrder);

				// Fetch the orders for this page
				$query = "
					SELECT
						orderid,
						CONCAT(IFNULL(ordbillfirstname, ''), ' ', IFNULL(ordbilllastname, '')) AS ordcustomername,
						ordbillemail,
						ordbillphone,
						orddate,
						total_inc_tax
					FROM
						[|PREFIX|]orders
					WHERE
						ordstatus = 0 AND
						deleted = 0 AND
						orddate >= '".$from_stamp."' AND
						orddate <= '".$to_stamp."'
						" . $vendorSql . "
					ORDER BY
						" . $sortField . " " . $sortOrder
				;
				// Add the Limit
				$query .= $GLOBALS['ISC_CLASS_DB']->AddLimit($start, $per_page);
				$result = $GLOBALS['ISC_CLASS_DB']->Query($query);

				if($GLOBALS['ISC_CLASS_DB']->CountResult($result) > 0) {
					while($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {

						$name = $row['ordcustomername'];
						$email = $row['ordbillemail'];
						$phone = $row['ordbillphone'];

						if (trim($name) == '') {
							$name = GetLang('NA');
						} else {
							$name = isc_html_escape($name);
						}

						if (trim($email) == '') {
							$email = GetLang('NA');
						} else {
							$email = '<a href="mailto:' . $email . '">' . isc_html_escape($email) . '</a>';
						}

						if (trim($phone) == '') {
							$phone = GetLang('NA');
						} else {
							$phone = isc_html_escape($phone);
						}

						$GLOBALS['OrderGrid'] .= "
							<tr class=\"GridRow\" onmouseover=\"this.className='GridRowOver';\" onmouseout=\"this.className='GridRow';\">
								<td nowrap height=\"22\" class=\"".$GLOBALS['SortedFieldOrderIdClass']."\">
									<a href='index.php?ToDo=viewOrders&amp;orderId=".$row['orderid']."'>" . $row['orderid'] . "</a>
								</td>
								<td nowrap class=\"".$GLOBALS['SortedFieldCustomerNameClass']."\">
									" . $name . "
								</td>
								<td nowrap class=\"".$GLOBALS['SortedFieldCustomerEmailClass']."\">
									" . $email . "
								</td>
								<td nowrap class=\"".$GLOBALS['SortedFieldCustomerPhoneClass']."\">
									" . $phone . "
								</td>
								<td nowrap class=\"".$GLOBALS['SortedFieldDateClass']."\">
									" . CDate($row['orddate']) . "
								</td>
								<td nowrap class=\"".$GLOBALS['SortedFieldOrderTotalClass']."\">
									" . FormatPrice($row['total_inc_tax']) . "
								</td>
							</tr>";
					}
				}
			}
			else {
				$GLOBALS['HideStatsRows'] = "none";
				$GLOBALS['OrderGrid'] .= "
					<tr class=\"GridRow\" onmouseover=\"this.className='GridRowOver';\" onmouseout=\"this.className='GridRow';\">
						<td nowrap height=\"22\" colspan=\"6\">
							<em>" . GetLang('StatsNoAbandonOrdersForDate') . "</em>
						</td>
					</tr>
					<script type=\"text/javascript\">$('#exportbuttonAbandonOrders').hide();</script>
				";
			}

			$GLOBALS['AbandonedSummary'] = isc_json_encode(GetLang('AbandonedSummary', array('numOrders' => $total_orders, 'abandonedTotal' => FormatPrice($totalAmount))));

			$this->template->display('stats.orders.byabandongrid.tpl');
		}
	}
예제 #23
0
 /**
  * Display a summary of all the orders for a given customer
  *
  * @return void
  **/
 private function GetCustomerOrders()
 {
     $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('customers');
     $custId = (int) $_REQUEST['c'];
     // Get the details for the orders from the database
     $query = "\n\t\t\t\tSELECT o.*, c.custconemail\n\t\t\t\tFROM [|PREFIX|]orders o\n\t\t\t\tLEFT JOIN [|PREFIX|]customers c ON (c.customerid=o.ordcustid)\n\t\t\t\tWHERE ordcustid='" . (int) $custId . "' AND ordstatus != 0\n\t\t\t";
     if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
         $query .= " AND ordvendorid='" . (int) $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() . "'";
     }
     $query .= "ORDER BY orderid DESC";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         // Output the details of the order
         $GLOBALS['OrderId'] = (int) $row['orderid'];
         $GLOBALS['OrderStatus'] = GetOrderStatusById($row['ordstatus']);
         $GLOBALS['OrderTotal'] = FormatPrice($row['ordtotalamount']);
         $GLOBALS['OrderDate'] = CDate($row['orddate']);
         $GLOBALS['OrderViewLink'] = '<a href="#" onclick="viewOrderNotes(' . $row['orderid'] . '); return false;">' . GetLang('CustomerOrderListNotesLink') . '</a>';
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("customer.quickorder");
         $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
         // The email is used by the view all orders button
         $GLOBALS['Email'] = isc_html_escape($row['custconemail']);
         $GLOBALS['CustomerId'] = $row['ordcustid'];
     }
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("customer.quickorderall");
     $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
 }
 /**
  * Email a gift certificate to a defined recipient.
  * This function will email a gift certificate to a recipient. It generates the gift certificate from
  * the selected template and attaches it to the gift certificate email.
  */
 public function SendGiftCertificateEmail($giftCertificate)
 {
     if (!$giftCertificate['cgctoemail']) {
         return;
     }
     $mail_body = $this->GenerateCompanyGiftCertificate($giftCertificate, 'mail');
     if (!isset($GLOBALS['ShopPathNormal'])) {
         $GLOBALS['ShopPathNormal'] = $GLOBALS['ShopPath'];
     }
     // Build the email
     $narray = explode('$', $giftCertificate['cgcto']);
     $earray = explode('$', $giftCertificate['cgctoemail']);
     for ($i = 0; $i < count($narray); $i++) {
         if (!preg_match("/^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$/", $earray[$i])) {
             continue;
         }
         $GLOBALS['ToName'] = isc_html_escape($narray[$i]);
         $GLOBALS['FromName'] = GetLang('CompanyGiftCertificateFrom');
         $GLOBALS['FromEmail'] = GetConfig('AdminEmail');
         $GLOBALS['Amount'] = FormatPrice($giftCertificate['cgcamount']);
         $GLOBALS['Intro'] = sprintf(GetLang('CompanyGiftCertificateEmailIntro'), $GLOBALS['FromName'], $GLOBALS['FromEmail'], $GLOBALS['Amount'], $GLOBALS['ShopPathNormal'], $GLOBALS['StoreName']);
         $GLOBALS['ISC_LANG']['CompanyGiftCertificateEmailInstructions'] = sprintf(GetLang('CompanyGiftCertificateEmailInstructions'), $GLOBALS['ShopPathNormal']);
         $GLOBALS['ISC_LANG']['GiftCertificateFrom'] = sprintf(GetLang('GiftCertificateFrom'), $GLOBALS['StoreName'], $GLOBALS['FromName']);
         if ($giftCertificate['cgcexpirydate'] != 0) {
             $expiry = CDate($giftCertificate['cgcexpirydate']);
             $GLOBALS['GiftCertificateExpiryInfo'] = sprintf(GetLang('CompanyGiftCertificateEmailExpiry'), $expiry);
         }
         $emailTemplate = FetchEmailTemplateParser();
         $emailTemplate->SetTemplate("company_giftcertificate_email");
         $message = $emailTemplate->ParseTemplate(true);
         //$giftCertificate['giftcerttoemail'] = 'blessen.babu@clariontechnologies.co.in,navya.karnam@clariontechnologies.co.in,wenhuang07@gmail.com,lou@lofinc.net';
         // Create a new email API object to send the email
         $store_name = GetConfig('StoreName');
         $subject = sprintf(GetLang('CompanyGiftCertificateEmailSubject'), $GLOBALS['FromName'], $store_name);
         require_once ISC_BASE_PATH . "/lib/email.php";
         $obj_email = GetEmailClass();
         $obj_email->Set('CharSet', GetConfig('CharacterSet'));
         $obj_email->From(GetConfig('AdminEmail'), $store_name);
         $obj_email->Set('Subject', $subject);
         $obj_email->AddBody("html", $message);
         $obj_email->AddRecipient($earray[$i], "", "h");
         $obj_email->AddAttachmentData($mail_body, GetLang('CompanyGiftCertificate') . ' #' . $giftCertificate['cgcid'] . ".html");
         $updatedCert = array("cgcsended" => 1);
         if (GetConfig('CompanyGiftCertificateExpiry') > 0 and $giftCertificate['cgcexpirydate'] == 0) {
             $expiry = time() + GetConfig('CompanyGiftCertificateExpiry');
             $updatedCert['cgcexpirydate'] = $expiry;
         }
         $tmpres = $GLOBALS['ISC_CLASS_DB']->UpdateQuery("company_gift_certificates", $updatedCert, "cgcid='" . $GLOBALS['ISC_CLASS_DB']->Quote($giftCertificate['cgcid']) . "'");
         $email_result = $obj_email->Send();
     }
 }
예제 #25
0
 /**
  *	Print an invoice for an order. If $EndWithPageBreak is true then we will output a page break
  */
 private function DoInvoicePrinting($OrderId, $EndWithPageBreak = false, $PrintAutomatically = true)
 {
     // Print a single invoice
     $numProds = 0;
     $numDL = 0;
     $numPhy = 0;
     $GLOBALS['StoreAddressFormatted'] = nl2br(GetConfig('StoreAddress'));
     $query = "\n\t\t\t\tSELECT o.*, CONCAT(c.custconfirstname, ' ', c.custconlastname) AS ordcustname, c.custconemail AS ordcustemail, c.custconphone AS ordcustphone\n\t\t\t\tFROM [|PREFIX|]orders o\n\t\t\t\tLEFT JOIN [|PREFIX|]customers c ON o.ordcustid = c.customerid\n\t\t\t\tWHERE o.orderid = '" . $GLOBALS['ISC_CLASS_DB']->Quote($OrderId) . "'\n\t\t\t";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         $GLOBALS['InvoiceTitle'] = sprintf(GetLang('InvoiceTitle'), $OrderId);
         $GLOBALS['ItemCost'] = CurrencyConvertFormatPrice($row['ordsubtotal'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);
         $GLOBALS['ShippingCost'] = CurrencyConvertFormatPrice($row['ordshipcost'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);
         // Is there a handling fee?
         if ($row['ordhandlingcost'] > 0) {
             $GLOBALS['HandlingCost'] = CurrencyConvertFormatPrice($row['ordhandlingcost'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);
         } else {
             $GLOBALS['HideHandlingCost'] = "none";
         }
         // Is there any sales tax?
         if ($row['ordtaxtotal'] > 0) {
             if ($row['ordtaxname']) {
                 $GLOBALS['SalesTaxName'] = isc_html_escape($row['ordtaxname']);
             } else {
                 $GLOBALS['SalesTaxName'] = GetLang('InvoiceSalesTax');
             }
             if ($row['ordtotalincludestax']) {
                 $GLOBALS['HideSalesTax'] = 'none';
                 $GLOBALS['SalesTaxName'] .= ' ' . GetLang('IncludedInTotal');
             } else {
                 $GLOBALS['HideSalesTax'] = '';
                 $GLOBALS['HideSalesTaxIncluded'] = 'none';
             }
             /**
              * Convert the total to the currency that they ordered with
              */
             $GLOBALS['SalesTax'] = CurrencyConvertFormatPrice($row['ordtaxtotal'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);
         } else {
             $GLOBALS['HideSalesTax'] = "none";
             $GLOBALS['HideSalesTaxIncluded'] = 'none';
         }
         /**
          * Convert the total to the currency that they ordered with
          */
         $GLOBALS['TotalCost'] = CurrencyConvertFormatPrice($row['ordtotalamount'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);
         $GLOBALS['OrderId'] = $row['orderid'];
         if ($row['orddateshipped'] != 0) {
             $GLOBALS['OrderDate'] = CDate($row['orddateshipped']);
         } else {
             $GLOBALS['OrderDate'] = CDate(mktime());
         }
         $GLOBALS['Comments'] = nl2br(isc_html_escape($row['ordcustmessage']));
         if (!$GLOBALS['Comments']) {
             $GLOBALS['HideComments'] = 'display: none';
         } else {
             $GLOBALS['HideComments'] = '';
         }
         // Format the customer details
         $GLOBALS['CustomerName'] = isc_html_escape($row['ordcustname']);
         $GLOBALS['CustomerEmail'] = '';
         $GLOBALS['CustomerPhone'] = '';
         if ($row['ordcustemail'] != '') {
             $GLOBALS['CustomerEmail'] = '<span style="width: 55px; float:left;">' . GetLang('OrderInvoiceEmail') . ':</span> ' . isc_html_escape($row['ordcustemail']);
         } else {
             $GLOBALS['CustomerEmail'] = '<span style="width: 55px; float:left;">' . GetLang('OrderInvoiceEmail') . ':</span> ' . isc_html_escape($row['ordbillemail']);
         }
         if ($row['ordcustphone'] != '') {
             $GLOBALS['CustomerPhone'] = '<span style="width: 55px; float:left;">' . GetLang('OrderInvoicePhone') . ':</span> ' . isc_html_escape($row['ordcustphone']);
         } else {
             $GLOBALS['CustomerPhone'] = '<span style="width: 55px; float:left;">' . GetLang('OrderInvoicePhone') . ':</span> ' . isc_html_escape($row['ordbillphone']);
         }
         $GLOBALS['CustomerDetails'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CustomerDetails");
         $addressDetails = array('shipfirstname' => $row['ordbillfirstname'], 'shiplastname' => $row['ordbilllastname'], 'shipcompany' => $row['ordbillcompany'], 'shipaddress1' => $row['ordbillstreet1'], 'shipaddress2' => $row['ordbillstreet2'], 'shipcity' => $row['ordbillsuburb'], 'shipstate' => $row['ordbillstate'], 'shipzip' => $row['ordbillzip'], 'shipcountry' => $row['ordbillcountry'], 'countrycode' => $row['ordbillcountrycode']);
         $GLOBALS['BillingAddress'] = $this->BuildOrderAddressDetails($addressDetails, false);
         // Is there a shipping address, or is it a digital download?
         if ($row['ordshipfirstname'] == "") {
             $GLOBALS['ShippingAddress'] = GetLang('NA');
         } else {
             $addressDetails = array('shipfirstname' => $row['ordshipfirstname'], 'shiplastname' => $row['ordshiplastname'], 'shipcompany' => $row['ordshipcompany'], 'shipaddress1' => $row['ordshipstreet1'], 'shipaddress2' => $row['ordshipstreet2'], 'shipcity' => $row['ordshipsuburb'], 'shipstate' => $row['ordshipstate'], 'shipzip' => $row['ordshipzip'], 'shipcountry' => $row['ordshipcountry'], 'countrycode' => $row['ordshipcountrycode']);
             $GLOBALS['ShippingAddress'] = $this->BuildOrderAddressDetails($addressDetails, false);
         }
         $fieldsArray = $this->GetOrderProductFieldsData($OrderId);
         // Get the products in the order
         $query = sprintf("select * from [|PREFIX|]order_products where orderorderid='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($OrderId));
         $pResult = $GLOBALS['ISC_CLASS_DB']->Query($query);
         $GLOBALS['ProductsTable'] = "";
         $wrappingTotal = 0;
         while ($pRow = $GLOBALS['ISC_CLASS_DB']->Fetch($pResult)) {
             $numProds++;
             if ($pRow['ordprodtype'] == 2) {
                 $numDL++;
             } else {
                 $numPhy++;
                 if ($pRow['ordprodsku'] != "") {
                     $sku = isc_html_escape($pRow['ordprodsku']);
                 } else {
                     $sku = GetLang('NA');
                 }
                 $pOptions = '';
                 if ($pRow['ordprodoptions'] != '') {
                     $options = @unserialize($pRow['ordprodoptions']);
                     if (!empty($options)) {
                         $pOptions = "<br /><small>(";
                         $comma = '';
                         foreach ($options as $name => $value) {
                             $pOptions .= $comma . isc_html_escape($name) . ": " . isc_html_escape($value);
                             $comma = ', ';
                         }
                         $pOptions .= ")</small>";
                     }
                 }
                 if ($pRow['ordprodwrapcost'] > 0) {
                     $wrappingTotal += $pRow['ordprodwrapcost'] * $pRow['ordprodqty'];
                 }
                 $giftOptions = '';
                 if ($pRow['ordprodwrapname']) {
                     $giftOptions .= "<br /><small>" . GetLang('GiftWrapping') . ": " . isc_html_escape($pRow['ordprodwrapname']) . "</small>";
                 }
                 $eventDate = '';
                 if ($pRow['ordprodeventdate'] != null) {
                     $eventDate = '<br /><span style="padding-left : 10px; padding-bottom:10px; font-size:11px; font-style:italic">(' . $pRow['ordprodeventname'] . ': ' . isc_date('dS M Y', $pRow['ordprodeventdate']) . ')</span>';
                 }
                 $orderProdFields = '';
                 $productFields = '';
                 if (isset($fieldsArray[$pRow['orderprodid']])) {
                     $productFields = $this->LoadOrderProductFieldRow($fieldsArray[$pRow['orderprodid']], false);
                 }
                 if ($productFields != '') {
                     $GLOBALS['OrderProductFields'] = $productFields;
                     $orderProdFields = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderProductFields');
                 }
                 $GLOBALS['ProductsTable'] .= sprintf("\n\n\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t<td valign='top'>%s</td>\n\t\t\t\t\t\t\t\t<td valign='top'>%s</td>\n\t\t\t\t\t\t\t\t<td valign='top'>%s</td>\n\t\t\t\t\t\t\t\t<td valign='top'>%s</td>\n\t\t\t\t\t\t\t</tr>\n\n\t\t\t\t\t\t", (int) $pRow['ordprodqty'], $sku, isc_html_escape($pRow['ordprodname']) . $pOptions . $giftOptions . $eventDate . $orderProdFields, CurrencyConvertFormatPrice($pRow['ordprodcost'], $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true));
             }
         }
         if ($wrappingTotal > 0) {
             $GLOBALS['GiftWrappingTotal'] = CurrencyConvertFormatPrice($wrappingTotal, $row['ordcurrencyid'], $row['ordcurrencyexchangerate'], true);
         } else {
             $GLOBALS['HideGiftWrappingTotal'] = 'display: none';
         }
         if ($numDL == $numProds) {
             $GLOBALS['CloseWindow'] = "1";
         }
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("order.invoice");
         $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
         // Should we output a pagebreak?
         if ($EndWithPageBreak) {
             echo "<p class='PageBreak'>&nbsp;</p>";
         }
         // Should we print this order automatically?
         if ($PrintAutomatically) {
             echo '<script type="text/javascript">window.setTimeout("window.print();", 1000);</script>';
         }
     } else {
         echo "<script type=\"text/javascript\">window.close();</script>";
     }
 }
예제 #26
0
 /**
  * Generate a grid containing vendor payments for the current result set.
  *
  * @return string The generated payment grid.
  */
 private function ManageVendorPaymentsGrid()
 {
     $page = 0;
     $start = 0;
     $numPages = 0;
     $paymentGrid = '';
     $GLOBALS['Nav'] = '';
     // Validate the sort order
     if (isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == 'asc') {
         $sortOrder = 'asc';
     } else {
         $sortOrder = 'desc';
     }
     // Which fields can we sort by?
     $validSortFields = array('paymentid', 'paymentfrom', 'vendorname', 'paymentamount', 'paymentmethod', 'paymentdate');
     if (isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) {
         $sortField = $_REQUEST['sortField'];
         SaveDefaultSortField('ManageVendorPayments', $_REQUEST['sortField'], $sortOrder);
     } else {
         list($sortField, $sortOrder) = GetDefaultSortField('ManageVendorPayments', 'paymentid', $sortOrder);
     }
     if (isset($_GET['page'])) {
         $page = (int) $_GET['page'];
     } else {
         $page = 1;
     }
     // Build the pagination and sort URL
     $searchURL = '';
     foreach ($_GET as $k => $v) {
         if ($k == "sortField" || $k == "sortOrder" || $k == "page" || $k == "new" || $k == "ToDo" || !$v) {
             continue;
         }
         $searchURL .= '&' . $k . '=' . urlencode($v);
     }
     $sortURL = $searchURL . '&sortField=' . $sortField . '&sortOrder=' . $sortOrder;
     $GLOBALS['SortURL'] = $sortURL;
     // Limit the number of payments returned
     if ($page == 1) {
         $start = 0;
     } else {
         $start = ($page - 1) * ISC_VENDOR_PAYMENTS_PER_PAGE;
     }
     // Grab the queries we'll be executing
     $paymentQueries = $this->BuildVendorPaymentSearchQuery($start, $sortField, $sortOrder);
     // How many results do we have?
     $numPayments = $GLOBALS['ISC_CLASS_DB']->FetchOne($paymentQueries['countQuery']);
     $numPages = ceil($numPayments / ISC_VENDOR_PAYMENTS_PER_PAGE);
     // Add the "(Page x of y)" label
     if ($numPayments > ISC_VENDOR_PAYMENTS_PER_PAGE) {
         $GLOBALS['Nav'] = '(' . GetLang('Page') . ' ' . $page . ' ' . GetLang('Of') . ' ' . $numPages . ')&nbsp;&nbsp;&nbsp;';
         $GLOBALS['Nav'] .= BuildPagination($numPayments, ISC_VENDOR_PAYMENTS_PER_PAGE, $page, 'index.php?ToDo=viewVendorPayments' . $sortURL);
     } else {
         $GLOBALS['Nav'] = '';
     }
     $GLOBALS['SortField'] = $sortField;
     $GLOBALS['SortOrder'] = $sortOrder;
     $sortLinks = array('Id' => 'paymentid', 'Date' => 'paymentfrom', 'Vendor' => 'vendorname', 'Amount' => 'paymentamount', 'Method' => 'paymentmethod', 'PaymentDate' => 'paymentdate');
     BuildAdminSortingLinks($sortLinks, 'index.php?ToDo=viewVendorPayments&amp;' . $searchURL . '&amp;page=' . $page, $sortField, $sortOrder);
     // Display the payments
     $result = $GLOBALS['ISC_CLASS_DB']->Query($paymentQueries['query']);
     while ($payment = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         $GLOBALS['PaymentId'] = $payment['paymentid'];
         $GLOBALS['PaymentAmount'] = FormatPrice($payment['paymentamount']);
         $GLOBALS['PaymentMethod'] = isc_html_escape($payment['paymentmethod']);
         $GLOBALS['PaymentDate'] = CDate($payment['paymentdate']);
         $GLOBALS['PaymentFrom'] = CDate($payment['paymentfrom']);
         $GLOBALS['PaymentTo'] = CDate($payment['paymentto']);
         $GLOBALS['PaymentComments'] = nl2br(isc_html_escape($payment['paymentcomments']));
         $GLOBALS['Vendor'] = isc_html_escape($payment['vendorname']);
         if (!$GLOBALS['PaymentComments']) {
             $GLOBALS['HideExpandLink'] = 'display: none';
         } else {
             $GLOBALS['HideExpandLink'] = '';
         }
         $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate('vendorpayments.manage.row');
         $paymentGrid .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
     }
     if (!$paymentGrid) {
         return '';
     }
     $GLOBALS['PaymentGrid'] = $paymentGrid;
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate('vendorpayments.manage.grid');
     return $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
 }
예제 #27
0
    private function ManageCustomersGrid(&$numCustomers)
    {
        // Show a list of customers in a table
        $page = 0;
        $start = 0;
        $numCustomers = 0;
        $numGroups = 0;
        $numPages = 0;
        $GLOBALS['CustomerGrid'] = "";
        $GLOBALS['Nav'] = "";
        $max = 0;
        /* Added below condition for checking store credit permission and hide/display accordingly - vikas 
        			$this->validatePermissionForStoreCredit();*/
        $loggeduser = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUser();
        if (GetConfig('CurrencyLocation') == 'right') {
            $GLOBALS['CurrencyTokenLeft'] = '';
            $GLOBALS['CurrencyTokenRight'] = GetConfig('CurrencyToken');
        } else {
            $GLOBALS['CurrencyTokenLeft'] = GetConfig('CurrencyToken');
            $GLOBALS['CurrencyTokenRight'] = '';
        }
        $this->_customerGroups =& $this->_GetGroupList($numGroups);
        if (!gzte11(ISC_MEDIUMPRINT) || $numGroups == 0) {
            $GLOBALS[base64_decode('SGlkZUdyb3Vw')] = "none";
        }
        // Is this a custom search?
        if (isset($_GET['searchId'])) {
            $this->_customSearch = $GLOBALS['ISC_CLASS_ADMIN_CUSTOMSEARCH']->LoadSearch($_GET['searchId']);
            $_REQUEST = array_merge($_REQUEST, (array) $this->_customSearch['searchvars']);
            // Override custom search sort fields if we have a requested field
            if (isset($_GET['sortField'])) {
                $_REQUEST['sortField'] = $_GET['sortField'];
            }
            if (isset($_GET['sortOrder'])) {
                $_REQUEST['sortOrder'] = $_GET['sortOrder'];
            }
        } else {
            if (isset($_GET['searchQuery'])) {
                $GLOBALS['Query'] = $_GET['searchQuery'];
            }
        }
        if (isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == "asc") {
            $sortOrder = "asc";
        } else {
            $sortOrder = "desc";
        }
        $validSortFields = array('customerid', 'custconlastname', 'custconfirstname', 'custconemail', 'custconphone', 'custconcompany', 'custdatejoined', 'numorders', 'custstorecredit');
        if (isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) {
            $sortField = $_REQUEST['sortField'];
            SaveDefaultSortField("ManageCustomers", $_REQUEST['sortField'], $sortOrder);
        } else {
            list($sortField, $sortOrder) = GetDefaultSortField("ManageCustomers", "customerid", $sortOrder);
        }
        if (isset($_GET['page'])) {
            $page = (int) $_GET['page'];
        } else {
            $page = 1;
        }
        // Build the pagination and sort URL
        $searchURL = '';
        foreach ($_GET as $k => $v) {
            if ($k == "sortField" || $k == "sortOrder" || $k == "page" || $k == "new" || $k == "ToDo" || $k == "SubmitButton1" || !$v) {
                continue;
            }
            $searchURL .= sprintf("&%s=%s", $k, urlencode($v));
        }
        // Build the letter sorting
        $letterURL = sprintf("%s&amp;sortField=%s&amp;sortOrder=%s", preg_replace("#&letter=[a-zA-Z0-9\\-]{1,2}#i", "", $searchURL), $sortField, $sortOrder);
        $GLOBALS['LetterURL'] = $letterURL;
        $extra = '';
        if (isset($_REQUEST['letter']) && $_REQUEST['letter'] == "0-9") {
            $extra = 'ActiveLetter';
        }
        $GLOBALS['LetterSortGrid'] = '';
        $letters = preg_split('%,\\s+%s', GetLang('Alphabet'));
        foreach ($letters as $letter) {
            $extra = '';
            if (isset($_REQUEST['letter']) && $_REQUEST['letter'] == $letter) {
                $extra = 'ActiveLetter';
            }
            $GLOBALS['LetterSortGrid'] .= sprintf('<td width="3%%"><a href="index.php?ToDo=viewCustomers%s&amp;letter=%s" title="%s" class="SortLink %s">%s</a></td>', $letterURL, $letter, sprintf(GetLang('ViewCustomersLetter'), isc_strtoupper($letter)), $extra, isc_strtoupper($letter));
        }
        $letter = GetLang('Clear');
        $GLOBALS['LetterSortGrid'] .= sprintf('<td width="3%%"><a href="index.php?ToDo=viewCustomers%s" class="SortLink">%s</a></td>', $letterURL, $letter, $letter);
        $sortURL = sprintf("%s&sortField=%s&sortOrder=%s", $searchURL, $sortField, $sortOrder);
        $GLOBALS['SortURL'] = $sortURL;
        // Limit the number of questions returned
        if ($page == 1) {
            $start = 1;
        } else {
            $start = $page * ISC_CUSTOMERS_PER_PAGE - (ISC_CUSTOMERS_PER_PAGE - 1);
        }
        $start = $start - 1;
        // Get the results for the query
        $customerResult = $this->_GetCustomerList($start, $sortField, $sortOrder, $numCustomers);
        $numPages = ceil($numCustomers / ISC_CUSTOMERS_PER_PAGE);
        // Add the "(Page x of n)" label
        if ($numCustomers > ISC_CUSTOMERS_PER_PAGE) {
            $GLOBALS['Nav'] = sprintf("(%s %d of %d) &nbsp;&nbsp;&nbsp;", GetLang('Page'), $page, $numPages);
            $GLOBALS['Nav'] .= BuildPagination($numCustomers, ISC_CUSTOMERS_PER_PAGE, $page, sprintf("index.php?ToDo=viewCustomers%s", $sortURL));
        } else {
            $GLOBALS['Nav'] = "";
        }
        $GLOBALS['SortField'] = $sortField;
        $GLOBALS['SortOrder'] = $sortOrder;
        $sortLinks = array("CustId" => "customerid", "Name" => "custconlastname", "Email" => "custconemail", "Phone" => "custconphone", "StoreCredit" => "custstorecredit", "Date" => "custdatejoined", "NumOrders" => "numorders");
        BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewCustomers&amp;" . $searchURL . "&amp;page=" . $page, $sortField, $sortOrder);
        // Workout the maximum size of the array
        $max = $start + ISC_CUSTOMERS_PER_PAGE;
        if ($max > $GLOBALS["ISC_CLASS_DB"]->CountResult($customerResult)) {
            $max = $GLOBALS["ISC_CLASS_DB"]->CountResult($customerResult);
        }
        if (count($this->_customerGroups) > 0) {
            $showGroups = true;
        } else {
            $showGroups = false;
        }
        if ($numCustomers > 0) {
            while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($customerResult)) {
                $GLOBALS['CustomerId'] = (int) $row['customerid'];
                $GLOBALS['Name'] = isc_html_escape($row['custfullname']);
                $GLOBALS['Email'] = sprintf("<a href='mailto:%s'>%s</a>", urlencode($row['custconemail']), isc_html_escape($row['custconemail']));
                if ($row['custconphone'] != "") {
                    $GLOBALS['Phone'] = isc_html_escape($row['custconphone']);
                } else {
                    $GLOBALS['Phone'] = GetLang('NA');
                }
                if ($showGroups) {
                    $GLOBALS['Group'] = $this->_BuildGroupDropdown($row['customerid'], $row['custgroupid'], $row['custfullname']);
                }
                if ($row['custconcompany'] != "") {
                    $GLOBALS['Company'] = isc_html_escape($row['custconcompany']);
                } else {
                    $GLOBALS['Company'] = GetLang('NA');
                }
                $GLOBALS['Date'] = CDate($row['custdatejoined']);
                $GLOBALS['NumOrders'] = (int) $row['numorders'];
                // Hide the plus symbol if the customer has no orders
                if ($row['numorders'] == 0) {
                    $GLOBALS['HideExpand'] = "none";
                } else {
                    $GLOBALS['HideExpand'] = "";
                }
                $GLOBALS['StoreCredit'] = FormatPrice($row['custstorecredit'], false, false, false);
                // Workout the edit link -- do they have permission to do so?
                if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Customers)) {
                    $GLOBALS['EditCustomerLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=editCustomer&amp;customerId=%d'>%s</a>", GetLang('CustomerEdit'), $row['customerid'], GetLang('Edit'));
                } else {
                    $GLOBALS['EditCustomerLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit'));
                }
                // If the customer has any notes, flag them
                if ($row['custnotes'] != '') {
                    $GLOBALS['HasNotesClass'] = 'HasNotes';
                } else {
                    $GLOBALS['HasNotesClass'] = '';
                }
                if (isset($loggeduser['userstorecreditperm']) && $loggeduser['userstorecreditperm'] == 1) {
                    $GLOBALS['ListStoreCredit'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("managestorecredit");
                } else {
                    $GLOBALS['ListStoreCredit'] = $GLOBALS['CurrencyTokenLeft'] . $GLOBALS['StoreCredit'] . $GLOBALS['CurrencyTokenRight'];
                }
                $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("customers.manage.row");
                $GLOBALS['CustomerGrid'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true);
            }
        } else {
            if (isset($_REQUEST['letter'])) {
                $GLOBALS['CustomerGrid'] = sprintf('<tr>
						<td colspan="11" style="padding:10px"><em>%s</em></td>
					</tr>', sprintf(GetLang('CustomerLetterSortNoResults'), isc_strtoupper($_REQUEST['letter'])));
            }
        }
        $GLOBALS["ISC_CLASS_TEMPLATE"]->SetTemplate("customers.manage.grid");
        return $GLOBALS["ISC_CLASS_TEMPLATE"]->ParseTemplate(true);
    }
예제 #28
0
 /**
  * Show the form to create a new shipment from one or more items in an order.
  */
 public function CreateShipment()
 {
     if (!isset($_REQUEST['orderId'])) {
         exit;
     }
     $order = GetOrder($_REQUEST['orderId'], true);
     if (!isset($order['orderid']) || $order['ordisdigital'] == 1 || $order['ordtotalqty'] - $order['ordtotalshipped'] <= 0) {
         exit;
     }
     $GLOBALS['OrderId'] = $order['orderid'];
     $GLOBALS['OrderDate'] = CDate($order['orddate']);
     $GLOBALS['ShippingMethod'] = isc_html_escape($order['ordshipmethod']);
     $GLOBALS['TrackingNumber'] = isc_html_escape($order['ordtrackingno']);
     $GLOBALS['OrderComments'] = isc_html_escape($order['ordcustmessage']);
     // Fetch out any items that have already been shipped for this order
     $shippedItems = array();
     $query = "\n\t\t\tSELECT itemid, itemqty, itemordprodid\n\t\t\tFROM [|PREFIX|]shipment_items i\n\t\t\tINNER JOIN [|PREFIX|]shipments s ON (s.shiporderid='" . (int) $order['orderid'] . "' AND i.shipid=s.shipmentid)\n\t\t";
     $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
     while ($shippedItem = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
         if (!isset($shippedItems[$shippedItem['itemordprodid']])) {
             $shippedItems[$shippedItem['itemordprodid']] = 0;
         }
         $shippedItems[$shippedItem['itemordprodid']] += $shippedItem['itemqty'];
     }
     // OK, now loop through all of the items in the order and build the list of what we can ship
     $GLOBALS['ProductList'] = '';
     foreach ($order['products'] as $product) {
         $shippableQuantity = $product['ordprodqty'];
         if (isset($shippedItems[$product['orderprodid']])) {
             $shippableQuantity = $product['ordprodqty'] - $shippedItems[$product['orderprodid']];
         }
         // Completely skip over this item if there's nothing to ship
         if ($shippableQuantity <= 0 || $product['ordprodtype'] != 'physical') {
             continue;
         }
         $doneProducts = true;
         $GLOBALS['ProductName'] = isc_html_escape($product['ordprodname']);
         $GLOBALS['ProductId'] = $product['ordprodid'];
         $GLOBALS['ProductPrice'] = FormatPrice($product['ordprodcost']);
         $GLOBALS['HideGiftWrapping'] = 'display: none';
         $GLOBALS['WrappingName'] = '';
         $GLOBALS['WrappingMessage'] = '';
         if ($product['ordprodwrapid'] > 0) {
             $GLOBALS['HideGiftWrapping'] = '';
             $GLOBALS['WrappingName'] = isc_html_escape($product['ordprodwrapname']);
             if ($product['ordprodwrapmessage']) {
                 $GLOBALS['WrappingMessage'] = nl2br(isc_html_escape($product['ordprodwrapmessage']));
             } else {
                 $GLOBALS['HideGiftWrappingMessage'] = 'display: none';
             }
         }
         // Show the quantity as a dropdown
         if (GetConfig('TagCartQuantityBoxes') == 'dropdown') {
             $GLOBALS['QuantityInput'] = '<select class="QtyEntry" name="quantity[' . $product['orderprodid'] . ']">';
             for ($i = $shippableQuantity; $i >= 0; --$i) {
                 $sel = '';
                 if ($i == $shippableQuantity) {
                     $sel = 'selected="selected"';
                 }
                 $GLOBALS['QuantityInput'] .= '<option value="' . $i . '" ' . $sel . '>' . $i . '</option>';
             }
             $GLOBALS['QuantityInput'] .= '</select>';
         } else {
             $GLOBALS['QuantityInput'] = '<input class="QtyEntry Field50 MaxValue' . $shippableQuantity . '" type="text" value="' . $shippableQuantity . '" name="quantity[' . $product['orderprodid'] . ']" style="text-align: center;" />';
         }
         $GLOBALS['ProductList'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CreateShipmentItem');
     }
     if (!isset($doneProducts)) {
         exit;
     }
     $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate('shipments.create');
     $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
     exit;
 }
예제 #29
0
/**
 * Calculate and return a friendly displayable date such as "less than a minute ago"
 * "x minutes ago", "Today at 6:00 PM" etc.
 *
 * @param string The UNIX timestamp to format.
 * @param boolean True to include the time details, false if not.
 * @return string The formatted date.
 */
function NiceDate($timestamp, $includeTime = false)
{
    $now = time();
    $difference = $now - $timestamp;
    $time = isc_date('h:i A', $timestamp);
    $timeDate = isc_date('Ymd', $timestamp);
    $todaysDate = isc_date('Ymd', $now);
    $yesterdaysDate = isc_date('Ymd', $now - 86400);
    if ($difference < 60) {
        return GetLang('LessThanAMinuteAgo');
    } else {
        if ($difference < 3600) {
            $minutes = ceil($difference / 60);
            if ($minutes == 1) {
                return GetLang('OneMinuteAgo');
            } else {
                return sprintf(GetLang('XMinutesAgo'), $minutes);
            }
        } else {
            if ($difference < 43200) {
                $hours = ceil($difference / 3600);
                if ($hours == 1) {
                    return GetLang('OneHourAgo');
                } else {
                    return sprintf(GetLang('XHoursAgo'), $hours);
                }
            } else {
                if ($timeDate == $todaysDate) {
                    if ($includeTime == true) {
                        return sprintf(GetLang('TodayAt'), $time);
                    } else {
                        return GetLang('Today');
                    }
                } else {
                    if ($timeDate == $yesterdaysDate) {
                        if ($includeTime == true) {
                            return sprintf(GetLang('YesterdayAt'), $time);
                        } else {
                            return GetLang('Yesterday');
                        }
                    } else {
                        $date = CDate($timestamp);
                        if ($includeTime == true) {
                            return sprintf(GetLang('OnDateAtTime'), $date, $time);
                        } else {
                            return sprintf(GetLang('OnDate'), $date);
                        }
                    }
                }
            }
        }
    }
}
예제 #30
0
	/**
	 * Create the pending order in the database with the customers selected payment details, etc.
	 *
	 * @return array An array containing information about what needs to be done next.
	 */
	public function SavePendingOrder()
	{
		$provider = null;
		$verifyPaymentProvider = true;
		$redirectToFinishOrder = false;
		$providerId = '';

		$pendingOrderResult = array();
		$creditUsed = 0;
		$giftCertificates = array();

		$orderTotal = $this->getQuote()->getGrandTotal();

		// store the discounted subtotal in the session for affiliate tracking
		$incTax = (getConfig('taxDefaultTaxDisplayOrders') == TAX_PRICES_DISPLAY_INCLUSIVE);
		$_SESSION['LAST_ORDER_DISCOUNTED_SUBTOTAL'] = $this->getQuote()->getDiscountedSubTotal($incTax);

		// Find out what currency we are using. We'll need this later to display their previous orders in the currency that they have selected
		$selectedCurrency = GetCurrencyById($GLOBALS['CurrentCurrency']);

		$giftCertificates = $this->getQuote()->getAppliedGiftCertificates();
		if(!empty($giftCertificates)) {
			$badCertificates = array();
			$remainingBalance = 0;
			$totalWithoutCertificates =
				$this->getQuote()->getGrandTotalWithoutGiftCertificates();
			$giftCertificateAmount =
				$this->getQuote()->getGiftCertificateTotal();
			getClass('ISC_GIFTCERTIFICATES')
				->giftCertificatesApplicableToOrder(
					$totalWithoutCertificates,
					$giftCertificates,
					$remainingBalance,
					$badCertificates);

			// One or more gift certificates were invalid so this order is now invalid
			if(!empty($badCertificates)) {
				$badCertificatesList = '<strong>'.GetLang('BadGiftCertificates').'</strong><ul>';
				foreach($badCertificates as $code => $reason) {
					if(is_array($reason) && $reason[0] == "expired") {
						$reason = sprintf(GetLang('BadGiftCertificateExpired'), CDate($reason[1]));
					}
					else {
						$reason = GetLang('BadGiftCertificate'.ucfirst($reason));
					}
					$badCertificatesList .= sprintf("<li>%s - %s", isc_html_escape($code), $reason);
				}
				$badCertificatesList .= "</ul>";
				$pendingOrderResult = array(
					'error' => GetLang('OrderContainedInvalidGiftCertificates'),
					'errorDetails' => $badCertificatesList
				);
				return $pendingOrderResult;
			}
			// This order was entirely paid for using gift certificates but the totals don't add up
			else if($totalWithoutCertificates == $giftCertificateAmount && $remainingBalance > 0) {
				$pendingOrderResult = array(
					'error' => GetLang('OrderTotalStillRemainingCertificates')
				);
				return $pendingOrderResult;
			}
			// Order was entirely paid for using gift certificates
			else if($totalWithoutCertificates == $giftCertificateAmount) {
				$providerId = 'giftcertificate';
				$verifyPaymentProvider = false;
				$redirectToFinishOrder = true;
			}
		}

		// If the order total is 0, then we just forward the user on to the "Thank You" page and set the payment provider to ''
		if($orderTotal == 0) {
			$providerId = '';
			$verifyPaymentProvider = false;
			$redirectToFinishOrder = true;
		}

		$selected_provider = '';
		if($verifyPaymentProvider) {
			$candidate = '';
			if (isset($_POST['checkout_provider']) && $_POST['checkout_provider'] != '') {
				$candidate = $_POST['checkout_provider'];
			} else if (isset($_POST['credit_checkout_provider']) && $_POST['credit_checkout_provider'] != '') {
				// used by paypal
				$candidate = $_POST['credit_checkout_provider'];
			}

			// Check if the chosen checkout method is valid
			$providers = GetCheckoutModulesThatCustomerHasAccessTo(true);
			foreach ($providers as $p) {
				if ($p['id'] == $candidate) {
					$selected_provider = $candidate;
				}
			}

			// If there's only one payment provider, then they're paying via that
			if($selected_provider == '' && count($providers) == 1) {
				$selected_provider = $providers[0]['object']->GetId();
			}

			// Are we using our store credit?
			$customer = getClass('ISC_CUSTOMER')->getCustomerDataByToken();
			if (isset($_POST['store_credit']) && $_POST['store_credit'] == 1
				&& $customer['custstorecredit'] > 0) {
					// User has not chosen a payment provider and can't afford this order using only store credit, throw back as error
					if ($selected_provider == '' && $customer['custstorecredit'] < $orderTotal) {
						return false;
					}
					// Otherwise we can use the store credit.
					// Subtract store credit from users account and send them to the finished page
					else {
						$onlyCredit = false;
						$updateExtra = '';
						// If we're only using store credit
						$creditToUse = $orderTotal;
						if ($customer['custstorecredit'] >= $creditToUse) {
							// Set the checkout provider
							$providerId = 'storecredit';
							$verifyPaymentProvider = false;
							$redirectToFinishOrder = true;
							$creditUsed = $creditToUse;
							$onlyCredit = true;
						}
						else {
							// Using all of our store credit to pay for this order and we owe more.
							$creditUsed = $customer['custstorecredit'];
						}
					}
			}
		}

		$orderStatus = ORDER_STATUS_INCOMPLETE;

		// Now with round 2, do we still need to verify the payment provider?
		if($verifyPaymentProvider) {
			// If there's more than one provider and one wasn't selected on the order confirmation screen then there's a problem
			if ((count($providers) == 0 ||
				(count($providers) > 1 && $selected_provider == '')) &&
					!isset($_SESSION['CHECKOUT']['ProviderListHTML'])) {
					return false;
			}

			// Is the payment provider selected actually valid?
			if (!GetModuleById('checkout', $provider, $selected_provider)) {
				return false;
			}
			$providerId = $provider->GetId();
		}

		if(isset($_COOKIE['SHOP_TOKEN'])) {
			$customerToken = $_COOKIE['SHOP_TOKEN'];
		}
		else {
			$customerToken = '';
		}

		$orderComments = '';
		if(isset($_REQUEST['ordercomments'])) {
			$orderComments = $_POST['ordercomments'];
		}

		// Set up the order to be created
		$this->getQuote()
			->setAppliedStoreCredit($creditUsed)
			->setCustomerMessage($orderComments);
			;

		$newOrder = array(
			'orderpaymentmodule' => $providerId,
			'ordcurrencyid' => $selectedCurrency['currencyid'],
			'ordcurrencyexchangerate' => $selectedCurrency['currencyexchangerate'],
			'ordipaddress' => getIp(),
			'ordstatus' => $orderStatus,
			'extraInfo' => array(),

			'quote' => $this->getQuote(),
		);


		// OK, we're successful down to here - do they want to create an account? If so then assign it to
		// a session so we can create the actual record on a successful order
		if(!empty($_SESSION['CHECKOUT']['CREATE_ACCOUNT']) ||
			!customerIsSignedIn() && getConfig('GuestCheckoutCreateAccounts')) {
				$createAccount = array(
					'addresses' => array()
				);
				if(!empty($_SESSION['CHECKOUT']['CREATE_ACCOUNT'])) {
					$createAccount['password'] = $_SESSION['CHECKOUT']['CREATE_ACCOUNT']['password'];
					$createAccount['customFormFields'] = $_SESSION['CHECKOUT']['CREATE_ACCOUNT']['customFields'];
				}
				else {
					$createAccount['autoCreated'] = 1;
				}

				// Handle saving of addresses for new customers
				foreach($this->getQuote()->getAllAddresses() as $address) {
					if($address->getSaveAddress()) {
						$customerAddress = $address->getAsArray();
						$customFields = $address->getCustomFields();
						if(!empty($customFields)) {
							$customerAddress['customFormFields'] = $customFields;

							// Shipping fields need to be mapped back to billing so they can be stored
							if($address->getType() == ISC_QUOTE_ADDRESS::TYPE_SHIPPING) {
								$newCustomFields = array();
								$map = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, array_keys($customFields));
								foreach($map as $oldId => $newId) {
									$newCustomFields[$newId] = $customFields[$oldId];
								}
								$customerAddress['customFormFields'] = $newCustomFields;
							}
						}

						$createAccount['addresses'][] = $customerAddress;
					}
				}

				$newOrder['extraInfo']['createAccount'] = $createAccount;
		}

		// Did they agree to signup to any mailing lists?
		if (isset($_POST['join_mailing_list'])) {
			$newOrder['extraInfo']['join_mailing_list'] = true;
		}

		if (isset($_POST['join_order_list'])) {
			$newOrder['extraInfo']['join_order_list'] = true;
		}

		if (isset($_POST['join_mailing_list']) || isset($_POST['join_order_list'])) {
			if (isset($_POST['mail_format_preference'])) {
				$newOrder['extraInfo']['mail_format_preference'] = (int)$_POST['mail_format_preference'];
			} else {
				$newOrder['extraInfo']['mail_format_preference'] = Interspire_EmailIntegration_Subscription::FORMAT_PREF_NONE;
			}
			$newOrder['extraInfo']['join_order_list'] = true;
		}


		if(isset($_POST['ordermessage'])) {
			$newOrder['ordermessage'] = $_POST['ordermessage'];
		} else {
			$newOrder['ordermessage'] = '';
		}

		$entity = new ISC_ENTITY_ORDER();
		$orderId = $entity->add($newOrder);

		// Failed to create the order
		if(!$orderId) {
			return false;
		}

		$order = getOrder($orderId);

		// Persist the pending order token as a cookie for 24 hours
		ISC_SetCookie("SHOP_ORDER_TOKEN", $order['ordtoken'], time() + (3600*24), true);
		$_COOKIE['SHOP_ORDER_TOKEN'] = $order['ordtoken'];

		// Redirecting to finish order page?
		if($redirectToFinishOrder) {
			return array(
				'redirectToFinishOrder' => true
			);
		}

		// Otherwise, the gateway want's to do something
		$orderData = LoadPendingOrdersByToken($order['ordtoken']);
		$provider->SetOrderData($orderData);

		// Is this an online payment provider? It would like to do something
		if($provider->GetPaymentType() == PAYMENT_PROVIDER_ONLINE || method_exists($provider, "ShowPaymentForm")) {
			// Call the checkout process for the selected provider
			if(method_exists($provider, "ShowPaymentForm")) {
				return array(
					'provider' => $provider,
					'showPaymentForm' => true
				);
			}
			else {
				return array(
					'provider' => $provider
				);
			}
		}
		// If an offline method, we throw them to the "Thank you for your order" page
		else {
			return array(
				'provider' => $provider
			);
		}
	}