Completed
Push — master ( df7b08...6ca0e7 )
by Harald
05:46 queued 02:54
created

catalog/includes/functions/general.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
  * osCommerce Online Merchant
4
  *
5
  * @copyright (c) 2016 osCommerce; https://www.oscommerce.com
6
  * @license MIT; https://www.oscommerce.com/license/mit.txt
7
  */
8
9
  use OSC\OM\HTML;
10
  use OSC\OM\OSCOM;
11
  use OSC\OM\Registry;
12
13
////
14
// Return a product's name
15
// TABLES: products
16
  function tep_get_products_name($product_id, $language_id = null) {
17
    $OSCOM_Db = Registry::get('Db');
18
    $OSCOM_Language = Registry::get('Language');
19
20
    if (empty($language_id) || !is_numeric($language_id)) $language_id = $OSCOM_Language->getId();
21
22
    $Qproduct = $OSCOM_Db->prepare('select products_name from :table_products_description where products_id = :products_id and language_id = :language_id');
23
    $Qproduct->bindInt(':products_id', $product_id);
24
    $Qproduct->bindInt(':language_id', $language_id);
25
    $Qproduct->execute();
26
27
    return $Qproduct->value('products_name');
28
  }
29
30
////
31
// Return a product's special price (returns nothing if there is no offer)
32
// TABLES: products
33
  function tep_get_products_special_price($product_id) {
34
    $OSCOM_Db = Registry::get('Db');
35
36
    $result = false;
37
38
    $Qproduct = $OSCOM_Db->prepare('select specials_new_products_price from :table_specials where products_id = :products_id and status = 1');
39
    $Qproduct->bindInt(':products_id', $product_id);
40
    $Qproduct->execute();
41
42
    if ($Qproduct->fetch() !== false) {
43
      $result = $Qproduct->valueDecimal('specials_new_products_price');
44
    }
45
46
    return $result;
47
  }
48
49
////
50
// Return a product's stock
51
// TABLES: products
52
  function tep_get_products_stock($products_id) {
53
    $OSCOM_Db = Registry::get('Db');
54
55
    $Qproduct = $OSCOM_Db->prepare('select products_quantity from :table_products where products_id = :products_id');
56
    $Qproduct->bindInt(':products_id', tep_get_prid($products_id));
57
    $Qproduct->execute();
58
59
    return $Qproduct->valueInt('products_quantity');
60
  }
61
62
////
63
// Check if the required stock is available
64
// If insufficent stock is available return an out of stock message
65
  function tep_check_stock($products_id, $products_quantity) {
66
    $stock_left = tep_get_products_stock($products_id) - $products_quantity;
67
    $out_of_stock = '';
68
69
    if ($stock_left < 0) {
70
      $out_of_stock = '<span class="text-danger"><b>' . STOCK_MARK_PRODUCT_OUT_OF_STOCK . '</b></span>';
71
    }
72
73
    return $out_of_stock;
74
  }
75
76
////
77
// Break a word in a string if it is longer than a specified length ($len)
78 View Code Duplication
  function tep_break_string($string, $len, $break_char = '-') {
79
    $l = 0;
80
    $output = '';
81
    for ($i=0, $n=strlen($string); $i<$n; $i++) {
82
      $char = substr($string, $i, 1);
83
      if ($char != ' ') {
84
        $l++;
85
      } else {
86
        $l = 0;
87
      }
88
      if ($l > $len) {
89
        $l = 1;
90
        $output .= $break_char;
91
      }
92
      $output .= $char;
93
    }
94
95
    return $output;
96
  }
97
98
////
99
// Return all $_GET variables, except those passed as a parameter
100
  function tep_get_all_get_params($exclude_array = '') {
101
    if (!is_array($exclude_array)) $exclude_array = array();
102
103
    $exclude_array[] = session_name();
104
    $exclude_array[] = 'error';
105
    $exclude_array[] = 'x';
106
    $exclude_array[] = 'y';
107
108
    $get_url = '';
109
110
    if (is_array($_GET) && (!empty($_GET))) {
111
      foreach ($_GET as $key => $value) {
112
        if ( !in_array($key, $exclude_array) ) {
113
          $get_url .= $key . '=' . rawurlencode($value) . '&';
114
        }
115
     }
116
  }
117
    return $get_url;
118
}
119
120
////
121
// Returns an array with countries
122
// TABLES: countries
123
  function tep_get_countries($countries_id = '', $with_iso_codes = false) {
124
    $OSCOM_Db = Registry::get('Db');
125
126
    $countries_array = array();
127
128
    if (tep_not_null($countries_id)) {
129
      if ($with_iso_codes == true) {
130
        $Qcountries = $OSCOM_Db->prepare('select countries_name, countries_iso_code_2, countries_iso_code_3 from :table_countries where countries_id = :countries_id');
131
        $Qcountries->bindInt(':countries_id', $countries_id);
132
        $Qcountries->execute();
133
134
        $countries_array = $Qcountries->toArray();
135 View Code Duplication
      } else {
136
        $Qcountries = $OSCOM_Db->prepare('select countries_name from :table_countries where countries_id = :countries_id');
137
        $Qcountries->bindInt(':countries_id', $countries_id);
138
        $Qcountries->execute();
139
140
        $countries_array = $Qcountries->toArray();
141
      }
142
    } else {
143
      $countries_array = $OSCOM_Db->query('select countries_id, countries_name from :table_countries order by countries_name')->fetchAll();
144
    }
145
146
    return $countries_array;
147
  }
148
149
////
150
// Alias function to tep_get_countries, which also returns the countries iso codes
151
  function tep_get_countries_with_iso_codes($countries_id) {
152
    return tep_get_countries($countries_id, true);
153
  }
