Esempio n. 1
0
	function print_script_request () {
		global $compress_scripts;
		$Settings =& EcartSettings();

		$zip = $compress_scripts ? 1 : 0;
		if ( $zip && defined('ENFORCE_GZIP') && ENFORCE_GZIP )
			$zip = 'gzip';

		if ( !empty($this->concat) ) {
			$ver = md5("$this->concat_version");
			if ($Settings->get('script_server') == 'plugin') {
				$src = trailingslashit(get_bloginfo('url')) . "?sjsl=" . trim($this->concat, ', ') . "&c={$zip}&ver=$ver";
				if (is_ssl()) $src = str_replace('http://','https://',$src);
			} else $src = $this->base_url . "scripts.php?c={$zip}&load=" . trim($this->concat, ', ') . "&ver=$ver";
			echo "<script type='text/javascript' src='" . esc_attr($src) . "'></script>\n";
		}

		if ( !empty($this->print_code) ) {
			echo "<script type='text/javascript'>\n";
			echo "/* <![CDATA[ */\n";
			echo $this->print_code;
			echo "/* ]]> */\n";
			echo "</script>\n";
		}

		if ( !empty($this->print_html) )
			echo $this->print_html;
	}
Esempio n. 2
0
function contact_meta_box ($Purchase) {
	$customer_url = add_query_arg(array('page'=>'ecart-customers','id'=>$Purchase->customer),admin_url('admin.php'));
	$customer_url = apply_filters('ecart_order_customer_url',$customer_url);

	$email_url = 'mailto:'.($Purchase->email).'?subject='.sprintf(__('RE: %s: Order #%s','Ecart'),get_bloginfo('sitename'),$Purchase->id);
	$email_url = apply_filters('ecart_order_customer_email_url',$email_url);

	$phone_url = 'callto:'.preg_replace('/[^\d+]/','',$Purchase->phone);
	$phone_url = apply_filters('ecart_order_customer_phone_url',$phone_url);

	$Settings =& EcartSettings();
	$accounts = $Settings->get('account_system');
	$wp_user = false;
	if ($accounts == "wordpress") {
		$Customer = new Customer($Purchase->customer);
		$wp_user = get_userdata($Customer->wpuser);
		$edituser_url = add_query_arg('user_id',$Customer->wpuser,admin_url('user-edit.php'));
		$edituser_url = apply_filters('ecart_order_customer_wpuser_url',$edituser_url);
	}


?>
	<p class="customer name"><a href="<?php echo esc_url($customer_url); ?>"><?php echo esc_html("{$Purchase->firstname} {$Purchase->lastname}"); ?></a><?php
		if ($wp_user) echo ' (<a href="'.esc_url($edituser_url).'">'.esc_html($wp_user->user_login).'</a>)';
	?></p>
	<?php echo !empty($Purchase->company)?'<p class="customer company">'.esc_html($Purchase->company).'</p>':''; ?>
	<?php echo !empty($Purchase->email)?'<p class="customer email"><a href="'.esc_url($email_url).'">'.esc_html($Purchase->email).'</a></p>':''; ?>
	<?php echo !empty($Purchase->phone)?'<p class="customer phone"><a href="'.esc_attr($phone_url).'">'.esc_html($Purchase->phone).'</a></p>':''; ?>
	<p class="customer <?php echo ($Purchase->Customer->marketing == "yes")?'marketing':'nomarketing'; ?>"><?php ($Purchase->Customer->marketing == "yes")?_e('Agreed to marketing','Ecart'):_e('No marketing','Ecart'); ?></p>
<?php
}
Esempio n. 3
0
	/**
	 * Establish event listeners
	 *	 
	 * @since 1.1
	 *
	 * @return void
	 **/
	function listeners () {
		$Settings =& EcartSettings();
		$this->confirm = ($Settings->get('order_confirmation') == "always");
		$this->accounts = $Settings->get('account_system');
		$this->validated = false; // Reset the order validation flag

		add_action('ecart_process_shipmethod', array(&$this,'shipmethod'));
		add_action('ecart_process_checkout', array(&$this,'checkout'));
		add_action('ecart_confirm_order', array(&$this,'confirmed'));
		add_action('ecart_process_order', array(&$this,'validate'),7);

		add_action('ecart_process_free_order',array(&$this,'freebie'));
		add_action('ecart_update_destination',array(&$this->Shipping,'destination'));
		add_action('ecart_create_purchase',array(&$this,'purchase'));
		add_action('ecart_order_notifications',array(&$this,'notify'));

		// Schedule for the absolute last action to be run
		add_action('ecart_order_success',array(&$this,'success'),100);

		add_action('ecart_resession',array(&$this->Cart,'clear'));
		add_action('ecart_resession',array(&$this,'clear'));

		// Collect available payment methods from active gateways
		// Schedule for after the gateways are loaded  (priority 20)
		add_action('ecart_init',array(&$this,'payoptions'),20);

		// Select the default gateway processor
		// Schedule for after the gateways are loaded (priority 20)
		add_action('ecart_init',array(&$this,'processor'),20);

		// Set locking timeout for concurrency operation protection
		if (!defined('ECART_TXNLOCK_TIMEOUT')) define('ECART_TXNLOCK_TIMEOUT',10);

	}
