rules_shipping_framework_joomla.php 18.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
/**
 * Shipping by Rules generic helper class (Joomla/VM-specific)
 * Reinhold Kainhofer, Open Tools, office@open-tools.net
 * @copyright (C) 2012-2015 - Reinhold Kainhofer
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/

// defined('_JEXEC') or	 die( 'Direct Access to ' . basename( __FILE__ ) . ' is not allowed.' ) ;

// if (!class_exists( 'VmConfig' )) 
//     require(JPATH_ROOT.DS.'administrator'.DS.'components'.DS.'com_virtuemart'.DS.'helpers'.DS.'config.php');
// VmConfig::loadConfig();

if (!class_exists( 'RulesShippingFramework' )) 
	require_once (dirname(__FILE__) . DS . 'library' . DS . 'rules_shipping_framework.php');

// $test=new asdfasdsf();
class RulesShippingFrameworkJoomla extends RulesShippingFramework {
20
	/* Constructor: Register the available scopings */
21
22
	function __construct() {
		parent::__construct();
23
24
		$this->registerScopings(array(
			"categories"    => 'categories',
25
			"subcategories" => 'subcategories',
26
27
28
29
30
31
			"products"      => 'products',
			"skus"          => 'products',
			"vendors"       => 'vendors',
			"manufacturers" => 'manufacturers',
		));
	}
32
33
34
35
36
37
38
39
40
	function getCustomFunctions() {
		// Let other plugins add custom functions! 
		// The onVmShippingRulesRegisterCustomFunctions() trigger is expected to return an array of the form:
		//   array ('functionname1' => 'function-to-be-called',
		//          'functionname2' => array($classobject, 'memberfunc')),
		//          ...);
		JPluginHelper::importPlugin('vmshipmentrules');
		$dispatcher = JDispatcher::getInstance();
		$custfuncdefs = $dispatcher->trigger('onVmShippingRulesRegisterCustomFunctions',array());
41
42
		$custfuncdefs['convertfromcurrency'] = array($this, 'convert_from_currency');
		$custfuncdefs['converttocurrency'] = array($this, 'convert_to_currency');
43
		
Reinhold Kainhofer's avatar
Reinhold Kainhofer committed
44
		return $custfuncdefs;
45
46
	}
	
47
	protected function printWarning($message) {
48
49
50
51
52
53
54
55
56
		// Keep track of warning messages, so we don't print them twice:
		global $printed_warnings;
		if (!isset($printed_warnings))
			$printed_warnings = array();
		if (!in_array($message, $printed_warnings)) {
			JFactory::getApplication()->enqueueMessage($message, 'error');
			$printed_warnings[] = $message;
		}
	}
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
	/** @tag public-api
	 *  @function debug()
	 *    Print a debug message (untranslated) in the system-specific way.
	 *  @param $message the debug message to be printed 
	 */
	public function debug($message) {
		vmDebug($message);
	}

	public function __($string) {
		$args = func_get_args();
		if (count($args)>1) {
			return call_user_func_array(array("JText", "sprintf"), $args);
		} else {
			return call_user_func(array("JText", "_"), $string);
		}
	}

	protected function setMethodCosts($method, $match, $costs) {
		$r = $match["rule"];
		// Allow some system-specific code, e.g. setting some members of $method, etc.
		$method->tax_id = $r->ruleinfo['tax_id'];
		// TODO: Shall we include the name of the modifiers, too?
		$method->rule_name = $match["rule_name"];
		$method->cost = $costs;
		$method->includes_tax = $r->includes_tax;
	}
	
85
86
87
88
	protected function getCartProducts($cart, $method) {
		return $cart->products;
	}
	
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
	protected function getMethodId($method) {
		return $method->virtuemart_shipmentmethod_id;
	}

	protected function getMethodName($method) {
		return $method->shipment_name;
	}

	protected function parseMethodRules (&$method) {
		$this->parseMethodRule ($method->rules1, $method->countries1, array('tax_id'=>$method->tax_id1), $method);
		$this->parseMethodRule ($method->rules2, $method->countries2, array('tax_id'=>$method->tax_id2), $method);
		$this->parseMethodRule ($method->rules3, $method->countries3, array('tax_id'=>$method->tax_id3), $method);
		$this->parseMethodRule ($method->rules4, $method->countries4, array('tax_id'=>$method->tax_id4), $method);
		$this->parseMethodRule ($method->rules5, $method->countries5, array('tax_id'=>$method->tax_id5), $method);
		$this->parseMethodRule ($method->rules6, $method->countries6, array('tax_id'=>$method->tax_id6), $method);
		$this->parseMethodRule ($method->rules7, $method->countries7, array('tax_id'=>$method->tax_id7), $method);
		$this->parseMethodRule ($method->rules8, $method->countries8, array('tax_id'=>$method->tax_id8), $method);
	}