154
155
////
156
// Generate a path to categories
157
  function tep_get_path($current_category_id = '') {
158
    global $cPath_array;
159
160
    $OSCOM_Db = Registry::get('Db');
161
162
    if (tep_not_null($current_category_id)) {
163
      $cp_size = sizeof($cPath_array);
164
      if ($cp_size == 0) {
165
        $cPath_new = $current_category_id;
166
      } else {
167
        $cPath_new = '';
168
169
        $QlastCategory = $OSCOM_Db->prepare('select parent_id from :table_categories where categories_id = :categories_id');
170
        $QlastCategory->bindInt(':categories_id', $cPath_array[($cp_size-1)]);
171
        $QlastCategory->execute();
172
173
        $QcurrentCategory = $OSCOM_Db->prepare('select parent_id from :table_categories where categories_id = :categories_id');
174
        $QcurrentCategory->bindInt(':categories_id', $current_category_id);
175
        $QcurrentCategory->execute();
176
177
        if ($QlastCategory->valueInt('parent_id') == $QcurrentCategory->valueInt('parent_id')) {
178 View Code Duplication
          for ($i=0; $i<($cp_size-1); $i++) {
179
            $cPath_new .= '_' . $cPath_array[$i];
180
          }
181
        } else {
182 View Code Duplication
          for ($i=0; $i<$cp_size; $i++) {
183
            $cPath_new .= '_' . $cPath_array[$i];
184
          }
185
        }
186
        $cPath_new .= '_' . $current_category_id;
187
188
        if (substr($cPath_new, 0, 1) == '_') {
189
          $cPath_new = substr($cPath_new, 1);
190
        }
191
      }
192
    } else {
193
      $cPath_new = implode('_', $cPath_array);
194
    }
195
196
    return 'cPath=' . $cPath_new;
197
  }
198
199
////
200
// Alias function to tep_get_countries()
201
  function tep_get_country_name($country_id) {
202
    $country_array = tep_get_countries($country_id);
203
204
    return $country_array['countries_name'];
205
  }
206
207
////
208
// Returns the zone (State/Province) name
209
// TABLES: zones
210 View Code Duplication
  function tep_get_zone_name($country_id, $zone_id, $default_zone) {
211
    $OSCOM_Db = Registry::get('Db');
212
213
    $Qzone = $OSCOM_Db->prepare('select zone_name from :table_zones where zone_country_id = :zone_country_id and zone_id = :zone_id');
214
    $Qzone->bindInt(':zone_country_id', $country_id);
215
    $Qzone->bindInt(':zone_id', $zone_id);
216
    $Qzone->execute();
217
218
    if ($Qzone->fetch() !== false) {
219
      return $Qzone->value('zone_name');
220
    } else {
221
      return $default_zone;
222
    }
223
  }
224
225
////
226
// Returns the zone (State/Province) code
227
// TABLES: zones
228 View Code Duplication
  function tep_get_zone_code($country_id, $zone_id, $default_zone) {
229
    $OSCOM_Db = Registry::get('Db');
230
231
    $Qzone = $OSCOM_Db->prepare('select zone_code from :table_zones where zone_country_id = :zone_country_id and zone_id = :zone_id');
232
    $Qzone->bindInt(':zone_country_id', $country_id);
233
    $Qzone->bindInt(':zone_id', $zone_id);
234
    $Qzone->execute();
235
236
    if ($Qzone->fetch() !== false) {
237
      return $Qzone->value('zone_code');
238
    } else {
239
      return $default_zone;
240
    }
241
  }
242
243
////
244
// Wrapper function for round()
245
  function tep_round($number, $precision) {
246
    if (strpos($number, '.') && (strlen(substr($number, strpos($number, '.')+1)) > $precision)) {
247
      $number = substr($number, 0, strpos($number, '.') + 1 + $precision + 1);
248
249
      if (substr($number, -1) >= 5) {
250
        if ($precision > 1) {
251
          $number = substr($number, 0, -1) + ('0.' . str_repeat(0, $precision-1) . '1');
252
        } elseif ($precision == 1) {
253
          $number = substr($number, 0, -1) + 0.1;
254
        } else {
255
          $number = substr($number, 0, -1) + 1;
256
        }
257
      } else {
258
        $number = substr($number, 0, -1);
259
      }
260
    }
261
262
    return $number;
263
  }
264
265
////
266
// Returns the tax rate for a zone / class
267
// TABLES: tax_rates, zones_to_geo_zones
268
  function tep_get_tax_rate($class_id, $country_id = -1, $zone_id = -1) {
269
    static $tax_rates = array();
270
271
    $OSCOM_Db = Registry::get('Db');
272
273
    if ( ($country_id == -1) && ($zone_id == -1) ) {
274
      if (!isset($_SESSION['customer_id'])) {
275
        $country_id = STORE_COUNTRY;
276
        $zone_id = STORE_ZONE;
277
      } else {
278
        $country_id = $_SESSION['customer_country_id'];
279
        $zone_id = $_SESSION['customer_zone_id'];
280
      }
281
    }
282
283
    if (!isset($tax_rates[$class_id][$country_id][$zone_id]['rate'])) {
284
      $Qtax = $OSCOM_Db->prepare('select sum(tr.tax_rate) as tax_rate from :table_tax_rates tr left join :table_zones_to_geo_zones za on (tr.tax_zone_id = za.geo_zone_id) left join :table_geo_zones tz on (tz.geo_zone_id = tr.tax_zone_id) where (za.zone_country_id is null or za.zone_country_id = 0 or za.zone_country_id = :zone_country_id) and (za.zone_id is null or za.zone_id = 0 or za.zone_id = :zone_id) and tr.tax_class_id = :tax_class_id group by tr.tax_priority');
285
      $Qtax->bindInt(':zone_country_id', $country_id);
286
      $Qtax->bindInt(':zone_id', $zone_id);
287
      $Qtax->bindInt(':tax_class_id', $class_id);
288
      $Qtax->execute();
289
290
      if ($Qtax->fetch() !== false) {
291
        $tax_multiplier = 1.0;
292
293
        do {
294
          $tax_multiplier *= 1.0 + ($Qtax->valueDecimal('tax_rate') / 100);
295
        } while ($Qtax->fetch());
296
297
        $tax_rates[$class_id][$country_id][$zone_id]['rate'] = ($tax_multiplier - 1.0) * 100;
298
      } else {
299
        $tax_rates[$class_id][$country_id][$zone_id]['rate'] = 0;
300
      }
301
    }
302
303
    return $tax_rates[$class_id][$country_id][$zone_id]['rate'];
304
  }
