Example #1
0
function IsCustomerServiceTime()
{
    $customerServiceTime = GetCustomerServiceTime();
    //GMT to EST
    $timezoneAdjustment = GetConfig('StoreTimeZone');
    if (GetConfig('StoreDSTCorrection')) {
        ++$timezoneAdjustment;
    }
    $timezoneAdjustment *= 3600;
    $currentTime = time() + $timezoneAdjustment;
    $now = array('week' => date('w', $currentTime), 'hour' => date('G', $currentTime), 'min' => date('i', $currentTime));
    $nowtime = $now['hour'] * 60 + $now['min'];
    $nowdate = ConvertDateToTime(date('m/d/Y', $currentTime));
    if ($now['week'] > 0 && $now['week'] < 6) {
        if ($nowtime > $customerServiceTime['weekday']['from'] && $nowtime < $customerServiceTime['weekday']['to']) {
            return true;
        }
    }
    if ($now['week'] == 6) {
        if ($nowtime > $customerServiceTime['saturday']['from'] && $nowtime < $customerServiceTime['saturday']['to']) {
            return true;
        }
    }
    if ($now['week'] == 0) {
        if ($nowtime > $customerServiceTime['sunday']['from'] && $nowtime < $customerServiceTime['sunday']['to']) {
            return true;
        }
    }
}
 private function _CommitCoupon($CouponId = 0)
 {
     include_once ISC_BASE_PATH . '/lib/api/coupon.api.php';
     $coupon = new API_COUPON();
     $_POST['couponappliesto'] = $_POST['usedfor'];
     if ($_POST['couponappliesto'] == "categories") {
         // Applies to categories
         $_POST['couponappliestovalues'] = implode(",", array_map('intval', $_POST['catids']));
     } else {
         // Applies to products
         $_POST['couponappliestovalues'] = implode(',', array_map('intval', explode(',', $_POST['prodids'])));
     }
     if (!empty($_POST['couponexpires'])) {
         $_POST['couponexpires'] = ConvertDateToTime($_POST['couponexpires']);
     } else {
         $_POST['couponexpires'] = 0;
     }
     if (!isset($_POST['couponcode']) || empty($_POST['couponcode'])) {
         $_POST['couponcode'] = GenerateCouponCode();
     }
     if (isset($_POST['couponenabled'])) {
         $_POST['couponenabled'] = 1;
     } else {
         $_POST['couponenabled'] = 0;
     }
     $_POST['couponminpurchase'] = str_replace(GetConfig('CurrencyToken'), "", $_POST['couponminpurchase']);
     if (isset($_POST['couponmaxuses'])) {
         $_POST['couponmaxuses'] = (int) $_POST['couponmaxuses'];
     } else {
         $_POST['couponmaxuses'] = 0;
     }
     if ($CouponId == 0) {
         $CouponId = $coupon->create();
     } else {
         $coupon->load($CouponId);
         $coupon->save();
     }
     if (!$coupon->error) {
         // Log this action
         $GLOBALS['ISC_CLASS_LOG']->LogAdminAction($CouponId, $_POST['couponcode']);
     }
     return $coupon->error;
 }
Example #3
0
		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;
		}