107
108
109
110
111
112
113
114

	/**
	 * Functions to calculate the cart variables:
	 *   - getOrderArticles($cart, $products)
	 *   - getOrderProducts
	 *   - getOrderDimensions
	 */
	/** Functions to calculate all the different variables for the given cart and given (sub)set of products in the cart */
115
	protected function getOrderCounts ($cart, $products, $method) {
116
117
118
		$counts = array(
			'articles' => 0,
			'products' => count($products),
119
			'quantity' => 0,
120
121
122
			'minquantity' => 9999999999,
			'maxquantity' => 0,
		);
123

124
		foreach ($products as $product) {
125
126
127
			$counts['articles']   += $product->quantity;
			$counts['maxquantity'] = max ($counts['maxquantity'], $product->quantity);
			$counts['minquantity'] = min ($counts['minquantity'], $product->quantity);
128
		}
129
130
		$counts['quantity'] = $counts['articles'];
		
131
		return $counts;
132
133
	}

134
	protected function getOrderDimensions ($cart, $products, $method) {
135
136
137
138
139
140
141
142
143
		/* Cache the value in a static variable and calculate it only once! */
		$dimensions=array(
			'volume' => 0,
			'maxvolume' => 0, 'minvolume' => 9999999999,
			'maxlength' => 0, 'minlength' => 9999999999, 'totallength' => 0,
			'maxwidth'  => 0, 'minwidth' => 9999999999,  'totalwidth'  => 0,
			'maxheight' => 0, 'minheight' => 9999999999, 'totalheight' => 0,
			'maxpackaging' => 0, 'minpackaging' => 9999999999, 'totalpackaging' => 0,
		);
144
		$length_dimension = $method->length_unit;
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
		foreach ($products as $product) {
	
			$l = ShopFunctions::convertDimensionUnit ($product->product_length, $product->product_lwh_uom, $length_dimension);
			$w = ShopFunctions::convertDimensionUnit ($product->product_width, $product->product_lwh_uom, $length_dimension);
			$h = ShopFunctions::convertDimensionUnit ($product->product_height, $product->product_lwh_uom, $length_dimension);

			$volume = $l * $w * $h;
			$dimensions['volume'] += $volume * $product->quantity;
			$dimensions['maxvolume'] = max ($dimensions['maxvolume'], $volume);
			$dimensions['minvolume'] = min ($dimensions['minvolume'], $volume);
				
			$dimensions['totallength'] += $l * $product->quantity;
			$dimensions['maxlength'] = max ($dimensions['maxlength'], $l);
			$dimensions['minlength'] = min ($dimensions['minlength'], $l);
			$dimensions['totalwidth'] += $w * $product->quantity;
			$dimensions['maxwidth'] = max ($dimensions['maxwidth'], $w);
			$dimensions['minwidth'] = min ($dimensions['minwidth'], $w);
			$dimensions['totalheight'] += $h * $product->quantity;
			$dimensions['maxheight'] = max ($dimensions['maxheight'], $h);
			$dimensions['minheight'] = min ($dimensions['minheight'], $h);
			$dimensions['totalpackaging'] += $product->product_packaging * $product->quantity;
			$dimensions['maxpackaging'] = max ($dimensions['maxpackaging'], $product->product_packaging);
			$dimensions['minpackaging'] = min ($dimensions['minpackaging'], $product->product_packaging);
		}

		return $dimensions;
	}
	