305
306
////
307
// Return the tax description for a zone / class
308
// TABLES: tax_rates;
309
  function tep_get_tax_description($class_id, $country_id, $zone_id) {
310
    static $tax_rates = array();
311
312
    $OSCOM_Db = Registry::get('Db');
313
314
    if (!isset($tax_rates[$class_id][$country_id][$zone_id]['description'])) {
315
      $Qtax = $OSCOM_Db->prepare('select tr.tax_description from :table_tax_rates tr left join :table_zones_to_geo_zones za on (tr.tax_zone_id = za.geo_zone_id) left join :table_geo_zones tz on (tz.geo_zone_id = tr.tax_zone_id) where (za.zone_country_id is null or za.zone_country_id = 0 or za.zone_country_id = :zone_country_id) and (za.zone_id is null or za.zone_id = 0 or za.zone_id = :zone_id) and tr.tax_class_id = :tax_class_id order by tr.tax_priority');
316
      $Qtax->bindInt(':zone_country_id', $country_id);
317
      $Qtax->bindInt(':zone_id', $zone_id);
318
      $Qtax->bindInt(':tax_class_id', $class_id);
319
      $Qtax->execute();
320
321
      if ($Qtax->fetch() !== false) {
322
        $tax_description = '';
323
324
        do {
325
          $tax_description .= $Qtax->value('tax_description') . ' + ';
326
        } while ($Qtax->fetch());
327
328
        $tax_description = substr($tax_description, 0, -3);
329
330
        $tax_rates[$class_id][$country_id][$zone_id]['description'] = $tax_description;
331
      } else {
332
        $tax_rates[$class_id][$country_id][$zone_id]['description'] = OSCOM::getDef('text_unknown_tax_rate');
333
      }
334
    }
335
336
    return $tax_rates[$class_id][$country_id][$zone_id]['description'];
337
  }
338
339
////
340
// Add tax to a products price
341
  function tep_add_tax($price, $tax) {
342 View Code Duplication
    if ( (DISPLAY_PRICE_WITH_TAX == 'true') && ($tax > 0) ) {
343
      return $price + tep_calculate_tax($price, $tax);
344
    } else {
345
      return $price;
346
    }
347
  }
348
349
// Calculates Tax rounding the result
350
  function tep_calculate_tax($price, $tax) {
351
    return $price * $tax / 100;
352
  }
353
354
////
355
// Return the number of products in a category
356
// TABLES: products, products_to_categories, categories
357
  function tep_count_products_in_category($category_id, $include_inactive = false) {
358
    $OSCOM_Db = Registry::get('Db');
359
360
    $products_count = 0;
361
362
    $products_query = 'select count(*) as total from :table_products p, :table_products_to_categories p2c where p.products_id = p2c.products_id and p2c.categories_id = :categories_id';
363
364
    if ($include_inactive == false) {
365
      $products_query .= ' and p.products_status = 1';
366
    }
367
368
    $Qproducts = $OSCOM_Db->prepare($products_query);
369
    $Qproducts->bindInt(':categories_id', $category_id);
370
    $Qproducts->execute();
371
372
    if ($Qproducts->fetch() !== false) {
373
      $products_count += $Qproducts->valueInt('total');
374
    }
375
376
    $Qcategories = $OSCOM_Db->prepare('select categories_id from :table_categories where parent_id = :parent_id');
377
    $Qcategories->bindInt(':parent_id', $category_id);
378
    $Qcategories->execute();
379
380
    if ($Qcategories->fetch() !== false) {
381
      do {
382
        $products_count += tep_count_products_in_category($Qcategories->valueInt('categories_id'), $include_inactive);
383
      } while ($Qcategories->fetch());
384
    }
385
386
    return $products_count;
387
  }
388
389
////
390
// Return true if the category has subcategories
391
// TABLES: categories
392 View Code Duplication
  function tep_has_category_subcategories($category_id) {
393
    $OSCOM_Db = Registry::get('Db');
394
395
    $Qcheck = $OSCOM_Db->prepare('select categories_id from :table_categories where parent_id = :parent_id limit 1');
396
    $Qcheck->bindInt(':parent_id', $category_id);
397
    $Qcheck->execute();
398
399
    return ($Qcheck->fetch() !== false);
400
  }
401
402
////
403
// Returns the address_format_id for the given country
404
// TABLES: countries;
405 View Code Duplication
  function tep_get_address_format_id($country_id) {
406
    $OSCOM_Db = Registry::get('Db');
407
408
    $format_id = 1;
409
410
    $Qformat = $OSCOM_Db->prepare('select address_format_id from :table_countries where countries_id = :countries_id');
411
    $Qformat->bindInt(':countries_id', $country_id);
412
    $Qformat->execute();
413
414
    if ($Qformat->fetch() !== false) {
415
      $format_id = $Qformat->valueInt('address_format_id');
416
    }
417
418
    return $format_id;
419
  }
