/**
  * Show the window to configure an item (variations, configurable fields) etc in the
  * order that's being created/edited.
  */
 private function OrderConfigureProduct()
 {
     if (!isset($_REQUEST['cartItemId']) || !isset($_REQUEST['orderSession'])) {
         exit;
     }
     // Initialize the cart management API
     $orderClass = GetClass('ISC_ADMIN_ORDERS');
     $orderClass->GetCartApi($_REQUEST['orderSession']);
     $existingProduct = $orderClass->GetCartApi()->GetProductInCart($_REQUEST['cartItemId']);
     if (is_array($existingProduct)) {
         if (isset($_REQUEST['productId']) && $existingProduct['product_id'] != $_REQUEST['productId']) {
             $existingProduct = false;
         } else {
             $_REQUEST['productId'] = $existingProduct['product_id'];
         }
     }
     // Fetch the product class on the front end as it'll be doing most of the work for this page
     $productClass = new ISC_PRODUCT($_REQUEST['productId']);
     if (!$productClass->GetProductId()) {
         exit;
     }
     if (!is_array($existingProduct) && !isset($_REQUEST['productId'])) {
         exit;
     } else {
         if (is_array($existingProduct)) {
             $GLOBALS['EditingExistingProduct'] = 1;
             $GLOBALS['Intro'] = GetLang('OrderConfigureProductEdit');
             $GLOBALS['ButtonLabel'] = GetLang('OrderConfigureProductEditButton');
             $productPrice = $existingProduct['product_price'];
             $GLOBALS['VariationId'] = $existingProduct['variation_id'];
         } else {
             $GLOBALS['Intro'] = GetLang('OrderConfigureProduct');
             $GLOBALS['ButtonLabel'] = GetLang('AddProductToOrder');
             // Finally, determine the price based on the customer group
             $product = $productClass->GetProduct();
             $productPrice = CalcProdCustomerGroupPrice($product, $product['prodcalculatedprice']);
         }
     }
     $GLOBALS['ProductPrice'] = FormatPrice($productPrice);
     $productVariations = $productClass->GetProductVariations();
     $GLOBALS['ProductName'] = isc_html_escape($productClass->GetProductName());
     $GLOBALS['ProductId'] = (int) $productClass->GetProductId();
     $GLOBALS['OrderSession'] = isc_html_escape($_REQUEST['orderSession']);
     $GLOBALS['CartItemId'] = isc_html_escape($_REQUEST['cartItemId']);
     $GLOBALS['Quantity'] = (int) $_REQUEST['quantity'];
     $GLOBALS['ProductOptionRequired'] = 0;
     $GLOBALS['VariationList'] = '';
     if (!empty($productVariations)) {
         // If we have an existing variation already, look up the combination
         $existingCombination = array();
         if (is_array($existingProduct) && $existingProduct['variation_id']) {
             $query = "\n\t\t\t\t\t\tSELECT vcoptionids\n\t\t\t\t\t\tFROM [|PREFIX|]product_variation_combinations\n\t\t\t\t\t\tWHERE combinationid='" . (int) $existingProduct['variation_id'] . "'\n\t\t\t\t\t";
             $existingCombination = explode(',', $GLOBALS['ISC_CLASS_DB']->FetchOne($query));
         }
         if ($productClass->IsOptionRequired()) {
             $GLOBALS['ProductOptionRequired'] = 1;
             $GLOBALS['VariationRequired'] = '*';
         } else {
             $GLOBALS['VariationRequired'] = ' ';
         }
         $GLOBALS['VariationNumber'] = 0;
         foreach ($productVariations as $name => $options) {
             $GLOBALS['VariationNumber']++;
             $optionList = '';
             foreach ($options as $option) {
                 $sel = '';
                 if (in_array($option['voptionid'], $existingCombination)) {
                     $sel = 'selected="selected"';
                 }
                 $optionList .= '<option value="' . $option['voptionid'] . '" ' . $sel . '>' . isc_html_escape($option['vovalue']) . '</option>';
             }
             $GLOBALS['VariationOptions'] = $optionList;
             $GLOBALS['VariationName'] = isc_html_escape($name);
             $GLOBALS['VariationList'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderProductConfigurationVariation');
         }
         $GLOBALS['ProductVariationJavascript'] = $productClass->GetProductVariationCombinationJavascript();
     } else {
         $GLOBALS['HideVariationList'] = 'display: none';
     }
     $fields = $productClass->GetProductFields($_REQUEST['productId']);
     $GLOBALS['ProductFields'] = '';
     if (!empty($fields)) {
         foreach ($fields as $field) {
             $GLOBALS['FieldId'] = $field['id'];
             $GLOBALS['FieldRequired'] = '&nbsp;';
             $requiredClass = '';
             $GLOBALS['FieldName'] = isc_html_escape($field['name']) . ':';
             $GLOBALS['HideFieldHelp'] = 'display: none';
             $GLOBALS['FieldHelp'] = '';
             $GLOBALS['HideFileCurrentValue'] = 'display: none';
             $existingValue = '';
             if (isset($existingProduct['product_fields'][$field['id']])) {
                 if ($field['type'] == 'file') {
                     $existingValue = isc_html_escape($existingProduct['product_fields'][$field['id']]['fileOriginName']);
                     $existingFileName = $existingProduct['product_fields'][$field['id']]['fileName'];
                 } else {
                     $existingValue = isc_html_escape($existingProduct['product_fields'][$field['id']]['fieldValue']);
                 }
             }
             if ($field['required'] == 1) {
                 $requiredClass = 'FieldRequired';
                 $GLOBALS['FieldRequired'] = '*';
             }
             switch ($field['type']) {
                 case 'textarea':
                     $inputField = '<textarea cols="30" rows="3" name="productFields[' . $field['id'] . ']" class="Field300 ' . $requiredClass . '">' . $existingValue . '</textarea>';
                     break;
                 case 'file':
                     if ($existingValue) {
                         $requiredClass .= 'HasExistingValue';
                     }
                     $inputField = '<input type="file" name="productFields[' . $field['id'] . ']" class="Field300 ' . $requiredClass . '" />';
                     $help = array();
                     if ($field['fileSize'] > 0) {
                         $help[] = GetLang('MaximumSize') . ': ' . NiceSize($field['fileSize'] * 1024);
                     }
                     if ($field['fileType'] != '') {
                         $help[] = GetLang('AllowedTypes') . ': ' . '<span class="FileTypes">' . isc_strtoupper(isc_html_escape($field['fileType']) . '</span>');
                     }
                     $help = implode('. ', $help);
                     if ($help != '') {
                         $GLOBALS['HideFieldHelp'] = '';
                         $GLOBALS['FieldHelp'] = '<em>(' . $help . ')</em>';
                     }
                     if ($existingValue) {
                         $GLOBALS['HideFileCurrentValue'] = '';
                         if (!$field['required']) {
                             $GLOBALS['HideRemoveFile'] = 'display: none';
                         }
                         $GLOBALS['CurrentFileName'] = $existingValue;
                         if (isset($existingProduct['product_fields'][$field['id']]['fieldExisting'])) {
                             $fileDirectory = 'configured_products';
                         } else {
                             $fileDirectory = 'configured_products_tmp';
                         }
                         $GLOBALS['CurrentFileLink'] = GetConfig('ShopPath') . '/' . GetConfig('ImageDirectory') . '/' . $fileDirectory . '/' . $existingFileName;
                     }
                     break;
                 case 'checkbox':
                     $checked = '';
                     if ($existingValue) {
                         $checked = 'checked="checked"';
                     }
                     $inputField = '<label><input type="checkbox" name="productFields[' . $field['id'] . ']" ' . $checked . ' value="1" /> ' . GetLang('TickToSelect') . '</label>';
                     break;
                 default:
                     $inputField = '<input type="text" name="productFields[' . $field['id'] . ']" class="Field300 ' . $requiredClass . '" value="' . $existingValue . '"/>';
             }
             $GLOBALS['InputField'] = $inputField;
             $GLOBALS['ProductFields'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderProductConfigurationField');
         }
     } else {
         $GLOBALS['HideConfigurableFields'] = 'display: none';
     }
     if ($productClass->GetEventDateRequired() == 1) {
         $this->LoadEventDate($productClass, $existingProduct);
     } else {
         $GLOBALS['EventDate'] = '';
         $GLOBALS['HideEventDate'] = 'display : none;';
     }
     echo $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrderProductConfiguration');
     exit;
 }
Example #2
0
		private function generateCustomizeItemForm(array $item)
		{
			$defaultItem = array(
				'name' => '',
				'quantity' => 1,
				'price' => '',
				'productId' => '',
				'variationOptions' => array(),
				'variationId' => 0,
				'configuration' => '',
				'wrapping' => '',
				'itemId' => '',
				'quoteSession' => '',
				'eventDate' => array(),
				'eventName' => '',
				'sku' => '',
			);
			$item = array_merge($defaultItem, $item);
			$this->template->assign('item', $item);

			if($item['productId']) {
				$productClass = new ISC_PRODUCT($item['productId']);
				if(!$productClass->getProductId()) {
					$this->sendEditOrderResponse(array(
						'errors' => array(
							getLang('InvalidProduct')
						)
					));
				}

				$this->template->assign('product', $productClass->getProduct());

				$this->template->assign('variationOptions', $productClass->GetProductVariationOptions());
				$this->template->assign('variationValues', $productClass->GetProductVariationOptionValues());

				$configurableFields = $productClass->GetProductFields($item['productId']);
				foreach($configurableFields as &$field) {
					if($field['type'] == 'select') {
						$options = explode(',', $field['selectOptions']);
						$field['selectOptions'] = array_map('trim', $options);
					}
				}
				$this->template->assign('configurableFields', $configurableFields);

				// Event date
				if($productClass->getEventDateRequired()) {
					$eventDateFromStamp = $productClass->getEventDateLimitedStartDate();
					$eventDateToStamp = $productClass->getEventDateLimitedEndDate();

					$eventDate = array(
						'fromStamp' => $eventDateFromStamp,
						'toStamp' => $eventDateToStamp,
						'yearFrom' => isc_date('Y', $eventDateFromStamp),
						'yearTo' => isc_date('Y', $eventDateToStamp)
					);

					// Generate a list of month options
					$eventDate['monthOptions'] = array();
					for($i = 1; $i <= 12; ++$i) {
						$stamp = isc_gmmktime(0, 0, 0, $i, 1, 2000);
						$month = isc_date("M", $stamp);
						$eventDate['monthOptions'][$i] = $month;
					}

					$eventDateLimit = $productClass->getEventDateLimited();
					if(empty($eventDateLimit)) {
						$eventDate['yearFrom'] = isc_date('Y');
						$eventDate['yearTo'] = $eventDate['yearFrom'] + 5;
					}
					else {
						$eventDate['limitationType'] = $productClass->getEventDateLimitedType();
						if($eventDate['limitationType'] == 1) {
							$eventDate['compDate'] = isc_date('Y/m/d', $eventDateFromStamp);
							$eventDate['compDateEnd'] = isc_date('Y/m/d', $eventDateToStamp);
						}
						else if($eventDate['limitationType'] == 2) {
							$eventDate['yearTo'] = $eventDate['yearFrom'] + 5;
							$eventDate['compDate'] = isc_date('Y/m/d', $eventDateFromStamp);
						}
						else if($eventDate['limitationType'] == 3) {
							$eventDate['yearFrom'] = isc_date('Y');
							$eventDate['compDate'] = isc_date('Y/m/d', $eventDateToStamp);
						}
					}

					$this->template->assign('eventDate', $eventDate);
				}
			}

			if(!empty($item['quoteItem'])) {
				$allowableWrappingOptions = $item['quoteItem']->getGiftWrappingOptions();
			}

			// Product still exists - get the gift wrapping options on the product
			if(isset($productClass)) {
				$product = $productClass->getProduct();
				$allowableWrappingOptions = explode(',', $product['prodwrapoptions']);
			}

			if(!empty($allowableWrappingOptions)) {
				if(empty($allowableWrappingOptions) || in_array(0, $allowableWrappingOptions)) {
					$giftWrapWhere = "wrapvisible='1'";
				}
				else {
					$wrappingOptions = implode(',', array_map('intval', $allowableWrappingOptions));
					$giftWrapWhere = "wrapid IN (".$wrappingOptions.")";
				}
				$query = "
					SELECT *
					FROM [|PREFIX|]gift_wrapping
					WHERE ".$giftWrapWhere."
					ORDER BY wrapname ASC
				";
				$giftWrappingOptions = array();
				$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
				while($wrap = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
					$giftWrappingOptions[$wrap['wrapid']] = $wrap;
				}

				$this->template->assign('giftWrappingOptions', $giftWrappingOptions);
			}

			return array(
				'data' => $this->template->render('order.form.customizeitem.tpl'),
				'width' => 600,
				'height' => 500,
			);
		}
Example #3
0
 public static function getProductPQVQ($productId = 0, $year = 0, $make = '', $model = '')
 {
     if (isset($_REQUEST['productId'])) {
         $productId = (int) $_REQUEST['productId'];
     }
     if (empty($make) && isset($_REQUEST['make']) && !empty($_REQUEST['make'])) {
         $make = $_REQUEST['make'];
     }
     if (empty($model) && isset($_REQUEST['model']) && !empty($_REQUEST['model'])) {
         $model = $_REQUEST['model'];
     }
     if (!$year && isset($_REQUEST['year']) && !empty($_REQUEST['year'])) {
         $year = (int) $_REQUEST['year'];
     }
     if ($productId) {
         $where = array();
         if ($make) {
             $where[] = sprintf("UPPER(prodmake)='%s'", strtoupper($make));
         }
         if ($model) {
             $where[] = sprintf("UPPER(prodmodel)='%s'", strtoupper($model));
         }
         if ($year) {
             $where[] = sprintf("(prodstartyear <= %d AND prodendyear >= %d)", $year, $year);
         }
         if (count($where) > 2) {
             return ISC_PRODUCT::GetProductPQVQHtml($productId, !empty($where) ? ' AND ' . implode(' AND ', $where) : '');
         }
     }
 }
Example #4
0
		public function SetPanelSettings()
		{
			if (!$GLOBALS["ISC_CLASS_SEARCH"]->searchIsLoaded()) {
				return;
			}

			// Do we have any categories
			$GLOBALS["SearchResultsCategory"] = "";

			if ($GLOBALS["ISC_CLASS_SEARCH"]->GetNumResults("category") > 0) {
				$GLOBALS["SearchResultsCategory"] = ISC_CATEGORY::buildSearchResultsHTML();
			}

			if (trim($GLOBALS["SearchResultsCategory"]) !== "") {
				$GLOBALS["HideSearchResultsCategory"] = "";
			} else {
				$GLOBALS["HideSearchResultsCategory"] = "none";
			}

			// Do we have any brands
			$GLOBALS["SearchResultsBrand"] = "";

			if ($GLOBALS["ISC_CLASS_SEARCH"]->GetNumResults("brand") > 0) {
				$GLOBALS["SearchResultsBrand"] = ISC_BRANDS::buildSearchResultsHTML();
			}

			if (trim($GLOBALS["SearchResultsBrand"]) !== "") {
				$GLOBALS["HideSearchResultsBrand"] = "";
			} else {
				$GLOBALS["HideSearchResultsBrand"] = "none";
			}

			// Now for the products
			$GLOBALS["SearchResultsProduct"] = "";
			$productSearchResults = "";

			if ($GLOBALS["ISC_CLASS_SEARCH"]->GetNumResults("product") > 0) {
				$productSearchResults = ISC_PRODUCT::buildSearchResultsHTML();
			}

			if (GetConfig("SearchProductDisplayMode") == "list") {
				$displayMode = "List";
			} else {
				$displayMode = "Grid";
			}

			if (trim($productSearchResults) !== "") {
				$GLOBALS["SectionResults"] = $productSearchResults;
				$GLOBALS["SectionType"] = "ProductList";
				$GLOBALS["SectionExtraClass"] = "";
				$GLOBALS["HideAddButton"] = "none";
				$GLOBALS["CompareButton"] = "";
				$GLOBALS["CompareButtonTop"] = "";

				$totalPages = $GLOBALS['ISC_CLASS_SEARCH']->GetNumPages("product");
				$totalRecords = $GLOBALS['ISC_CLASS_SEARCH']->GetNumResults("product");

				$page = (int)@$_REQUEST['page'];
				if ($page < 1) {
					$page = 1;
				} else if ($page > $totalPages) {
					$page = $totalPages;
				}

				if (GetConfig("SearchProductDisplayMode") == "list") {
					$GLOBALS["SectionExtraClass"] = "List";
					$GLOBALS["HideAddButton"] = "";
					$GLOBALS["ListJS"] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ListCheckForm");
					$GLOBALS["CompareButton"] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CompareButton" . $displayMode);

					if ($totalPages > 1) {
						$GLOBALS["CompareButtonTop"] = $GLOBALS["CompareButton"];
					}
				} else {
					$GLOBALS["CompareButton"] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CompareButton");
				}

				// generate url with all current GET params except page, ajax and section
				$url = array();
				foreach ($_GET as $key => $value) {
					if ($key == 'page' || $key == 'ajax' || $key == 'section') {
						continue;
					}
					if (is_array($value)) {
						foreach ($value as $subvalue) {
							$url[] = urlencode($key . '[]') . '=' . urlencode($subvalue);
						}
					} else {
						$url[] = urlencode($key) . '=' . urlencode($value);
					}
				}
				$url[] = "page={page}";
				$url[] = "section=product";
				$url = 'search.php?' . implode('&', $url) . '#results';

				$GLOBALS['SectionPaging'] = '';

				$maxPagingLinks = 5;
				if($GLOBALS['ISC_CLASS_TEMPLATE']->getIsMobileDevice()) {
					$maxPagingLinks = 3;
				}

				$start = max($page - $maxPagingLinks, 1);
				$end = min($page + $maxPagingLinks, $totalPages);

				for ($i = $start; $i <= $end; $i++) {
					if($i == $page) {
						$snippet = "CategoryPagingItemCurrent";
					}
					else {
						$snippet = "CategoryPagingItem";
					}

					$GLOBALS['PageLink'] = str_replace('{page}', $i, $url);
					$GLOBALS['PageNumber'] = $i;
					$GLOBALS['SectionPaging'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet($snippet);
				}

				// Parse the paging snippet
				if($page > 1) {
					$prevPage = $page - 1;
					$GLOBALS['PrevLink'] = str_replace('{page}', $prevPage, $url);
					$GLOBALS['SectionPagingPrevious'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryPagingPrevious");
				}

				if($page < $totalPages) {
					$prevPage = $page + 1;
					$GLOBALS['NextLink'] = str_replace('{page}', $prevPage, $url);
					$GLOBALS['SectionPagingNext'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryPagingNext");
				}

				if ($totalPages > 1) {
					$GLOBALS["HideSectionPaging"] = "";
				} else {
					$GLOBALS["HideSectionPaging"] = "none";
				}

				if ($GLOBALS["ISC_CLASS_SEARCH"]->GetNumResults("product") <= 1) {
					$GLOBALS["HideSectionSorting"] = "none";
				} else {
					$GLOBALS["HideSectionSorting"] = "";
				}

				$GLOBALS["SectionSortingOptions"] = getAdvanceSearchSortOptions("product");
				$GLOBALS["SectionSearchResults"] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("SearchResultGrid");
				$GLOBALS["SearchResultsProduct"] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("SearchResultSectionProduct");
				$GLOBALS["HideSearchResultsProduct"] = "none";

				if(!getProductReviewsEnabled()) {
					$GLOBALS["HideProductRating"] = "display: none";
				}

			} else {
				$GLOBALS["HideSearchResultsProduct"] = "";
			}

			// If no results then show the 'no results found' div
			if (trim($GLOBALS["SearchResultsBrand"]) == "" && trim($GLOBALS["SearchResultsCategory"]) == "" && trim($GLOBALS["SearchResultsProduct"]) == "") {
				$GLOBALS["HideSearchResultsCategoryAndBrand"] = "none";
				$GLOBALS["HideSearchResultsProduct"] = "none";
				$GLOBALS["HideSearchResultsNoResult"] = "";

			// Else if we just have no categories or brands then do not show the top containing div
			} else if (trim($GLOBALS["SearchResultsBrand"]) == "" && trim($GLOBALS["SearchResultsCategory"]) == "") {
				$GLOBALS["HideSearchResultsCategoryAndBrand"] = "none";
				$GLOBALS["HideSearchResultsProduct"] = "";
				$GLOBALS["HideSearchResultsNoResult"] = "none";

			// Else if we have categories or brands BUT no products then display the 'no results found' div
			} else if ((trim($GLOBALS["SearchResultsBrand"]) == "" || trim($GLOBALS["SearchResultsCategory"]) !== "") && trim($GLOBALS["SearchResultsProduct"]) == "") {
				$GLOBALS["HideSearchResultsCategoryAndBrand"] = "";
				$GLOBALS["HideSearchResultsProduct"] = "none";
				$GLOBALS["HideSearchResultsNoResult"] = "";
			} else {
				$GLOBALS["HideSearchResultsCategoryAndBrand"] = "";
				$GLOBALS["HideSearchResultsProduct"] = "";
				$GLOBALS["HideSearchResultsNoResult"] = "none";
			}

			/*
			 * if the "Enable Product Search Feeds?" is ticked in Store
			 * Settings -> Display and we are searching add the link
			 */
			if (isset($GLOBALS['ISC_CLASS_SEARCH']) && GetConfig('RSSProductSearches')) {
				$GLOBALS['RSSURL'] = SearchLink($GLOBALS['ISC_CLASS_SEARCH']->GetQuery(), 0, false);
				$GLOBALS['SnippetSearchResultsFeed'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('SearchResultsFeed');
			}
		}
Example #5
0
 function getYMMOptions($params, $ymm_type)
 {
     switch ($ymm_type) {
         case 'year':
             $options = "<option value=''>--select year--</option>";
             $filter_array = array();
             //$ymm_qry = "select group_concat(v.prodstartyear separator '~') as prodstartyear , group_concat(v.prodendyear separator '~') as prodendyear from [|PREFIX|]products p LEFT JOIN [|PREFIX|]import_variations AS v ON v.productid = p.productid where p.prodvisible='1' ";
             $ymm_qry = " select min(v.prodstartyear) as prodstartyear , max(v.prodendyear)  as prodendyear from isc_products p LEFT JOIN isc_import_variations AS v ON v.productid = p.productid where p.prodvisible='1' and v.prodstartyear is not null and v.prodstartyear !='' and v.prodstartyear !='all'  and v.prodendyear is not null and v.prodendyear !='' and v.prodendyear !='all'  ";
             if (isset($params['make']) && $GLOBALS['UniversalCat'] == 0) {
                 $ymm_qry .= " and prodmake = '" . $params['make'] . "' ";
             }
             if (isset($params['model']) && (!isset($params['model_flag']) || $params['model_flag'] == 1) && $GLOBALS['UniversalCat'] == 0) {
                 $ymm_qry .= " and prodmodel = '" . $params['model'] . "' ";
             }
             //$ymm_qry .= " group by p.productid ";
             $ymm_res = $GLOBALS['ISC_CLASS_DB']->Query($ymm_qry);
             if ($ymm_row = $GLOBALS['ISC_CLASS_DB']->Fetch($ymm_res)) {
                 if (empty($ymm_row["prodstartyear"]) || !isnumeric($ymm_row["prodstartyear"])) {
                     $startyear = 1950;
                 }
                 if (empty($ymm_row["prodendyear"]) || !isnumeric($ymm_row["prodendyear"])) {
                     $endyear = date('Y');
                 }
                 $startyear = $ymm_row["prodstartyear"];
                 $endyear = $ymm_row["prodendyear"];
                 //2011-1-20 Ronnie add,year range 1900~2050
                 $YMMMinYear = 1900;
                 $YMMMaxYear = 2050;
                 if ($startyear < $YMMMinYear) {
                     $startyear = $YMMMinYear;
                 }
                 if ($startyear > $YMMMaxYear) {
                     $startyear = $YMMMaxYear;
                 }
                 if ($endyear < $YMMMinYear) {
                     $endyear = $YMMMinYear;
                 }
                 if ($endyear > $YMMMaxYear) {
                     $endyear = $YMMMaxYear;
                 }
                 //$endyear=$YMMMaxYear;
                 for ($i = $startyear; $i <= $endyear; $i++) {
                     if (!in_array($i, $filter_array)) {
                         $filter_array[] = $i;
                     }
                 }
                 /*$grp_startyear = explode("~",$ymm_row['prodstartyear']);
                 					$grp_endyear = explode("~",$ymm_row['prodendyear']);
                 					for($g=0;$g<count($grp_startyear);$g++)
                 					{
                 						$prod_start_year = $grp_startyear[$g];
                 						$prod_end_year = $grp_endyear[$g];
                 
                 						if(is_numeric($prod_start_year) && is_numeric($prod_end_year))
                 						{
                 							$prod_year_diff = $prod_end_year - $prod_start_year;
                 							for($i=0;$i<=$prod_year_diff;$i++)
                 							{
                 								$actual_year = $prod_start_year + $i;
                 								if(in_array($actual_year,$filter_array)) {
                 									$count_filter_array[$actual_year]++;
                 								}  else {
                 									$filter_array[] = $actual_year;
                 									$count_filter_array[$actual_year] = 1;
                 								}
                 							}
                 						}
                 					}*/
             }
             rsort($filter_array);
             foreach ($filter_array as $key => $value) {
                 $selected = "";
                 if (isset($params['year']) && strcasecmp($params['year'], $value) == 0) {
                     $selected = " selected";
                 }
                 if (!empty($this->productImpVariations) && !ISC_PRODUCT::CheckYMMUseVariation($value, $this->productImpVariations, 'year')) {
                     continue;
                 }
                 $options .= "<option value='" . MakeURLSafe(strtolower($value)) . "'{$selected}>{$value}</option>";
             }
             break;
         case 'make':
             $filter_array = array();
             $GLOBALS['ISC_YMMS'] = GetClass('ISC_YMMS');
             $result = $GLOBALS['ISC_YMMS']->getResultArray("make", "", "", "");
             $options = "<option value=''>--select make--</option>";
             //$ymm_qry = "select group_concat(DISTINCT v.prodmake separator '~') as prodmake from [|PREFIX|]products p LEFT JOIN [|PREFIX|]import_variations AS v ON v.productid = p.productid where p.prodvisible='1' ";
             //$ymm_qry = "select DISTINCT v.prodmake  as prodmake from [|PREFIX|]products p LEFT JOIN [|PREFIX|]import_variations AS v ON v.productid = p.productid where p.prodvisible='1' ";
             //$ymm_res = $GLOBALS['ISC_CLASS_DB']->Query($ymm_qry);
             //while($ymm_row = $GLOBALS['ISC_CLASS_DB']->Fetch($ymm_res))
             //{
             /*$filters = explode('~',$ymm_row['prodmake']);
             		for($j=0;$j<count($filters);$j++) 
             	    {
             			$filter_value = $filters[$j]; 
             			if(strtoupper($filter_value) != "NON-SPEC VEHICLE" && strtolower($filter_value) != "all" && $filter_value != "")
             			{
             				if(in_array($filter_value,$filter_array))   {
             					$count_filter_array[$filter_value]++;
             				} else {
             					$filter_array[] = $filter_value;
             					$count_filter_array[$filter_value] = 1;
             				}
             			}
             	    }*/
             //if(strtoupper($ymm_row['prodmake']) != "NON-SPEC VEHICLE" && strtolower($ymm_row['prodmake']) != "all" && $ymm_row['prodmake'] != "")
             //{
             //	$filter_array[] = $ymm_row['prodmake'];
             //}
             //}
             foreach ($result as $key => $value) {
                 if (strtoupper($value) != "NON-SPEC VEHICLE" && strtolower($value) != "all" && $value != "") {
                     $filter_array[] = $value;
                 }
             }
             sort($filter_array);
             $all_makes = array('CHEVROLET', 'GMC', 'FORD', 'DODGE', 'TOYOTA', 'NISSAN', 'HONDA', 'JEEP', 'HYUNDAI', 'CHRYSLER', 'INFINITI', 'LEXUS');
             //$temp_arr =  array_diff($filter_array,$all_makes);	// commented as client told to include the above makes in other list also
             $temp_arr = $filter_array;
             //alandy_2011-10-13 modify.
             array_unique($temp_arr);
             if (!$GLOBALS['ProductIds']) {
                 foreach ($all_makes as $key => $value) {
                     $selected = "";
                     if (!empty($this->productImpVariations) && !ISC_PRODUCT::CheckYMMUseVariation($value, $this->productImpVariations, 'make')) {
                         continue;
                     }
                     if (isset($params['make']) && strcasecmp($params['make'], $value) == 0) {
                         $selected = " selected";
                     }
                     $options .= "<option value='" . MakeURLSafe(strtolower($value)) . "'{$selected}>{$value}</option>";
                 }
                 $options .= "<option value=''>------------</option>";
             }
             foreach ($temp_arr as $key => $value) {
                 $selected = "";
                 if (!empty($this->productImpVariations) && !ISC_PRODUCT::CheckYMMUseVariation($value, $this->productImpVariations, 'make')) {
                     continue;
                 }
                 if (isset($params['make']) && strcasecmp($params['make'], $value) == 0) {
                     $selected = " selected";
                 }
                 $options .= "<option value='" . MakeURLSafe(strtolower($value)) . "'{$selected}>{$value}</option>";
             }
             break;
         case 'model':
             $options = "<option value=''>--select model--</option>";
             if (isset($params['make'])) {
                 $filter_array = array();
                 $ymm_qry = "select distinct prodmodel from [|PREFIX|]products p LEFT JOIN [|PREFIX|]import_variations AS v ON v.productid = p.productid where p.prodvisible='1' ";
                 if (isset($params['make'])) {
                     $ymm_qry .= " and prodmake = '" . $params['make'] . "' ";
                 }
                 if (isset($params['year']) && $GLOBALS['UniversalCat'] == 0) {
                     $ymm_qry .= " and " . $params['year'] . " between prodstartyear and prodendyear ";
                 }
                 //$ymm_qry .= " group by p.productid ";
                 $ymm_res = $GLOBALS['ISC_CLASS_DB']->Query($ymm_qry);
                 while ($ymm_row = $GLOBALS['ISC_CLASS_DB']->Fetch($ymm_res)) {
                     if (!empty($ymm_row['prodmodel']) && $ymm_row['prodmodel'] != '~') {
                         $filters = explode('~', $ymm_row['prodmodel']);
                         for ($j = 0; $j < count($filters); $j++) {
                             $filter_value = ucwords(strtolower($filters[$j]));
                             if (strtolower($filter_value) != "all") {
                                 if (in_array($filter_value, $filter_array)) {
                                 } else {
                                     $filter_array[] = $filter_value;
                                 }
                             }
                         }
                     }
                 }
                 sort($filter_array);
                 foreach ($filter_array as $key => $value) {
                     $selected = "";
                     if (isset($params['model']) && strcasecmp($params['model'], $value) == 0) {
                         $selected = " selected";
                     }
                     if (!empty($this->productImpVariations) && !ISC_PRODUCT::CheckYMMUseVariation($value, $this->productImpVariations, 'model')) {
                         continue;
                     }
                     $options .= "<option value='" . MakeURLSafe(strtolower($value)) . "'{$selected}>{$value}</option>";
                 }
             }
             break;
     }
     return $options;
 }
Example #6
0
 public function GetYmmsForDialogPage()
 {
     $ymmtype = strtolower(MakeURLNormal(isset($_GET['ymmtype']) ? $_GET['ymmtype'] : ""));
     $year = strtolower(MakeURLNormal(isset($_GET['year']) ? $_GET['year'] : ""));
     $make = strtolower(MakeURLNormal(isset($_GET['make']) ? $_GET['make'] : ""));
     $model = strtolower(MakeURLNormal(isset($_GET['model']) ? $_GET['model'] : ""));
     $productId = isset($_GET['productId']) ? (int) $_GET['productId'] : 0;
     $isDialogPQVQ = isset($_GET['isDialogPQVQ']) ? (int) $_GET['isDialogPQVQ'] : 0;
     $output = "";
     $array_str = $impvaritions = array();
     if ($productId) {
         $impvaritions = ISC_PRODUCT::GetImpVariationForYMM($productId, $ymmtype, '', '', '');
     }
     foreach (array('make', 'model', 'year') as $column) {
         $tmp = '';
         $array_str[$column] = "<option value=''>--select {$column}--</option>";
         $ymms_array = $this->getResultArray($column, $year, $make, $model, $productId);
         if ($column == 'model' and empty($ymms_array)) {
             $ymms_array = $this->getResultArray($column, "", $make, $model, $productId);
         }
         switch ($column) {
             case 'year':
                 $tmp = $year;
                 break;
             case 'make':
                 $tmp = $make;
                 break;
             default:
                 $tmp = $model;
                 break;
         }
         foreach ($ymms_array as $value) {
             $selected = "";
             if ($tmp == strtolower($value)) {
                 $selected = "selected";
             }
             if (empty($impvaritions) && !ISC_PRODUCT::CheckYMMUseVariation($value, $impvaritions, $column)) {
                 continue;
             }
             $array_str[$column] .= "<option value='" . strtoupper($value) . "' {$selected}>{$value}</option>";
         }
         //alandy_2012-2-20 add redirct option.
         if ($isDialogPQVQ == 1) {
             $array_str[$column] .= "<option value=1>My " . ucwords($column) . " Not Showing Here</option>";
         }
     }
     if ($ymmtype == "make") {
         $output = $array_str['model'] . '~' . $array_str['year'];
     } elseif ($ymmtype == "year") {
         $output = $array_str['make'] . '~' . $array_str['model'];
     } elseif ($ymmtype == "model") {
         $output = $array_str['year'];
     } else {
     }
     return $output;
 }
Example #7
0
		/**
		*
		* @param int The customer group to use to determine the final product price (used when getting variation details from back end quote system)
		*/
		public function GetVariationOptions($customerGroupId = null)
		{
			$productId = (int)$_GET['productId'];
			$optionIds = $_GET['options'];
			$optionIdsArray = array_map('intval', explode(',', $optionIds));

			// We need to find the next type of option that's selectable, so what we do
			// is because the vcoptionids column is in the order that the customer selects
			// the options, we just find a single matching option and then look up values
			// according to the voname.

			$query = "
				SELECT prodvariationid, vnumoptions
				FROM [|PREFIX|]products p
				JOIN [|PREFIX|]product_variations v ON (v.variationid=p.prodvariationid)
				WHERE p.productid='".$productId."'
			";
			$result =$GLOBALS['ISC_CLASS_DB']->query($query);
			$product = $GLOBALS['ISC_CLASS_DB']->fetch($result);

			// Invalid product variation, or product doesn't have a variation
			if(empty($product)) {
				exit;
			}

			// If we received the number of options the variation has in, then the customer
			// has selected an entire row. Find that row.
			if(count($optionIdsArray) == $product['vnumoptions']) {
				$setMatches = array();
				foreach($optionIdsArray as $optionId) {
					$setMatches[] = 'FIND_IN_SET('.$optionId.', vcoptionids)';
				}
				$query = "
					SELECT *
					FROM [|PREFIX|]product_variation_combinations
					WHERE
						vcproductid='".$productId."' AND
						vcenabled=1 AND
						".implode(' AND ', $setMatches)."
					LIMIT 1
				";
				$result = $GLOBALS['ISC_CLASS_DB']->query($query);
				$combination = $GLOBALS['ISC_CLASS_DB']->fetch($result);

				$productClass = new ISC_PRODUCT($productId);
				$combinationDetails = $productClass->getCombinationDetails($combination, $customerGroupId);
				$combinationDetails['comboFound'] = true;

				if ($combinationDetails['sku'] == null) {
					// prevent a blank sku on details page
					$combinationDetails['sku'] = '';
				}

				echo isc_json_encode($combinationDetails);
				exit;
			}

			// Try to find a combination row with the incoming option ID string, to determine
			// which set of options is next.
			$query = "
				SELECT DISTINCT voname
				FROM [|PREFIX|]product_variation_options
				WHERE
					vovariationid='".$product['prodvariationid']."'
				ORDER BY vooptionsort ASC
				LIMIT ".count($optionIdsArray).", 1
			";
			$optionName = $GLOBALS['ISC_CLASS_DB']->fetchOne($query);

			$hasOptions = false;
			$valueHTML = '';

			$setMatches = array();
			foreach($optionIdsArray as $optionId) {
				$setMatches[] = 'FIND_IN_SET('.$optionId.', vcoptionids)';
			}

			$query = "
				SELECT *
				FROM [|PREFIX|]product_variation_options
				WHERE
					vovariationid='".$product['prodvariationid']."' AND
					voname='".$GLOBALS['ISC_CLASS_DB']->quote($optionName)."'
				ORDER BY vovaluesort ASC
			";
			$result = $GLOBALS['ISC_CLASS_DB']->query($query);
			while($option = $GLOBALS['ISC_CLASS_DB']->fetch($result)) {
				$query = "
					SELECT combinationid
					FROM [|PREFIX|]product_variation_combinations
					WHERE
						vcproductid='".$productId."' AND
						vcenabled=1 AND
						FIND_IN_SET(".$option['voptionid'].", vcoptionids) > 0 AND
						".implode(' AND ', $setMatches)."
					LIMIT 1
				";
				// Ok, this variation option isn't in use for this product at the moment. Skip it
				if(!$GLOBALS['ISC_CLASS_DB']->fetchOne($query)) {
					continue;
				}

				$option = new Xhtml_Option($option['vovalue'], (int)$option['voptionid']);
				$valueHTML .= $option->render();
				$hasOptions = true;
			}

			$return = array(
				'hasOptions' 	=> $hasOptions,
				'options'		=> $valueHTML
			);

			echo isc_json_encode($return);
			exit;
		}
	/**
	* Ebay: Sent to a seller when a buyer completes the checkout process for an item. Not sent when an auction ends without bids.
	*
	* My notes: Seems to be triggered when the buyer's payment process for an AUCTION item has completed, is not fired for fixed price items which fire 'FixedPrice...' notifications instead
	*
	* @param array $body
	*/
	protected function _handleAuctionCheckoutComplete($body)
	{
		// The data fields in the notification are the same as those returned by the GetItemTransactions call with the default detail level.
		if (!empty ($body['Item']['ItemID']) && ISC_ADMIN_EBAY::validEbayItemId($body['Item']['ItemID'])) {
			// variables init
			$order = array();
			$orderId = 1;
			$order['ShippingInsuranceCost'] = 0;
			$completedPaymentHoldStatus = array('None', 'Released');
			$orderStatus = ORDER_STATUS_AWAITING_PAYMENT;
			$existingOrderId = 0;

			// Determine if the buyer purchase multiple items from the same seller
			if (!empty($body['TransactionArray']['Transaction']['ContainingOrder'])) {
			 // Call the operation to get the order transaction.
				$orderId = $body['TransactionArray']['Transaction']['ContainingOrder']['OrderID'];

				// if the record already exist, check if we need to update existing orders, that the payment hasn't been cleared previously.
				$existingOrder = GetOrderByEbayOrderId($orderId);
				$orderTransaction = ISC_ADMIN_EBAY_OPERATIONS::getOrderTransactions($orderId);
				$transactions = $orderTransaction->OrderArray->Order->TransactionArray->Transaction;

				$order['SubTotal'] = (string) $orderTransaction->OrderArray->Order->Subtotal;
				$order['ShippingCost'] = (string) $orderTransaction->OrderArray->Order->ShippingServiceSelected->ShippingServiceCost;
				$order['ShippingInsuranceCost'] = 0;
				$order['GrandTotal'] = (string) $orderTransaction->OrderArray->Order->Total;
				$order['TotalQuantityPurchased'] = 0;
				foreach ($transactions as $transaction) {
					$convertedTransaction = (array) $transaction;
					$variationOptionsString = '';
					if (isset($convertedTransaction['Variation']->VariationSpecifics)) {
						$variationNameValueList = (array) $convertedTransaction['Variation']->VariationSpecifics->NameValueList;
						$variationOptions = array();
						$variationSpecifics = (array) $convertedTransaction['Variation']->VariationSpecifics;
						if (is_array($variationSpecifics['NameValueList'])) {
							foreach ($variationSpecifics['NameValueList'] as $option) {
								$variationOptions[(string) $option->Name] = (string) $option->Value;
							}
						} else {
							$variationOptions[(string) $variationSpecifics['NameValueList']->Name] = (string) $variationSpecifics['NameValueList']->Value;
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$quantityPurchased = $convertedTransaction['QuantityPurchased'];
					$transactionPrice = $convertedTransaction['TransactionPrice'];
					$itemId = (string) $convertedTransaction['Item']->ItemID;
					$transactionId = (string) $convertedTransaction['TransactionID'];
					$totalTransactionPrice = $transactionPrice * $quantityPurchased;
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $transactionPrice,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['TotalQuantityPurchased'] += $quantityPurchased;
					$order['Currency'] = GetCurrencyByCode($body['TransactionArray']['Transaction']['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $body['TransactionArray']['Transaction']['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $body['TransactionArray']['Transaction']['Buyer']['Email'];
				}

				if ($existingOrder) {
					$existingOrderId = $existingOrder['orderid'];
				}
			}
			else {
				$transactions = $body['TransactionArray'];
				foreach ($transactions as $transaction) {
					$itemId = $body['Item']['ItemID'];
					$transactionId = $transaction['TransactionID'];
					$query = "
						SELECT *
						FROM [|PREFIX|]order_products
						WHERE ebay_item_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($itemId)."'
							AND ebay_transaction_id = '".$GLOBALS["ISC_CLASS_DB"]->Quote($transactionId)."'
						LIMIT 1
					";
					$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
					$row = $GLOBALS['ISC_CLASS_DB']->Fetch($res);
					$eachItemPriceExTax = $transaction['TransactionPrice']['!'];
					$quantityPurchased = $transaction['QuantityPurchased'];
					$totalTransactionPrice = $quantityPurchased * $eachItemPriceExTax;
					$variationOptionsString = '';

					// do we have a variation for this product?
					if (isset($transaction['Variation']['VariationSpecifics'])) {
						$variationNameValueList = $transaction['Variation']['VariationSpecifics']['NameValueList'];
						$variationOptions = array();
						foreach ($variationNameValueList as $option) {
							$variationOptions[$option['Name']] = $option['Value'];
						}
						$variationOptionsString = serialize($variationOptions);
					}
					$order['TotalQuantityPurchased'] = $quantityPurchased;
					$order['SubTotal'] = $eachItemPriceExTax * $order['TotalQuantityPurchased'];
					$order['ShippingCost'] = $transaction['ShippingServiceSelected']['ShippingServiceCost']['!'];
					if (isset ($transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'])) {
						$order['ShippingInsuranceCost'] = $transaction['ShippingServiceSelected']['ShippingInsuranceCost']['!'];
					}
					$order['GrandTotal'] = $transaction['AmountPaid']['!'];
					$order['Transaction'][] = array(
						'QuantityPurchased' => $quantityPurchased,
						'TransactionPrice' => $eachItemPriceExTax,
						'ItemId' => $itemId,
						'TotalTransactionPrice' => $totalTransactionPrice,
						'VariationOptionsString' => $variationOptionsString,
						'TransactionId' => $transactionId,
					);
					$order['Currency'] = GetCurrencyByCode($transaction['AmountPaid']['!currencyID']);
					$buyerInfoShippingAddress = $transaction['Buyer']['BuyerInfo']['ShippingAddress'];
					$buyerEmailAddress = $transaction['Buyer']['Email'];

					if (!$row) {
						// only process the new transaction
						break;
					} else {
						$existingOrderId = $row['orderorderid'];
					}
				}
			}

			$paymentHoldStatus = $body['TransactionArray']['Transaction']['Status']['PaymentHoldStatus'];
			if (in_array(trim($paymentHoldStatus), $completedPaymentHoldStatus)) {
				$orderStatus = ORDER_STATUS_AWAITING_FULFILLMENT;
			}
			if ($existingOrderId != 0) {
				if (!isset ($existingOrder)) {
					$existingOrder = GetOrder($existingOrderId, false, true, true);
				}

				// check if there're any existing order need to be updated.
				// in the case, paypal release the hold payment of buyer
				if ($existingOrder['ordstatus'] == ORDER_STATUS_AWAITING_PAYMENT
				&& $orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the quantity for each transaction
					$GLOBALS["ISC_CLASS_DB"]->StartTransaction();
					foreach ($order['Transaction'] as $eachTransaction) {
						// Get product Id
						try {
							$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
							$productId = $itemObj->getProductId();
						} catch (Exception $e) {
							$this->log->LogSystemDebug('ebay', $e->getMessage());
							return false;
						}

						// update the item quantity in store
						$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
						if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
							$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
						if (!UpdateOrderStatus($existingOrderId, $orderStatus, true, true)) {
							$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
							return false;
						}
					}
					$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

					// update the store inventory if necessary
					if (GetConfig('UpdateInventoryLevels') == 1) {
						DecreaseInventoryFromOrder($existingOrderId);
					}
					$this->log->LogSystemDebug('ebay', 'The status of the store order ('. $existingOrderId .') has been updated to: Awaiting Fulfillment');
				}
				return true;
			}

			$order['ShippingTotalCost'] = $order['ShippingInsuranceCost'] + $order['ShippingCost'];

			// Buyer's address information
			$addressMap = array(
				'Name',
				'CompanyName',
				'Street1',
				'Street2',
				'CityName',
				'PostalCode',
				'Country',
				'CountryName',
				'Phone',
				'StateOrProvince',
			);

			// Initialize the value, make sure it's not empty
			foreach ($addressMap as $key) {
				if (!isset($buyerInfoShippingAddress[$key])) {
					$buyerInfoShippingAddress[$key] = '';
				}
			}
			$buyerCountryId = GetCountryIdByISO2($buyerInfoShippingAddress['Country']);
			$buyerStateId = GetStateByName($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
			$buyerStateName = $buyerInfoShippingAddress['StateOrProvince'];
			if (!$buyerStateId) {
				$buyerStateId = GetStateByAbbrev($buyerInfoShippingAddress['StateOrProvince'], $buyerCountryId);
				$stateInfo = GetStateInfoById($buyerStateId);
				$buyerStateName = $stateInfo['statename'];
			}

			// Tokenize buyer's first and last name
			$nameTokens = explode(' ', $buyerInfoShippingAddress['Name']);
			$buyerFirstName = $nameTokens[0];
			$buyerLastName = '';
			if (!empty($nameTokens[1])) {
				$buyerLastName = $nameTokens[1];
			}

			$orderToken = generateOrderToken();

			// Preparing data to be inserted to orders table
			$newOrder = array(
				'ordtoken' => $orderToken,
				'orderpaymentmodule' => '',
				'orderpaymentmethod' => '',
				'orderpaymentmodule' => '',
				'extraInfo' => serialize(array()),
				'orddefaultcurrencyid' => $order['Currency']['currencyid'],
				'orddate' => time(),
				'ordlastmodified' => time(),
				'ordcurrencyid' => $order['Currency']['currencyid'],
				'ordcurrencyexchangerate' => 1,
				'ordipaddress' => GetIP(),
				'ordcustmessage' => '',
				'ordstatus' => $orderStatus,
				'base_shipping_cost' => $order['ShippingTotalCost'],
				'base_handling_cost' => 0,
				'ordbillemail' => $buyerEmailAddress,
				'ordbillfirstname' => $buyerFirstName,
				'ordbilllastname' => $buyerLastName,
				'ordbillcompany' => $buyerInfoShippingAddress['CompanyName'],
				'ordbillstreet1' => $buyerInfoShippingAddress['Street1'],
				'ordbillstreet2' => $buyerInfoShippingAddress['Street2'],
				'ordbillsuburb' => $buyerInfoShippingAddress['CityName'],
				'ordbillzip' => $buyerInfoShippingAddress['PostalCode'],
				'ordbillcountrycode' => $buyerInfoShippingAddress['Country'],
				'ordbillphone' => $buyerInfoShippingAddress['Phone'],
				'ordbillstateid' => (int) $buyerStateId,
				'ordbillstate' => $buyerStateName,
				'ordbillcountry' => $buyerInfoShippingAddress['CountryName'],
				'ordbillcountryid' => (int) $buyerCountryId,
				'total_ex_tax' => $order['GrandTotal'],
				'total_inc_tax' => $order['GrandTotal'],
				'shipping_cost_ex_tax' => $order['ShippingTotalCost'],
				'shipping_cost_inc_tax' => $order['ShippingTotalCost'],
				'subtotal_inc_tax' => $order['SubTotal'],
				'subtotal_ex_tax' => $order['SubTotal'],
				'ebay_order_id' => $orderId,
			);
			ResetStartingOrderNumber();

			// Start the transaction
			$GLOBALS["ISC_CLASS_DB"]->StartTransaction();

			// Inserting order data
			$newOrderId = $GLOBALS["ISC_CLASS_DB"]->InsertQuery('orders', $newOrder);
			if (!$newOrderId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			$orderAddress = array(
				'first_name' => $buyerFirstName,
				'last_name' => $buyerLastName,
				'company' => $buyerInfoShippingAddress['CompanyName'],
				'address_1' => $buyerInfoShippingAddress['Street1'],
				'address_2' => $buyerInfoShippingAddress['Street2'],
				'city' => $buyerInfoShippingAddress['CityName'],
				'zip' => $buyerInfoShippingAddress['PostalCode'],
				'country_iso2' => $buyerInfoShippingAddress['Country'],
				'phone' => $buyerInfoShippingAddress['Phone'],
				'total_items' => $order['TotalQuantityPurchased'],
				'email' => $buyerEmailAddress,
				'country_id' => (int) $buyerCountryId,
				'country' => $buyerInfoShippingAddress['CountryName'],
				'state_id' => (int) $buyerStateId,
				'state' => $buyerStateName,
				'order_id' => $newOrderId,
			);

			$addressId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_addresses', $orderAddress);
			if (!$addressId) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Inserting order shipping
			$orderShipping = array(
				'order_address_id' => $addressId,
				'order_id' => $newOrderId,
				'base_cost' => $order['ShippingTotalCost'],
				'cost_inc_tax' => $order['ShippingTotalCost'],
				'cost_ex_tax' => $order['ShippingTotalCost'],
				'method' => 'Available on eBay',
			);

			if (!$GLOBALS['ISC_CLASS_DB']->insertQuery('order_shipping', $orderShipping)) {
				$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
				$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
				return false;
			}

			// Go thru each sold item in the order
			foreach ($order['Transaction'] as $eachTransaction) {
				// Get product Id
				try {
					$itemObj = new ISC_ADMIN_EBAY_ITEMS($eachTransaction['ItemId']);
					$productId = $itemObj->getProductId();
				} catch (Exception $e) {
					$this->log->LogSystemDebug('ebay', $e->getMessage());
					return false;
				}

				// Inserting order product
				$productObj = new ISC_PRODUCT($productId);
				$newProduct = array(
					'orderorderid' => $newOrderId,
					'ordprodid' => $productId,
					'ordprodsku' => $productObj->GetSKU(),
					'ordprodname' => $productObj->GetProductName(),
					'ordprodtype' => $productObj->GetProductType(),
					'ordprodqty' => $eachTransaction['QuantityPurchased'],
					'base_price' => $eachTransaction['TransactionPrice'],
					'price_ex_tax' => $eachTransaction['TransactionPrice'],
					'price_inc_tax' => $eachTransaction['TransactionPrice'],
					'price_tax' => 0,
					'base_total' => $eachTransaction['TotalTransactionPrice'],
					'total_ex_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_inc_tax' => $eachTransaction['TotalTransactionPrice'],
					'total_tax' => 0,
					'base_cost_price' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_inc_tax' => 0,
					'cost_price_tax' => 0,
					'ordprodweight' => $productObj->GetWeight(false),
					'ordprodoptions' => $eachTransaction['VariationOptionsString'],
					'ordprodvariationid' => $productObj->_prodvariationid,
					'ordprodwrapid' => 0,
					'ordprodwrapname' => '',
					'base_wrapping_cost' => 0,
					'wrapping_cost_ex_tax' => 0,
					'wrapping_cost_inc_tax' => 0,
					'wrapping_cost_tax' => 0,
					'ordprodwrapmessage' => '',
					'ordprodeventname' => '',
					'ordprodeventdate' => 0,
					'ordprodfixedshippingcost' => $productObj->GetFixedShippingCost(),
					'order_address_id' => $addressId,
					'ebay_item_id' => $eachTransaction['ItemId'],
					'ebay_transaction_id' => $eachTransaction['TransactionId'],
				);

				$orderProductId = $GLOBALS['ISC_CLASS_DB']->insertQuery('order_products', $newProduct);
				if (!$orderProductId) {
					$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
					$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
					return false;
				}

				if ($orderStatus == ORDER_STATUS_AWAITING_FULFILLMENT) {
					// update the item quantity in store
					$updatedData['quantity_remaining'] = $itemObj->getQuantityRemaining() - $eachTransaction['QuantityPurchased'];
					if (!$GLOBALS['ISC_CLASS_DB']->UpdateQuery('ebay_items', $updatedData, "ebay_item_id='" . $eachTransaction['ItemId'] . "'")) {
						$this->log->LogSystemDebug('ebay', $GLOBALS["ISC_CLASS_DB"]->Error());
						$GLOBALS["ISC_CLASS_DB"]->RollbackTransaction();
						return false;
					}
				}
			}
			$GLOBALS["ISC_CLASS_DB"]->CommitTransaction();

			// update the store inventory if necessary
			if (GetConfig('UpdateInventoryLevels') == 1) {
				DecreaseInventoryFromOrder($newOrderId);
			}

			// Trigger new order notifications
			SendOrderNotifications($orderToken);

			$this->log->LogSystemDebug('ebay', 'An Item ('. $body['Item']['ItemID'] .') has been paid by the buyer and added to the store order (' . $newOrderId. ').');
			return true;
		}
		return false;
	}
Example #9
0
		/**
		* Shows a page of results when requested by an ajax query
		*
		*/
		public function ShowAjaxSearchPage()
		{
			$section = isc_strtolower(trim(@$_REQUEST["section"]));
			if (!$section) {
				exit;
			}

			$GLOBALS["ISC_CLASS_SEARCH"] = GetClass("ISC_SEARCH");

			$searchTerms = $GLOBALS["ISC_CLASS_SEARCH"]->readSearchSession();

			$sortBy = trim(@$_REQUEST["sortBy"]);

			$page = (int)@$_REQUEST['page'];
			if ($page < 1) {
				$page = 1;
			}

			// Do the search
			$limit = (int)GetConfig("SearchResultsPerPage");

			$start = ($page - 1) * $limit;

			// We have all the details, now we need to load up the ISC_SEARCH class
			$GLOBALS["ISC_CLASS_SEARCH"]->_SetSearchData($searchTerms);
			$GLOBALS["ISC_CLASS_SEARCH"]->DoSearch($start, $limit, $section, $sortBy);

			$GLOBALS["SectionResults"] = "";

			if ($section == "content") {
				$searchResults = $GLOBALS["ISC_CLASS_SEARCH"]->GetResults("content");

				if (is_array($searchResults["results"]) && !empty($searchResults["results"])) {
					foreach ($searchResults["results"] as $item) {
						if ($item["nodetype"] == "page") {
							$GLOBALS["SectionResults"] .= ISC_PAGE::buildContentSearchResultHTML($item);
						} else {
							$GLOBALS["SectionResults"] .= ISC_NEWS::buildContentSearchResultHTML($item);
						}
					}
				}
			} else if ($section == "product") {
				$GLOBALS["SectionResults"] = ISC_PRODUCT::buildSearchResultsHTML();
			} else {
				exit;
			}

			$totalPages = $GLOBALS['ISC_CLASS_SEARCH']->GetNumPages($section);
			$totalRecords = $GLOBALS['ISC_CLASS_SEARCH']->GetNumResults($section);

			if (GetConfig("SearchProductDisplayMode") == "list") {
				$GLOBALS["SectionExtraClass"] = 'List';
			} else {
				$GLOBALS["SectionExtraClass"] = '';
			}

			$GLOBALS["SectionType"] = ucfirst($section) . 'List';

			$navTitle = GetLang("SearchResultsTab" . ucfirst($section));

			// generate url with all current GET params except page and ajax
			$url = array();
			foreach ($_GET as $key => $value) {
				if ($key == 'page' || $key == 'ajax') {
					continue;
				}
				if (is_array($value)) {
					foreach ($value as $subvalue) {
						$url[] = urlencode($key . '[]') . '=' . urlencode($subvalue);
					}
				} else {
					$url[] = urlencode($key) . '=' . urlencode($value);
				}
			}
			$url[] = "page={page}";
			$url = 'search.php?' . implode('&', $url) . '#results';

			$GLOBALS['SectionPaging'] = '';

			$maxPagingLinks = 5;
			if($GLOBALS['ISC_CLASS_TEMPLATE']->getIsMobileDevice()) {
				$maxPagingLinks = 3;
			}

			$start = max($page - $maxPagingLinks, 1);
			$end = min($page + $maxPagingLinks, $totalPages);

			for ($i = $start; $i <= $end; $i++) {
				if($i == $page) {
					$snippet = "CategoryPagingItemCurrent";
				}
				else {
					$snippet = "CategoryPagingItem";
				}

				$GLOBALS['PageLink'] = str_replace('{page}', $i, $url);
				$GLOBALS['PageNumber'] = $i;
				$GLOBALS['SectionPaging'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet($snippet);
			}

			// Parse the paging snippet
			if($page > 1) {
				$prevPage = $page - 1;
				$GLOBALS['PrevLink'] = str_replace('{page}', $prevPage, $url);
				$GLOBALS['SectionPagingPrevious'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryPagingPrevious");
			}

			if($page < $totalPages) {
				$prevPage = $page + 1;
				$GLOBALS['NextLink'] = str_replace('{page}', $prevPage, $url);
				$GLOBALS['SectionPagingNext'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("CategoryPagingNext");
			}

			if ($totalPages > 1) {
				$GLOBALS["HideSectionPaging"] = "";
			} else {
				$GLOBALS["HideSectionPaging"] = "none";
			}

			$GLOBALS["SectionSortingOptions"] = getAdvanceSearchSortOptions($section, $sortBy);
			print $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("SearchResultGrid");
			exit;
		}