1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
214
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
| <?php
# jCart v1.3.5
# http://conceptlogic.com/jcart/
# http://jcart.info
class Jcart
{
public $config = array();
private $items = array();
private $params = array();
private $subtotal = 0;
private $discount = 0;
private $itemCount = 0;
function __construct()
{
# Get $config array
if (is_file(dirname(__FILE__) . '/config.php'))
include_once dirname(__FILE__) . '/config-loader.php';
else
{
preg_match('/(.*)jcart/', 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'], $uri);
header('Location: ' . $uri[1] . 'jcart/install/');
}
$this->config = $config;
foreach ($config['param'] as $param_name)
{
$this->params[$param_name] = array();
}
# Добавляем в корзину товар по умолчанию
if (isset($config['default_product']))
$this->add_item($config['default_product']['id'], $config['default_product']['name'], $config['default_product']['price'], $config['default_product']['discount'], $config['default_product']['qty'], $config['default_product']['url'], $config['default_product']['size'], $config['default_product']['color'], $config['default_product']['param']);
}
public function get_subtotal()
{
return $this->subtotal;
}
/**
* Get cart contents
*
* @return array
*/
public function get_contents()
{
$items = array();
$params = array();
foreach ($this->items as $tmpItem)
{
$item = null;
$item['id'] = $tmpItem;
foreach ($this->config['param'] as $param_name)
{
$item[$param_name] = $this->params[$param_name][$tmpItem];
}
$item['subtotal'] = $item['price'] * $item['qty'] * (1 - max($this->discount, $item['discount']) / 100);
$items[] = $item;
}
return $items;
}
/**
* Add an item to the cart
*
* @param string $id
* @param string $name
* @param float $price
* @param mixed $qty
* @param string $url
*
* @return mixed
*/
private function add_item($cart_data)
{
$id = $cart_data['id'];
foreach ($this->config['param'] as $param_name)
{
if ($this->config['encoding'] == 'windows-1251' && is_string($cart_data[$param_name]))
{
@$$param_name = iconv('utf-8', 'windows-1251', $cart_data[$param_name]);
//$$param_name = $cart_data[$param_name];
}
else
$$param_name = $cart_data[$param_name];
}
$validPrice = false;
$validQty = false;
# Verify the price is numeric
if (is_numeric($price))
{
$validPrice = true;
}
# If decimal quantities are enabled, verify the quantity is a positive float
if ($this->config['decimalQtys'] === true && filter_var($qty, FILTER_VALIDATE_FLOAT) && $qty > 0)
{
$validQty = true;
} # By default, verify the quantity is a positive integer
elseif (filter_var($qty, FILTER_VALIDATE_INT) && $qty > 0)
{
$validQty = true;
}
# Add the item
if ($validPrice !== false && $validQty !== false)
{
# If the item is already in the cart , increase its quantity
if (isset($this->params['qty'][$id]) && $this->params['qty'][$id] > 0)
{
$this->params['qty'][$id] += $qty;
$this->update_subtotal();
} # This is a new item
else
{
$this->items[] = $id;
foreach ($this->config['param'] as $param_name)
{
$this->params[$param_name][$id] = $$param_name;
}
}
$this->update_subtotal();
return true;
} elseif ($validPrice !== true)
{
$errorType = 'price';
return $errorType;
} elseif ($validQty !== true)
{
$errorType = 'qty';
return $errorType;
}
}
# Склонение существительных с числительными (http://mcaizer.habrahabr.ru/blog/11555/)
public function plural($n, $form1, $form2, $form5)
{
$n = abs($n) % 100;
$n1 = $n % 10;
if ($n > 10 && $n < 20) return $form5;
else if ($n1 > 1 && $n1 < 5) return $form2;
else if ($n1 == 1) return $form1;
return $form5;
} # echo $n." ".plural($n, "письмо", "письма", "писем")." у Вас в ящике";
/**
* Update an item in the cart
*
* @param string $id
* @param mixed $qty
*
* @return boolean
*/
private function update_item($id, $qty)
{
$validQty = false;
# If the quantity is zero, no futher validation is required
if ((int)$qty === 0)
{
$validQty = true;
} # If decimal quantities are enabled, verify it's a float
elseif ($this->config['decimalQtys'] === true && filter_var($qty, FILTER_VALIDATE_FLOAT))
{
$validQty = true;
} # By default, verify the quantity is an integer
elseif (filter_var($qty, FILTER_VALIDATE_INT))
{
$validQty = true;
}
# If it's a valid quantity, remove or update as necessary
if ($validQty === true)
{
if ($qty < 1)
{
$this->remove_item($id);
}
else
{
$this->params['qty'][$id] = $qty;
}
$this->update_subtotal();
return true;
}
}
/* Using post vars to remove items doesn't work because we have to pass the
id of the item to be removed as the value of the button. If using an input
with type submit, all browsers display the item id, instead of allowing for
user-friendly text. If using an input with type image, IE does not submit
the value, only x and y coordinates where button was clicked. Can't use a
hidden input either since the cart form has to encompass all items to
recalculate subtotal when a quantity is changed, which means there are
multiple remove buttons and no way to associate them with the correct
hidden input. */
/**
* Reamove an item from the cart
*
* @param string $id *
*/
private function remove_item($id)
{
$tmpItems = array();
foreach ($this->config['param'] as $param_name)
{
unset($this->params[$param_name][$id]);
}
# Rebuild the items array, excluding the id we just removed
foreach ($this->items as $item)
{
if ($item != $id)
{
$tmpItems[] = $item;
}
}
$this->items = $tmpItems;
$this->update_subtotal();
}
/**
* Empty the cart
*/
public function empty_cart()
{
foreach ($this->config['param'] as $param_name)
{
$this->params[$param_name] = array();
}
$this->items = array();
$this->subtotal = 0;
$this->discount = 0;
$this->itemCount = 0;
}
/**
* Update the entire cart
*/
public function update_cart()
{
# Post value is an array of all item quantities in the cart
# Treat array as a string for validation
if (isset($_POST['jcartItemQty']) && is_array($_POST['jcartItemQty']))
{
$qtys = implode($_POST['jcartItemQty']);
}
# If no item ids, the cart is empty
if (isset($_POST['jcartItemId']))
{
$validQtys = false;
# If decimal quantities are enabled, verify the combined string only contain digits and decimal points
if ($this->config['decimalQtys'] === true && preg_match("/^[0-9.,]+$/i", $qtys))
{
$validQtys = true;
} # By default, verify the string only contains integers
elseif (filter_var($qtys, FILTER_VALIDATE_INT) || $qtys == '')
{
$validQtys = true;
}
if ($validQtys === true)
{
# The item index
$count = 0;
# For each item in the cart, remove or update as necessary
foreach ($_POST['jcartItemId'] as $id)
{
$qty = str_replace(',', '.', $_POST['jcartItemQty'][$count]);
if ($qty < 1)
{
$this->remove_item($id);
} else
{
$this->update_item($id, $qty);
}
# Increment index for the next item
$count++;
}
return true;
}
} # If no items in the cart, return true to prevent unnecssary error message
elseif (!isset($_POST['jcartItemId']))
{
return true;
}
}
/**
* Recalculate subtotal
*/
private function update_subtotal()
{
$this->itemCount = 0;
$this->subtotal = 0;
if (sizeof($this->items > 0))
{
foreach ($this->items as $item)
{
$this->subtotal += ($this->params['qty'][$item] * $this->params['price'][$item] * (1 - max($this->params['discount'][$item], $this->discount) / 100));
# Total number of items
$this->itemCount += $this->params['qty'][$item];
}
}
}
/**
* Get currency symbol by code
*
* @param string $currencyCode
* @return void
*/
function currencySymbol($currencyCode)
{
switch ($currencyCode)
{
case 'EUR':
return $currencySymbol = '€';
case 'GBP':
return $currencySymbol = '£';
case 'JPY':
return $currencySymbol = '¥';
case 'CHF':
return $currencySymbol = 'CHF ';
case 'NOK':
return $currencySymbol = 'Kr ';
case 'PLN':
return $currencySymbol = 'zł ';
case 'HUF':
return $currencySymbol = 'Ft ';
case 'CZK':
return $currencySymbol = 'Kč ';
case 'ILS':
return $currencySymbol = '₪ ';
case 'TWD':
return $currencySymbol = 'NT$';
case 'THB':
return $currencySymbol = '฿';
case 'MYR':
return $currencySymbol = 'RM';
case 'PHP':
return $currencySymbol = 'Php';
case 'BRL':
return $currencySymbol = 'R$';
case 'RUR':
return $currencySymbol = 'руб.';
case 'UAH':
return $currencySymbol = 'грн.';
case 'USD':
default:
return $currencySymbol = '$';
}
}
/**
* Process and display cart
*/
public function display_cart()
{
$config = $this->config;
$errorMessage = null;
# Simplify some config variables
$checkout = $config['sitelink'] . $config['checkoutPath'];
$priceFormat = $config['priceFormat'];
foreach ($this->config['item'] as $param_name => $atr_name)
{
${$param_name} = $atr_name;
}
# Use config values as literal indices for incoming POST values
# Values are the HTML name attributes set in config.json
$id = (isset($_POST[$id])) ? $_POST[$id] : '';
foreach ($this->config['param'] as $param_name)
{
if($param_name == 'qty')
{
$$param_name = (isset($_POST[$$param_name])) ? str_replace(',', '.', $_POST[$$param_name]) : '';
}
else
$$param_name = (isset($_POST[$$param_name])) ? $_POST[$$param_name] : '';
}
# Optional CSRF protection, see: http://conceptlogic.com/jcart/security.php
$jcartToken = (isset($_POST['jcartToken'])) ? $_POST['jcartToken'] : '';
# Only generate unique token once per session
if (!isset($_SESSION['jcartToken']))
{
$_SESSION['jcartToken'] = md5(session_id() . time() . $_SERVER['HTTP_USER_AGENT']);
}
# If enabled, check submitted token against session token for POST requests
if ($config['csrfToken'] == true && !empty($_POST) && $jcartToken != $_SESSION['jcartToken'] && isset($_POST[$add]))
{
$errorMessage = 'Invalid token!' . $jcartToken . ' / ' . $_SESSION['jcartToken'];
}
# Sanitize values for output in the browser
$id = filter_var($id, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW);
$name = filter_var($name, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FLAG_STRIP_LOW);
if (isset($url))
$url = filter_var($url, FILTER_SANITIZE_URL);
# Round the quantity if necessary
if ($config['decimalQtys'] === true)
{
$qty = round($qty, $config['decimalPlaces']);
}
# Add an item
if (isset($config['unique']))
{
foreach ($config['unique'] as $unic)
{
$id .= '_' . $$unic;
}
}
$cart_data = array();
$cart_data['id'] = $id;
foreach ($this->config['param'] as $param_name)
{
$cart_data[$param_name] = $$param_name;
}
if (isset($_POST[$add]) || isset($_POST[$add . '_x']))
{
$itemAdded = $this->add_item($cart_data);
# If not true the add item function returns the error type
if ($itemAdded !== true)
{
$errorType = $itemAdded;
switch ($errorType)
{
case 'qty':
$errorMessage = $config['text']['quantityError'];
break;
case 'price':
$errorMessage = $config['text']['priceError'];
break;
}
}
}
# Update a single item
if (isset($_POST['jcartUpdate']))
{
$itemUpdated = $this->update_item($_POST['itemId'], str_replace(',', '.', $_POST['itemQty']));
if ($itemUpdated !== true)
{
$errorMessage = $config['text']['quantityError'];
}
}
# Update all items in the cart
if (isset($_POST['jcartUpdateCart']) || isset($_POST['jcartCheckout']))
{
$cartUpdated = $this->update_cart();
if ($cartUpdated !== true)
{
$errorMessage = $config['text']['quantityError'];
}
}
# Remove an item
/* After an item is removed, its id stays set in the query string,
preventing the same item from being added back to the cart in
subsequent POST requests. As result, it's not enough to check for
GET before deleting the item, must also check that this isn't a POST
request. */
if (isset($_GET['jcartRemove']) && empty($_POST))
{
$this->remove_item($_GET['jcartRemove']);
}
# Empty the cart
if (isset($_POST['jcartEmpty']))
{
$this->empty_cart();
}
# Determine which text to use for the number of items in the cart
$itemsText = $this->plural($this->itemCount, $config['text']['singleItem'], $config['text']['multipleItems1'], $config['text']['multipleItems2']);
# Determine if this is the checkout page
/* First we check the request uri against the config checkout (set when
the visitor first clicks checkout), then check for the hidden input
sent with Ajax request (set when visitor has javascript enabled and
updates an item quantity). */
#$isCheckout = strpos(request_uri(), $checkout);
$isCheckout = strpos('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'], $checkout);
if ($isCheckout !== false || isset($_REQUEST['jcartIsCheckout']) && $_REQUEST['jcartIsCheckout'] == 'true')
{
$isCheckout = true;
} else
{
$isCheckout = false;
}
# Overwrite the form action to post to gateway.php instead of posting back to checkout page
if ($isCheckout === true)
{
# Sanititze config path
$path = filter_var($config['jcartPath'], FILTER_SANITIZE_URL);
# Trim trailing slash if necessary
$path = rtrim($path, '/');
$checkout = $config['sitelink'] . $path . '/gateway.php';
}
# Default input types
# Overridden if using button images in config.php
$inputTypeCheckout = $inputTypeUpdate = $inputTypeEmpty = $inputTypeCheckoutPaypal = 'submit';
# If this error is true the visitor updated the cart from the checkout page using an invalid price format
# Passed as a session var since the checkout page uses a header redirect
# If passed via GET the query string stays set even after subsequent POST requests
if (isset($_SESSION['quantityError']) && $_SESSION['quantityError'] === true)
{
$errorMessage = $config['text']['quantityError'];
unset($_SESSION['quantityError']);
}
# Set currency symbol based on config currency code
$currencyCode = trim(strtoupper($config['currencyCode']));
$currencySymbol = $this->currencySymbol($currencyCode);
# Модуль работы с пользователями
if (($config['auth']['enabled'] == true || isset($config['discounts'])) && is_file(dirname(__FILE__) . '/modules/M_Users.inc.php'))
{
include_once dirname(__FILE__) . '/modules/M_Users.inc.php';
$mUsers = M_Users::Instance();
# Авторизация пользователя
if (!isset($_SESSION['id_user']) && isset($_COOKIE['email']) && isset($_COOKIE['password']))
{
$mUsers->Login($_COOKIE['email'], $_COOKIE['password']);
}
if (isset($_SESSION['id_user']))
{
$user = $mUsers->GetLastOrder($_SESSION['id_user']);
$email = (isset($user['email'])) ? $user['email'] : '';
$name = (isset($user['name'])) ? $user['name'] : '';
$lastname = (isset($user['lastname'])) ? $user['lastname'] : '';
$fathername = (isset($user['fathername'])) ? $user['fathername'] : '';
$zip = (isset($user['zip'])) ? $user['zip'] : '';
$region = (isset($user['region'])) ? $user['region'] : '';
$city = (isset($user['city'])) ? $user['city'] : '';
$address = (isset($user['address'])) ? $user['address'] : '';
$phone = (isset($user['phone'])) ? $user['phone'] : '';
$order_delivery = (isset($user['delivery'])) ? $user['delivery'] : '';
$order_payment = (isset($user['payment'])) ? $user['payment'] : '';
$juridical = (!empty($user['juridical'])) ? explode('|', $user['juridical']) : '';
if (!empty($juridical))
{
$juridical_inn = (isset($juridical[0])) ? $juridical[0] : '';
$juridical_kpp = (isset($juridical[1])) ? $juridical[1] : '';
$juridical_firm = (isset($juridical[2])) ? $juridical[2] : '';
}
if (isset($config['discounts']))
$user += $mUsers->CountDiscount($this->subtotal + $user['sum'], $config['discounts']);
$_COOKIE['user-sum'] = (isset($user['sum'])) ? $user['sum'] : '';
}
}
if (isset($config['discounts']) && !isset($user['discount']))
$user = $mUsers->CountDiscount($this->subtotal, $config['discounts']);
if (!isset($user['discount']))
$user['discount'] = 0;
else
$this->discount = $user['discount'];
if (isset($config['discounts']))
$this->update_subtotal();
# If there's an error message wrap it in some HTML
if (isset($errorMessage))
{
$errorMessage = '<p id="jcart-error">' . $errorMessage . '</p>';
}
# If this is the checkout hide the cart checkout button
if ($isCheckout !== true)
{
if ($config['button']['checkout'])
{
$inputTypeCheckout = 'image';
$srcCheckout = ' src="' . $config['button']['checkout'] . '" alt="' . $config['text']['checkout'] . '" title="" ';
}
}
if ($config['button']['update'])
{
$inputTypeUpdate = 'image';
$srcUpdate = ' src="' . $config['button']['update'] . '" alt="' . $config['text']['update'] . '" title="" ';
}
if ($config['button']['empty'])
{
$inputTypeEmpty = 'image';
$srcEmpty = ' src="' . $config['button']['empty'] . '" alt="' . $config['text']['emptyButton'] . '" title="" ';
}
# If this is the checkout display the PayPal checkout button
if ($isCheckout === true)
{
# Hidden input allows us to determine if we're on the checkout page
# We normally check against request uri but ajax update sets value to relay.php
# PayPal checkout button
if ($config['button']['paypal'])
{
$inputTypeCheckoutPaypal = 'image';
$srcCheckoutPaypal = ' src="' . $config['button']['paypal'] . '" alt="' . $config['text']['checkoutPaypal'] . '" title="" ';
}
if ($this->itemCount <= 0)
{
$disablePaypalCheckout = ' disabled="disabled"';
}
if (is_file(dirname(__FILE__) . '/modules/M_Email.inc.php'))
{
# Генерация антиспама
include_once dirname(__FILE__) . '/modules/M_Email.inc.php';
$mEmail = M_Email::Instance();
$antispam = $mEmail->GenerateAntispam($config['secretWord']);
}
}
if ($isCheckout != true && $config['modal'] == true)
{
ob_start();
include_once dirname(__FILE__) . '/design/CartModal.tpl.php';
$modal_cart = ob_get_clean();
}
if ($isCheckout != true && $config['smallCart'] == true)
include_once dirname(__FILE__) . '/design/CartSmall.tpl.php';
else
include_once dirname(__FILE__) . '/design/Cart.tpl.php';
if ($isCheckout === true) {
include_once dirname(__FILE__) . '/design/CartOrderForm.tpl.php';
}
}
}
# Start a new session in case it hasn't already been started on the including page
if (isset($config['session']['length']))
ini_set('session.gc_maxlifetime', $config['session']['length']);
if (isset($config['cookie']['length']) && $config['cookie']['length'] > 0)
ini_set('session.cookie_lifetime', $config['cookie']['length']);
@session_start();
# Initialize jcart after session start
$jcart = (isset($_SESSION['jcart'])) ? $_SESSION['jcart'] : '';
if (!is_object($jcart))
{
$jcart = $_SESSION['jcart'] = new Jcart();
}
# Only generate unique token once per session
if (!isset($_SESSION['jcartToken']) && isset($_SERVER['HTTP_USER_AGENT']))
{
$_SESSION['jcartToken'] = md5(session_id() . time() . $_SERVER['HTTP_USER_AGENT']);
}
# Enable request_uri for non-Apache environments
# See: http://api.drupal.org/api/function/request_uri/7
if (!function_exists('request_uri'))
{
function request_uri()
{
if (isset($_SERVER['REQUEST_URI']))
{
$uri = $_SERVER['REQUEST_URI'];
} else
{
if (isset($_SERVER['argv']))
{
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
} elseif (isset($_SERVER['QUERY_STRING']))
{
$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
} else
{
$uri = $_SERVER['SCRIPT_NAME'];
}
}
$uri = '/' . ltrim($uri, '/');
return $uri;
}
}
# Функция вывода ошибки
if (!function_exists('error404'))
{
function error404($pageout = false, $encoding = 'utf-8')
{
header('Cache-Control: no-cache, no-store');
header('Content-Type: text/html; charset=' . $encoding);
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
if ($pageout)
readfile('404.shtml');
die;
}
} |