Esempio n. 4
0
	/**
	 * Loads images assigned to this category
	 *	 
	 * @since 1.0
	 * @version 1.1
	 *
	 * @return boolean Successful load or not
	 **/
	function load_images () {
		$db = DB::get();
		$Settings =& EcartSettings();

		$ordering = $Settings->get('product_image_order');
		$orderby = $Settings->get('product_image_orderby');

		if ($ordering == "RAND()") $orderby = $ordering;
		else $orderby .= ' '.$ordering;
		$table = DatabaseObject::tablename(CategoryImage::$table);
		if (empty($this->id)) return false;
		$records = $db->query("SELECT * FROM $table WHERE parent=$this->id AND context='category' AND type='image' ORDER BY $orderby",AS_ARRAY);

		foreach ($records as $r) {
			$image = new CategoryImage();
			$image->copydata($r,false,array());
			$image->value = unserialize($image->value);
			$image->expopulate();
			$this->images[] = $image;
		}

		return true;
	}
Esempio n. 5
0
	function reset () {
		$Settings =& EcartSettings();
		if (!in_array($this->module,explode(',',$_POST['settings']['active_gateways'])))
			$Settings->save('OfflinePayment',false);

	}
Esempio n. 6
0
	/**
	 * CartShipping constructor
	 *	 
	 * @since 1.1
	 *
	 * @return void
	 **/
	function __construct () {
		global $Ecart;
		$Settings =& EcartSettings();

		$this->Cart = &$Ecart->Order->Cart;
		$this->modules = &$Ecart->Shipping->active;
		$this->Shipping = &$Ecart->Order->Shipping;
		$this->Shipping->destination();

		$this->showpostcode = $Ecart->Shipping->postcodes;

		$this->disabled = $this->Cart->noshipping = ($Settings->get('shipping') == "off");
		$this->handling = $Settings->get('order_shipfee');

	}