173
174
	protected function getOrderWeights ($cart, $products, $method) {
		$weight_unit = $method->weight_unit;
175
176
177
178
179
180
181
182
183
184
185
186
187
		$dimensions=array(
			'weight' => 0,
			'maxweight' => 0, 'minweight' => 9999999999,
		);
		foreach ($products as $product) {
			$w = ShopFunctions::convertWeigthUnit ($product->product_weight, $product->product_weight_uom, $weight_unit);
			$dimensions['maxweight'] = max ($dimensions['maxweight'], $w);
			$dimensions['minweight'] = min ($dimensions['minweight'], $w);
			$dimensions['weight'] += $w * $product->quantity;
		}
		return $dimensions;
	}
	
188
	protected function getOrderListProperties ($cart, $products, $method) {
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
		$categories = array();
		$vendors = array();
		$skus = array();
		$manufacturers = array();
		foreach ($products as $product) {
			$skus[] = $product->product_sku;
			$categories = array_merge ($categories, $product->categories);
			$vendors[] = $product->virtuemart_vendor_id;
			if (is_array($product->virtuemart_manufacturer_id)) {
				$manufacturers = array_merge($manufacturers, $product->virtuemart_manufacturer_id);
			} elseif ($product->virtuemart_manufacturer_id) {
				$manufacturers[] = $product->virtuemart_manufacturer_id;
			}
		}
		$skus = array_unique($skus);
		$vendors = array_unique($vendors);
		$categories = array_unique($categories);
		$manufacturers = array_unique($manufacturers);
		return array ('skus'=>$skus, 
			      'categories'=>$categories,
			      'vendors'=>$vendors,
			      'manufacturers'=>$manufacturers,
		);
	}
	
214
	protected function getOrderAddress ($cart, $method) {
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
		$address = (($cart->ST == 0 || $cart->STsameAsBT == 1) ? $cart->BT : $cart->ST);
		$zip = isset($address['zip'])?trim($address['zip']):'';
		$data = array('zip'=>$zip,
			'zip1'=>substr($zip,0,1),
			'zip2'=>substr($zip,0,2),
			'zip3'=>substr($zip,0,3),
			'zip4'=>substr($zip,0,4),
			'zip5'=>substr($zip,0,5),
			'zip6'=>substr($zip,0,6),
			'city'=>isset($address['city'])?trim($address['city']):'',
			'countryid' => 0, 'country' => '', 'country2' => '', 'country3' => '',
			'stateid'   => 0, 'state'   => '', 'state2'   => '', 'state3'   => '',
		);
		$data['company'] = isset($address['company'])?$address['company']:'';
		$data['title'] = isset($address['title'])?$address['title']:'';
		$data['first_name'] = isset($address['title'])?$address['title']:'';
		$data['middle_name'] = isset($address['middle_name'])?$address['middle_name']:'';
		$data['last_name'] = isset($address['last_name'])?$address['last_name']:'';
		$data['address1'] = isset($address['address_1'])?$address['address_1']:'';
		$data['address2'] = isset($address['address_2'])?$address['address_2']:'';
		$data['city'] = isset($address['city'])?$address['city']:'';
		$data['phone1'] = isset($address['phone_1'])?$address['phone_1']:'';
		$data['phone2'] = isset($address['phone_2'])?$address['phone_2']:'';
		$data['fax'] = isset($address['fax'])?$address['fax']:'';
		$data['email'] = isset($address['email'])?$address['email']:'';
		
		// Country and State variables:
		$countriesModel = VmModel::getModel('country');
		if (isset($address['virtuemart_country_id'])) {
			$data['countryid'] = $address['virtuemart_country_id'];
			// The following is a workaround to make sure the cache is invalidated
			// because if some other extension meanwhile called $countriesModel->getCountries,
			// the cache will be modified, but the model's id will not be changes, so the
			// getData call will return the wrong cache.
			$countriesModel->setId(0); 
			$countriesModel->setId($address['virtuemart_country_id']);
			$country = $countriesModel->getData($address['virtuemart_country_id']);
			if (!empty($country)) {
				$data['country'] = $country->country_name;
				$data['country2'] = $country->country_2_code;
				$data['country3'] = $country->country_3_code;
			}
		}
		
		$statesModel = VmModel::getModel('state');
		if (isset($address['virtuemart_state_id'])) {
			$data['stateid'] = $address['virtuemart_state_id'];
			// The following is a workaround to make sure the cache is invalidated
			// because if some other extension meanwhile called $countriesModel->getCountries,
			// the cache will be modified, but the model's id will not be changes, so the
			// getData call will return the wrong cache.
			$statesModel->setId(0); 
			$statesModel->setId($address['virtuemart_state_id']);
			$state = $statesModel->getData($address['virtuemart_state_id']);
			if (!empty($state)) {
				$data['state'] = $state->state_name;
				$data['state2'] = $state->state_2_code;
				$data['state3'] = $state->state_3_code;
			}
		}
		
		return $data;
	}
	
