Example #1
0
	public function execute($transitions)
	{
		$current = current(array_keys($transitions));

		do
		{
			$next = $transitions[$current];
			if(is_array($next)) {
				$found = false;
				foreach($next as $transition) {
					if(is_array($transition)) {
						if($this->actor->{$transition['on']}() === true) {
							$next = $transition['next'];
							$found = true;
							break;
						}
					}
					else
					{
						$next = $transition;
						$found = true;
						break;
					}
				}
				if(!$found)
					throw new Exception('No valid next state: '.isc_json_encode($current));
			}

			if($next !== null)
				$this->actor->{$next}();
			$current = $next;
		}
		while($next !== null);
	}
Example #2
0
	private function removeFromGroup()
	{
		$group = $this->getValue('group');

		$controllers = (array)json_decode($this->keystore->get('jc_'.$group));
		unset($controllers[$this->getId()]);

		$this->keystore->set('jc_'.$group,isc_json_encode($controllers));
		$this->clearValue('group');
	}
Example #3
0
	public static function output($message, $success=false, $additionalArray=null)
	{
		// @codeCoverageIgnoreStart
		// if this is ever changed so that die() is optiona, remove the ignore tags - otherwise this method should never be called during a unit test since it makes phpunit quit

		if (is_array($message)) {
			$jsonArray = $message;
		} else {
			if(is_array($additionalArray) && !empty($additionalArray)) {
				$jsonArray = $additionalArray;
			}else{
				$jsonArray = array();
			}

			$jsonArray['success'] = (bool)$success;
			$jsonArray['message'] = $message;
		}

		$charset = GetConfig('CharacterSet');
		if (!$charset) {
			$charset = 'utf-8';
		}

		if(self::$useTextarea) {
			header('Content-type: text/html; charset=' . $charset);
			echo '<textarea>';
		} else {
			header('Content-type: application/json; charset=' . $charset);
		}

		echo isc_json_encode($jsonArray);

		if(self::$useTextarea) {
			echo '</textarea>';
		}

		die();
		// @codeCoverageIgnoreEnd
	}
Example #4
0
	public function remoteDeleteMultiple(ISC_ADMIN_REMOTE $remote)
	{
		$db = $GLOBALS["ISC_CLASS_DB"];

		$productId = false;
		$productHash = false;

		if (isset($_POST['product'])) {
			$productId = (int)@$_POST['product'];
			if (!isId($productId) || !ProductExists($productId)) {
				$response['error'] = GetLang('ProductDoesntExist');
				die(isc_json_encode($response));
			}
			if (!$GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Products)) {
				$response['error'] = GetLang('Unauthorized');
				die(isc_json_encode($response));
			}
		} else if (isset($_POST['hash']) && $_POST['hash']) {
			$productHash = $_POST['hash'];
			if (!$GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Create_Product)) {
				$response['error'] = GetLang('Unauthorized');
				die(isc_json_encode($response));
			}
		} else {
			$response['error'] = GetLang('ProductDoesntExist');
			die(isc_json_encode($response));
		}

		$deletes = array();
		$errors = array();
		$warnings = array();
		$newThumbnailId = null;

		if (!isset($_POST['images']) || !is_array($_POST['images'])) {
			$response['error'] = GetLang('InvalidProductImageId');
			die(isc_json_encode($response));
		}

		$_POST['images'] = array_unique(@$_POST['images']);

		foreach ($_POST['images'] as $imageId) {
			if (!(int)$imageId) {
				$errors[$imageId] = GetLang('InvalidProductImageId');
				continue;
			}

			$imageId = (int)$imageId;

			try {
				$image = new ISC_PRODUCT_IMAGE($imageId);
			} catch (ISC_PRODUCT_IMAGE_RECORDNOTFOUND_EXCEPTION $exception) {
				// record was not found in database, so it's already been deleted, mark it as deleted and skip it
				$deletes[] = $imageId;
				continue;
			} catch (Exception $exception) {
				// some other error occurred when trying to load the image, note it in errors list
				$errors[$imageId] = GetLang('ProductImageDeleteDatabaseError');
				continue;
			}

			if ($productId) {
				if ($image->getProductId() !== $productId) {
					// image does not belong to specified product id, note it in errors list
					$errors[$imageId] = GetLang('ProductImageDeleteInvalidProductId');
					continue;
				}
			} else if ($productHash) {
				if ($image->getProductId() !== 0 || $image->getProductHash() !== $productHash) {
					// image does not belong to specified product id, note it in errors list
					$errors[$imageId] = GetLang('ProductImageDeleteInvalidProductId');
					continue;
				}
			}

			try {
				$image->delete(true, true, $newThumbnailId);
				$deletes[] = $imageId;
			} catch (ISC_PRODUCT_IMAGE_CANNOTDELETEFILE_EXCEPTION $exception) {
				// indicates that the record was deleted but files weren't
				$deletes[] = $imageId;
				$warnings[$imageId] = GetLang('ProductImageDeleteFileDeleteError');
			} catch (Exception $exception) {
				// any other error indicates a failure to delete the record
				$errors[$imageId] = GetLang('ProductImageDeleteUnknownError');
			}
		}

		$tags = array();

		foreach ($errors as $imageId => $message) {
			$tags[] = $remote->MakeXMLTag('error', $message, true, array('image' => $imageId));
		}

		foreach ($warnings as $imageId => $message) {
			$tags[] = $remote->MakeXMLTag('warning', $message, true, array('image' => $imageId));
		}

		foreach ($deletes as $imageId) {
			$tags[] = $remote->MakeXMLTag('delete', false, false, array('image' => $imageId));
		}

		if ($newThumbnailId) {
			$tags[] = $remote->MakeXMLTag('thumbnail', false, false, array('image' => $newThumbnailId));
		}

		$remote->SendXMLHeader();
		$remote->SendXMLResponse($tags);
		die();
	}
Example #5
0
		private function ManageCustomers($MsgDesc = "", $MsgStatus = "")
		{
			$GLOBALS['HideClearResults'] = "none";

			$numCustomers = 0;

			// Fetch any results, place them in the data grid
			$GLOBALS['CustomerDataGrid'] = $this->ManageCustomersGrid($numCustomers);

			// Was this an ajax based sort? Return the table now
			if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 1) {
				echo $GLOBALS['CustomerDataGrid'];
				return;
			}

			if (isset($this->_customSearch['searchname'])) {
				$GLOBALS['ViewName'] = isc_html_escape($this->_customSearch['searchname']);
			}
			else {
				$GLOBALS['ViewName'] = GetLang('AllCustomers');
				$GLOBALS['HideDeleteViewLink'] = "none";
			}

			if (isset($this->_customSearch['searchname'])) {
				$GLOBALS['CustomSearchName'] = ": ".isc_html_escape($this->_customSearch['searchname']);
			}

			// Get the custom search as option fields
			$num_custom_searches = 0;
			$GLOBALS['CustomSearchOptions'] = $GLOBALS['ISC_CLASS_ADMIN_CUSTOMSEARCH']->GetSearchesAsOptions(@$_GET['searchId'], $num_custom_searches, "AllCustomers", "viewCustomers", "customCustomerSearch");

			if (!isset($_REQUEST['searchId'])) {
				$GLOBALS['HideDeleteCustomSearch'] = "none";
			}
			else {
				$GLOBALS['CustomSearchId'] = (int)$_REQUEST['searchId'];
			}

			// Do we need to disable the add button?
			if (!$GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Add_Customer)) {
				$GLOBALS['DisableAdd'] = "DISABLED";
			}

			// Do we need to disable the delete button?
			if (!$GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Delete_Customers) || $numCustomers == 0) {
				$GLOBALS['DisableDelete'] = "DISABLED";
			}

			// Do we need to disable the expory button?
			if (!$GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Export_Customers) || $numCustomers == 0) {
				$GLOBALS['DisableExport'] = "DISABLED";
			}

			if (isset($_REQUEST['searchQuery']) || isset($_GET['searchId'])) {
				$GLOBALS['HideClearResults'] = "";
			}

			$GLOBALS['CustomerIntro'] = GetLang('ManageCustomersIntro');

			if ($numCustomers > 0) {
				if ($MsgDesc == "" && (isset($_REQUEST['searchQuery']) || isset($_GET['searchId']))) {
					if ($numCustomers == 1) {
						$MsgDesc = GetLang('CustomerSearchResultsBelow1');
					}
					else {
						$MsgDesc = sprintf(GetLang('CustomerSearchResultsBelowX'), $numCustomers);
					}

					$MsgStatus = MSG_SUCCESS;
				}
			}
			else {
				$GLOBALS['DisplayGrid'] = "none";
				if (count($_GET) > 1) {
					if ($MsgDesc == "") {
						$GLOBALS['Message'] = MessageBox(GetLang('NoCustomerResults'), MSG_ERROR);
					}
				}
				else {
					// No actual custoemrs
					$GLOBALS['DisplaySearch'] = "none";
					$GLOBALS['Message'] = MessageBox(GetLang('NoCustomers'), MSG_SUCCESS);
				}
			}

			if (!gzte11(ISC_MEDIUMPRINT)) {
				$GLOBALS[base64_decode('SGlkZUV4cG9ydA==')] = "none";
			}

			if ($MsgDesc != "") {
				$GLOBALS['Message'] = MessageBox($MsgDesc, $MsgStatus);
			}

			$flashMessages = GetFlashMessages();
			if(is_array($flashMessages) && !empty($flashMessages)) {
				$GLOBALS['Message'] = '';
				foreach($flashMessages as $flashMessage) {
					$GLOBALS['Message'] .= MessageBox($flashMessage['message'], $flashMessage['type']);
				}
			}

			if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Export_Customers)) {
				$exportAction = "index.php?ToDo=startExport&t=customers";
				if (isset($GLOBALS['CustomSearchId']) && $GLOBALS['CustomSearchId'] != '0') {
					$exportAction .= "&searchId=" . $GLOBALS['CustomSearchId'];
				}
				else {
					$params = $_GET;
					unset($params['ToDo']);

					if (!empty($params)) {
						$exportAction .= "&" . http_build_query($params);
					}
				}

				$searchQueryForExport = $_POST + $_GET;
				foreach ($searchQueryForExport as $index => $value) {
					if ($value === '') {
						unset($searchQueryForExport[$index]);
					}
				}
				unset($searchQueryForExport['ToDo'], $searchQueryForExport['SubmitButton1'], $searchQueryForExport['sortField'], $searchQueryForExport['sortOrder'], $searchQueryForExport['SearchButton_x'], $searchQueryForExport['SearchButton_y']);
				$searchQueryForExport = isc_json_encode($searchQueryForExport);

				$customerExportMenu = array();

				$customerExportMenu[] = array(
					array(
						'backgroundImage' => 'images/export.gif',
						'label' => GetLang('EmailIntegrationExportToFile'),
						'class' => 'exportMenuLink',
						'href' => $exportAction,
					),
				);

				$customerExportMenuModules = array();

				$emailModules = ISC_EMAILINTEGRATION::getConfiguredModules();
				foreach ($emailModules as /** @var ISC_EMAILINTEGRATION */$emailModule) {
					if (!$emailModule->supportsBulkExport()) {
						// not all modules have to support bulk exports
						continue;
					}

					$customerExportMenuModules[] = array(
						'backgroundImage' => '../modules/' . str_replace('_', '/', $emailModule->GetId()) . '/images/16x16.png',
						'label' => GetLang('EmailIntegrationExportToModule', array('module' => $emailModule->GetName())),
						'href' => 'javascript:Interspire_EmailIntegration_ModuleExportMachine.start({ exportType: "Customer", exportModule: "' . $emailModule->GetId() . '", exportSearch: ' . $searchQueryForExport . ' });',
					);
				}

				if (!empty($customerExportMenuModules)) {
					$customerExportMenu[] = $customerExportMenuModules;

					$this->engine->bodyScripts[] = '../javascript/fsm.js';
					$this->engine->bodyScripts[] = '../javascript/jquery/plugins/disabled/jquery.disabled.js';
					$this->engine->bodyScripts[] = '../javascript/ajaxDataProvider.js';
					$this->engine->bodyScripts[] = 'script/emailintegration.js';
					$this->engine->bodyScripts[] = 'script/emailintegration.export.js';

					// disabled for now until batch rule processing is implemented, as the existing, single-subscription rule processing is too slow for bulk export

	//				$customerExportMenu[] = array(
	//					array(
	//						'backgroundImage' => 'images/export_to_rules.gif',
	//						'label' => GetLang('EmailIntegrationExportToNewsletterRules'),
	//						'href' => 'javascript:Interspire_EmailIntegration_RuleExportMachine.start({ exportType: "Customer", exportRule: "NewsletterSubscribed", exportSearch: ' . $searchQueryForExport . ' });',
	//					),
	//				);
				}

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

			$this->template->display('customers.manage.tpl');
		}