Esempio n. 7
0
	/**
	 * Aggregates product pricing information
	 * 
	 * @since 1.1
	 *
	 * @param array $options ecart() tag option list
	 * @return void
	 **/
	function pricing ($options = false) {

		// Variation range index/properties
		$varranges = array('price' => 'price','saleprice'=>'promoprice');

		$variations = ($this->variations == "on");
		$freeshipping = true;
		$this->inventory = false;
		foreach ($this->prices as $i => &$price) {
			$price->price = (float)$price->price;
			$price->saleprice = (float)$price->saleprice;
			$price->shipfee = (float)$price->shipfee;
			$price->promoprice = 0;

			// Build secondary lookup table using the price id as the key
			$this->priceid[$price->id] = $price;

			if (defined('WP_ADMIN') && !isset($options['taxes'])) $options['taxes'] = true;
			if (defined('WP_ADMIN') && value_is_true($options['taxes']) && $price->tax == "on") {
				$Settings =& EcartSettings();
				$base = $Settings->get('base_operations');
				if ($base['vat']) {
					$Taxes = new CartTax();
					$taxrate = $Taxes->rate($this);
					$price->price += $price->price*$taxrate;
					$price->saleprice += $price->saleprice*$taxrate;
				}
			}

			if ($price->type == "N/A" || $price->context == "addon" || ($i > 0 && !$variations)) continue;

			// Build third lookup table using the combined optionkey
			$this->pricekey[$price->optionkey] = $price;

			// Boolean flag for custom product sales
			$price->onsale = false;
			if ($price->sale == "on" && $price->type != "N/A")
				$this->onsale = $price->onsale = true;

			$price->stocked = false;
			if ($price->inventory == "on" && $price->type != "N/A") {
				$this->stock += $price->stock;
				$this->inventory = $price->stocked = true;
			}

			if ($price->freeshipping == '0' || $price->shipping == 'on')
				$freeshipping = false;

			if ($price->onsale) $price->promoprice = (float)$price->saleprice;
			else $price->promoprice = (float)$price->price;

			if ((isset($price->promos) && $price->promos == 'enabled')) {
				if ($price->percentoff > 0) {
					$price->promoprice = $price->promoprice - ($price->promoprice * ($price->percentoff/100));
					$this->onsale = $price->onsale = true;
				}
				if ($price->amountoff > 0) {
					$price->promoprice = $price->promoprice - $price->amountoff;
					$this->onsale = $price->onsale = true;;
				}
			}

			// Grab price and saleprice ranges (minimum - maximum)
			if ($price->type != "N/A") {
				if (!$price->price) $price->price = 0;
				if ($price->stocked) $varranges['stock'] = 'stock';

				foreach ($varranges as $name => $prop) {
					if (!isset($price->$prop)) continue;

					if (!isset($this->min[$name])) $this->min[$name] = $price->$prop;
					else $this->min[$name] = min($this->min[$name],$price->$prop);
					if ($this->min[$name] == $price->$prop) $this->min[$name.'_tax'] = ($price->tax == "on");


					if (!isset($this->max[$name])) $this->max[$name] = $price->$prop;
					else $this->max[$name] = max($this->max[$name],$price->$prop);
					if ($this->max[$name] == $price->$prop) $this->max[$name.'_tax'] = ($price->tax == "on");
				}
			}

			// Determine savings ranges
			if ($price->onsale && isset($this->min['price']) && isset($this->min['saleprice'])) {

				if (!isset($this->min['saved'])) {
					$this->min['saved'] = $price->price;
					$this->min['savings'] = 100;
					$this->max['saved'] = $this->max['savings'] = 0;
				}

				$this->min['saved'] = min($this->min['saved'],($price->price-$price->promoprice));
				$this->max['saved'] = max($this->max['saved'],($price->price-$price->promoprice));

				// Find lowest savings percentage
				if ($this->min['saved'] == ($price->price-$price->promoprice))
					$this->min['savings'] = (1 - $price->promoprice/($price->price == 0?1:$price->price))*100;
				if ($this->max['saved'] == ($price->price-$price->promoprice))
					$this->max['savings'] = (1 - $price->promoprice/($price->price == 0?1:$price->price))*100;
			}

			// Determine weight ranges
			if($price->weight && $price->weight > 0) {
				if(!isset($this->min['weight'])) $this->min['weight'] = $this->max['weight'] = $price->weight;
				$this->min['weight'] = min($this->min['weight'],$price->weight);
				$this->max['weight'] = max($this->max['weight'],$price->weight);
			}

		} // end foreach($price)

		if ($this->inventory && $this->stock <= 0) $this->outofstock = true;
		if ($freeshipping) $this->freeshipping = true;
	}
Esempio n. 8
0
	/**
	 * Builds a regular express to match the current currency format
	 *	 
	 * @since 1.1
	 *
	 * @param boolean $symbol (optional) Require currency symbol - required by default
	 * @return string The current currency regex pattern
	 **/
	static function _currency_regex ($symbol=true) {
		$Settings = EcartSettings();

		$baseop = $Settings->get('base_operations');
		extract($baseop['currency']['format']);

		$pre = ($cpos?''.preg_quote($currency).($symbol?'':'?'):'');
		$amount = '[\d'.preg_quote($thousands).']+';
		$fractional = '('.preg_quote($decimals).'\d{'.$precision.'}?)?';
		$post = (!$cpos?''.preg_quote($currency).($symbol?'':'?'):'');
		return $pre.$amount.$fractional.$post;
	}