420
421
////
422
// Return a formatted address
423
// TABLES: address_format
424
  function tep_address_format($address_format_id, $address, $html, $boln, $eoln) {
425
    $OSCOM_Db = Registry::get('Db');
426
427
    $Qformat = $OSCOM_Db->prepare('select address_format from :table_address_format where address_format_id = :address_format_id');
428
    $Qformat->bindInt(':address_format_id', $address_format_id);
429
    $Qformat->execute();
430
431
    $replace = [
432
      '$company' => HTML::outputProtected($address['company']),
433
      '$firstname' => '',
434
      '$lastname' => '',
435
      '$street' => HTML::outputProtected($address['street_address']),
436
      '$suburb' => HTML::outputProtected($address['suburb']),
437
      '$city' => HTML::outputProtected($address['city']),
438
      '$state' => HTML::outputProtected($address['state']),
439
      '$postcode' => HTML::outputProtected($address['postcode']),
440
      '$country' => ''
441
    ];
442
443 View Code Duplication
    if (isset($address['firstname']) && tep_not_null($address['firstname'])) {
444
      $replace['$firstname'] = HTML::outputProtected($address['firstname']);
445
      $replace['$lastname'] = HTML::outputProtected($address['lastname']);
446
    } elseif (isset($address['name']) && tep_not_null($address['name'])) {
447
      $replace['$firstname'] = HTML::outputProtected($address['name']);
448
    }
449
450 View Code Duplication
    if (isset($address['country_id']) && tep_not_null($address['country_id'])) {
451
      $replace['$country'] = tep_get_country_name($address['country_id']);
452
453
      if (isset($address['zone_id']) && tep_not_null($address['zone_id'])) {
454
        $replace['$state'] = tep_get_zone_code($address['country_id'], $address['zone_id'], $replace['$state']);
455
      }
456
    } elseif (isset($address['country']) && tep_not_null($address['country'])) {
457
      $replace['$country'] = HTML::outputProtected($address['country']['title']);
458
    }
459
460
    $replace['$zip'] = $replace['$postcode'];
461
462 View Code Duplication
    if ($html) {
463
// HTML Mode
464
      $HR = '<hr />';
465
      $hr = '<hr />';
466
      if ( ($boln == '') && ($eoln == "\n") ) { // Values not specified, use rational defaults
467
        $CR = '<br />';
468
        $cr = '<br />';
469
        $eoln = $cr;
470
      } else { // Use values supplied
471
        $CR = $eoln . $boln;
472
        $cr = $CR;
473
      }
474
    } else {
475
// Text Mode
476
      $CR = $eoln;
477
      $cr = $CR;
478
      $HR = '----------------------------------------';
479
      $hr = '----------------------------------------';
480
    }
481
482
    $replace['$CR'] = $CR;
483
    $replace['$cr'] = $cr;
484
    $replace['$HR'] = $HR;
485
    $replace['$hr'] = $hr;
486
487
    $replace['$statecomma'] = '';
488
    $replace['$streets'] = $replace['$street'];
489 View Code Duplication
    if ($replace['$suburb'] != '') $replace['$streets'] = $replace['$street'] . $replace['$cr'] . $replace['$suburb'];
490
    if ($replace['$state'] != '') $replace['$statecomma'] = $replace['$state'] . ', ';
491
492
    $address = strtr($Qformat->value('address_format'), $replace);
493
494 View Code Duplication
    if ( (ACCOUNT_COMPANY == 'true') && tep_not_null($replace['$company']) ) {
495
      $address = $replace['$company'] . $replace['$cr'] . $address;
496
    }
497
498
    return $address;
499
  }
500
501
////
502
// Return a formatted address
503
// TABLES: customers, address_book
504
  function tep_address_label($customers_id, $address_id = 1, $html = false, $boln = '', $eoln = "\n") {
505
    $OSCOM_Db = Registry::get('Db');
506
507
    if (is_array($address_id) && !empty($address_id)) {
508
      return tep_address_format($address_id['address_format_id'], $address_id, $html, $boln, $eoln);
509
    }
510
511
    $Qaddress = $OSCOM_Db->prepare('select entry_firstname as firstname, entry_lastname as lastname, entry_company as company, entry_street_address as street_address, entry_suburb as suburb, entry_city as city, entry_postcode as postcode, entry_state as state, entry_zone_id as zone_id, entry_country_id as country_id from :table_address_book where address_book_id = :address_book_id and customers_id = :customers_id');
512
    $Qaddress->bindInt(':address_book_id', $address_id);
513
    $Qaddress->bindInt(':customers_id', $customers_id);
514
    $Qaddress->execute();
515
516
    $format_id = tep_get_address_format_id($Qaddress->valueInt('country_id'));
517
518
    return tep_address_format($format_id, $Qaddress->toArray(), $html, $boln, $eoln);
519
  }
520
521
  function tep_row_number_format($number) {
522
    if ( ($number < 10) && (substr($number, 0, 1) != '0') ) $number = '0' . $number;
523
524
    return $number;
525
  }
526
527
  function tep_get_categories($categories_array = '', $parent_id = '0', $indent = '') {
528
    $OSCOM_Db = Registry::get('Db');
529
    $OSCOM_Language = Registry::get('Language');
530
531
    if (!is_array($categories_array)) $categories_array = array();
532
533
    $Qcategories = $OSCOM_Db->prepare('select c.categories_id, cd.categories_name from :table_categories c, :table_categories_description cd where c.parent_id = :parent_id and c.categories_id = cd.categories_id and cd.language_id = :language_id order by c.sort_order, cd.categories_name');
534
    $Qcategories->bindInt(':parent_id', $parent_id);
535
    $Qcategories->bindInt(':language_id', $OSCOM_Language->getId());
536
    $Qcategories->execute();
537
538 View Code Duplication
    while ($Qcategories->fetch()) {
539
      $categories_array[] = array('id' => $Qcategories->valueInt('categories_id'),
540
                                  'text' => $indent . $Qcategories->value('categories_name'));
541
542
      if ($Qcategories->valueInt('categories_id') != $parent_id) {
543
        $categories_array = tep_get_categories($categories_array, $Qcategories->valueInt('categories_id'), $indent . '&nbsp;&nbsp;');
544
      }
545
    }
546
547
    return $categories_array;
548
  }
549
550
  function tep_get_manufacturers($manufacturers_array = '') {
551
    $OSCOM_Db = Registry::get('Db');
552
553
    if (!is_array($manufacturers_array)) $manufacturers_array = array();
554
555
    $Qmanufacturers = $OSCOM_Db->query('select manufacturers_id, manufacturers_name from :table_manufacturers order by manufacturers_name');
556
557 View Code Duplication
    while ($Qmanufacturers->fetch()) {
558
      $manufacturers_array[] = array('id' => $Qmanufacturers->valueInt('manufacturers_id'), 'text' => $Qmanufacturers->value('manufacturers_name'));
559
    }
560
561
    return $manufacturers_array;
562
  }
563
564
////
565
// Return all subcategory IDs
566
// TABLES: categories
567 View Code Duplication
  function tep_get_subcategories(&$subcategories_array, $parent_id = 0) {
568
    $OSCOM_Db = Registry::get('Db');
569
570
    $Qsub = $OSCOM_Db->prepare('select categories_id from :table_categories where parent_id = :parent_id');
571
    $Qsub->bindInt(':parent_id', $parent_id);
572
    $Qsub->execute();
573
574
    while ($Qsub->fetch()) {
575
      $subcategories_array[sizeof($subcategories_array)] = $Qsub->valueInt('categories_id');
576
577
      if ($Qsub->valueInt('categories_id') != $parent_id) {
578
        tep_get_subcategories($subcategories_array, $Qsub->valueInt('categories_id'));
579
      }
580
    }
581
  }