Example #6
0
 /**
  * Set up all of the template variables and predefined values for showing the form to edit an
  * existing order or create a new order. Will also set up the post variables as values if this
  * is a post request.
  *
  * @param array Optionally, if editing an order, the existing order to use for the default values.
  */
 private function SetupOrderManagementForm($order = array())
 {
     $GLOBLS['CurrentTab'] = 0;
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {
         $postData = $_POST;
     } else {
         $postData = $order;
     }
     $orderFields = array('OrderBillFirstName' => 'ordbillfirstname', 'OrderBillLastName' => 'ordbilllastname', 'OrderBillCompany' => 'ordbillcompany', 'OrderBillPhone' => 'ordbillphone', 'OrderBillStreet1' => 'ordbillstreet1', 'OrderBillStreet2' => 'ordbillstreet2', 'OrderBillSuburb' => 'ordbillsuburb', 'OrderBillZip' => 'ordbillzip', 'OrderShipFirstName' => 'ordshipfirstname', 'OrderShipLastName' => 'ordshiplastname', 'OrderShipCompany' => 'ordshipcompany', 'OrderShipPhone' => 'ordshipphone', 'OrderShipStreet1' => 'ordshipstreet1', 'OrderShipStreet2' => 'ordshipstreet2', 'OrderShipSuburb' => 'ordshipsuburb', 'OrderShipZip' => 'ordshipzip', 'CustomerEmail' => 'custconemail', 'CustomerPassword' => 'custpassword', 'CustomerPassword2' => 'custpassword2', 'CustomerStoreCredit' => 'custstorecredit', 'CustomerGroup' => 'custgroupid', 'CustomerType' => 'customerType', 'OrderComments' => 'ordcustmessage', 'OrderNotes' => 'ordnotes', 'OrderId' => 'orderid', 'OrderTrackingNo' => 'ordtrackingno', 'AnonymousEmail' => 'anonymousemail', 'OrderBillEmail' => 'ordbillemail', 'OrderShipEmail' => 'ordshipemail');
     /* Added below condition for applying store credit permission - vikas */
     $loggeduser = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetUser();
     if ($loggeduser['userstorecreditperm'] == 0) {
         $GLOBALS['StoreCreditDisable'] = " disabled=\"\" ";
     }
     $GLOBALS['HideSelectedCustomer'] = 'display: none';
     $GLOBALS['HideCustomerSearch'] = '';
     $GLOBALS['HideAddressSelects'] = 'display: none';
     if (isset($postData['ordcustid']) && $postData['ordcustid'] > 0) {
         $GLOBALS['CurrentTab'] = 1;
         $GLOBALS['CustomerType'] = 'existing';
         $query = "\n\t\t\t\t\tSELECT *\n\t\t\t\t\tFROM [|PREFIX|]customers WHERE customerid='" . (int) $postData['ordcustid'] . "'\n\t\t\t\t";
         $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
         $existingCustomer = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
         if ($existingCustomer['customerid']) {
             $GLOBALS['HideSelectedCustomer'] = '';
             $GLOBALS['HideCustomerSearch'] = 'display: none';
             $GLOBALS['HideHistoryLink'] = 'display: none';
             $GLOBALS['CustomerId'] = $existingCustomer['customerid'];
             $GLOBALS['CustomerFirstName'] = isc_html_escape($existingCustomer['custconfirstname']);
             $GLOBALS['CustomerLastName'] = isc_html_escape($existingCustomer['custconlastname']);
             $GLOBALS['CustomerPhone'] = '';
             if ($existingCustomer['custconphone']) {
                 $GLOBALS['CustomerPhone'] = isc_html_escape($existingCustomer['custconphone']) . '<br />';
             }
             $GLOBALS['CustomerEmail'] = '';
             if ($existingCustomer['custconemail']) {
                 $GLOBALS['CustomerEmail'] = '<a href="mailto:' . isc_html_escape($existingCustomer['custconemail']) . '">' . isc_html_escape($existingCustomer['custconemail']) . '</a><br />';
             }
             $GLOBALS['CustomerCompany'] = '';
             if ($existingCustomer['custconcompany']) {
                 $GLOBALS['CustomerCompany'] = isc_html_escape($existingCustomer['custconcompany']) . '<br />';
             }
             // Grab the addresses
             $addresses = $this->LoadCustomerAddresses($existingCustomer['customerid']);
             $GLOBALS['AddressJson'] = 'OrderManager.LoadInAddresses(' . isc_json_encode($addresses) . ');';
             if (!empty($addresses)) {
                 $GLOBALS['HideAddressSelects'] = '';
                 $GLOBALS['DisableAddressSelects'] = 'disabled="disabled"';
             }
             $GLOBALS['SelectedCustomer'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrdersCustomerSearchResult');
         }
         //alandy_2011-6-23 add.
         /*
         if($postData['orderid']>0){
          $query = "
         	   SELECT ordbillemail,ordshipemail
         	   FROM [|PREFIX|]orders WHERE ordcustid='".(int)$postData['ordcustid']."' and orderid=".$postData['orderid']."
            ";
            $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
            while($rs=$GLOBALS['ISC_CLASS_DB']->Fetch($result)){
            	  if(!empty($rs['ordbillemail'])){
            	   $GLOBALS['GuestCustomerEmail']=$rs['ordbillemail'];
            	  }else{
            	  	$GLOBALS['GuestCustomerEmail']=$rs['ordshipemail'];
            	  }
            }
         }
         */
     } else {
         if (isset($postData['ordcustid']) && $postData['ordcustid'] == 0) {
             if (!isset($postData['customerType'])) {
                 $GLOBALS['CurrentTab'] = 2;
             } else {
                 if ($postData['customerType'] == 'anonymous') {
                     $GLOBALS['CurrentTab'] = 2;
                 } else {
                     $GLOBALS['CurrenTab'] = 1;
                 }
             }
         }
     }
     /**
      * Customer and order custom fields
      */
     $GLOBALS['OrderCustomFormFieldsAccountFormId'] = FORMFIELDS_FORM_ACCOUNT;
     $GLOBALS['OrderCustomFormFieldsBillingFormId'] = FORMFIELDS_FORM_BILLING;
     $GLOBALS['OrderCustomFormFieldsShippingFormId'] = FORMFIELDS_FORM_SHIPPING;
     $GLOBALS['CustomFieldsAccountLeftColumn'] = '';
     $GLOBALS['CustomFieldsAccountRightColumn'] = '';
     $GLOBALS['CustomFieldsBillingColumn'] = '';
     $GLOBALS['CustomFieldsShippingColumn'] = '';
     $formIdx = array(FORMFIELDS_FORM_ACCOUNT, FORMFIELDS_FORM_BILLING, FORMFIELDS_FORM_SHIPPING);
     $fieldMap = array('FirstName' => 'firstname', 'LastName' => 'lastname', 'Company' => 'company', 'Phone' => 'phone', 'AddressLine1' => 'street1', 'AddressLine2' => 'street2', 'City' => 'suburb', 'Zip' => 'zip', 'Country' => 'country', 'State' => 'state');
     /**
      * Now process the forms
      */
     foreach ($formIdx as $formId) {
         $formSessionId = 0;
         if ($formId == FORMFIELDS_FORM_ACCOUNT) {
             /**
              * We are only using the real custom fields for the account section, so check here
              */
             if (!gzte11(ISC_MEDIUMPRINT)) {
                 continue;
             }
             if (isset($existingCustomer['custformsessionid'])) {
                 $formSessionId = $existingCustomer['custformsessionid'];
             }
         } else {
             if (isset($postData['ordformsessionid'])) {
                 $formSessionId = $postData['ordformsessionid'];
             }
         }
         /**
          * This part here gets all the existing fields
          */
         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
             $fields = $GLOBALS['ISC_CLASS_FORM']->getFormFields($formId, true);
         } else {
             if (isId($formSessionId)) {
                 $fields = $GLOBALS['ISC_CLASS_FORM']->getFormFields($formId, false, $formSessionId);
             } else {
                 $fields = $GLOBALS['ISC_CLASS_FORM']->getFormFields($formId);
             }
         }
         /**
          * Get any selected country and state. This needs to be separate as we physically
          * print out each form field at a time so we need this information before hand
          */
         if ($formId !== FORMFIELDS_FORM_ACCOUNT) {
             $countryId = GetCountryIdByName(GetConfig('CompanyCountry'));
             $stateFieldId = 0;
             foreach (array_keys($fields) as $fieldId) {
                 if (isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'state') {
                     $stateFieldId = $fieldId;
                 } else {
                     if (isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'country') {
                         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                             $country = $fields[$fieldId]->getValue();
                         }
                         if ($formId == FORMFIELDS_FORM_BILLING) {
                             $country = @$order['ordbillcountry'];
                         } else {
                             $country = @$order['ordshipcountry'];
                         }
                         if (trim($country) !== '') {
                             $countryId = GetCountryIdByName($country);
                         }
                     }
                 }
             }
         }
         /**
          * Now we construct and build each form field
          */
         $column = 0;
         foreach (array_keys($fields) as $fieldId) {
             if ($formId == FORMFIELDS_FORM_ACCOUNT) {
                 if ($fields[$fieldId]->record['formfieldprivateid'] !== '' || !gzte11(ISC_MEDIUMPRINT)) {
                     continue;
                 }
                 $fieldHTML = $fields[$fieldId]->loadForFrontend();
                 if ($column % 2 > 0) {
                     $varname = 'CustomFieldsAccountLeftColumn';
                 } else {
                     $varname = 'CustomFieldsAccountRightColumn';
                 }
             } else {
                 /**
                  * We are using all the custom fields for the billing/shipping are, so check here
                  */
                 if (!gzte11(ISC_MEDIUMPRINT) && $fields[$fieldId]->record['formfieldprivateid'] == '') {
                     continue;
                 }
                 if ($formId == FORMFIELDS_FORM_BILLING) {
                     $varname = 'CustomFieldsBillingColumn';
                 } else {
                     $varname = 'CustomFieldsShippingColumn';
                 }
                 /**
                  * Set the value for the private fields if this is NOT a post
                  */
                 if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $fields[$fieldId]->record['formfieldprivateid'] !== '') {
                     $key = @$fieldMap[$fields[$fieldId]->record['formfieldprivateid']];
                     if (trim($key) !== '') {
                         if ($formId == FORMFIELDS_FORM_BILLING) {
                             $key = 'ordbill' . $key;
                         } else {
                             $key = 'ordship' . $key;
                         }
                         if (array_key_exists($key, $order)) {
                             $fields[$fieldId]->setValue($order[$key]);
                         }
                     }
                 }
                 /**
                  * Add in any of the country/state lists if needed
                  */
                 if (isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'country') {
                     $fields[$fieldId]->setOptions(array_values(GetCountryListAsIdValuePairs()));
                     if ($fields[$fieldId]->getValue() == '') {
                         $fields[$fieldId]->setValue(GetConfig('CompanyCountry'));
                     }
                     $fields[$fieldId]->addEventHandler('change', 'FormFieldEvent.SingleSelectPopulateStates', array('countryId' => $fieldId, 'stateId' => $stateFieldId, 'inOrdersAdmin' => true));
                 } else {
                     if (isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'state' && isId($countryId)) {
                         $stateOptions = GetStateListAsIdValuePairs($countryId);
                         if (is_array($stateOptions) && !empty($stateOptions)) {
                             $fields[$fieldId]->setOptions($stateOptions);
                         }
                     }
                 }
                 /**
                  * We also do not what these fields
                  */
                 if (isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'savethisaddress' || isc_strtolower($fields[$fieldId]->record['formfieldprivateid']) == 'shiptoaddress') {
                     continue;
                 }
             }
             $GLOBALS[$varname] .= $fields[$fieldId]->loadForFrontend() . "\n";
             $column++;
         }
     }
     /**
      * Add this to generate our JS event script
      */
     $GLOBALS['FormFieldEventData'] = $GLOBALS['ISC_CLASS_FORM']->buildRequiredJS();
     /**
      * Do we display the customer custom fields?
      */
     if (!gzte11(ISC_MEDIUMPRINT)) {
         $GLOBALS['HideCustomFieldsAccountLeftColumn'] = 'none';
         $GLOBALS['HideCustomFieldsAccountRightColumn'] = 'none';
     } else {
         if ($GLOBALS['CustomFieldsAccountLeftColumn'] == '') {
             $GLOBALS['HideCustomFieldsAccountLeftColumn'] = 'none';
         }
         if ($GLOBALS['CustomFieldsAccountRightColumn'] == '') {
             $GLOBALS['HideCustomFieldsAccountRightColumn'] = 'none';
         }
     }
     $defaultValues = array('custgroupid' => 0, 'ordstatus' => 7);
     foreach ($defaultValues as $postField => $default) {
         if (!isset($postData[$postField])) {
             $postData[$postField] = $default;
         }
     }
     foreach ($orderFields as $templateField => $orderField) {
         if (!isset($postData[$orderField])) {
             $GLOBALS[$templateField] = '';
         } else {
             $GLOBALS[$templateField] = isc_html_escape($postData[$orderField]);
         }
     }
     if (empty($GLOBALS["AnonymousEmail"])) {
         $GLOBALS["AnonymousEmail"] = $postData['ordbillemail'];
     }
     if (isset($postData['ordbillsaveAddress'])) {
         $GLOBALS['OrderBillSaveAddress'] = 'checked="checked"';
     }
     if (isset($postData['ordshipsaveAddress'])) {
         $GLOBALS['OrderShipSaveAddress'] = 'checked="checked"';
     }
     if (isset($postData['shippingUseBilling'])) {
         $GLOBALS['ShippingUseBillingChecked'] = 'checked="checked"';
     }
     if (isset($postData['billingUseShipping'])) {
         $GLOBALS['BillingUseShippingChecked'] = 'checked="checked"';
     }
     $GLOBALS['OrderStatusOptions'] = $this->GetOrderStatusOptions($postData['ordstatus']);
     /*
      * To hide Pay and save button in edit mode -- Baskaran
      */
     if ($postData['ordstatus'] == '11') {
         $GLOBALS['PayandSaveDisplay'] = 'none';
     } else {
         $GLOBALS['PayandSaveDisplay'] = '';
     }
     $customerClass = GetClass('ISC_ADMIN_CUSTOMERS');
     $GLOBALS['CustomerGroupOptions'] = $customerClass->GetCustomerGroupsAsOptions($postData['custgroupid']);
     $GLOBALS['PaymentMethodsList'] = $this->GetPaymentProviderList($postData);
     if (!empty($order)) {
         $GLOBALS['HideEmailInvoice'] = 'display: none';
     } else {
         if (isset($postData['emailinvoice'])) {
             $GLOBALS['EmailInvoiceChecked'] = 'checked="checked"';
         }
     }
     $GLOBALS['Message'] = GetFlashMessageBoxes();
 }
Example #7
0
		protected function restoreOrderAction ()
		{
			echo isc_json_encode($this->restoreOrderActionHandler(Interspire_Request::post('orderId', 0)));
			exit;
		}
 /**
  * Upload a new image from the Image Manager or TinyMCE itself. Images are thrown in the uploaded_images
  * directory. Invalid images (no dimensions available, mismatched type) are not accepted. Will output
  * a JSON encoded array of details about the image just uploaded.
  */
 private function UploadImage()
 {
     if (empty($_FILES['Filedata'])) {
         exit;
     }
     $_FILES['Filedata']['filesize'] = NiceSize($_FILES['Filedata']['size']);
     $_FILES['Filedata']['id'] = substr(md5($_FILES['Filedata']['name']), 0, 10);
     $_FILES['Filedata']['errorfile'] = false;
     $_FILES['Filedata']['imagepath'] = GetConfig('AppPath') . '/' . GetConfig('ImageDirectory') . '/uploaded_images/';
     $_FILES['Filedata']['duplicate'] = false;
     if ($_FILES['Filedata']['error'] != UPLOAD_ERR_OK) {
         $_FILES['Filedata']['erorrfile'] = 'badupload';
         die(isc_json_encode($_FILES));
     }
     $tmpName = $_FILES['Filedata']['tmp_name'];
     $name = basename($_FILES['Filedata']['name']);
     $name = str_replace(' ', '_', $name);
     $destination = ISC_BASE_PATH . '/' . GetConfig('ImageDirectory') . '/uploaded_images/' . $name;
     if (!$this->IsValidImageFile($tmpName, $_FILES['Filedata']['type'])) {
         $_FILES['FileData']['errorfile'] = 'badtype';
     } else {
         if (!$this->IsImageFile(isc_strtolower($name))) {
             $_FILES['Filedata']['errorfile'] = 'badname';
         } else {
             if (file_exists($destination)) {
                 $_FILES['Filedata']['duplicate'] = true;
             } else {
                 if (!@move_uploaded_file($tmpName, $destination)) {
                     $_FILES['Filedata']['errorfile'] = 'badupload';
                 }
             }
         }
     }
     // Get the image dimensions so we can show a thumbnail
     list($imgWidth, $imgHeight) = @getimagesize($destination);
     if (!$imgWidth || !$imgHeight) {
         $imgWidth = 200;
         $imgHeight = 150;
     }
     $_FILES['Filedata']['origwidth'] = $imgWidth;
     $_FILES['Filedata']['origheight'] = $imgHeight;
     if ($imgWidth > 200) {
         $imgHeight = 200 / $imgWidth * $imgHeight;
         $imgWidth = 200;
     }
     if ($imgHeight > 150) {
         $imgWidth = 150 / $imgHeight * $imgWidth;
         $imgHeight = 150;
     }
     $_FILES['Filedata']['width'] = $imgWidth;
     $_FILES['Filedata']['height'] = $imgHeight;
     unset($_FILES['Filedata']['tmp_name']);
     echo isc_json_encode($_FILES);
     exit;
 }
