[ Index ]

PHP Cross Reference of osCMax 2.0.4

title

Body

[close]

/includes/functions/ -> general.php (source)

   1  <?php
   2  /*

   3  $Id: general.php 14 2006-07-28 17:42:07Z user $

   4  

   5    osCMax Power E-Commerce

   6    http://oscdox.com

   7  

   8    Copyright 2006 osCMax

   9  

  10    Released under the GNU General Public License

  11  */
  12  
  13  ////

  14  // Stop from parsing any further PHP code

  15    function tep_exit() {
  16     tep_session_close();
  17     exit();
  18    }
  19  
  20  ////

  21  // Redirect to another page or site

  22    function tep_redirect($url) {
  23  // BOF: MS2 update 501112 - Added

  24      if ( (strstr($url, "\n") != false) || (strstr($url, "\r") != false) ) {
  25        tep_redirect(tep_href_link(FILENAME_DEFAULT, '', 'NONSSL', false));
  26      }
  27  // EOF: MS2 update 501112 - Added

  28      if ( (ENABLE_SSL == true) && (getenv('HTTPS') == 'on') ) { // We are loading an SSL page
  29        if (substr($url, 0, strlen(HTTP_SERVER)) == HTTP_SERVER) { // NONSSL url
  30          $url = HTTPS_SERVER . substr($url, strlen(HTTP_SERVER)); // Change it to SSL

  31        }
  32      }
  33  
  34      header('Location: ' . $url);
  35  
  36      tep_exit();
  37    }
  38  
  39  ////

  40  // Parse the data used in the html tags to ensure the tags will not break

  41    function tep_parse_input_field_data($data, $parse) {
  42      return strtr(trim($data), $parse);
  43    }
  44  
  45    function tep_output_string($string, $translate = false, $protected = false) {
  46      if ($protected == true) {
  47        return htmlspecialchars($string);
  48      } else {
  49        if ($translate == false) {
  50          return tep_parse_input_field_data($string, array('"' => '&quot;'));
  51        } else {
  52          return tep_parse_input_field_data($string, $translate);
  53        }
  54      }
  55    }
  56  
  57    function tep_output_string_protected($string) {
  58      return tep_output_string($string, false, true);
  59    }
  60  
  61    function tep_sanitize_string($string) {
  62      $string = ereg_replace(' +', ' ', trim($string));
  63  
  64      return preg_replace("/[<>]/", '_', $string);
  65    }
  66  
  67  ////

  68  // Return a random row from a database query

  69    function tep_random_select($query) {
  70      $random_product = '';
  71      $random_query = tep_db_query($query);
  72      $num_rows = tep_db_num_rows($random_query);
  73      if ($num_rows > 0) {
  74        $random_row = tep_rand(0, ($num_rows - 1));
  75        tep_db_data_seek($random_query, $random_row);
  76        $random_product = tep_db_fetch_array($random_query);
  77      }
  78  
  79      return $random_product;
  80    }
  81  
  82  ////

  83  // Return a product's name

  84  // TABLES: products

  85    function tep_get_products_name($product_id, $language = '') {
  86      global $languages_id;
  87  
  88      if (empty($language)) $language = $languages_id;
  89  
  90      $product_query = tep_db_query("select products_name from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int)$product_id . "' and language_id = '" . (int)$language . "'");
  91      $product = tep_db_fetch_array($product_query);
  92  
  93      return $product['products_name'];
  94    }
  95  
  96  ////

  97  // Return a product's special price (returns nothing if there is no offer)

  98  // TABLES: products

  99    function tep_get_products_special_price($product_id) {
 100  // BOF: MOD - Separate Pricing Per Customer

 101  //  $product_query = tep_db_query("select specials_new_products_price from " . TABLE_SPECIALS . " where products_id = '" . (int)$product_id . "' and status");

 102      global $sppc_customer_group_id;
 103  
 104      if(!tep_session_is_registered('sppc_customer_group_id')) {
 105        $customer_group_id = '0';
 106      } else {
 107        $customer_group_id = $sppc_customer_group_id;
 108      }
 109      $product_query = tep_db_query("select specials_new_products_price from " . TABLE_SPECIALS . " where products_id = '" . (int)$product_id . "' and status and customers_group_id = '" . (int)$customer_group_id . "'");
 110  // EOF: MOD - Separate_Pricing Per Customer

 111  
 112      $product = tep_db_fetch_array($product_query);
 113  
 114      return $product['specials_new_products_price'];
 115    }
 116  
 117  ////

 118  // Return a product's stock

 119  // TABLES: products

 120  // BOF: MOD - QT Pro

 121  //function tep_get_products_stock($products_id) {

 122  //  $products_id = tep_get_prid($products_id);

 123  //  $stock_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");

 124  //  $stock_values = tep_db_fetch_array($stock_query);

 125  //  return $stock_values['products_quantity'];

 126    function tep_get_products_stock($products_id, $attributes=array()) {
 127      global $languages_id;
 128      $products_id = tep_get_prid($products_id);
 129      if (sizeof($attributes)>0) {
 130        $all_nonstocked = true;
 131        $attr_list='';
 132        $options_list=implode(",",array_keys($attributes));
 133        $track_stock_query=tep_db_query("select products_options_id, products_options_track_stock from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id in ($options_list) and language_id= '" . (int)$languages_id . "order by products_options_id'");
 134        while($track_stock_array=tep_db_fetch_array($track_stock_query)) {
 135          if ($track_stock_array['products_options_track_stock']) {
 136            $attr_list.=$track_stock_array['products_options_id'] . '-' . $attributes[$track_stock_array['products_options_id']] . ',';
 137            $all_nonstocked=false;
 138          }
 139        }
 140        $attr_list=substr($attr_list,0,strlen($attr_list)-1);
 141      }
 142  
 143      if ((sizeof($attributes)==0) | ($all_nonstocked)) {
 144        $stock_query = tep_db_query("select products_quantity as quantity from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
 145      } else {
 146        $stock_query=tep_db_query("select products_stock_quantity as quantity from " . TABLE_PRODUCTS_STOCK . " where products_id='". (int)$products_id . "' and products_stock_attributes='$attr_list'");
 147      }
 148      if (tep_db_num_rows($stock_query)>0) {
 149        $stock=tep_db_fetch_array($stock_query);
 150        $quantity=$stock['quantity'];
 151      } else {
 152        $quantity = 0;
 153      }
 154      return $quantity;
 155  // EOF: MOD - QT Pro

 156    }
 157  
 158  ////

 159  // Check if the required stock is available

 160  // If insufficent stock is available return an out of stock message

 161  // BOF: MOD - QT Pro

 162  //function tep_check_stock($products_id, $products_quantity) {

 163  //  $stock_left = tep_get_products_stock($products_id) - $products_quantity;

 164    function tep_check_stock($products_id, $products_quantity, $attributes=array()) {
 165      $stock_left = tep_get_products_stock($products_id, $attributes) - $products_quantity;
 166  // EOF: MOD - QT Pro

 167      $out_of_stock = '';
 168  
 169      if ($stock_left < 0) {
 170        $out_of_stock = '<span class="markProductOutOfStock">' . STOCK_MARK_PRODUCT_OUT_OF_STOCK . '</span>';
 171      }
 172  
 173      return $out_of_stock;
 174    }
 175  
 176  ////

 177  // Break a word in a string if it is longer than a specified length ($len)

 178    function tep_break_string($string, $len, $break_char = '-') {
 179      $l = 0;
 180      $output = '';
 181      for ($i=0, $n=strlen($string); $i<$n; $i++) {
 182        $char = substr($string, $i, 1);
 183        if ($char != ' ') {
 184          $l++;
 185        } else {
 186          $l = 0;
 187        }
 188        if ($l > $len) {
 189          $l = 1;
 190          $output .= $break_char;
 191        }
 192        $output .= $char;
 193      }
 194  
 195      return $output;
 196    }
 197  
 198  ////

 199  // Return all HTTP GET variables, except those passed as a parameter

 200    function tep_get_all_get_params($exclude_array = '') {
 201      global $HTTP_GET_VARS;
 202  
 203      if (!is_array($exclude_array)) $exclude_array = array();
 204  
 205      $get_url = '';
 206      if (is_array($HTTP_GET_VARS) && (sizeof($HTTP_GET_VARS) > 0)) {
 207        reset($HTTP_GET_VARS);
 208        while (list($key, $value) = each($HTTP_GET_VARS)) {
 209          if ( (strlen($value) > 0) && ($key != tep_session_name()) && ($key != 'error') && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') ) {
 210            $get_url .= $key . '=' . rawurlencode(stripslashes($value)) . '&';
 211          }
 212        }
 213      }
 214  
 215      return $get_url;
 216    }
 217  
 218  ////

 219  // Returns an array with countries

 220  // TABLES: countries

 221    function tep_get_countries($countries_id = '', $with_iso_codes = false) {
 222      $countries_array = array();
 223      if (tep_not_null($countries_id)) {
 224        if ($with_iso_codes == true) {
 225          $countries = tep_db_query("select countries_name, countries_iso_code_2, countries_iso_code_3 from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$countries_id . "' order by countries_name");
 226          $countries_values = tep_db_fetch_array($countries);
 227          $countries_array = array('countries_name' => $countries_values['countries_name'],
 228                                   'countries_iso_code_2' => $countries_values['countries_iso_code_2'],
 229                                   'countries_iso_code_3' => $countries_values['countries_iso_code_3']);
 230        } else {
 231          $countries = tep_db_query("select countries_name from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$countries_id . "'");
 232          $countries_values = tep_db_fetch_array($countries);
 233          $countries_array = array('countries_name' => $countries_values['countries_name']);
 234        }
 235      } else {
 236        $countries = tep_db_query("select countries_id, countries_name from " . TABLE_COUNTRIES . " order by countries_name");
 237        while ($countries_values = tep_db_fetch_array($countries)) {
 238          $countries_array[] = array('countries_id' => $countries_values['countries_id'],
 239                                     'countries_name' => $countries_values['countries_name']);
 240        }
 241      }
 242  
 243      return $countries_array;
 244    }
 245  
 246  ////

 247  // Alias function to tep_get_countries, which also returns the countries iso codes

 248    function tep_get_countries_with_iso_codes($countries_id) {
 249      return tep_get_countries($countries_id, true);
 250    }
 251  
 252  ////

 253  // Generate a path to categories

 254   // changed to do everything without queries and in one query if parent_id or grand_parent_id is not set

 255      function tep_get_path($current_category_id = '', $parent_id = '', $grand_parent_id = '') {
 256      global $cPath_array;
 257  
 258      if (tep_not_null($current_category_id)) {
 259        $cp_size = sizeof($cPath_array);
 260        if ($cp_size == 0) {
 261          $cPath_new = $current_category_id;
 262        } else {
 263          $cPath_new = '';
 264          if (!tep_not_null($parent_id) || !tep_not_null($grand_parent_id) ) {
 265          $parent_query = tep_db_query("select c.parent_id, pcategories.parent_id as grand_parent_id from categories c, categories AS pcategories where c.categories_id = '" . (int)$cPath_array[($cp_size-1)] . "' and pcategories.categories_id = '" . (int)$current_category_id . "'");
 266    
 267          $parent_categories = tep_db_fetch_array($parent_query);
 268          $grand_parent_id = $parent_categories['grand_parent_id'];
 269          $parent_id = $parent_categories['parent_id'];
 270          }
 271          if ($parent_id == $grand_parent_id) {  
 272            for ($i=0; $i<($cp_size-1); $i++) {
 273              $cPath_new .= '_' . $cPath_array[$i];
 274            }
 275          } else {
 276            for ($i=0; $i<$cp_size; $i++) {
 277              $cPath_new .= '_' . $cPath_array[$i];
 278            }
 279          }
 280          $cPath_new .= '_' . $current_category_id;
 281  
 282          if (substr($cPath_new, 0, 1) == '_') {
 283            $cPath_new = substr($cPath_new, 1);
 284          }
 285        }
 286      } else {
 287        $cPath_new = implode('_', $cPath_array);
 288      }
 289  
 290      return 'cPath=' . $cPath_new;
 291    }
 292  
 293  ////

 294  // Returns the clients browser

 295    function tep_browser_detect($component) {
 296      global $HTTP_USER_AGENT;
 297  
 298      return stristr($HTTP_USER_AGENT, $component);
 299    }
 300  
 301  ////

 302  // Alias function to tep_get_countries()

 303    function tep_get_country_name($country_id) {
 304      $country_array = tep_get_countries($country_id);
 305  
 306      return $country_array['countries_name'];
 307    }
 308  
 309  ////

 310  // Returns the zone (State/Province) name

 311  // TABLES: zones

 312    function tep_get_zone_name($country_id, $zone_id, $default_zone) {
 313      $zone_query = tep_db_query("select zone_name from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_id = '" . (int)$zone_id . "'");
 314      if (tep_db_num_rows($zone_query)) {
 315        $zone = tep_db_fetch_array($zone_query);
 316        return $zone['zone_name'];
 317      } else {
 318        return $default_zone;
 319      }
 320    }
 321  
 322  ////

 323  // Returns the zone (State/Province) code

 324  // TABLES: zones

 325    function tep_get_zone_code($country_id, $zone_id, $default_zone) {
 326      $zone_query = tep_db_query("select zone_code from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_id = '" . (int)$zone_id . "'");
 327      if (tep_db_num_rows($zone_query)) {
 328        $zone = tep_db_fetch_array($zone_query);
 329        return $zone['zone_code'];
 330      } else {
 331        return $default_zone;
 332      }
 333    }
 334  
 335  ////

 336  // Wrapper function for round()

 337    function tep_round($number, $precision) {
 338      if (strpos($number, '.') && (strlen(substr($number, strpos($number, '.')+1)) > $precision)) {
 339        $number = substr($number, 0, strpos($number, '.') + 1 + $precision + 1);
 340  
 341        if (substr($number, -1) >= 5) {
 342          if ($precision > 1) {
 343            $number = substr($number, 0, -1) + ('0.' . str_repeat(0, $precision-1) . '1');
 344          } elseif ($precision == 1) {
 345            $number = substr($number, 0, -1) + 0.1;
 346          } else {
 347            $number = substr($number, 0, -1) + 1;
 348          }
 349        } else {
 350          $number = substr($number, 0, -1);
 351        }
 352      }
 353  
 354      return $number;
 355    }
 356  
 357  ////

 358  // Returns the tax rate for a zone / class

 359  // TABLES: tax_rates, zones_to_geo_zones

 360    function tep_get_tax_rate($class_id, $country_id = -1, $zone_id = -1) {
 361  // BOF: MOD - Separate Pricing Per Customer, show_tax modification

 362      global $customer_zone_id, $customer_country_id, $osC_Tax, $sppc_customer_group_tax_exempt;
 363  
 364       if(!tep_session_is_registered('sppc_customer_group_tax_exempt')) {
 365       $customer_group_tax_exempt = '0';
 366       } else {
 367       $customer_group_tax_exempt = $sppc_customer_group_tax_exempt;
 368       }
 369  
 370       if ($customer_group_tax_exempt == '1') {
 371         return 0;
 372       }
 373   return $osC_Tax->getTaxRate($class_id, $country_id, $zone_id);
 374  }
 375  // EOF: MOD - Separate Pricing Per Customer, show_tax modification

 376  
 377  ////

 378  // Return the tax description for a zone / class

 379  // TABLES: tax_rates;

 380    function tep_get_tax_description($class_id, $country_id, $zone_id) {
 381  // BOF: MOD - Separate Pricing Per Customer, show_tax modification

 382       global $osC_Tax;
 383       return $osC_Tax->getTaxRateDescription($class_id, $country_id, $zone_id);
 384  // EOF: MOD - Separate Pricing Per Customer, show_tax modification

 385      }
 386  
 387  ////

 388  // Add tax to a products price

 389    function tep_add_tax($price, $tax) {
 390  // BOF: MOD - Separate Pricing Per Customer, show_tax modification

 391  // next line was original code

 392  //    if ( (DISPLAY_PRICE_WITH_TAX == 'true') && ($tax > 0) ) {

 393      global $sppc_customer_group_show_tax;
 394      global $sppc_customer_group_tax_exempt;
 395       if(!tep_session_is_registered('sppc_customer_group_show_tax')) {
 396       $customer_group_show_tax = '1';
 397       } else {
 398       $customer_group_show_tax = $sppc_customer_group_show_tax;
 399       }
 400  
 401   //    echo '<br>cg_tax_exempt: ';

 402   //    echo $sppc_customer_group_tax_exempt;

 403       if ( (DISPLAY_PRICE_WITH_TAX == 'true') && ($tax > 0) && ($customer_group_show_tax == '1')) {
 404  // EOF: MOD - Separate Pricing Per Customer, show_tax modification

 405        return $price + tep_calculate_tax($price, $tax);
 406      } else {
 407        return $price;
 408      }
 409    }
 410  
 411  // Calculates Tax rounding the result

 412    function tep_calculate_tax($price, $tax) {
 413      return $price * $tax / 100;
 414    }
 415  
 416  ////

 417  // Return the number of products in a category

 418  // TABLES: products, products_to_categories, categories

 419    function tep_count_products_in_category($category_id, $include_inactive = false) {
 420      $products_count = 0;
 421      if ($include_inactive == true) {
 422        $products_query = tep_db_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 = '" . (int)$category_id . "'");
 423      } else {
 424        $products_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where p.products_id = p2c.products_id and p.products_status = '1' and p2c.categories_id = '" . (int)$category_id . "'");
 425      }
 426      $products = tep_db_fetch_array($products_query);
 427      $products_count += $products['total'];
 428  
 429      $child_categories_query = tep_db_query("select categories_id from " . TABLE_CATEGORIES . " where parent_id = '" . (int)$category_id . "'");
 430      if (tep_db_num_rows($child_categories_query)) {
 431        while ($child_categories = tep_db_fetch_array($child_categories_query)) {
 432          $products_count += tep_count_products_in_category($child_categories['categories_id'], $include_inactive);
 433        }
 434      }
 435  
 436      return $products_count;
 437    }
 438  
 439  ////

 440  // Return true if the category has subcategories

 441  // TABLES: categories

 442    function tep_has_category_subcategories($category_id) {
 443      $child_category_query = tep_db_query("select count(*) as count from " . TABLE_CATEGORIES . " where parent_id = '" . (int)$category_id . "'");
 444      $child_category = tep_db_fetch_array($child_category_query);
 445  
 446      if ($child_category['count'] > 0) {
 447        return true;
 448      } else {
 449        return false;
 450      }
 451    }
 452  
 453  ////

 454  // Returns the address_format_id for the given country

 455  // TABLES: countries;

 456    function tep_get_address_format_id($country_id) {
 457      $address_format_query = tep_db_query("select address_format_id as format_id from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$country_id . "'");
 458      if (tep_db_num_rows($address_format_query)) {
 459        $address_format = tep_db_fetch_array($address_format_query);
 460        return $address_format['format_id'];
 461      } else {
 462        return '1';
 463      }
 464    }
 465  
 466  ////

 467  // Return a formatted address

 468  // TABLES: address_format

 469    function tep_address_format($address_format_id, $address, $html, $boln, $eoln) {
 470      $address_format_query = tep_db_query("select address_format as format from " . TABLE_ADDRESS_FORMAT . " where address_format_id = '" . (int)$address_format_id . "'");
 471      $address_format = tep_db_fetch_array($address_format_query);
 472  
 473      $company = tep_output_string_protected($address['company']);
 474      if (isset($address['firstname']) && tep_not_null($address['firstname'])) {
 475        $firstname = tep_output_string_protected($address['firstname']);
 476        $lastname = tep_output_string_protected($address['lastname']);
 477      } elseif (isset($address['name']) && tep_not_null($address['name'])) {
 478        $firstname = tep_output_string_protected($address['name']);
 479        $lastname = '';
 480      } else {
 481        $firstname = '';
 482        $lastname = '';
 483      }
 484      $street = tep_output_string_protected($address['street_address']);
 485      $suburb = tep_output_string_protected($address['suburb']);
 486      $city = tep_output_string_protected($address['city']);
 487      $state = tep_output_string_protected($address['state']);
 488      if (isset($address['country_id']) && tep_not_null($address['country_id'])) {
 489        $country = tep_get_country_name($address['country_id']);
 490  
 491        if (isset($address['zone_id']) && tep_not_null($address['zone_id'])) {
 492          $state = tep_get_zone_code($address['country_id'], $address['zone_id'], $state);
 493        }
 494      } elseif (isset($address['country']) && tep_not_null($address['country'])) {
 495        $country = tep_output_string_protected($address['country']['title']);
 496      } else {
 497        $country = '';
 498      }
 499      $postcode = tep_output_string_protected($address['postcode']);
 500      $zip = $postcode;
 501  
 502      if ($html) {
 503  // HTML Mode

 504        $HR = '<hr>';
 505        $hr = '<hr>';
 506        if ( ($boln == '') && ($eoln == "\n") ) { // Values not specified, use rational defaults
 507          $CR = '<br>';
 508          $cr = '<br>';
 509          $eoln = $cr;
 510        } else { // Use values supplied
 511          $CR = $eoln . $boln;
 512          $cr = $CR;
 513        }
 514      } else {
 515  // Text Mode

 516        $CR = $eoln;
 517        $cr = $CR;
 518        $HR = '----------------------------------------';
 519        $hr = '----------------------------------------';
 520      }
 521  
 522      $statecomma = '';
 523      $streets = $street;
 524      if ($suburb != '') $streets = $street . $cr . $suburb;
 525      if ($country == '') $country = tep_output_string_protected($address['country']);
 526      if ($state != '') $statecomma = $state . ', ';
 527  
 528      $fmt = $address_format['format'];
 529      eval("\$address = \"$fmt\";");
 530  
 531      if ( (ACCOUNT_COMPANY == 'true') && (tep_not_null($company)) ) {
 532        $address = $company . $cr . $address;
 533      }
 534  
 535      return $address;
 536    }
 537  
 538  ////

 539  // Return a formatted address

 540  // TABLES: customers, address_book

 541    function tep_address_label($customers_id, $address_id = 1, $html = false, $boln = '', $eoln = "\n") {
 542      if (is_array($address_id) && !empty($address_id)) {
 543        return tep_address_format($address_id['address_format_id'], $address_id, $html, $boln, $eoln);
 544      }
 545      $address_query = tep_db_query("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 customers_id = '" . (int)$customers_id . "' and address_book_id = '" . (int)$address_id . "'");
 546      $address = tep_db_fetch_array($address_query);
 547  
 548      $format_id = tep_get_address_format_id($address['country_id']);
 549  
 550      return tep_address_format($format_id, $address, $html, $boln, $eoln);
 551    }
 552  
 553    function tep_row_number_format($number) {
 554      if ( ($number < 10) && (substr($number, 0, 1) != '0') ) $number = '0' . $number;
 555  
 556      return $number;
 557    }
 558  
 559    function tep_get_categories($categories_array = '', $parent_id = '0', $indent = '') {
 560      global $languages_id;
 561  
 562      if (!is_array($categories_array)) $categories_array = array();
 563  
 564      $categories_query = tep_db_query("select c.categories_id, cd.categories_name from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where parent_id = '" . (int)$parent_id . "' and c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' order by sort_order, cd.categories_name");
 565      while ($categories = tep_db_fetch_array($categories_query)) {
 566        $categories_array[] = array('id' => $categories['categories_id'],
 567                                    'text' => $indent . $categories['categories_name']);
 568  
 569        if ($categories['categories_id'] != $parent_id) {
 570          $categories_array = tep_get_categories($categories_array, $categories['categories_id'], $indent . '&nbsp;&nbsp;');
 571        }
 572      }
 573  
 574      return $categories_array;
 575    }
 576  
 577    function tep_get_manufacturers($manufacturers_array = '') {
 578      if (!is_array($manufacturers_array)) $manufacturers_array = array();
 579  
 580      $manufacturers_query = tep_db_query("select manufacturers_id, manufacturers_name from " . TABLE_MANUFACTURERS . " order by manufacturers_name");
 581      while ($manufacturers = tep_db_fetch_array($manufacturers_query)) {
 582        $manufacturers_array[] = array('id' => $manufacturers['manufacturers_id'], 'text' => $manufacturers['manufacturers_name']);
 583      }
 584  
 585      return $manufacturers_array;
 586    }
 587  
 588  ////

 589  // Return all subcategory IDs

 590  // TABLES: categories

 591    function tep_get_subcategories(&$subcategories_array, $parent_id = 0) {
 592      $subcategories_query = tep_db_query("select categories_id from " . TABLE_CATEGORIES . " where parent_id = '" . (int)$parent_id . "'");
 593      while ($subcategories = tep_db_fetch_array($subcategories_query)) {
 594        $subcategories_array[sizeof($subcategories_array)] = $subcategories['categories_id'];
 595        if ($subcategories['categories_id'] != $parent_id) {
 596          tep_get_subcategories($subcategories_array, $subcategories['categories_id']);
 597        }
 598      }
 599    }
 600  
 601  // Output a raw date string in the selected locale date format

 602  // $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS

 603    function tep_date_long($raw_date) {
 604      if ( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '') ) return false;
 605  
 606      $year = (int)substr($raw_date, 0, 4);
 607      $month = (int)substr($raw_date, 5, 2);
 608      $day = (int)substr($raw_date, 8, 2);
 609      $hour = (int)substr($raw_date, 11, 2);
 610      $minute = (int)substr($raw_date, 14, 2);
 611      $second = (int)substr($raw_date, 17, 2);
 612  
 613      return strftime(DATE_FORMAT_LONG, mktime($hour,$minute,$second,$month,$day,$year));
 614    }
 615  
 616  ////

 617  // Output a raw date string in the selected locale date format

 618  // $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS

 619  // NOTE: Includes a workaround for dates before 01/01/1970 that fail on windows servers

 620    function tep_date_short($raw_date) {
 621      if ( ($raw_date == '0000-00-00 00:00:00') || empty($raw_date) ) return false;
 622  
 623      $year = substr($raw_date, 0, 4);
 624      $month = (int)substr($raw_date, 5, 2);
 625      $day = (int)substr($raw_date, 8, 2);
 626      $hour = (int)substr($raw_date, 11, 2);
 627      $minute = (int)substr($raw_date, 14, 2);
 628      $second = (int)substr($raw_date, 17, 2);
 629  
 630      if (@date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year) {
 631        return date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
 632      } else {
 633        return ereg_replace('2037' . '$', $year, date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, 2037)));
 634      }
 635    }
 636  
 637  ////

 638  // Parse search string into indivual objects

 639    function tep_parse_search_string($search_str = '', &$objects) {
 640      $search_str = trim(strtolower($search_str));
 641  
 642  // Break up $search_str on whitespace; quoted string will be reconstructed later

 643      $pieces = split('[[:space:]]+', $search_str);
 644      $objects = array();
 645      $tmpstring = '';
 646      $flag = '';
 647  
 648      for ($k=0; $k<count($pieces); $k++) {
 649        while (substr($pieces[$k], 0, 1) == '(') {
 650          $objects[] = '(';
 651          if (strlen($pieces[$k]) > 1) {
 652            $pieces[$k] = substr($pieces[$k], 1);
 653          } else {
 654            $pieces[$k] = '';
 655          }
 656        }
 657  
 658        $post_objects = array();
 659  
 660        while (substr($pieces[$k], -1) == ')')  {
 661          $post_objects[] = ')';
 662          if (strlen($pieces[$k]) > 1) {
 663            $pieces[$k] = substr($pieces[$k], 0, -1);
 664          } else {
 665            $pieces[$k] = '';
 666          }
 667        }
 668  
 669  // Check individual words

 670  
 671        if ( (substr($pieces[$k], -1) != '"') && (substr($pieces[$k], 0, 1) != '"') ) {
 672          $objects[] = trim($pieces[$k]);
 673  
 674          for ($j=0; $j<count($post_objects); $j++) {
 675            $objects[] = $post_objects[$j];
 676          }
 677        } else {
 678  /* This means that the $piece is either the beginning or the end of a string.

 679     So, we'll slurp up the $pieces and stick them together until we get to the

 680     end of the string or run out of pieces.

 681  */
 682  
 683  // Add this word to the $tmpstring, starting the $tmpstring

 684          $tmpstring = trim(ereg_replace('"', ' ', $pieces[$k]));
 685  
 686  // Check for one possible exception to the rule. That there is a single quoted word.

 687          if (substr($pieces[$k], -1 ) == '"') {
 688  // Turn the flag off for future iterations

 689            $flag = 'off';
 690  
 691            $objects[] = trim($pieces[$k]);
 692  
 693            for ($j=0; $j<count($post_objects); $j++) {
 694              $objects[] = $post_objects[$j];
 695            }
 696  
 697            unset($tmpstring);
 698  
 699  // Stop looking for the end of the string and move onto the next word.

 700            continue;
 701          }
 702  
 703  // Otherwise, turn on the flag to indicate no quotes have been found attached to this word in the string.

 704          $flag = 'on';
 705  
 706  // Move on to the next word

 707          $k++;
 708  
 709  // Keep reading until the end of the string as long as the $flag is on

 710  
 711          while ( ($flag == 'on') && ($k < count($pieces)) ) {
 712            while (substr($pieces[$k], -1) == ')') {
 713              $post_objects[] = ')';
 714              if (strlen($pieces[$k]) > 1) {
 715                $pieces[$k] = substr($pieces[$k], 0, -1);
 716              } else {
 717                $pieces[$k] = '';
 718              }
 719            }
 720  
 721  // If the word doesn't end in double quotes, append it to the $tmpstring.

 722            if (substr($pieces[$k], -1) != '"') {
 723  // Tack this word onto the current string entity

 724              $tmpstring .= ' ' . $pieces[$k];
 725  
 726  // Move on to the next word

 727              $k++;
 728              continue;
 729            } else {
 730  /* If the $piece ends in double quotes, strip the double quotes, tack the

 731     $piece onto the tail of the string, push the $tmpstring onto the $haves,

 732     kill the $tmpstring, turn the $flag "off", and return.

 733  */
 734              $tmpstring .= ' ' . trim(ereg_replace('"', ' ', $pieces[$k]));
 735  
 736  // Push the $tmpstring onto the array of stuff to search for

 737              $objects[] = trim($tmpstring);
 738  
 739              for ($j=0; $j<count($post_objects); $j++) {
 740                $objects[] = $post_objects[$j];
 741              }
 742  
 743              unset($tmpstring);
 744  
 745  // Turn off the flag to exit the loop

 746              $flag = 'off';
 747            }
 748          }
 749        }
 750      }
 751  
 752  // add default logical operators if needed

 753      $temp = array();
 754      for($i=0; $i<(count($objects)-1); $i++) {
 755        $temp[] = $objects[$i];
 756        if ( ($objects[$i] != 'and') &&
 757             ($objects[$i] != 'or') &&
 758             ($objects[$i] != '(') &&
 759             ($objects[$i+1] != 'and') &&
 760             ($objects[$i+1] != 'or') &&
 761             ($objects[$i+1] != ')') ) {
 762          $temp[] = ADVANCED_SEARCH_DEFAULT_OPERATOR;
 763        }
 764      }
 765      $temp[] = $objects[$i];
 766      $objects = $temp;
 767  
 768      $keyword_count = 0;
 769      $operator_count = 0;
 770      $balance = 0;
 771      for($i=0; $i<count($objects); $i++) {
 772        if ($objects[$i] == '(') $balance --;
 773        if ($objects[$i] == ')') $balance ++;
 774        if ( ($objects[$i] == 'and') || ($objects[$i] == 'or') ) {
 775          $operator_count ++;
 776        } elseif ( ($objects[$i]) && ($objects[$i] != '(') && ($objects[$i] != ')') ) {
 777          $keyword_count ++;
 778        }
 779      }
 780  
 781      if ( ($operator_count < $keyword_count) && ($balance == 0) ) {
 782        return true;
 783      } else {
 784        return false;
 785      }
 786    }
 787  
 788  ////

 789  // Check date

 790    function tep_checkdate($date_to_check, $format_string, &$date_array) {
 791      $separator_idx = -1;
 792  
 793      $separators = array('-', ' ', '/', '.');
 794      $month_abbr = array('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec');
 795      $no_of_days = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 796  
 797      $format_string = strtolower($format_string);
 798  
 799      if (strlen($date_to_check) != strlen($format_string)) {
 800        return false;
 801      }
 802  
 803      $size = sizeof($separators);
 804      for ($i=0; $i<$size; $i++) {
 805        $pos_separator = strpos($date_to_check, $separators[$i]);
 806        if ($pos_separator != false) {
 807          $date_separator_idx = $i;
 808          break;
 809        }
 810      }
 811  
 812      for ($i=0; $i<$size; $i++) {
 813        $pos_separator = strpos($format_string, $separators[$i]);
 814        if ($pos_separator != false) {
 815          $format_separator_idx = $i;
 816          break;
 817        }
 818      }
 819  
 820      if ($date_separator_idx != $format_separator_idx) {
 821        return false;
 822      }
 823  
 824      if ($date_separator_idx != -1) {
 825        $format_string_array = explode( $separators[$date_separator_idx], $format_string );
 826        if (sizeof($format_string_array) != 3) {
 827          return false;
 828        }
 829  
 830        $date_to_check_array = explode( $separators[$date_separator_idx], $date_to_check );
 831        if (sizeof($date_to_check_array) != 3) {
 832          return false;
 833        }
 834  
 835        $size = sizeof($format_string_array);
 836        for ($i=0; $i<$size; $i++) {
 837          if ($format_string_array[$i] == 'mm' || $format_string_array[$i] == 'mmm') $month = $date_to_check_array[$i];
 838          if ($format_string_array[$i] == 'dd') $day = $date_to_check_array[$i];
 839          if ( ($format_string_array[$i] == 'yyyy') || ($format_string_array[$i] == 'aaaa') ) $year = $date_to_check_array[$i];
 840        }
 841      } else {
 842        if (strlen($format_string) == 8 || strlen($format_string) == 9) {
 843          $pos_month = strpos($format_string, 'mmm');
 844          if ($pos_month != false) {
 845            $month = substr( $date_to_check, $pos_month, 3 );
 846            $size = sizeof($month_abbr);
 847            for ($i=0; $i<$size; $i++) {
 848              if ($month == $month_abbr[$i]) {
 849                $month = $i;
 850                break;
 851              }
 852            }
 853          } else {
 854            $month = substr($date_to_check, strpos($format_string, 'mm'), 2);
 855          }
 856        } else {
 857          return false;
 858        }
 859  
 860        $day = substr($date_to_check, strpos($format_string, 'dd'), 2);
 861        $year = substr($date_to_check, strpos($format_string, 'yyyy'), 4);
 862      }
 863  
 864      if (strlen($year) != 4) {
 865        return false;
 866      }
 867  
 868      if (!settype($year, 'integer') || !settype($month, 'integer') || !settype($day, 'integer')) {
 869        return false;
 870      }
 871  
 872      if ($month > 12 || $month < 1) {
 873        return false;
 874      }
 875  
 876      if ($day < 1) {
 877        return false;
 878      }
 879  
 880      if (tep_is_leap_year($year)) {
 881        $no_of_days[1] = 29;
 882      }
 883  
 884      if ($day > $no_of_days[$month - 1]) {
 885        return false;
 886      }
 887  
 888      $date_array = array($year, $month, $day);
 889  
 890      return true;
 891    }
 892  
 893  ////

 894  // Check if year is a leap year

 895    function tep_is_leap_year($year) {
 896      if ($year % 100 == 0) {
 897        if ($year % 400 == 0) return true;
 898      } else {
 899        if (($year % 4) == 0) return true;
 900      }
 901  
 902      return false;
 903    }
 904  
 905  ////

 906  // Return table heading with sorting capabilities

 907    function tep_create_sort_heading($sortby, $colnum, $heading) {
 908      global $PHP_SELF;
 909  
 910      $sort_prefix = '';
 911      $sort_suffix = '';
 912  
 913      if ($sortby) {
 914        $sort_prefix = '<a href="' . tep_href_link(basename($PHP_SELF), tep_get_all_get_params(array('page', 'info', 'sort')) . 'page=1&sort=' . $colnum . ($sortby == $colnum . 'a' ? 'd' : 'a')) . '" title="' . tep_output_string(TEXT_SORT_PRODUCTS . ($sortby == $colnum . 'd' || substr($sortby, 0, 1) != $colnum ? TEXT_ASCENDINGLY : TEXT_DESCENDINGLY) . TEXT_BY . $heading) . '" class="productListing-heading">' ;
 915        $sort_suffix = (substr($sortby, 0, 1) == $colnum ? (substr($sortby, 1, 1) == 'a' ? '+' : '-') : '') . '</a>';
 916      }
 917  
 918      return $sort_prefix . $heading . $sort_suffix;
 919    }
 920  
 921  ////

 922  // Recursively go through the categories and retreive all parent categories IDs

 923  // TABLES: categories

 924    function tep_get_parent_categories(&$categories, $categories_id) {
 925      $parent_categories_query = tep_db_query("select parent_id from " . TABLE_CATEGORIES . " where categories_id = '" . (int)$categories_id . "'");
 926      while ($parent_categories = tep_db_fetch_array($parent_categories_query)) {
 927        if ($parent_categories['parent_id'] == 0) return true;
 928        $categories[sizeof($categories)] = $parent_categories['parent_id'];
 929        if ($parent_categories['parent_id'] != $categories_id) {
 930          tep_get_parent_categories($categories, $parent_categories['parent_id']);
 931        }
 932      }
 933    }
 934  
 935  ////

 936  // Construct a category path to the product

 937  // TABLES: products_to_categories

 938    function tep_get_product_path($products_id) {
 939      $cPath = '';
 940  
 941      $category_query = tep_db_query("select p2c.categories_id from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where p.products_id = '" . (int)$products_id . "' and p.products_status = '1' and p.products_id = p2c.products_id limit 1");
 942      if (tep_db_num_rows($category_query)) {
 943        $category = tep_db_fetch_array($category_query);
 944  
 945        $categories = array();
 946        tep_get_parent_categories($categories, $category['categories_id']);
 947  
 948        $categories = array_reverse($categories);
 949  
 950        $cPath = implode('_', $categories);
 951  
 952        if (tep_not_null($cPath)) $cPath .= '_';
 953        $cPath .= $category['categories_id'];
 954      }
 955  
 956      return $cPath;
 957    }
 958  
 959  ////

 960  // Return a product ID with attributes

 961    function tep_get_uprid($prid, $params) {
 962  // LINE ADDED: MS2 update 501112

 963      if (is_numeric($prid)) {
 964        $uprid = $prid;
 965  // BOF: MS2 update 501112 - Added

 966  //  if ( (is_array($params)) && (!strstr($prid, '{')) ) {

 967        if (is_array($params) && (sizeof($params) > 0)) {
 968          $attributes_check = true;
 969          $attributes_ids = '';
 970          reset($params);
 971  // EOF: MS2 update 501112 - Added

 972          while (list($option, $value) = each($params)) {
 973  // BOF: MS2 update 501112 - Added

 974  //      $uprid = $uprid . '{' . $option . '}' . $value;

 975            if (is_numeric($option) && is_numeric($value)) {
 976              $attributes_ids .= '{' . (int)$option . '}' . (int)$value;
 977            } else {
 978              $attributes_check = false;
 979              break;
 980            }
 981          }
 982  
 983          if ($attributes_check == true) {
 984            $uprid .= $attributes_ids;
 985          }
 986        }
 987      } else {
 988        $uprid = tep_get_prid($prid);
 989  
 990        if (is_numeric($uprid)) {
 991          if (strpos($prid, '{') !== false) {
 992            $attributes_check = true;
 993            $attributes_ids = '';
 994  
 995  // strpos()+1 to remove up to and including the first { which would create an empty array element in explode()

 996            $attributes = explode('{', substr($prid, strpos($prid, '{')+1));
 997  
 998            for ($i=0, $n=sizeof($attributes); $i<$n; $i++) {
 999              $pair = explode('}', $attributes[$i]);
1000  
1001              if (is_numeric($pair[0]) && is_numeric($pair[1])) {
1002                $attributes_ids .= '{' . (int)$pair[0] . '}' . (int)$pair[1];
1003              } else {
1004                $attributes_check = false;
1005                break;
1006              }
1007            }
1008  
1009            if ($attributes_check == true) {
1010              $uprid .= $attributes_ids;
1011            }
1012          }
1013        } else {
1014          return false;
1015  // EOF: MS2 update 501112 - Added

1016        }
1017      }
1018  
1019      return $uprid;
1020    }
1021  
1022  ////

1023  // Return a product ID from a product ID with attributes

1024    function tep_get_prid($uprid) {
1025      $pieces = explode('{', $uprid);
1026  
1027  // LINE ADDED: MS2 update 501112

1028      if (is_numeric($pieces[0])) {
1029        return $pieces[0];
1030  // BOF: MS2 update 501112 - Added

1031      } else {
1032        return false;
1033      }
1034  // EOF: MS2 update 501112 - Added

1035    }
1036  
1037  ////

1038  // Return a customer greeting

1039    function tep_customer_greeting() {
1040      global $customer_id, $customer_first_name;
1041  
1042      if (tep_session_is_registered('customer_first_name') && tep_session_is_registered('customer_id')) {
1043        $greeting_string = sprintf(TEXT_GREETING_PERSONAL, tep_output_string_protected($customer_first_name), tep_href_link(FILENAME_PRODUCTS_NEW));
1044      } else {
1045        $greeting_string = sprintf(TEXT_GREETING_GUEST, tep_href_link(FILENAME_LOGIN, '', 'SSL'), tep_href_link(FILENAME_CREATE_ACCOUNT, '', 'SSL'));
1046      }
1047  
1048      return $greeting_string;
1049    }
1050  
1051  ////

1052  //! Send email (text/html) using MIME

1053  // This is the central mail function. The SMTP Server should be configured

1054  // correct in php.ini

1055  // Parameters:

1056  // $to_name           The name of the recipient, e.g. "Jan Wildeboer"

1057  // $to_email_address  The eMail address of the recipient,

1058  //                    e.g. [email protected]

1059  // $email_subject     The subject of the eMail

1060  // $email_text        The text of the eMail, may contain HTML entities

1061  // $from_email_name   The name of the sender, e.g. Shop Administration

1062  // $from_email_adress The eMail address of the sender,

1063  //                    e.g. [email protected]

1064  
1065    function tep_mail($to_name, $to_email_address, $email_subject, $email_text, $from_email_name, $from_email_address) {
1066      if (SEND_EMAILS != 'true') return false;
1067  
1068      //Dont send any injection type mails.

1069      if (eregi('Content-Type:', $to_name)) return false;
1070      if (eregi('Content-Type:', $email_subject)) return false;
1071      if (eregi('Content-Type:', $from_email_name)) return false;
1072      if (eregi('Content-Type:', $email_text)) return false;
1073  
1074      //Remove any newline and anything after it on the header fields of the mail.

1075      //$to_email_address and $from_email_address are checked with tep_validate_email().

1076      $to_name = preg_replace('/[\n|\r].*/', '', $to_name);
1077      $email_subject = preg_replace('/[\n|\r].*/', '', $email_subject);
1078      $from_email_name = preg_replace('/[\n|\r].*/', '', $from_email_name);
1079  
1080      // Instantiate a new mail object

1081      $message = new email(array('X-Mailer: osCMax Mailer'));
1082  
1083      // Build the text version

1084      $text = strip_tags($email_text);
1085      if (EMAIL_USE_HTML == 'true') {
1086        $message->add_html($email_text, $text);
1087      } else {
1088        $message->add_text($text);
1089      }
1090  
1091      // Send message

1092      $message->build_message();
1093      $message->send($to_name, $to_email_address, $from_email_name, $from_email_address, $email_subject);
1094    }
1095  
1096  ////

1097  // Check if product has attributes

1098    function tep_has_product_attributes($products_id) {
1099      $attributes_query = tep_db_query("select count(*) as count from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$products_id . "'");
1100      $attributes = tep_db_fetch_array($attributes_query);
1101  
1102      if ($attributes['count'] > 0) {
1103        return true;
1104      } else {
1105        return false;
1106      }
1107    }
1108  
1109  ////

1110  // Get the number of times a word/character is present in a string

1111    function tep_word_count($string, $needle) {
1112      $temp_array = split($needle, $string);
1113  
1114      return sizeof($temp_array);
1115    }
1116  
1117    function tep_count_modules($modules = '') {
1118      $count = 0;
1119  
1120      if (empty($modules)) return $count;
1121  
1122      $modules_array = split(';', $modules);
1123  
1124      for ($i=0, $n=sizeof($modules_array); $i<$n; $i++) {
1125        $class = substr($modules_array[$i], 0, strrpos($modules_array[$i], '.'));
1126  
1127        if (is_object($GLOBALS[$class])) {
1128          if ($GLOBALS[$class]->enabled) {
1129            $count++;
1130          }
1131        }
1132      }
1133  
1134      return $count;
1135    }
1136  
1137    function tep_count_payment_modules() {
1138      return tep_count_modules(MODULE_PAYMENT_INSTALLED);
1139    }
1140  
1141    function tep_count_shipping_modules() {
1142      return tep_count_modules(MODULE_SHIPPING_INSTALLED);
1143    }
1144  
1145    function tep_create_random_value($length, $type = 'mixed') {
1146      if ( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) return false;
1147  
1148      $rand_value = '';
1149      while (strlen($rand_value) < $length) {
1150        if ($type == 'digits') {
1151          $char = tep_rand(0,9);
1152        } else {
1153          $char = chr(tep_rand(0,255));
1154        }
1155        if ($type == 'mixed') {
1156          if (eregi('^[a-z0-9]$', $char)) $rand_value .= $char;
1157        } elseif ($type == 'chars') {
1158          if (eregi('^[a-z]$', $char)) $rand_value .= $char;
1159        } elseif ($type == 'digits') {
1160          if (ereg('^[0-9]$', $char)) $rand_value .= $char;
1161        }
1162      }
1163  
1164      return $rand_value;
1165    }
1166  
1167    function tep_array_to_string($array, $exclude = '', $equals = '=', $separator = '&') {
1168      if (!is_array($exclude)) $exclude = array();
1169  
1170      $get_string = '';
1171      if (sizeof($array) > 0) {
1172        while (list($key, $value) = each($array)) {
1173          if ( (!in_array($key, $exclude)) && ($key != 'x') && ($key != 'y') ) {
1174            $get_string .= $key . $equals . $value . $separator;
1175          }
1176        }
1177        $remove_chars = strlen($separator);
1178        $get_string = substr($get_string, 0, -$remove_chars);
1179      }
1180  
1181      return $get_string;
1182    }
1183  
1184    function tep_not_null($value) {
1185      if (is_array($value)) {
1186        if (sizeof($value) > 0) {
1187          return true;
1188        } else {
1189          return false;
1190        }
1191      } else {
1192        if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
1193          return true;
1194        } else {
1195          return false;
1196        }
1197      }
1198    }
1199  
1200  ////

1201  // Output the tax percentage with optional padded decimals

1202    function tep_display_tax_value($value, $padding = TAX_DECIMAL_PLACES) {
1203      if (strpos($value, '.')) {
1204        $loop = true;
1205        while ($loop) {
1206          if (substr($value, -1) == '0') {
1207            $value = substr($value, 0, -1);
1208          } else {
1209            $loop = false;
1210            if (substr($value, -1) == '.') {
1211              $value = substr($value, 0, -1);
1212            }
1213          }
1214        }
1215      }
1216  
1217      if ($padding > 0) {
1218        if ($decimal_pos = strpos($value, '.')) {
1219          $decimals = strlen(substr($value, ($decimal_pos+1)));
1220          for ($i=$decimals; $i<$padding; $i++) {
1221            $value .= '0';
1222          }
1223        } else {
1224          $value .= '.';
1225          for ($i=0; $i<$padding; $i++) {
1226            $value .= '0';
1227          }
1228        }
1229      }
1230  
1231      return $value;
1232    }
1233  
1234  ////

1235  // Checks to see if the currency code exists as a currency

1236  // TABLES: currencies

1237    function tep_currency_exists($code) {
1238      $code = tep_db_prepare_input($code);
1239  
1240      $currency_query = tep_db_query("select code from " . TABLE_CURRENCIES . " where code = '" . tep_db_input($code) . "' limit 1");
1241      if (tep_db_num_rows($currency_query)) {
1242        $currency = tep_db_fetch_array($currency_query);
1243        return $currency['code'];
1244      } else {
1245        return false;
1246      }
1247    }
1248  
1249    function tep_string_to_int($string) {
1250      return (int)$string;
1251    }
1252  
1253  ////

1254  // Parse and secure the cPath parameter values

1255    function tep_parse_category_path($cPath) {
1256  // make sure the category IDs are integers

1257      $cPath_array = array_map('tep_string_to_int', explode('_', $cPath));
1258  
1259  // make sure no duplicate category IDs exist which could lock the server in a loop

1260      $tmp_array = array();
1261      $n = sizeof($cPath_array);
1262      for ($i=0; $i<$n; $i++) {
1263        if (!in_array($cPath_array[$i], $tmp_array)) {
1264          $tmp_array[] = $cPath_array[$i];
1265        }
1266      }
1267  
1268      return $tmp_array;
1269    }
1270  
1271  ////

1272  // Return a random value

1273    function tep_rand($min = null, $max = null) {
1274      static $seeded;
1275  
1276      if (!isset($seeded)) {
1277        mt_srand((double)microtime()*1000000);
1278        $seeded = true;
1279      }
1280  
1281      if (isset($min) && isset($max)) {
1282        if ($min >= $max) {
1283          return $min;
1284        } else {
1285          return mt_rand($min, $max);
1286        }
1287      } else {
1288        return mt_rand();
1289      }
1290    }
1291  
1292    function tep_setcookie($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = 0) {
1293      setcookie($name, $value, $expire, $path, (tep_not_null($domain) ? $domain : ''), $secure);
1294    }
1295  
1296    function tep_get_ip_address() {
1297      global $HTTP_SERVER_VARS;
1298  
1299      if (isset($HTTP_SERVER_VARS)) {
1300        if (isset($HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'])) {
1301          $ip = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'];
1302        } elseif (isset($HTTP_SERVER_VARS['HTTP_CLIENT_IP'])) {
1303          $ip = $HTTP_SERVER_VARS['HTTP_CLIENT_IP'];
1304        } else {
1305          $ip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
1306        }
1307      } else {
1308        if (getenv('HTTP_X_FORWARDED_FOR')) {
1309          $ip = getenv('HTTP_X_FORWARDED_FOR');
1310        } elseif (getenv('HTTP_CLIENT_IP')) {
1311          $ip = getenv('HTTP_CLIENT_IP');
1312        } else {
1313          $ip = getenv('REMOTE_ADDR');
1314        }
1315      }
1316  
1317      return $ip;
1318    }
1319  
1320    function tep_count_customer_orders($id = '', $check_session = true) {
1321      global $customer_id, $languages_id;
1322  
1323      if (is_numeric($id) == false) {
1324        if (tep_session_is_registered('customer_id')) {
1325          $id = $customer_id;
1326        } else {
1327          return 0;
1328        }
1329      }
1330  
1331      if ($check_session == true) {
1332        if ( (tep_session_is_registered('customer_id') == false) || ($id != $customer_id) ) {
1333          return 0;
1334        }
1335      }
1336  
1337      $orders_check_query = tep_db_query("select count(*) as total from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_STATUS . " s where o.customers_id = '" . (int)$id . "' and o.orders_status = s.orders_status_id and s.language_id = '" . (int)$languages_id . "' and s.public_flag = '1'");
1338      $orders_check = tep_db_fetch_array($orders_check_query);
1339  
1340      return $orders_check['total'];
1341    }
1342  
1343    function tep_count_customer_address_book_entries($id = '', $check_session = true) {
1344      global $customer_id;
1345  
1346      if (is_numeric($id) == false) {
1347        if (tep_session_is_registered('customer_id')) {
1348          $id = $customer_id;
1349        } else {
1350          return 0;
1351        }
1352      }
1353  
1354      if ($check_session == true) {
1355        if ( (tep_session_is_registered('customer_id') == false) || ($id != $customer_id) ) {
1356          return 0;
1357        }
1358      }
1359  
1360      $addresses_query = tep_db_query("select count(*) as total from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$id . "'");
1361      $addresses = tep_db_fetch_array($addresses_query);
1362  
1363      return $addresses['total'];
1364    }
1365  
1366  // nl2br() prior PHP 4.2.0 did not convert linefeeds on all OSs (it only converted \n)

1367    function tep_convert_linefeeds($from, $to, $string) {
1368      if ((PHP_VERSION < "4.0.5") && is_array($from)) {
1369        return ereg_replace('(' . implode('|', $from) . ')', $to, $string);
1370      } else {
1371        return str_replace($from, $to, $string);
1372      }
1373    }
1374  
1375  // BOF: MOD - Downloads Controller

1376    require (DIR_WS_FUNCTIONS . 'downloads_controller.php');
1377  // EOF: MOD - Downloads Controller

1378  
1379  // BOF: MOD - Ultimate SEO URLs - by Chemo

1380  // Funtion to reset SEO URLs database cache entries

1381    function tep_reset_cache_data_seo_urls($action){
1382      switch ($action){
1383        case 'reset':
1384          tep_db_query("DELETE FROM cache WHERE cache_name LIKE '%seo_urls%'");
1385          tep_db_query("UPDATE configuration SET configuration_value='false' WHERE configuration_key='SEO_URLS_CACHE_RESET'");
1386          break;
1387        default:
1388          break;
1389      }
1390      # The return value is used to set the value upon viewing

1391      # It's NOT returining a false to indicate failure!!

1392      return 'false';
1393    }
1394  // EOF: MOD - Ultimate SEO URLs - by Chemo

1395  
1396  // BOF: MOD - FedEx

1397  // link to fedex shipment tracker

1398    function tep_track_fedex($order_id) {
1399      $fedex_query = tep_db_query("select fedex_tracking from " . TABLE_ORDERS . " where orders_id = '" . (int)$order_id . "'");
1400      $fedexArray = tep_db_fetch_array($fedex_query);
1401      $fedex_tracking = $fedexArray['fedex_tracking'];
1402      $trackLink = false;
1403      if ($fedex_tracking) {
1404        $trackLink = tep_href_link(FILENAME_TRACK_FEDEX) . '?&track=' . $fedex_tracking;
1405      }
1406      return $trackLink;
1407    }
1408  // EOF: MOD - FedEx

1409  
1410  // BOF: Mod - Validate SEO URLs

1411    function tep_validate_seo_urls() {
1412      global $HTTP_GET_VARS, $request_type;
1413      ( $request_type == 'NONSSL' ? $fwr_server_port = HTTP_SERVER : $fwr_server_port = HTTPS_SERVER );
1414      $querystring = str_replace('?', '&', $_SERVER['REQUEST_URI']);
1415      if (isset($HTTP_GET_VARS['products_id']))
1416      $get_id_vars = str_replace(strstr($HTTP_GET_VARS['products_id'], '{'), '', $HTTP_GET_VARS['products_id']); // Remove attributes

1417      $qs_parts = explode('&', $querystring); // explode the querystring into an array

1418      $count = count($qs_parts);
1419      $added_uri = array();
1420      $remove_nasties = array('%3C', '%3E', '<', '>', ':/', 'http', 'HTTP'); // We do tep_sanitize_string() later anyway

1421      for ( $i=0; $i<$count; $i++ ) { // We don't want to introduce vulnerability do we :)
1422        switch($qs_parts[$i]) {
1423          case(false !== strpos($qs_parts[$i], '.html')):
1424            $core = urldecode($qs_parts[$i]); // Found the path

1425            ( (strstr($core, '{') !== false) ? ($core = str_replace(strstr($core, '{'), '', $core) . '.html') : NULL ); // Remove attributes

1426            break;
1427          case(false !== strpos($qs_parts[$i], 'osCsid')):
1428            $seo_sid = $qs_parts[$i]; // Found the osCsid

1429            break;
1430          default:
1431            $added_uri[] = ( urldecode(str_replace($remove_nasties, '', $qs_parts[$i])) ); // Found the additional querystring (e.g. &page=3&sort=2a from split_page_results)

1432          }
1433        }
1434        $do_validation = true; // Set to false later if it is not an seo url so that other .html files pass through unhindered

1435        // If -x- is in the querystring create var $querytype which is a string which explodes into an array on -

1436        ( strpos($_SERVER['REQUEST_URI'], '-p-') ? ($querytype = 'filename_product_info-products_id=' . $get_id_vars) :
1437        ( strpos($_SERVER['REQUEST_URI'], '-c-') ? ($querytype = 'filename_default-cPath=' . $HTTP_GET_VARS['cPath']) :
1438        ( strpos($_SERVER['REQUEST_URI'], '-m-') ? ($querytype = 'filename_default-manufacturers_id=' . $HTTP_GET_VARS['manufacturers_id']) :
1439        ( strpos($_SERVER['REQUEST_URI'], '-pi-') ? ($querytype = 'filename_popup_image-pID=' . $HTTP_GET_VARS['pID']) :
1440        ( strpos($_SERVER['REQUEST_URI'], '-t-') ? ($querytype = 'filename_articles-tPath=' . $HTTP_GET_VARS['tPath']) :
1441        ( strpos($_SERVER['REQUEST_URI'], '-a-') ? ($querytype = 'filename_article_info-articles_id=' . $HTTP_GET_VARS['articles_id']) :
1442        ( strpos($_SERVER['REQUEST_URI'], '-pr-') ? ($querytype = 'filename_product_reviews-products_id=' . $get_id_vars) :
1443        ( strpos($_SERVER['REQUEST_URI'], '-pri-') ? ($querytype = 'filename_product_reviews_info-products_id=' . $get_id_vars) :
1444        ( strpos($_SERVER['REQUEST_URI'], '-prw-') ? ($querytype = 'filename_product_reviews_write-products_id=' . $get_id_vars) :
1445        ( strpos($_SERVER['REQUEST_URI'], '-i-') ? ($querytype = 'filename_information-info_id=' . $HTTP_GET_VARS['info_id']) :
1446        ( strpos($_SERVER['REQUEST_URI'], '-links-') ? ($querytype = 'filename_links-lPath=' . $HTTP_GET_VARS['lPath']) :
1447        $do_validation = false )))))))))) );
1448  
1449        if ( true === $do_validation ) { // It's an SEO URL so we will validate it
1450          $validate_array = explode('-', $querytype); // Gives e.g. $validate_array[0] = filename_default, $validate_array[1] = products_id=xx

1451          $linkreturned = tep_href_link(constant(strtoupper($validate_array[0])), $validate_array[1]); // Get a propper new SEO link

1452          // Rebuild the extra querystring

1453          ( (strpos($linkreturned, '?') !== false) ? ($seperator = '&') : ($seperator = '?') ); // Is there an osCsid on $linkreturned?

1454          $count = count($added_uri); // Count the extra querystring items

1455          for ($i=0; $i<$count; $i++)
1456          if ($i == 0) $linkreturned = $linkreturned . $seperator . tep_sanitize_string($added_uri[$i]); //add the first using seperator ? or &

1457          else $linkreturned = $linkreturned . '&' . tep_sanitize_string($added_uri[$i]); // Just add "&" this time

1458          $linkreturnedstripped = str_replace( strstr($linkreturned, '?'), '', $linkreturned); // Strip osCsid to allow a match with $core

1459          $linktest = str_replace($fwr_server_port . DIR_WS_HTTP_CATALOG, '', $linkreturned); // Pair the url down to the querystring

1460          if (strpos($linktest, '-') === 0) { // If the link returned by seo.class.php has no text mysite.com/-c-xxx.html
1461          four_o_four_die(); // Product/category does not exist so die here with a 404

1462          exit;
1463        } else if ( $fwr_server_port . $core != $linkreturnedstripped ) { // Link looks bad so 301
1464          $linkreturned = str_replace('&amp;', '&', $linkreturned); // Just in case those sneaky W3C urls tried to throw in an &amp;

1465          header("HTTP/1.0 301 Moved Permanently"); // redirect to the good version

1466          header("Location: $linkreturned"); // 301 redirect

1467          exit;
1468        }
1469      } // We're not doing validation as the -p-, -c- etc was not found

1470    }
1471  
1472    function four_o_four_die() { // 404 then redirect doesn't work as Google records a 302 so we need to die here with a 404
1473      echo
1474        header("HTTP/1.0 404 Not Found") .
1475        '<p align="left" style="font-size: large;">&nbsp;&nbsp;404 Page not found!</p>
1476        <div align="center" style="width: 100%; margin-top: 70px;">
1477        <div align="center" style="font-family: verdana; font-size: 0.8em; color: #818181; padding: 90px 10px 90px 10px; width: 60%; border: 1px solid #818181;">
1478        This product/category does not exist it may have been deleted.<p />
1479        To return to ' . STORE_NAME .
1480        '. Please click here <a href="' . tep_href_link(FILENAME_DEFAULT) . '" title="' . STORE_NAME . '">back to ' . STORE_NAME . '</a>
1481        </div></div>';
1482    }
1483  // EOF: Mod - Validate SEO URLs

1484  ?>


Generated: Fri Jan 1 13:43:16 2010 Cross-referenced by PHPXref 0.7