582
583
////
584
// Parse search string into indivual objects
585
  function tep_parse_search_string($search_str = '', &$objects) {
586
    $search_str = trim(strtolower($search_str));
587
588
// Break up $search_str on whitespace; quoted string will be reconstructed later
589
    $pieces = preg_split('/[[:space:]]+/', $search_str);
590
    $objects = array();
591
    $tmpstring = '';
592
    $flag = '';
593
594
    for ($k=0; $k<count($pieces); $k++) {
595 View Code Duplication
      while (substr($pieces[$k], 0, 1) == '(') {
596
        $objects[] = '(';
597
        if (strlen($pieces[$k]) > 1) {
598
          $pieces[$k] = substr($pieces[$k], 1);
599
        } else {
600
          $pieces[$k] = '';
601
        }
602
      }
603
604
      $post_objects = array();
605
606 View Code Duplication
      while (substr($pieces[$k], -1) == ')')  {
607
        $post_objects[] = ')';
608
        if (strlen($pieces[$k]) > 1) {
609
          $pieces[$k] = substr($pieces[$k], 0, -1);
610
        } else {
611
          $pieces[$k] = '';
612
        }
613
      }
614
615
// Check individual words
616
617
      if ( (substr($pieces[$k], -1) != '"') && (substr($pieces[$k], 0, 1) != '"') ) {
618
        $objects[] = trim($pieces[$k]);
619
620
        for ($j=0; $j<count($post_objects); $j++) {
621
          $objects[] = $post_objects[$j];
622
        }
623
      } else {
624
/* This means that the $piece is either the beginning or the end of a string.
625
   So, we'll slurp up the $pieces and stick them together until we get to the
626
   end of the string or run out of pieces.
627
*/
628
629
// Add this word to the $tmpstring, starting the $tmpstring
630
        $tmpstring = trim(preg_replace('/"/', ' ', $pieces[$k]));
631
632
// Check for one possible exception to the rule. That there is a single quoted word.
633 View Code Duplication
        if (substr($pieces[$k], -1 ) == '"') {
634
// Turn the flag off for future iterations
635
          $flag = 'off';
636
637
          $objects[] = trim(preg_replace('/"/', ' ', $pieces[$k]));
638
639
          for ($j=0; $j<count($post_objects); $j++) {
640
            $objects[] = $post_objects[$j];
641
          }
642
643
          unset($tmpstring);
644
645
// Stop looking for the end of the string and move onto the next word.
646
          continue;
647
        }
648
649
// Otherwise, turn on the flag to indicate no quotes have been found attached to this word in the string.
650
        $flag = 'on';
651
652
// Move on to the next word
653
        $k++;
654
655
// Keep reading until the end of the string as long as the $flag is on
656
657
        while ( ($flag == 'on') && ($k < count($pieces)) ) {
658 View Code Duplication
          while (substr($pieces[$k], -1) == ')') {
659
            $post_objects[] = ')';
660
            if (strlen($pieces[$k]) > 1) {
661
              $pieces[$k] = substr($pieces[$k], 0, -1);
662
            } else {
663
              $pieces[$k] = '';
664
            }
665
          }
666
667
// If the word doesn't end in double quotes, append it to the $tmpstring.
668
          if (substr($pieces[$k], -1) != '"') {
669
// Tack this word onto the current string entity
670
            $tmpstring .= ' ' . $pieces[$k];
671
672
// Move on to the next word
673
            $k++;
674
            continue;
675 View Code Duplication
          } else {
676
/* If the $piece ends in double quotes, strip the double quotes, tack the
677
   $piece onto the tail of the string, push the $tmpstring onto the $haves,
678
   kill the $tmpstring, turn the $flag "off", and return.
679
*/
680
            $tmpstring .= ' ' . trim(preg_replace('/"/', ' ', $pieces[$k]));
681
682
// Push the $tmpstring onto the array of stuff to search for
683
            $objects[] = trim($tmpstring);
684
685
            for ($j=0; $j<count($post_objects); $j++) {
686
              $objects[] = $post_objects[$j];
687
            }
688
689
            unset($tmpstring);
690
691
// Turn off the flag to exit the loop
692
            $flag = 'off';
693
          }
694
        }
695
      }
696
    }
697
698
// add default logical operators if needed
699
    $temp = array();
700
    for($i=0; $i<(count($objects)-1); $i++) {
701
      $temp[] = $objects[$i];
702
      if ( ($objects[$i] != 'and') &&
703
           ($objects[$i] != 'or') &&
704
           ($objects[$i] != '(') &&
705
           ($objects[$i+1] != 'and') &&
706
           ($objects[$i+1] != 'or') &&
707
           ($objects[$i+1] != ')') ) {
708
        $temp[] = ADVANCED_SEARCH_DEFAULT_OPERATOR;
709
      }
710
    }
711
    $temp[] = $objects[$i];
712
    $objects = $temp;
713
714
    $keyword_count = 0;
715
    $operator_count = 0;
716
    $balance = 0;
717
    for($i=0; $i<count($objects); $i++) {
718
      if ($objects[$i] == '(') $balance --;
719
      if ($objects[$i] == ')') $balance ++;
720
      if ( ($objects[$i] == 'and') || ($objects[$i] == 'or') ) {
721
        $operator_count ++;
722
      } elseif ( ($objects[$i]) && ($objects[$i] != '(') && ($objects[$i] != ')') ) {
723
        $keyword_count ++;
724
      }
725
    }
726
727
    if ( ($operator_count < $keyword_count) && ($balance == 0) ) {
728
      return true;
729
    } else {
730
      return false;
731
    }
732
  }