Example #9
0
 /**
  * Handles adding products from the list display mode
  *
  */
 private function AddProductsToCart()
 {
     $response = array();
     if (isset($_REQUEST['products'])) {
         $cart = GetClass('ISC_CART');
         $products = explode("&", $_REQUEST["products"]);
         foreach ($products as $product) {
             list($id, $qty) = explode("=", $product);
             if (!$cart->AddSimpleProductToCart($id, $qty)) {
                 $response["error"] = $_SESSION['ProductErrorMessage'];
             }
         }
     }
     echo isc_json_encode($response);
     exit;
 }
Example #10
0
		private function BulkUpdateVariations()
		{
			$productId = 0;
			$vid = 0;
			$inv = 0;
			$useHash = false;

			if(isset($_GET['v']) && is_numeric($_GET['v']) && isset($_GET['inv']) && is_numeric($_GET['inv'])) {
				$vid = (int)$_GET['v'];
				$inv = (bool)$_GET['inv'];
			}

			if (isset($_GET['productId'])) {
				$productId = (int)$_GET['productId'];
			}

			if (isId($productId)) {
				$query = 'SELECT prodvariationid FROM [|PREFIX|]products WHERE productid = ' . $productId;
				$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
				if ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($res)) {
					if ($row['prodvariationid'] != $vid) {
						$useHash = true;
					}
				}
			}

			if (!empty($_GET['productHash'])) {
				$useHash = true;
				$productId = $GLOBALS['ISC_CLASS_DB']->Quote($_GET['productHash']);
			}

			if ($useHash) {
				$whereSQL = "vcproductid = 0 AND vcproducthash = '" . $productId . "' ";
			}
			else {
				$whereSQL = 'vcproductid = ' . $productId . ' ';
			}

			$filterOptions = array();
			if (isset($_GET['filterOptions'])) {
				parse_str($_GET['filterOptions'], $filterOptions);
			}

			// create the sql to update the filtered options
			$optionSQL = '';
			if (!empty($filterOptions)) {
				foreach ($filterOptions as $optionName => $optionValues) {
					$thisOptionSQL = '';
					foreach ($optionValues as $value) {
						if ($value == 'all') {
							continue;
						}

						if ($thisOptionSQL) {
							$thisOptionSQL .= ' OR ';
						}
						$thisOptionSQL .= "CONCAT(',', vcoptionids, ',') LIKE '%," . $value . ",%'";
					}

					if ($thisOptionSQL) {
						if ($optionSQL) {
							$optionSQL .= " AND ";
						}

						$optionSQL .= "(" . $thisOptionSQL . ")";
					}
				}
			}

			if ($optionSQL != '') {
				$optionSQL = ' AND ' . $optionSQL;
			}

			$updates = array();
			switch ($_GET['updatePurchaseable']) {
				case "reset":
				case "yes":
					$updates[] = "vcenabled = '1'";
					break;
				case "no":
					$updates[] = "vcenabled = '0'";
					break;
			}

			switch ($_GET['updatePriceDiff']) {
				case "reset":
					$updates[] = "vcpricediff = ''";
					$updates[] = "vcprice = 0";
					break;
				case "add":
				case "subtract":
				case "fixed":
					$updates[] = "vcpricediff = '" . $_GET['updatePriceDiff'] . "'";
					$updates[] = "vcprice = " . (float)$_GET['updatePrice'];
					break;
			}

			switch ($_GET['updateWeightDiff']) {
				case "reset":
					$updates[] = "vcweightdiff = ''";
					$updates[] = "vcweight = 0";
					break;
				case "add":
				case "subtract":
				case "fixed":
					$updates[] = "vcweightdiff = '" . $_GET['updateWeightDiff'] . "'";
					$updates[] = "vcweight = " . (float)$_GET['updateWeight'];
					break;
			}

			if ($inv) {
				if ($_GET['updateStockLevel'] != '') {
					$updates[] = 'vcstock = ' . (int)$_GET['updateStockLevel'];
				}

				if ($_GET['updateLowStockLevel'] != '') {
					$updates[] = 'vclowstock = ' . (int)$_GET['updateLowStockLevel'];
				}
			}

			// delete existing images?
			if (isset($_GET['updateDelImages'])) {
				// get distinct images not associated with variations that aren't in the current filter
				$query = '
					SELECT
						vcimagezoom,
						vcimagestd,
						vcimagethumb
					FROM
						[|PREFIX|]product_variation_combinations pvc
					WHERE
						' . $whereSQL .
						$optionSQL . '
					GROUP BY
						vcimagezoom
					HAVING
						COUNT(*) = (
									SELECT
										COUNT(*)
									FROM
										[|PREFIX|]product_variation_combinations pvc2
									WHERE
										pvc2.vcproductid = pvc.vcproductid AND
										pvc2.vcimagezoom = pvc.vcimagezoom
									)
				';

				$res = $GLOBALS['ISC_CLASS_DB']->Query($query);
				while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($res)) {
					GetClass('ISC_ADMIN_PRODUCT')->DeleteVariationImagesForRow($row);
				}

				$updates[] = "vcimage = ''";
				$updates[] = "vcimagezoom = ''";
				$updates[] = "vcimagestd = ''";
				$updates[] = "vcimagethumb = ''";
			}
			// import image
			elseif (isset($_FILES['updateImage'])) {
				try {
					$image = ISC_PRODUCT_IMAGE::importImage($_FILES['updateImage']['tmp_name'], $_FILES['updateImage']['name'], false, false, true, false);

					$zoom = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true, false);
					$standard = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true, false);
					$thumb = $image->getResizedFilePath(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true, false);

					$updates[] = "vcimage = '" . $image->getSourceFilePath() . "'";
					$updates[] = "vcimagezoom = '" . $zoom . "'";
					$updates[] = "vcimagestd = '" . $standard . "'";
					$updates[] = "vcimagethumb = '" . $thumb . "'";
				}
				catch (Exception $ex) {

				}
			}

			if (!empty($updates)) {
				$updates[] = "vclastmodified = " . time();

				$updateSQL = implode(', ', $updates);

				// update the combinations
				$query = 'UPDATE [|PREFIX|]product_variation_combinations SET ' . $updateSQL . ' WHERE ' . $whereSQL . $optionSQL;
				$GLOBALS['ISC_CLASS_DB']->Query($query);
			}

			// regenerate the combinations table to get fresh data
			$html = $this->GetVariationCombinationsTable($filterOptions, true);
			$response['tableData'] = $html;
			echo '<textarea>'.isc_json_encode($response).'</textarea>';
			exit;
		}