279
	protected function getOrderPrices ($cart, $products, /*$cart_prices, */$method) {
280
281
282
283
284
285
286
287
288
289
290
291
292
		$data = array(
			'amount' => 0, 
			'amountwithtax' => 0, 
			'amountwithouttax' => 0, 
			'baseprice' => 0, 
			'basepricewithtax' => 0, 
			'discountedpricewithouttax' => 0, 
			'salesprice' => 0, 
			'taxamount' => 0, 
			'salespricewithdiscount' => 0, 
			'discountamount' => 0, 
			'pricewithouttax' => 0,
		);
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// 		if (!empty($cart_prices)) {
// 			// get prices for the whole cart -> simply user the cart_prices
// 			$data['amount']                 = $cart_prices['salesPrice'];
// 			$data['amountwithtax']          = $cart_prices['salesPrice'];
// 			$data['amountwithouttax']       = $cart_prices['priceWithoutTax'];
// 			$data['baseprice']              = $cart_prices['basePrice'];
// 			$data['basepricewithtax']       = $cart_prices['basePriceWithTax'];
// 			$data['discountedpricewithouttax'] = $cart_prices['discountedPriceWithoutTax'];
// 			$data['salesprice']             = $cart_prices['salesPrice'];
// 			$data['taxamount']              = $cart_prices['taxAmount'];
// 			$data['salespricewithdiscount'] = $cart_prices['salesPriceWithDiscount'];
// 			$data['discountamount']         = $cart_prices['discountAmount'];
// 			$data['pricewithouttax']        = $cart_prices['priceWithoutTax'];
// 		} else {
307
308
309
			// Calculate the prices from the individual products!
			// Possible problems are discounts on the order total
			foreach ($products as $product) {
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// 				$prices = isset($product->allPrices)?($product->allPrices[$product->selectedPrice]):($product->prices);
				$prices = $product->prices;
				$quant = $product->quantity;
				$data['amount']                    += $quant * $prices['salesPrice'];
				$data['amountwithtax']             += $quant * $prices['salesPrice'];
				$data['amountwithouttax']          += $quant * $prices['priceWithoutTax'];
				$data['baseprice']                 += $quant * $prices['basePrice'];
				$data['basepricewithtax']          += $quant * $prices['basePriceWithTax'];
				$data['discountedpricewithouttax'] += $quant * $prices['discountedPriceWithoutTax'];
				$data['salesprice']                += $quant * $prices['salesPrice'];
				$data['taxamount']                 += $quant * $prices['taxAmount'];
				$data['salespricewithdiscount']    += $quant * $prices['salesPriceWithDiscount'];
				$data['discountamount']            += $quant * $prices['discountAmount'];
				$data['pricewithouttax']           += $quant * $prices['priceWithoutTax'];
// JFactory::getApplication()->enqueueMessage("<pre>prices: ".print_r($prices,1)."</pre>", 'error');
// JFactory::getApplication()->enqueueMessage("<pre>product: ".print_r($product,1)."</pre>", 'error');
				
327
			}
328
// 		}
329
330
331
332
333
		return $data;
	}

	/** Allow child classes to add additional variables for the rules or modify existing one
	 */
334
	protected function addCustomCartValues ($cart, $products, $method, &$values) {
335
	}