Esempio n. 9
0
	function confirmation () {
		$Settings =& EcartSettings();
		$Order = $this->Order;

		if (!isset($Order->token) || !isset($Order->payerid)) return false;

		$_ = $this->headers();

   		$_['METHOD'] 				= "GetExpressCheckoutDetails";
		$_['TOKEN'] 				= $Order->token;

		// Get transaction details
		$response = false;
		for ($attempts = 0; $attempts < 2 && !$response; $attempts++) {
			$message = $this->encode($_);
			$response = $this->send($message);
		}

		$fields = array(
			'Customer' => array(
				'firstname' => 'firstname',
				'lastname' => 'lastname',
				'email' => 'email',
				'phone' => 'phonenum',
				'company' => 'payerbusiness'
			),
			'Shipping' => array(
				'address' => 'shiptostreet',
				'xaddress' => 'shiptostreet2',
				'city' => 'shiptocity',
				'state' => 'shiptostate',
				'country' => 'shiptocountrycode',
				'postcode' => 'shiptozip'
			)
		);


		foreach ($fields as $Object => $set) {
			$changes = false;
			foreach ($set as $ecart => $paypal) {
				if (isset($response->{$paypal}) && (empty($Order->{$Object}->{$ecart}) || $changes)) {
					$Order->{$Object}->{$ecart} = $response->{$paypal};
					// If any of the fieldset is changed, change the rest to keep data sets in sync
					$changes = true;
				}
			}
		}

		if (empty($Order->Shipping->state) && empty($Order->Shipping->country))
			add_filter('ecart_cart_taxrate',array(&$this,'notax'));

		$targets = $Settings->get('target_markets');
		if (!in_array($Order->Shipping->country,array_keys($targets))) {
			new EcartError(__('The location you are purchasing from is outside of our market regions. This transaction cannot be processed.','Ecart'),'paypalexpress_market',ECART_TRXN_ERR);
			ecart_redirect(ecarturl(false,'checkout'));
		}

	}
Esempio n. 10
0
	/**
	 * Unstock the item from inventory
	 *	 
	 * @since 1.1
	 *
	 * @return void
	 **/
	function unstock () {
		if (!$this->inventory) return;
		$db = DB::get();
		$Settings =& EcartSettings();

		// Update stock in the database
		$table = DatabaseObject::tablename(Price::$table);
		$db->query("UPDATE $table SET stock=stock-{$this->quantity} WHERE id='{$this->priceline}' AND stock > 0");

		if (!empty($this->addons)) {
			foreach ($this->addons as &$Addon) {
				$db->query("UPDATE $table SET stock=stock-{$this->quantity} WHERE id='{$Addon->id}' AND stock > 0");
				$Addon->stock -= $this->quantity;
				$product_addon = "$product ($Addon->label)";
				if ($Addon->stock == 0)
					new EcartError(sprintf(__('%s is now out-of-stock!','Ecart'),$product_addon),'outofstock_warning',ECART_STOCK_ERR);
				elseif ($Addon->stock <= $Settings->get('lowstock_level'))
					return new EcartError(sprintf(__('%s has low stock levels and should be re-ordered soon.','Ecart'),$product_addon),'lowstock_warning',ECART_STOCK_ERR);

			}
		}

		// Update stock in the model
		$this->option->stock -= $this->quantity;

		// Handle notifications
		$product = "$this->name (".$this->option->label.")";
		if ($this->option->stock == 0)
			return new EcartError(sprintf(__('%s is now out-of-stock!','Ecart'),$product),'outofstock_warning',ECART_STOCK_ERR);

		if ($this->option->stock <= $Settings->get('lowstock_level'))
			return new EcartError(sprintf(__('%s has low stock levels and should be re-ordered soon.','Ecart'),$product),'lowstock_warning',ECART_STOCK_ERR);

	}
Esempio n. 11
0
/**
 * Generates canonical storefront URLs that respects the WordPress permalink settings
 * 
 * @since 1.1
 *
 * @param mixed $request Additional URI requests
 * @param string $page The gateway page
 * @param boolean $secure (optional) True for secure URLs, false to force unsecure URLs
 * @return string The final URL
 **/