733
734
////
735
// Check date
736
  function tep_checkdate($date_to_check, $format_string, &$date_array) {
737
    $separator_idx = -1;
738
739
    $separators = array('-', ' ', '/', '.');
740
    $month_abbr = array('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec');
741
    $no_of_days = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
742
743
    $format_string = strtolower($format_string);
744
745
    if (strlen($date_to_check) != strlen($format_string)) {
746
      return false;
747
    }
748
749
    $size = sizeof($separators);
750 View Code Duplication
    for ($i=0; $i<$size; $i++) {
751
      $pos_separator = strpos($date_to_check, $separators[$i]);
752
      if ($pos_separator != false) {
753
        $date_separator_idx = $i;
754
        break;
755
      }
756
    }
757
758 View Code Duplication
    for ($i=0; $i<$size; $i++) {
759
      $pos_separator = strpos($format_string, $separators[$i]);
760
      if ($pos_separator != false) {
761
        $format_separator_idx = $i;
762
        break;
763
      }
764
    }
765
766
    if ($date_separator_idx != $format_separator_idx) {
767
      return false;
768
    }
769
770
    if ($date_separator_idx != -1) {
771
      $format_string_array = explode( $separators[$date_separator_idx], $format_string );
772
      if (sizeof($format_string_array) != 3) {
773
        return false;
774
      }
775
776
      $date_to_check_array = explode( $separators[$date_separator_idx], $date_to_check );
777
      if (sizeof($date_to_check_array) != 3) {
778
        return false;
779
      }
780
781
      $size = sizeof($format_string_array);
782
      for ($i=0; $i<$size; $i++) {
783
        if ($format_string_array[$i] == 'mm' || $format_string_array[$i] == 'mmm') $month = $date_to_check_array[$i];
784
        if ($format_string_array[$i] == 'dd') $day = $date_to_check_array[$i];
785
        if ( ($format_string_array[$i] == 'yyyy') || ($format_string_array[$i] == 'aaaa') ) $year = $date_to_check_array[$i];
786
      }
787
    } else {
788
      if (strlen($format_string) == 8 || strlen($format_string) == 9) {
789
        $pos_month = strpos($format_string, 'mmm');
790
        if ($pos_month != false) {
791
          $month = substr( $date_to_check, $pos_month, 3 );
792
          $size = sizeof($month_abbr);
793
          for ($i=0; $i<$size; $i++) {
794
            if ($month == $month_abbr[$i]) {
795
              $month = $i;
796
              break;
797
            }
798
          }
799
        } else {
800
          $month = substr($date_to_check, strpos($format_string, 'mm'), 2);
801
        }
802
      } else {
803
        return false;
804
      }
805
806
      $day = substr($date_to_check, strpos($format_string, 'dd'), 2);
807
      $year = substr($date_to_check, strpos($format_string, 'yyyy'), 4);
808
    }
809
810
    if (strlen($year) != 4) {
811
      return false;
812
    }
813
814
    if (!settype($year, 'integer') || !settype($month, 'integer') || !settype($day, 'integer')) {
815
      return false;
816
    }
817
818
    if ($month > 12 || $month < 1) {
819
      return false;
820
    }
821
822
    if ($day < 1) {
823
      return false;
824
    }
825
826
    if (tep_is_leap_year($year)) {
827
      $no_of_days[1] = 29;
828
    }
829
830
    if ($day > $no_of_days[$month - 1]) {
831
      return false;
832
    }
833
834
    $date_array = array($year, $month, $day);
835
836
    return true;
837
  }
838
839
////
840
// Check if year is a leap year
841
  function tep_is_leap_year($year) {
842
    if ($year % 100 == 0) {
843
      if ($year % 400 == 0) return true;
844
    } else {
845
      if (($year % 4) == 0) return true;
846
    }
847
848
    return false;
849
  }
850
851
////
852
// Return table heading with sorting capabilities
853
  function tep_create_sort_heading($sortby, $colnum, $heading) {
854
    global $PHP_SELF;
855
856
    $sort_prefix = '';
857
    $sort_suffix = '';
858
859
    if ($sortby) {
860
      $sort_prefix = '<a href="' . OSCOM::link($PHP_SELF, tep_get_all_get_params(array('page', 'info', 'sort')) . 'page=1&sort=' . $colnum . ($sortby == $colnum . 'a' ? 'd' : 'a')) . '" title="' . HTML::output(OSCOM::getDef('text_sort_products') . ($sortby == $colnum . 'd' || substr($sortby, 0, 1) != $colnum ? OSCOM::getDef('text_ascendingly') : OSCOM::getDef('text_descendingly')) . OSCOM::getDef('text_by') . $heading) . '" class="productListing-heading">' ;
861
      $sort_suffix = (substr($sortby, 0, 1) == $colnum ? (substr($sortby, 1, 1) == 'a' ? '+' : '-') : '') . '</a>';
862
    }
863
864
    return $sort_prefix . $heading . $sort_suffix;
865
  }
866
867
////
868
// Recursively go through the categories and retreive all parent categories IDs
869
// TABLES: categories
870 View Code Duplication
  function tep_get_parent_categories(&$categories, $categories_id) {
871
    $OSCOM_Db = Registry::get('Db');
872
873
    $Qparent = $OSCOM_Db->prepare('select parent_id from :table_categories where categories_id = :categories_id');
874
    $Qparent->bindInt(':categories_id', $categories_id);
875
    $Qparent->execute();
876
877
    while ($Qparent->fetch()) {
878
      if ($Qparent->valueInt('parent_id') == 0) return true;
879
880
      $categories[sizeof($categories)] = $Qparent->valueInt('parent_id');
881
882
      if ($Qparent->valueInt('parent_id') != $categories_id) {
883
        tep_get_parent_categories($categories, $Qparent->valueInt('parent_id'));
884
      }
885
    }
886
  }
887
888
////
889
// Construct a category path to the product
890
// TABLES: products_to_categories
891
  function tep_get_product_path($products_id) {
892
    $OSCOM_Db = Registry::get('Db');
893
894
    $cPath = '';
895
896
    $Qcategory = $OSCOM_Db->prepare('select p2c.categories_id from :table_products p, :table_products_to_categories p2c where p.products_id = :products_id and p.products_status = 1 and p.products_id = p2c.products_id limit 1');
897
    $Qcategory->bindInt(':products_id', $products_id);
898
    $Qcategory->execute();
899
900
    if ($Qcategory->fetch() !== false) {
901
      $categories = array();
902
      tep_get_parent_categories($categories, $Qcategory->valueInt('categories_id'));
903
904
      $categories = array_reverse($categories);
905
906
      $cPath = implode('_', $categories);
907
908
      if (tep_not_null($cPath)) $cPath .= '_';
909
      $cPath .= $Qcategory->valueInt('categories_id');
910
    }
911
912
    return $cPath;
913
  }