336
	protected function addPluginCartValues($cart, $products, $method, &$values) {
337
338
		// Finally, call the triger of vmshipmentrules plugins to let them add/modify variables
		JPluginHelper::importPlugin('vmshipmentrules');
339
		JDispatcher::getInstance()->trigger('onVmShippingRulesGetCartValues',array(&$values, $cart, $products, $method));
340
	}
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
	
	
	protected function getCategoryTreeRecursive($catmodel, $parent_category_id, &$categories) {
		if ($catmodel->hasChildren($parent_category_id)){
			// We need to call getCategories with vendorID=1, because the 
			// default "" will cause VM to check the current user for superuser 
			// access, which he usually does not have, and thus no child 
			// categories would be displayed.
			$childCats = $catmodel->getCategories(/*$onlyPublished*/false, 
				$parent_category_id, /*child id*/false, /*$keyword*/"", 
				/*VendorID*/1);
			foreach ($childCats as $key => $category) {
				$categories[] = $category->virtuemart_category_id;
				$this->getCategoryTreeRecursive($catmodel, $category->virtuemart_category_id, $categories);
			}
		}
	}
358
359
360

	/** Filter the given array of products and return only those that belong to the categories, manufacturers, 
	*  vendors or products given in the $filter_conditions. The $filter_conditions is an array of the form:
361
	*     array( 'products'=>array(....), 'categories'=>array(1,2,3,42), 'manufacturers'=>array(77,78,83), 'vendors'=>array(1,2))
362
363
364
365
366
	*  Notice that giving an empty array for any of the keys means "no restriction" and is exactly the same 
	*  as leaving out the entry altogether
	*/
	public function filterProducts($products, $filter_conditions) {
		$result = array();
367
368
369
370
371
372
373
		
		// For the subcategories scoping we need all subcategories of the conditions:
		$subcategories = array();
		if (isset($filter_conditions['subcategories']) && !empty($filter_conditions['subcategories'])) {
			$catmodel = VmModel::getModel('category');
			foreach ($filter_conditions['subcategories'] as $catid) {
				$subcategories[] = $catid;
374
				$categories = $this->getCategoryTreeRecursive($catmodel, $catid, $subcategories);
375
376
377
378
379
			}
			$subcategories = array_unique($subcategories);
		}
		

380
		foreach ($products as $p) {
381
			if (!empty($filter_conditions['products']) && !in_array($p->product_sku, $filter_conditions['products']))
382
383
384
				continue;
			if (!empty($filter_conditions['categories']) && count(array_intersect($filter_conditions['categories'], $p->categories))==0)
				continue;
385
386
			if (!empty($filter_conditions['subcategories']) && count(array_intersect($subcategories, $p->categories))==0)
				continue;
387
388
389
390
391
392
393
394
395
			if (!empty($filter_conditions['manufacturers']) && count(array_intersect($filter_conditions['manufacturers'], $p->virtuemart_manufacturer_id))==0)
				continue;
			if (!empty($filter_conditions['vendors']) && !in_array($p->virtuemart_vendor_id, $filter_conditions['vendors']))
				continue;
			$result[] = $p;
		}
		return $result;
	}
	
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
	
	/** Currency conversion function
	 */
	 
	protected function getCurrencyDisplay($curr) {
		if (!class_exists('ShopFunctions'))
			require(VMPATH_ADMIN . '/' . 'helpers' . '/' . 'shopfunctions.php');
		if (is_string($curr)) {
			$currID = ShopFunctions::getCurrencyIDByName($curr);
		} elseif (is_numeric($curr)) {
			$currID = $curr;
		} else {
			$this->printWarning(JText::sprintf('OTSHIPMENT_RULES_CURRENCY_CONVERSION_FAILED', $curr, $rule->rulestring));
			$currID = 0;
		}
		
		return CurrencyDisplay::getInstance($currID);
	}
	
	public function convert_from_currency($args, $rule) {
		$value = $args[0];
		$curr = $args[1];
		$currency = $this->getCurrencyDisplay($curr);
		if ($currency) {
			return $currency->convertCurrencyTo($curr, $value, TRUE);
		} else {
			$this->printWarning(JText::sprintf('OTSHIPMENT_RULES_CURRENCY_CONVERSION_FAILED', $curr, $rule->rulestring));
			return 0;
		}
	}
	
	public function convert_to_currency($args, $rule) {
		$value = $args[0];
		$curr = $args[1];
		$currency = $this->getCurrencyDisplay($curr);
		if ($currency) {
			return $currency->convertCurrencyTo($curr, $value, FALSE);
		} else {
			$this->printWarning(JText::sprintf('OTSHIPMENT_RULES_CURRENCY_CONVERSION_FAILED', $curr, $rule->rulestring));
			return 0;
		}
	}
438
}