function ecarturl ($request=false,$page='catalog',$secure=null) {
	$dynamic = array("thanks","receipt","confirm-order");

	$Settings =& EcartSettings();
	if (!$Settings->available) return;

	// Get the currently indexed Ecart gateway pages
	$pages = $Settings->get('pages');
	if (empty($pages)) { // Hrm, no pages, attempt to rescan for them
		// No WordPress actions, #epicfail
		if (!function_exists('do_action')) return false;
		do_action('ecart_reindex_pages');
		$pages = $Settings->get('pages');
		// Still no pages? WTH? #epicfailalso
		if (empty($pages)) return false;
	}

	// Start with the site url
	$siteurl = trailingslashit(get_bloginfo('url'));

	// Rewrite as an HTTPS connection if necessary
	if ($secure === false) $siteurl = str_replace('https://','http://',$siteurl);
	elseif (($secure || is_ecart_secure()) && !ECART_NOSSL) $siteurl = str_replace('http://','https://',$siteurl);

	// Determine WordPress gateway page URI path fragment
	if (isset($pages[$page])) {
		$path = $pages[$page]['uri'];
		$pageid = $pages[$page]['id'];
	} else {
		if (in_array($page,$dynamic)) {
			$target = $pages['checkout'];
			if (ECART_PRETTYURLS) {
				$catalog = empty($pages['catalog']['uri'])?$pages['catalog']['name']:$pages['catalog']['uri'];
				$path = trailingslashit($catalog).$page;
			} else $pageid = $target['id']."&ecart_proc=$page";
		} elseif ('images' == $page) {
			$target = $pages['catalog'];
			$path = trailingslashit($target['uri']).'images';
			if (!ECART_PRETTYURLS) $request = array('siid'=>$request);
		} else {
			$path = $pages['catalog']['uri'];
			$pageid = $pages['catalog']['id'];
		}
	}

	if (ECART_PRETTYURLS) $url = user_trailingslashit($siteurl.$path);
	else $url = isset($pageid)?add_query_arg('page_id',$pageid,$siteurl):$siteurl;

	// No extra request, return the complete URL
	if (!$request) return $url;

	// Filter URI request
	$uri = false;
	if (!is_array($request)) $uri = urldecode($request);
	if (is_array($request && isset($request[0]))) $uri = array_shift($request);
	if (!empty($uri)) $uri = join('/',array_map('urlencode',explode('/',$uri))); // sanitize

	$url = user_trailingslashit(trailingslashit($url).$uri);

	if (!empty($request) && is_array($request)) {
		$request = array_map('urldecode',$request);
		$request = array_map('urlencode',$request);
		$url = add_query_arg($request,$url);
	}

	return $url;
}
Esempio n. 12
0
	/**
	 * Grabs interface help screencasts
	 *	 
	 * @since 1.1
	 *
	 * @return void
	 **/
	function help () {
		if (!isset($_GET['id'])) return;

		$Settings =& EcartSettings();
		list($status,$key) = $Settings->get('updatekey');
		$site = get_bloginfo('siteurl');

		$request = array("EcartScreencast" => $_GET['id'],'key'=>$key,'site'=>$site);
		$response = Ecart::callhome($request);
		echo $response;
		exit();
	}
Esempio n. 13
0
	function upgrade ($addon,$type) {
		$Settings = EcartSettings();

		$this->init();
		$this->upgrade_strings();

		switch ($type) {
			case "gateway": $this->addons_dir = ECART_GATEWAYS; break;
			case "shipping": $this->addons_dir = ECART_SHIPPING; break;
			case "storage": $this->addons_dir = ECART_STORAGE; break;
			default: $this->addons_dir = ECART_PLUGINDIR;
		}

		$current = $Settings->get('updates');
		if ( !isset( $current->response[ ECART_PLUGINFILE.'/addons' ][$addon] ) ) {
			$this->skin->set_result(false);
			$this->skin->error('up_to_date');
			$this->skin->after();
			return false;
		}

		// Get the URL to the zip file
		$r = $current->response[ ECART_PLUGINFILE.'/addons' ][$addon];
		$this->addon = $r->slug;

		add_filter('upgrader_destination_selection', array(&$this, 'destination_selector'), 10, 2);

		$this->run(array(
					'package' => $r->package,
					'destination' => $this->addons_dir,
					'clear_destination' => true,
					'clear_working' => true,
					'hook_extra' => array(
						'addon' => $addon
					)
		));

		// Cleanup our hooks, in case something else does an upgrade on this connection.
		remove_filter('upgrader_destination_selection', array(&$this, 'destination_selector'));

		if ( ! $this->result || is_wp_error($this->result) )
			return $this->result;

		// Force refresh of plugin update information
		$Settings->save('updates',false);
	}
