/** * Output the service XML * * Method will construct the XML string using the information stored in $this->xmlNode and return the XML string * * @access protected * @param bool $isQuery TRUE if this service is a query, FALSE if not (add, mod, etc). Default is FALSE * @return string The constructed XML string */ protected function buildOutput($isQuery = false) { /** * Add the replacement for the client's qbXML version */ $clientVersion = $this->quickbooks->getAccountingSessionKey('QBXML_VERSION'); $clientCountry = $this->quickbooks->getAccountingSessionKey('CLIENT_COUNTRY'); /** * If this version 2-3 and where are UK/CA then we need to prepend the country code in the version */ if ((isc_strtolower($clientCountry) == "uk" || isc_strtolower($clientCountry) == "ca") && version_compare($clientVersion, "3.0") !== 1) { $version = isc_strtoupper($clientCountry) . (string) $clientVersion; } else { $version = (string) $clientVersion; } $GLOBALS['VersionNo'] = $version; $GLOBALS['EntityType'] = $this->data->service; $GLOBALS['EntityXML'] = $this->xmlNode->outputMemory(true); $xml = $this->quickbooks->ParseTemplate('module.quickbooks.qbxml', true); /** * If this is a query then remove the <$this->data->service> tags. Why can't everything be the same */ if ($isQuery) { $xml = str_replace('<' . $this->data->service . '>', '', $xml); $xml = str_replace('</' . $this->data->service . '>', '', $xml); } return $xml; }
public function GenerateLogo() { $this->NewLogo($this->FileType); // defaults to png. can use jpg or gif as well $this->FontPath = dirname(__FILE__) . '/fonts/'; $imageHeight = 50; $textLeft = 0; $textSize = 28; // we need the height of the text box to position the image and then caculate the text position $t_box = $this->TextBox($this->Text[0], 'ITCAvantGardeStd-Bold.otf', '4e4e42', $textSize, 0, 0); // determine the y position for the text $y_pos = 8+(($imageHeight - $t_box['height'])/2); if(strlen($this->Text[0]) > 0) { // AddText() - text, font, fontcolor, fontSize (pt), x, y, center on this width $this->Text[0] = isc_strtoupper($this->Text[0]); $text_position = $this->AddText($this->Text[0], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $textLeft-1, $y_pos-1); $text_position = $this->AddText($this->Text[0], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $textLeft-1, $y_pos+1); $text_position = $this->AddText($this->Text[0], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $textLeft+1, $y_pos-1); $text_position = $this->AddText($this->Text[0], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $textLeft+1, $y_pos+1); $text_position = $this->AddText($this->Text[0], 'ITCAvantGardeStd-Bold.otf', '4e4e42', $textSize, $textLeft, $y_pos); } if(strlen($this->Text[1]) > 0) { $this->Text[1] = isc_strtoupper($this->Text[1]); // put in our second bit of text $left = $text_position['top_right_x']+10; $text_position2 = $this->AddText($this->Text[1], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $left-1, $y_pos-1); $text_position2 = $this->AddText($this->Text[1], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $left-1, $y_pos+1); $text_position2 = $this->AddText($this->Text[1], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $left+1, $y_pos-1); $text_position2 = $this->AddText($this->Text[1], 'ITCAvantGardeStd-Bold.otf', 'ffffff', $textSize, $left+1, $y_pos+1); $text_position2 = $this->AddText($this->Text[1], 'ITCAvantGardeStd-Bold.otf', 'a88b67', $textSize, $left, $y_pos); $top_right = $text_position2['top_right_x']; } else { $top_right = $text_position['top_right_x']; } $this->TransparentBackground = true; $this->SetImageSize($top_right+20, $imageHeight); $this->CropImage = true; return $this->MakeLogo(); }
/** * Include the form field code file * * Method will include (once) the form field code file * * @access private * @param string $fieldType The field type to include * @return string The class name of the field class if the code source file was found and * included successfully, FALSE if not */ private function includeFormFieldCode($fieldType) { $typeToLower = isc_strtolower($fieldType); if ($typeToLower == '' || $typeToLower == 'base' || preg_match('/[^a-z]+/', $typeToLower)) { return false; } $filepath = $this->fieldPath . '/formfield.' . $typeToLower . '.php'; if (!file_exists($filepath) || !is_file($filepath)) { return false; } $className = "ISC_FORMFIELD_" . isc_strtoupper($fieldType); if (!class_exists($className)) { include_once $filepath; } return $className; }
/** * Generic second step of the importer. Handles uploaded files, parses out first row and shows field matching page. */ protected function _ImportStep2() { $importer = new ISC_ADMIN_CSVPARSER; // Haven't been to this step before, need to parse CSV file if (!isset($this->ImportSession['FieldSeparator'])) { if (isset($_POST['Headers'])) { $this->ImportSession['Headers'] = $_POST['Headers']; } if (isset($_POST['OverrideDuplicates'])) { $this->ImportSession['OverrideDuplicates'] = $_POST['OverrideDuplicates']; } // Using a file off the server if (isset($_POST['serverfile']) && $_POST['serverfile'] != "") { $_POST['serverfile'] = basename($_POST['serverfile']); if (!is_file($this->ServerImportDirectory . "/". $_POST['serverfile'])) { $this->_ImportStep1(GetLang('ImportInvalidServerFile'), MSG_ERROR); $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter(); exit; } $newfilename = $this->ServerImportDirectory . '/' . $_POST['serverfile']; } else { if (!isset($_FILES['importfile'])) { $this->_ImportStep1($this->_GetUploadError(0), MSG_ERROR); $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter(); exit; } if (!is_uploaded_file($_FILES['importfile']['tmp_name']) || $_FILES['importfile']['error']) { $this->_ImportStep1($this->_GetUploadError($_FILES['importfile']['error']), MSG_ERROR); $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter(); exit; } // Move the uploaded file to the cache directory temporarily with a new unique name while(true) { $newfilename = ISC_TMP_IMPORT_DIRECTORY . '/' . $this->type . '-import-' . md5(uniqid(rand(), true)); if (!is_file($newfilename)) { break; } } if (!move_uploaded_file($_FILES['importfile']['tmp_name'], $newfilename)) { $this->_ImportStep1(GetLang('ImportUploadMoveFailed'), MSG_ERROR); $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter(); exit; } } $separator = html_entity_decode($_POST['FieldSeparator']); // convert to actual tab separator if (trim(isc_strtoupper($separator)) == "TAB") { $separator = " "; } $this->ImportSession['FieldEnclosure'] = html_entity_decode($_POST['FieldEnclosure']); $this->ImportSession['FieldSeparator'] = $separator; if (isset($this->ImportSession['FieldSeparator']) && $this->ImportSession['FieldSeparator'] != "") { $importer->FieldSeparator = $this->ImportSession['FieldSeparator']; } if (isset($this->ImportSession['FieldEnclosure']) && $this->ImportSession['FieldEnclosure'] != "") { $importer->FieldEnclosure = $this->ImportSession['FieldEnclosure']; } $this->ImportSession['ImportFile'] = $newfilename; $importer->OpenCSVFile($newfilename); $header = $importer->FetchNextRecord(); $importer->CloseCSVFile(); $this->ImportSession['TotalFileSize'] = filesize($newfilename); $this->ImportSession['LastPosition'] = 0; $this->ImportSession['PageSize'] = 3000; if (!$header) { $this->_ImportStep1('Invalid file', MSG_ERROR); $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter(); exit; } if (isset($_POST['Headers']) && $_POST['Headers'] == 1) { $this->ImportSession['Header'] = $header; } } // Already been past this step once, no need to reparse CSV file else { $importer->OpenCSVFile($this->ImportSession['ImportFile']); $header = $importer->FetchNextRecord(); $importer->CloseCSVFile(); } $this->_PreFieldMatch($header); $fieldlist = ''; foreach($this->_ImportFields as $column => $field) { $fieldlist .= $this->_buildMatchField($column, $field, $header); } $GLOBALS['ImportFieldList'] = $fieldlist; $GLOBALS['ImportSession'] = $_REQUEST['ImportSession']; $this->SaveImportSession(); $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader(); $this->template->display('import.'.$this->type.'.step2.tpl'); $GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter(); }
public function VerifyOrderPayment() { $callertoken = $_REQUEST['CallerTokenId']; $receipttoken = $_REQUEST['RecipientTokenId']; $sendertoken = $_REQUEST['tokenID']; $status = $_REQUEST['status']; $orderid = $_REQUEST['Order']; $key = $_REQUEST['Key']; $sessionId = $_REQUEST['SessionId']; $amount = $_REQUEST['PaymentAmount']; if(empty($status)) { return false; } if (!in_array(isc_strtoupper($status), array('SA', 'SB', 'SC'))) { $amazonStatusCodes = $this->getStatusCodes(); if(isset($amazonStatusCodes[$status])) { $amazonSaid = "Amazon Said: ". $amazonStatusCodes[$status]; } else { $amazonSaid = "Unknown status '" . isc_htmlencode($status) ."' returned from Amazon."; } $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('AmazonFpsPaymentError'), 'Status returned unsuccessful. '. $amazonSaid . '<br />' . '<pre>' . isc_htmlencode(var_export($_REQUEST, true)) . '</pre>'); return false; } if ($this->GetCombinedOrderId() != $orderid) { $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('AmazonFpsErrorOrderId'), '<pre>' . isc_htmlencode(var_export($_REQUEST, true)) . '</pre>'); return false; } if ($this->GetGatewayAmount() != $amount) { $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('AmazonFpsErrorGatewayAmount'), '<pre>' . isc_htmlencode(var_export($_REQUEST, true)) . '</pre>'); return false; } if (md5($this->GetValue("accessid").$orderid.$sessionId.$amount.$callertoken.$receipttoken) != $key) { $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('AmazonFpsErrorHash'), '<pre>' . isc_htmlencode(var_export($_REQUEST, true)) . '</pre>'); return false; } $chargeFeeTo = 'Recipient'; $date = date('Y-m-d')."T".date('H:i:s'); $callerReference = 'Order-'.$orderid.microtime(true); $timestamp = gmdate("Y-m-d\TH:i:s\Z"); $params = array( 'Action' => 'Pay', 'CallerTokenId' => $callertoken, 'SenderTokenId' => $sendertoken, 'RecipientTokenId' => $receipttoken, 'TransactionAmount.Amount' => round($amount,2), 'TransactionAmount.CurrencyCode' => 'USD', 'TransactionDate' => $date, 'ChargeFeeTo' => $chargeFeeTo, 'CallerReference' => $callerReference, 'Timestamp' => $timestamp, 'Version' => '2007-01-08', 'AWSAccessKeyId' => $this->GetValue('accessid'), ); if ($this->GetValue('testmode') == "YES") { $url = 'https://fps.sandbox.amazonaws.com/'; } else { $url = 'https://fps.amazonaws.com/'; } if(function_exists("curl_exec")) { // Use CURL if it's available $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getSignedParamString($url, $params, 'POST')); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Setup the proxy settings if there are any if (GetConfig('HTTPProxyServer')) { curl_setopt($ch, CURLOPT_PROXY, GetConfig('HTTPProxyServer')); if (GetConfig('HTTPProxyPort')) { curl_setopt($ch, CURLOPT_PROXYPORT, GetConfig('HTTPProxyPort')); } } if (GetConfig('HTTPSSLVerifyPeer') == 0) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } $result = curl_exec($ch); if(curl_errno($ch)) { $this->SetError(GetLang($this->_languagePrefix."SomethingWentWrong") . $this->GetValue('displayname') . ":" .curl_error($ch)); return false; } } if (!empty($result)) { $xml = new SimpleXMLElement($result); } else { $this->SetError(GetLang($this->_languagePrefix."SomethingWentWrong") . $this->GetValue('displayname')); return false; } $transaction = GetClass('ISC_TRANSACTION'); $previousTransaction = $transaction->LoadByTransactionId($sendertoken, $this->GetId()); // Already processed before, HALT and log error if(is_array($previousTransaction) && $previousTransaction['transactionid']) { $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), sprintf(GetLang('AmazonFpsAlreadyProcessed'), $sendertoken)); return false; } $newTransaction = array( 'providerid' => $this->GetId(), 'transactiondate' => time(), 'transactionid' => $sendertoken, 'orderid' => array_keys($this->GetOrders()), 'message' => '', 'status' => '', 'amount' => $amount, 'extrainfo' => array() ); if ($xml->Status == 'Failure') { $this->SetError("Status : " . $xml->Status . ":" . $xml->Errors->Errors->ReasonText); $newTransaction['status'] = TRANS_STATUS_FAILED; $newTransaction['message'] = (string)$xml->Errors->Errors->ReasonText; $transactionId = $transaction->Create($newTransaction); return false; } if ($xml->Status == 'Success') { $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang('AmazonFpsSuccess')); $this->SetPaymentStatus(PAYMENT_STATUS_PAID); $newTransaction['status'] = TRANS_STATUS_COMPLETED; $newTransaction['message'] = 'Success'; $transactionId = $transaction->Create($newTransaction); return true; } return false; }
/** * Return the object of a module based on the passed ID. * * @param string The type of module that needs to be loaded. * @param object The object of the module, returned by reference. * @param string The ID of the module to load. * @return boolean True if successful, false if not. */ function GetModuleById($type, &$returned_module, $id) { $valid_types = array('accounting', 'analytics', 'checkout', 'notification', 'shipping', 'currency', 'livechat', 'addon', 'rule'); if (!in_array($type, $valid_types)) { return false; } // Try and load the module $idPieces = explode('_', $id, 2); if (isset($idPieces[1])) { $id = basename($idPieces[1]); } // Filter to allowable characters (a-zA-Z0-9-_) $id = preg_replace('#[^a-z0-9\\-_]#i', '', $id); if ($type == 'addon') { $moduleFile = ISC_BASE_PATH . '/addons/' . $id . '/addon.' . $id . '.php'; } else { $moduleFile = ISC_BASE_PATH . '/modules/' . $type . '/' . $id . '/module.' . $id . '.php'; } $className = isc_strtoupper($type . '_' . $id); if (!file_exists($moduleFile)) { return false; } include_once $moduleFile; if (!class_exists($className)) { return false; } $returned_module = new $className(); return true; }
/** * Unset the transaction session * * Method will unset the transaction session * * @access protected * @param string $moduleid The module ID * @return bool TRUE if the session was unset, FALSE on error */ protected function unsetAccountingSession($moduleid) { if ($moduleid == '') { return false; } $modkey = isc_strtoupper($moduleid); if (isset($_SESSION[$modkey])) { unset($_SESSION[$modkey]); } return !isset($_SESSION[$modkey]); }
/** * Validates the posted form data * * @param int $templateid The template used when checking for existing template name */ private function ValidateInput($templateid = 0) { // check for template name if (!isset($_POST["templateName"]) || !trim($_POST["templateName"])) { throw new Exception(GetLang("NoTemplateName")); } else { $templatename = trim($_POST["templateName"]); // check for existing template $query = "SELECT * FROM [|PREFIX|]import_templates WHERE UCASE(importtemplatename) = '" . $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtoupper($templatename)) . "'"; if ($templateid) { $query .= " AND importtemplateid != '" . $GLOBALS['ISC_CLASS_DB']->Quote($templateid) . "'"; } $vendorid = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(); $query .= " AND vendorid = '" . $GLOBALS['ISC_CLASS_DB']->Quote($vendorid) . "'"; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if ($GLOBALS['ISC_CLASS_DB']->CountResult($result)) { throw new Exception(sprintf(GetLang("TemplateAlreadyExists"), $templatename)); } } }
public function convert_accounting_spool() { $query = "ALTER TABLE [|PREFIX|]accountingref MODIFY `accountingreftype` enum('customer','customergroup','product','order','salestaxcode','account','inventorylevel','orderlineitem') NOT NULL"; if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) { $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()); return false; } if (!$this->TableExists('accountingspool')) { $query = "\n\t\t\t\tCREATE TABLE `[|PREFIX|]accountingspool` (\n\t\t\t\t `accountingspoolid` int(10) unsigned NOT NULL auto_increment,\n\t\t\t\t `accountingspoolparentid` int(10) unsigned NOT NULL default '0',\n\t\t\t\t `accountingspoolmoduleid` varchar(100) NOT NULL default '',\n\t\t\t\t `accountingspoolnodeid` int(10) unsigned NOT NULL default '0',\n\t\t\t\t `accountingspoolserial` text,\n\t\t\t\t `accountingspooltype` enum('customer','customergroup','product','order','salestaxcode','account','inventorylevel') NOT NULL,\n\t\t\t\t `accountingspoolservice` enum('add','edit','query') NOT NULL,\n\t\t\t\t `accountingspoollock` char(36) NOT NULL default '',\n\t\t\t\t `accountingspoolstatus` tinyint(1) default '0',\n\t\t\t\t `accountingspooldisabled` tinyint(1) NOT NULL default '0',\n\t\t\t\t `accountingspoolerrmsg` tinytext,\n\t\t\t\t `accountingspoolerrno` int(10) unsigned NOT NULL default '0',\n\t\t\t\t `accountingspoolreturn` text,\n\t\t\t\t PRIMARY KEY (`accountingspoolid`),\n\t\t\t\t KEY `i_accountingspool_accountingspoolparentid` (`accountingspoolparentid`),\n\t\t\t\t KEY `i_accountingspool_accountingspoolmoduleid` (`accountingspoolmoduleid`),\n\t\t\t\t KEY `i_accountingspool_accountingspoolnodeid` (`accountingspoolnodeid`),\n\t\t\t\t KEY `i_accountingspool_accountingspooltype` (`accountingspooltype`)\n\t\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=utf8;"; if (!$GLOBALS['ISC_CLASS_DB']->Query($query)) { $this->SetError($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()); return false; } /** * If this table already exists and it has records in it then DO NOT import the spool files as order will double up and could potentially duplciate * products and customers */ } else { $result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]accountingspool"); if ($result && $GLOBALS['ISC_CLASS_DB']->CountResult($result) > 0) { return true; } } /** * Now convert the existsing spool files into database accountingspool records. Force out the mandatory account spools just in case */ $accounting = GetClass('ISC_ACCOUNTING'); $initdata = array(array('type' => 'account', 'service' => 'add', 'data' => array('Name' => GetLang('QuickBooksIncomeAccountName'), 'AccountType' => 'Income')), array('type' => 'account', 'service' => 'add', 'data' => array('Name' => GetLang('QuickBooksCOGSAccountName'), 'AccountType' => 'CostOfGoodsSold')), array('type' => 'account', 'service' => 'add', 'data' => array('Name' => GetLang('QuickBooksAssetAccountName'), 'AccountType' => 'FixedAsset'))); foreach ($initdata as $data) { $accounting->createServiceRequest($data['type'], $data['service'], $data['data']); } /** * Now for the rest. These will be in the spool cache file so you'll need to read the files from there */ $files = scandir(ISC_BASE_PATH . '/cache/spool'); foreach ($files as $file) { $realfile = ISC_BASE_PATH . '/cache/spool/' . $file; if (!is_file($realfile) || !is_readable($realfile) || substr($file, 0, 6) !== 'spool.') { continue; } $spooldata = null; @(include_once $realfile); if (!is_array($spooldata)) { continue; } /** * Find out if this entity exists. If not then do not import it */ if (isId($spooldata['nodeid'])) { $className = "ISC_ENTITY_" . isc_strtoupper($spooldata['type']); $entity = new $className(); if (!$entity->exists($spooldata['nodeid'])) { continue; } /** * Save it using the data array instead of the nodeid as they might delete that entity before they import */ $savedata = $entity->get($spooldata['nodeid']); if (!$savedata) { continue; } } else { continue; } switch (isc_strtolower($spooldata['type'])) { case 'order': /** * We need to check if the customer and all of the products for this order still exist */ $query = "SELECT IF(EXISTS(SELECT * FROM [|PREFIX|]customers c WHERE o.ordcustid=c.customerid), 1, 0) AS CustomerExists,\n\t\t\t\t\t\t\t\t\t(SELECT COUNT(*) FROM [|PREFIX|]order_products op1 WHERE op1.orderorderid=o.orderid) AS TotalProducts,\n\t\t\t\t\t\t\t\t\t(SELECT COUNT(*) FROM [|PREFIX|]order_products op2 JOIN [|PREFIX|]products p ON op2.ordprodid=p.productid WHERE op2.orderorderid=o.orderid) AS ValidProducts\n\t\t\t\t\t\t\t\tFROM [|PREFIX|]orders o\n\t\t\t\t\t\t\t\tWHERE o.orderid=" . (int) $spooldata['nodeid']; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if (!$result) { break; } $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result); if (!$row) { break; } if (!$row['CustomerExists'] || $row['TotalProducts'] !== $row['ValidProducts']) { break; } $accounting->createServiceRequest('order', 'add', $savedata, 'order_create'); break; case 'product': case 'customer': case 'customergroup': /** * Find out if this is an add or mod. If query then skip */ if (substr(isc_strtolower($spooldata['service']), -3) == 'add') { $permission = 'create'; $service = 'add'; } else { if (substr(isc_strtolower($spooldata['service']), -3) == 'mod') { $permission = 'edit'; $service = 'edit'; } else { break; } } if (isc_strtolower($spooldata['type']) == 'product') { $permission = 'product_' . $permission; } else { $permission = 'customer_' . $permission; } $accounting->createServiceRequest(isc_strtolower($spooldata['type']), $service, $savedata, $permission); break; default: break; } } return true; }
private function GetCurrencyDataFromPost() { $data = array( 'currencyname' => $_POST['currencyname'], 'currencycode' => isc_strtoupper($_POST['currencycode']), 'currencyconvertercode' => $_POST['currencyconverter'], 'currencyexchangerate' => $_POST['currencyexchangerate'], 'currencystringposition' => isc_strtoupper($_POST['currencystringposition']), 'currencystring' => $_POST['currencystring'], 'currencydecimalstring' => $_POST['currencydecimalstring'], 'currencythousandstring' => $_POST['currencythousandstring'], 'currencydecimalplace' => $_POST['currencydecimalplace'], 'currencylastupdated' => time() ); if (strtolower($_POST['currencyorigintype']) == "country") { $data['currencycouregid'] = null; $data['currencycountryid'] = $_POST["currencyorigin"]; } else if (strtolower($_POST['currencyorigintype']) == "region") { $data['currencycouregid'] = $_POST["currencyorigin"]; $data['currencycountryid'] = null; } if (isset($_POST['currencystatus'])) { $data['currencystatus'] = 1; } else { $data['currencystatus'] = 0; } return $data; }
public function ManageProductsGrid(&$numProducts) { // Show a list of products in a table $page = 0; $start = 0; $numProducts = 0; $GLOBALS['ProductGrid'] = ""; $max = 0; // 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($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) { $featuredColumn = 'prodvendorfeatured'; } else { $featuredColumn = 'prodfeatured'; } $validSortFields = array('productid', 'prodcode', 'currentinv', 'prodname', 'prodcalculatedprice', 'prodvisible', $featuredColumn, '_calc_prodstatus'); if(isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == "asc") { $sortOrder = "asc"; } else { $sortOrder = "desc"; } if(isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) { $sortField = $_REQUEST['sortField']; SaveDefaultSortField("ManageProducts", $_REQUEST['sortField'], $sortOrder); } else { list($sortField, $sortOrder) = GetDefaultSortField("ManageProducts", "productid", $sortOrder); } if(isset($_GET['page'])) { $page = (int)$_GET['page']; } else { $page = 1; } if (isset($_GET['perpage'])) { $perPage = (int)$_GET['perpage']; SaveDefaultPerPage("ManageProducts", $perPage); } else { $perPage = GetDefaultPerPage("ManageProducts", ISC_PRODUCTS_PER_PAGE); } if(isset($_GET['filterCategory']) && $_GET['filterCategory'] == "-1") { $GLOBALS['FilterLow'] = "selected=\"selected\""; } if(isset($_GET['filterCategory'])) { $filterCat = (int)$_GET['filterCategory']; } else { $filterCat = 0; } if(!gzte11(ISC_MEDIUMPRINT)) { $GLOBALS['ProductNameSpan'] = 3; $GLOBALS['HideInventoryOptions'] = 'none'; } else { $GLOBALS['HideInventoryOptions'] = ''; } // Build the search and sort URL $searchURL = $this->buildSearchUrlData($_GET, $sortField, $sortOrder); $this->buildLetterSearchUrlData($searchURL); $sortURL = $searchURL; unset($sortURL['sortField'], $sortURL['sortOrder']); // Limit the number of questions returned if($page == 1) { $start = 1; } else { $start = ($page * $perPage) - ($perPage-1); } $start = $start-1; // Get the results for the query $product_result = $this->_GetProductList($start, $sortField, $sortOrder, $numProducts, '', $perPage); $GLOBALS['perPage'] = $perPage; $GLOBALS['numProducts'] = $numProducts; $GLOBALS['pageURL'] = "index.php?ToDo=viewProducts&" . http_build_query($searchURL); $GLOBALS['currentPage'] = $page; if (isset($_REQUEST['searchQuery'])) { $query = $_REQUEST['searchQuery']; } else { $query = ''; } $GLOBALS['EscapedQuery'] = isc_html_escape($query); $GLOBALS['SearchQuery'] = isc_html_escape($query); $GLOBALS['SortField'] = $sortField; $GLOBALS['SortOrder'] = $sortOrder; if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) { $featuredColumn = 'prodvendorfeatured'; } else { $featuredColumn = 'prodfeatured'; } $sortLinks = array( "Code" => "prodcode", "Stock" => "currentinv", "Name" => "prodname", "Price" => "prodcalculatedprice", "Status" => "_calc_prodstatus", "Visible" => "prodvisible", "Featured" => $featuredColumn ); BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewProducts&".http_build_query($sortURL)."&page=".$page, $sortField, $sortOrder); // Workout the maximum size of the array $max = $start + $perPage; if ($max > $numProducts) { $max = $numProducts; } if($numProducts > 0) { // Display the products while($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($product_result)) { if ($row['prodcode'] == "") { $GLOBALS['SKU'] = GetLang('NA'); } else { $GLOBALS['SKU'] = isc_html_escape($row['prodcode']); } $GLOBALS['ProductId'] = (int)$row['productid']; $GLOBALS['Name'] = sprintf("<a title='%s' class='Action' href='%s' target='_blank'>%s</a>", GetLang('ProductView'), ProdLink($row['prodname']), isc_html_escape($row['prodname'])); // Do we need to show product thumbnails? if(GetConfig('ShowThumbsInControlPanel')) { if ($row['imageid'] !== null) { $image = new ISC_PRODUCT_IMAGE(); $image->populateFromDatabaseRow($row); try { $imageThumbnailUrl = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true); $imageDimensions = $image->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY); $GLOBALS['ProductImage'] = sprintf('<img src="%1$s" width="%2$d" height="%3$d" />', isc_html_escape($imageThumbnailUrl), $imageDimensions[0], $imageDimensions[1]); } catch (Exception $exception) { // source image is not readable, show the no image placeholder $GLOBALS['ProductImage'] = sprintf("<div class='NoThumb'>%s<br />%s<br />%s</div>", GetLang('NoImage1'), GetLang('NoImage2'), GetLang('NoImage3')); } } else { $GLOBALS['ProductImage'] = sprintf("<div class='NoThumb'>%s<br />%s<br />%s</div>", GetLang('NoImage1'), GetLang('NoImage2'), GetLang('NoImage3')); } } else { // Use JavaScript to hide the thumbnail field $GLOBALS['HideThumbnailField'] = "1"; } $GLOBALS['Price'] = FormatPrice($row['prodcalculatedprice']); $GLOBALS['StockExpand'] = " "; $GLOBALS['LowStockStyle'] = ""; if ($row['prodinvtrack'] == 0) { $GLOBALS['StockInfo'] = GetLang('NA'); } else if($row['prodinvtrack'] > 0) { $GLOBALS['StockExpand'] = sprintf("<a href=\"#\" onclick=\"ShowStock('%d', '%d', '%d'); return false;\"><img id=\"expand%d\" src=\"images/plus.gif\" align=\"left\" class=\"ExpandLink\" width=\"19\" height=\"16\" title=\"%s\" border=\"0\"></a>", $row['productid'], $row['prodinvtrack'], $row['prodvariationid'], $row['productid'], GetLang('ClickToViewStock')); $percent = 0; if($row['prodlowinv'] > 0) { $percent = ceil(($row['currentinv'] / ($row['prodlowinv'] * 2)) * 100); } elseif ($row['currentinv'] > 0) { $percent = 100; } if($percent > 100) { $percent = 100; } if($percent > 75) { $stockClass = 'InStock'; $orderMore = GetLang('SNo'); } else if($percent > 50) { $stockClass = 'StockWarning'; $orderMore = GetLang('Soon'); } else { $stockClass = 'LowStock'; $orderMore = GetLang('SYes'); } $width = ceil(($percent/100)*72); $stockInfo = sprintf(GetLang('CurrentStockLevel').': %s<br />'.GetLang('LowStockLevel1').': %s<br />'.GetLang('OrderMore').': '.$orderMore, $row['currentinv'], $row['prodlowinv'], $orderMore); $GLOBALS['StockInfo'] = sprintf("<div class=\"StockLevelIndicator\" onmouseover=\"ShowQuickHelp(this, '%s', '%s')\" onmouseout=\"HideQuickHelp(this)\"><span class=\"%s\" style=\"width: %spx\"></span></div>", GetLang('StockLevel'), $stockInfo, $stockClass, $width); } // If they have permission to edit products, they can change // the visibility status of a product by clicking on the icon if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) { if ($row['prodvisible'] == 1) { $GLOBALS['Visible'] = sprintf("<a title='%s' href='index.php?ToDo=editProductVisibility&prodId=%d&visible=0' onclick=\"quickToggle(this, 'visible'); return false;\"><img border='0' src='images/tick.gif' alt='tick'></a>", GetLang('ClickToHide'), $row['productid']); } else { $GLOBALS['Visible'] = sprintf("<a title='%s' href='index.php?ToDo=editProductVisibility&prodId=%d&visible=1' onclick=\"quickToggle(this, 'visible'); return false;\"><img border='0' src='images/cross.gif' alt='cross'></a>", GetLang('ClickToShow'), $row['productid']); } } else { if ($row['prodvisible'] == 1) { $GLOBALS['Visible'] = '<img border="0" src="images/tick.gif" alt="tick">'; } else { $GLOBALS['Visible'] = '<img border="0" src="images/cross.gif" alt="cross">'; } } // If they have permission to edit products, they can change // the featured status of a product by clicking on the icon if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) { $featuredColumn = 'prodvendorfeatured'; } else { $featuredColumn = 'prodfeatured'; } if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) { if ($row[$featuredColumn] == 1) { $GLOBALS['Featured'] = sprintf("<a title='%s' href='index.php?ToDo=editProductFeatured&prodId=%d&featured=0' onclick=\"quickToggle(this, 'featured'); return false;\"><img border='0' src='images/tick.gif' alt='tick'></a>", GetLang('ClickToHide'), $row['productid']); } else { $GLOBALS['Featured'] = sprintf("<a title='%s' href='index.php?ToDo=editProductFeatured&prodId=%d&featured=1' onclick=\"quickToggle(this, 'featured'); return false;\"><img border='0' src='images/cross.gif' alt='cross'></a>", GetLang('ClickToShow'), $row['productid']); } } else { if ($row[$featuredColumn] == 1) { $GLOBALS['Featured'] = '<img border="0" src="images/tick.gif" alt="tick">'; } else { $GLOBALS['Featured'] = '<img border="0" src="images/cross.gif" alt="cross">'; } } // Workout the edit link -- do they have permission to do so? if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) { $GLOBALS['EditProductLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=editProduct&productId=%d'>%s</a>", GetLang('ProductEdit'), $row['productid'], GetLang('Edit')); } else { $GLOBALS['EditProductLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit')); } $allowpurchases = (int)$row['prodallowpurchases']; $prodpreorder = (int)$row['prodpreorder']; $status = GetLang('CatalogueOnly'); if ($allowpurchases) { if ($prodpreorder) { $status= GetLang('PreOrder'); } else { $status = GetLang('Selling'); } } $GLOBALS['Status'] = $status; $GLOBALS['CopyProductLink'] = "<a title='".GetLang('ProductCopy')."' class='Action' href='index.php?ToDo=copyProduct&productId=".$row['productid']."'>".GetLang('Copy')."</a>"; $GLOBALS['ProductGrid'] .= $this->template->render('product.manage.row.tpl'); } } if($GLOBALS['ProductGrid'] == '') { if(isset($_REQUEST['letter'])) { $GLOBALS['ProductGrid'] = sprintf('<tr> <td colspan="11" style="padding:10px"><em>%s</em></td> </tr>', sprintf(GetLang('LetterSortNoResults'), isc_strtoupper($_REQUEST['letter']))); } } return $this->template->render('products.manage.grid.tpl'); }
/** * Export vendor payments (for all vendors or a specific vendor) to a CSV or XML file. */ private function ExportVendorPayments() { // 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); } ob_end_clean(); // Grab the queries we'll be executing $paymentQueries = $this->BuildVendorPaymentSearchQuery(0, $sortField, $sortOrder, false); $numPayments = $GLOBALS['ISC_CLASS_DB']->FetchOne($paymentQueries['countQuery']); if (!$numPayments) { header('Location: index.php?ToDo=viewVendorPayments'); exit; } // Set up the list of columns $columns = array('paymentid' => 'PAYMENT ID', 'paymentfrom' => 'PAYMENT FROM', 'paymentto' => 'PAYMENT TO', 'paymentvendorid' => 'PAYMENT VENDOR ID', 'vendorname' => 'PAYMENT VENDOR NAME', 'paymentamount' => 'PAYMENT AMOUNT', 'paymentforwardbalance' => 'OUTSTANDING BALANCE', 'paymentdate' => 'PAYMENT DATE', 'paymentmethod' => 'PAYMENT METHOD', 'paymentcomments' => 'PAYMENT COMMENTS'); if (!isset($_GET['format']) || $_GET['format'] == "csv") { $ext = 'csv'; } else { $ext = 'xml'; } $GLOBALS['ISC_CLASS_LOG']->LogAdminAction(isc_strtoupper($_REQUEST['format'])); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Disposition: attachment; filename=\"payments-" . isc_date("Y-m-d") . "." . $ext . "\";"); if ($ext == 'csv') { $row = ''; foreach ($columns as $field) { $row .= EXPORT_FIELD_ENCLOSURE . $field . EXPORT_FIELD_ENCLOSURE . EXPORT_FIELD_SEPARATOR; } echo rtrim($row, EXPORT_FIELD_SEPARATOR); echo EXPORT_RECORD_SEPARATOR; } else { echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; echo "<payments>\n"; } // Export the payments $result = $GLOBALS['ISC_CLASS_DB']->Query($paymentQueries['query']); while ($payment = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { // If CSV export, handle that now if ($ext == 'csv') { $row = ''; foreach ($columns as $k => $v) { switch ($k) { case 'paymentfrom': case 'paymentto': case 'paymentdate': $value = isc_date(GetConfig('ExportDateFormat'), $payment[$k]); break; case 'paymentamount': case 'paymentforwardbalance': $value = FormatPrice($payment[$k]); default: $value = $payment[$k]; } $value = str_replace(EXPORT_FIELD_ENCLOSURE, EXPORT_FIELD_ENCLOSURE . EXPORT_FIELD_ENCLOSURE, $value); $row .= EXPORT_FIELD_ENCLOSURE . $value . EXPORT_FIELD_ENCLOSURE . EXPORT_FIELD_SEPARATOR; } echo rtrim($row, EXPORT_FIELD_SEPARATOR); echo EXPORT_RECORD_SEPARATOR; @flush(); } else { echo "\t<payment paymentid=\"" . $payment['paymentid'] . "\">\n"; foreach ($columns as $k => $v) { switch ($k) { case 'paymentfrom': case 'paymentto': case 'paymentdate': $value = isc_date(GetConfig('ExportDateFormat'), $payment[$k]); break; case 'paymentamount': case 'paymentforwardbalance': $value = FormatPrice($payment[$k]); default: $value = $payment[$k]; } echo "\t\t<" . $k . "><![CDATA[" . $value . "]]></" . $k . ">\n"; flush(); } echo "\t</payment>\n"; } } if ($ext == 'xml') { echo "</payments>"; } exit; }
/** * Validates the posted form data * * @param int $templateid The template used when checking for existing template name */ private function ValidateInput($templateid = 0) { // check for template name if (!isset($_POST["templateName"]) || !trim($_POST["templateName"])) { throw new Exception(GetLang("NoTemplateName")); } else { $templatename = trim($_POST["templateName"]); // check for existing template $query = "SELECT * FROM [|PREFIX|]export_templates WHERE builtin = 0 AND UCASE(exporttemplatename) = '" . $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtoupper($templatename)) . "'"; if ($templateid) { $query .= " AND exporttemplateid != '" . $GLOBALS['ISC_CLASS_DB']->Quote($templateid) . "'"; } $vendorid = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(); $query .= " AND vendorid = '" . $GLOBALS['ISC_CLASS_DB']->Quote($vendorid) . "'"; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if ($GLOBALS['ISC_CLASS_DB']->CountResult($result)) { throw new Exception(sprintf(GetLang("TemplateAlreadyExists"), $templatename)); } } // ensure at least one file is selected if (!isset($_POST["includeType"])) { throw new Exception(GetLang("NoFilesSelected")); } // check for valid date format if (!array_key_exists($_POST['dateFormat'], $this->GetDateFormats())) { throw new Exception(GetLang("NoDateFormat")); } // check for valid price format if (!array_key_exists($_POST['priceFormat'], $this->GetPriceFormats())) { throw new Exception(GetLang("NoPriceFormat")); } // check for valid bool format if (!array_key_exists($_POST['boolFormat'], $this->GetBoolFormats())) { throw new Exception(GetLang("NoBoolFormat")); } // validate each type foreach ($_POST['includeType'] as $type => $blah) { // check that at least one field is checked for the type if (!isset($_POST[$type . "Field"])) { throw new Exception(sprintf(GetLang("NoFields"), $type)); } // check that ticked fields have a header $filetype = ISC_ADMIN_EXPORTFILETYPE_FACTORY::GetExportFileType($type); $fields = $filetype->FlattenFields($filetype->LoadFields()); foreach ($_POST[$type . "Field"] as $field => $val) { if (!isset($_POST[$type . "Header"][$field]) || !trim($_POST[$type . "Header"][$field])) { throw new Exception(GetLang("FieldNoHeader") . '"' . $fields[$field]['label'] . '"'); } } } }
public function SaveModuleSettings($settings=array(), $deleteFirst=true) { // validate the prefix $prefix = trim($settings['referenceprefix']); if ($prefix) { $prefix = isc_strtoupper(isc_substr($prefix, 0, 1)); if (!preg_match("/[a-zA-Z0-9]/", $prefix)) { $this->SetError(GetLang('BPAYInvalidPrefix')); $prefix = ""; } } $settings['referenceprefix'] = $prefix; $return = parent::SaveModuleSettings($settings, $deleteFirst); if ($this->HasErrors()) { return false; } else { return $ret; } }
/** * Get the file path and the class name of a class file * * Method will return an array where "file" will be the file path and "name" will be the class name * * @access public * @param string $type The class type ("classes", "handlers", "services" or "entities") * @param string $class The class name (Not the full name) * @param bool $includeParentBase TRUE to also find and include the base parent. Default is TRUE * @return array An array with the class file path and full class name on success, NULL if no result, FALSE on error */ public function findModuleClass($type, $class, $includeParentBase=true) { if (trim($type) == '' || trim($class) == '') { return false; } $filePathPrefix = dirname(__FILE__) . "/includes"; $classNamePrefix = "ACCOUNTING_QUICKBOOKS_"; switch (isc_strtolower($type)) { case "classes": $filePathPrefix .= "/classes/class."; $classNamePrefix .= "CLASS_"; break; case "handlers": $filePathPrefix .= "/handlers/handler."; $classNamePrefix .= "HANDLER_"; break; case "services": $filePathPrefix .= "/services/service."; $classNamePrefix .= "SERVICE_"; break; case "entities": $filePathPrefix .= "/entities/entity."; $classNamePrefix .= "ENTITY_"; break; default: return null; } $filePath = realpath($filePathPrefix . isc_strtolower($class) . ".php"); $className = $classNamePrefix . isc_strtoupper($class); if ($filePath == '' || !file_exists($filePath)) { $xargs = func_get_args(); $this->logError("Cannot find module class file", $xargs); return null; } if ($includeParentBase) { $basePath = realpath(realpath($filePathPrefix . "base.php")); if ($basePath == '' || !file_exists($basePath)) { $xargs = func_get_args(); $this->logError("Cannot find module base class file", $xargs); return null; } else { @include_once($basePath); } } return array("file" => $filePath, "class" => $className); }
/** * Fetch a list of supported importers by checking the importers directory. * * @return array Array of importers containing importer ID and configuraiton fields. */ public function FetchImporterList() { $importerRoot = APP_ROOT . "/includes/converter/importers/"; $files = scandir($importerRoot); foreach ($files as $file) { if (!is_file($importerRoot . $file) || isc_substr($file, -3) != "php") { continue; } require_once $importerRoot . $file; $file = isc_substr($file, 0, isc_strlen($file) - 4); $className = "ISC_ADMIN_CONVERTER_" . isc_strtoupper($file); if (!class_exists($className)) { continue; } $converter = new $className(); $importers[$file] = array("title" => $converter->title); if (method_exists($converter, "Configure")) { $importers[$file]['configuration'] = $converter->Configure(); } } return $importers; }
/** * Get the XML version no * * Method will return the XML version no * * @access private * @return string The XML version no */ private function getVersionNo() { $clientVersion = $this->getCompanySessionData("QBXML_VERSION"); $clientCountry = $this->getCompanySessionData("CLIENT_COUNTRY"); /** * If this version 2-3 and where are UK/CA then we need to prepend the country code in the version */ if ((isc_strtolower($clientCountry) == "uk" || isc_strtolower($clientCountry) == "ca") && version_compare($clientVersion, "3.0") !== 1) { $versionNo = isc_strtoupper($clientCountry) . $clientVersion; } else { $versionNo = number_format((float)$clientVersion, 1); } return $versionNo; }
/** * Export shipments to a CSV or XML file. */ private function ExportShipments() { // Is this a custom view? if (isset($_GET['searchId'])) { $this->customSearch = $GLOBALS['ISC_CLASS_ADMIN_CUSTOMSEARCH']->LoadSearch($_GET['searchId']); $_REQUEST = array_merge($_REQUEST, $this->customSearch['searchvars']); } // Validate the sort order if (isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == 'asc') { $sortOrder = 'asc'; } else { $sortOrder = 'desc'; } // Which fields can we sort by? $validSortFields = array('shipmentid', 'shipdate', 'shiporderid', 'shiporderdate', 'shipfullname'); if (isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) { $sortField = $_REQUEST['sortField']; SaveDefaultSortField('ManageShipments', $_REQUEST['sortField'], $sortOrder); } else { list($sortField, $sortOrder) = GetDefaultSortField('ManageShipments', 'shipmentid', $sortOrder); } ob_end_clean(); // Grab the queries we'll be executing $shipmentQueries = $this->BuildShipmentSearchQuery(0, $sortField, $sortOrder, false); $numShipments = $GLOBALS['ISC_CLASS_DB']->FetchOne($shipmentQueries['countQuery']); if (!$numShipments) { header('Location: index.php?ToDo=viewShipments'); exit; } // Set up the list of columns $columns = array('shipmentid' => 'SHIPMENT ID', 'shipdate' => 'DATE SHIPPED', 'shiporderid' => 'ORDER ID', 'shiporderdate' => 'ORDER DATE', 'shiptrackno' => 'TRACKING NO', 'shipmethod' => 'SHIPPING METHOD', 'shipbillfullname' => 'BILLING FULL NAME', 'shipbillfirstname' => 'BILLING FIRST NAME', 'shipbilllastname' => 'BILLING LAST NAME', 'shipbillcompany' => 'BILLING COMPANY', 'shipbillstreet1' => 'BILLING STREET 1', 'shipbillstreet2' => 'BILLING STREET 2', 'shipbillsuburb' => 'BILLING SUBURB', 'shipbillstate' => 'BILLING STATE', 'shipbillzip' => 'BILLING ZIP/POSTCODE', 'shipbillcountry' => 'BILLING COUNTRY', 'shipbillphone' => 'BILLING PHONE', 'shipshipfirstname' => 'SHIPPING FIRST NAME', 'shipshiplastname' => 'SHIPPING LAST NAME', 'shipshipfullname' => 'SHIPPING FULL NAME', 'shipshipcompany' => 'SHIPPING COMPANY', 'shipshipstreet1' => 'SHIPPING STREET 1', 'shipshipstreet2' => 'SHIPPING STREET 2', 'shipshipsuburb' => 'SHIPPING SUBURB', 'shipshipstate' => 'SHIPPING STATE', 'shipshipzip' => 'SHIPPING ZIP', 'shipshipcountry' => 'SHIPPING COUNTRY', 'shipshipphone' => 'SHIPPING PHONE', 'shipitems' => 'SHIPMENT ITEMS'); if (!isset($_GET['format']) || $_GET['format'] == "csv") { $ext = 'csv'; } else { $ext = 'xml'; } $GLOBALS['ISC_CLASS_LOG']->LogAdminAction(isc_strtoupper($_REQUEST['format'])); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Disposition: attachment; filename=\"shipments-" . isc_date("Y-m-d") . "." . $ext . "\";"); if ($ext == 'csv') { $row = ''; foreach ($columns as $field) { $row .= EXPORT_FIELD_ENCLOSURE . $field . EXPORT_FIELD_ENCLOSURE . EXPORT_FIELD_SEPARATOR; } echo rtrim($row, EXPORT_FIELD_SEPARATOR); echo EXPORT_RECORD_SEPARATOR; } else { echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; echo "<shipments>\n"; } // Export the shipments $result = $GLOBALS['ISC_CLASS_DB']->Query($shipmentQueries['query']); while ($shipment = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { if ($ext == 'csv') { $shipment['shipitems'] = ''; } else { $shipment['shipitems'] = array(); } $query = "\n\t\t\t\tSELECT itemid, itemprodid, itemordprodid, itemprodsku, itemprodname, itemqty\n\t\t\t\tFROM [|PREFIX|]shipment_items\n\t\t\t\tWHERE shipid='" . $shipment['shipmentid'] . "'\n\t\t\t"; $itemResult = $GLOBALS['ISC_CLASS_DB']->Query($query); while ($item = $GLOBALS['ISC_CLASS_DB']->Fetch($itemResult)) { if ($ext == 'csv') { $shipment['shipitems'] .= $item['itemprodid'] . '|' . $item['itemprodname'] . '|' . $item['itemprodsku'] . '|' . $item['itemqty'] . '~'; } else { $shipment['shipitems'][] = $item; } } if ($ext == 'csv') { $shipment['shipitems'] = rtrim($shipment['shipitems'], '~'); } // If CSV export, handle that now if ($ext == 'csv') { $row = ''; foreach ($columns as $k => $v) { switch ($k) { case 'shipbillfullname': $value = trim($shipment['shipbillfirstname'] . ' ' . $shipment['shipbilllastname']); break; case 'shipshipfullname': $value = trim($shipment['shipshipfirstname'] . ' ' . $shipment['shipshiplastname']); break; case 'shipdate': case 'shiporderdate': $value = isc_date(GetConfig('ExportDateFormat'), $shipment[$k]); break; default: $value = $shipment[$k]; } $value = str_replace(EXPORT_FIELD_ENCLOSURE, EXPORT_FIELD_ENCLOSURE . EXPORT_FIELD_ENCLOSURE, $value); $row .= EXPORT_FIELD_ENCLOSURE . $value . EXPORT_FIELD_ENCLOSURE . EXPORT_FIELD_SEPARATOR; } echo rtrim($row, EXPORT_FIELD_SEPARATOR); echo EXPORT_RECORD_SEPARATOR; @flush(); } else { echo "\t<shipment shipmentid=\"" . $shipment['shipmentid'] . "\">\n"; foreach ($columns as $k => $v) { switch ($k) { case 'shipbillfullname': $value = trim($shipment['shipbillfirstname'] . ' ' . $shipment['shipbilllastname']); break; case 'shipshipfullname': $value = trim($shipment['shipshipfirstname'] . ' ' . $shipment['shipshiplastname']); break; case 'shipdate': case 'shiporderdate': $value = isc_date(GetConfig('ExportDateFormat'), $shipment[$k]); break; case 'shipitems': echo "\t\t<items>\n"; foreach ($shipment['shipitems'] as $item) { echo "\t\t\t<item>\n"; foreach ($item as $itemKey => $itemVal) { echo "\t\t\t<" . $itemKey . "><![CDATA[" . $itemVal . "]]></" . $itemKey . ">\n"; } echo "\t\t\t</item>\n"; } echo "\t\t</items>\n"; continue 2; case 'shipmentid': continue 2; default: $value = $shipment[$k]; } echo "\t\t<" . $k . "><![CDATA[" . $value . "]]></" . $k . ">\n"; flush(); } echo "\t</shipment>\n"; } } if ($ext == 'xml') { echo "</shipments>"; } }
/** * _CheckPermissions * Create the database and perform other install-orientated tasks * * @param none * * @return void */ private function RunInstall() { $lk = ''; if(isset($_POST['LK'])) { $lk = ech0($_POST['LK']); } if(!$lk) { $installMessage = GetLang('LKBad'); $installCode = "badLicenseKey"; } if(!isset($_POST['StoreCountryLocationId']) || !isId($_POST['StoreCountryLocationId'])) { $_POST['StoreCountryLocationId'] = 227; // United States } if(!isset($_POST['StoreCurrencyCode']) || $_POST['StoreCurrencyCode'] == '') { $_POST['StoreCurrencyCode'] = 'USD'; } if(!isset($_POST['ShopPath']) || $_POST['ShopPath'] == '') { $installMessage = GetLang('InstallMissingShopPath'); $installCode = "missingShopPath"; } else if (isc_strlen($_POST['StoreCurrencyCode']) > 3) { $installMessage = GetLang('InstallInvalidStoreCurrencyCode'); $installCode = "invalidStoreCurrencyCode"; } else if(!isset($_POST['ShopPath']) || $_POST['ShopPath'] == '') { $installMessage = GetLang('InstallMissingShopPath'); $installCode = "missingShopPath"; } else if(!isset($_POST['UserEmail']) || $_POST['UserEmail'] == '') { $installMessage = GetLang('InstallMissingUserEmail'); $installCode = "missingUserEmail"; } else if(!isset($_POST['UserPass']) || $_POST['UserPass'] == '') { $installMessage = GetLang('InstallMissingUserPass'); $installCode = "missingUserPass"; } else if(!isset($_POST['dbServer']) || $_POST['dbServer'] == '') { $installMessage = GetLang('InstallMissingDbServer'); $installCode = "missingDbServer"; } else if(!isset($_POST['dbUser']) || $_POST['dbUser'] == '') { $installMessage = GetLang('InstallMissingDbUser'); $installCode = "missingDbUser"; } else if(!isset($_POST['dbPass'])) { $installMessage = GetLang('InstallMissingDbPass'); $installCode = "missingDbPass"; } else if(!isset($_POST['dbDatabase']) || $_POST['dbDatabase'] == '') { $installMessage = GetLang('InstallMissingDbDatabase'); $installCode = "missingDbDatabase"; } if(!isset($_POST['tablePrefix'])) { $_POST['tablePrefix'] = ''; } // One or more error messages were detected if(isset($installMessage)) { $errors = array( 0 => array( "code" => $installCode, "message" => $installMessage ) ); $this->ShowInstallErrors($installMessage, $errors, false, true); return; } // Try to connect to the database $db_type = GetConfig("dbType") . 'Db'; $db = new $db_type(); if(isset($GLOBALS['ISC_CFG']["dbEncoding"])) { $db->charset = $GLOBALS['ISC_CFG']["dbEncoding"]; } $connection = $db->Connect($_POST['dbServer'], $_POST['dbUser'], $_POST['dbPass'], $_POST['dbDatabase']); $db->TablePrefix = $_POST['tablePrefix']; if($connection) { $GLOBALS["ISC_CLASS_DB"] = &$db; // Are we running the required version of MySQL? $ver = $GLOBALS["ISC_CLASS_DB"]->FetchOne("select version() as ver"); $mysql_check = version_compare($ver, MYSQL_VERSION_REQUIRED); if($mysql_check < 0) { $message = sprintf(GetLang("MySQLV4Message"), MYSQL_VERSION_REQUIRED, $ver); $errors = array( 0 => array( "code" => "mysqlVersion", "extra" => $ver, "message" => $message ) ); $this->ShowInstallErrors($message, $errors, false, true); return; } else { // Run the database commands $queries = $this->template->render('install.schema.tpl'); $queries = str_replace("\r", "\n", str_replace("\r\n", "\n", $queries)); $queries = explode(";\n", $queries); $GLOBALS["ISC_CLASS_DB"]->Query("start transaction"); // Initialize the admin auth class to get the list of permissions $auth = new ISC_ADMIN_AUTH(); require_once(dirname(__FILE__) . "/class.user.php"); $userManager = GetClass('ISC_ADMIN_USER'); $pass = $_POST['UserPass']; $token = $userManager->_GenerateUserToken(); foreach($queries as $query) { $query = str_replace("%%PREFIX%%", $_POST['tablePrefix'], $query); $query = str_replace("%%EMAIL%%", $GLOBALS["ISC_CLASS_DB"]->Quote($_POST['UserEmail']), $query); $query = str_replace("%%TOKEN%%", $GLOBALS["ISC_CLASS_DB"]->Quote($token), $query); if(trim($query) != "") { $GLOBALS["ISC_CLASS_DB"]->Query($query); } } // update admin user password $user_id = $userManager->getUserByField('username', 'admin'); $userManager->updatePassword($user_id, $pass); // Give the admin user permissions $constants = get_defined_constants(); foreach($constants as $constant => $val) { if(is_numeric(strpos($constant, "AUTH_")) && strpos($constant, "AUTH_") == 0) { $newPermission = array( "permuserid" => $user_id, "permpermissionid" => $val ); $GLOBALS['ISC_CLASS_DB']->InsertQuery("permissions", $newPermission); } } // Set the version $db_version = array( 'database_version' => PRODUCT_VERSION_CODE ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('config', $db_version); // Install our default currency. We need to do it here as it also needs to be in the config file $GLOBALS['ISC_CLASS_DB']->Query("DELETE FROM [|PREFIX|]currencies"); $GLOBALS['ISC_CLASS_DB']->Query("ALTER TABLE [|PREFIX|]currencies AUTO_INCREMENT=1"); $currency = array( 'currencycountryid' => $_POST['StoreCountryLocationId'], 'currencycode' => isc_strtoupper($_POST['StoreCurrencyCode']), 'currencyname' => GetLang('InstallDefaultCurrencyName'), 'currencyexchangerate' => GetConfig('DefaultCurrencyRate'), 'currencystring' => html_entity_decode(GetLang('InstallDefaultCurrencyString')), 'currencystringposition' => isc_strtolower(GetLang('InstallDefaultCurrencyStringPosition')), 'currencydecimalstring' => GetLang('InstallDefaultCurrencyDecimalString'), 'currencythousandstring' => GetLang('InstallDefaultCurrencyThousandString'), 'currencydecimalplace' => GetLang('InstallDefaultCurrencyDecimalPlace'), 'currencylastupdated' => time(), 'currencyisdefault' => 1, 'currencystatus' => 1 ); $defaultCurrencyId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('currencies', $currency); // Insert the default/master shipping zone $GLOBALS['ISC_CLASS_DB']->Query("DELETE FROM [|PREFIX|]shipping_zones"); $GLOBALS['ISC_CLASS_DB']->Query("ALTER TABLE [|PREFIX|]shipping_zones AUTO_INCREMENT=1"); $masterZone = array( 'zonename' => 'Default Zone', 'zonetype' => 'country', 'zonefreeshipping' => 0, 'zonefreeshippingtotal' => 0, 'zonehandlingtype' => 'none', 'zonehandlingfee' => 0, 'zonehandlingseparate' => 1, 'zoneenabled' => 1, 'zonedefault' => 1 ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('shipping_zones', $masterZone); // Is there a custom SQL file to include? $customPath = ISC_BASE_PATH.'/custom'; if(file_exists($customPath.'/install.schema.tpl')) { $template = Interspire_Template::getInstance('custominstall', $customPath, array( 'cache' => getAdminTwigTemplateCacheDirectory(), 'auto_reload' => true )); $queries = $template->render('install.schema.tpl'); $queries = str_replace("\r", "\n", str_replace("\r\n", "\n", $queries)); $queries = explode(";\n", $queries); $GLOBALS['ISC_CLASS_DB']->StartTransaction(); foreach($queries as $query) { $query = str_replace("%%PREFIX%%", $_POST['tablePrefix'], $query); if(trim($query)) { $GLOBALS['ISC_CLASS_DB']->Query($query); } } $GLOBALS['ISC_CLASS_DB']->CommitTransaction(); } // Was there an error? if($GLOBALS["ISC_CLASS_DB"]->Error() == "") { $GLOBALS["ISC_CLASS_DB"]->Query("commit"); // Save the config file foreach($_POST as $k => $v) { $GLOBALS['ISC_NEW_CFG'][$k] = $v; } // Set the email address for this user as the store admin/order email address $GLOBALS['ISC_NEW_CFG']['AdminEmail'] = $_POST['UserEmail']; $GLOBALS['ISC_NEW_CFG']['OrderEmail'] = $_POST['UserEmail']; $GLOBALS['ISC_NEW_CFG']['serverStamp'] = $_POST['LK']; $GLOBALS['ISC_CFG']['serverStamp'] = $_POST['LK']; $settings = GetClass('ISC_ADMIN_SETTINGS'); $GLOBALS['ISC_NEW_CFG']['HostingProvider'] = ""; // Can we send server details back to Interspire? // If we can, the HostingProvider global will also be set if(isset($_POST['sendServerDetails'])) { $this->SendServerDetails(); if(isset($GLOBALS['InfoImage'])) { $GLOBALS['HiddenImage'] = $GLOBALS['InfoImage']; } } $GLOBALS['ISC_NEW_CFG']['ShopPath'] = $_POST['ShopPath']; $GLOBALS['ISC_NEW_CFG']['DefaultCurrencyID'] = $defaultCurrencyId; if (isset($GLOBALS['ISC_NEW_CFG']['StoreCountryLocationId'])) { unset($GLOBALS['ISC_NEW_CFG']['StoreCountryLocationId']); } if (isset($GLOBALS['ISC_NEW_CFG']['StoreCurrencyCode'])) { unset($GLOBALS['ISC_NEW_CFG']['StoreCurrencyCode']); } // set up the product images sizes // load the product image class to get the constants GetClass('ISC_PRODUCT_IMAGE'); $GLOBALS['ISC_NEW_CFG']['ProductImagesStorewideThumbnail_width'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_THUMBNAIL; $GLOBALS['ISC_NEW_CFG']['ProductImagesStorewideThumbnail_height'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_THUMBNAIL; $GLOBALS['ISC_NEW_CFG']['ProductImagesProductPageImage_width'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_STANDARD; $GLOBALS['ISC_NEW_CFG']['ProductImagesProductPageImage_height'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_STANDARD; $GLOBALS['ISC_NEW_CFG']['ProductImagesGalleryThumbnail_width'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_TINY; $GLOBALS['ISC_NEW_CFG']['ProductImagesGalleryThumbnail_height'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_TINY; $GLOBALS['ISC_NEW_CFG']['ProductImagesZoomImage_width'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_ZOOM; $GLOBALS['ISC_NEW_CFG']['ProductImagesZoomImage_height'] = ISC_PRODUCT_DEFAULT_IMAGE_SIZE_ZOOM; $GLOBALS['ISC_NEW_CFG']['ProductImagesTinyThumbnailsEnabled'] = 1; $GLOBALS['ISC_NEW_CFG']['ProductImagesImageZoomEnabled'] = 1; // Build the unique encryption token $GLOBALS['ISC_NEW_CFG']['EncryptionToken'] = $this->_BuildEncryptionToken(); // Set the install date $GLOBALS['ISC_NEW_CFG']['InstallDate'] = time(); if ($settings->CommitSettings()) { // Calling commit settings a second time to ensure the config.backup.php file // Is written with valid data $settings->CommitSettings(); // The installation is complete $GLOBALS['Password'] = $pass; // Do we need to install the sample product data? Copy that across if(isset($_POST['installSampleData']) && $_POST['installSampleData'] == 1) { $this->InstallSampleData(); } // The install schemas can't predict the nested set values if custom install scripts arbitrarily add categories or pages // Rebuilt any nested sets instead of including their values in the install schema $nestedSet = new ISC_NESTEDSET_CATEGORIES(); $nestedSet->rebuildTree(); $nestedSet = new ISC_NESTEDSET_PAGES(); $nestedSet->rebuildTree(); // Remove any existing cookies ISC_UnsetCookie("STORESUITE_CP_TOKEN"); //Initialize the data store system require_once ISC_BASE_PATH."/lib/class.datastore.php"; $GLOBALS['ISC_CLASS_DATA_STORE'] = new ISC_DATA_STORE(); // Clear the data store just in case it contains something $GLOBALS['ISC_CLASS_DATA_STORE']->Clear(); $GLOBALS['ISC_LANG']['InstallationCompleted'] = sprintf(GetLang('InstallationCompleted'), $pass); unset($_SESSION['LK'.md5(strtolower($_POST['ShopPath']))]); // The installation was complete! if($this->apiMode == 'cli') { fwrite(STDOUT, "Success:\n"); fwrite(STDOUT, "\n"); fwrite(STDOUT, "ShopPath: ".$_POST['ShopPath']."\n"); fwrite(STDOUT, "ControlPanel: ".$_POST['ShopPath']."admin/index.php\n"); fwrite(STDOUT, "Username: admin\n"); fwrite(STDOUT, "Password: "******"1.0" encoding="'.GetConfig("CharacterSet").'" ?'.">\n"; echo "<response>\n"; echo " <status>OK</status>\n"; echo " <shop>\n"; echo " <shopPath>".$_POST['ShopPath']."</shopPath>\n"; echo " <controlPanel>".$_POST['ShopPath']."admin/index.php</controlPanel>\n"; echo " </shop>\n"; echo " <user>\n"; echo " <username>admin</username>\n"; echo " <password>".$_POST['UserPass']."</password>\n"; echo " </user>\n"; echo "</response>\n"; exit; } else { $this->template->display('install.done.tpl'); } } else { $message = GetLang("ConfigErr"); $errors = array( 0 => array( "code" => "unableSaveConfig", "message" => $message ) ); $this->ShowInstallErrors($message, $errors, false, true); return; } } else { list($error, $level) = $db->GetError(); $GLOBALS["ISC_CLASS_DB"]->Query("rollback"); $message = sprintf(GetLang("DBErr"), $error); $errors = array( 0 => array( "code" => "dbError", "message" => $GLOBALS["ISC_CLASS_DB"]->Error() ) ); $this->ShowInstallErrors($message, $errors, false, true); return; } } } else { list($error, $level) = $db->GetError(); $message = sprintf(GetLang("DBErr"), $error); $errors = array( 0 => array( "code" => "dbConnectError", "message" => $error ) ); $this->ShowInstallErrors($message, $errors, false, true); return; } }
private function GetQuote() { // The following array will be returned to the calling function. // It will contain at least one ISC_SHIPPING_QUOTE object if // the shipping quote was successful. $cp_quote = array(); // Connect to Canada Post to retrieve a live shipping quote $items = ""; $result = ""; $valid_quote = false; $cp_url = "http://sellonline.canadapost.ca:30000?"; $readytoship = ''; if($this->_readytoship == 'yes') { $readytoship = "<readyToShip/>"; } foreach($this->_products as $product) { $items .= sprintf("<item> <quantity>%d</quantity> <weight>%s</weight> <length>%s</length> <width>%s</width> <height>%s</height> <description><![CDATA[%s]]></description> %s </item>", $product->getquantity(), ConvertWeight($product->GetWeight(), 'kgs'), ConvertLength($product->getlength(), "cm"), ConvertLength($product->getwidth(), "cm"), ConvertLength($product->getheight(), "cm"), $product->getdesc(), $readytoship ); } $cp_xml = sprintf("<" . "?" . "xml version=\"1.0\" ?" . "> <eparcel> <language>en</language> <ratesAndServicesRequest> <merchantCPCID>%s</merchantCPCID> <fromPostalCode>%s</fromPostalCode> <lineItems> %s </lineItems> <city></city> <provOrState>%s</provOrState> <country>%s</country> <postalCode>%s</postalCode> </ratesAndServicesRequest> </eparcel> ", $this->_merchantid, $this->_origin_zip, $items, $this->_deststate, isc_strtoupper($this->_destcountry), $this->_destzip); $post_vars = implode("&", array("XMLRequest=$cp_xml" ) ); $result = PostToRemoteFileAndGetResponse($cp_url, $post_vars); if($result) { $valid_quote = true; } if(!$valid_quote) { $this->SetError(GetLang('CanadaPostOpenError')); return false; } $xml = @simplexml_load_string($result); if(!is_object($xml)) { $this->SetError(GetLang('CanadaPostBadResponse')); return false; } if(isset($xml->error)) { $this->SetError((string)$xml->error->statusMessage); return false; } if(isset($xml->ratesAndServicesResponse)) { foreach($xml->ratesAndServicesResponse->product as $ship_method) { // Calculate the transit time $transit_time = -1; $today = $ship_method->shippingDate; $arr_today = explode("-", $today); $today_stamp = mktime(0, 0, 0, $arr_today[1], $arr_today[2], $arr_today[0]); $delivered = $ship_method->deliveryDate; $arr_delivered = explode("-", $delivered); if(count($arr_delivered) == 3) { $delivered_stamp = mktime(0, 0, 0, $arr_delivered[1], $arr_delivered[2], $arr_delivered[0]); $transit_time = $delivered_stamp - $today_stamp; // Convert transit time to days $transit_time = floor($transit_time/60/60/24); } $quote = new ISC_SHIPPING_QUOTE($this->GetId(), $this->GetDisplayName(), (float)$ship_method->rate, (string)$ship_method->name, $transit_time); $cp_quote[] = $quote; } } return $cp_quote; }
private function SaveUpdatedMailSettings() { $messages = array(); if (isset($_POST['MailXMLPath']) && isset($_POST['MailXMLToken']) && isset($_POST['MailUsername'])) { $xml_path = $_POST['MailXMLPath']; $xml_token = $_POST['MailXMLToken']; $api_user = $_POST['MailUsername']; $xml = "<xmlrequest>\n\t\t\t\t\t\t\t<username>" . $api_user . "</username>\n\t\t\t\t\t\t\t<usertoken>" . $xml_token . "</usertoken>\n\t\t\t\t\t\t\t<requesttype>authentication</requesttype>\n\t\t\t\t\t\t\t<requestmethod>xmlapitest</requestmethod>\n\t\t\t\t\t\t\t<details>\n\t\t\t\t\t\t\t</details>\n\t\t\t\t\t\t</xmlrequest>"; $xml = urlencode($xml); // Let's make sure the path is valid before enabling the XML API $result = PostToRemoteFileAndGetResponse($xml_path, "xml=" . $xml); $response = @simplexml_load_string($result); if (!is_object($response)) { $GLOBALS['MailXMLAPIValid'] = 0; } // We expect the response to contain SUCCESS - no point using XML to validate when we can do a string comparison if (is_numeric(isc_strpos(isc_strtoupper($result), "<STATUS>SUCCESS</STATUS>"))) { $GLOBALS['ISC_NEW_CFG']['MailXMLAPIValid'] = "1"; $GLOBALS['ISC_NEW_CFG']['MailXMLPath'] = $_POST['MailXMLPath']; $GLOBALS['ISC_NEW_CFG']['MailXMLToken'] = $_POST['MailXMLToken']; $GLOBALS['ISC_NEW_CFG']['MailUsername'] = $_POST['MailUsername']; } else { $GLOBALS['ISC_NEW_CFG']['MailXMLAPIValid'] = "0"; $GLOBALS['ISC_NEW_CFG']['MailXMLPath'] = ""; $GLOBALS['ISC_NEW_CFG']['MailXMLToken'] = ""; $GLOBALS['ISC_NEW_CFG']['MailUsername'] = ""; $GLOBALS['ISC_NEW_CFG']['MailAutomaticallyTickNewsletterBox'] = 0; $GLOBALS['ISC_NEW_CFG']['MailAutomaticallyTickOrderBox'] = 0; // Was an error message returned? if (isset($response->errormessage)) { $message = strval($response->errormessage); if (isc_strtolower(trim($message)) != "invalid details") { $messages[$message] = MSG_ERROR; } } } // Are we capturing subscribers from the newsletter form? if (isset($_POST['UseMailAPIForNewsletters'])) { $GLOBALS['ISC_NEW_CFG']['UseMailerForNewsletter'] = 1; $GLOBALS['ISC_NEW_CFG']['MailNewsletterList'] = (int) $_POST['MailNewsletterList']; $GLOBALS['ISC_NEW_CFG']['MailNewsletterCustomField'] = (int) @$_POST['MailNewsletterCustomField']; } else { $GLOBALS['ISC_NEW_CFG']['UseMailerForNewsletter'] = 0; $GLOBALS['ISC_NEW_CFG']['MailNewsletterList'] = 0; $GLOBALS['ISC_NEW_CFG']['MailNewsletterCustomField'] = 0; } // Are we capturing subscribers for customers? if (isset($_POST['UseMailAPIForOrders'])) { $GLOBALS['ISC_NEW_CFG']['UseMailerForOrders'] = 1; $GLOBALS['ISC_NEW_CFG']['MailOrderList'] = (int) $_POST['MailOrderList']; $GLOBALS['ISC_NEW_CFG']['MailOrderFirstName'] = (int) @$_POST['MailOrderFirstName']; $GLOBALS['ISC_NEW_CFG']['MailOrderLastName'] = (int) @$_POST['MailOrderLastName']; $GLOBALS['ISC_NEW_CFG']['MailOrderFullName'] = (int) @$_POST['MailOrderFullName']; $GLOBALS['ISC_NEW_CFG']['MailOrderZip'] = (int) @$_POST['MailOrderZip']; $GLOBALS['ISC_NEW_CFG']['MailOrderCountry'] = (int) @$_POST['MailOrderCountry']; $GLOBALS['ISC_NEW_CFG']['MailOrderTotal'] = (int) @$_POST['MailOrderTotal']; $GLOBALS['ISC_NEW_CFG']['MailOrderPaymentMethod'] = (int) @$_POST['MailOrderPaymentMethod']; $GLOBALS['ISC_NEW_CFG']['MailOrderShippingMethod'] = (int) @$_POST['MailOrderShippingMethod']; $GLOBALS['ISC_NEW_CFG']['MailOrderListAutoSubscribe'] = (int) @$_POST['MailOrderListAutoSubscribe']; } else { $GLOBALS['ISC_NEW_CFG']['UseMailerForOrders'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderList'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderFirstName'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderLastName'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderFullName'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderZip'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderCountry'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderTotal'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderPaymentMethod'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderShippingMethod'] = 0; $GLOBALS['ISC_NEW_CFG']['MailOrderListAutoSubscribe'] = 0; } // Are we showing product updates? if (isset($_POST['UseMailAPIForUpdates'])) { $GLOBALS['ISC_NEW_CFG']['UseMailAPIForUpdates'] = 1; $GLOBALS['ISC_NEW_CFG']['MailProductUpdatesListType'] = $_POST['MailProductUpdatesListType']; } else { $GLOBALS['ISC_NEW_CFG']['UseMailAPIForUpdates'] = 0; $GLOBALS['ISC_NEW_CFG']['MailProductUpdatesListType'] = ""; } // Update the settings if ($this->CommitSettings($messages)) { if (GetConfig('MailXMLAPIValid')) { if ($GLOBALS['CurrentTab'] == 0) { $success_var = "MailAPIInitSuccess"; } else { $success_var = "MailAPIIntegrationSuccess"; } // Log this action $GLOBALS['ISC_CLASS_LOG']->LogAdminAction(); $messages = array_merge(array(GetLang($success_var) => MSG_SUCCESS), $messages); foreach ($messages as $message => $type) { FlashMessage($message, $type); } header("Location: index.php?ToDo=viewMailSettings"); exit; } else { $GLOBALS['ISC_NEW_CFG']['MailXMLPath'] = $_POST['MailXMLPath']; $GLOBALS['ISC_NEW_CFG']['MailXMLToken'] = $_POST['MailXMLToken']; $GLOBALS['ISC_NEW_CFG']['MailUsername'] = $_POST['MailUsername']; $messages = array_merge(array(GetLang('MailAPIInitFailed') => MSG_ERROR), $messages); foreach ($messages as $message => $type) { FlashMessage($message, $type); } header("Location: index.php?ToDo=viewMailSettings"); exit; } } else { $messages = array_merge(array(GetLang('SettingsNotSaved') => MSG_ERROR), $messages); foreach ($messages as $message => $type) { FlashMessage($message, $type); } header("Location: index.php?ToDo=viewMailSettings"); exit; } } else { header("Location: index.php?ToDo=viewMailSettings"); exit; } }
<?php define('ISC_AJAX', 1); include dirname(__FILE__) . "/init.php"; if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->IsLoggedIn()) { $className = 'ISC_ADMIN_REMOTE'; if (array_key_exists('remoteSection', $_REQUEST) && trim($_REQUEST['remoteSection']) !== '') { $className .= '_' . isc_strtoupper(trim($_REQUEST['remoteSection'])); } $GLOBALS['ISC_CLASS_ADMIN_REMOTE'] = GetClass($className); $GLOBALS['ISC_CLASS_ADMIN_REMOTE']->HandleToDo(); }
public function ManageProductsGrid(&$numProducts) { // Show a list of products in a table $page = 0; $start = 0; $numProducts = 0; $numPages = 0; $GLOBALS['ProductGrid'] = ""; $GLOBALS['Nav'] = ""; $max = 0; // 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']; } } if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) { $featuredColumn = 'prodvendorfeatured'; } else { $featuredColumn = 'prodfeatured'; } $validSortFields = array('productid', 'prodcode', 'currentinv', 'prodname', 'prodcalculatedprice', 'prodvisible', $featuredColumn); if (isset($_REQUEST['sortOrder']) && $_REQUEST['sortOrder'] == "asc") { $sortOrder = "asc"; } else { $sortOrder = "desc"; } if (isset($_REQUEST['sortField']) && in_array($_REQUEST['sortField'], $validSortFields)) { $sortField = $_REQUEST['sortField']; SaveDefaultSortField("ManageProducts", $_REQUEST['sortField'], $sortOrder); } else { list($sortField, $sortOrder) = GetDefaultSortField("ManageProducts", "productid", $sortOrder); } if (isset($_GET['page'])) { $page = (int) $_GET['page']; } else { $page = 1; } if (isset($_GET['filterCategory']) && $_GET['filterCategory'] == "-1") { $GLOBALS['FilterLow'] = "selected=\"selected\""; } if (isset($_GET['filterCategory'])) { $filterCat = (int) $_GET['filterCategory']; } else { $filterCat = 0; } if (!gzte11(ISC_MEDIUMPRINT)) { $GLOBALS['ProductNameSpan'] = 3; $GLOBALS['HideInventoryOptions'] = 'none'; } else { $GLOBALS['HideInventoryOptions'] = ''; } // 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" || $k == "ISSelectReplacement_category" || !$v && $v !== '0') { continue; } if (is_array($v)) { foreach ($v as $v2) { $searchURL .= sprintf("&%s[]=%s", $k, urlencode($v2)); } } else { $searchURL .= sprintf("&%s=%s", $k, urlencode($v)); } } // Build the letter sorting $letterURL = sprintf("%s&sortField=%s&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'] = sprintf('<td width="3%%"><a href="index.php?ToDo=viewProducts%s&letter=0-9" title="%s" class="SortLink %s">#</a></td>', $letterURL, sprintf(GetLang('ViewProductsLetter'), '0-9'), $extra); $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=viewProducts%s&letter=%s" title="%s" class="SortLink %s">%s</a></td>', $letterURL, $letter, sprintf(GetLang('ViewProductsLetter'), isc_strtoupper($letter)), $extra, isc_strtoupper($letter)); } $letter = GetLang('Clear'); $GLOBALS['LetterSortGrid'] .= sprintf('<td width="3%%"><a href="index.php?ToDo=viewProducts%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_PRODUCTS_PER_PAGE - (ISC_PRODUCTS_PER_PAGE - 1); } $start = $start - 1; // Get the results for the query $product_result = $this->_GetProductList($start, $sortField, $sortOrder, $numProducts); $numPages = ceil($numProducts / ISC_PRODUCTS_PER_PAGE); // Add the "(Page x of n)" label if ($numProducts > ISC_PRODUCTS_PER_PAGE) { $GLOBALS['Nav'] = sprintf("(%s %d of %d) ", GetLang('Page'), $page, $numPages); $GLOBALS['Nav'] .= BuildPagination($numProducts, ISC_PRODUCTS_PER_PAGE, $page, sprintf("index.php?ToDo=viewProducts%s", $sortURL)); } else { $GLOBALS['Nav'] = ""; } if (isset($_REQUEST['searchQuery'])) { $query = $_REQUEST['searchQuery']; } else { $query = ''; } //Create Identity for each search result if (isset($_GET['searchQuery'])) { $_SESSION['SesDelIdentity'] = $GLOBALS['DelIdentity'] = $_GET['searchQuery'] . rand(1000, 9999); } else { unset($_SESSION['SesDelIdentity']); } $GLOBALS['Nav'] = preg_replace('# \\|$#', "", $GLOBALS['Nav']); $GLOBALS['SearchQuery'] = isc_html_escape($query); $GLOBALS['SortField'] = $sortField; $GLOBALS['SortOrder'] = $sortOrder; if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) { $featuredColumn = 'prodvendorfeatured'; } else { $featuredColumn = 'prodfeatured'; } $sortLinks = array("Code" => "prodcode", "Stock" => "currentinv", "Name" => "prodname", "Price" => "prodcalculatedprice", "Visible" => "prodvisible", "Featured" => $featuredColumn); BuildAdminSortingLinks($sortLinks, "index.php?ToDo=viewProducts&" . $searchURL . "&page=" . $page, $sortField, $sortOrder); // Workout the maximum size of the array $max = $start + ISC_PRODUCTS_PER_PAGE; if ($max > $numProducts) { $max = $numProducts; } if ($numProducts > 0) { // Display the products while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($product_result)) { if ($row['prodcode'] == "") { $GLOBALS['SKU'] = GetLang('NA'); } else { $GLOBALS['SKU'] = isc_html_escape($row['prodcode']); } $GLOBALS['ProductId'] = (int) $row['productid']; $GLOBALS['Name'] = sprintf("<a title='%s' class='Action' href='%s' target='_blank'>%s</a>", GetLang('ProductView'), ProdLink($row['prodname']), isc_html_escape($row['prodname'])); // Do we need to show product thumbnails? if (GetConfig('ShowThumbsInControlPanel')) { if ($row['tinythumb'] != "") { $GLOBALS['ProductImage'] = sprintf("<img src='%s/%s/%s' />", $GLOBALS['ShopPath'], GetConfig('ImageDirectory'), $row['tinythumb']); } else { $GLOBALS['ProductImage'] = sprintf("<div class='NoThumb'>%s<br />%s<br />%s</div>", GetLang('NoImage1'), GetLang('NoImage2'), GetLang('NoImage3')); } } else { // Use JavaScript to hide the thumbnail field $GLOBALS['HideThumbnailField'] = "1"; } $GLOBALS['Price'] = FormatPrice($row['prodcalculatedprice']); $GLOBALS['StockExpand'] = " "; $GLOBALS['LowStockStyle'] = ""; if ($row['prodinvtrack'] == 0) { $GLOBALS['StockInfo'] = GetLang('NA'); } else { if ($row['prodinvtrack'] > 0) { $GLOBALS['StockExpand'] = sprintf("<a href=\"#\" onclick=\"ShowStock('%d', '%d', '%d'); return false;\"><img id=\"expand%d\" src=\"images/plus.gif\" align=\"left\" class=\"ExpandLink\" width=\"19\" height=\"16\" title=\"%s\" border=\"0\"></a>", $row['productid'], $row['prodinvtrack'], $row['prodvariationid'], $row['productid'], GetLang('ClickToViewStock')); if ($row['prodlowinv'] > 0) { $percent = ceil($row['currentinv'] / ($row['prodlowinv'] * 2) * 100); } else { $percent = ceil($row['currentinv'] / (1 * 2) * 100); } if ($percent > 100) { $percent = 100; } if ($percent > 75) { $stockClass = 'InStock'; $orderMore = GetLang('SNo'); } else { if ($percent > 50) { $stockClass = 'StockWarning'; $orderMore = GetLang('Soon'); } else { $stockClass = 'LowStock'; $orderMore = GetLang('SYes'); } } $width = ceil($percent / 100 * 72); $stockInfo = sprintf(GetLang('CurrentStockLevel') . ': %s<br />' . GetLang('LowStockLevel1') . ': %s<br />' . GetLang('OrderMore') . ': ' . $orderMore, $row['currentinv'], $row['prodlowinv'], $orderMore); $GLOBALS['StockInfo'] = sprintf("<div class=\"StockLevelIndicator\" onmouseover=\"ShowQuickHelp(this, '%s', '%s')\" onmouseout=\"HideQuickHelp(this)\"><span class=\"%s\" style=\"width: %spx\"></span></div>", GetLang('StockLevel'), $stockInfo, $stockClass, $width); } } // If they have permission to edit products, they can change // the visibility status of a product by clicking on the icon if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) { if ($row['prodvisible'] == 1) { $GLOBALS['Visible'] = sprintf("<a title='%s' href='index.php?ToDo=editProductVisibility&prodId=%d&visible=0' onclick=\"quickToggle(this, 'visible'); return false;\"><img border='0' src='images/tick.gif' alt='tick'></a>", GetLang('ClickToHide'), $row['productid']); } else { $GLOBALS['Visible'] = sprintf("<a title='%s' href='index.php?ToDo=editProductVisibility&prodId=%d&visible=1' onclick=\"quickToggle(this, 'visible'); return false;\"><img border='0' src='images/cross.gif' alt='cross'></a>", GetLang('ClickToShow'), $row['productid']); } } else { if ($row['prodvisible'] == 1) { $GLOBALS['Visible'] = '<img border="0" src="images/tick.gif" alt="tick">'; } else { $GLOBALS['Visible'] = '<img border="0" src="images/cross.gif" alt="cross">'; } } // If they have permission to edit products, they can change // the featured status of a product by clicking on the icon if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) { $featuredColumn = 'prodvendorfeatured'; } else { $featuredColumn = 'prodfeatured'; } if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) { if ($row[$featuredColumn] == 1) { $GLOBALS['Featured'] = sprintf("<a title='%s' href='index.php?ToDo=editProductFeatured&prodId=%d&featured=0' onclick=\"quickToggle(this, 'featured'); return false;\"><img border='0' src='images/tick.gif' alt='tick'></a>", GetLang('ClickToHide'), $row['productid']); } else { $GLOBALS['Featured'] = sprintf("<a title='%s' href='index.php?ToDo=editProductFeatured&prodId=%d&featured=1' onclick=\"quickToggle(this, 'featured'); return false;\"><img border='0' src='images/cross.gif' alt='cross'></a>", GetLang('ClickToShow'), $row['productid']); } } else { if ($row[$featuredColumn] == 1) { $GLOBALS['Featured'] = '<img border="0" src="images/tick.gif" alt="tick">'; } else { $GLOBALS['Featured'] = '<img border="0" src="images/cross.gif" alt="cross">'; } } // Workout the edit link -- do they have permission to do so? if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) { $GLOBALS['EditProductLink'] = sprintf("<a title='%s' class='Action' href='index.php?ToDo=editProduct&productId=%d'>%s</a>", GetLang('ProductEdit'), $row['productid'], GetLang('Edit')); } else { $GLOBALS['EditProductLink'] = sprintf("<a class='Action' disabled>%s</a>", GetLang('Edit')); } //blessen goto $GLOBALS['GOTO'] = '<INPUT TYPE="text" NAME="page_no" size="2" id="page_no" onkeyup="go(this.value);"> <a href="#" id="gotopage");>Go to page</a>'; $GLOBALS['GOTO1'] = '<INPUT TYPE="text" NAME="page_no1" size="2" id="page_no1" onkeyup="go1(this.value);"> <a href="#" id="gotopage1");>Go to page</a>'; $GLOBALS['CopyProductLink'] = "<a title='" . GetLang('ProductCopy') . "' class='Action' href='index.php?ToDo=copyProduct&productId=" . $row['productid'] . "'>" . GetLang('Copy') . "</a>"; $GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("product.manage.row"); $GLOBALS['ProductGrid'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate(true); } } if ($GLOBALS['ProductGrid'] == '') { if (isset($_REQUEST['letter'])) { $GLOBALS['ProductGrid'] = sprintf('<tr> <td colspan="11" style="padding:10px"><em>%s</em></td> </tr>', sprintf(GetLang('LetterSortNoResults'), isc_strtoupper($_REQUEST['letter']))); } } $GLOBALS["ISC_CLASS_TEMPLATE"]->SetTemplate("products.manage.grid"); return $GLOBALS["ISC_CLASS_TEMPLATE"]->ParseTemplate(true); }
/** * Verify the order was successful on the "Thank you" page. */ public function VerifyOrderPayment() { $this->_secretword = trim($this->GetValue("secretword")); $testmode_on = $this->GetValue("testmode"); if(isset($_REQUEST['total']) && isset($_REQUEST['credit_card_processed']) && isset($_REQUEST['order_number']) && isset($_REQUEST['sid'])) { $total = $_REQUEST['total']; $cc_proc = $_REQUEST['credit_card_processed']; $vendor_id = $_REQUEST['sid']; $hash_2co = $_REQUEST['key']; if(isset($_REQUEST['demo']) && isc_strtoupper($_REQUEST['demo']) == "Y" && $testmode_on == "YES") { $order_no = 1; } else { $order_no = $_REQUEST['order_number']; } // Workout the hash, which is MD5(secret_word+vendor_number+order_number+total) $calc_hash = isc_strtoupper(md5(sprintf("%s%s%s%s", $this->_secretword, $vendor_id, $order_no, $total))); // The order total must match and the hash must match too if($this->GetGatewayAmount() == $total && $calc_hash == $hash_2co && $cc_proc == "Y") { $this->SetPaymentStatus(PAYMENT_STATUS_PAID); $GLOBALS['ISC_CLASS_LOG']->LogSystemSuccess(array('payment', $this->GetName()), GetLang('2CheckoutSuccess')); return true; } else { $errorMsg = sprintf(GetLang('2CheckoutErrorMismatchMsg'), $total, $this->GetGatewayAmount(), $hash_2co, $calc_hash, $cc_proc); $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('2CheckoutErrorMismatch'), $errorMsg); return false; } } else { $GLOBALS['ISC_CLASS_LOG']->LogSystemError(array('payment', $this->GetName()), GetLang('2CheckoutErrorOrderId')); return false; } }
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&sortField=%s&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&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) ", 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&" . $searchURL . "&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&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); }
/** * Show the window to configure an item (variations, configurable fields) etc in the * order that's being created/edited. */ private function OrderConfigureProduct() { if (!isset($_REQUEST['cartItemId']) || !isset($_REQUEST['orderSession'])) { exit; } // Initialize the cart management API $orderClass = GetClass('ISC_ADMIN_ORDERS'); $orderClass->GetCartApi($_REQUEST['orderSession']); $existingProduct = $orderClass->GetCartApi()->GetProductInCart($_REQUEST['cartItemId']); if (is_array($existingProduct)) { if (isset($_REQUEST['productId']) && $existingProduct['product_id'] != $_REQUEST['productId']) { $existingProduct = false; } else { $_REQUEST['productId'] = $existingProduct['product_id']; } } // Fetch the product class on the front end as it'll be doing most of the work for this page $productClass = new ISC_PRODUCT($_REQUEST['productId']); if (!$productClass->GetProductId()) { exit; } if (!is_array($existingProduct) && !isset($_REQUEST['productId'])) { exit; } else { if (is_array($existingProduct)) { $GLOBALS['EditingExistingProduct'] = 1; $GLOBALS['Intro'] = GetLang('OrderConfigureProductEdit'); $GLOBALS['ButtonLabel'] = GetLang('OrderConfigureProductEditButton'); $productPrice = $existingProduct['product_price']; $GLOBALS['VariationId'] = $existingProduct['variation_id']; } else { $GLOBALS['Intro'] = GetLang('OrderConfigureProduct'); $GLOBALS['ButtonLabel'] = GetLang('AddProductToOrder'); // Finally, determine the price based on the customer group $product = $productClass->GetProduct(); $productPrice = CalcProdCustomerGroupPrice($product, $product['prodcalculatedprice']); } } $GLOBALS['ProductPrice'] = FormatPrice($productPrice); $productVariations = $productClass->GetProductVariations(); $GLOBALS['ProductName'] = isc_html_escape($productClass->GetProductName()); $GLOBALS['ProductId'] = (int) $productClass->GetProductId(); $GLOBALS['OrderSession'] = isc_html_escape($_REQUEST['orderSession']); $GLOBALS['CartItemId'] = isc_html_escape($_REQUEST['cartItemId']); $GLOBALS['Quantity'] = (int) $_REQUEST['quantity']; $GLOBALS['ProductOptionRequired'] = 0; $GLOBALS['VariationList'] = ''; if (!empty($productVariations)) { // If we have an existing variation already, look up the combination $existingCombination = array(); if (is_array($existingProduct) && $existingProduct['variation_id']) { $query = "\n\t\t\t\t\t\tSELECT vcoptionids\n\t\t\t\t\t\tFROM [|PREFIX|]product_variation_combinations\n\t\t\t\t\t\tWHERE combinationid='" . (int) $existingProduct['variation_id'] . "'\n\t\t\t\t\t"; $existingCombination = explode(',', $GLOBALS['ISC_CLASS_DB']->FetchOne($query)); } if ($productClass->IsOptionRequired()) { $GLOBALS['ProductOptionRequired'] = 1; $GLOBALS['VariationRequired'] = '*'; } else { $GLOBALS['VariationRequired'] = ' '; } $GLOBALS['VariationNumber'] = 0; foreach ($productVariations as $name => $options) { $GLOBALS['VariationNumber']++; $optionList = ''; foreach ($options as $option) { $sel = ''; if (in_array($option['voptionid'], $existingCombination)) { $sel = 'selected="selected"'; } $optionList .= '<option value="' . $option['voptionid'] . '" ' . $sel . '>' . isc_html_escape($option['vovalue']) . '</option>'; } $GLOBALS['VariationOptions'] = $optionList; $GLOBALS['VariationName'] = isc_html_escape($name); $GLOBALS['VariationList'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderProductConfigurationVariation'); } $GLOBALS['ProductVariationJavascript'] = $productClass->GetProductVariationCombinationJavascript(); } else { $GLOBALS['HideVariationList'] = 'display: none'; } $fields = $productClass->GetProductFields($_REQUEST['productId']); $GLOBALS['ProductFields'] = ''; if (!empty($fields)) { foreach ($fields as $field) { $GLOBALS['FieldId'] = $field['id']; $GLOBALS['FieldRequired'] = ' '; $requiredClass = ''; $GLOBALS['FieldName'] = isc_html_escape($field['name']) . ':'; $GLOBALS['HideFieldHelp'] = 'display: none'; $GLOBALS['FieldHelp'] = ''; $GLOBALS['HideFileCurrentValue'] = 'display: none'; $existingValue = ''; if (isset($existingProduct['product_fields'][$field['id']])) { if ($field['type'] == 'file') { $existingValue = isc_html_escape($existingProduct['product_fields'][$field['id']]['fileOriginName']); $existingFileName = $existingProduct['product_fields'][$field['id']]['fileName']; } else { $existingValue = isc_html_escape($existingProduct['product_fields'][$field['id']]['fieldValue']); } } if ($field['required'] == 1) { $requiredClass = 'FieldRequired'; $GLOBALS['FieldRequired'] = '*'; } switch ($field['type']) { case 'textarea': $inputField = '<textarea cols="30" rows="3" name="productFields[' . $field['id'] . ']" class="Field300 ' . $requiredClass . '">' . $existingValue . '</textarea>'; break; case 'file': if ($existingValue) { $requiredClass .= 'HasExistingValue'; } $inputField = '<input type="file" name="productFields[' . $field['id'] . ']" class="Field300 ' . $requiredClass . '" />'; $help = array(); if ($field['fileSize'] > 0) { $help[] = GetLang('MaximumSize') . ': ' . NiceSize($field['fileSize'] * 1024); } if ($field['fileType'] != '') { $help[] = GetLang('AllowedTypes') . ': ' . '<span class="FileTypes">' . isc_strtoupper(isc_html_escape($field['fileType']) . '</span>'); } $help = implode('. ', $help); if ($help != '') { $GLOBALS['HideFieldHelp'] = ''; $GLOBALS['FieldHelp'] = '<em>(' . $help . ')</em>'; } if ($existingValue) { $GLOBALS['HideFileCurrentValue'] = ''; if (!$field['required']) { $GLOBALS['HideRemoveFile'] = 'display: none'; } $GLOBALS['CurrentFileName'] = $existingValue; if (isset($existingProduct['product_fields'][$field['id']]['fieldExisting'])) { $fileDirectory = 'configured_products'; } else { $fileDirectory = 'configured_products_tmp'; } $GLOBALS['CurrentFileLink'] = GetConfig('ShopPath') . '/' . GetConfig('ImageDirectory') . '/' . $fileDirectory . '/' . $existingFileName; } break; case 'checkbox': $checked = ''; if ($existingValue) { $checked = 'checked="checked"'; } $inputField = '<label><input type="checkbox" name="productFields[' . $field['id'] . ']" ' . $checked . ' value="1" /> ' . GetLang('TickToSelect') . '</label>'; break; default: $inputField = '<input type="text" name="productFields[' . $field['id'] . ']" class="Field300 ' . $requiredClass . '" value="' . $existingValue . '"/>'; } $GLOBALS['InputField'] = $inputField; $GLOBALS['ProductFields'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderProductConfigurationField'); } } else { $GLOBALS['HideConfigurableFields'] = 'display: none'; } if ($productClass->GetEventDateRequired() == 1) { $this->LoadEventDate($productClass, $existingProduct); } else { $GLOBALS['EventDate'] = ''; $GLOBALS['HideEventDate'] = 'display : none;'; } echo $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderProductConfiguration'); exit; }
/** * _CreateGroupLevelDiscounts * Create the group-level discounts for a new/updated group * * @param Int $GroupId The group to which the discounts belong * @return Boolean True if they were created, false on DB error */ private function _CreateGroupLevelDiscounts($groupId, $discounts, $removeFirst=false) { if (!isId($groupId) || !is_array($discounts)) { return false; } if ($removeFirst) { $status = $GLOBALS['ISC_CLASS_DB']->DeleteQuery("customer_group_discounts", "WHERE customergroupid=" . (int)$groupId); if ($status === false) { return false; } } foreach ($discounts as $discount) { $savedata = array( 'customergroupid' => $groupId, 'discounttype' => isc_strtoupper($discount['discounttype']), 'catorprodid' => (int)$discount['catorprodid'], 'discountpercent' => DefaultPriceFormat($discount['discountpercent']), 'discountmethod' => $discount['discountmethod'] ); if (isc_strtolower($discount['discounttype']) == 'product') { $savedata['appliesto'] = 'NOT_APPLICABLE'; } else { $savedata['appliesto'] = isc_strtoupper($discount['appliesto']); } if ($GLOBALS['ISC_CLASS_DB']->InsertQuery("customer_group_discounts", $savedata) === false) { return false; } } // Build the cache again $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateCustomerGroupsCategoryDiscounts($groupId); return true; }
/** * Run the full text searches to find matching products */ public function DoSearch($start=0, $limit=-1, $sections='', $sortBy='') { $total = 0; $searchTypes = $this->_searchtypes; if (!is_array($sections)) { $sections = array($sections); } $sections = array_map("trim", $sections); $sections = array_filter($sections); if (!empty($sections)) { $newSearchTypes = array(); foreach ($sections as $section) { if (in_array($section, $searchTypes)) { $newSearchTypes[] = $section; } } if (!empty($newSearchTypes)) { $searchTypes = $newSearchTypes; } } if (!is_array($this->_searchresults)) { $this->_searchresults = array(); } foreach ($searchTypes as $searchType) { $subtotal = 0; // Special case for 'content' which is basically 'page' and 'news' results merged into one if ($searchType == "content") { $pageQuery = ISC_PAGE::searchForItemsSQLAsContent($this->_searchterms); $newsQuery = ISC_NEWS::searchForItemsSQLAsContent($this->_searchterms); $itemResults = array(); if (trim($pageQuery) !== "" && trim($newsQuery) !== "") { $query = "(" . trim($pageQuery) . ") UNION (" . trim($newsQuery) . ")"; if (trim($sortBy) == "") { $sortBy = GetConfig("SearchDefaultContentSort"); } $orderBy = ""; switch (isc_strtolower($sortBy)) { case "relevance": $orderBy = "score DESC"; break; case "alphaasc": $orderBy = "nodetitle ASC"; break; case "alphadesc": $orderBy = "nodetitle DESC"; break; } if (trim($orderBy) !== "") { $query .= " ORDER BY " . $orderBy; } if (is_numeric($limit) && $limit > 0) { if (is_numeric($start) && $start > 0) { $query .= " LIMIT " . (int)$start . "," . (int)$limit; } else { $query .= " LIMIT " . (int)$limit; } } $result = $GLOBALS["ISC_CLASS_DB"]->Query($query); $row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result); if ($row) { $subtotal = $GLOBALS["ISC_CLASS_DB"]->FetchOne("SELECT FOUND_ROWS()"); $itemResults[] = $row; while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) { $itemResults[] = $row; } } } } else { // The brand class id called 'brands' (wtf) if ($searchType == "brand") { $className = "ISC_BRANDS"; } else { $className = "ISC_" . isc_strtoupper($searchType); } $itemResults = call_user_func_array(array($className, "searchForItems"), array($this->_searchterms, &$subtotal, $start, $limit, $sortBy)); } $this->_searchresults[$searchType] = array( "results" => $itemResults, "total" => $subtotal ); $total += $subtotal; } return $total; }