Example #11
0
	/**
	 * Generate the product images/thumbnails to be shown.
	 */
	private function SetProductImages()
	{

		$GLOBALS['ProductThumbWidth'] = ISC_PRODUCT_IMAGE::getSizeWidth(ISC_PRODUCT_IMAGE_SIZE_STANDARD);
		$GLOBALS['ProductThumbHeight'] = ISC_PRODUCT_IMAGE::getSizeHeight(ISC_PRODUCT_IMAGE_SIZE_STANDARD);

		$GLOBALS['ProductMaxTinyWidth'] = ISC_PRODUCT_IMAGE::getSizeWidth(ISC_PRODUCT_IMAGE_SIZE_TINY);
		$GLOBALS['ProductMaxTinyHeight'] = ISC_PRODUCT_IMAGE::getSizeHeight(ISC_PRODUCT_IMAGE_SIZE_TINY);



		$GLOBALS['ProductTinyBoxWidth'] = $GLOBALS['ProductMaxTinyWidth']+4;
		$GLOBALS['ProductTinyBoxHeight'] = $GLOBALS['ProductMaxTinyHeight']+4;


		$GLOBALS['ProductMaxZoomWidth'] = ISC_PRODUCT_IMAGE::getSizeWidth(ISC_PRODUCT_IMAGE_SIZE_ZOOM);
		$GLOBALS['ProductMaxZoomHeight'] = ISC_PRODUCT_IMAGE::getSizeHeight(ISC_PRODUCT_IMAGE_SIZE_ZOOM);

		$GLOBALS['ProductZoomWidth'] = ISC_PRODUCT_IMAGE::getSizeWidth(ISC_PRODUCT_IMAGE_SIZE_ZOOM);
		$GLOBALS['ProductZoomHeight'] = ISC_PRODUCT_IMAGE::getSizeHeight(ISC_PRODUCT_IMAGE_SIZE_ZOOM);


		$productImages = ISC_PRODUCT_IMAGE::getProductImagesFromDatabase($GLOBALS['ProductId']);
		$GLOBALS['NumProdImages'] = count($productImages);

		$GLOBALS['CurrentProdThumbImage'] = 0;
		$thumb = '';
		$curZoomImage = '';
		$GLOBALS['SNIPPETS']['ProductTinyImages'] = '';
		$GLOBALS['HideImageCarousel'] = 'display:none;';
		$GLOBALS['HideMorePicturesLink'] = 'display:none;';
		$thumbImageDescription = '';
		$i = 0;

		$GLOBALS['ProdImageJavascript'] = '';
		$GLOBALS['ProdImageZoomJavascript'] = '';
		$GLOBALS['LightBoxImageList'] = '';
		$GLOBALS['ZoomImageMaxWidth'] = 0;
		$GLOBALS['ZoomImageMaxHeight'] = 0;
		$GLOBALS['ZoomImageMaxWidthHeight'] = 0;
		$GLOBALS['HideAlwaysLinkedMorePicturesLink'] = 'display: none';

		if ($GLOBALS['NumProdImages']) {
			//Show image carousel

			if ($GLOBALS['NumProdImages'] == 2) {
				$var = "MorePictures1";
			} else if ($GLOBALS['NumProdImages'] == 1) {
				$var = "SeeLargerImage";
			} else {
				$var = "MorePictures2";
			}

			$GLOBALS['SeeMorePictures'] = sprintf(GetLang($var), count($productImages) - 1);
			$GLOBALS['HideAlwaysLinkedMorePicturesLink'] = '';

			if (GetConfig('ProductImagesTinyThumbnailsEnabled')) {
				$GLOBALS['HideImageCarousel'] = '';
			} else {
				$GLOBALS['HideMorePicturesLink'] = '';
			}

			$continue=false;

			foreach ($productImages as $productImage) {

				$thumbURL = '';
				$zoomImageURL = '';

				try{
					$thumbURL = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_STANDARD, true);
					//$GLOBALS['ProductThumbURL'] = $thumbURL;
				} catch (Exception $exception) {
					// do nothing, will result in returning blank string, which is fine
				}

				try{
					$zoomImageURL = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true);
				} catch (Exception $exception) {
					// do nothing, will result in returning blank string, which is fine
				}

				if($thumbURL == '' && $zoomImageURL == '') {
					continue;
				}

				$resizedZoomDimension = $productImage->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_ZOOM);
				$resizedTinyDimension = $productImage->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY);

				//calculate the max zoom image width and height
				if ($GLOBALS['ZoomImageMaxWidth'] < $resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_WIDTH]) {

					$GLOBALS['ZoomImageMaxWidth'] = $resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_WIDTH];
					//the height of the image has got the max width needed to calulate the image fancy box size.
					$GLOBALS['ZoomImageMaxWidthHeight'] = $resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_HEIGHT];
				}

				if ($GLOBALS['ZoomImageMaxHeight'] < $resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_HEIGHT]) {
					$GLOBALS['ZoomImageMaxHeight'] = $resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_HEIGHT];
					//the width of the image has got the max height needed to calulate the image fancy box size.
					$GLOBALS['ZoomImageMaxHeightWidth'] = $resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_HEIGHT];
				}

				$GLOBALS['ImageDescription'] = isc_html_escape($productImage->getDescription());
				if($GLOBALS['ImageDescription'] == '') {
					$GLOBALS['ImageDescription'] = GetLang("Image") . " " . ($i + 1);
				}

				//show image carousel
				if(GetConfig('ProductImagesTinyThumbnailsEnabled')==1) {

					$GLOBALS['ProdImageJavascript'] .= "
						ThumbURLs[".$i."] = " . isc_json_encode($thumbURL) . ";
						ProductImageDescriptions[".$i."] = " . isc_json_encode($GLOBALS['ImageDescription']) . ";
					";
					$GLOBALS['TinyImageOverJavascript'] = "showProductThumbImage(".$i.")";
					//$GLOBALS['ProductTinyImageURL'] = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true);

					try{
						$GLOBALS['ProductTinyImageURL'] = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true);
						//$GLOBALS['ProductThumbURL'] = $thumbURL;
					} catch (Exception $exception) {
						// do nothing, will result in returning blank string, which is fine
					}

					$GLOBALS['ProductThumbIndex'] = $i;
					if(GetConfig('ProductImageMode') == 'lightbox') {
						$GLOBALS['TinyImageClickJavascript'] = "showProductImageLightBox(".$i."); return false;";

					} else {
						$GLOBALS['TinyImageClickJavascript'] = "showProductImage('".GetConfig('ShopPath')."/productimage.php', ".$GLOBALS['ProductId'].", ".$i.");";
					}

					$GLOBALS['TinyImageWidth'] = $resizedTinyDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_WIDTH];
					$GLOBALS['TinyImageHeight'] = $resizedTinyDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_HEIGHT];
					$GLOBALS['TinyImageTopPadding'] = floor(($GLOBALS['ProductMaxTinyHeight'] - $GLOBALS['TinyImageHeight']) / 2);
					$GLOBALS['SNIPPETS']['ProductTinyImages'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ProductTinyImage");
					$continue = true;
				}

				if(GetConfig('ProductImagesImageZoomEnabled') == 1) {
					//check if zoom image is large enough for image zoomer
					if($resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_WIDTH]<ISC_PRODUCT_IMAGE_MIN_ZOOM_WIDTH && $resizedZoomDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_HEIGHT]<ISC_PRODUCT_IMAGE_MIN_ZOOM_HEIGHT) {
						$zoomImageURL = '';
					}
					$GLOBALS['ProdImageZoomJavascript'] .= "
						ZoomImageURLs[".$i."] = " . isc_json_encode($zoomImageURL) . ";
					";
					$continue = true;
				}

				//	$GLOBALS['ProductZoomImageURL'] = $zoomImageURL;

				//this image is the product page thumbnail
				if($i==0) {
					//get the thumb image for product page
					$thumb = $thumbURL;
					$curZoomImage = $zoomImageURL;
					$thumbImageDescription = $GLOBALS['ImageDescription'];
					//if there is no need to loop through images anymore, get out from the loop.
					if($continue === false) {
						break;
					}
				}
				$i++;
			}
		}

		$GLOBALS['VisibleImageTotal'] = $i+1;

		$GLOBALS['ShowImageZoomer'] = GetConfig('ProductImagesImageZoomEnabled');
		if ($GLOBALS['ShowImageZoomer']) {
			$GLOBALS['SNIPPETS']['ProductImageZoomer'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ProductImageZoomer");
		}
		$GLOBALS['ZoomImageURL'] = $curZoomImage;

		//if no product thumb images
		if($thumb == '') {
			if(GetConfig('DefaultProductImage') == 'template') {
				$thumb = $GLOBALS['IMG_PATH'].'/ProductDefault.gif';
			}
			else {
				$thumb = GetConfig('ShopPath').'/'.GetConfig('DefaultProductImage');
			}
		}

		// need to check for variation images
		//$GLOBALS['HideOnNoImages'] = 'display: none;';
		$GLOBALS['ImageDescription'] = $thumbImageDescription;
		$GLOBALS['ThumbImageURL'] = $thumb;


		//image popup javascript for the thumbnail image when the page is loaded
		$imagePopupLink = "showProductImage('".GetConfig('ShopPath')."/productimage.php', ".$GLOBALS['ProductId'].");";
		$GLOBALS['ImagePopupLink'] = $imagePopupLink;
		$GLOBALS['TinyImageClickJavascript'] = $imagePopupLink;

		// If we're showing images as a lightbox, we need to load up the URLs for the other images for this product
		if(GetConfig('ProductImageMode') == 'lightbox') {
			$GLOBALS['TinyImageClickJavascript'] = "showProductImageLightBox(); return false;";
			$GLOBALS['LightBoxImageJavascript'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('ProductImagesLightBox');
		}

		if ($GLOBALS['NumProdImages']) {
			$GLOBALS['SNIPPETS']['ProductThumbImage'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('ProductThumbImage');
		} else {
			$GLOBALS['SNIPPETS']['ProductThumbImage'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('ProductThumbImagePlaceholder');
		}
	}
Example #12
0
	/**
	* Filter which encodes any given object/string as a json packet
	*
	* @param mixed $obj
	* @return string
	*/
	public function jsonFilter($obj)
	{
		return isc_json_encode($obj);
	}
Example #13
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;
		}
 /**
  * GetAllBrands
  * wirror_20110130: ajax call for series
  * 
  */
 private function GetSeries()
 {
     $series = array();
     $squery = "SELECT * FROM [|PREFIX|]brand_series WHERE brandid!='0' ";
     if (isset($_REQUEST['bid']) && $_REQUEST['bid'] > 0) {
         $squery .= " AND brandid = {$_REQUEST['bid']} ";
     }
     $squery .= "ORDER BY seriesname ASC";
     $sresult = $GLOBALS["ISC_CLASS_DB"]->Query($squery);
     while ($row = $GLOBALS["ISC_CLASS_DB"]->Fetch($sresult)) {
         $series[] = array('id' => $row['seriesid'], 'name' => isc_html_escape($row['seriesname']));
     }
     echo isc_json_encode($series);
     exit;
 }
Example #15
0
 function pics_save($_FILES, $description, $firstName, $lastName, $address1, $address2)
 {
     $description = trim($description);
     $firstName = trim($firstName);
     $lastName = trim($lastName);
     $address1 = trim($address1);
     $address2 = trim($address2);
     $tempFile = $_FILES['tmp_name'];
     $rootdir = ISC_BASE_PATH;
     //$allowpictypes = array(1, 2, 3, 6, 7, 8);
     $allowpictypestr = GetConfig('LimitCustomerUploadImageFileType');
     $allowpictypes = explode(',', $allowpictypestr);
     // get file ext
     $single_type = exif_imagetype($tempFile);
     $picExt = '';
     switch ($single_type) {
         case 1:
             $picExt = '.gif';
             break;
         case 2:
             $picExt = '.jpg';
             break;
         case 3:
             $picExt = '.png';
             break;
         case 4:
             $picExt = '.swf';
             break;
         case 6:
             $picExt = '.bmp';
             break;
         case 7:
             $picExt = '.tiff';
             break;
         case 8:
             $picExt = '.tiff';
             break;
     }
     $allowCustomerUploadMaxNum = GetConfig('LimitCustomerUploadImageNum');
     $customerId = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerId();
     $imgNumQuery = "\n\t\t\t\tSELECT imagenum\n\t\t\t\tFROM [|PREFIX|]customers\n\t\t\t\tWHERE customerid='" . (int) $customerId . "'";
     $imgNumResult = $GLOBALS['ISC_CLASS_DB']->Query($imgNumQuery);
     $imagenum = $GLOBALS['ISC_CLASS_DB']->FetchOne($imgNumResult);
     if (!in_array($single_type, $allowpictypes)) {
         $status = 0;
         $message = "Invalid type of file!";
         $errorCode = -1;
     } elseif (strlen($description) > 1000) {
         $status = 0;
         $message = "Description should not surpass 1000 characters!";
         $errorCode = -2;
     } elseif (strlen($description) <= 0) {
         $status = 0;
         $message = "You must enter a description for each image submitted!";
         $errorCode = -3;
     } elseif ($imagenum >= $allowCustomerUploadMaxNum) {
         $status = 0;
         $message = "You cannot upload more than {$allowCustomerUploadMaxNum} images.";
         $errorCode = -4;
     } else {
         $targetPath = $rootdir . '/upload/' . date('ymd', time()) . '/';
         $fileName = time() . md5(mt_rand(0, 999999)) . $picExt;
         $path = '/upload/' . date('ymd', time()) . '/' . $fileName;
         $targetFile = $rootdir . $path;
         mkdir(str_replace('//', '/', $targetPath), 0755, true);
         if (move_uploaded_file($tempFile, $targetFile)) {
             $CustomerId = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerId();
             $NewPicture = array("customerid" => $CustomerId, "path" => $path, "description" => $description, "filename" => $_FILES['name'], "dateline" => time(), "uploaderFirstName" => $firstName, "uploaderLastName" => $lastName, "address1" => $address1, "address2" => $address2);
             if ($GLOBALS['ISC_CLASS_DB']->InsertQuery("pic", $NewPicture)) {
                 $query1 = "UPDATE [|PREFIX|]customers set imagenum = imagenum + 1 where customerid = '{$CustomerId}'";
                 $result = $GLOBALS["ISC_CLASS_DB"]->Query($query1);
             }
             $status = 1;
             $errorCode = 0;
             $message = "Upload successfully";
         }
     }
     //echo serialize(array("status" => $status, "errorCode" => $errorCode, "message" => $message));
     echo isc_json_encode(array("status" => $status, "errorCode" => $errorCode, "message" => $message));
     exit;
 }
Example #16
0
	/**
	 * Show the page allowing a customer to choose the billing address for their order.
	 *
	 * @param array Optionally, an array of errors that have occurred and need to be shown.
	 */
	private function ChooseBillingAddress($errors=array())
	{
		// If we're coming here from a post request and we're not logged in then we've just chosen how we're checking out
		if(empty($errors) && $_SERVER['REQUEST_METHOD'] == "POST" && !CustomerIsSignedIn()) {

			// Are we logging in?
			if(isset($_REQUEST['login_email'])) {
				$GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
				if(!$GLOBALS['ISC_CLASS_CUSTOMER']->CheckLogin(true)) {
					@ob_end_clean();
					header("Location: ".GetConfig('ShopPath').'/checkout.php?action=checkout&bad_login=1');
					exit;
				}
			}
			// Perhaps we've chosen to create an account?
			else if(isset($_REQUEST['checkout_type']) && $_REQUEST['checkout_type'] == 'register') {
				@ob_end_clean();
				header("Location: ".GetConfig('ShopPath').'/login.php?action=create_account&checking_out=yes');
				exit;
			}
			// Otherwise, we're trying to checkout as a guest
		}

		if(isset($_SESSION['CHECKOUT']['CHECKOUT_TYPE']) && $_SESSION['CHECKOUT']['CHECKOUT_TYPE'] == 'express') {
			$redirectOnError = getConfig('ShopPath').'/checkout.php?action=express';
		}
		else {
			$redirectOnError = getConfig('ShopPath').'/checkout.php?action=checkout';
		}

		// If guest checkout is not enabled and the customer isn't signed in then send the customer
		// back to the beginning of the checkout process.
		if(!GetConfig('GuestCheckoutEnabled') && !CustomerIsSignedIn()) {
			redirect($redirectOnError);
		}

		$GLOBALS['HideErrors'] = 'display: none';
		if(!empty($errors)) {
			$GLOBALS['ErrorMessage'] = implode('<br />', $errors);
			$GLOBALS['SavedAddress'] = $_POST;
			$GLOBALS['HideIntro'] = 'display: none';
			$GLOBALS['HideErrors'] = '';
		}
		else if(isset($_SESSION['CHECKOUT']['BILLING_ADDRESS']) && is_array($_SESSION['CHECKOUT']['BILLING_ADDRESS'])) {
			$GLOBALS['SavedAddress'] = $_SESSION['CHECKOUT']['BILLING_ADDRESS'];
			if(isset($_SESSION['CHECKOUT']['ACCOUNT_EMAIL'])) {
				$GLOBALS['SavedAddress']['account_email'] = $_SESSION['CHECKOUT']['ACCOUNT_EMAIL'];
			}
		}

		$addressVars = array(
			'account_email' => 'AccountEmail',
		);
		foreach($addressVars as $addressField => $formField) {
			if(isset($GLOBALS['SavedAddress'][$addressField])) {
				$GLOBALS[$formField] = isc_html_escape($GLOBALS['SavedAddress'][$addressField]);
			}
		}


		$GLOBALS['FromURL'] = urlencode("checkout.php?action=choose_billing_address");
		$GLOBALS['ShipAddressButtonText'] = isc_html_escape(GetLang('BillToThisAddress'));
		$GLOBALS['ShipAddressButtonText_JS'] = isc_json_encode(GetLang('BillToThisAddress'));
		$GLOBALS['ShippingFormAction'] = "save_biller";

		// If the customer isn't signed in then they're performing a guest checkout so they don't see a list of addresses, but actually
		// the shipping address form
		$GLOBALS['HidePanels'][] = 'ChooseShippingAddress';
		$GLOBALS['ShipToBillingName'] = 'ship_to_billing';
		if(!CustomerIsSignedIn()) {
			$GLOBALS['HidePanels'][] = 'ChooseBillingAddress';
			$GLOBALS['CheckoutShippingTitle'] = GetLang('BillingDetails');
			$GLOBALS['CheckoutShippingIntro'] = GetLang('EnterBillingAddressBelow');
			$GLOBALS['ShipAddressButtonText'] = isc_html_escape(GetLang('BillAndShipToAddress'));
			$GLOBALS['ShipAddressButtonText_JS'] = isc_json_encode(GetLang('BillAndShipToAddress'));
		}
		else {
			// Hide the address entry panel
			$GLOBALS['HidePanels'][] = 'CheckoutNewAddressForm';

			// Do they have a shipping address stored in the system?
			// If not we will ask them to create one

			if ($this->GetNumShippingAddresses() == 0) {
				// Take them to add a shipping address
				$this_page = urlencode("checkout.php?action=choose_billing_address");
				@ob_end_clean();
				header(sprintf("Location: %s/account.php?action=add_shipping_address&from=%s", $GLOBALS['ShopPath'], $this_page));
				die();
			}

			$GLOBALS['CheckoutShippingTitle'] = GetLang('ChooseBillingAddress');
			$GLOBALS['CheckoutShippingIntro'] = sprintf("%s <a href='%s/account.php?action=add_shipping_address&amp;from=%s'>%s</a>", GetLang('ChooseBillingAddressIntro1'), $GLOBALS['ShopPath'], $GLOBALS['FromURL'], GetLang('ChooseBillingAddressIntro2'));
		}

		if(isset($_SESSION['CART_CHANGED'])) {
			$GLOBALS['CheckoutShippingIntro'] = GetLang('CartChangedSinceCheckout');
			unset($_SESSION['CART_CHANGED']);
		}

		if($this->getQuote()->isDigital()) {
			$GLOBALS['HideShippingOptions'] = 'display: none';
			$GLOBALS['ShipAddressButtonText'] = isc_html_escape(GetLang('BillToThisAddress'));
			$GLOBALS['ShipAddressButtonText_JS'] = isc_json_encode(GetLang('BillToThisAddress'));
		}
		else {
			$GLOBALS['ShipToAddressChecked'] = 'checked="checked"';
		}

		// If the cart is empty, take them back to it
		if ($this->getQuote()->getNumItems() == 0) {
			@ob_end_clean();
			header(sprintf("Location: %s/cart.php", $GLOBALS['ShopPath']));
			die();
		}

		$GLOBALS['CustomFieldSelectedAddressType'] = FORMFIELDS_FORM_BILLING;

		// Show the list of available shipping addresses
		$GLOBALS['ISC_CLASS_TEMPLATE']->SetPageTitle(GetConfig('StoreName') . " - " . GetLang('ChooseBillingAddress'));
		$GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("checkout_address");
		$GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
	}
Example #17
0
		public function HandleToDo($Do)
		{
			$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('categories');
			$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('optimizer');
			switch (isc_strtolower($Do))
			{
				case 'getreassigncategorystep1data':
				{
					$data = $this->getReassignCategoryStep1Data();
					echo isc_json_encode($data);
					break;
				}
				case 'getreassigncategorystep2data':
				{
					echo $this->getParentLineage($_POST['parentCat']);
					break;
				}
				case 'reassigncategory':
				{
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Delete_Categories)) {
						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories");
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						$this->reassignCategory();
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}
					break;
				}
				case "saveupdatedcategory":
				{
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Categories)) {
						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories");

						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						$this->SaveUpdatedCategory();
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}

					break;
				}
				case "editcategory":
				{
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Categories)) {
						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories", GetLang('EditCategory1') => "index.php?ToDo=editCategory");

						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						$this->EditCategory();
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}

					break;
				}
				case "savecategory":
				{
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Create_Category)) {
						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories");

						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						$this->SaveCategory();
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}

					break;
				}
				case "createcategory":
				{
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Create_Category)) {
						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories", GetLang('CreateCategory') => "index.php?ToDo=addCategory");

						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						$this->CreateCategory();
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}

					break;
				}
				case "editcategoryvisibility":
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Edit_Categories)) {

						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories");

						if(!isset($_REQUEST['ajax'])) {
							$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						}

						$this->EditCategoryVisibility();

						if(!isset($_REQUEST['ajax'])) {
							$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
						}

						die();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}
					break;
				case "deletecategory":
				{
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Delete_Categories)) {
						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories");

						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						$this->DeleteCategory();
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}
				}
				default:
				{
					if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Manage_Categories)) {
						$GLOBALS['BreadcrumEntries'] = array(GetLang('Home') => "index.php", GetLang('Categories') => "index.php?ToDo=viewCategories");

						$GLOBALS['InfoTip'] = GetLang('InfoTipManageCategories');

						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintHeader();
						$this->ManageCategories();
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->PrintFooter();
					} else {
						$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
					}
				}
			}
		}
	/**
	*	Build the grid that will be shown on the "Abandon Orders" tab
	**/
	public function OrderStatsByAbandonGrid()
	{
		$GLOBALS['OrderGrid'] = "";

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

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

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

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

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

			$GLOBALS['OrdersByAbandonCurrentPage'] = $page;

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

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

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

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

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

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

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

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

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

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

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

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

				$GLOBALS['JumpToOrdersByAbandonGrid'] = "";

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

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

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

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

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

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

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

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

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

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

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

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

			$this->template->display('stats.orders.byabandongrid.tpl');
		}
	}
 /**
  * Return a JSON response with all of the addresses from the address book
  * for the selected customer.
  */
 private function LoadCustomerAddresses()
 {
     $tags = array();
     if (!isset($_REQUEST['customerId']) || !IsId($_REQUEST['customerId'])) {
         exit;
     }
     $orderClass = GetClass('ISC_ADMIN_ORDERS');
     echo isc_json_encode($orderClass->LoadCustomerAddresses($_REQUEST['customerId']));
     exit;
 }