Esempio n. 14
0
	function notification () {
		global $Ecart;
		$Settings =& EcartSettings();
		// The blogname option is escaped with esc_html on the way into the database in sanitize_option
		// we want to reverse this for the plain text arena of emails.
		$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);

		$_ = array();
		$_[] = 'From: "'.get_option('blogname').'" <'.$Settings->get('merchant_email').'>';
		$_[] = 'To: '.$Settings->get('merchant_email');
		$_[] = 'Subject: '.sprintf(__('[%s] New Customer Registration','Ecart'),$blogname);
		$_[] = '';
		$_[] = sprintf(__('New customer registration on your "%s" store:','Ecart'), $blogname);
		$_[] = sprintf(__('E-mail: %s','Ecart'), stripslashes($this->email));

		if (!ecart_email(join("\r\n",$_)))
			new EcartError('The new account notification e-mail could not be sent.','new_account_email',ECART_ADMIN_ERR);
		elseif (ECART_DEBUG) new EcartError('A new account notification e-mail was sent to the merchant.','new_account_email',ECART_DEBUG_ERR);
		if (empty($this->password)) return;

		$_ = array();
		$_[] = 'From: "'.get_option('blogname').'" <'.$Settings->get('merchant_email').'>';
		$_[] = 'To: '.$this->email;
		$_[] = 'Subject: '.sprintf(__('[%s] New Customer Registration','Ecart'),$blogname);
		$_[] = '';
		$_[] = sprintf(__('New customer registration on your "%s" store:','Ecart'), $blogname);
		$_[] = sprintf(__('E-mail: %s','Ecart'), stripslashes($this->email));
		$_[] = sprintf(__('Password: %s'), $this->password);
		$_[] = '';
		$_[] = ecarturl(false,'account',$Ecart->Gateways->secure);

		if (!ecart_email(join("\r\n",$_)))
			new EcartError('The customer\'s account notification e-mail could not be sent.','new_account_email',ECART_ADMIN_ERR);
		elseif (ECART_DEBUG) new EcartError('A new account notification e-mail was sent to the customer.','new_account_email',ECART_DEBUG_ERR);
	}
Esempio n. 15
0
	/**
	 * Report the current status of the update key
	 *	 
	 * @since 1.1
	 *
	 * @return boolean
	 **/
	function keystatus ($_=true) {
		$Settings =& EcartSettings();
		$status = $Settings->get('updatekey');
		if ($status[0] != "1") return false;
		return $_;
	}
Esempio n. 16
0
	/**
	 * Adds a dynamic style declaration for the category grid view
	 *
	 * Ties the presentation setting to the grid view category rendering
	 * in the storefront.
	 *	 
	 * @since 1.1
	 *
	 * @return void Description...
	 **/
	function catalogcss () {
		$Settings = &EcartSettings();
		if (!isset($row_products)) $row_products = 3;
		$row_products = $Settings->get('row_products');
		$products_per_row = floor((100/$row_products));
?>
	<!-- Ecart dynamic catalog styles -->
	<style type="text/css">
	#ecart ul.products li.product { width: <?php echo $products_per_row; ?>%; } /* For grid view */
	</style>
	<!-- END Ecart dynamic catalog styles -->
<?php
	}
Esempio n. 17
0
	/**
	 * Handles saving updated category information from the category editor
	 *	 
	 * @since 1.0
	 * @return void
	 **/
	function save ($Category) {
		global $Ecart;
		$Settings = &EcartSettings();
		$db = DB::get();
		check_admin_referer('ecart-save-category');

		if ( !(is_ecart_userlevel() || current_user_can('ecart_categories')) )
			wp_die(__('You do not have sufficient permissions to access this page.'));

		$Settings->saveform(); // Save workflow setting

		$Ecart->Catalog = new Catalog();
		$Ecart->Catalog->load_categories(array(
			'columns' => "cat.id,cat.parent,cat.name,cat.description,cat.uri,cat.slug",
			'where' => array(),
			'joins' => array(),
			'orderby' => false,
			'order' => false,
			'outofstock' => true
		));

		$Category->update_slug();

		if (!empty($_POST['deleteImages'])) {
			$deletes = array();
			if (strpos($_POST['deleteImages'],","))	$deletes = explode(',',$_POST['deleteImages']);
			else $deletes = array($_POST['deleteImages']);
			$Category->delete_images($deletes);
		}

		// Variation price templates
		if (!empty($_POST['price']) && is_array($_POST['price'])) {
			foreach ($_POST['price'] as &$pricing) {
				$pricing['price'] = floatvalue($pricing['price'],false);
				$pricing['saleprice'] = floatvalue($pricing['saleprice'],false);
				$pricing['shipfee'] = floatvalue($pricing['shipfee'],false);
			}
			$Category->prices = stripslashes_deep($_POST['price']);
		} else $Category->prices = array();

		if (empty($_POST['specs'])) $Category->specs = array();
		else $_POST['specs'] = stripslashes_deep($_POST['specs']);

		if (empty($_POST['options'])
			|| (count($_POST['options']['v'])) == 1 && !isset($_POST['options']['v'][1]['options'])) {
				$_POST['options'] = $Category->options = array();
				$_POST['prices'] = $Category->prices = array();
		} else $_POST['options'] = stripslashes_deep($_POST['options']);
		if (isset($_POST['content'])) $_POST['description'] = $_POST['content'];

		$Category->updates($_POST);
		$Category->save();

		if (!empty($_POST['images']) && is_array($_POST['images'])) {
			$Category->link_images($_POST['images']);
			$Category->save_imageorder($_POST['images']);
			if (!empty($_POST['imagedetails']) && is_array($_POST['imagedetails'])) {
				foreach($_POST['imagedetails'] as $i => $data) {
					$Image = new CategoryImage($data['id']);
					$Image->title = $data['title'];
					$Image->alt = $data['alt'];
					$Image->save();
				}
			}
		}

		do_action_ref_array('ecart_category_saved',array(&$Category));

		$updated = '<strong>'.$Category->name.'</strong> '.__('category saved.','Ecart');

	}