Example #4
0
	/**
	 * 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'];
	}
Example #5
0
 private function _GetCouponData($CouponId = 0, &$RefArray)
 {
     if ($CouponId == 0) {
         $RefArray['couponid'] = 0;
         $RefArray['coupontype'] = $_POST['coupontype'];
         $RefArray['couponamount'] = (int) $_POST['couponamount'];
         $RefArray['couponminpurchase'] = CFloat($_POST['couponminpurchase']);
         $RefArray['couponmaxuses'] = (int) $_POST['couponmaxuses'];
         if ($_POST['couponexpires'] != "") {
             $RefArray['couponexpires'] = ConvertDateToTime($_POST['couponexpires']);
         } else {
             $RefArray['couponexpires'] = 0;
         }
         if (isset($_POST['couponenabled'])) {
             $RefArray['couponenabled'] = 1;
         } else {
             $RefArray['couponenabled'] = 0;
         }
         if (isset($_POST['couponcode']) && $_POST['couponcode'] != "") {
             $RefArray['couponcode'] = $_POST['couponcode'];
         } else {
             $RefArray['couponcode'] = GenerateCouponCode();
         }
     } else {
         // Get the data for this coupon code from the database
         $query = sprintf("select * from [|PREFIX|]coupons where couponid='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($CouponId));
         $result = $GLOBALS["ISC_CLASS_DB"]->Query($query);
         if ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($result)) {
             $RefArray = $row;
         }
     }
 }
 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'] = ConvertDateToTime($_POST['discountruleexpiresdateamount']);
     }
     $_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;
 }
Example #7
0
		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;
		}
Example #8
0
 function __construct()
 {
     // First up, which page are we on?
     $GLOBALS['Banners'] = array();
     $banners = array();
     $page = "";
     $page_type = "";
     if (isset($GLOBALS['ISC_CLASS_INDEX'])) {
         $page_type = 'home_page';
     } else {
         if (isset($GLOBALS['ISC_CLASS_SEARCH']) || isset($GLOBALS['ISC_CLASS_NEWSEARCH'])) {
             $page_type = 'search_page';
         } else {
             if (isset($GLOBALS['ISC_CLASS_BRANDS'])) {
                 $page_type = 'brand_page';
             } else {
                 if (isset($GLOBALS['ISC_CLASS_CATEGORY'])) {
                     $page_type = 'category_page';
                 } else {
                     $page_type = 'other';
                 }
             }
         }
     }
     // Save the page type globally so we can access it from the template engine
     $GLOBALS['PageType'] = $page_type;
     if ($page_type != "") {
         $stamp = time();
         $query = sprintf("select * from [|PREFIX|]banners\n\t\t\t\t\t\t  where page IN ('%s', 'entire_site')\n\t\t\t\t\t\t\tand status='1'\n\t\t\t\t\t\t\tand (\n\t\t\t\t\t\t\t\t(datetype='always' and datefrom = 0 and dateto = 0)\n\t\t\t\t\t\t\t\tor (datetype='custom' and datefrom < %s and dateto > %s)\n\t\t\t\t\t\t\t\tor (datetype='weekly' and (locate(lower(dayname(curdate())), displayweekly)>0))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t  order by bannerid", $GLOBALS['ISC_CLASS_DB']->Quote($page_type), $GLOBALS['ISC_CLASS_DB']->Quote($stamp), $GLOBALS['ISC_CLASS_DB']->Quote($stamp));
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         $customerServiceTime = $this->GetCustomerServiceTime();
         //GMT to EST
         $timezoneAdjustment = GetConfig('StoreTimeZone');
         if (GetConfig('StoreDSTCorrection')) {
             ++$timezoneAdjustment;
         }
         $timezoneAdjustment *= 3600;
         $currentTime = time() + $timezoneAdjustment;
         $now = array('week' => date('w', $currentTime), 'hour' => date('G', $currentTime), 'min' => date('i', $currentTime));
         $nowtime = $now['hour'] * 60 + $now['min'];
         $nowdate = ConvertDateToTime(date('m/d/Y', $currentTime));
         while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
             if ($row['showtime'] == 'entireday') {
                 array_push($banners, $row);
             } else {
                 foreach ($customerServiceTime['holiday'] as $holiday) {
                     if ($nowtime > $holiday['from'] && $nowtime < $holiday['to']) {
                         if ($holiday['specialdate'] == $nowdate) {
                             array_push($banners, $row);
                             break;
                         }
                     }
                 }
                 if (empty($banners)) {
                     if ($now['week'] > 0 && $now['week'] < 6) {
                         if ($nowtime > $customerServiceTime['weekday']['from'] && $nowtime < $customerServiceTime['weekday']['to']) {
                             array_push($banners, $row);
                         }
                     }
                     if ($now['week'] == 6) {
                         if ($nowtime > $customerServiceTime['saturday']['from'] && $nowtime < $customerServiceTime['saturday']['to']) {
                             array_push($banners, $row);
                         }
                     }
                     if ($now['week'] == 0) {
                         if ($nowtime > $customerServiceTime['sunday']['from'] && $nowtime < $customerServiceTime['sunday']['to']) {
                             array_push($banners, $row);
                         }
                     }
                 }
             }
         }
         if ($GLOBALS['ISC_CLASS_DB']->CountResult($result) > 0) {
             foreach ($banners as $banner) {
                 if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
                     $banner['content'] = str_replace($GLOBALS['ShopPathNormal'], $GLOBALS['ShopPathSSL'], $banner['content']);
                 }
                 // Wrap the banner in a div which can be styled
                 $banner['content'] = sprintf("%s<div class='Block BlockContent banner_%s_%s'>%s</div>", $banner['controlscript'], $banner['page'], $banner['location'], $banner['content']);
                 switch ($page_type) {
                     case "other":
                     case "home_page":
                     case "search_page":
                         if ($banner['location'] == "top" && !isset($GLOBALS['Banners']['top'])) {
                             $GLOBALS['Banners']['top'] = $banner;
                         } else {
                             if ($banner['location'] == "bottom" && !isset($GLOBALS['Banners']['bottom'])) {
                                 $GLOBALS['Banners']['bottom'] = $banner;
                             }
                         }
                         break;
                     case "brand_page":
                     case "category_page":
                         if ($banner['location'] == "top" && !isset($GLOBALS['Banners'][$banner['catorbrandid']]['top'])) {
                             $GLOBALS['Banners'][$banner['catorbrandid']]['top'] = $banner;
                         } else {
                             if ($banner['location'] == "bottom" && !isset($GLOBALS['Banners'][$banner['catorbrandid']]['bottom'])) {
                                 $GLOBALS['Banners'][$banner['catorbrandid']]['bottom'] = $banner;
                             }
                         }
                         break;
                 }
             }
         }
     }
 }