Example #20
0
 /**
  * Build the form field event JavaScript for the frontend
  *
  * Method will build the JavaScript events for the form field
  *
  * @access public
  * @return string The event JavaScript if there is any, empty string if not
  */
 public function loadEventsForFrontend()
 {
     if (!self::isLoaded()) {
         return '';
     }
     if (!is_array($this->events) || empty($this->events)) {
         return '';
     }
     $eventJS = '';
     foreach ($this->events as $type => $events) {
         foreach ($events as $event) {
             $func = $event['func'];
             $args = isc_json_encode($event['args']);
             $eventJS .= '$(FormField.GetField(' . $this->fieldId . ')).bind("' . $type . '", ' . $args . ', ' . $func . ');' . "\n";
         }
     }
     return $eventJS;
 }
Example #21
0
		protected function ManageOrders($MsgDesc = "", $MsgStatus = "")
		{
			$GLOBALS['HideClearResults'] = "none";
			$status = array();
			$num_custom_searches = 0;
			$numOrders = 0;

			// Fetch any results, place them in the data grid
			$GLOBALS['OrderDataGrid'] = $this->ManageOrdersGrid($numOrders, $numDeletedOrders);

			// Was this an ajax based sort? Return the table now
			if(isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 1) {
				echo $GLOBALS['OrderDataGrid'];
				return;
			}

			if(isset($_REQUEST['searchQuery']) || isset($_GET['searchId'])) {
				$GLOBALS['HideClearResults'] = "";
			}

			if(isset($this->_customSearch['searchname'])) {
				$GLOBALS['ViewName'] = $this->_customSearch['searchname'];

				if(!empty($this->_customSearch['searchlabel'])) {
					$GLOBALS['HideDeleteViewLink'] = "none";
				}
			}
			else {
				$GLOBALS['ViewName'] = GetLang('AllOrders');
				$GLOBALS['HideDeleteViewLink'] = "none";
			}

			// Do we display the add order buton?
			if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Add_Orders)) {
				$GLOBALS['AddOrderButton'] = '<input type="button" value="' . GetLang('AddAnOrder') . '..." class="FormButton" style="width:100px" onclick="document.location.href=\'index.php?ToDo=addOrder\'" />';
			} else {
				$GLOBALS['AddOrderButton'] = '';
			}

			$GLOBALS['OrderActionOptions'] = '<option selected="1">' . GetLang('ChooseAction') . '</option>';

			$searchDeletedOrders = 'no';
			if (isset($_REQUEST['searchDeletedOrders'])) {
				$searchDeletedOrders = $_REQUEST['searchDeletedOrders'];
			}

			if ($searchDeletedOrders != 'only') {
				// Do we need to disable the delete button?
				if (!$GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Delete_Orders) || $numOrders == 0) {
					$args = 'disabled="disabled"';
				} else {
					$args = 'value="delete"';
				}

				$GLOBALS['OrderActionOptions'] .= '<option ' . $args . '>' . GetLang('DeleteSelected') . '</option>';
			}

			$searchGet = $_GET;
			if (isset($searchGet['searchId']) && $searchGet['searchId'] == 0) {
				// this is a nasty hack but I can't right now figure out a better way of making count($_GET) work as
				// expected when the clicking 'view: all orders' which is '&ToDo=viewOrders&searchId=0'
				unset($searchGet['searchId']);
			}

			if ($searchDeletedOrders != 'no') {
				if (!$GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Undelete_Orders) || $numOrders == 0) {
					$GLOBALS['OrderActionOptions'] .= '<option disabled="disabled">' . isc_html_escape(GetLang('UndeleteSelected')) . '</option>';
				} else {
					$GLOBALS['OrderActionOptions'] .= '<option value="undelete">' . isc_html_escape(GetLang('UndeleteSelected')) . '</option>';
				}

				if (!$GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Purge_Orders) || $numOrders == 0) {
					$GLOBALS['OrderActionOptions'] .= '<option disabled="disabled">' . isc_html_escape(GetLang('PurgeSelected')) . '</option>';
				} else {
					$GLOBALS['OrderActionOptions'] .= '<option value="purge">' . isc_html_escape(GetLang('PurgeSelected')) . '</option>';
				}
			}

			if ($searchDeletedOrders == 'only' && GetConfig('DeletedOrdersAction') == 'purge') {
				// show a notice about searching for deleted orders when the feature is turned off
				FlashMessage(GetLang('OrderArchivingIsTurnedOff'), MSG_INFO);
			}

			if($numOrders > 0) {
				if($MsgDesc == "" && (isset($_REQUEST['searchQuery']) || count($searchGet) > 1) && !isset($_GET['selectOrder'])) {
					if($numOrders == 1) {
						$MsgDesc = GetLang('OrderSearchResultsBelow1');
					}
					else {
						$MsgDesc = sprintf(GetLang('OrderSearchResultsBelowX'), $numOrders);
					}

					$MsgStatus = MSG_SUCCESS;
				}
				$args1 = 'value="printInvoice"';
				$args2 = 'value="printSlip"';
			}
			else {
				$args1 = 'disabled="disabled"';
				$args2 = 'disabled="disabled"';
			}

			$GLOBALS['OrderActionOptions'] .= '<option ' . $args1 . '>' . GetLang('PrintInvoicesSelected') . '</option>';
			$GLOBALS['OrderActionOptions'] .= '<option ' . $args2 . '>' . GetLang('PrintPackingSlipsSelected') . '</option>';

			if(!gzte11(ISC_MEDIUMPRINT)) {
				$GLOBALS[base64_decode('SGlkZUV4cG9ydA==')] = "none";
				$GLOBALS[B('ZGlzYWJsZU9yZGVyRXhwb3J0cw==')] = true;
			}

			$GLOBALS['OrderActionOptions'] .= '<option disabled="disabled"></option><optgroup label="' . GetLang('BulkOrderStatus') . '">';

			$result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]order_status ORDER BY statusorder ASC");
			while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
				$GLOBALS['OrderActionOptions'] .= '<option value="updateStatus' . $row['statusid'] . '">' . $row['statusdesc'] . '</option>';
			}
			$GLOBALS['OrderActionOptions'] .= '</optgroup>';

			if (!isset($_REQUEST['searchId'])) {
				$_REQUEST['searchId'] = 0;
			}

			// Get the custom search as option fields
			$GLOBALS['CustomSearchOptions'] = $GLOBALS['ISC_CLASS_ADMIN_CUSTOMSEARCH']->GetSearchesAsOptions($_REQUEST['searchId'], $num_custom_searches, "AllOrders", "viewOrders", "customOrderSearch");

			// the above is pre-formatted, need it as raw data for the iphone
			$GLOBALS['customSearchList'] = $GLOBALS['ISC_CLASS_ADMIN_CUSTOMSEARCH']->GetSearches();

			if(!isset($_REQUEST['searchId'])) {
				$GLOBALS['HideDeleteCustomSearch'] = "none";
			} else {
				$GLOBALS['CustomSearchId'] = (int)$_REQUEST['searchId'];
			}

			$GLOBALS['OrderIntro'] = GetLang('ManageOrdersIntro');
			$GLOBALS['Message'] = '';

			// No orders
			if($numOrders == 0) {
				$GLOBALS['DisplayGrid'] = "none";

				if(count($searchGet) > 1) {
					// Performing a search of some kind
					if ($MsgDesc == "") {
						$GLOBALS['Message'] = MessageBox(GetLang('NoOrderResults'), MSG_ERROR);
						if ($numDeletedOrders) {
							$deletedUrl = $searchGet;
							$deletedUrl['searchDeletedOrders'] = 'only';
							$deletedUrl = 'index.php?' . http_build_query($deletedUrl);

							$GLOBALS['Message'] .= MessageBox(GetLang('DeletedOrdersMatchedYourSearch', array(
								'viewDeletedOrdersUrl' => $deletedUrl,
							)), MSG_INFO, 'MessageBoxTrash');
							unset($deletedUrl);
						}
					}
				} else {
					$GLOBALS['Message'] = MessageBox(GetLang('NoOrders'), MSG_SUCCESS);
					$GLOBALS['DisplaySearch'] = "none";
				}

				unset($searchGet);
			}

			if($MsgDesc != "") {
				$GLOBALS['Message'] = MessageBox($MsgDesc, $MsgStatus);
			}

			$flashMessages = GetFlashMessages();
			if(is_array($flashMessages)) {
				foreach($flashMessages as $flashMessage) {
					$GLOBALS['Message'] .= MessageBox($flashMessage['message'], $flashMessage['type']);
				}
			}

			if ($GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Export_Orders)) {
				$GLOBALS['ExportAction'] = "index.php?ToDo=startExport&t=orders";
				if (isset($GLOBALS['CustomSearchId']) && $GLOBALS['CustomSearchId'] != '0') {
					$GLOBALS['ExportAction'] .= "&searchId=" . $GLOBALS['CustomSearchId'];
				}
				else {
					$params = $_GET;
					unset($params['ToDo']);

					if (!empty($params)) {
						$GLOBALS['ExportAction'] .= "&" . http_build_query($params);
					}
				}
			}

			$selectOrder = '';
			if (!empty($_GET['selectOrder']) && isId($_GET['selectOrder'])) {
				$selectOrder = 'QuickView(' . $_GET['selectOrder'] . ');';
			}
			$GLOBALS['SelectOrder'] = $selectOrder;

			// Used for iPhone interface
			$GLOBALS['OrderStatusOptions'] = $this->GetOrderStatusOptions();

			if ($numOrders && $GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Export_Orders)) {
				$exportAction = "index.php?ToDo=startExport&t=orders";
				if (isset($GLOBALS['CustomSearchId']) && $GLOBALS['CustomSearchId'] != '0') {
					$exportAction .= "&searchId=" . $GLOBALS['CustomSearchId'];
				}
				else {
					$params = $_GET;
					unset($params['ToDo']);

					if (!empty($params)) {
						$exportAction .= "&" . http_build_query($params);
					}
				}

				$searchQueryForExport = $_POST + $_GET;
				foreach ($searchQueryForExport as $index => $value) {
					if ($value === '') {
						unset($searchQueryForExport[$index]);
					}
				}
				unset($searchQueryForExport['ToDo'], $searchQueryForExport['SubmitButton1'], $searchQueryForExport['sortField'], $searchQueryForExport['sortOrder'], $searchQueryForExport['SearchButton_x'], $searchQueryForExport['SearchButton_y']);
				$searchQueryForExport = isc_json_encode($searchQueryForExport);

				$orderExportMenu = array();

				$orderExportMenu[] = array(
					array(
						'backgroundImage' => 'images/export.gif',
						'label' => GetLang('EmailIntegrationExportToFile'),
						'class' => 'exportMenuLink',
						'href' => $exportAction,
					),
				);

				$emailModules = ISC_EMAILINTEGRATION::getConfiguredModules();
				foreach ($emailModules as /** @var ISC_EMAILINTEGRATION */$emailModule) {
					if (!$emailModule->supportsBulkExport()) {
						// not all modules have to support bulk exports
						continue;
					}

					$orderExportMenuModules[] = array(
						'backgroundImage' => '../modules/' . str_replace('_', '/', $emailModule->GetId()) . '/images/16x16.png',
						'label' => GetLang('EmailIntegrationExportToModule', array('module' => $emailModule->GetName())),
						'href' => 'javascript:Interspire_EmailIntegration_ModuleExportMachine.start({ exportType: "Order", exportModule: "' . $emailModule->GetId() . '", exportSearch: ' . $searchQueryForExport . ' });',
					);
				}

				if (!empty($orderExportMenuModules)) {
					$orderExportMenu[] = $orderExportMenuModules;

					$this->engine->bodyScripts[] = '../javascript/fsm.js';
					$this->engine->bodyScripts[] = '../javascript/jquery/plugins/disabled/jquery.disabled.js';
					$this->engine->bodyScripts[] = '../javascript/ajaxDataProvider.js';
					$this->engine->bodyScripts[] = 'script/emailintegration.js';
					$this->engine->bodyScripts[] = 'script/emailintegration.export.js';
				}

				$this->template->assign('orderExportMenu', $orderExportMenu);
			} else {
				$this->template->assign('disableOrderExports', true);
			}

			$this->template->display('orders.manage.tpl');
		}