914
915
////
916
// Return a product ID with attributes
917
  function tep_get_uprid($prid, $params) {
918
    if (is_numeric($prid)) {
919
      $uprid = (int)$prid;
920
921
      if (is_array($params) && (!empty($params))) {
922
        $attributes_check = true;
923
        $attributes_ids = '';
924
925
        foreach ($params as $option => $value) {
926
          if (is_numeric($option) && is_numeric($value)) {
927
            $attributes_ids .= '{' . (int)$option . '}' . (int)$value;
928
          } else {
929
            $attributes_check = false;
930
            break;
931
          }
932
        }
933
934
        if ($attributes_check == true) {
935
          $uprid .= $attributes_ids;
936
        }
937
      }
938
    } else {
939
      $uprid = tep_get_prid($prid);
940
941
      if (is_numeric($uprid)) {
942
        if (strpos($prid, '{') !== false) {
943
          $attributes_check = true;
944
          $attributes_ids = '';
945
946
// strpos()+1 to remove up to and including the first { which would create an empty array element in explode()
947
          $attributes = explode('{', substr($prid, strpos($prid, '{')+1));
948
949
          for ($i=0, $n=sizeof($attributes); $i<$n; $i++) {
950
            $pair = explode('}', $attributes[$i]);
951
952
            if (is_numeric($pair[0]) && is_numeric($pair[1])) {
953
              $attributes_ids .= '{' . (int)$pair[0] . '}' . (int)$pair[1];
954
            } else {
955
              $attributes_check = false;
956
              break;
957
            }
958
          }
959
960
          if ($attributes_check == true) {
961
            $uprid .= $attributes_ids;
962
          }
963
        }
964
      } else {
965
        return false;
966
      }
967
    }
968
969
    return $uprid;
970
  }
971
972
////
973
// Return a product ID from a product ID with attributes
974
  function tep_get_prid($uprid) {
975
    $pieces = explode('{', $uprid);
976
977
    if (is_numeric($pieces[0])) {
978
      return (int)$pieces[0];
979
    } else {
980
      return false;
981
    }
982
  }
983
984
////
985
// Check if product has attributes
986 View Code Duplication
  function tep_has_product_attributes($products_id) {
987
    $OSCOM_Db = Registry::get('Db');
988
989
    $Qattributes = $OSCOM_Db->prepare('select products_id from :table_products_attributes where products_id = :products_id limit 1');
990
    $Qattributes->bindInt(':products_id', $products_id);
991
    $Qattributes->execute();
992
993
    return $Qattributes->fetch() !== false;
994
  }
995
996
  function tep_count_modules($modules = '') {
997
    $count = 0;
998
999
    if (empty($modules)) return $count;
1000
1001
    $modules_array = explode(';', $modules);
1002
1003
    for ($i=0, $n=sizeof($modules_array); $i<$n; $i++) {
1004
      $class = substr($modules_array[$i], 0, strrpos($modules_array[$i], '.'));
1005
1006
      if (isset($GLOBALS[$class]) && is_object($GLOBALS[$class])) {
1007
        if ($GLOBALS[$class]->enabled) {
1008
          $count++;
1009
        }
1010
      }
1011
    }
1012
1013
    return $count;
1014
  }
1015
1016 View Code Duplication
  function tep_count_payment_modules() {
0 ignored issues
show
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1017
    $count = 0;
1018
1019
    $modules_array = explode(';', MODULE_PAYMENT_INSTALLED);
1020
1021
    for ($i=0, $n=sizeof($modules_array); $i<$n; $i++) {
1022
      $m = $modules_array[$i];
1023
1024
      $OSCOM_PM = null;
1025
1026
      if (strpos($m, '\\') !== false) {
1027
        list($vendor, $app, $module) = explode('\\', $m);
1028
1029
        $module = $vendor . '\\' . $app . '\\' . $module;
1030
1031
        $code = 'Payment_' . str_replace('\\', '_', $module);
1032
1033
        if (Registry::exists($code)) {
1034
          $OSCOM_PM = Registry::get($code);
1035
        }
1036
      } else {
1037
        $module = substr($m, 0, strrpos($m, '.'));
1038
1039
        if (is_object($GLOBALS[$module])) {
1040
          $OSCOM_PM = $GLOBALS[$module];
1041
        }
1042
      }
1043
1044
      if (isset($OSCOM_PM) && $OSCOM_PM->enabled) {
1045
        $count++;
1046
      }
1047
    }
1048
1049
    return $count;
1050
  }
1051
1052 View Code Duplication
  function tep_count_shipping_modules() {
0 ignored issues
show
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1053
    $count = 0;
1054
1055
    $modules_array = explode(';', MODULE_SHIPPING_INSTALLED);
1056
1057
    for ($i=0, $n=sizeof($modules_array); $i<$n; $i++) {
1058
      $m = $modules_array[$i];
1059
1060
      $OSCOM_SM = null;
1061
1062
      if (strpos($m, '\\') !== false) {
1063
        list($vendor, $app, $module) = explode('\\', $m);
1064
1065
        $module = $vendor . '\\' . $app . '\\' . $module;
1066
1067
        $code = 'Shipping_' . str_replace('\\', '_', $module);
1068
1069
        if (Registry::exists($code)) {
1070
          $OSCOM_SM = Registry::get($code);
1071
        }
1072
      } else {
1073
        $module = substr($m, 0, strrpos($m, '.'));
1074
1075
        if (is_object($GLOBALS[$module])) {
1076
          $OSCOM_SM = $GLOBALS[$module];
1077
        }
1078
      }
1079
1080
      if (isset($OSCOM_SM) && $OSCOM_SM->enabled) {
1081
        $count++;
1082
      }
1083
    }
1084
1085
    return $count;
1086
  }
1087
1088
  function tep_array_to_string($array, $exclude = '', $equals = '=', $separator = '&') {
1089
    if (!is_array($exclude)) $exclude = array();
1090
1091
    $get_string = '';
1092
    if (!empty($array)) {
1093
      foreach ($array as $key => $value) {
1094
        if ( (!in_array($key, $exclude)) && ($key != 'x') && ($key != 'y') ) {
1095
          $get_string .= $key . $equals . $value . $separator;
1096
        }
1097
      }
1098
      $remove_chars = strlen($separator);
1099
      $get_string = substr($get_string, 0, -$remove_chars);
1100
    }
1101
1102
    return $get_string;
1103
  }
