protected function _ImportRecord($record) { // the field we have chosen to identify the product $prodIdentField = $this->ImportSession['IdentField']; $identFieldName = $this->_ImportFields[$prodIdentField]; // chosen ident field is empty, can't continue if (empty($prodIdentField)) { $this->addImportResult('Failures', GetLang('NoIdentField', array('identField' => $identFieldName))); return; } // get the product for this row $query = "SELECT * FROM [|PREFIX|]products WHERE " . $prodIdentField . " = '" . $GLOBALS['ISC_CLASS_DB']->Quote(trim($record[$prodIdentField])) . "'"; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if (($prod = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) === false) { // no prod found? failrow $this->addImportResult('Failures', GetLang('AssociatedProductNotFound', array('identField' => $identFieldName, 'identValue' => $record[$prodIdentField]))); return; } $productID = $prod['productid']; $variationID = $prod['prodvariationid']; //---- the fields we'll be updating the product with ---- // variation code if (isset($record['prodvarsku'])) { $prodCode = $record['prodvarsku']; if (!empty($prodCode) || (empty($prodCode) && $this->ImportSession['DefaultForEmpty'])) { $updateFields['vcsku'] = $prodCode; } } elseif (isset($record['prodcode'])) { $prodCode = $record['prodcode']; if (!empty($prodCode) || (empty($prodCode) && $this->ImportSession['DefaultForEmpty'])) { $updateFields['vcsku'] = $prodCode; } } // variation price if (isset($record['prodvarprice'])) { $varPrice = $record['prodvarprice']; if (empty($varPrice) && $this->ImportSession['DefaultForEmpty']) { $updateFields['vcprice'] = 0; $updateFields['vcpricediff'] = ''; } else { // prefixed by a + then it's a price addition if (isc_substr($varPrice, 0, 1) == "+") { $priceDiff = "add"; } // price subtraction elseif ($varPrice < 0) { $priceDiff = "subtract"; } // fixed price else { $priceDiff = "fixed"; } $varPrice = abs((float)DefaultPriceFormat($varPrice)); $updateFields['vcprice'] = $varPrice; $updateFields['vcpricediff'] = $priceDiff; } } // variation weight if (isset($record['prodvarweight'])) { $varWeight = $record['prodvarweight']; if (empty($varWeight) && $this->ImportSession['DefaultForEmpty']) { $updateFields['vcweight'] = 0; $updateFields['vcweightdiff'] = ''; } elseif (!empty($record['prodvarweight'])) { // prefixed by a + then it's a weight addition if (isc_substr($varWeight, 0, 1) == "+") { $weightDiff = "add"; } // weight subtraction elseif ($varWeight < 0) { $weightDiff = "subtract"; } // fixed weight else { $weightDiff = "fixed"; } $updateFields['vcweight'] = abs((float)$varWeight); $updateFields['vcweightdiff'] = $weightDiff; } } // stock level if (isset($record['prodvarstock'])) { if (empty($record['prodvarstock']) && $this->ImportSession['DefaultForEmpty']) { $updateFields['vcstock'] = 0; } else { $updateFields['vcstock'] = $record['prodvarstock']; } } // low stock level if (isset($record['prodvarlowstock'])) { if (empty($record['prodvarlowstock']) && $this->ImportSession['DefaultForEmpty']) { $updateFields['vclowstock'] = 0; } else { $updateFields['vclowstock'] = $record['prodvarlowstock']; } } // enable the option? if (isset($record['prodvarenabled'])) { if (empty($record['prodvarenabled']) && $this->ImportSession['DefaultForEmpty']) { $updateFields['vcenabled'] = 1; } else { $updateFields['vcenabled'] = $this->StringToYesNoInt($record['prodvarenabled']); } } else { // enable by default $updateFields['vcenabled'] = 1; } // variation image if(!empty($record['prodvarimage'])) { // code exists in the new product image management classes to handle these imports $imageFile = $record['prodvarimage']; $imageAdmin = new ISC_ADMIN_PRODUCT_IMAGE; $variationImage = false; // check if this image file (either remote or local) has already been processed on a previous variation, if // so, simply re-use those values instead of re-downloading / re-processing if (isset($this->ImportSession['ImportedImages'][$imageFile])) { $importedImage = $this->ImportSession['ImportedImages'][$imageFile]; if (is_array($importedImage)) { $updateFields = array_merge($updateFields, $importedImage); } } else { $this->ImportSession['ImportedImages'][$imageFile] = false; if (preg_match('#^(?P<scheme>[a-zA-Z0-9\.]+)://#i', $imageFile, $matches)) { // the filename is an external URL, import it against the calcualted product hash $imageAdmin->importImagesFromUrls(false, array($imageFile), $importImages, $importImageErrors, false); if (!empty($importImages)) { $variationImage = $importImages[0]; } if (!empty($importImageErrors)) { // as this import works on one file only and importImagesFromWebUrls creates one error per file, can simply tack on the new error $importImageError = $importImageErrors[0]; if (is_array($importImageError)) { $this->addImportResult('Warnings', $importImageError[1]); } else { $this->addImportResult('Warnings', $importImageError); } } } else { // the filename is a local file $importImageFilePath = ISC_BASE_PATH . "/" . GetConfig('ImageDirectory') . "/import/" . $imageFile; try { $variationImage = ISC_PRODUCT_IMAGE::importImage($importImageFilePath, basename($importImageFilePath), false, false, false, false); } catch (ISC_PRODUCT_IMAGE_SOURCEFILEDOESNTEXIST_EXCEPTION $exception) { // exception message may contain server path; present filtered message and log the original $this->addImportResult('Warnings', GetLang('ProductImageFileDoesNotExist')); trigger_error($exception->getMessage(), E_WARNING); } catch (ISC_PRODUCT_IMAGE_IMPORT_CANTCREATEDIR_EXCEPTION $exception) { // exception message may contain server path; present filtered message and log the original $this->addImportResult('Warnings', GetLang('ImportProductImageFilePermissionIssue')); trigger_error($exception->getMessage(), E_WARNING); } catch (ISC_PRODUCT_IMAGE_IMPORT_CANTMOVEFILE_EXCEPTION $exception) { // exception message may contain server path; present filtered message and log the original $this->addImportResult('Warnings', GetLang('ImportProductImageFilePermissionIssue')); trigger_error($exception->getMessage(), E_WARNING); } catch (Exception $exception) { // other exceptions should be ok to present $this->addImportResult('Warnings', $exception->getMessage()); } } if ($variationImage !== false) { try { $importedImage = array( 'vcimage' => $variationImage->getSourceFilePath(), 'vcimagezoom' => $variationImage->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true, false), 'vcimagestd' => $variationImage->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true, false), 'vcimagethumb' => $variationImage->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true, false), ); $updateFields = array_merge($updateFields, $importedImage); $this->ImportSession['ImportedImages'][$imageFile] = $importedImage; } catch (ISC_PRODUCT_IMAGE_SOURCEFILEDOESNTEXIST_EXCEPTION $exception) { // exception message may contain server path; present filtered message and log the original $this->addImportResult('Warnings', GetLang('ProductImageFileDoesNotExist')); trigger_error($exception->getMessage(), E_WARNING); } catch (ISC_PRODUCT_IMAGE_IMPORT_CANTCREATEDIR_EXCEPTION $exception) { // exception message may contain server path; present filtered message and log the original $this->addImportResult('Warnings', GetLang('ImportProductImageFilePermissionIssue')); trigger_error($exception->getMessage(), E_WARNING); } catch (ISC_PRODUCT_IMAGE_IMPORT_CANTMOVEFILE_EXCEPTION $exception) { // exception message may contain server path; present filtered message and log the original $this->addImportResult('Warnings', GetLang('ImportProductImageFilePermissionIssue')); trigger_error($exception->getMessage(), E_WARNING); } catch (Exception $exception) { // other exceptions should be ok to present $this->addImportResult('Warnings', $exception->getMessage()); } } } } // get the index of the last matched field...we assume that all the remaining fields are variations $lastindex = 0; foreach ($this->ImportSession['FieldList'] as $field => $index) { if ($index > $lastindex) { $lastindex = $index; } } $variationStartIndex = $lastindex + 1; // get the variation fields $variationFields = array_slice($record['original_record'], $variationStartIndex); // split the variation fields into key => value pairs $variationData = array(); foreach ($variationFields as $field) { $varField = explode(":", $field, 2); // ensure we have a key and value...otherwise bad field if (count($varField) != 2) { $this->addImportResult('Failures', GetLang('CantExtractData', array('dataField' => $field))); return; } $varName = trim($varField[0]); $varValue = trim($varField[1]); $variationData[$varName] = $varValue; } // ensure we actually have variation data if (empty($variationData)) { // generate a failure $this->addImportResult('Failures', GetLang('NoVariationData', array('rowNum' => $this->ImportSession['DoneCount'] + 1))); return; } // are we choosing to update an existing variation combination or replacing with a new variation? // make sure this isn't a variation we've created this session if ($this->ImportSession['UpdateExisting'] && $variationID > 0 && !isset($this->ImportSession['NewVariations'][$productID])){ // find the variation options so we can find the combination $query = " SELECT voptionid, voname, vovalue FROM [|PREFIX|]product_variation_options WHERE vovariationid = " . $variationID . " AND ("; $where = ""; foreach ($variationData as $varName => $varValue) { if ($where) { $where .= " OR "; } $where .= " ( voname = '" . $GLOBALS['ISC_CLASS_DB']->Quote($varName) . "' AND vovalue = '" . $GLOBALS['ISC_CLASS_DB']->Quote($varValue) . "' ) "; } $query .= $where . ") ORDER BY vooptionsort, vovaluesort"; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); $optionList = array(); $notFoundOptions = $variationData; // get the option id's if ($GLOBALS['ISC_CLASS_DB']->CountResult($result)) { while ($optionRow = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { $optionList[] = $optionRow['voptionid']; unset($notFoundOptions[$optionRow['voname']]); } } $updatedName = false; // create any remaining options if (!empty($notFoundOptions)) { foreach ($notFoundOptions as $varName => $varValue) { // find whether it's the option name or value that doesn't exist $query = " SELECT COUNT(*) AS valuecount, vooptionsort, voname FROM [|PREFIX|]product_variation_options WHERE vovariationid = " . $variationID . " AND voname = '" . $GLOBALS['ISC_CLASS_DB']->Quote($varName) . "' GROUP BY voname "; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); // name exists, just create a new value if ($option = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { $newOption = array( 'vovariationid' => $variationID, 'voname' => $option['voname'], 'vovalue' => $varValue, 'vooptionsort' => $option['vooptionsort'], 'vovaluesort' => $option['valuecount'] + 1 ); $optionID = $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_options', $newOption); array_splice($optionList, $option['vooptionsort'] - 1, 0, $optionID); // we have a new value, we have to create new combinations for each of the rows using the existing data // get existing combinations but exclude the option name that we're on if ($this->ImportSession['CreateAllCombos']) { $combinations = GetVariationCombinations($productID, $varName); foreach ($combinations as $combination) { $newCombination = $combination; // insert the option at correct position array_splice($newCombination, $option['vooptionsort'] - 1, 0, $optionID); $newOptionList = implode(',', $newCombination); // create combination $newCombo = array( 'vcproductid' => $productID, 'vcvariationid' => $variationID, 'vcoptionids' => $newOptionList, 'vcenabled' => 1 ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_combinations', $newCombo); } } } else { // name not found, create it with the option // get total option names $query = "SELECT COUNT(DISTINCT voname) AS optioncount FROM [|PREFIX|]product_variation_options WHERE vovariationid = " . $variationID; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); $optioncount = $GLOBALS['ISC_CLASS_DB']->FetchOne($result, 'optioncount'); $newOption = array( 'vovariationid' => $variationID, 'voname' => $varName, 'vovalue' => $varValue, 'vooptionsort' => $optioncount + 1, 'vovaluesort' => 1 ); $optionID = $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_options', $newOption); array_splice($optionList, $optioncount, 0, $optionID); // we have a new option name, so append the new option id to existing combinations $query = " UPDATE [|PREFIX|]product_variation_combinations SET vcoptionids = CONCAT(vcoptionids, '," . $optionID . "') WHERE vcvariationid = " . $variationID; $GLOBALS['ISC_CLASS_DB']->Query($query); // update the variation option count $query = "UPDATE [|PREFIX|]product_variations SET vnumoptions = vnumoptions + 1 WHERE variationid = " . $variationID; $GLOBALS['ISC_CLASS_DB']->Query($query); } } } $optionString = implode(",", $optionList); // attempt to find existing combination again using list of options $query = " SELECT combinationid FROM [|PREFIX|]product_variation_combinations WHERE vcproductid = " . $productID . " AND vcvariationid = " . $variationID . " AND vcoptionids = '" . $optionString . "' "; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); // update the combination if ($comboID = $GLOBALS['ISC_CLASS_DB']->FetchOne($result, 'combinationid')) { $GLOBALS['ISC_CLASS_DB']->UpdateQuery('product_variation_combinations', $updateFields, 'combinationid = ' . $comboID); $this->addImportResult('Updates', $prod['prodname']); } else { // couldn't update an existing combo, create a new one $newCombo = array( 'vcproductid' => $productID, 'vcvariationid' => $variationID, 'vcoptionids' => $optionString ); $newCombo = $newCombo + $updateFields; $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_combinations', $newCombo); $this->ImportSession['Results']['SuccessCount']++; } } else { // create a new variation for this product // have we already created a variation for this product in this import session? if (isset($this->ImportSession['NewVariations'][$productID])) { // we only need to create our new options and the combinations // find any options previously created $thisVar = $this->ImportSession['NewVariations'][$productID]; $thisOptions = array(); $thisOptionsL = array(); foreach ($variationData as $varName => $varValue) { if (isset($thisVar[isc_strtolower($varName)][isc_strtolower($varValue)])) { $thisOptions[$varName] = $thisVar[isc_strtolower($varName)][isc_strtolower($varValue)]; $thisOptionsL[isc_strtolower($varName)] = $thisVar[isc_strtolower($varName)][isc_strtolower($varValue)]; } } // create any remaining uncreated options $remainingOptions = array_diff_key($variationData, $thisOptions); if (!empty($remainingOptions)) { foreach ($remainingOptions as $varName => $varValue) { $lvarName = isc_strtolower($varName); // get the option and value sort numbers // does this option name exist, but just not the value? if (isset($thisVar[$lvarName])) { $keyIndex = array_search($lvarName, array_keys($thisVar)); $optionSort = $keyIndex + 1; $valueSort = count($thisVar[$lvarName]) + 1; } else { $valueSort = 1; $optionSort = count($thisVar) + 1; } $insertOption = array( 'vovariationid' => $variationID, 'voname' => $varName, 'vovalue' => $varValue, 'vooptionsort' => $optionSort, 'vovaluesort' => $valueSort ); $optionID = $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_options', $insertOption); // add this new option to the list $thisVar[$lvarName][isc_strtolower($varValue)] = $optionID; $thisOptionsL[$lvarName] = $optionID; // is it a new option name? if (!$thisVar[isc_strtolower($varName)]) { // we have a new option name, so append the new option id to existing combinations $query = " UPDATE [|PREFIX|]product_variation_combinations SET vcoptionids = CONCAT(vcoptionids, '," . $optionID . "') WHERE vcvariationid = " . $variationID; $GLOBALS['ISC_CLASS_DB']->Query($query); } } } // store options back in session $this->ImportSession['NewVariations'][$productID] = $thisVar; // get the option ids for this combination. they must be in the order that the option names were created. $comboRows = array(array()); foreach ($thisVar as $varName => $varData) { // is there an option that may have already been created but is missing for this record? if (isset($thisOptionsL[$varName])) { foreach ($comboRows as &$combo) { $combo[] = $thisOptionsL[$varName]; } } else { $newRows = array(); // missing option, iterate through all values for that option and create combinations foreach ($comboRows as $combo) { foreach ($varData as $varValue => $optionID) { $newRow = $combo; $newRow[] = $optionID; $newRows[] = $newRow; } } $comboRows = $newRows; } } // insert all our combinations foreach ($comboRows as $thisCombo) { $optionString = implode(",", $thisCombo); // now we can finally create the combination $newCombo = array( 'vcproductid' => $prod['productid'], 'vcvariationid' => $variationID, 'vcoptionids' => $optionString ); $newCombo = $newCombo + $updateFields; $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_combinations', $newCombo); } $this->ImportSession['Results']['SuccessCount']++; } else { // do we have an existing combinations for this product? we should delete any combinations for that first if ($variationID) { $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_variation_combinations', 'WHERE vcproductid = ' . $productID); } // name of our new variation .. check if it already exists $variationName = $prod['prodname'] . " Variations " . date('dmy'); $query = "SELECT variationid FROM [|PREFIX|]product_variations WHERE vname = '" . $GLOBALS['ISC_CLASS_DB']->Quote($variationName) . "'"; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if ($varRow = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { // delete the old variation $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_variations', 'WHERE variationid = ' . $varRow['variationid']); $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_variation_options', 'WHERE vovariationid = ' . $varRow['variationid']); $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_variation_combinations', 'WHERE vcvariationid = ' . $varRow['variationid']); // update products that use this variation $updateProd = array( 'prodvariationid' => 0 ); $GLOBALS['ISC_CLASS_DB']->UpdateQuery('products', $updateProd, 'prodvariationid = ' . $varRow['variationid']); } // create our new variation first $newVariation = array( 'vname' => $variationName, 'vvendorid' => $prod['prodvendorid'] ); $variationID = $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variations', $newVariation); $this->ImportSession['NewVariationIDs'][$productID] = $variationID; // update our product with the variation ID $updateProd = array( 'prodvariationid' => $variationID ); $GLOBALS['ISC_CLASS_DB']->UpdateQuery('products', $updateProd, 'productid = ' . $productID); $thisVar = array(); $options = array(); // now to create the options $optionCount = 0; foreach ($variationData as $varName => $varValue) { $newOption = array( 'vovariationid' => $variationID, 'voname' => $varName, 'vovalue' => $varValue, 'vooptionsort' => ++$optionCount, 'vovaluesort' => 1 ); $optionID = $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_options', $newOption); $thisVar[isc_strtolower($varName)][isc_strtolower($varValue)] = $optionID; $options[] = $optionID; } $this->ImportSession['NewVariations'][$productID] = $thisVar; // create the combination $optionString = implode(",", $options); $newCombo = array( 'vcproductid' => $productID, 'vcvariationid' => $variationID, 'vcoptionids' => $optionString ); $newCombo = $newCombo + $updateFields; $GLOBALS['ISC_CLASS_DB']->InsertQuery('product_variation_combinations', $newCombo); $this->ImportSession['Results']['SuccessCount']++; } } // a stock or low stock is supplied, enable inventory tracking for the product if (!empty($record['prodvarstock']) || !empty($record['prodvarlowstock'])) { $updateProd = array( 'prodinvtrack' => 2 ); $GLOBALS['ISC_CLASS_DB']->UpdateQuery('products', $updateProd, 'productid = ' . $productID); } /** * This is a bit hackish but we need to update the product last modified time WITHOUT using the * product entity class (shock horror). This is because we have nothing else to update it with */ $savedata = array( "prodlastmodified" => time() ); $GLOBALS["ISC_CLASS_DB"]->UpdateQuery("products", $savedata, "productid = " . $productID); }
/** * _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) { // Now add any category specific discounts if (isset($_POST['catRules']['category']) && isset($_POST['catRules']['discount']) && isset($_POST['catRules']['discounttype']) && isset($_POST['catRules']['discountMethod'])) { for ($i = 0; $i < count($_POST['catRules']['category']); $i++) { $cat_id = $_POST['catRules']['category'][$i]; $discount = DefaultPriceFormat($_POST['catRules']['discount'][$i]); $applies_to = $_POST['catRules']['discounttype'][$i]; $discountmethod = $_POST['catRules']['discountMethod'][$i]; $newCatDiscount = array("customergroupid" => $GroupId, "discounttype" => "CATEGORY", "catorprodid" => $cat_id, "discountpercent" => $discount, "appliesto" => $applies_to, "discountmethod" => $discountmethod); $newCatDiscountId = $GLOBALS['ISC_CLASS_DB']->InsertQuery("customer_group_discounts", $newCatDiscount); } } // Build the cache again $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateCustomerGroupsCategoryDiscounts($GroupId); // Followed by any product specific discounts if (isset($_POST['prodRules']['product']) && isset($_POST['prodRules']['discount']) && isset($_POST['prodRules']['discountMethod'])) { for ($i = 0; $i < count($_POST['prodRules']['product']); $i++) { $prod_id = $_POST['prodRules']['product'][$i]; $discount = DefaultPriceFormat($_POST['prodRules']['discount'][$i]); $discountmethod = $_POST['prodRules']['discountMethod'][$i]; $newProdDiscount = array("customergroupid" => $GroupId, "discounttype" => "PRODUCT", "catorprodid" => $prod_id, "discountpercent" => $discount, "appliesto" => "NOT_APPLICABLE", "discountmethod" => $discountmethod); $newProdDiscountId = $GLOBALS['ISC_CLASS_DB']->InsertQuery("customer_group_discounts", $newProdDiscount); } } $err = $GLOBALS["ISC_CLASS_DB"]->GetErrorMsg(); if ($err == "") { return true; } else { return false; } }
/** * Check if passed string is a price (decimal) format * * @param string The The string to check that's a valid price. * @return boolean True if valid, false if not */ function IsPrice($price) { // Format the price as we'll be storing it internally $price = DefaultPriceFormat($price); // If the price contains anything other than [0-9.] then it's invalid if (preg_match('#[^0-9\\.]#i', $price)) { return false; } return true; }
/** * Save the configuration variables for this module that come in from the POST * array. * * @param array An array of configuration variables. * @return boolean True if successful. */ public function SaveModuleSettings($settings = array()) { // Delete any current settings the module has $this->DeleteModuleSettings(); // Insert the new settings if (empty($settings)) { return true; } $shippingMethod = GetShippingMethodById($this->methodId); // Mark the module as being configured $newVar = array('zoneid' => $shippingMethod['zoneid'], 'methodid' => $this->methodId, 'modulename' => $this->GetId(), 'variablename' => 'is_setup', 'variableval' => 1, 'varvendorid' => $shippingMethod['methodvendorid']); $GLOBALS['ISC_CLASS_DB']->InsertQuery("shipping_vars", $newVar); $moduleVariables = $this->GetCustomVars(); // Loop through the options that this module has foreach ($settings as $name => $value) { $format = ''; if (isset($moduleVariables[$name]['format'])) { $format = $moduleVariables[$name]['format']; } if (is_array($value)) { foreach ($value as $childValue) { switch ($format) { case 'price': $value = DefaultPriceFormat($childValue); break; case 'weight': case 'dimension': $value = DefaultDimensionFormat($value); break; } // Mark the module as being configured $newVar = array('zoneid' => $shippingMethod['zoneid'], 'methodid' => $this->methodId, 'modulename' => $this->GetId(), 'variablename' => $name, 'variableval' => $childValue, 'varvendorid' => $shippingMethod['methodvendorid']); $GLOBALS['ISC_CLASS_DB']->InsertQuery("shipping_vars", $newVar); } } else { switch ($format) { case 'price': $value = DefaultPriceFormat($value); break; case 'weight': case 'dimension': $value = DefaultDimensionFormat($value); break; } // Mark the module as being configured $newVar = array('zoneid' => $shippingMethod['zoneid'], 'methodid' => $this->methodId, 'modulename' => $this->GetId(), 'variablename' => $name, 'variableval' => $value, 'varvendorid' => $shippingMethod['methodvendorid']); $GLOBALS['ISC_CLASS_DB']->InsertQuery("shipping_vars", $newVar); } } return true; }
/** * Imports an actual product record in to the database. * * @param array Array of record data */ protected function _ImportRecord($record) { if (!$record['custconemail']) { $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportCustomersMissingEmail'); return; } if (!is_email_address($record['custconemail'])) { $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record']) . " " . GetLang('ImportCustomersInvalidEmail'); return; } $fillin = array('custconcompany', 'custconfirstname', 'custconlastname', 'custconphone'); foreach ($fillin as $fillkey) { if (!isset($record[$fillkey])) { $record[$fillkey] = ''; } } // Is there an existing customer with the same email? $customerId = 0; $existingFormSessionId = 0; $query = sprintf("select customerid from [|PREFIX|]customers where lower(custconemail)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote(isc_strtolower($record['custconemail']))); $result = $GLOBALS["ISC_CLASS_DB"]->Query($query); if ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) { // Overriding existing products, set the product id if (isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) { $customerId = $row['customerid']; $this->ImportSession['Results']['Updates'][] = $record['custconfirstname'] . " " . $record['custconlastname'] . " (" . $record['custconemail'] . ")"; } else { $this->ImportSession['Results']['Duplicates'][] = $record['custconfirstname'] . " " . $record['custconlastname'] . " (" . $record['custconemail'] . ")"; return; } if (isId($row['custformsessionid'])) { $existingFormSessionId = $row['custformsessionid']; } } $customerData = array('company' => $record['custconcompany'], 'firstname' => $record['custconfirstname'], 'lastname' => $record['custconlastname'], 'email' => $record['custconemail'], 'phone' => $record['custconphone']); if (isset($record['custpassword']) && $record['custpassword'] !== '') { $customerData['password'] = $record['custpassword']; } if (isset($record['custstorecredit'])) { $customerData['storecredit'] = DefaultPriceFormat($record['custstorecredit']); } if (isId($customerId)) { $customerData['customerid'] = $customerId; } // Are we placing the customer in a customer group? $groupId = 0; if (!empty($record['custgroup'])) { static $customerGroups; $groupName = strtolower($record['custgroup']); if (isset($customerGroups[$groupName])) { $groupId = $customerGroups[$groupName]; } else { $query = "\n\t\t\t\t\tSELECT customergroupid\n\t\t\t\t\tFROM [|PREFIX|]customer_groups\n\t\t\t\t\tWHERE LOWER(groupname)='" . $GLOBALS['ISC_CLASS_DB']->Quote($groupName) . "'\n\t\t\t\t"; $groupId = $GLOBALS['ISC_CLASS_DB']->FetchOne($query, 'customergroupid'); // Customer group doesn't exist, create it if (!$groupId) { $newGroup = array('name' => $record['custgroup'], 'discount' => 0, 'isdefault' => 0, 'categoryaccesstype' => 'all'); $entity = new ISC_ENTITY_CUSTOMERGROUP(); $groupId = $entity->add($newGroup); } if ($groupId) { $customerGroups[$groupName] = $groupId; } } } $customerData['customergroupid'] = $groupId; // Do we have a shipping address? $shippingData = array(); if (isset($record['shipfullname']) || isset($record['shipfirstname']) || isset($record['shipaddress1']) || isset($record['shipaddress2']) || isset($record['shipcity']) || isset($record['shipstate']) || isset($record['shipzip']) || isset($record['shipcountry'])) { $fillin = array('shipaddress1', 'shipaddress2', 'shipcity', 'shipstate', 'shipzip', 'shipcountry'); foreach ($fillin as $fillkey) { if (!isset($record[$fillkey])) { $record[$fillkey] = ''; } } $shippingData['shipfirstname'] = ''; $shippingData['shiplastname'] = ''; $shippingData['shipaddress1'] = $record['shipaddress1']; $shippingData['shipaddress2'] = $record['shipaddress2']; $shippingData['shipcity'] = $record['shipcity']; $shippingData['shipstate'] = $record['shipstate']; $shippingData['shipzip'] = $record['shipzip']; $shippingData['shipcountry'] = $record['shipcountry']; $shippingData['shipstateid'] = 0; $shippingData['shipcountryid'] = 0; $shippingData['shipdestination'] = ''; // Find the country and state $shippingData['shipcountryid'] = (int) GetCountryByName($record['shipcountry']); if (!$shippingData['shipcountryid']) { $shippingData['shipcountryid'] = (int) GetCountryIdByISO2($record['shipcountry']); } // Still nothing? 0 for the shipping country ID if (!$shippingData['shipcountryid']) { $shippingData['shipcountryid'] = 0; } if (isset($record['shipstate'])) { $shippingData['shipstateid'] = GetStateByName($record['shipstate'], $shippingData['shipcountryid']); } // Still nothing? 0 for the shipping state ID if (!$shippingData['shipstateid']) { $shippingData['shipstateid'] = 0; } if (!isset($record['shipfullname']) || $record['shipfullname'] == "") { if (isset($record['shipfirstname']) && $record['shipfirstname'] != '') { $shippingData['shipfirstname'] = $record['shipfirstname']; } else { $shippingData['shipfirstname'] = $customerData['firstname']; } if (isset($record['shiplastname']) && $record['shiplastname'] != '') { $shippingData['shiplastname'] = $record['shiplastname']; } else { $shippingData['shiplastname'] = $customerData['lastname']; } } if (!isset($record['shipphone']) && isset($record['custconphone'])) { $shippingData['shipphone'] = $record['custconphone']; } else { $shippingData['shipphone'] = $record['shipphone']; } /** * Handle any of the address custom fields that we might have */ if (!empty($this->customFields) && array_key_exists('custom', $record)) { $shippingData['shipformsessionid'] = $this->_importCustomFormfields(FORMFIELDS_FORM_ADDRESS, $record['custom']); if (!isId($shippingData['shipformsessionid'])) { unset($shippingData['shipformsessionid']); } } } /** * Handle any of the customer custom fields that we might have */ if (!empty($this->customFields) && array_key_exists('custom', $record)) { $formSessionId = $this->_importCustomFormfields(FORMFIELDS_FORM_ACCOUNT, $record['custom'], $existingFormSessionId); if (isId($formSessionId)) { $customerData['custformsessionid'] = $formSessionId; } } $customerData['is_import'] = true; $customerEntity = new ISC_ENTITY_CUSTOMER(); // New customer, insert in to DB if ($customerId == 0) { // Set a temporary password, retrievable later via lost password function if (!isset($customerData['password']) || $customerData['password'] == '') { $customerData['password'] = isc_substr(uniqid(rand(), true), 0, 10); } $customerData['token'] = GenerateCustomerToken(); $customerData['shipping_address'] = $shippingData; $rtn = $customerEntity->add($customerData); ++$this->ImportSession['Results']['SuccessCount']; } else { if (count($shippingData) > 0) { $query = sprintf("select shipid from [|PREFIX|]shipping_addresses where shipcustomerid='%d' and lower(shipaddress1)='%s' and lower(shipaddress2)='%s' and lower(shipcity)='%s' and lower(shipstate)='%s' and lower(shipcountry)='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($customerId), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipaddress1']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipaddress2']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipcity']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipstate']), $GLOBALS['ISC_CLASS_DB']->Quote($shippingData['shipcountry'])); $Result = $GLOBALS['ISC_CLASS_DB']->Query($query); $row = $GLOBALS['ISC_CLASS_DB']->Fetch($Result); // Address doesn't exist, we insert it if (!$row['shipid']) { $customerData['shipping_address'] = $shippingData; } } $rtn = $customerEntity->edit($customerData); } }
/** * Commit a gift wrapping type to the database (either create a new one or update an existing one) * * @param array An array of data about the gift wrapping type. * @param int If updating an existing wrap, the ID. * @return boolean True if successful, false if not. */ private function CommitWrap($data, $wrapId=0) { if(!isset($data['wrapvisible'])) { $data['wrapvisible'] = 0; } if(!isset($data['wrapallowcomments'])) { $data['wrapallowcomments'] = ''; } // image validation is performed in ValidateWrap $files = ISC_UPLOADHANDLER::getUploadedFiles(); foreach ($files as /** @var UploadHandlerFile */$file) { if ($file->fieldName == 'wrapimage') { if ($file->getIsMoved()) { // only save if file was moved by ValidateWrap $data['wrappreview'] = str_replace(ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/', '', $file->getMovedDestination()); } break; } } $wrapData = array( 'wrapname' => $data['wrapname'], 'wrapprice' => DefaultPriceFormat($data['wrapprice']), 'wrapvisible' => (int)$data['wrapvisible'], 'wrapallowcomments' => (int)$data['wrapallowcomments'], ); if(isset($data['wrappreview'])) { $wrapData['wrappreview'] = $data['wrappreview']; } if($wrapId == 0) { $wrapId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('gift_wrapping', $wrapData); } else { $GLOBALS['ISC_CLASS_DB']->UpdateQuery('gift_wrapping', $wrapData, "wrapid='".(int)$wrapId."'"); } $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateGiftWrapping(); // Couldn't save? return an error message if($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()) { return false; } return true; }
/** * Actually save a new order or an updated existing order in the database * after it's been validated. * * @param array An array of details about the order to save. * @param int The ID of the existing order if we're updating an order. * @return boolean True if successful, false if not. */ private function CommitOrder($data, $orderId = 0) { $GLOBALS['ISC_CLASS_DB']->StartTransaction(); /** * We need to find our billing/shipping details from the form fields first as it is * also used in creating the customer */ $billingDetails = array(); $shippingDetails = array(); $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true); $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true); $fields = $billingFields + $shippingFields; $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone'); foreach (array_keys($fields) as $fieldId) { $privateName = $fields[$fieldId]->record['formfieldprivateid']; if ($privateName == '' || !array_key_exists($privateName, $addressMap)) { continue; } if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) { $detailsVar =& $billingDetails; } else { $detailsVar =& $shippingDetails; } /** * Find the country */ if (isc_strtolower($privateName) == 'country') { $detailsVar['shipcountry'] = $fields[$fieldId]->getValue(); $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue()); if (!isId($detailsVar['shipcountryid'])) { $detailsVar['shipcountryid'] = 0; } /** * Else find the state */ } else { if (isc_strtolower($privateName) == 'state') { $detailsVar['shipstate'] = $fields[$fieldId]->getValue(); $stateInfo = GetStateInfoByName($detailsVar['shipstate']); if ($stateInfo && isId($stateInfo['stateid'])) { $detailsVar['shipstateid'] = $stateInfo['stateid']; } else { $detailsVar['shipstateid'] = 0; } /** * Else the rest */ } else { $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue(); } } } // If we're creating an account for this customer, create it now if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') { $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid']); $GLOBALS['CusFirstname'] = $billingDetails['shipfirstname']; # Baskaran /* Added the store credit as seperate as it may be disabled while add/edit order - vikas */ if (isset($data['custstorecredit'])) { $customerData['storecredit'] = DefaultPriceFormat($data['custstorecredit']); } /** * Save the customer custom fields */ if (gzte11(ISC_MEDIUMPRINT)) { $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT); if (isId($formSessionId)) { $customerData['custformsessionid'] = $formSessionId; } } $entity = new ISC_ENTITY_CUSTOMER(); $data['ordcustid'] = $entity->add($customerData); if (!$data['ordcustid']) { $GLOBALS['ISC_CLASS_DB']->RollbackTransaction(); return false; } } //2010-11-08 Ronnie add When calculating the ship infomation corresponding to no $GLOBALS['BCK_shipcountryid'] = $detailsVar['shipcountry']; $GLOBALS['BCK_shipstateid'] = $detailsVar['shipstate']; if ($GLOBALS['BCK_shipstateid'] == '') { $GLOBALS['BCK_shipcountryid'] = $billingDetails['shipcountry']; $GLOBALS['BCK_shipstateid'] = $billingDetails['shipstate']; } foreach ($this->GetCartApi()->GetProductsInCart() as $rowId => $product) { if (!isset($product['exists_order_coupon']) && isset($product['discount'])) { // Now workout the discount amount if ($product['coupontype'] == 0) { // It's a dollar discount $newPrice = $product['product_price'] - $product['discount']; } else { // It's a percentage discount $discount = $product['product_price'] / 100 * $product['discount']; if ($discount == $product['product_price']) { $newPrice = 0; } else { $newPrice = $product['product_price'] - $discount; } } if ($newPrice < 0) { $newPrice = 0; } $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $newPrice); } elseif (isset($product['exists_order_coupon']) && isset($product['discount'])) { $this->GetCartApi()->SetItemValue($rowId, 'discount_price', $product['product_price']); $newPrice = 0; if ($product['coupontype'] == 0) { // It's a dollar discount $newPrice = $product['product_price'] + $product['discount']; } else { // It's a percentage discount $newPrice = $product['product_price'] / (1 - $product['discount'] / 100); } $this->GetCartApi()->SetItemValue($rowId, 'product_price', $newPrice); } } $orderSummary = $this->CalculateOrderSummary(); //ronnie //$orderSummary['taxCost']; $defaultCurrency = GetDefaultCurrency(); $email = ''; if (isset($data['custconemail']) && $data['customerType'] == 'new') { $email = $data['custconemail']; } else { if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') { $email = $data['anonymousemail']; } } /********************************************************** Code added by Mayank Jaitly for getting the logged user for adding his/her id as order owner. ************************************************************/ $loggeduser = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUser(); ////////// End of alteration $custid = $data['ordcustid']; $ordstatus = ''; $query = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]customers c, [|PREFIX|]customer_groups cg WHERE c.customerid = '{$custid}' AND cg.customergroupid = c.custgroupid AND cg.groupname = 'Walk In' "); if ($GLOBALS['ISC_CLASS_DB']->CountResult($query) > 0) { $ordstatus = '10'; } else { $ordstatus = $data['ordstatus']; } $billemail = $email; $shipemail = $email; if ($data['customerType'] == 'anonymous') { if (isset($data['anonymousemail']) && !empty($data['anonymousemail'])) { $billemail = $email; $shipemail = $email; } else { $billemail = $_POST['ordbillemail']; $shipemail = $_POST['ordshipemail']; } } $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $billemail, 'ordshipemail' => $shipemail, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'companygiftcertificateamount' => $orderSummary['companyGiftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno'], 'orderowner' => $loggeduser['pk_userid']); if (isset($data['ordbillsaveAddress'])) { $newOrder['billingaddress']['saveAddress'] = 1; if (gzte11(ISC_MEDIUMPRINT)) { $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING); } } if ($newOrder['paymentmethod'] == 'manual') { $newOrder['paymentmethodname'] = GetLang('ManualPayment'); } else { if ($newOrder['paymentmethod'] == 'giftcertificate') { $newOrder['giftcertificateamount'] = $orderSummary['total']; } else { if ($newOrder['paymentmethod'] == 'storecredit') { $newOrder['storecreditamount'] = $orderSummary['total']; } else { if ($newOrder['paymentmethod'] == 'custom') { $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name']; } else { if ($newOrder['paymentmethod'] == 'paypal_admin') { // added new condition for paypal payment option - vikas $newOrder['paymentmethodname'] = GetLang('PaypalPayment'); } else { if ($newOrder['paymentmethod'] == 'googlecheckout_admin') { $newOrder['paymentmethodname'] = GetLang('GooglePayment'); } else { if ($newOrder['paymentmethod'] == 'creditcard') { $newOrder['paymentmethodname'] = GetLang('CreditCardPayment'); } else { if ($newOrder['paymentmethod'] == 'cash') { $newOrder['paymentmethodname'] = GetLang('CashPayment'); } } } } } } } } if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) { if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) { $newOrder['shippingaddress'] = $newOrder['billingaddress']; } else { $newOrder['shippingaddress'] = $shippingDetails; if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) { /** * This is a bit tricky. We need to convert these shipping fields to use the billing * field IDs when saving in the shipping_addresses table as they all use the billing * fields on the frontend */ $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true); $shippingKeys = array_keys($shippingFields); $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys); $shippingSessData = array(); foreach ($shippingMap as $fieldId => $newBillingId) { if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') { continue; } $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue(); } $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData); } } if (isset($data['ordshipsaveAddress'])) { $newOrder['shippingaddress']['saveAddress'] = 1; } } if ($orderId > 0) { $existingOrder = GetOrder($orderId); $newOrder['vendorid'] = $existingOrder['ordvendorid']; $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']); //Alandy_2011-14-20 debug credit amount error! recalculate the gatewayamount,fetch the gatewayamount from profer order is wrong! //$newOrder['gatewayamount'] = $existingOrder['ordgatewayamount']; $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount']; $newOrder['currencyid'] = $existingOrder['ordcurrencyid']; $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate']; $newOrder['orderid'] = $orderId; $newOrder['orddate'] = $existingOrder['orddate']; $newOrder['ordipaddress'] = $existingOrder['ordipaddress']; } /** * Save the billing/shipping custom fields for the order */ if (gzte11(ISC_MEDIUMPRINT)) { if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) { $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']); } else { $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING)); if (isId($formSessionId)) { $newOrder['ordformsessionid'] = $formSessionId; } } } // dada.wang 20120406 save cgc change $cgces = $this->GetCartApi()->Get('COMPANYGIFTCERTIFICATES'); if (is_array($cgces) && !empty($cgces)) { $newOrder['companygiftcertificates'] = $cgces; } $entity = new ISC_ENTITY_ORDER(); if (isset($existingOrder)) { $newOrder['adminflag'] = 1; //dada.wang 2012-04-10 if has gc or cgc was remove then use this function to remove it $this->RemoveGCAndCGC($newOrder); if (!$entity->edit($newOrder)) { $GLOBALS['ISC_CLASS_DB']->RollbackTransaction(); return false; } } else { $newOrder['adminflag'] = 1; $data['orderid'] = $entity->add($newOrder); if (!$data['orderid']) { $GLOBALS['ISC_CLASS_DB']->RollbackTransaction(); return false; } $newOrder['orderid'] = $data['orderid']; } // If one or more gift certificates were used we need to apply them to this order if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) { $usedCertificates = array(); $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES'); $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates); } // Add by NI_20100827_Jack // If one or more gift certificates were used we need to apply them to this order if ($newOrder['companygiftcertificateamount'] > 0 && isset($newOrder['companygiftcertificates']) && !empty($newOrder['companygiftcertificates'])) { $usedCertificates = array(); $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES'] = GetClass('ISC_COMPANYGIFTCERTIFICATES'); $GLOBALS['ISC_CLASS_COMPANY_GIFT_CERTIFICATES']->ApplyCompanyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['companygiftcertificates'], $usedCertificates); } $GLOBALS['ISC_CLASS_DB']->CommitTransaction(); // Did the payment method have any info it needs to save? Save it $provider = null; GetModuleById('checkout', $provider, $data['orderpaymentmodule']); if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) { $fields = $data['paymentField'][$data['orderpaymentmodule']]; $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields); } if ($data['ordstatus'] != $newOrder['ordstatus']) { UpdateOrderStatus($data['orderid'], $data['ordstatus'], false); } // If we're emailing the customer about their order, send it now if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) { EmailInvoiceToCustomer($data['orderid']); } unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]); /************************************************************* Alterations done by Mayank Jaitly on 28 June 2010 **************************************************************/ /* // commented the below code as this is not needed. $customerYMMdata=array( 'year' => $data['searchyear'], 'make' => $data['searchmake'], 'model' => MakeURLNormal($data['searchmodel']), 'bed_size' =>$data['bedsize'], 'cab_size' =>$data['cabsize'] ); $clarion_entity = new ISC_ADMIN_CLARION(); $ymmID=$clarion_entity->fnSaveUserYMM($customerYMMdata,$data['ordcustid'],$_REQUEST['customerType'],$data['orderid']); */ /*********************** End of Alteration *********/ /*************************************************************** Code Added by Mayank Jaitly on 29 June 2010 ****************************************************************/ // commented the below code as this is not needed. // $clarion_entity->fnUpdateOrderYMM($data['orderid'],$ymmID); /********************* End of code **************************/ return $data['orderid']; }
private function _CommitCompanyGiftCertificate($cgcId = 0) { $_POST['cgcappliesto'] = $_POST['usedfor']; if ($_POST['cgcappliesto'] == "categories") { // Applies to categories $_POST['cgcappliestovalues'] = implode(",", array_map('intval', $_POST['catids'])); } else { // Applies to products $_POST['cgcappliestovalues'] = implode(',', array_map('intval', explode(',', $_POST['prodids']))); } if (!empty($_POST['cgcexpires'])) { //$_POST['cgcexpires'] = ConvertDateToTime($_POST['cgcexpires']); comment by NI_20100901_Jack make it same with coupon $vals = explode("/", $_POST['cgcexpires']); $mktime = mktime(23, 59, 59, $vals[0], $vals[1], $vals[2]); $_POST['cgcexpires'] = $mktime; } else { $_POST['cgcexpires'] = 0; } if (!isset($_POST['cgccode']) || empty($_POST['cgccode'])) { $_POST['cgccode'] = GenerateCouponCode(); } if (isset($_POST['cgcenabled'])) { $_POST['cgcenabled'] = 1; } else { $_POST['cgcenabled'] = 0; } $_POST['cgcminpurchase'] = DefaultPriceFormat($_POST['cgcminpurchase']); $_POST['cgcamount'] = DefaultPriceFormat($_POST['cgcamount']); $_POST['cgcbalance'] = DefaultPriceFormat($_POST['cgcbalance']); for ($i = 1; $i <= $_POST['recipientcount']; $i++) { if (empty($_POST['to_name_' . $i]) && empty($_POST['to_email_' . $i])) { continue; } if ($i == 1 or empty($_POST['to_name']) and empty($_POST['to_email'])) { $_POST['to_name'] .= $_POST['to_name_' . $i]; $_POST['to_email'] .= $_POST['to_email_' . $i]; } else { $_POST['to_name'] .= '$' . $_POST['to_name_' . $i]; $_POST['to_email'] .= '$' . $_POST['to_email_' . $i]; } } if ($cgcId == 0) { //check if code or name already exist $query = sprintf("select * from [|PREFIX|]company_gift_certificates where cgccode = '%s'", $_POST['cgccode']); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if ($GLOBALS['ISC_CLASS_DB']->CountResult($result) > 0) { return GetLang('CompanyGiftCertificateCodeExists'); } //new cgc $query = sprintf("insert into [|PREFIX|]company_gift_certificates (\n\t\t\t\t\tcgccode, cgcto, cgctoemail, \n\t\t\t\t\tcgccustid, cgcamount, cgcbalance, cgcenabled, cgcmessage, \n\t\t\t\t\tcgcname, cgcappliesto, cgcappliestovalues, cgcminpurchase, cgctemplate, \n\t\t\t\t\tcgcexpirydate, cgcpurchasedate, cgcstatus) VALUES\n\t\t\t\t\t('%s', '%s', '%s', \n\t\t\t\t\t%s, %s, %s, %s, '%s', \n\t\t\t\t\t'%s', '%s', '%s', %s, '%s', \n\t\t\t\t\t%s, %s, 2);", $_POST['cgccode'], $_POST['to_name'], $_POST['to_email'], 0, $_POST['cgcamount'], $_POST['cgcbalance'], $_POST['cgcenabled'], $_POST['message'], $_POST['cgcname'], $_POST['cgcappliesto'], $_POST['cgcappliestovalues'], (int) $_POST['cgcminpurchase'], $_POST['certificate_theme'], $_POST['cgcexpires'], time()); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if ($result == false) { return GetLang('CompanyGiftCertificateInsertError'); } else { return; } } else { //check if code or name already exist $query = sprintf("select * from [|PREFIX|]company_gift_certificates where cgccode = '%s' and cgcid <> %s ", $_POST['cgccode'], $cgcId); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if ($GLOBALS['ISC_CLASS_DB']->CountResult($result) > 0) { return GetLang('CompanyGiftCertificateCodeExists'); } //check balance $query = sprintf("UPDATE [|PREFIX|]company_gift_certificates SET \n\t\t\t\t\tcgccode = '%s', cgcto = '%s',cgctoemail = '%s',cgcamount = %s,cgcbalance = %s,\n\t\t\t\t\tcgcenabled = %s,cgcmessage = '%s',cgcname = '%s',cgcappliesto = '%s',cgcappliestovalues = '%s',\n\t\t\t\t\tcgcminpurchase = %s,cgctemplate = '%s',cgcexpirydate = %s WHERE cgcid = %s;", $_POST['cgccode'], $_POST['to_name'], $_POST['to_email'], $_POST['cgcamount'], $_POST['cgcbalance'], $_POST['cgcenabled'], $_POST['message'], $_POST['cgcname'], $_POST['cgcappliesto'], $_POST['cgcappliestovalues'], $_POST['cgcminpurchase'], $_POST['certificate_theme'], $_POST['cgcexpires'], $cgcId); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if ($result == false) { return GetLang('ErrCompanyGiftCertificateNotUpdated'); } else { return; } } }
/** * _GetVariationData * Load the variation data for a product either from the form or database * * @param Int $ProductId The ID of the product to load variations for. 0 if it's a new product * @param String $RefArray The array to store the variation details in * @return Void */ public function _GetVariationData($ProductId = 0, &$RefArray = array()) { if($ProductId == 0) { // First, do we even have a variation selected? if(isset($_POST['variationId']) && is_numeric($_POST['variationId']) && isset($_POST['options'])) { foreach($_POST['options'] as $option_counter => $option) { $tmp = array(); // The combination ID hasn't been assigned yet if(isset($option['id'])) { $tmp['combinationid'] = $option['id']; } else { $tmp['combinationid'] = 0; } // The product ID hasn't been assigned yet $tmp['vcproductid'] = 0; // The variation id $tmp['vcvariationid'] = (int)$_POST['variationId']; // Is the combination enabled? $tmp['vcenabled'] = 0; if(isset($option['enabled'])) { $tmp['vcenabled'] = 1; } // The variation option combination $ids = preg_replace("/^#/", "", $option['variationcombination']); $ids = str_replace("#", ",", $ids); $tmp['vcoptionids'] = $ids; // The product option's SKU $tmp['vcsku'] = $option['sku']; // The price difference type $tmp['vcpricediff'] = $option['pricediff']; // The price difference or fixed price $tmp['vcprice'] = DefaultPriceFormat($option['price']); // The weight difference type $tmp['vcweightdiff'] = $option['weightdiff']; // The weight difference or fixed weight $tmp['vcweight'] = DefaultDimensionFormat($option['weight']); $tmp['vcimage'] = ''; $tmp['vcimagezoom'] = ''; $tmp['vcimagestd'] = ''; $tmp['vcimagethumb'] = ''; if (isset($_FILES['options']['name'][$option_counter]['image']) && $_FILES['options']['name'][$option_counter]['image'] != '') { try { $image = ISC_PRODUCT_IMAGE::importImage( $_FILES['options']['tmp_name'][$option_counter]['image'], $_FILES['options']['name'][$option_counter]['image'], false, false, true, false ); $tmp['vcimage'] = $image->getSourceFilePath(); $tmp['vcimagezoom'] = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true, false); $tmp['vcimagestd'] = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true, false); $tmp['vcimagethumb'] = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true, false); } catch (Exception $ex) { } } elseif (isset($option['delimage'])) { $tmp['vcimage'] = "REMOVE"; } // The current stock level if(isset($option['currentstock'])) { $tmp['vcstock'] = (int)$option['currentstock']; } else { $tmp['vcstock'] = 0; } // The low stock level if(isset($option['lowstock'])) { $tmp['vclowstock'] = (int)$option['lowstock']; } else { $tmp['vclowstock'] = 0; } // Push the option to the stack array_push($RefArray, $tmp); } } } }
/** * Save an updated tax rate in the database. */ private function SaveUpdatedTaxRate() { $data = $this->GetTaxRateDataFromPost(); $updatedRate = array("taxratename" => $data['taxratename'], "taxratepercent" => DefaultPriceFormat($data['taxratepercent']), "taxratecountry" => $data['taxratecountry'], "taxratestates" => $data['taxratestates'], "taxratebasedon" => $data['taxratebasedon'], "taxratestatus" => (int) $data['taxratestatus'], 'taxaddress' => $data['taxaddress']); $GLOBALS['ISC_CLASS_DB']->UpdateQuery("tax_rates", $updatedRate, "taxrateid='" . $GLOBALS['ISC_CLASS_DB']->Quote((int) $data['taxrateid']) . "'"); if ($GLOBALS['ISC_CLASS_DB']->Error() == "") { $this->ManageTaxSettings(array(GetLang('TaxRateUpdatedSuccessfully') => MSG_SUCCESS)); // Log this action $GLOBALS['ISC_CLASS_LOG']->LogAdminAction($data['taxrateid'], $data['taxratename']); } else { $this->ManageTaxSettings(array(sprintf(GetLang('TaxRateNotUpdated'), $GLOBALS['ISC_CLASS_DB']->Error()) => MSG_ERROR)); } }
/** * Imports an actual product record in to the database. * * @param array Array of record data */ protected function _ImportRecord($record) { static $customerGroups=array(); if(!$record['custconemail']) { $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang('ImportCustomersMissingEmail'); return; } if(!is_email_address($record['custconemail'])) { $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang('ImportCustomersInvalidEmail'); return; } // Is there an existing customer with the same email? $existingCustomer = null; $existingFormSessionId = 0; $searchFields = array( "custconemail" => array( "value" => isc_strtolower($record["custconemail"]), "func" => "LOWER" ) ); $customerId = $this->customerEntity->search($searchFields); if (isId($customerId)) { $existingCustomer = $this->customerEntity->get($customerId); } else { $customerId = 0; } if(is_array($existingCustomer)) { // Overriding existing customer, set the customer id if(isset($this->ImportSession['OverrideDuplicates']) && $this->ImportSession['OverrideDuplicates'] == 1) { $this->ImportSession['Results']['Updates'][] = $record['custconfirstname']." ".$record['custconlastname']." (".$record['custconemail'].")"; } else { $this->ImportSession['Results']['Duplicates'][] = $record['custconfirstname']." ".$record['custconlastname']." (".$record['custconemail'].")"; return; } if (isId($existingCustomer['custformsessionid'])) { $existingFormSessionId = $existingCustomer['custformsessionid']; } } else { /** * Fill in the blanks only if we are adding in a customer */ $fillin = array('custconcompany', 'custconfirstname', 'custconlastname', 'custconphone'); foreach ($fillin as $fillkey) { if (!isset($record[$fillkey])) { $record[$fillkey] = ''; } } } $customerData = array(); foreach (array_keys($this->_ImportFields) as $field) { if (substr($field, 0, 4) == "cust" && array_key_exists($field, $record)) { $customerData[$field] = $record[$field]; } } if(isset($customerData["custstorecredit"])) { $customerData["custstorecredit"] = DefaultPriceFormat($customerData["custstorecredit"]); } if (array_key_exists("custgroup", $customerData)) { $customerData["custgroupid"] = $customerData["custgroup"]; } if (isId($customerId)) { $customerData["customerid"] = $customerId; } // Are we placing the customer in a customer group? $groupId = 0; if (array_key_exists("custgroup", $record) && trim($record["custgroup"]) !== "") { $groupName = strtolower($record['custgroup']); if(isset($customerGroups[$groupName])) { $groupId = $customerGroups[$groupName]; } else { $searchFields = array( "groupname" => array( "value" => isc_strtolower($groupName), "func" => "LOWER" ) ); $groupId = $this->groupEntity->search($searchFields); // Customer group doesn't exist, create it if(!isId($groupId)) { $newGroup = array( 'groupname' => $record['custgroup'], 'discount' => 0, 'isdefault' => 0, 'categoryaccesstype' => 'all' ); $groupId = $this->groupEntity->add($newGroup); } if($groupId) { $customerGroups[$groupName] = $groupId; } } } $customerData['custgroupid'] = $groupId; // Do we have a shipping address? $shippingData = array(); if (!$this->ImportSession['IsBulkEdit']) { // Don't import the address if we are missing the street address if(isset($record['shipaddress1']) && trim($record['shipaddress1']) !== "" && (isset($record['shipfirstname']) || isset($record['shipaddress2']) || isset($record['shipcity']) || isset($record['shipstate']) || isset($record['shipzip']) || isset($record['shipcountry']))) { $shippingData[] = $this->ParseAddress($record, $customerId); } } else { // bulk edit import // search for addresses for ($x = 1; $x <= $this->ImportSession['AddressCount']; $x++) { if(isset($record['shipaddress1' . $x]) && trim($record['shipaddress1' . $x]) !== "" && (isset($record['shipfirstname' . $x]) || isset($record['shipaddress2' . $x]) || isset($record['shipcity' . $x]) || isset($record['shipstate' . $x]) || isset($record['shipzip' . $x]) || isset($record['shipcountry' . $x]))) { $shippingData[] = $this->ParseAddress($record, $customerId, $x); } } } if (!empty($shippingData)) { $customerData['addresses'] = $shippingData; } /** * Handle any of the customer custom fields that we might have */ if (!empty($this->customFields) && array_key_exists('custom', $record)) { $formSessionId = $this->_importCustomFormfields(FORMFIELDS_FORM_ACCOUNT, $record['custom'], $existingFormSessionId); if (isId($formSessionId)) { $customerData['custformsessionid'] = $formSessionId; } } $customerData['is_import'] = true; // New customer, insert in to DB if($customerId == 0) { // Set a temporary password, retrievable later via lost password function if(!isset($customerData['custpassword']) || $customerData['custpassword'] == '') { $customerData['custpassword'] = isc_substr(uniqid(rand(), true), 0, 10); } $customerData['customertoken'] = GenerateCustomerToken(); $rtn = $this->customerEntity->add($customerData); ++$this->ImportSession['Results']['SuccessCount']; } // Updating an existing customer else { $rtn = $this->customerEntity->edit($customerData); } }
/** * To save the defined eBay listing template * * @param string $error Referenced variable to store an error message in if saving is unsuccessfull * @param int $templateId The optional template to update instead. If 0 a new template is created. * @return mixed Returns the template Id if saved successfully, FALSE otherwise */ public function SaveEbayTemplate(&$error, $templateId = 0) { // site we're listing on $siteId = (int)$_POST['siteId']; // set up basic template variables $templateName = $_POST['templateName']; $templateIsDefault = isset($_POST['templateAsDefault']); $privateListing = isset($_POST['privateListing']); // set up category variables $categoryOptions = $_POST['primaryCategoryOptions']; $secondaryCategoryOptions = array(); $primaryCategoryId = $categoryOptions['category_id']; $secondaryCategoryId = 0; $secondaryCategoryName = ''; $primaryStoreCategoryId = 0; $primaryStoreCategoryName = ''; $secondaryStoreCategoryId = 0; $secondaryStoreCategoryName = ''; if (!empty($_POST['secondaryCategoryOptions'])) { $secondaryCategoryId = $_POST['secondaryCategoryOptions']['category_id']; $secondaryCategoryName = $_POST['secondaryCategoryOptions']['name']; $secondaryCategoryOptions = $_POST['secondaryCategoryOptions']; } if (!empty($_POST['primaryStoreCategoryOptions'])) { $primaryStoreCategoryId = $_POST['primaryStoreCategoryOptions']['category_id']; $primaryStoreCategoryName = $_POST['primaryStoreCategoryOptions']['name']; } if (!empty($_POST['secondaryStoreCategoryOptions'])) { $secondaryStoreCategoryId = $_POST['secondaryStoreCategoryOptions']['category_id']; $secondaryStoreCategoryName = $_POST['secondaryStoreCategoryOptions']['name']; } // item details $quantityToSell = 1; if ($_POST['quantityType'] == 'more') { $quantityToSell = (int)$_POST['quantityMore']; } if ($quantityToSell < 1) { $quantityToSell = 1; } $useItemPhoto = isset($_POST['useItemPhoto']); $lotSize = 0; if (isset($_POST['lotSize'])) { $lotSize = (int)$_POST['lotSize']; } if ($lotSize < 0) { $lotSize = 0; } $useProductImage = isset($_POST['useItemPhoto']); // item location $locationCountry = (int)$_POST['locationCountry']; $locationCountryCode = GetCountryISO2ById($locationCountry); $locationZip = $_POST['locationZip']; $locationCityState = $_POST['locationCityState']; $prices = array(); // selling method $sellingMethod = $_POST['sellingMethod']; // Online Auction if ($sellingMethod == 'Chinese') { // reserve price $useReservePrice = isset($_POST['useReservePrice']); if ($useReservePrice) { $reservePriceOption = $_POST['reservePriceOption']; $price = array( 'price_type' => self::RESERVE_PRICE_TYPE, 'selected_type' => $reservePriceOption ); if ($reservePriceOption == 'PriceExtra') { $price['calculate_operator'] = $_POST['reservePricePlusOperator']; $price['calculate_option'] = $_POST['reservePricePlusType']; if ($price['calculate_option'] == 'amount') { $price['calculate_price'] = DefaultPriceFormat($_POST['reservePricePlusValue']); } else { $price['calculate_price'] = (double)$_POST['reservePricePlusValue']; } } elseif ($reservePriceOption == 'CustomPrice') { $price['price'] = DefaultPriceFormat($_POST['reservePriceCustomValue']); } $prices[] = $price; } // start price $startPriceOption = $_POST['startPriceOption']; $price = array( 'price_type' => self::STARTING_PRICE_TYPE, 'selected_type' => $startPriceOption ); if ($startPriceOption == 'PriceExtra') { $price['calculate_operator'] = $_POST['startPricePlusOperator']; $price['calculate_option'] = $_POST['startPricePlusType']; if ($price['calculate_option'] == 'amount') { $price['calculate_price'] = DefaultPriceFormat($_POST['startPricePlusValue']); } else { $price['calculate_price'] = (double)$_POST['startPricePlusValue']; } } elseif ($startPriceOption == 'CustomPrice') { $price['price'] = DefaultPriceFormat($_POST['startPriceCustomValue']); } $prices[] = $price; // buy it now if (isset($_POST['useBuyItNowPrice'])) { $buyItNowPriceOption = $_POST['buyItNowPriceOption']; $price = array( 'price_type' => self::BUY_PRICE_TYPE, 'selected_type' => $buyItNowPriceOption ); if ($buyItNowPriceOption == 'PriceExtra') { $price['calculate_operator'] = $_POST['buyItNowPricePlusOperator']; $price['calculate_option'] = $_POST['buyItNowPricePlusType']; if ($price['calculate_option'] == 'amount') { $price['calculate_price'] = DefaultPriceFormat($_POST['buyItNowPricePlusValue']); } else { $price['calculate_price'] = (double)$_POST['buyItNowPricePlusValue']; } } elseif ($buyItNowPriceOption == 'CustomPrice') { $price['price'] = DefaultPriceFormat($_POST['buyItNowPriceCustomValue']); } $prices[] = $price; } // auction duration $listingDuration = $_POST['auctionDuration']; } // Fixed item listing else { $fixedBuyItNowPriceOption = $_POST['fixedBuyItNowPriceOption']; $price = array( 'price_type' => self::STARTING_PRICE_TYPE, 'selected_type' => $fixedBuyItNowPriceOption ); if ($fixedBuyItNowPriceOption == 'PriceExtra') { $price['calculate_operator'] = $_POST['fixedBuyItNowPricePlusOperator']; $price['calculate_option'] = $_POST['fixedBuyItNowPricePlusType']; if ($price['calculate_option'] == 'amount') { $price['calculate_price'] = DefaultPriceFormat($_POST['fixedBuyItNowPricePlusValue']); } else { $price['calculate_price'] = (double)$_POST['fixedBuyItNowPricePlusValue']; } } elseif ($fixedBuyItNowPriceOption == 'CustomPrice') { $price['price'] = DefaultPriceFormat($_POST['fixedBuyItNowPriceCustomValue']); } $prices[] = $price; // auction duration $listingDuration = $_POST['fixedDuration']; } // payment options $paymentMethods = array(); if (isset($_POST['paymentMethods'])) { foreach ($_POST['paymentMethods'] as $paymentMethod) { $paymentMethods[] = $paymentMethod; } } // manually add paypal in if required since it wont be posted (disabled form field) if ($categoryOptions['paypal_required']) { $paymentMethods[] = 'PayPal'; } $paypalEmail = $_POST['paypalEmailAddress']; // shipping options $useInternationalShipping = isset($_POST['yesInternationalShipping']); $useDomesticShipping = false; if ($_POST['domesticShipping'] == 'specify') { $useDomesticShipping = true; } $shippingAreas = array( 'domestic' => $useDomesticShipping, 'international' => $useInternationalShipping ); $dispatchTimeMax = 0; if (isset($_POST['handlingTime'])) { $dispatchTimeMax = (int)$_POST['handlingTime']; } // sales tax $useSalesTax = false; if (!empty ($_POST['salesTax']) && $_POST['salesTax'] == '1') { $useSalesTax = (bool)$_POST['salesTax']; } $salesTaxState = ''; $salesTaxPercentage = 0; $salesTaxIncludesShippingCost = false; if ($useSalesTax) { $salesTaxState = $_POST['salesTaxState']; $salesTaxPercentage = DefaultPriceFormat($_POST['salesTaxPercentage'], false); $salesTaxIncludesShippingCost = isset($_POST['salesTaxIncludeShippingCost']); } // other options $checkoutInstructions = $_POST['checkoutInstructions']; // returns $acceptReturns = isset($_POST['acceptReturns']); $returnOfferAs = ''; if (isset($_POST['refundOption'])) { $returnOfferAs= $_POST['refundOption']; } $returnsPeriod = ''; if (isset($_POST['returnsWithin'])) { $returnsPeriod = $_POST['returnsWithin']; } $returnCostPaidBy = ''; if (isset($_POST['returnCostPaidBy'])) { $returnCostPaidBy = $_POST['returnCostPaidBy']; } $additionalPolicyInfo = ''; if (isset($_POST['additionalPolicyInfo'])) { $additionalPolicyInfo = $_POST['additionalPolicyInfo']; } // upgrade options $counterStyle = $_POST['hitCounter']; $galleryOption = $_POST['galleryOption']; $galleryDuration = ''; if ($galleryOption == 'Featured') { $galleryDuration = $_POST['galleryDuration']; } $listingFeatures = array(); if (isset($_POST['listingFeature'])) { $listingFeatures = $_POST['listingFeature']; } $acceptBestOffer = false; // where did this option go? // our template data to insert $newTemplate = array( 'name' => $templateName, 'enabled' => 1, 'user_id' => $this->auth->GetUserId(), 'site_id' => $siteId, 'is_default' => $templateIsDefault, 'is_private' => $privateListing, 'quantities' => $quantityToSell, 'use_prod_image' => $useItemPhoto, 'lot_size' => $lotSize, 'listing_type' => $sellingMethod, 'listing_duration' => $listingDuration, 'primary_category_options' => serialize($categoryOptions), 'secondary_category_options' => serialize($secondaryCategoryOptions), 'primary_category_id' => $primaryCategoryId, 'secondary_category_id' => $secondaryCategoryId, 'secondary_category_name' => $secondaryCategoryName, 'store_category1_id' => $primaryStoreCategoryId, 'store_category1_name' => $primaryStoreCategoryName, 'store_category2_id' => $secondaryStoreCategoryId, 'store_category2_name' => $secondaryStoreCategoryName, 'accept_best_offer' => $acceptBestOffer, 'payment_method' => serialize($paymentMethods), 'paypal_email' => $paypalEmail, 'payment_instruction' => $checkoutInstructions, 'item_country' => $locationCountryCode, 'item_zip' => $locationZip, 'item_city' => $locationCityState, 'accept_return' => $acceptReturns, 'return_offer_as' => $returnOfferAs, 'return_period' => $returnsPeriod, 'return_cost_by' => $returnCostPaidBy, 'return_policy_description' => $additionalPolicyInfo, 'use_domestic_shipping' => $useDomesticShipping, 'use_international_shipping' => $useInternationalShipping, 'handling_time' => $dispatchTimeMax, 'use_salestax' => $useSalesTax, 'sales_tax_states' => $salesTaxState, 'salestax_percent' => $salesTaxPercentage, 'salestax_inc_shipping' => $salesTaxIncludesShippingCost, 'counter_style' => $counterStyle, 'gallery_opt' => $galleryOption, 'featured_gallery_duration' => $galleryDuration, 'listing_opt' => serialize($listingFeatures), 'date_added' => time() ); if (!$this->db->StartTransaction()) { $error = $this->db->Error(); return false; } if ($templateId) { if (!$this->db->UpdateQuery('ebay_listing_template', $newTemplate, 'id = ' . $templateId)) { $this->db->RollbackTransaction(); $error = $this->db->Error(); return false; } // delete old prices and shipping settings $this->db->DeleteQuery('ebay_listing_prices', 'WHERE ebay_listing_template_id = ' . $templateId); $query = 'DELETE es.*, ess.* FROM [|PREFIX|]ebay_shipping es, [|PREFIX|]ebay_shipping_serv ess WHERE ess.ebay_shipping_id = es.id AND es.ebay_listing_template_id = ' . $templateId; $this->db->Query($query); } else { // create new template $templateId = $this->db->InsertQuery('ebay_listing_template', $newTemplate); } if (!$templateId) { $this->db->RollbackTransaction(); $error = $this->db->Error(); return false; } // add the prices foreach ($prices as $price) { $price['ebay_listing_template_id'] = $templateId; if (!$this->db->InsertQuery('ebay_listing_prices', $price)) { $this->db->RollbackTransaction(); $error = $this->db->Error(); return false; } } // Saving Shipping Details foreach ($shippingAreas as $shippingArea => $enable) { // Skip if the shipping area isn't enabled if (!$enable) { continue; } // Skip the Freight shipping as there is nothing to be saved $shippingType = $_POST[$shippingArea . 'ShippingType']; $offerPickup = 0; $getItFast = 0; if (isset($_POST[$shippingArea . 'YesGetItFast'])) { $getItFast = 1; } $freeShipping = 0; $handlingCost = 0; if (isset($_POST[$shippingArea . 'HandlingCost'])) { $handlingCost = DefaultPriceFormat($_POST[$shippingArea . 'HandlingCost']); } $shippingPackage = ''; $services = array(); switch ($shippingType) { case 'Flat': // local pickup only available for domestic if (!empty($_POST[$shippingArea . 'LocalPickup'])) { $offerPickup = 1; } if (!empty($_POST[$shippingArea . 'YesFreeFlatShipping'])) { $freeShipping = 1; } foreach ($_POST[$shippingArea . 'ShippingServFlat'] as $index => $shippingService) { if (!$shippingService['Type']) { continue; } $shipToLocations = array(); if (!empty($shippingService['ShipTo'])) { // only support once service currently, but store as array for future use $shipToLocations = array($shippingService['ShipTo']); } if ($freeShipping && $index == 0) { $cost = 0; $additionalCost = 0; } else { $cost = DefaultPriceFormat($shippingService['Cost']); $additionalCost = DefaultPriceFormat($shippingService['MoreCost']); } $services[] = array ( 'ebay_shipping_id' => 0, 'name' => $shippingService['Type'], 'cost' => $cost, 'additional_cost' => $additionalCost, 'ship_to_locations' => serialize($shipToLocations), ); } break; case 'Calculated': $shippingPackage = $_POST[$shippingArea . 'ShippingPackage']; if (!empty($_POST[$shippingArea . 'YesFreeCalculatedShipping'])) { $freeShipping = 1; } foreach ($_POST[$shippingArea . 'ShippingServCalculated'] as $shippingService) { if (!$shippingService['Type']) { continue; } $shipToLocations = array(); if (!empty($shippingService['ShipTo'])) { // only support once service currently, but store as array for future use $shipToLocations = array($shippingService['ShipTo']); } $services[] = array ( 'ebay_shipping_id' => 0, 'name' => $shippingService['Type'], 'cost' => 0, 'additional_cost' => 0, 'ship_to_locations' => serialize($shipToLocations), ); } break; } // Save the shipping data $shippingData = array( 'ebay_listing_template_id' => $templateId, 'area' => $shippingArea, 'cost_type' => $shippingType, 'offer_pickup' => $offerPickup, 'is_free_shipping' => $freeShipping, 'handling_cost' => $handlingCost, 'package_type' => $shippingPackage, 'get_it_fast' => $getItFast, ); $eBayShippingId = $this->db->InsertQuery("ebay_shipping", $shippingData); if (!$eBayShippingId) { $this->db->RollbackTransaction(); $error = $this->db->Error(); return false; } // Save Shipping Services to the database foreach ($services as $serviceData) { $serviceData['ebay_shipping_id'] = (int)$eBayShippingId; if(!$this->db->InsertQuery("ebay_shipping_serv", $serviceData)) { $this->db->RollbackTransaction(); $error = $this->db->Error(); return false; } } } $this->db->CommitTransaction(); FlashMessage(GetLang('EbayTemplateSavedSuccessfully'), MSG_SUCCESS, '', 'EbayListingTemplate'); return $templateId; }
/** * Commit the changes (or a new shipping zone) to the database. * * @param array Array of information to insert/update about the shipping zone. * @param int The shipping zone ID if we're updating an existing zone. * @return boolean True if successful, false if there was an error. */ public function CommitShippingZone($data, $zoneId=0) { // If the zone ID is 0, then we're creating a new zone if($zoneId > 0) { $existingZone = $this->GetShippingZoneData($zoneId); } else { if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() > 0) { $data['zonevendorid'] = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(); } else if(isset($_REQUEST['vendorId'])) { $data['zonevendorid'] = (int)$_REQUEST['vendorId']; } } if(!trim($data['zonename'])) { return false; } if(($data['zonetype'] != 'state' && $data['zonetype'] != 'zip') || $zoneId == 1) { $data['zonetype'] = 'country'; } if(!isset($data['zonefreeshipping'])) { $data['zonefreeshipping'] = 0; $data['zonefreeshippingtotal'] = 0; } if(!isset($data['zoneenabled'])) { $data['zoneenabled'] = 0; } else { $data['zoneenabled'] = 1; } if(!isset($data['zonehandlingseparate'])) { $data['zonehandlingseparate'] = 0; } if(!isset($data['zonehandlingtype'])) { $data['zonehandlingtype'] = 'none'; } if(!isset($data['zonehandlingfee'])) { $data['zonehandlingfee'] = 0; } $zoneData = array( 'zonename' => $data['zonename'], 'zonetype' => $data['zonetype'], 'zonefreeshipping' => $data['zonefreeshipping'], 'zonefreeshippingtotal' => DefaultPriceFormat($data['zonefreeshippingtotal']), 'zonehandlingtype' => $data['zonehandlingtype'], 'zonehandlingfee' => DefaultPriceFormat($data['zonehandlingfee']), 'zonehandlingseparate' => $data['zonehandlingseparate'], 'zoneenabled' => $data['zoneenabled'] ); if(isset($data['zonevendorid'])) { $zoneData['zonevendorid'] = $data['zonevendorid']; } else if(isset($existingZone)) { $zoneData['zonevendorid'] = $existingZone['zonevendorid']; } else { $zoneData['zonevendorid'] = 0; } if($zoneId == 0) { $zoneId = $GLOBALS['ISC_CLASS_DB']->InsertQuery("shipping_zones", $zoneData); } else { $GLOBALS['ISC_CLASS_DB']->UpdateQuery("shipping_zones", $zoneData, "zoneid='".(int)$zoneId."'"); } $GLOBALS['ZoneId'] = $zoneId; // Couldn't save? return an error message if($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()) { return false; } if(!isset($existingZone) || (isset($existingZone) && $existingZone['zonedefault'] != 1)) { // Delete the old locations first if(isset($existingZone)) { $GLOBALS['ISC_CLASS_DB']->DeleteQuery('shipping_zone_locations', "WHERE zoneid='".$zoneId."'"); } // Now we insert the locations for this zone type. switch($data['zonetype']) { case 'country': $countryList = GetCountryListAsIdValuePairs(); foreach($data['zonetype_country_list'] as $countryId) { if(!isset($countryList[$countryId])) { continue; } $newLocation = array( 'zoneid' => $zoneId, 'locationtype' => 'country', 'locationvalue' => $countryList[$countryId], 'locationvalueid' => $countryId, 'locationvendorid' => (int)$zoneData['zonevendorid'], ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('shipping_zone_locations', $newLocation); } break; case 'state': $countryList = GetCountryListAsIdValuePairs(); $stateList = array(); foreach($data['zonetype_states'] as $stateRecord) { $state = explode('-', $stateRecord, 2); if(!isset($stateList[$state[0]])) { // Load the states in this country as we haven't done that before $stateList[$state[0]] = array(); $query = "SELECT * FROM [|PREFIX|]country_states WHERE statecountry='".(int)$state[0]."'"; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); while($stateResult = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { $stateList[$stateResult['statecountry']][$stateResult['stateid']] = $stateResult['statename']; } } // Start storing what we received if(isset($stateList[$state[0]][$state[1]])) { $stateName = $stateList[$state[0]][$state[1]]; } else { $stateName = ''; } $newLocation = array( 'zoneid' => $zoneId, 'locationtype' => 'state', 'locationvalue' => $stateName, 'locationvalueid' => (int)$state[1], 'locationcountryid' => (int)$state[0], 'locationvendorid' => (int)$zoneData['zonevendorid'], ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('shipping_zone_locations', $newLocation); } break; case 'zip': $countryId = $data['zonetype_zip_country']; $countryName = GetCountryById($countryId); if(!$countryName) { return false; } // Now save all of the codes that were entered $zipCodes = explode("\n", $data['zonetype_zip_list']); foreach($zipCodes as $zipCode) { $zipCode = trim($zipCode); if(!$zipCode) { continue; } $newLocation = array( 'zoneid' => $zoneId, 'locationtype' => 'zip', 'locationvalue' => $zipCode, 'locationvalueid' => '0', 'locationcountryid' => $countryId, 'locationvendorid' => (int)$zoneData['zonevendorid'], ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('shipping_zone_locations', $newLocation); } break; } } // We've just configured shipping - mark it as so. if(!in_array('shippingOptions', GetConfig('GettingStartedCompleted'))) { GetClass('ISC_ADMIN_ENGINE')->MarkGettingStartedComplete('shippingOptions'); } return $zoneId; }
protected function _CommitCoupon($CouponId = 0) { $name = trim($_POST['couponname']); $type = $_POST['coupontype']; // dollar or percent $amount = DefaultPriceFormat($_POST['couponamount']); $appliesTo = $_POST['usedfor']; if($appliesTo == "categories") { $appliesValues = $_POST['catids']; // nothing selected then default to all categories if (empty($appliesValues)) { $appliesValues = array('0'); } } else { $appliesValues = explode(",", $_POST['prodids']); } if (!empty($_POST['couponexpires'])) { $expires = ConvertDateToTime($_POST['couponexpires']); } else { $expires = 0; } if (!isset($_POST['couponcode']) || empty($_POST['couponcode'])) { $code = GenerateCouponCode(); } else { $code = trim($_POST['couponcode']); } if (isset($_POST['couponenabled'])) { $enabled = 1; } else { $enabled = 0; } $minPurchase = DefaultPriceFormat($_POST['couponminpurchase']); $maxUses = 0; $maxUsesPerCus = 0; if (isset($_POST['couponmaxuses'])) { $maxUses = (int)$_POST['couponmaxuses']; } if (isset($_POST['couponmaxusespercus'])) { $maxUsesPerCus = (int)$_POST['couponmaxusespercus']; } $locationRestricted = 0; if (!empty ($_POST['YesLimitByLocation'])) { $locationRestricted = 1; } $shippingMethodRestricted = 0; if (!empty ($_POST['YesLimitByShipping'])) { $shippingMethodRestricted = 1; } $coupon = array( 'couponname' => $name, 'coupontype' => $type, 'couponamount' => $amount, 'couponminpurchase' => $minPurchase, 'couponexpires' => $expires, 'couponenabled' => $enabled, 'couponcode' => $code, 'couponappliesto' => $appliesTo, 'couponmaxuses' => $maxUses, 'couponmaxusespercus' => $maxUsesPerCus, 'location_restricted' => $locationRestricted, 'shipping_method_restricted' => $shippingMethodRestricted, ); // update existing coupon if ($CouponId) { $result = $GLOBALS['ISC_CLASS_DB']->UpdateQuery("coupons", $coupon, "couponid = '" . $GLOBALS['ISC_CLASS_DB']->Quote($CouponId) . "'"); if (!$result) { return "Failed to update coupon"; } //delete existing values $query = "DELETE FROM [|PREFIX|]coupon_values WHERE couponid = '" . $GLOBALS['ISC_CLASS_DB']->Quote($CouponId) . "'"; $GLOBALS['ISC_CLASS_DB']->Query($query); } else { // create new coupon $CouponId = $GLOBALS['ISC_CLASS_DB']->InsertQuery("coupons", $coupon); if (!isId($CouponId)) { return "Failed to create coupon"; } } // add applies to values if (!empty($appliesValues)) { foreach ($appliesValues as $value) { $couponvalue = array( 'couponid' => $CouponId, 'valueid' => $value ); $GLOBALS['ISC_CLASS_DB']->InsertQuery("coupon_values", $couponvalue); } } // Location restriction // Remove all the existing ones if exist $GLOBALS['ISC_CLASS_DB']->DeleteQuery('coupon_locations', "WHERE coupon_id = " . $GLOBALS['ISC_CLASS_DB']->Quote($CouponId)); if ($locationRestricted) { $selectedType = $_POST['LocationType']; if ($selectedType == 'country') { $countryList = GetCountryListAsIdValuePairs(); foreach($_POST['LocationTypeCountries'] as $countryId) { if(empty ($countryList[$countryId])) { continue; } $newLocation = array( 'coupon_id' => (int)$CouponId, 'selected_type' => $selectedType, 'value' => $countryList[$countryId], 'value_id' => $countryId, 'country_id' => 0, ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('coupon_locations', $newLocation); } } else if ($selectedType == 'state') { $countryList = GetCountryListAsIdValuePairs(); $stateList = array(); foreach($_POST['LocationTypeStatesSelect'] as $stateRecord) { $state = explode('-', $stateRecord, 2); if(!isset($stateList[$state[0]])) { // Load the states in this country as we haven't done that before $stateList[$state[0]] = array(); $query = "SELECT * FROM [|PREFIX|]country_states WHERE statecountry='".(int)$state[0]."'"; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); while($stateResult = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { $stateList[$stateResult['statecountry']][$stateResult['stateid']] = $stateResult['statename']; } } // Start storing what we received if(isset($stateList[$state[0]][$state[1]])) { $stateName = $stateList[$state[0]][$state[1]]; } else { $stateName = ''; } $newLocation = array( 'coupon_id' => (int)$CouponId, 'selected_type' => $selectedType, 'value' => $stateName, 'value_id' => (int)$state[1], 'country_id' => (int)$state[0], ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('coupon_locations', $newLocation); } } else if ($selectedType == 'zip') { $zipCodes = explode("\n", $_POST['LocationTypeZipPostCodes']); foreach($zipCodes as $zipCode) { $zipCode = trim($zipCode); if(!$zipCode) { continue; } $newLocation = array( 'coupon_id' => (int)$CouponId, 'selected_type' => $selectedType, 'value' => $zipCode, 'value_id' => '0', 'country_id' => (int)$_POST['LocationTypeZipCountry'], ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('coupon_locations', $newLocation); } } } // Shipping Method restriction // Remove all the existing ones if exist $GLOBALS['ISC_CLASS_DB']->DeleteQuery('coupon_shipping_methods', "WHERE coupon_id = " . $GLOBALS['ISC_CLASS_DB']->Quote($CouponId)); if ($shippingMethodRestricted) { foreach ($_POST['LocationTypeShipping'] as $shipper) { $newShippingMethod = array( 'coupon_id' => (int)$CouponId, 'module_id' => $shipper, ); $GLOBALS['ISC_CLASS_DB']->InsertQuery('coupon_shipping_methods', $newShippingMethod); } } // Log this action $GLOBALS['ISC_CLASS_LOG']->LogAdminAction($CouponId, $_POST['couponcode']); return $CouponId; }
/** * Update the store credit for a customer * * @return void **/ private function UpdateStoreCredit() { if (!isset($_REQUEST['customerId'])) { exit; } $query = sprintf("SELECT customerid, custstorecredit FROM [|PREFIX|]customers WHERE customerid='%d'", $GLOBALS['ISC_CLASS_DB']->Quote($_REQUEST['customerId'])); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); $customer = $GLOBALS['ISC_CLASS_DB']->Fetch($result); if ($customer['customerid'] == 0) { exit; } $updatedCustomer = array("custstorecredit" => DefaultPriceFormat($_REQUEST['credit'])); $GLOBALS['ISC_CLASS_DB']->UpdateQuery("customers", $updatedCustomer, "customerid='" . $GLOBALS['ISC_CLASS_DB']->Quote($customer['customerid']) . "'"); // Log the credit change $creditChange = CFloat($_REQUEST['credit'] - $customer['custstorecredit']); if ($creditChange != 0) { $creditLog = array("customerid" => (int) $customer['customerid'], "creditamount" => $creditChange, "credittype" => "adjustment", "creditdate" => time(), "creditrefid" => 0, "credituserid" => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUserId(), "creditreason" => ""); $GLOBALS['ISC_CLASS_DB']->InsertQuery("customer_credits", $creditLog); } echo 1; exit; }
/** * Imports an actual product record in to the database. * * @param array Array of record data */ protected function _ImportRecord($record) { if(empty($record['prodname'])) { $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang('ImportProductsMissingName'); return; } if ($message = strtokenize($_REQUEST, '#')) { $this->ImportSession['Results']['Failures'][] = implode(",", $record['original_record'])." ".GetLang(B('UmVhY2hlZFByb2R1Y3RMaW1pdA==')); return; } $record = $this->normalizeInventoryTracking($record); $productHash = uniqid('IMPORT', true); $productId = 0; $hasThumb = false; $productFiles = array(); $productImages = array(); $existing = null; $isOverrideDuplicates = !empty($this->ImportSession['OverrideDuplicates']); $dupeCheckWhere = ''; // Is there an existing product with this product ID ? if (!empty($record['productid'])) { $query = "SELECT * FROM [|PREFIX|]products WHERE productid = " . (int)$record['productid']; $result = $GLOBALS["ISC_CLASS_DB"]->Query($query); if($existing = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) { // Overriding existing products, set the product id if($isOverrideDuplicates) { $productId = $existing['productid']; $this->addImportResult('Updates', $record['prodname']); } else { // a product was found, but we're not updating existing record: skip $this->addImportResult('Duplicates', $record['prodname']); return; } // merge existing product details with the incoming record $record = $this->mergeExistingRecord($record, $existing); } else { // no product for this id was found, skip $this->addImportResult('Failures', $record['productid'] . " " . GetLang('ImportProductNotFound')); return; } $dupeCheckWhere = " AND productid != " . (int)$record['productid']; } // Check if there is a different product with the same name $query = "SELECT * FROM [|PREFIX|]products WHERE prodname = '" . $GLOBALS['ISC_CLASS_DB']->Quote($record['prodname']) . "'" . $dupeCheckWhere; $result = $GLOBALS["ISC_CLASS_DB"]->Query($query); $differentProductWithSameName = $GLOBALS['ISC_CLASS_DB']->Fetch($result); if($differentProductWithSameName) { if($existing || !$isOverrideDuplicates) { $this->addImportResult('Duplicates', $record['prodname']); return; } $existing = $differentProductWithSameName; $productId = $existing['productid']; $this->addImportResult('Updates', $record['prodname']); $record = $this->mergeExistingRecord($record, $existing); } // Apply any default data $defaults = array( 'prodprice' => 0, 'prodcostprice' => 0, 'prodretailprice' => 0, 'prodsaleprice' => 0, 'prodweight' => 0, 'prodheight' => 0, 'prodwidth' => 0, 'proddepth' => 0, 'prodsearchkeywords' => '', 'prodsortorder' => 0, 'prodvisible' => 1, 'prodfeatured' => 0, 'prodrelatedproducts' => '-1', 'prodoptionsrequired' => 0, 'prodfreeshipping' => 0, 'prodlayoutfile' => '', 'prodtags' => '', 'prodcondition' => 'New', 'prodshowcondition' => 0, 'prodallowpurchases' => 1, 'prodeventdaterequired' => 0, 'prodeventdatefieldname' => '', 'prodeventdatelimited' => 0, 'prodeventdatelimitedtype' => 0, 'prodeventdatelimitedstartdate' => 0, 'prodeventdatelimitedenddate' => 0, 'prodbrandid' => 0, 'tax_class_name' => '', 'upc' => '', 'category' => null, ); $record += $defaults; // check validity of price columns $priceFields = array( 'prodprice', 'prodcostprice', 'prodsaleprice', 'prodretailprice' ); foreach ($priceFields as $field) { // price was invalid if (!IsPrice($record[$field])) { if ($productId) { // using existing price $record[$field] = $existing[$field]; } else { $record[$field] = 0; } $this->addImportResult('Warnings', $record['prodname']." ".GetLang('ImportProductInvalidPrice')); } } // Do we have a product file? $productFiles = array(); if (!$this->ImportSession['IsBulkEdit']) { if (!empty($record['prodfile'])) { $productFile = $this->_ImportFile($record); if ($productFile) { $productFiles[] = $productFile; } } } else { // bulk import files for ($x = 1; $x <= $this->ImportSession['MultiFieldCount']['files']; $x++) { if (empty($record['prodfile' . $x])) { continue; } $productFile = $this->_ImportFile($record, $x); if ($productFile) { $productFiles[] = $productFile; } } } // Do we have an image? $productImages = array(); if (!$this->ImportSession['IsBulkEdit']) { if(!empty($record['prodimagefile'])) { $importedImage = $this->_ImportImage($productId, $record); if ($importedImage) { $productImages[] = $importedImage; } } } else { // bulk import images for ($x = 1; $x <= $this->ImportSession['MultiFieldCount']['images']; $x++) { if (empty($record['prodimagefile' . $x])) { if (empty($record['prodimageid' . $x])) { continue; } // image file is empty but an ID was supplied, we should delete the image if ($productId) { try { $image = new ISC_PRODUCT_IMAGE($record['prodimageid' . $x]); // ensure this image is associated with this product if ($image->getProductId() == $productId) { $image->delete(); } } catch (Exception $ex) { } } continue; } $importedImage = $this->_ImportImage($productId, $record, $x); if ($importedImage) { $productImages[] = $importedImage; } } } // a category is not required if we have an existing record and ignore blanks is enabled $requireCatsField = !(!empty($record['productid']) && $this->ignoreBlankFields()); $cats = $this->getImportRecordCategories($record); if($requireCatsField && empty($cats)) { $this->addImportResult('Failures', implode(",", $record['original_record'])." ".GetLang('ImportProductsMissingCategory')); return; } // If there's a tax class, we need to fetch it now $record['tax_class_id'] = 0; if(!empty($record['tax_class_name'])) { static $taxClassCache = array(); if(!isset($taxClassCache[$record['tax_class_name']])) { $query = " SELECT id FROM [|PREFIX|]tax_classes WHERE name='".$GLOBALS['ISC_CLASS_DB']->quote($record['tax_class_name'])."' "; $taxClassCache[$record['tax_class_name']] = $GLOBALS['ISC_CLASS_DB']->fetchOne($query); } // Still don't have a matching tax class? Must be new. if(!$taxClassCache[$record['tax_class_name']]) { $newTaxClass = array( 'name' => $record['tax_class_name'] ); $taxClassCache[$record['tax_class_name']] = $GLOBALS['ISC_CLASS_DB']->insertQuery('tax_classes', $newTaxClass); } $record['tax_class_id'] = $taxClassCache[$record['tax_class_name']]; } // check the condition is valid $validConditions = array('new', 'used', 'refurbished'); if (!isset($record['prodcondition']) || !in_array(isc_strtolower($record['prodcondition']), $validConditions)) { $record['prodcondition'] = 'New'; } // Does the brand already exist? if(isset($record['brandname']) && $record['brandname'] != '') { $query = sprintf("select brandid from [|PREFIX|]brands where brandname='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($record['brandname'])); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); if($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { $brandId = $row['brandid']; } // Create new brand else { // do we have permission to create brands? if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Add_Brands)) { $newBrand = array( "brandname" => $record['brandname'] ); $brandId = $GLOBALS['ISC_CLASS_DB']->InsertQuery("brands", $newBrand); } else { // no brand creation permission, abort this record $this->addImportResult('Failures', $record['prodname'] . " " . GetLang('ImportNoPermissionCreateBrand')); return; } } $record['prodbrandid'] = $brandId; } else if(!$this->ignoreBlankFields()){ $record['prodbrandid'] = 0; } if (isset($record['prodfile']) && $record['prodfile'] != '') { $productType = 2; } else if (isset($existing['prodtype']) && isId($existing['prodtype'])) { $productType = (int)$existing['prodtype']; } else { $productType = 1; } // event date $record['prodeventdaterequired'] = $this->StringToYesNoInt($record['prodeventdaterequired']); if ($record['prodeventdaterequired']) { // we must have an event name if (empty($record['prodeventdatefieldname'])) { $record['prodeventdaterequired'] = 0; $this->addImportResult('Warnings', $record['prodname'] . ' ' . GetLang('ImportNoEventDateName')); } else { $record['prodeventdatelimited'] = $this->StringToYesNoInt($record['prodeventdatelimited']); if ($record['prodeventdatelimited']) { if (!empty($record['prodeventdatelimitedstartdate'])) { $record['prodeventdatelimitedstartdate'] = (int)@ConvertDateToTime($record['prodeventdatelimitedstartdate']); } if (!empty($record['prodeventdatelimitedenddate'])) { $record['prodeventdatelimitedenddate'] = (int)@ConvertDateToTime($record['prodeventdatelimitedenddate']); } // determine what type of event date it is if ($record['prodeventdatelimitedstartdate'] > 0 && $record['prodeventdatelimitedenddate'] == 0) { $record['prodeventdatelimitedtype'] = 2; // start date } elseif ($record['prodeventdatelimitedstartdate'] == 0 && $record['prodeventdatelimitedenddate'] > 0) { $record['prodeventdatelimitedtype'] = 3; // end date } elseif ($record['prodeventdatelimitedenddate'] > $record['prodeventdatelimitedstartdate']) { $record['prodeventdatelimitedtype'] = 1; // date range } else { $record['prodeventdatelimited'] = 0; $this->addImportResults('Warnings', $record['prodname'] . ' ' . GetLang('ImportEventDateInvalid')); } } } } // Verify the inventory tracking method is valid. if($record['prodinvtrack'] == 2 && !($existing && $existing['prodvariationid'])) { $this->addImportResult('Warnings', $record['prodname'] . ' ' . GetLang('ImportProductTrackInventoryNoVariations')); $record['prodinvtrack'] = $existing['prodinvtrack']; } // This is our product $productData = array( "prodname" => $record['prodname'], "prodcode" => @$record['prodcode'], "proddesc" => @$record['proddesc'], "prodsearchkeywords" => @$record['prodsearchkeywords'], "prodtype" => $productType, "prodprice" => DefaultPriceFormat($record['prodprice']), "prodcostprice" => DefaultPriceFormat($record['prodcostprice']), "prodretailprice" => DefaultPriceFormat($record['prodretailprice']), "prodsaleprice" => DefaultPriceFormat($record['prodsaleprice']), "prodavailability" => @$record['prodavailability'], "prodsortorder" => $record['prodsortorder'], "prodvisible" => (int)$record['prodvisible'], "prodfeatured" => $record['prodfeatured'], "prodrelatedproducts" => $record['prodrelatedproducts'], "prodinvtrack" => (int)@$record['prodinvtrack'], "prodcurrentinv" => (int)@$record['prodcurrentinv'], "prodlowinv" => (int)@$record['prodlowinv'], "prodoptionsrequired" => $record['prodoptionsrequired'], "prodwarranty" => @$record['prodwarranty'], "prodheight" => DefaultDimensionFormat(@$record['prodheight']), "prodweight" => DefaultDimensionFormat(@$record['prodweight']), "prodwidth" => DefaultDimensionFormat(@$record['prodwidth']), "proddepth" => DefaultDimensionFormat(@$record['proddepth']), "prodfreeshipping" => (int)$record['prodfreeshipping'], "prodfixedshippingcost" => DefaultPriceFormat(@$record['prodfixedshippingcost']), "prodbrandid" => (int)$record['prodbrandid'], "prodcats" => $cats, "prodpagetitle" => @$record['prodpagetitle'], "prodmetakeywords" => @$record['prodmetakeywords'], "prodmetadesc" => @$record['prodmetadesc'], "prodlayoutfile" => $record['prodlayoutfile'], 'prodtags' => $record['prodtags'], 'prodmyobasset' => '', 'prodmyobincome' => '', 'prodmyobexpense' => '', 'prodpeachtreegl' => '', 'prodcondition' => $record['prodcondition'], 'prodshowcondition' => (bool)$record['prodshowcondition'], 'prodallowpurchases' => (bool)$record['prodallowpurchases'], 'prodeventdaterequired' => $record['prodeventdaterequired'], 'prodeventdatefieldname' => $record['prodeventdatefieldname'], 'prodeventdatelimited' => $record['prodeventdatelimited'], 'prodeventdatelimitedtype' => $record['prodeventdatelimitedtype'], 'prodeventdatelimitedstartdate' => $record['prodeventdatelimitedstartdate'], 'prodeventdatelimitedenddate' => $record['prodeventdatelimitedenddate'], 'tax_class_id' => $record['tax_class_id'], 'upc' => $record['upc'], 'last_import' => $this->ImportSession['StartTime'], ); /** * The variation is part of the product record, so it will have to be attached to the record if this is an * update AND the existing product already has a variation */ if (isset($existing) && is_array($existing) && isId($existing['prodvariationid'])) { $productData['prodvariationid'] = $existing['prodvariationid']; } $empty = array(); // Save it $err = ''; if (!$GLOBALS['ISC_CLASS_ADMIN_PRODUCT']->_CommitProduct($productId, $productData, $empty, $empty, $empty, $err, $empty, true)) { $this->addImportResult('Failures', $record['prodname'] . " " . GetLang('ImportDatabaseError')); return; } if($productId == 0) { $productId = $GLOBALS['NewProductId']; } // Post process images $existingImages = new ISC_PRODUCT_IMAGE_ITERATOR("SELECT * FROM `[|PREFIX|]product_images` WHERE imageprodid = " . (int)$productId); $maxSort = count($existingImages); if ($this->ImportSession['DeleteImages']) { foreach ($existingImages as $existingImage) { $existingImage->delete(false); } $maxSort = 0; } if(!empty($productImages)) { // sort the images usort($productImages, array($this, "_compare_images")); // update our images with the product id foreach ($productImages as $image) { $image->setProductId($productId); // ensure that an image doesn't have a sort set higher than max, or if no sort specified, then also set it to the highest. if ($image->getSort() > $maxSort || $image->getSort() === null) { $image->setSort($maxSort); $maxSort++; } $image->saveToDatabase(false); } } // Delete existing files if ($this->ImportSession['DeleteDownloads']) { $query = " SELECT * FROM [|PREFIX|]product_downloads WHERE productid = " . $productId; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); while ($download = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) { // Remove the file from the file system @unlink(GetConfig('DownloadDirectory') . "/" . $download['downfile']); // Delete from the database $GLOBALS['ISC_CLASS_DB']->DeleteQuery('product_downloads', 'WHERE downloadid = ' . $download['downloadid']); } } // Process product files if(!empty($productFiles)) { foreach($productFiles as $file) { $file['productid'] = $productId; $GLOBALS['ISC_CLASS_DB']->InsertQuery("product_downloads", $file); } } ++$this->ImportSession['Results']['SuccessCount']; }
public function ProcessManualPayment($order, $data) { $amount = $order['total_inc_tax']; $amount = DefaultPriceFormat($amount); if ($amount <= 0) { return array('amount' => 0, 'result' => false, 'message' => GetLang('ManualPaymentNoAmountSpecified')); } $order['total_inc_tax'] = $amount; $orderData = array( 'orders' => array( $order['orderid'] => $order ) ); $this->SetOrderData($orderData); $result = $this->ProcessPaymentForm($data, true); $message = ''; if ($this->HasErrors()) { foreach ($this->GetErrors() as $error) { $message .= $error . "<br />"; } } return array('amount' => $amount, 'result' => $result, 'message' => $message); }
/** * Reformat the products array * * Method will reformat the products aray into something more standardised * * @access private * @param array &$input The referenced input data */ private function reformatProducts(&$input) { if (!array_key_exists('products', $input) || !is_array($input['products'])) { return null; } $newProducts = array(); foreach ($input['products'] as $product) { $tmpProd = array(); $price = 0; if (array_key_exists('type', $product) && strtolower($product['type']) == 'giftcertificate') { $price = $product['giftamount']; } else { if (array_key_exists('discount_price', $product)) { $price = $product['discount_price']; } else { $price = $product['product_price']; } } $tmpProd['productid'] = $product['product_id']; $tmpProd['name'] = $product['product_name']; $tmpProd['amount'] = DefaultPriceFormat(CPrice($price)); $tmpProd['quantity'] = $product['quantity']; $newProducts[] = $tmpProd; } $input['products'] = $newProducts; }
private function _CommitDiscount($DiscountId = 0) { require_once ISC_BASE_PATH . '/lib/api/discount.api.php'; $discount = new API_DISCOUNT(); if ($DiscountId != 0) { $discount->load($DiscountId); } $_POST['discountmaxuses'] = 0; if (isset($_POST['discountruleexpiresuses'])) { $_POST['discountmaxuses'] = $_POST['discountruleexpiresusesamount']; } $_POST['discountcurrentuses'] = 0; $query = sprintf("select max(sortorder) from [|PREFIX|]discounts"); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result); $_POST['discountenabled'] = 0; if (isset($_POST['enabled'])) { $_POST['discountenabled'] = 1; } $_POST['discountexpiry'] = 0; if (isset($_POST['discountruleexpiresdateamount']) && !empty($_POST['discountruleexpiresdateamount'])) { $_POST['discountexpiry'] = ConvertDateToTimeWithHours($_POST['discountruleexpiresdateamount'], $_POST['discountruleexpireshoursamount']); } $_POST['discountstart'] = 0; if (isset($_POST['discountrulestartsdateamount']) && !empty($_POST['discountrulestartsdateamount'])) { $_POST['discountstart'] = ConvertDateToTimeWithHours($_POST['discountrulestartsdateamount'], $_POST['discountrulestartshoursamount']); } $_POST['discountruletype'] = 0; if (isset($_POST['RuleType']) && !empty($_POST['RuleType'])) { $_POST['discountruletype'] = $_POST['RuleType']; } $_POST['configdata'] = ''; $cd = array(); foreach ($_POST as $module_id => $vars) { // Checkout variables start with checkout_ if (isc_substr($module_id, 0, 4) != "var_" && isc_substr($module_id, 0, 5) != "varn_") { continue; } if (is_array($vars)) { $vars = implode(',', $vars); } if (isc_substr($module_id, 0, 5) == "varn_") { $vars = DefaultPriceFormat($vars); } $cd[isc_html_escape($module_id)] = isc_html_escape($vars); } $_POST['configdata'] = serialize($cd); GetModuleById('rule', $ruleModule, $_POST['discountruletype']); if (!is_object($ruleModule)) { // Something really bad went wrong >_< return 'Rule Type Doesn\'t Exist'; } if ($DiscountId == 0) { $_POST['sortorder'] = $row['max(sortorder)'] + 1; $DiscountId = $discount->create(); } else { $_POST['sortorder'] = $discount->getSortOrder(); $discount->save(); } // calling the background process to update the price of the products under the discount if ($_POST['discountruletype'] == 'rule_percentoffitemsinseries' || $_POST['discountruletype'] == 'rule_percentoffitemsincat') { $this->UpdatePriceInBackground($DiscountId); } return $discount->error; }
/** * Save the selected shipping method for this order. */ private function OrderSaveShipping() { if (!isset($_REQUEST['orderSession']) || !isset($_REQUEST['shippingMethod'])) { exit; } $orderClass = GetClass('ISC_ADMIN_ORDERS'); $orderClass->GetCartApi($_REQUEST['orderSession']); $shippingMethods = $orderClass->GetCartApi()->Get('SHIPPING_QUOTES'); if ($_REQUEST['shippingMethod'] == 'existing') { $order = GetOrder($orderClass->GetCartApi()->Get('EXISTING_ORDER')); $shippingMethod = array('methodName' => $order['ordshipmethod'], 'methodCost' => $order['ordshipcost'], 'methodId' => 'existing', 'methodModule' => $order['ordershipmodule'], 'handlingCost' => $order['ordhandlingcost']); } else { if ($_REQUEST['shippingMethod'] == 'custom') { $shippingMethod = array('methodName' => $_REQUEST['customName'], 'methodCost' => DefaultPriceFormat($_REQUEST['customPrice']), 'methodId' => '', 'methodModule' => 'custom', 'handlingCost' => 0); } else { if (isset($shippingMethods[$_REQUEST['shippingMethod']])) { $quote = $shippingMethods[$_REQUEST['shippingMethod']]; $shippingMethod = array('methodName' => $quote['description'], 'methodCost' => $quote['price'], 'methodId' => $quote['methodId'], 'methodModule' => $quote['module'], 'handlingCost' => $quote['handling']); } else { exit; } } } $orderClass->GetCartApi()->Set('SHIPPING_METHOD', $shippingMethod); $response = array('orderSummary' => $orderClass->GenerateOrderSummaryTable()); echo isc_json_encode($response); exit; }
private function _CommitDiscount($DiscountId=0) { require_once(ISC_BASE_PATH.'/lib/api/discount.api.php'); $discount = new API_DISCOUNT(); $freeShippingMesgLocation = array(); if ($DiscountId != 0) { $discount->load($DiscountId); } $_POST['discountmaxuses'] = 0; if (isset($_POST['discountruleexpiresuses'])) { $_POST['discountmaxuses'] = $_POST['discountruleexpiresusesamount']; } $_POST['discountcurrentuses'] = 0; $query = sprintf("select max(sortorder) from [|PREFIX|]discounts"); $result = $GLOBALS['ISC_CLASS_DB']->Query($query); $row = $GLOBALS['ISC_CLASS_DB']->Fetch($result); $_POST['discountenabled'] = 0; if (isset($_POST['enabled'])) { $_POST['discountenabled'] = 1; } $_POST['discountexpiry'] = 0; if (isset($_POST['discountruleexpiresdateamount']) && !empty($_POST['discountruleexpiresdateamount'])) { $_POST['discountexpiry'] = ConvertDateToTime($_POST['discountruleexpiresdateamount']); } $_POST['discountruletype'] = 0; $_POST['free_shipping_message'] = ''; if (isset($_POST['RuleType']) && !empty($_POST['RuleType'])) { $_POST['discountruletype'] = $_POST['RuleType']; // if the selected rule related to free shipping, we will be collecting // additional message here. if (in_array($_POST['RuleType'], array('rule_buyxgetfreeshipping', 'rule_freeshippingwhenoverx'))) { if (!empty ($_POST['FreeShippingMessage']) && !empty ($_POST['ShowFreeShippingMesgOn'])) { $_POST['free_shipping_message'] = $_POST['FreeShippingMessage']; $freeShippingMesgLocation = $_POST['ShowFreeShippingMesgOn']; } } } $_POST['configdata'] = ''; $cd = array(); foreach($_POST as $module_id => $vars) { // Checkout variables start with checkout_ if (isc_substr($module_id, 0, 4) != "var_" && isc_substr($module_id,0,5) != "varn_") { continue; } if (is_array($vars)) { $vars = implode(',', $vars); } if (isc_substr($module_id,0,5) == "varn_") { $vars = DefaultPriceFormat($vars); } $cd[isc_html_escape($module_id)] = isc_html_escape($vars); } $_POST['configdata'] = serialize($cd); $_POST['free_shipping_message_location'] = serialize($freeShippingMesgLocation); GetModuleById('rule', $ruleModule, $_POST['discountruletype']); if(!is_object($ruleModule)) { // Something really bad went wrong >_< return 'Rule Type Doesn\'t Exist'; } if($DiscountId == 0) { $_POST['sortorder'] = $row['max(sortorder)']+1; $DiscountId = $discount->create(); } else { $_POST['sortorder'] = $discount->getSortOrder(); $discount->save(); } return $discount->error; }
/** * Save the configuration variables for this module that come in from the POST * array. * * @param array An array of configuration variables. * @return boolean True if successful. */ public function SaveModuleSettings($settings = array()) { foreach (array_keys($settings) as $setting) { list($fieldType, ) = explode('_', $setting, 2); switch ($fieldType) { case 'upper': case 'lower': $settings[$setting] = DefaultDimensionFormat($settings[$setting]); break; case 'cost': $settings[$setting] = DefaultPriceFormat($settings[$setting]); break; } } parent::SaveModuleSettings($settings); }
/** * Commit a gift wrapping type to the database (either create a new one or update an existing one) * * @param array An array of data about the gift wrapping type. * @param int If updating an existing wrap, the ID. * @return boolean True if successful, false if not. */ private function CommitWrap($data, $wrapId = 0) { if (!isset($data['wrapvisible'])) { $data['wrapvisible'] = 0; } if (!isset($data['wrapallowcomments'])) { $data['wrapallowcomments'] = ''; } if (isset($_FILES['wrapimage']) && is_array($_FILES['wrapimage']) && $_FILES['wrapimage']['name'] != '') { // Clean up the incoming file name a bit $_FILES['wrapimage']['name'] = preg_replace("#[^\\w.]#i", "_", $_FILES['wrapimage']['name']); $_FILES['wrapimage']['name'] = preg_replace("#_{1,}#i", "_", $_FILES['wrapimage']['name']); $randomFileName = GenRandFileName($_FILES['wrapimage']['name']); $imageLocation = 'wrap_images/' . $randomFileName; $dest = ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/' . $imageLocation; if (move_uploaded_file($_FILES['wrapimage']['tmp_name'], $dest)) { isc_chmod($dest, ISC_WRITEABLE_FILE_PERM); $data['wrappreview'] = $imageLocation; } } $wrapData = array('wrapname' => $data['wrapname'], 'wrapprice' => DefaultPriceFormat($data['wrapprice']), 'wrapvisible' => (int) $data['wrapvisible'], 'wrapallowcomments' => (int) $data['wrapallowcomments']); if (isset($data['wrappreview'])) { $wrapData['wrappreview'] = $data['wrappreview']; } if ($wrapId == 0) { $wrapId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('gift_wrapping', $wrapData); } else { $GLOBALS['ISC_CLASS_DB']->UpdateQuery('gift_wrapping', $wrapData, "wrapid='" . (int) $wrapId . "'"); } $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateGiftWrapping(); // Couldn't save? return an error message if ($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()) { return false; } return true; }
/** * This function checks to see if the user wants to save the search details as a custom search, * and if they do one is created. They are then forwarded onto the search results */ protected function SearchOrdersRedirect() { // Format totals back to the western standard if (isset($_GET['totalFrom']) && $_GET['totalFrom'] != "") { $_GET['totalFrom'] = $_REQUEST['totalFrom'] = DefaultPriceFormat($_GET['totalFrom']); } if (isset($_GET['totalTo']) && $_GET['totalTo'] != "") { $_GET['totalTo'] = $_REQUEST['totalTo'] = DefaultPriceFormat($_GET['totalTo']); } // Are we saving this as a custom search? if(isset($_GET['viewName']) && $_GET['viewName'] != '') { $search_id = $GLOBALS['ISC_CLASS_ADMIN_CUSTOMSEARCH']->SaveSearch($_GET['viewName'], $_GET); if($search_id > 0) { // Log this action $GLOBALS['ISC_CLASS_LOG']->LogAdminAction($search_id, $_GET['viewName']); ob_end_clean(); header(sprintf("Location:index.php?ToDo=customOrderSearch&searchId=%d&new=true", $search_id)); exit; } else { $this->ManageOrders(sprintf(GetLang('ViewAlreadExists'), $_GET['viewName']), MSG_ERROR); } } // Plain search else { $this->ManageOrders(); } }
/** * _GetVariationData * Load the variation data for a product either from the form or database * * @param Int $ProductId The ID of the product to load variations for. 0 if it's a new product * @param String $RefArray The array to store the variation details in * @return Void */ public function _GetVariationData($ProductId = 0, &$RefArray = array()) { if ($ProductId == 0) { // First, do we even have a variation selected? if (isset($_POST['variationId']) && is_numeric($_POST['variationId']) && isset($_POST['options'])) { foreach ($_POST['options'] as $option_counter => $option) { $tmp = array(); // The combination ID hasn't been assigned yet if (isset($option['id'])) { $tmp['combinationid'] = $option['id']; } else { $tmp['combinationid'] = 0; } // The product ID hasn't been assigned yet $tmp['vcproductid'] = 0; // The variation id $tmp['vcvariationid'] = (int) $_POST['variationId']; // Is the combination enabled? $tmp['vcenabled'] = 0; if (isset($option['enabled'])) { $tmp['vcenabled'] = 1; } // The variation option combination $ids = preg_replace("/^#/", "", $option['variationcombination']); $ids = str_replace("#", ",", $ids); $tmp['vcoptionids'] = $ids; // The product option's SKU $tmp['vcsku'] = $option['sku']; // The price difference type $tmp['vcpricediff'] = $option['pricediff']; // The price difference or fixed price $tmp['vcprice'] = DefaultPriceFormat($option['price']); // The weight difference type $tmp['vcweightdiff'] = $option['weightdiff']; // The weight difference or fixed weight $tmp['vcweight'] = DefaultDimensionFormat($option['weight']); // The image for this product option (if it's set) if ($this->_IsValidVariationImage($option_counter)) { $tmp['vcimage'] = $this->_StoreOptionImageAndReturnId($option_counter); } else { // Do we need to remove the image? if (isset($option['delimage'])) { $tmp['vcimage'] = "REMOVE"; } else { $tmp['vcimage'] = ""; } } // The thumbnail image for this product option if ($tmp['vcimage'] != "") { $tmp['vcthumb'] = $this->_AutoGenerateThumb($tmp['vcimage']); } else { $tmp['vcthumb'] = ""; } // The current stock level if (isset($option['currentstock'])) { $tmp['vcstock'] = (int) $option['currentstock']; } else { $tmp['vcstock'] = 0; } // The low stock level if (isset($option['lowstock'])) { $tmp['vclowstock'] = (int) $option['lowstock']; } else { $tmp['vclowstock'] = 0; } // Push the option to the stack array_push($RefArray, $tmp); } } } }
/** * Actually save a new order or an updated existing order in the database * after it's been validated. * * @param array An array of details about the order to save. * @param int The ID of the existing order if we're updating an order. * @return boolean True if successful, false if not. */ private function CommitOrder($data, $orderId = 0) { $GLOBALS['ISC_CLASS_DB']->StartTransaction(); /** * We need to find our billing/shipping details from the form fields first as it is * also used in creating the customer */ $billingDetails = array(); $shippingDetails = array(); $billingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_BILLING, true); $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true); $fields = $billingFields + $shippingFields; $addressMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'CompanyName' => 'company', 'AddressLine1' => 'address1', 'AddressLine2' => 'address2', 'City' => 'city', 'State' => 'state', 'Zip' => 'zip', 'State' => 'state', 'Country' => 'country', 'Phone' => 'phone'); foreach (array_keys($fields) as $fieldId) { $privateName = $fields[$fieldId]->record['formfieldprivateid']; if ($privateName == '' || !array_key_exists($privateName, $addressMap)) { continue; } if ($fields[$fieldId]->record['formfieldformid'] == FORMFIELDS_FORM_BILLING) { $detailsVar =& $billingDetails; } else { $detailsVar =& $shippingDetails; } /** * Find the country */ if (isc_strtolower($privateName) == 'country') { $detailsVar['shipcountry'] = $fields[$fieldId]->getValue(); $detailsVar['shipcountryid'] = GetCountryByName($fields[$fieldId]->getValue()); if (!isId($detailsVar['shipcountryid'])) { $detailsVar['shipcountryid'] = 0; } /** * Else find the state */ } else { if (isc_strtolower($privateName) == 'state') { $detailsVar['shipstate'] = $fields[$fieldId]->getValue(); $stateInfo = GetStateInfoByName($detailsVar['shipstate']); if ($stateInfo && isId($stateInfo['stateid'])) { $detailsVar['shipstateid'] = $stateInfo['stateid']; } else { $detailsVar['shipstateid'] = 0; } /** * Else the rest */ } else { $detailsVar['ship' . $addressMap[$privateName]] = $fields[$fieldId]->getValue(); } } } // If we're creating an account for this customer, create it now if ($data['ordcustid'] == 0 && $data['customerType'] == 'new') { $customerData = array('email' => $data['custconemail'], 'password' => $data['custpassword'], 'firstname' => $billingDetails['shipfirstname'], 'lastname' => $billingDetails['shiplastname'], 'company' => $billingDetails['shipcompany'], 'phone' => $billingDetails['shipphone'], 'token' => GenerateCustomerToken(), 'customergroupid' => $data['custgroupid'], 'storecredit' => DefaultPriceFormat($data['custstorecredit'])); /** * Save the customer custom fields */ if (gzte11(ISC_MEDIUMPRINT)) { $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_ACCOUNT); if (isId($formSessionId)) { $customerData['custformsessionid'] = $formSessionId; } } $entity = new ISC_ENTITY_CUSTOMER(); $data['ordcustid'] = $entity->add($customerData); if (!$data['ordcustid']) { $GLOBALS['ISC_CLASS_DB']->RollbackTransaction(); return false; } } $orderSummary = $this->CalculateOrderSummary(); $defaultCurrency = GetDefaultCurrency(); $email = ''; if (isset($data['custconemail']) && $data['customerType'] == 'new') { $email = $data['custconemail']; } else { if (isset($data['anonymousemail']) && $data['customerType'] == 'anonymous') { $email = $data['anonymousemail']; } } $newOrder = array('paymentmethod' => $data['orderpaymentmodule'], 'customerid' => $data['ordcustid'], 'billingaddress' => $billingDetails, 'ordbillemail' => $email, 'ordbillphone' => $billingDetails['shipphone'], 'geoipcountry' => $billingDetails['shipcountry'], 'geoipcountrycode' => GetCountryISO2ByName($billingDetails['shipcountry']), 'vendorid' => $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId(), 'giftcertificates' => $this->GetCartApi()->GetGiftCertificates(), 'shippingcost' => $orderSummary['shippingCost'], 'handlingcost' => $orderSummary['handlingCost'], 'pending_token' => GenerateOrderToken(), 'itemtotal' => $orderSummary['subtotal'], 'taxcost' => $orderSummary['taxCost'], 'taxrate' => $orderSummary['taxRate'], 'taxname' => $orderSummary['taxName'], 'giftcertificateamount' => $orderSummary['giftCertificateTotal'], 'gatewayamount' => $orderSummary['adjustedTotalCost'], 'totalincludestax' => $orderSummary['taxIncluded'], 'shippingprovider' => $orderSummary['shippingMethod'], 'shippingmodule' => $orderSummary['shippingModule'], 'totalcost' => $orderSummary['total'], 'ordstatus' => 0, 'isdigitalorder' => (int) $this->GetCartApi()->AllProductsInCartAreIntangible(), 'currencyid' => $defaultCurrency['currencyid'], 'currencyexchangerate' => 0, 'ordercomments' => @$data['ordcustmessage'], 'ordnotes' => @$data['ordnotes'], 'products' => $this->GetCartApi()->GetProductsInCart(), 'ordtrackingno' => $data['ordtrackingno']); if (isset($data['ordbillsaveAddress'])) { $newOrder['billingaddress']['saveAddress'] = 1; if (gzte11(ISC_MEDIUMPRINT)) { $newOrder['billingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(FORMFIELDS_FORM_BILLING); } } if ($newOrder['paymentmethod'] == 'manual') { $newOrder['paymentmethodname'] = GetLang('ManualPayment'); } else { if ($newOrder['paymentmethod'] == 'giftcertificate') { $newOrder['giftcertificateamount'] = $orderSummary['total']; } else { if ($newOrder['paymentmethod'] == 'storecredit') { $newOrder['storecreditamount'] = $orderSummary['total']; } else { if ($newOrder['paymentmethod'] == 'custom') { $newOrder['paymentmethodname'] = $data['paymentField']['custom']['name']; } } } } if (!$this->GetCartApi()->AllProductsInCartAreIntangible()) { if (isset($data['shippingUseBilling']) && $data['shippingUseBilling'] == 1) { $newOrder['shippingaddress'] = $newOrder['billingaddress']; } else { $newOrder['shippingaddress'] = $shippingDetails; if (isset($data['ordshipsaveAddress']) && gzte11(ISC_MEDIUMPRINT)) { /** * This is a bit tricky. We need to convert these shipping fields to use the billing * field IDs when saving in the shipping_addresses table as they all use the billing * fields on the frontend */ $shippingFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_SHIPPING, true); $shippingKeys = array_keys($shippingFields); $shippingMap = $GLOBALS['ISC_CLASS_FORM']->mapAddressFieldList(FORMFIELDS_FORM_SHIPPING, $shippingKeys); $shippingSessData = array(); foreach ($shippingMap as $fieldId => $newBillingId) { if ($shippingFields[$fieldId]->record['formfieldprivateid'] !== '') { continue; } $shippingSessData[$newBillingId] = $shippingFields[$fieldId]->getValue(); } $newOrder['shippingaddress']['shipformsessionid'] = $GLOBALS['ISC_CLASS_FORM']->saveFormSessionManual($shippingSessData); } } if (isset($data['ordshipsaveAddress'])) { $newOrder['shippingaddress']['saveAddress'] = 1; } } if ($orderId > 0) { $existingOrder = GetOrder($orderId); $newOrder['vendorid'] = $existingOrder['ordvendorid']; $newOrder['extraInfo'] = @unserialize($existingOrder['extrainfo']); $newOrder['gatewayamount'] = $existingOrder['ordgatewayamount']; $newOrder['storecreditamount'] = $existingOrder['ordstorecreditamount']; $newOrder['currencyid'] = $existingOrder['ordcurrencyid']; $newOrder['currencyexchangerate'] = $existingOrder['ordcurrencyexchangerate']; $newOrder['orderid'] = $orderId; $newOrder['orddate'] = $existingOrder['orddate']; $newOrder['ordipaddress'] = $existingOrder['ordipaddress']; } /** * Save the billing/shipping custom fields for the order */ if (gzte11(ISC_MEDIUMPRINT)) { if (isId($orderId) && isset($existingOrder['ordformsessionid']) && isId($existingOrder['ordformsessionid'])) { $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING), true, $existingOrder['ordformsessionid']); } else { $formSessionId = $GLOBALS['ISC_CLASS_FORM']->saveFormSession(array(FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING)); if (isId($formSessionId)) { $newOrder['ordformsessionid'] = $formSessionId; } } } $entity = new ISC_ENTITY_ORDER(); if (isset($existingOrder)) { if (!$entity->edit($newOrder)) { $GLOBALS['ISC_CLASS_DB']->RollbackTransaction(); return false; } } else { $data['orderid'] = $entity->add($newOrder); if (!$data['orderid']) { $GLOBALS['ISC_CLASS_DB']->RollbackTransaction(); return false; } } // If one or more gift certificates were used we need to apply them to this order if ($newOrder['giftcertificateamount'] > 0 && isset($newOrder['giftcertificates']) && !empty($newOrder['giftcertificates'])) { $usedCertificates = array(); $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES'] = GetClass('ISC_GIFTCERTIFICATES'); $GLOBALS['ISC_CLASS_GIFT_CERTIFICATES']->ApplyGiftCertificatesToOrder($newOrder['orderid'], $newOrder['totalcost'], $newOrder['giftcertificates'], $usedCertificates); } $GLOBALS['ISC_CLASS_DB']->CommitTransaction(); // Did the payment method have any info it needs to save? Save it $provider = null; GetModuleById('checkout', $provider, $data['orderpaymentmodule']); if (is_object($provider) && method_exists($provider, 'SaveManualPaymentFields')) { $fields = $data['paymentField'][$data['orderpaymentmodule']]; $provider->SaveManualPaymentFields(GetOrder($data['orderid'], false, false), $fields); } if ($data['ordstatus'] != $newOrder['ordstatus']) { UpdateOrderStatus($data['orderid'], $data['ordstatus'], false); } // If we're emailing the customer about their order, send it now if (isset($data['emailinvoice']) && $data['emailinvoice'] == 1) { EmailInvoiceToCustomer($data['orderid']); } unset($_SESSION['ORDER_MANAGER'][$data['orderSession']]); return $data['orderid']; }
/** * _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; }
public function editOrderUpdateItemQuantityPriceAction() { if(empty($_POST['quoteSession']) || empty($_POST['itemId'])) { exit; } /** @var ISC_QUOTE */ $quote = getClass('ISC_ADMIN_ORDERS')->getQuoteSession($_POST['quoteSession']); if(!$quote) { $this->sendEditOrderNoQuoteResponse(); } if(!$quote->hasItem($_POST['itemId'])) { exit; } $item = $quote->getItemById($_POST['itemId']); if ($item->isGiftCertificate()) { exit; // this should be denied by the ui } $item->setQuantity($_POST['quantity']); if($item->getBasePrice() != $_POST['price']) { $item->setBasePrice(DefaultPriceFormat($_POST['price'], null, true), true); } if(getConfig('taxDefaultTaxDisplayCart') == TAX_PRICES_DISPLAY_INCLUSIVE) { $incTax = true; } else { $incTax = false; } $response = array( 'itemsUpdateItemTotal' => array( 'id' => $item->getId(), 'content' => formatPrice($item->getTotal($incTax)) ), 'itemsSubtotal' => formatPrice($quote->getSubtotal($incTax)), ); if ($quote->getIsSplitShipping()) { $response['multiShippingTable'] = getClass('ISC_ADMIN_ORDERS')->renderMultiShippingTable($quote); } $this->sendEditOrderResponse($response); }
/** * Actually save a new vendor in the database or update an existing one. * * @param array Array of data about the vendor to save. * @param int The existing vendor ID to update, if we have one. * @return boolean True if successful, false if not. */ private function CommitVendor($data, $vendorId=0) { $data['vendorcountry'] = GetCountryById((int)$data['vendorcountry']); if (isset($data['vendorstate']) && $data['vendorstate'] != "") { $data['vendorstate'] = GetStateById((int)$data['vendorstate']); } else { $data['vendorstate'] = $_POST['vendorstate1']; } $existingName = ''; if($vendorId > 0) { $existingVendor = $this->GetVendorData($vendorId); $existingName = $existingVendor['vendorfriendlyname']; } if(!isset($data['vendororderemail'])) { $data['vendororderemail'] = ''; } if(!isset($data['vendorshipping']) || $data['vendorshipping'] == 0) { $data['vendorshipping'] = 0; if($vendorId > 0) { $GLOBALS['ISC_CLASS_DB']->DeleteQuery('shipping_zones', "WHERE zonevendorid='".(int)$vendorId."'"); $GLOBALS['ISC_CLASS_DB']->DeleteQuery('shipping_zone_locations', "WHERE locationvendorid='".(int)$vendorId."'"); $GLOBALS['ISC_CLASS_DB']->DeleteQuery('shipping_methods', "WHERE methodvendorid='".(int)$vendorId."'"); $GLOBALS['ISC_CLASS_DB']->DeleteQuery('shipping_vars', "WHERE varvendorid='".(int)$vendorId."'"); } } else { if($vendorId > 0 && $existingVendor['vendorshipping'] == 0) { // Find the default zone for the store and copy it $query = " SELECT * FROM [|PREFIX|]shipping_zones WHERE zonedefault='1' AND zonevendorid='0' "; $result = $GLOBALS['ISC_CLASS_DB']->Query($query); $masterZone = $GLOBALS['ISC_CLASS_DB']->Fetch($result); unset($masterZone['zoneid']); $masterZone['zonevendorid'] = $vendorId; $GLOBALS['ISC_CLASS_DB']->InsertQuery('shipping_zones', $masterZone); } } $vendorData = array( 'vendorname' => $data['vendorname'], 'vendorphone' => $data['vendorphone'], 'vendorbio' => $data['vendorbio'], 'vendoraddress' => $data['vendoraddress'], 'vendorcity' => $data['vendorcity'], 'vendorcountry' => $data['vendorcountry'], 'vendorstate' => $data['vendorstate'], 'vendorzip' => $data['vendorzip'], 'vendorfriendlyname' => $this->GenerateVendorFriendlyName($data['vendorname'], $vendorId, $existingName), 'vendororderemail' => $data['vendororderemail'], 'vendorshipping' => (int)$data['vendorshipping'], 'vendoremail' => $data['vendoremail'], ); // If we have permission to, set the permissions for the vendor we're creating/editing if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() == 0 || $vendorId == 0) { $vendorData['vendorprofitmargin'] = DefaultPriceFormat($data['vendorprofitmargin']); $vendorData['vendoraccesscats'] = ''; if(!isset($data['vendorlimitcats']) && is_array($data['vendoraccesscats'])) { $data['vendoraccesscats'] = array_map('intval', $data['vendoraccesscats']); $vendorData['vendoraccesscats'] = implode(',', $data['vendoraccesscats']); } } if($vendorId == 0) { $vendorId = $GLOBALS['ISC_CLASS_DB']->InsertQuery('vendors', $vendorData); $updatedVendor = array(); // If we chose to upload a logo for this vendor, save it too foreach(array(self::VENDOR_LOGO, self::VENDOR_PHOTO) as $image) { $vendorImage = $this->SaveVendorImage($vendorId, $image); if($vendorImage === false) { $GLOBALS['ISC_CLASS_DB']->DeleteQuery('vendors', "WHERE vendorid='".(int)$vendorId."'"); return false; } else { $updatedVendor['vendor'.$image] = $vendorImage; } } if(!empty($updatedVendor)) { $GLOBALS['ISC_CLASS_DB']->UpdateQuery('vendors', $updatedVendor, "vendorid='".(int)$vendorId."'"); } } else { // If we chose to upload a logo for this vendor, save it too foreach(array(self::VENDOR_LOGO, self::VENDOR_PHOTO) as $image) { // Did we choose to delete a logo? if(isset($data['deletevendor'.$image])) { $this->DeleteVendorImage($vendorId, $image); $vendorData['vendor'.$image] = ''; } // Maybe we chose to upload an image? $vendorImage = $this->SaveVendorImage($vendorId, $image); if($vendorImage === false) { return false; } else if($vendorImage) { $vendorData['vendor'.$image] = $vendorImage; } } $GLOBALS['ISC_CLASS_DB']->UpdateQuery('vendors', $vendorData, "vendorid='".(int)$vendorId."'"); } $GLOBALS['ISC_CLASS_DATA_STORE']->UpdateVendors(); // Couldn't save? return an error message if($GLOBALS['ISC_CLASS_DB']->GetErrorMsg()) { return false; } return true; }
/** * Save the configuration variables for this module that come in from the POST * array. * * @param array An array of configuration variables. * @param bool RUE to delete any existing module settings, FALSE not to. Default is TRUE * @return boolean True if successful. */ public function SaveModuleSettings($settings = array(), $deleteFirst = true) { // Delete any current settings the module has if we are set to if ($deleteFirst) { $this->DeleteModuleSettings(); } // If we weren't supplied any settings and this module has one or more settings // don't continue and don't mark it as being set up yet if (empty($settings) && $this->GetNumSettings() > 0) { return true; } // Mark the module has being configured $newVar = array('modulename' => $this->GetId(), 'variablename' => 'is_setup', 'variableval' => 1); $GLOBALS['ISC_CLASS_DB']->InsertQuery('module_vars', $newVar); $moduleVariables = $this->GetCustomVars(); // Loop through the options that this module has foreach ($settings as $name => $value) { $format = ''; if (isset($moduleVariables[$name]['format'])) { $format = $moduleVariables[$name]['format']; } if (is_array($value)) { foreach ($value as $childValue) { switch ($format) { case 'price': $value = DefaultPriceFormat($childValue); break; case 'weight': case 'dimension': $value = DefaultDimensionFormat($value); break; } $newVar = array('modulename' => $this->GetId(), 'variablename' => $name, 'variableval' => $childValue); $GLOBALS['ISC_CLASS_DB']->InsertQuery('module_vars', $newVar); } } else { switch ($format) { case 'price': $value = DefaultPriceFormat($value); break; case 'weight': case 'dimension': $value = DefaultDimensionFormat($value); break; } $newVar = array('modulename' => $this->GetId(), 'variablename' => $name, 'variableval' => $value); $GLOBALS['ISC_CLASS_DB']->InsertQuery('module_vars', $newVar); } } return true; }