Example #22
0
		public function SetPanelSettings()
		{
			$GLOBALS['FooterScripts'] = '';

			$GLOBALS['HideLogoutLink'] = 'display: none';
			if(CustomerIsSignedIn()) {
				$GLOBALS['HideLogoutLink'] = '';
			}

			if($_SERVER['REQUEST_METHOD'] == 'POST') {
				$baseURL = getConfig('ShopPathNormal');
			}
			else {
				$baseURL = getCurrentLocation();
			}

			if(strpos($baseURL, '?') === false) {
				$baseURL .= '?';
			}
			else {
				$baseURL .= '&';
			}

			$fullSiteLink = $baseURL.'fullSite=1';
			$GLOBALS['ISC_CLASS_TEMPLATE']->assign('FullSiteLink', $fullSiteLink);

			// Show Mobile Site link
			if(canViewMobileSite()) {
				$mobileSiteURL = preg_replace('/(&)?fullSite=\d*/i', '', $baseURL);
				$GLOBALS['MobileSiteURL'] = $mobileSiteURL.'fullSite=0';
				$GLOBALS['MobileSiteLink'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('MobileSiteLink');
			}

			// Show "All prices are in [currency code]"
			$currency = GetCurrencyById($GLOBALS['CurrentCurrency']);
			if(is_array($currency) && $currency['currencycode']) {
				$GLOBALS['AllPricesAreInCurrency'] = sprintf(GetLang('AllPricesAreInCurrency'), isc_html_escape($currency['currencyname']), isc_html_escape($currency['currencycode']));
			}

			if(GetConfig('DebugMode') == 1) {
				$end_time = microtime_float();
				$GLOBALS['ScriptTime'] = number_format($end_time - ISC_START_TIME, 4);
				$GLOBALS['QueryCount'] = $GLOBALS['ISC_CLASS_DB']->NumQueries;
				if (function_exists('memory_get_peak_usage')) {
					$GLOBALS['MemoryPeak'] = "Memory usage peaked at ".Store_Number::niceSize(memory_get_peak_usage(true));
				} else {
					$GLOBALS['MemoryPeak'] = '';
				}

				if (isset($_REQUEST['debug'])) {
					$GLOBALS['QueryList'] = "<ol class='QueryList' style='font-size: 13px;'>\n";
					foreach($GLOBALS['ISC_CLASS_DB']->QueryList as $query) {
						$GLOBALS['QueryList'] .= "<li style='line-height: 1.4; margin-bottom: 4px;'>".isc_html_escape($query['Query'])." &mdash; <em>".number_format($query['ExecutionTime'], 4)."seconds</em></li>\n";
					}
					$GLOBALS['QueryList'] .= "</ol>";
				}
				$GLOBALS['DebugDetails'] = "<p>Page built in ".$GLOBALS['ScriptTime']."s with ".$GLOBALS['QueryCount']." queries. ".$GLOBALS['MemoryPeak']."</p>";
			}
			else {
				$GLOBALS['DebugDetails'] = '';
			}

			// Do we have any live chat service code to show in the footer
			$modules = GetConfig('LiveChatModules');
			if(!empty($modules)) {
				$liveChatClass = GetClass('ISC_LIVECHAT');
				$GLOBALS['LiveChatFooterCode'] = $liveChatClass->GetPageTrackingCode('footer');
			}

			// Load our whitelabel file for the front end
			require_once ISC_BASE_PATH.'/includes/whitelabel.php';

			// Load the configuration file for this template
			$poweredBy = 0;
			require_once ISC_BASE_PATH.'/templates/'.GetConfig('template').'/config.php';
			if(isset($GLOBALS['TPL_CFG']['PoweredBy'])) {
				if(!isset($GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$GLOBALS['TPL_CFG']['PoweredBy']])) {
					$GLOBALS['TPL_CFG']['PoweredBy'] = 0;
				}
				$poweredBy = $GLOBALS['TPL_CFG']['PoweredBy'];
			}

			// Showing the powered by?
			$GLOBALS['PoweredBy'] = '';
			if($GLOBALS['ISC_CFG']['DisableFrontEndPoweredBy'] == false && isset($GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$poweredBy])) {
				$GLOBALS['PoweredBy'] = $GLOBALS['ISC_CFG']['TemplatePoweredByLines'][$poweredBy];
			}

			if(empty($GLOBALS['OptimizerConversionScript']) && empty($GLOBALS['OptimizerTrackingScript']) && empty($GLOBALS['OptimizerControlScript'])) {
				$this->setGwoCookieCrossDomain();
			}

			$GLOBALS['SitemapURL_HTML'] = isc_html_escape(SitemapLink());
			$GLOBALS['SNIPPETS']['SitemapLink'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('SitemapLink');

			if (Interspire_TaskManager::hasTasks()) {
				// hasTasks is only implemented for Internal so this will (should) never run for Resque-based task manager
				$GLOBALS['FooterScripts'] .= Interspire_TaskManager::getTriggerHtml('json');
			}

			if (ISC_CATEGORY::areCategoryFlyoutsEnabled()) {
				// this needs to be output from php into the body since it's based on config vars
				// @todo use the stuff gaston is working on instead

				// bgiframe fixes some IE-related issues with CSS menus (like hovering over SELECT elements)
				$GLOBALS['FooterScripts'] .= '<script type="text/javascript" src="'
					. GetConfig('AppPath') . '/javascript/superfish/js/jquery.bgiframe.min.js?'
					. GetConfig('JSCacheToken') . '"></script>' . "\n";
				$GLOBALS['FooterScripts'] .= '<script type="text/javascript" src="'
					. GetConfig('AppPath') . '/javascript/superfish/js/superfish.js?'
					. GetConfig('JSCacheToken') . '"></script>' . "\n";
				$GLOBALS['FooterScripts'] .= '<script type="text/javascript">
	$(function(){
		if (typeof $.fn.superfish == "function") {
			$("ul.sf-menu").superfish({
				delay: ' . ((float)GetConfig('categoryFlyoutMouseOutDelay') * 1000) . ',
				dropShadows: ' . isc_json_encode(GetConfig('categoryFlyoutDropShadow')) . ',
				speed: "fast"
			})
			.find("ul")
			.bgIframe();
		}
	})
</script>
';
			}

			if (GetConfig('FastCartAction') == 'popup' && GetConfig('ShowCartSuggestions')) {
				$GLOBALS['SNIPPETS']['FastCartThickBoxJs'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('FastCartThickBoxJs');
			}
		}
Example #23
0
	/**
	* Returns a javascript representation of this rule
	*
	* @return string
	*/
	public function toJavaScript()
	{
		return isc_json_encode($this);
	}
	private function DeleteImage()
	{
		$successImages = $errorFiles = $return = array();
		ini_set('track_errors', '1');
		// TODO: permission check

		if(!is_array($_POST['deleteimages']) || empty($_POST['deleteimages'])) {
			$return['success'] = false;
			$return['message'] = GetLang('imageManagerNoImagesSelectedDelete');
			die(isc_json_encode($return));
		}

		foreach($_POST['deleteimages'] as $k => $image) {
			if(file_exists($this->GetImagePath() . '/' . $image)){
				if(!@unlink($this->GetImagePath() . '/' . $image)) {
					if(isset($php_errormsg)){
						$msgBits = explode(':', $php_errormsg);
						if(isset($msgBits[1])){
							$errorFiles =  $msgBits[1] .'.';
						}else{
							$errorFiles =  $php_errormsg  .'.';
						}
					}else{
						$errorFiles[] = GetLang('UnableToDelete') . ' ' . $image;
					}
					unset($php_errormsg);
				}else{
					$successImages[] = $image;
				}
			}
		}

		if(!empty($errorFiles)){
			$return['success'] = false;
			$return['message'] = GetLang('imageManagerDeleteErrors') . '<ul><li>'.implode('</li><li>', $errorFiles) . '</li></ul>';
			die(isc_json_encode($return));
		}


		$return['success'] = true;
		$return['successimages'] = $successImages;
		if(count($successImages) == 1){
			$return['message'] = GetLang('imageManagerDeleteSuccessSingle');
		}elseif(count($successImages) > 1){
			$return['message'] = sprintf(GetLang('imageManagerDeleteSuccessMulti'), count($successImages));
		}
		echo isc_json_encode($return);
	}
Example #25
0
	public function rebuildTaxZonePricesAction()
	{
		$pendingChanges = getConfig('taxPendingChanges');

		// Initial request to the rebuild page so show the status window
		if(!isset($_POST['run'])) {
			if(isset($pendingChanges['deleteZone']) || isset($pendingChanges['deleteClass'])) {
				$this->template->assign('isDeleting', true);
			}
			else {
				$this->template->assign('isUpdating', true);
			}

			$this->template->display('settings.tax.pricerebuild.tpl');
			exit;
		}

		$start = 0;
		if(isset($_POST['start'])) {
			$start = (int)$_POST['start'];
		}

		$callableActions = array(
			'deleteZone' => 'deleteTaxPricingByZone',
			'deleteClass' => 'deleteTaxPricingByClass',
			'rebuildPricing' => 'rebuildProductPricing',
		);

		$callback = null;
		foreach($callableActions as $action => $callback) {
			if(isset($pendingChanges[$action])) {
				break;
			}
		}

		// Nothing was found left to do, we're finished rebuilding
		if($callback === null || !isset($pendingChanges[$action])) {
			$GLOBALS['ISC_NEW_CFG']['taxPendingChanges'] = null;
			getClass('ISC_ADMIN_SETTINGS')->commitSettings($messages);
			echo isc_json_encode(array(
				'finished' => true
			));
			exit;
		}

		// If we're still here, then $callback needs to be run
		$changes = $this->$callback($pendingChanges[$action], $start);

		// No changes were made, so we're finished with $action
		if($changes === 0) {
			unset($pendingChanges[$action]);
			$GLOBALS['ISC_NEW_CFG']['taxPendingChanges'] = $pendingChanges;
			getClass('ISC_ADMIN_SETTINGS')->commitSettings($messages);
			$nextStart = 0;
		}
		else {
			$nextStart = $start + $changes;
		}

		echo isc_json_encode(array(
			'action' => $action,
			'changes' => $changes,
			'nextStart' => $nextStart
		));
	}
Example #26
0
	/**
	* Given a picnik token and a remote file, downloads and processes the remote image, updating and cleaning up local data as required, and sets up template data for displaying to the browser
	*
	* @param array $token
	* @param string $remoteFile
	* @return bool True on success, false on error - on error, a template variable named 'PicnikError' will be assigned as non-false
	*/
	public function receivePicnik($token, $remoteFile)
	{
		$this->template->assign('PicnikError', false);

		$sourceFile = $this->getSourceFileForImage($token['imagetype'], $token['imageid']);
		if (!$sourceFile) {
			$this->template->assign('PicnikError', GetLang('PicnikError_NoSourceFile'));
			return false;
		}

		$errorType = null;

		if (!$this->downloadToFile($remoteFile, $sourceFile, $errorType)) {
			if ($errorType == 1) {
				$this->template->assign('PicnikError', GetLang('PicnikError_NoWrite'));
			} else {
				$this->template->assign('PicnikError', GetLang('PicnikError_NoDownload'));
			}
			return false;
		}

		$imageSize = @getimagesize($sourceFile);
		if (!$imageSize) {
			$this->template->assign('PicnikError', GetLang('PicnikError_Invalid'));
			return false;
		}

		$callbackData = array();

		// the source file has been replaced, now regenerate other files based on it if necessary
		switch ($token['imagetype']) {
			case ISC_PICNIK_TYPE_PRODUCTIMAGE:
				$image = new ISC_PRODUCT_IMAGE((int)$token['imageid']);
				$image->removeResizedFiles();
				$image->saveToDatabase(true);
				$callbackData['thumbnail'] = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true);
				$callbackData['zoom'] = $image->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true);
				break;

			case ISC_PICNIK_TYPE_IMAGEMANAGER:
				$callbackData['name'] = basename($sourceFile);
				$callbackData['size'] = Store_Number::niceSize(filesize($sourceFile));
				$callbackData['url'] = GetConfig('ShopPathSSL') . '/' . GetConfig('ImageDirectory') . '/uploaded_images/' . $callbackData['name'];
				$callbackData['dimensions'] = $imageSize[0] . ' x ' . $imageSize[1];
				$callbackData['id'] = md5($callbackData['name']);

				$callbackData['displaywidth'] = $imageSize[0];
				$callbackData['displayheight'] = $imageSize[1];

				if ($callbackData['displaywidth'] > 200) {
					$callbackData['displayheight'] = (200 / $callbackData['displaywidth']) * $callbackData['displayheight'];
					$callbackData['displaywidth']= 200;
				}

				if ($callbackData['displayheight'] > 150) {
					$callbackData['displaywidth'] = (150/$callbackData['displayheight']) * $callbackData['displaywidth'];
					$callbackData['displayheight'] = 150;
				}
				break;
		}

		$this->removeToken($token['picniktokenid']);
		$this->template->assign('PicnikCallbackData', isc_json_encode($callbackData));
		return $callbackData;
	}
Example #27
0
		public function ShowImage()
		{
			if ($this->GetNumImages() == 1) {
				// do no show nav link if there is only 1 image
				$GLOBALS['NavLinkDisplay'] = 'display:none;';
			}

			if($image = $this->GetImage()) {
				// Set product name
				$GLOBALS['ProductName'] = isc_html_escape($this->_prodname);

				// Show we show the "Previous Image" link?
				if($this->GetCurrentImage() == 0 || $this->GetCurrentImage() == 'variation') {
					$GLOBALS['DisablePrevLink'] = "disabled";
				} else {
					$GLOBALS['PrevLink'] = sprintf("%s/productimage.php?product_id=%d&current_image=%d", $GLOBALS['ShopPath'], $this->GetProductId(), $this->GetCurrentImage()-1);
				}

				// Should we show the "Next Image" link?
				if($this->GetNumImages()-1 == $this->GetCurrentImage() || $this->GetCurrentImage() == 'variation') {
					$GLOBALS['DisableNextLink'] = "disabled";
				} else {
					$GLOBALS['NextLink'] = sprintf("%s/productimage.php?product_id=%d&current_image=%d", $GLOBALS['ShopPath'], $this->GetProductId(), $this->GetCurrentImage()+1);
				}

				if($this->GetCurrentImage() == 'variation') {
					$GLOBALS['VariationImage'] = $image;
				}

				$GLOBALS['ProductMaxImageWidth'] = ISC_PRODUCT_IMAGE::getSizeWidth(ISC_PRODUCT_IMAGE_SIZE_ZOOM);
				$GLOBALS['ProductMaxImageHeight'] = ISC_PRODUCT_IMAGE::getSizeHeight(ISC_PRODUCT_IMAGE_SIZE_ZOOM);

				$GLOBALS['ProductMaxTinyWidth'] = ISC_PRODUCT_IMAGE::getSizeWidth(ISC_PRODUCT_IMAGE_SIZE_TINY);
				$GLOBALS['ProductMaxTinyHeight'] = ISC_PRODUCT_IMAGE::getSizeHeight(ISC_PRODUCT_IMAGE_SIZE_TINY);

				$GLOBALS['ProductTinyBoxWidth'] = $GLOBALS['ProductMaxTinyWidth']+4;
				$GLOBALS['ProductTinyBoxHeight'] = $GLOBALS['ProductMaxTinyHeight']+4;

				// a list of images does exist in _prodimages but it's just a list of urls with no sizing information, with the given time frame I have no choice but to re-query the db -ge
				$productImages = ISC_PRODUCT_IMAGE::getProductImagesFromDatabase($this->GetProductId());

				$GLOBALS['TotalImages'] = count($productImages);
				$GLOBALS['ProdImageJavascript'] = '';

				if ($GLOBALS['TotalImages']) {
					$GLOBALS['SNIPPETS']['ProductTinyImages'] = '';
					$GLOBALS['ProductZoomImageURLs'] = array();

					foreach ($productImages as $index => /** @var ISC_PRODUCT_IMAGE */$productImage) {
						$thumbURL = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true);

						$GLOBALS['ProductThumbURL'] = $thumbURL;
						$GLOBALS['ProductThumbIndex'] = $index;
						$GLOBALS['ImageDescription'] = isc_html_escape($productImage->getDescription());

						$GLOBALS['ProdImageJavascript'] .= "ThumbURLs[" . $index . "] = " . isc_json_encode($thumbURL) . ";";
						$GLOBALS['ProdImageJavascript'] .= "ImageDescriptions[" . $index . "]=" . isc_json_encode($GLOBALS['ImageDescription']) . ";";

						$GLOBALS['ProductTinyImageURL'] = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_TINY, true);

						$resizedTinyDimension = $productImage->getResizedFileDimensions(ISC_PRODUCT_IMAGE_SIZE_TINY, true);
						$GLOBALS['TinyImageWidth'] = $resizedTinyDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_WIDTH];
						$GLOBALS['TinyImageHeight'] = $resizedTinyDimension[ISC_PRODUCT_IMAGE_DIMENSIONS_HEIGHT];

						$GLOBALS['TinyImageTopPadding'] = floor(($GLOBALS['ProductMaxTinyHeight'] - $GLOBALS['TinyImageHeight']) / 2);

						$GLOBALS['TinyImageClickJavascript'] = "showProductZoomImage(" . $index . ");";
						$GLOBALS['SNIPPETS']['ProductTinyImages'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ProductTinyImage");
					}
				}

				$GLOBALS['CurrentImageIndex'] = $this->GetCurrentImage();
				$GLOBALS['ImageFile'] = $image;
				$GLOBALS['ISC_CLASS_TEMPLATE']->SetTemplate("productimage");
				$GLOBALS['ISC_CLASS_TEMPLATE']->ParseTemplate();
			}
		}