1104
1105
  function tep_not_null($value) {
1106
    if (is_array($value)) {
1107
      if (!empty($value)) {
1108
        return true;
1109
      } else {
1110
        return false;
1111
      }
1112
    } elseif(is_object($value)) {
1113
      if (count(get_object_vars($value)) === 0) {
1114
        return false;
1115
      } else {
1116
        return true;
1117
      }
1118
    } else {
1119
      if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
1120
        return true;
1121
      } else {
1122
        return false;
1123
      }
1124
    }
1125
  }
1126
1127
////
1128
// Output the tax percentage with optional padded decimals
1129 View Code Duplication
  function tep_display_tax_value($value, $padding = TAX_DECIMAL_PLACES) {
1130
    if (strpos($value, '.')) {
1131
      $loop = true;
1132
      while ($loop) {
1133
        if (substr($value, -1) == '0') {
1134
          $value = substr($value, 0, -1);
1135
        } else {
1136
          $loop = false;
1137
          if (substr($value, -1) == '.') {
1138
            $value = substr($value, 0, -1);
1139
          }
1140
        }
1141
      }
1142
    }
1143
1144
    if ($padding > 0) {
1145
      if ($decimal_pos = strpos($value, '.')) {
1146
        $decimals = strlen(substr($value, ($decimal_pos+1)));
1147
        for ($i=$decimals; $i<$padding; $i++) {
1148
          $value .= '0';
1149
        }
1150
      } else {
1151
        $value .= '.';
1152
        for ($i=0; $i<$padding; $i++) {
1153
          $value .= '0';
1154
        }
1155
      }
1156
    }
1157
1158
    return $value;
1159
  }
1160
1161
////
1162
// Checks to see if the currency code exists as a currency
1163
// TABLES: currencies
1164 View Code Duplication
  function tep_currency_exists($code) {
1165
    $OSCOM_Db = Registry::get('Db');
1166
1167
    $Qcurrency = $OSCOM_Db->prepare('select code from :table_currencies where code = :code limit 1');
1168
    $Qcurrency->bindValue(':code', $code);
1169
    $Qcurrency->execute();
1170
1171
    if ($Qcurrency->fetch() !== false) {
1172
      return $Qcurrency->value('code');
1173
    }
1174
1175
    return false;
1176
  }
1177
1178
////
1179
// Parse and secure the cPath parameter values
1180 View Code Duplication
  function tep_parse_category_path($cPath) {
1181
// make sure the category IDs are integers
1182
    $cPath_array = array_map(function ($string) {
1183
      return (int)$string;
1184
    }, explode('_', $cPath));
1185
1186
// make sure no duplicate category IDs exist which could lock the server in a loop
1187
    $tmp_array = array();
1188
    $n = sizeof($cPath_array);
1189
    for ($i=0; $i<$n; $i++) {
1190
      if (!in_array($cPath_array[$i], $tmp_array)) {
1191
        $tmp_array[] = $cPath_array[$i];
1192
      }
1193
    }
1194
1195
    return $tmp_array;
1196
  }
1197
1198
  function tep_count_customer_orders($id = '', $check_session = true) {
1199
    $OSCOM_Db = Registry::get('Db');
1200
    $OSCOM_Language = Registry::get('Language');
1201
1202 View Code Duplication
    if (is_numeric($id) == false) {
1203
      if (isset($_SESSION['customer_id'])) {
1204
        $id = $_SESSION['customer_id'];
1205
      } else {
1206
        return 0;
1207
      }
1208
    }
1209
1210 View Code Duplication
    if ($check_session == true) {
1211
      if (!isset($_SESSION['customer_id']) || ($id != $_SESSION['customer_id'])) {
1212
        return 0;
1213
      }
1214
    }
1215
1216
    $Qorders = $OSCOM_Db->prepare('select count(*) as total from :table_orders o, :table_orders_status s where o.customers_id = :customers_id and o.orders_status = s.orders_status_id and s.language_id = :language_id and s.public_flag = 1');
1217
    $Qorders->bindInt(':customers_id', $id);
1218
    $Qorders->bindInt(':language_id', $OSCOM_Language->getId());
1219
    $Qorders->execute();
1220
1221
    if ($Qorders->fetch() !== false) {
1222
      return $Qorders->valueInt('total');
1223
    }
1224
1225
    return 0;
1226
  }
1227
1228
  function tep_count_customer_address_book_entries($id = '', $check_session = true) {
1229
    $OSCOM_Db = Registry::get('Db');
1230
1231 View Code Duplication
    if (is_numeric($id) == false) {
1232
      if (isset($_SESSION['customer_id'])) {
1233
        $id = $_SESSION['customer_id'];
1234
      } else {
1235
        return 0;
1236
      }
1237
    }
1238
1239 View Code Duplication
    if ($check_session == true) {
1240
      if (!isset($_SESSION['customer_id']) || ($id != $_SESSION['customer_id'])) {
1241
        return 0;
1242
      }
1243
    }
1244
1245
    $Qaddresses = $OSCOM_Db->prepare('select count(*) as total from :table_address_book where customers_id = :customers_id');
1246
    $Qaddresses->bindInt(':customers_id', $id);
1247
    $Qaddresses->execute();
1248
1249
    if ($Qaddresses->fetch() !== false) {
1250
      return $Qaddresses->valueInt('total');
1251
    }
1252
1253
    return 0;
1254
  }
1255
1256
////
1257
// Creates a pull-down list of countries
1258
  function tep_get_country_list($name, $selected = '', $parameters = '') {
1259
    $countries_array = array(array('id' => '', 'text' => OSCOM::getDef('pull_down_default')));
1260
    $countries = tep_get_countries();
1261
1262
    for ($i=0, $n=sizeof($countries); $i<$n; $i++) {
1263
      $countries_array[] = array('id' => $countries[$i]['countries_id'], 'text' => $countries[$i]['countries_name']);
1264
    }
1265
1266
    return HTML::selectField($name, $countries_array, $selected, $parameters);
1267
  }
1268
?>
1269