Esempio n. 18
0
	/**
	 * Handles saving updates from the product editor
	 *
	 * Saves all product related information which includes core product data
	 * and supporting elements such as images, digital downloads, tags,
	 * assigned categories, specs and pricing variations.
	 *	 
	 * @return void
	 **/
	function save_product ($Product) {
		$db = DB::get();
		$Settings = &EcartSettings();
		check_admin_referer('ecart-save-product');

		if ( !(is_ecart_userlevel() || current_user_can('ecart_products')) )
			wp_die(__('You do not have sufficient permissions to access this page.'));

		$Settings->saveform(); // Save workflow setting

		$base = $Settings->get('base_operations');
		$taxrate = 0;
		if ($base['vat']) $taxrate = ecart_taxrate(null,true,$Product);

		if (empty($_POST['options'])) $Product->options = array();
		else $_POST['options'] = stripslashes_deep($_POST['options']);

		if (empty($Product->slug)) $Product->slug = sanitize_title_with_dashes($_POST['name']);

		// Check for an existing product slug
		$exclude_product = !empty($Product->id)?"AND id != $Product->id":"";
		$existing = $db->query("SELECT slug FROM $Product->_table WHERE slug='$Product->slug' $exclude_product LIMIT 1");
		if ($existing) {
			$suffix = 2;
			while($existing) {
				$altslug = substr($Product->slug, 0, 200-(strlen($suffix)+1)). "-".$suffix++;
				$existing = $db->query("SELECT slug FROM $Product->_table WHERE slug='$altslug' $exclude_product LIMIT 1");
			}
			$Product->slug = $altslug;
		}

		if ($_POST['status'] == "publish") {
			$publishfields = array('month' => '','date' => '','year' => '','hour'=>'','minute'=>'','meridiem'=>'');
			$publishdate = join('',array_merge($publishfields,$_POST['publish']));
			if (!empty($publishdate)) {
				if ($_POST['publish']['meridiem'] == "PM" && $_POST['publish']['hour'] < 12)
					$_POST['publish']['hour'] += 12;
				$_POST['publish'] = mktime($_POST['publish']['hour'],$_POST['publish']['minute'],0,$_POST['publish']['month'],$_POST['publish']['date'],$_POST['publish']['year']);
			} else {
				unset($_POST['publish']);
				// Auto set the publish date if not set (or more accurately, if set to an irrelevant timestamp)
				if ($Product->publish <= 86400) $Product->publish = time();
			}
		} else {
			unset($_POST['publish']);
			$Product->publish = 0;
		}

		if (isset($_POST['content'])) $_POST['description'] = $_POST['content'];

		$Product->updates($_POST,array('categories','prices'));
		$Product->save();

		$Product->save_categories($_POST['categories']);
		$Product->save_tags(explode(",",$_POST['taglist']));

		if (!empty($_POST['price']) && is_array($_POST['price'])) {

			// Delete prices that were marked for removal
			if (!empty($_POST['deletePrices'])) {
				$deletes = array();
				if (strpos($_POST['deletePrices'],","))	$deletes = explode(',',$_POST['deletePrices']);
				else $deletes = array($_POST['deletePrices']);

				foreach($deletes as $option) {
					$Price = new Price($option);
					$Price->delete();
				}
			}

			// Save prices that there are updates for
			foreach($_POST['price'] as $i => $option) {
				if (empty($option['id'])) {
					$Price = new Price();
					$option['product'] = $Product->id;
				} else $Price = new Price($option['id']);
				$option['sortorder'] = array_search($i,$_POST['sortorder'])+1;

				// Remove VAT amount to save in DB
				if ($base['vat'] && isset($option['tax']) && $option['tax'] == "on") {
					$option['price'] = (floatvalue($option['price'])/(1+$taxrate));
					$option['saleprice'] = (floatvalue($option['saleprice'])/(1+$taxrate));
				}
				$option['shipfee'] = floatvalue($option['shipfee']);

				$option['weight'] = floatvalue($option['weight']);
				if (isset($options['dimensions']) && is_array($options['dimensions']))
					foreach ($option['dimensions'] as &$dimension)
						$dimension = floatvalue($dimension);

				$Price->updates($option);
				$Price->save();

				if (!empty($option['download'])) $Price->attach_download($option['download']);

				if (!empty($option['downloadpath'])) { // Attach file specified by URI/path
					if (!empty($Price->download->id) || (empty($Price->download) && $Price->load_download())) {
						$File = $Price->download;
					} else $File = new ProductDownload();

					$stored = false;
					$tmpfile = sanitize_path($option['downloadpath']);

					$File->storage = false;
					$Engine = $File->_engine(); // Set engine from storage settings

					$File->parent = $Price->id;
					$File->context = "price";
					$File->type = "download";
					$File->name = !empty($option['downloadfile'])?$option['downloadfile']:basename($tmpfile);
					$File->filename = $File->name;

					if ($File->found($tmpfile)) {
						$File->uri = $tmpfile;
						$stored = true;
					} else $stored = $File->store($tmpfile,'file');

					if ($stored) {
						$File->readmeta();
						$File->save();
					}

				} // END attach file by path/uri
			}
			unset($Price);
		}

		// No variation options at all, delete all variation-pricelines
		if (!empty($Product->prices) && is_array($Product->prices)
				&& (empty($_POST['options']['v']) || empty($_POST['options']['a']))) {
			foreach ($Product->prices as $priceline) {
				// Skip if not tied to variation options
				if ($priceline->optionkey == 0) continue;
				if ((empty($_POST['options']['v']) && $priceline->context == "variation")
					|| (empty($_POST['options']['a']) && $priceline->context == "addon")) {
						$Price = new Price($priceline->id);
						$Price->delete();
				}
			}
		}

		if (!empty($_POST['details']) || !empty($_POST['deletedSpecs'])) {
			$deletes = array();
			if (!empty($_POST['deletedSpecs'])) {
				if (strpos($_POST['deletedSpecs'],","))	$deletes = explode(',',$_POST['deletedSpecs']);
				else $deletes = array($_POST['deletedSpecs']);
				foreach($deletes as $option) {
					$Spec = new Spec($option);
					$Spec->delete();
				}
				unset($Spec);
			}

			if (is_array($_POST['details'])) {
				foreach ($_POST['details'] as $i => $spec) {
					if (in_array($spec['id'],$deletes)) continue;
					if (isset($spec['new'])) {
						$Spec = new Spec();
						$spec['id'] = '';
						$spec['parent'] = $Product->id;
					} else $Spec = new Spec($spec['id']);
					$spec['sortorder'] = array_search($i,$_POST['details-sortorder'])+1;

					$Spec->updates($spec);
					$Spec->save();
				}
			}
		}

		if (!empty($_POST['deleteImages'])) {
			$deletes = array();
			if (strpos($_POST['deleteImages'],","))	$deletes = explode(',',$_POST['deleteImages']);
			else $deletes = array($_POST['deleteImages']);
			$Product->delete_images($deletes);
		}

		if (!empty($_POST['images']) && is_array($_POST['images'])) {
			$Product->link_images($_POST['images']);
			$Product->save_imageorder($_POST['images']);
			if (!empty($_POST['imagedetails']))
				$Product->update_images($_POST['imagedetails']);
		}

		do_action_ref_array('ecart_product_saved',array(&$Product));

		unset($Product);
		return true;
	}
Esempio n. 19
0
	function settings () {
		global $Ecart;
		$Ecart->Settings = new Settings();
		$this->Settings = &EcartSettings();
	}
Esempio n. 20
0
	function verify_file () {
		check_admin_referer('wp_ajax_ecart_verify_file');
		$Settings = &EcartSettings();
		chdir(WP_CONTENT_DIR); // relative file system path context for realpath
		$url = $_POST['url'];
		$request = parse_url($url);

		if ($request['scheme'] == "http") {
			$results = get_headers(linkencode($url));
			if (substr($url,-1) == "/") die("ISDIR");
			if (strpos($results[0],'200') === false) die("NULL");
		} else {
			$url = str_replace('file://','',$url);

			if ($url{0} != "/" || substr($url,0,2) == "./" || substr($url,0,3) == "../")
				$result = apply_filters('ecart_verify_stored_file',$url);

			$url = sanitize_path(realpath($url));
			if (!file_exists($url)) die('NULL');
			if (is_dir($url)) die('ISDIR');
			if (!is_readable($url)) die('READ');

		}

		die('OK');

	}