Example #28
0
		public function EditProductStep1($MsgDesc = "", $MsgStatus = "", $PreservePost=false)
		{
			if ($MsgDesc != "") {
				$GLOBALS['Message'] = MessageBox($MsgDesc, $MsgStatus);
			}

			// Show the form to edit a product
			$prodId = (int)$_REQUEST['productId'];
			$z = 0;
			$arrData = array();
			$arrCustomFields = array();

			// assign product comparison options to the template
			$this->template->assign('shoppingComparisonModules', $this->getComparisonOptions($prodId));

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

			$GLOBALS['ServerFiles'] = $this->_GetImportFilesOptions();

			$GLOBALS['ISC_CLASS_ADMIN_CATEGORY'] = GetClass('ISC_ADMIN_CATEGORY');

			// load image manager language file as the lang vars are used by product image management
			$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->LoadLangFile('imagemanager');

			// Make sure the product exists
			if (ProductExists($prodId)) {
				$this->_GetProductData($prodId, $arrData);

				// Does this user have permission to edit this product?
				if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId() && $arrData['prodvendorid'] != $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
					FlashMessage(GetLang('Unauthorized'), MSG_ERROR, 'index.php?ToDo=viewProducts');
				}

				if($PreservePost == true) {
					$this->_GetProductData(0, $arrData);
					$this->_GetCustomFieldData(0, $arrCustomFields);
					$GLOBALS['ProductFields'] = $this->_GetProductFieldsLayout(0);
				} else {
					$this->_GetCustomFieldData($prodId, $arrCustomFields);
					$GLOBALS['ProductFields'] = $this->_GetProductFieldsLayout($prodId);
				}

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

				if(isset($_POST['currentTab'])) {
					$GLOBALS['CurrentTab'] = (int)$_POST['currentTab'];
				}
				else {
					$GLOBALS['CurrentTab'] = 0;
				}

				$GLOBALS['FormAction'] = "editProduct2";
				$GLOBALS['ProductId'] = $prodId;
				$GLOBALS['Title'] = GetLang('EditProductTitle');
				$GLOBALS['Intro'] = GetLang('EditProductIntro');
				$GLOBALS["ProdType_" . $arrData['prodtype']] = 'checked="checked"';
				$GLOBALS['ProdType'] = $arrData['prodtype'] - 1;
				$GLOBALS['ProdCode'] = isc_html_escape($arrData['prodcode']);
				$GLOBALS['ProdHash'] = '';

				// set videos data
				$GLOBALS['YouTubeVideos'] = '';
				$videosArray = array();
				if(isset($arrData['product_videos']) && !empty($arrData['product_videos'])) {
					foreach($arrData['product_videos'] as $videoId => $videoData) {
						$videosArray[] = $videoId;
					}
					$GLOBALS['YouTubeVideos'] = isc_html_escape(implode(',', $videosArray));
				}

				// --- BEGIN PRODUCT IMAGES

				// create a html template for use in javascript when adding product image rows and store it as a javascript string
				$GLOBALS['productImage_thumbnailWidth'] = ISC_PRODUCT_IMAGE::getSizeWidth(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL);
				$GLOBALS['productImage_thumbnailHeight'] = ISC_PRODUCT_IMAGE::getSizeHeight(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL);
				$GLOBALS['productImage_newRowTemplate_js'] = isc_json_encode($this->template->render('product.form.images.row.tpl'));
				$GLOBALS['sessionid'] = session_id();
				$_SESSION['STORESUITE_CP_TOKEN'] = $_COOKIE['STORESUITE_CP_TOKEN'];

				// send through the file extensions that should be accepted as images
				$extensions = '*.' . implode(';*.', ISC_IMAGE_LIBRARY_FACTORY::getSupportedImageExtensions());
				$GLOBALS['productImage_swfUploadFileTypes_js'] = isc_json_encode($extensions);

				// generate statements to initialise new productimages as javascript objects
				$GLOBALS['productImage_javascriptInitialiseCode'] = '';
				foreach ($arrData['product_images'] as /** @var ISC_PRODUCT_IMAGE */$productImage) {

					$baseThumbnail = 'false';
					if ($productImage->getIsThumbnail()) {
						$baseThumbnail = 'true';
					}

					try {
						$preview = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_THUMBNAIL, true);
						$zoom = $productImage->getResizedUrl(ISC_PRODUCT_IMAGE_SIZE_ZOOM, true);
						$original = $productImage->getSourceUrl();
					} catch (Exception $Exception) {
						$preview = false;
						$zoom = false;
						$original = false;
					}

					$GLOBALS['productImage_javascriptInitialiseCode'] .= sprintf(
						'new ProductImages.Image({id:%1$d,product:%8$d,preview:%2$s,zoom:%3$s,original:%9$s,description:%4$s,baseThumbnail:%5$s,sort:%7$d});',
						/*1*/ $productImage->getProductImageId(),
						/*2*/ isc_json_encode($preview),
						/*3*/ isc_json_encode($zoom),
						/*4*/ isc_json_encode($productImage->getDescription()),
						/*5*/ $baseThumbnail,
						/*6*/ null,
						/*7*/ $productImage->getSort(),
						/*8*/ $productImage->getProductId(),
						/*9*/ isc_json_encode($original)
					);
				}

				// done setting up the product images template, render it and put it into the main template
				$GLOBALS['productImagesList'] = $this->template->render('product.form.images.tpl');

				// --- END PRODUCT IMAGES

				// Get the list of tax classes and assign them
				$this->template->assign('taxClasses', array(
					0 => getLang('DefaultTaxClass')
				) + getClass('ISC_TAX')->getTaxClasses());

				$GLOBALS['ProdTags'] = isc_html_escape($arrData['prodtags']);


				$GLOBALS['ProdName'] = isc_html_escape($arrData['prodname']);
				$visibleCategories = array();
				if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
					$vendorData = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendor();
					if($vendorData['vendoraccesscats']) {
						$visibleCategories = explode(',', $vendorData['vendoraccesscats']);
					}
				}

				$GLOBALS['CategoryOptions'] = $GLOBALS["ISC_CLASS_ADMIN_CATEGORY"]->GetCategoryOptions($arrData['prodcats'], "<option %s value='%d'>%s</option>", "selected=\"selected\"", "", false, '', $visibleCategories);
				$GLOBALS['RelatedCategoryOptions'] = $GLOBALS["ISC_CLASS_ADMIN_CATEGORY"]->GetCategoryOptions(0, "<option %s value='%d'>%s</option>", "selected=\"selected\"", "- ", false);

				$wysiwygOptions = array(
					'id'		=> 'wysiwyg',
					'width'		=> '100%',
					'height'	=> '500px',
					'value'		=> $arrData['proddesc']
				);
				$GLOBALS['WYSIWYG'] = GetClass('ISC_ADMIN_EDITOR')->GetWysiwygEditor($wysiwygOptions);

				$GLOBALS['ProdSearchKeywords'] = isc_html_escape($arrData['prodsearchkeywords']);
				$GLOBALS['ProdAvailability'] = isc_html_escape($arrData['prodavailability']);
				$GLOBALS['ProdPrice'] = number_format($arrData['prodprice'], GetConfig('DecimalPlaces'), GetConfig('DecimalToken'), "");

				if (CFloat($arrData['prodcostprice']) > 0) {
					$GLOBALS['ProdCostPrice'] = number_format($arrData['prodcostprice'], GetConfig('DecimalPlaces'), GetConfig('DecimalToken'), "");
				}

				if (CFloat($arrData['prodretailprice']) > 0) {
					$GLOBALS['ProdRetailPrice'] = number_format($arrData['prodretailprice'], GetConfig('DecimalPlaces'), GetConfig('DecimalToken'), "");
				}

				if (CFloat($arrData['prodsaleprice']) > 0) {
					$GLOBALS['ProdSalePrice'] = number_format($arrData['prodsaleprice'], GetConfig('DecimalPlaces'), GetConfig('DecimalToken'), "");
				}

				$GLOBALS['ProdSortOrder'] = $arrData['prodsortorder'];

				if ($arrData['prodvisible'] == 1) {
					$GLOBALS['ProdVisible'] = "checked";
				}

				if ($arrData['prodfeatured'] == 1) {
					$GLOBALS['ProdFeatured'] = "checked";
				}

				if($GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendorId()) {
					$GLOBALS['HideStoreFeatured'] = 'display: none';
				}
				else if(!gzte11(ISC_HUGEPRINT) || !$arrData['prodvendorid']) {
					$GLOBALS['HideVendorFeatured'] = 'display: none';
				}

				if($arrData['prodvendorfeatured'] == 1) {
					$GLOBALS['ProdVendorFeatured'] = 'checked="checked"';
				}

				if($arrData['prodallowpurchases'] == 1) {
					$GLOBALS['ProdAllowPurchases'] = 'checked="checked"';
				}
				else {
					if($arrData['prodhideprice'] == 1) {
						$GLOBALS['ProdHidePrice'] = 'checked="checked"';
					}
					$GLOBALS['ProdCallForPricingLabel'] = isc_html_escape($arrData['prodcallforpricinglabel']);
				}

				$GLOBALS['ProdWarranty'] = $arrData['prodwarranty'];
				$GLOBALS['ProdWeight'] = number_format($arrData['prodweight'], GetConfig('DimensionsDecimalPlaces'), GetConfig('DimensionsDecimalToken'), "");

				if (CFloat($arrData['prodwidth']) > 0) {
					$GLOBALS['ProdWidth'] = number_format($arrData['prodwidth'], GetConfig('DimensionsDecimalPlaces'), GetConfig('DimensionsDecimalToken'), "");
				}

				if (CFloat($arrData['prodheight']) > 0) {
					$GLOBALS['ProdHeight'] = number_format($arrData['prodheight'], GetConfig('DimensionsDecimalPlaces'), GetConfig('DimensionsDecimalToken'), "");
				}

				if (CFloat($arrData['proddepth']) > 0) {
					$GLOBALS['ProdDepth'] = number_format($arrData['proddepth'], GetConfig('DimensionsDecimalPlaces'), GetConfig('DimensionsDecimalToken'), "");
				}

				if (CFloat($arrData['prodfixedshippingcost']) > 0) {
					$GLOBALS['ProdFixedShippingCost'] = number_format($arrData['prodfixedshippingcost'], GetConfig('DecimalPlaces'), GetConfig('DecimalToken'), "");
				}

				if ($arrData['prodfreeshipping'] == 1) {
					$GLOBALS['FreeShipping'] = 'checked="checked"';
				}

				if($arrData['prodrelatedproducts'] == -1) {
					$GLOBALS['IsProdRelatedAuto'] = 'checked="checked"';
				}
				else if(isset($arrData['prodrelated'])) {
					$GLOBALS['RelatedProductOptions'] = "";

					foreach ($arrData['prodrelated'] as $r) {
						$GLOBALS['RelatedProductOptions'] .= sprintf("<option value='%d'>%s</option>", (int) $r[0], isc_html_escape($r[1]));
					}
				}

				$GLOBALS['CurrentStockLevel'] = $arrData['prodcurrentinv'];
				$GLOBALS['LowStockLevel'] = $arrData['prodlowinv'];
				$GLOBALS["InvTrack_" . $arrData['prodinvtrack']] = 'checked="checked"';

				if ($arrData['prodinvtrack'] == 1) {
					$GLOBALS['OptionButtons'] = "ToggleProductInventoryOptions(true);";
				} else {
					$GLOBALS['OptionButtons'] = "ToggleProductInventoryOptions(false);";
				}

				if ($arrData['prodoptionsrequired'] == 1) {
					$GLOBALS['OptionsRequired'] = 'checked="checked"';
				}

				if ($arrData['prodtype'] == 1) {
					$GLOBALS['HideProductInventoryOptions'] = "none";
				}

				$GLOBALS['EnterOptionPrice'] = sprintf(GetLang('EnterOptionPrice'), GetConfig('CurrencyToken'), GetConfig('CurrencyToken'));
				$GLOBALS['EnterOptionWeight'] = sprintf(GetLang('EnterOptionWeight'), GetConfig('WeightMeasurement'));
				$GLOBALS['HideCustomFieldLink'] = "none";

				if(getConfig('taxEnteredWithPrices') == TAX_PRICES_ENTERED_INCLUSIVE) {
					$this->template->assign('enterPricesWithTax', true);
				}

				$GLOBALS['ProductFields'] = $this->_GetProductFieldsLayout($prodId);

				$GLOBALS['CustomFields'] = '';
				$GLOBALS['CustomFieldKey'] = 0;

				if (!empty($arrCustomFields)) {
					foreach ($arrCustomFields as $f) {
						$GLOBALS['CustomFieldName'] = isc_html_escape($f['name']);
						$GLOBALS['CustomFieldValue'] = isc_html_escape($f['value']);
						$GLOBALS['CustomFieldLabel'] = $this->GetFieldLabel(($GLOBALS['CustomFieldKey']+1), GetLang('CustomField'));

						if (!$GLOBALS['CustomFieldKey']) {
							$GLOBALS['HideCustomFieldDelete'] = 'none';
						} else {
							$GLOBALS['HideCustomFieldDelete'] = '';
						}

						$GLOBALS['CustomFields'] .= $this->template->render('Snippets/CustomFields.html');

						$GLOBALS['CustomFieldKey']++;
					}
				}

				// Add one more custom field
				$GLOBALS['CustomFieldName'] = '';
				$GLOBALS['CustomFieldValue'] = '';
				$GLOBALS['CustomFieldLabel'] = $this->GetFieldLabel(($GLOBALS['CustomFieldKey']+1), GetLang('CustomField'));

				if (!$GLOBALS['CustomFieldKey']) {
					$GLOBALS['HideCustomFieldDelete'] = 'none';
				} else {
					$GLOBALS['HideCustomFieldDelete'] = '';
				}

				$GLOBALS['CustomFields'] .= $this->template->render('Snippets/CustomFields.html');

				$GLOBALS['ProductHash'] = '';

				// Get a list of any downloads associated with this product
				$GLOBALS['DownloadsGrid'] = $this->GetDownloadsGrid($prodId);
				$GLOBALS['ISC_LANG']['MaxUploadSize'] = sprintf(GetLang('MaxUploadSize'), GetMaxUploadSize());
				if($GLOBALS['DownloadsGrid'] == '') {
					$GLOBALS['DisplayDownloaadGrid'] = "none";
				}

				// Get the brands as select options
				$GLOBALS['ISC_CLASS_ADMIN_BRANDS'] = GetClass('ISC_ADMIN_BRANDS');
				$GLOBALS['BrandNameOptions'] = $GLOBALS['ISC_CLASS_ADMIN_BRANDS']->GetBrandsAsOptions($arrData['prodbrandid']);
				$GLOBALS['SaveAndAddAnother'] = GetLang('SaveAndContinueEditing');

				// Get a list of all layout files
				$layoutFile = 'product.html';
				if($arrData['prodlayoutfile'] != '') {
					$layoutFile = $arrData['prodlayoutfile'];
				}
				$GLOBALS['LayoutFiles'] = GetCustomLayoutFilesAsOptions("product.html", $layoutFile);

				$GLOBALS['ProdPageTitle'] = isc_html_escape($arrData['prodpagetitle']);
				$GLOBALS['ProdMetaKeywords'] = isc_html_escape($arrData['prodmetakeywords']);
				$GLOBALS['ProdMetaDesc'] = isc_html_escape($arrData['prodmetadesc']);
				$GLOBALS['SaveAndAddAnother'] = GetLang('SaveAndContinueEditing');

				if(!gzte11(ISC_MEDIUMPRINT)) {
					$GLOBALS['HideInventoryOptions'] = "none";
				}
				else {
					$GLOBALS['HideInventoryOptions'] = '';
				}

				// Does this product have a variation assigned to it?
				$GLOBALS['ProductVariationExisting'] = $arrData['prodvariationid'];

				if($arrData['prodvariationid'] > 0) {
					$GLOBALS['IsYesVariation'] = 'checked="checked"';
				}
				else {
					$GLOBALS['IsNoVariation'] = 'checked="checked"';
					$GLOBALS['HideVariationList'] = "none";
					$GLOBALS['HideVariationCombinationList'] = "none";
				}

				// If there are no variations then disable the option to choose one
				$numVariations = 0;
				$GLOBALS['VariationOptions'] = $this->GetVariationsAsOptions($numVariations, $arrData['prodvariationid']);

				if($numVariations == 0) {
					$GLOBALS['VariationDisabled'] = "DISABLED";
					$GLOBALS['VariationColor'] = "#CACACA";
					$GLOBALS['IsNoVariation'] = 'checked="checked"';
					$GLOBALS['IsYesVariation'] = "";
					$GLOBALS['HideVariationCombinationList'] = "none";
				}
				else {
					// Load the variation combinations
					if($arrData['prodinvtrack'] == 2) {
						$show_inv_fields = true;
					}
					else {
						$show_inv_fields = false;
					}

					$GLOBALS['VariationCombinationList'] = $this->_LoadVariationCombinationsTable($arrData['prodvariationid'], $show_inv_fields, $arrData['productid']);
				}

				$GLOBALS['WrappingOptions'] = $this->BuildGiftWrappingSelect(explode(',', $arrData['prodwrapoptions']));
				$GLOBALS['HideGiftWrappingOptions'] = 'display: none';
				if($arrData['prodwrapoptions'] == 0) {
					$GLOBALS['WrappingOptionsDefaultChecked'] = 'checked="checked"';
				}
				else if($arrData['prodwrapoptions'] == -1) {
					$GLOBALS['WrappingOptionsNoneChecked'] = 'checked="checked"';
				}
				else {
					$GLOBALS['HideGiftWrappingOptions'] = '';
					$GLOBALS['WrappingOptionsCustomChecked'] = 'checked="checked"';
				}

				if(!gzte11(ISC_HUGEPRINT)) {
					$GLOBALS['HideVendorOption'] = 'display: none';
				}
				else {
					$vendorData = $GLOBALS['ISC_CLASS_ADMIN_AUTH']->GetVendor();
					if(isset($vendorData['vendorid'])) {
						$GLOBALS['HideVendorSelect'] = 'display: none';
						$GLOBALS['CurrentVendor'] = isc_html_escape($vendorData['vendorname']);
					}
					else {
						$GLOBALS['HideVendorLabel'] = 'display: none';
						$GLOBALS['VendorList'] = $this->BuildVendorSelect($arrData['prodvendorid']);
					}
				}

				// Display the discount rules
				if ($PreservePost == true) {
					$GLOBALS['DiscountRules'] = $this->GetDiscountRules(0);
				} else {
					$GLOBALS['DiscountRules'] = $this->GetDiscountRules($prodId);
				}

				// Hide if we are not enabled
				if (!GetConfig('BulkDiscountEnabled')) {
					$GLOBALS['HideDiscountRulesWarningBox'] = '';
					$GLOBALS['DiscountRulesWarningText'] = GetLang('DiscountRulesNotEnabledWarning');
					$GLOBALS['DiscountRulesWithWarning'] = 'none';

				// Also hide it if this product has variations
				} else if (isset($arrData['prodvariationid']) && isId($arrData['prodvariationid'])) {
					$GLOBALS['HideDiscountRulesWarningBox'] = '';
					$GLOBALS['DiscountRulesWarningText'] = GetLang('DiscountRulesVariationWarning');
					$GLOBALS['DiscountRulesWithWarning'] = 'none';
				} else {
					$GLOBALS['HideDiscountRulesWarningBox'] = 'none';
					$GLOBALS['DiscountRulesWithWarning'] = '';
				}

				$GLOBALS['DiscountRulesEnabled'] = (int)GetConfig('BulkDiscountEnabled');

				if(!$GLOBALS['ISC_CLASS_ADMIN_AUTH']->HasPermission(AUTH_Create_Category)) {
					$GLOBALS['HideCategoryCreation'] = 'display: none';
				}

				$GLOBALS['EventDateFieldName'] = $arrData['prodeventdatefieldname'];

				if ($GLOBALS['EventDateFieldName'] == null) {
					$GLOBALS['EventDateFieldName'] = GetLang('EventDateDefault');
				}

				if ($arrData['prodeventdaterequired'] == 1) {
					$GLOBALS['EventDateRequired'] = 'checked="checked"';
					$from_stamp = $arrData['prodeventdatelimitedstartdate'];
					$to_stamp = $arrData['prodeventdatelimitedenddate'];
				} else {
					$from_stamp = isc_gmmktime(0, 0, 0, isc_date("m"), isc_date("d"), isc_date("Y"));
					$to_stamp = isc_gmmktime(0, 0, 0, isc_date("m")+1, isc_date("d"), isc_date("Y"));
				}
				if ($arrData['prodeventdatelimited'] == 1) {
					$GLOBALS['LimitDates'] = 'checked="checked"';
				}

				$GLOBALS['LimitDateOption1'] = '';
				$GLOBALS['LimitDateOption2'] = '';
				$GLOBALS['LimitDateOption3'] = '';

				switch ($arrData['prodeventdatelimitedtype']) {

					case 1 :
						$GLOBALS['LimitDateOption1'] = 'selected="selected"';
					break;
					case 2 :
						$GLOBALS['LimitDateOption2'] = 'selected="selected"';
					break;
					case 3 :
						$GLOBALS['LimitDateOption3'] = 'selected="selected"';
					break;
				}

				// Set the global variables for the select boxes

				$from_day = isc_date("d", $from_stamp);
				$from_month = isc_date("m", $from_stamp);
				$from_year = isc_date("Y", $from_stamp);

				$to_day = isc_date("d", $to_stamp);
				$to_month = isc_date("m", $to_stamp);
				$to_year = isc_date("Y", $to_stamp);

				$GLOBALS['OverviewFromDays'] = $this->_GetDayOptions($from_day);
				$GLOBALS['OverviewFromMonths'] = $this->_GetMonthOptions($from_month);
				$GLOBALS['OverviewFromYears'] = $this->_GetYearOptions($from_year);

				$GLOBALS['OverviewToDays'] = $this->_GetDayOptions($to_day);
				$GLOBALS['OverviewToMonths'] = $this->_GetMonthOptions($to_month);
				$GLOBALS['OverviewToYears'] = $this->_GetYearOptions($to_year);

				$GLOBALS['ProdMYOBAsset'] = isc_html_escape($arrData['prodmyobasset']);
				$GLOBALS['ProdMYOBIncome'] = isc_html_escape($arrData['prodmyobincome']);
				$GLOBALS['ProdMYOBExpense'] = isc_html_escape($arrData['prodmyobexpense']);

				$GLOBALS['ProdPeachtreeGL'] = isc_html_escape($arrData['prodpeachtreegl']);

				$GLOBALS['ProdCondition' . $arrData['prodcondition'] . 'Selected'] = 'selected="selected"';
				if ($arrData['prodshowcondition']) {
					$GLOBALS['ProdShowCondition'] = 'checked="checked"';
				}

				//Google website optimizer
				$GLOBALS['GoogleWebsiteOptimizerIntro'] = GetLang('ProdGoogleWebsiteOptimizerIntro');

				$GLOBALS['HideOptimizerConfigForm'] = 'display:none;';
				$GLOBALS['CheckEnableOptimizer'] = '';

				$GLOBALS['SkipOptimizerConfirmMsg'] = 'true';
				$enabledOptimizers = GetConfig('OptimizerMethods');
				if(!empty($enabledOptimizers)) {
					foreach ($enabledOptimizers as $id => $date) {
						GetModuleById('optimizer', $optimizerModule, $id);
						if ($optimizerModule->_testPage == 'products' || $optimizerModule->_testPage == 'all') {
							$GLOBALS['SkipOptimizerConfirmMsg'] = 'false';
							break;
						}
					}
				}

				if($arrData['product_enable_optimizer'] == '1') {
					$GLOBALS['HideOptimizerConfigForm'] = '';
					$GLOBALS['CheckEnableOptimizer'] = 'Checked';
				}

				if ($arrData['prodminqty']) {
					$this->template->assign('prodminqty', $arrData['prodminqty']);
				}

				if ($arrData['prodmaxqty']) {
					$this->template->assign('prodmaxqty', $arrData['prodmaxqty']);
				}

				$optimizer = getClass('ISC_ADMIN_OPTIMIZER');
				$GLOBALS['OptimizerConfigForm'] = $optimizer->showPerItemConfigForm('product', $prodId, prodLink($arrData['prodname']));

				if ($arrData['prodpreorder'] && $arrData['prodreleasedateremove'] && time() >= $arrData['prodreleasedate']) {
					// pre-order release date has passed and remove is ticked, remove it now for the edit form at least - saving it will commit it to the db
					$arrData['prodpreorder'] = 0;
					$arrData['prodreleasedate'] = 0;
					$arrData['prodreleasedateremove'] = 0;
				}

				// note: prodpreorder is a database column does not map directly to a form field, it'll be set to 1 if _prodorderable is 'pre', along with prodallowpurchases to 1
				// note: _prodorderable is a form field that does not map to a database column
				if (!$arrData['prodallowpurchases']) {
					$this->template->assign('_prodorderable', 'no');
				} else if ($arrData['prodpreorder']) {
					$this->template->assign('_prodorderable', 'pre');
				} else {
					$this->template->assign('_prodorderable', 'yes');
				}

				$this->template->assign('prodreleasedateremove', $arrData['prodreleasedateremove']);

				if (isset($arrData['prodpreordermessage']) && $arrData['prodpreordermessage']) {
					$this->template->assign('prodpreordermessage', $arrData['prodpreordermessage']);
				} else {
					$this->template->assign('prodpreordermessage', GetConfig('DefaultPreOrderMessage'));
				}

				if ($arrData['prodreleasedate']) {
					$this->template->assign('prodreleasedate', isc_date('m/d/Y', $arrData['prodreleasedate']));
				}

				// Open Graph Settings
				$this->template->assign('openGraphTypes', ISC_OPENGRAPH::getObjectTypes(true));
				$this->template->assign('openGraphSelectedType', $arrData['opengraph_type']);
				$this->template->assign('openGraphUseProductName', (bool)$arrData['opengraph_use_product_name']);
				$this->template->assign('openGraphTitle', $arrData['opengraph_title']);
				$this->template->assign('openGraphUseMetaDescription', (bool)$arrData['opengraph_use_meta_description']);
				$this->template->assign('openGraphDescription', $arrData['opengraph_description']);
				$this->template->assign('openGraphUseImage', (bool)$arrData['opengraph_use_image']);

				// UPC
				$this->template->assign('ProdUPC', isc_html_escape($arrData['upc']));

				// Google Checkout
				$this->template->assign('ProdDisableGoogleCheckout', isc_html_escape($arrData['disable_google_checkout']));

				$GLOBALS['SaveAndAddAnother'] = GetLang('SaveAndContinueEditing');
				$this->setupProductLanguageString();
				$this->template->display('product.form.tpl');
			} else {
				// The product doesn't exist
				if ($GLOBALS["ISC_CLASS_ADMIN_AUTH"]->HasPermission(AUTH_Manage_Products)) {
					$this->ManageProducts(GetLang('ProductDoesntExist'), MSG_ERROR);
				} else {
					$GLOBALS['ISC_CLASS_ADMIN_ENGINE']->DoHomePage(GetLang('Unauthorized'), MSG_ERROR);
				}
			}
		}
Example #29
0
/**
 * Shopping Cart equivalent function for json_encode. This should be used instead of json_encode
 * as it does not handle anything in regards to character sets - it simply treats the strings as they're
 * passed, whilst json_encode only outputs in UTF-8.
 *
 * @param mixed The data to be JSON formatted.
 * @return string The JSON generated data.
 */
function isc_json_encode($a = false)
{
    if (is_null($a)) {
        return 'null';
    } else {
        if ($a === false) {
            return 'false';
        } else {
            if ($a === true) {
                return 'true';
            } else {
                if (is_scalar($a)) {
                    if (is_float($a)) {
                        // Always use "." for floats.
                        return floatval(str_replace(",", ".", strval($a)));
                    }
                    if (is_string($a)) {
                        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\\"'));
                        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
                    } else {
                        return $a;
                    }
                }
            }
        }
    }
    $isList = true;
    for ($i = 0, reset($a); $i < count($a); $i++, next($a)) {
        if (key($a) !== $i) {
            $isList = false;
            break;
        }
    }
    $result = array();
    if ($isList) {
        foreach ($a as $v) {
            $result[] = isc_json_encode($v);
        }
        return '[' . implode(',', $result) . ']';
    } else {
        foreach ($a as $k => $v) {
            $result[] = isc_json_encode($k) . ':' . isc_json_encode($v);
        }
        return '{' . implode(',', $result) . '}';
    }
}
 private function importAccountingSettingsSyncNodes()
 {
     $rtn = array('status' => false);
     if (!array_key_exists('section', $_POST) || $_POST['section'] == '') {
         print isc_json_encode($rtn);
         exit;
     }
     if (!array_key_exists('moduleid', $_POST) || $_POST['moduleid'] == '') {
         print isc_json_encode($rtn);
         exit;
     }
     if (array_key_exists('reset', $_POST) && $_POST['reset'] == 1) {
         if (!$this->resetAccountingSettingsSyncNodes($_POST['section'])) {
             print isc_json_encode($rtn);
             exit;
         }
     }
     if (!array_key_exists('AccountingImport', $_SESSION) || !array_key_exists($_POST['section'], $_SESSION['AccountingImport'])) {
         print isc_json_encode($rtn);
         exit;
     }
     GetModuleById("accounting", $module, $_REQUEST['moduleid']);
     if (!$module) {
         print isc_json_encode($rtn);
         exit;
     }
     $rtn['status'] = true;
     $session =& $_SESSION['AccountingImport'][$_POST['section']];
     if (empty($session['nodeidx'])) {
         $rtn['percent'] = 100;
         $rtn['total'] = 0;
         print isc_json_encode($rtn);
         exit;
     }
     $importAmount = ceil($session['total'] / 100);
     $importAmount = max(1, $importAmount);
     $rtn['total'] = $importAmount;
     for ($i = 0; $i < $importAmount; $i++) {
         if (!isset($session['nodeidx'][$i])) {
             break;
         }
         $module->importSync($_POST['section'], $session['nodeidx'][$i]);
         unset($session['nodeidx'][$i]);
     }
     if (!empty($session['nodeidx'])) {
         $_SESSION['AccountingImport'][$_POST['section']]['nodeidx'] = array_values($_SESSION['AccountingImport'][$_POST['section']]['nodeidx']);
         $total = $session['total'] - count($session['nodeidx']);
         $rtn['percent'] = round($total / $session['total'] * 100);
     } else {
         $rtn['percent'] = 100;
     }
     print isc_json_encode($rtn);
     exit;
 }