<?php
/* --------------------------------------------------------------
   $Id: general.php,v 1.35 2003/08/13 23:38:04 mbs Exp

   XT-Commerce - community made shopping
   http://www.xt-commerce.com

   Copyright (c) 2003 XT-Commerce
   --------------------------------------------------------------
   based on:
   (c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
   (c) 2002-2003 osCommerce(general.php,v 1.156 2003/05/29); www.oscommerce.com
   (c) 2003	 nextcommerce (general.php,v 1.35 2003/08/1); www.nextcommerce.org

   Released under the GNU General Public License
   --------------------------------------------------------------
   Third Party contributions:

   Customers Status v3.x (c) 2002-2003 Copyright Elari elari@free.fr | www.unlockgsm.com/dload-osc/ | CVS : http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/elari/?sortby=date#dirlist

   Enable_Disable_Categories 1.3                Autor: Mikel Williams | mikel@ladykatcostumes.com

   Category Descriptions (Version: 1.5 MS2)    Original Author:   Brian Lowe <blowe@wpcusrgrp.org> | Editor: Lord Illicious <shaolin-venoms@illicious.net>

   Credit Class/Gift Vouchers/Discount Coupons (Version 5.10)
   http://www.oscommerce.com/community/contributions,282
   Copyright (c) Strider | Strider@oscworks.com
   Copyright (c  Nick Stanko of UkiDev.com, nick@ukidev.com
   Copyright (c) Andre ambidex@gmx.net
   Copyright (c) 2001,2002 Ian C Wilson http://www.phesis.org

   Released under the GNU General Public License
   --------------------------------------------------------------*/
  function clear_string($value) {

  $string=str_replace("'",'',$value);
  $string=str_replace(')','',$string);
  $string=str_replace('(','',$string);
  $array=explode(',',$string);
  return $array;

  }

function xtc_show_dir($dir, $pos=2){
	$files = array();
	$handle = @opendir($dir);
	while ($file = @readdir ($handle)) 
	{
		if (eregi("^\.{1,2}$",$file))
		{
		continue;
		}
	
	if(is_dir($dir.$file))
		{
		printf ("% ".$pos."s <b>%s</b>\n", "|-", $file);
		show_dir($dir.$file."/", $pos + 3);               
		}
		else
		{
		$files[] = $file;
		}
	}
	@closedir($handle); 
	return($files);
  }
  
  function xtc_cfg_pull_down_ebay_user($ebay_user,$key='') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
    $user_array = xtc_get_ebay_users();
    return xtc_draw_pull_down_menu($name, $user_array, $ebay_user);
  }

  function xtc_get_ebay_users(){
	$env = (EBAY_TESTMODE == 1) ? 'sandbox' : 'production';
	$user_array = array();
	$user_query = xtc_db_query("SELECT user FROM ebay_auth WHERE environment='".$env."'");
	while($user = xtc_db_fetch_array($user_query)){
		$user_array[] = array('id'=>$user['user'],'text'=>$user['user']);
	}
	return $user_array;
  }
  
  
  function xtc_get_editor_name($editor_id) {
    if($editor_id == 0) return 'System';
    $editor_name_query = xtc_db_query("SELECT customers_firstname,customers_lastname FROM customers WHERE customers_id='".(int)xtc_db_input($editor_id)."'");
    $editor_name = xtc_db_fetch_array($editor_name_query);
    return $editor_name['customers_firstname'].' '.$editor_name['customers_lastname'];
  }

  // Set Admin Access Rights
  function xtc_set_admin_access($fieldname, $status, $cID) {
    if ($status == '1') {
      return xtc_db_query("update " . TABLE_ADMIN_ACCESS . " set " . $fieldname . " = '1' where customers_id = '" . $cID . "'");
    } else {
      return xtc_db_query("update " . TABLE_ADMIN_ACCESS . " set " . $fieldname . " = '0' where customers_id = '" . $cID . "'");
    }
  }

  // Check whether a referer has enough permission to open an admin page
  function xtc_check_permission($pagename){
  if ($pagename!='index') {
    $access_permission_query = xtc_db_query("select " . $pagename . " from " . TABLE_ADMIN_ACCESS . " where customers_id = '" . $_SESSION['customer_id'] . "'");
    $access_permission = xtc_db_fetch_array($access_permission_query);

    if (($_SESSION['customers_status']['customers_status_id'] == '0') && ($access_permission[$pagename] == '1')) {
      return true;
    } else {
     return false;
    }
    } else {
    xtc_redirect(xtc_href_link(FILENAME_LOGIN));
    }
  }


  ////
  // Redirect to another page or site
  function xtc_redirect($url) {
    global $logger;

    header('Location: ' . $url);

    if (STORE_PAGE_PARSE_TIME == 'true') {
      if (!is_object($logger)) $logger = new logger;
      $logger->timer_stop();
    }

    exit;
  }

  function xtc_customers_name($customers_id) {
    $customers = xtc_db_query("select customers_firstname, customers_lastname from " . TABLE_CUSTOMERS . " where customers_id = '" . $customers_id . "'");
    $customers_values = xtc_db_fetch_array($customers);

    return $customers_values['customers_firstname'] . ' ' . $customers_values['customers_lastname'];
  }

  function yes_get_customers_default_address_book_id($customers_id){
  	global $conn;
  	$resultSet = $conn->GetRow(sprintf("SELECT customers_default_address_id FROM %s WHERE customers_id='%s'",TABLE_CUSTOMERS,$customers_id));
  	return $resultSet['customers_default_address_id'];
  }

  function xtc_get_all_get_params($exclude_array = '') {

    if ($exclude_array == '') $exclude_array = array();

    $get_url = '';

    reset($_GET);
    while (list($key, $value) = each($_GET)) {
      if (($key != session_name()) && ($key != 'error') && (!xtc_in_array($key, $exclude_array))) $get_url .= $key . '=' . $value . '&';
    }

    return $get_url;
  }

  function xtc_date_long($raw_date) {
    if ( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '') ) return false;

    $year = (int)substr($raw_date, 0, 4);
    $month = (int)substr($raw_date, 5, 2);
    $day = (int)substr($raw_date, 8, 2);
    $hour = (int)substr($raw_date, 11, 2);
    $minute = (int)substr($raw_date, 14, 2);
    $second = (int)substr($raw_date, 17, 2);

    return strftime(DATE_FORMAT_LONG, mktime($hour, $minute, $second, $month, $day, $year));
  }

  ////
  // Output a raw date string in the selected locale date format
  // $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
  // NOTE: Includes a workaround for dates before 01/01/1970 that fail on windows servers
  function xtc_date_short($raw_date) {
    if ( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '') ) return false;

    $year = substr($raw_date, 0, 4);
    $month = (int)substr($raw_date, 5, 2);
    $day = (int)substr($raw_date, 8, 2);
    $hour = (int)substr($raw_date, 11, 2);
    $minute = (int)substr($raw_date, 14, 2);
    $second = (int)substr($raw_date, 17, 2);

    if (@date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year) {
      return date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
    } else {
      return ereg_replace('2037' . '$', $year, date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, 2037)));
    }

  }

  function xtc_datetime_short($raw_datetime) {
    if ( ($raw_datetime == '0000-00-00 00:00:00') || ($raw_datetime == '') ) return false;

    $year = (int)substr($raw_datetime, 0, 4);
    $month = (int)substr($raw_datetime, 5, 2);
    $day = (int)substr($raw_datetime, 8, 2);
    $hour = (int)substr($raw_datetime, 11, 2);
    $minute = (int)substr($raw_datetime, 14, 2);
    $second = (int)substr($raw_datetime, 17, 2);

    return strftime(DATE_TIME_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
  }

  function xtc_array_merge($array1, $array2, $array3 = '') {
    if ($array2 == '') $array2 = array();
    if ($array3 == '') $array3 = array();
    if (function_exists('array_merge')) {
      $array_merged = array_merge($array1, $array2, $array3);
    } else {
      while (list($key, $val) = each($array1)) $array_merged[$key] = $val;
      while (list($key, $val) = each($array2)) $array_merged[$key] = $val;
      if (sizeof($array3) > 0) while (list($key, $val) = each($array3)) $array_merged[$key] = $val;
    }

    return (array) $array_merged;
  }

  function xtc_in_array($lookup_value, $lookup_array) {
    if (function_exists('in_array')) {
      if (in_array($lookup_value, $lookup_array)) return true;
    } else {
      reset($lookup_array);
      while (list($key, $value) = each($lookup_array)) {
        if ($value == $lookup_value) return true;
      }
    }

    return false;
  }

  function xtc_get_country_name($country_id) {
    $country_query = xtc_db_query("select countries_name from " . TABLE_COUNTRIES . " where countries_id = '" . $country_id . "'");

    if (!xtc_db_num_rows($country_query)) {
      return $country_id;
    } else {
      $country = xtc_db_fetch_array($country_query);
      return $country['countries_name'];
    }
  }

  function xtc_get_zone_name($country_id, $zone_id, $default_zone) {
    $zone_query = xtc_db_query("select zone_name from " . TABLE_ZONES . " where zone_country_id = '" . $country_id . "' and zone_id = '" . $zone_id . "'");
    if (xtc_db_num_rows($zone_query)) {
      $zone = xtc_db_fetch_array($zone_query);
      return $zone['zone_name'];
    } else {
      return $default_zone;
    }
  }


  function xtc_browser_detect($component) {

    return stristr($_SERVER['HTTP_USER_AGENT'], $component);
  }

  function xtc_geo_zones_pull_down($parameters, $selected = '') {
    $select_string = '<select ' . $parameters . '>';
    $zones_query = xtc_db_query("select geo_zone_id, geo_zone_name from " . TABLE_GEO_ZONES . " order by geo_zone_name");
    while ($zones = xtc_db_fetch_array($zones_query)) {
      $select_string .= '<option value="' . $zones['geo_zone_id'] . '"';
      if ($selected == $zones['geo_zone_id']) $select_string .= ' SELECTED';
      $select_string .= '>' . $zones['geo_zone_name'] . '</option>';
    }
    $select_string .= '</select>';

    return $select_string;
  }

  function xtc_get_geo_zone_name($geo_zone_id) {
    $zones_query = xtc_db_query("select geo_zone_name from " . TABLE_GEO_ZONES . " where geo_zone_id = '" . $geo_zone_id . "'");

    if (!xtc_db_num_rows($zones_query)) {
      $geo_zone_name = $geo_zone_id;
    } else {
      $zones = xtc_db_fetch_array($zones_query);
      $geo_zone_name = $zones['geo_zone_name'];
    }

    return $geo_zone_name;
  }

  function xtc_address_format($address_format_id, $address, $html, $boln, $eoln) {
    $address_format_query = xtc_db_query("select address_format as format from " . TABLE_ADDRESS_FORMAT . " where address_format_id = '" . $address_format_id . "'");
    $address_format = xtc_db_fetch_array($address_format_query);

    $company = addslashes($address['company']);
    $firstname = addslashes($address['firstname']);
    $cid = addslashes($address['csID']);
    $lastname = addslashes($address['lastname']);
    $street = addslashes($address['street_address']);
    $suburb = addslashes($address['suburb']);
    $city = addslashes($address['city']);
    $state = addslashes($address['state']);
    $country_id = $address['country_id'];
    $zone_id = $address['zone_id'];
    $postcode = addslashes($address['postcode']);
    $zip = $postcode;
    $country = xtc_get_country_name($country_id);
    $state = xtc_get_zone_code($country_id, $zone_id, $state);

    if ($html) {
      // HTML Mode
      $HR = '<hr>';
      $hr = '<hr>';
      if ( ($boln == '') && ($eoln == "\n") ) { // Values not specified, use rational defaults
        $CR = '<br>';
        $cr = '<br>';
        $eoln = $cr;
      } else { // Use values supplied
        $CR = $eoln . $boln;
        $cr = $CR;
      }
    } else {
      // Text Mode
      $CR = $eoln;
      $cr = $CR;
      $HR = '----------------------------------------';
      $hr = '----------------------------------------';
    }

    $statecomma = '';
    $streets = $street;
    if ($suburb != '') $streets = $street . $cr . $suburb;
    if ($firstname == '') $firstname = addslashes($address['name']);
    if ($country == '') $country = addslashes($address['country']);
    if ($state != '') $statecomma = $state . ', ';

    $fmt = $address_format['format'];
    eval("\$address = \"$fmt\";");
    $address = stripslashes($address);

    if ( (ACCOUNT_COMPANY == 'true') && (xtc_not_null($company)) ) {
      $address = $company . $cr . $address;
    }

    return $address;
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Function    : xtc_get_zone_code
  //
  // Arguments   : country           country code string
  //               zone              state/province zone_id
  //               def_state         default string if zone==0
  //
  // Return      : state_prov_code   state/province code
  //
  // Description : Function to retrieve the state/province code (as in FL for Florida etc)
  //
  ////////////////////////////////////////////////////////////////////////////////////////////////
  function xtc_get_zone_code($country, $zone, $def_state) {

    $state_prov_query = xtc_db_query("select zone_code from " . TABLE_ZONES . " where zone_country_id = '" . $country . "' and zone_id = '" . $zone . "'");

    if (!xtc_db_num_rows($state_prov_query)) {
      $state_prov_code = $def_state;
    }
    else {
      $state_prov_values = xtc_db_fetch_array($state_prov_query);
      $state_prov_code = $state_prov_values['zone_code'];
    }

    return $state_prov_code;
  }

  function xtc_get_languages() {
    $languages_query = xtc_db_query("select languages_id, name, code, image, directory from " . TABLE_LANGUAGES . " order by sort_order");
    while ($languages = xtc_db_fetch_array($languages_query)) {
      $languages_array[] = array('id' => $languages['languages_id'],
                                 'name' => $languages['name'],
                                 'code' => $languages['code'],
                                 'image' => $languages['image'],
                                 'directory' => $languages['directory']
                                );
    }

    return $languages_array;
  }


  ////
  // Wrapper for class_exists() function
  // This function is not available in all PHP versions so we test it before using it.
  function xtc_class_exists($class_name) {
    if (function_exists('class_exists')) {
      return class_exists($class_name);
    } else {
      return true;
    }
  }


  ////
  // Returns an array with countries
  // TABLES: countries
  function xtc_get_countries($default = '') {
    $countries_array = array();
    if ($default) {
      $countries_array[] = array('id' => STORE_COUNTRY,
                                 'text' => $default);
    }
    $countries_query = xtc_db_query("select countries_id, countries_name from " . TABLE_COUNTRIES . " order by countries_name");
    while ($countries = xtc_db_fetch_array($countries_query)) {
      $countries_array[] = array('id' => $countries['countries_id'],
                                 'text' => $countries['countries_name']);
    }

    return $countries_array;
  }

  ////
  // return an array with country zones
  function xtc_get_country_zones($country_id) {
    $zones_array = array();
    $zones_query = xtc_db_query("select zone_id, zone_name from " . TABLE_ZONES . " where zone_country_id = '" . $country_id . "' order by zone_name");
    while ($zones = xtc_db_fetch_array($zones_query)) {
      $zones_array[] = array('id' => $zones['zone_id'],
                             'text' => $zones['zone_name']);
    }

    return $zones_array;
  }

  function xtc_prepare_country_zones_pull_down($country_id = '') {
    // preset the width of the drop-down for Netscape
    $pre = '';
    if ( (!xtc_browser_detect('MSIE')) && (xtc_browser_detect('Mozilla/4')) ) {
      for ($i=0; $i<45; $i++) $pre .= '&nbsp;';
    }

    $zones = xtc_get_country_zones($country_id);

    if (sizeof($zones) > 0) {
      $zones_select = array(array('id' => '', 'text' => PLEASE_SELECT));
      $zones = xtc_array_merge($zones_select, $zones);
    } else {
      $zones = array(array('id' => '', 'text' => TYPE_BELOW));
      // create dummy options for Netscape to preset the height of the drop-down
      if ( (!xtc_browser_detect('MSIE')) && (xtc_browser_detect('Mozilla/4')) ) {
        for ($i=0; $i<9; $i++) {
          $zones[] = array('id' => '', 'text' => $pre);
        }
      }
    }

    return $zones;
  }

  ////
  // Get list of address_format_id's
  function xtc_get_address_formats() {
    $address_format_query = xtc_db_query("select address_format_id from " . TABLE_ADDRESS_FORMAT . " order by address_format_id");
    $address_format_array = array();
    while ($address_format_values = xtc_db_fetch_array($address_format_query)) {
      $address_format_array[] = array('id' => $address_format_values['address_format_id'],
                                      'text' => $address_format_values['address_format_id']);
    }
    return $address_format_array;
  }

  ////
  // Alias function for Store configuration values in the Administration Tool
  function xtc_cfg_pull_down_country_list($country_id) {
    return xtc_draw_pull_down_menu('configuration_value', xtc_get_countries(), $country_id);
  }

  function xtc_cfg_pull_down_zone_list($zone_id) {
    return xtc_draw_pull_down_menu('configuration_value', xtc_get_country_zones(STORE_COUNTRY), $zone_id);
  }

  function xtc_cfg_pull_down_tax_classes($tax_class_id, $key = '') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');

    $tax_class_array = array(array('id' => '0', 'text' => TEXT_NONE));
    $tax_class_query = xtc_db_query("select tax_class_id, tax_class_title from " . TABLE_TAX_CLASS . " order by tax_class_title");
    while ($tax_class = xtc_db_fetch_array($tax_class_query)) {
      $tax_class_array[] = array('id' => $tax_class['tax_class_id'],
                                 'text' => $tax_class['tax_class_title']);
    }

    return xtc_draw_pull_down_menu($name, $tax_class_array, $tax_class_id);
  }

  ////
  // Function to read in text area in admin
 function xtc_cfg_textarea($text) {
    return xtc_draw_textarea_field('configuration_value', false, 35, 5, $text);
  }

  function xtc_cfg_get_zone_name($zone_id) {
    $zone_query = xtc_db_query("select zone_name from " . TABLE_ZONES . " where zone_id = '" . $zone_id . "'");

    if (!xtc_db_num_rows($zone_query)) {
      return $zone_id;
    } else {
      $zone = xtc_db_fetch_array($zone_query);
      return $zone['zone_name'];
    }
  }

  ////
  // Alias function for Store configuration values in the Administration Tool
  function xtc_cfg_select_option($select_array, $key_value, $key = '') {
    for ($i = 0, $n = sizeof($select_array); $i < $n; $i++) {
      $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
      $string .= '<br><input type="radio" name="' . $name . '" value="' . $select_array[$i] . '"';
      if ($key_value == $select_array[$i]) $string .= ' CHECKED';
      $string .= '> ' . $select_array[$i];
    }

    return $string;
  }

  ////
  // Alias function for module configuration keys
  function xtc_mod_select_option($select_array, $key_name, $key_value) {
    reset($select_array);
    while (list($key, $value) = each($select_array)) {
      if (is_int($key)) $key = $value;
      $string .= '<br><input type="radio" name="configuration[' . $key_name . ']" value="' . $key . '"';
      if ($key_value == $key) $string .= ' CHECKED';
      $string .= '> ' . $value;
    }

    return $string;
  }

  function xtc_array_shift(&$array) {
    if (function_exists('array_shift')) {
      return array_shift($array);
    } else {
      $i = 0;
      $shifted_array = array();
      reset($array);
      while (list($key, $value) = each($array)) {
        if ($i > 0) {
          $shifted_array[$key] = $value;
        } else {
          $return = $array[$key];
        }
        $i++;
      }
      $array = $shifted_array;

      return $return;
    }
  }

  function xtc_array_reverse($array) {
    if (function_exists('array_reverse')) {
      return array_reverse($array);
    } else {
      $reversed_array = array();
      for ($i=sizeof($array)-1; $i>=0; $i--) {
        $reversed_array[] = $array[$i];
      }
      return $reversed_array;
    }
  }


  function xtc_reset_cache_block($cache_block) {
    global $cache_blocks;

    for ($i = 0, $n = sizeof($cache_blocks); $i < $n; $i++) {
      if ($cache_blocks[$i]['code'] == $cache_block) {
        if ($cache_blocks[$i]['multiple']) {
          if ($dir = @opendir(DIR_FS_CACHE)) {
            while ($cache_file = readdir($dir)) {
              $cached_file = $cache_blocks[$i]['file'];
              $languages = xtc_get_languages();
              for ($j = 0, $k = sizeof($languages); $j < $k; $j++) {
                $cached_file_unlink = ereg_replace('-language', '-' . $languages[$j]['directory'], $cached_file);
                if (ereg('^' . $cached_file_unlink, $cache_file)) {
                  @unlink(DIR_FS_CACHE . $cache_file);
                }
              }
            }
            closedir($dir);
          }
        } else {
          $cached_file = $cache_blocks[$i]['file'];
          $languages = xtc_get_languages();
          for ($i = 0, $n = sizeof($languages); $i < $n; $i++) {
            $cached_file = ereg_replace('-language', '-' . $languages[$i]['directory'], $cached_file);
            @unlink(DIR_FS_CACHE . $cached_file);
          }
        }
        break;
      }
    }
  }

  function xtc_array_slice($array, $offset, $length = '0') {
    if (function_exists('array_slice')) {
      return array_slice($array, $offset, $length);
    } else {
      $length = abs($length);
      if ($length == 0) {
        $high = sizeof($array);
      } else {
        $high = $offset+$length;
      }

      for ($i=$offset; $i<$high; $i++) {
        $new_array[$i-$offset] = $array[$i];
      }

      return $new_array;
    }
  }


  ////
  // Wrapper for constant() function
  // Needed because its only available in PHP 4.0.4 and higher.
  function xtc_constant($constant) {
    if (function_exists('constant')) {
      $temp = constant($constant);
    } else {
      eval("\$temp=$constant;");
    }
    return $temp;
  }

  ////
  // Output the tax percentage with optional padded decimals
  function xtc_display_tax_value($value, $padding = TAX_DECIMAL_PLACES) {
    if (strpos($value, '.')) {
      $loop = true;
      while ($loop) {
        if (substr($value, -1) == '0') {
          $value = substr($value, 0, -1);
        } else {
          $loop = false;
          if (substr($value, -1) == '.') {
            $value = substr($value, 0, -1);
          }
        }
      }
    }

    if ($padding > 0) {
      if ($decimal_pos = strpos($value, '.')) {
        $decimals = strlen(substr($value, ($decimal_pos+1)));
        for ($i=$decimals; $i<$padding; $i++) {
          $value .= '0';
        }
      } else {
        $value .= '.';
        for ($i=0; $i<$padding; $i++) {
          $value .= '0';
        }
      }
    }

    return $value;
  }



  function xtc_get_tax_class_title($tax_class_id) {
    if ($tax_class_id == '0') {
      return TEXT_NONE;
    } else {
      $classes_query = xtc_db_query("select tax_class_title from " . TABLE_TAX_CLASS . " where tax_class_id = '" . $tax_class_id . "'");
      $classes = xtc_db_fetch_array($classes_query);

      return $classes['tax_class_title'];
    }
  }


  ////
  // Wrapper function for round()
  function xtc_round($value, $precision) {
      return round($value, $precision);
  }

  ////
  // Add tax to a products price
  /*
  function xtc_add_tax($price, $tax) {
    global $currencies;

    if (DISPLAY_PRICE_WITH_TAX == 'true') {
      return xtc_round($price, $currencies->currencies[DEFAULT_CURRENCY]['decimal_places']) + xtc_calculate_tax($price, $tax);
    } else {
      return xtc_round($price, $currencies->currencies[DEFAULT_CURRENCY]['decimal_places']);
    }
  }
*/
  // Calculates Tax rounding the result
  function xtc_calculate_tax($price, $tax) {
    global $currencies;

    return xtc_round($price * $tax / 100, $currencies->currencies[DEFAULT_CURRENCY]['decimal_places']);
  }

  function xtc_call_function($function, $parameter, $object = '') {
    if ($object == '') {
      return call_user_func($function, $parameter);
    } else {
      return call_user_func(array($object, $function), $parameter);
    }
  }

  function xtc_get_zone_class_title($zone_class_id) {
    if ($zone_class_id == '0') {
      return TEXT_NONE;
    } else {
      $classes_query = xtc_db_query("select geo_zone_name from " . TABLE_GEO_ZONES . " where geo_zone_id = '" . $zone_class_id . "'");
      $classes = xtc_db_fetch_array($classes_query);

      return $classes['geo_zone_name'];
    }
  }


  function xtc_cfg_pull_down_zone_classes($zone_class_id, $key = '') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');

    $zone_class_array = array(array('id' => '0', 'text' => TEXT_NONE));
    $zone_class_query = xtc_db_query("select geo_zone_id, geo_zone_name from " . TABLE_GEO_ZONES . " order by geo_zone_name");
    while ($zone_class = xtc_db_fetch_array($zone_class_query)) {
      $zone_class_array[] = array('id' => $zone_class['geo_zone_id'],
                                  'text' => $zone_class['geo_zone_name']);
    }

    return xtc_draw_pull_down_menu($name, $zone_class_array, $zone_class_id);
  }

  ////
  // Return a random value
  function xtc_rand($min = null, $max = null) {
    static $seeded;

    if (!$seeded) {
      mt_srand((double)microtime()*1000000);
      $seeded = true;
    }

    if (isset($min) && isset($max)) {
      if ($min >= $max) {
        return $min;
      } else {
        return mt_rand($min, $max);
      }
    } else {
      return mt_rand();
    }
  }

  // nl2br() prior PHP 4.2.0 did not convert linefeeds on all OSs (it only converted \n)
  function xtc_convert_linefeeds($from, $to, $string) {
    if ((PHP_VERSION < "4.0.5") && is_array($from)) {
      return ereg_replace('(' . implode('|', $from) . ')', $to, $string);
    } else {
      return str_replace($from, $to, $string);
    }
  }

  // Return all customers statuses for a specified language_id and return an array(array())
  // Use it to make pull_down_menu, checkbox....
  function xtc_get_customers_statuses() {

     $customers_statuses_array = array(array());
     $customers_statuses_query = xtc_db_query("select customers_status_id, customers_status_name, customers_status_image from " . TABLE_CUSTOMERS_STATUS . " where language_id = '" . $_SESSION['languages_id'] . "' order by customers_status_id");
     $i=1;        // this is changed from 0 to 1 in cs v1.2
     while ($customers_statuses = xtc_db_fetch_array($customers_statuses_query)) {
       $i=$customers_statuses['customers_status_id'];
       $customers_statuses_array[$i] = array('id' => $customers_statuses['customers_status_id'],
                                           'text' => $customers_statuses['customers_status_name'],
                                           'csa_public' => $customers_statuses['customers_status_public'],
                                           'csa_image' => $customers_statuses['customers_status_image']
                                           );
     }
    return $customers_statuses_array;
  }


  function xtc_get_customer_status($customers_id) {

    $customer_status_array = array();
    $customer_status_query = xtc_db_query("select customers_status, member_flag, customers_status_name, customers_status_public, customers_status_image, customers_status_discount, customers_status_ot_discount_flag, customers_status_ot_discount, customers_status_graduated_prices  FROM " . TABLE_CUSTOMERS . " left join " . TABLE_CUSTOMERS_STATUS . " on customers_status = customers_status_id where customers_id='" . $customers_id . "' and language_id = '" . $_SESSION['languages_id'] . "'");
    $customer_status_array = xtc_db_fetch_array($customer_status_query);
  return $customer_status_array;
  }

   function xtc_get_customers_status_name($customers_status_id, $language_id = '') {

     if (!$language_id) $language_id = $_SESSION['languages_id'];
     $customers_status_query = xtc_db_query("select customers_status_name from " . TABLE_CUSTOMERS_STATUS . " where customers_status_id = '" . $customers_status_id . "' and language_id = '" . $language_id . "'");
     $customers_status = xtc_db_fetch_array($customers_status_query);
     return $customers_status['customers_status_name'];
   }

   /**
    * get companies name
    *
    * @param integer $companies_id
    * @return string
    */
   function yes_get_companies_name($companies_id) {
   		global $conn;
   		$query = sprintf("select name from %s where companies_id = '%s'",TABLE_COMPANIES,$companies_id);
   		$records = $conn->CacheGetRow($query);
   		return $records['name'];
   }

   /**
    * get allocated customers for a company
    *
    * @param integer $companies_id
    * @return array
    */
   function yes_get_company_customers($companies_id=false){
   		$array = array();
   		if($companies_id){
	   		$records = xtc_db_query(sprintf("SELECT c.customers_id,concat(c.customers_firstname,' ',c.customers_lastname) as name FROM %s c LEFT JOIN %s c2c USING(customers_id) WHERE c2c.companies_id='%s'",TABLE_CUSTOMERS,TABLE_CUSTOMERS_TO_COMPANIES,$companies_id));
	   		while($row = xtc_db_fetch_array($records)){
	   			$array[] = array('id'=>$row['customers_id'],'text'=>$row['name']);
	   		}
   		}else{
	   		$array[] = array('id'=>'','text'=>TEXT_NONE);
   		}
   		return $array;
   	}

   /*
    * get address array for smarty template
    */	
   function yes_get_address_data_array($array,$key,$type='company',$id=''){
   		if($type == 'address_book' and $key == '') $key = 'entry_';
		$return_array = array(
   			'street_address'=>$array[$key.'street_address'],
   			'suburb'=>$array[$key.'suburb'],
   		   	'postcode'=>$array[$key.'postcode'],
   		   	'city'=>$array[$key.'city']
		);
   		switch($type){
   			case 'company':
   				if($id == '')
   					$return_array['id'] = $array[$key.'id'];
   				else
   					$return_array['id'] = $array[$id];
   				$return_array['name'] = $array[$key.'name'];
   				$return_array['countries_id'] = $array[$key.'countries_id'];
   				$return_array['companies_id'] = $array[$key.'id'];
   				$return_array['vat_id'] = $array[$key.'vat_id'];
   				$return_array['homepage'] = $array[$key.'homepage'];
   				$return_array['email_address'] = $array[$key.'email_address'];
   				$return_array['telephone'] = $array[$key.'telephone'];
   				$return_array['telefax'] = $array[$key.'telefax'];
   				$return_array['company_code'] = $array[$key.'company_code'];
   				$return_array['cid'] = $array['companies_cid'];
   				break;
   			case 'address_book':
   				$return_array['id'] = $array['address_book_id'];
   				$return_array['gender'] = $array['gender_name'];
   				$return_array['firstname'] = $array['entry_firstname'];
   				$return_array['lastname'] = $array['entry_lastname'];
   		   		$return_array['countries_id'] = $array[$key.'country_id'];
   				$return_array['date_added'] = $array['address_date_added'];
   				break;
   			case 'customer':
   				$return_array = array(
   					'id' => $array['customers_id'],
   					'status' => $array['customers_status'],
   					'type' => $array['type'],
   				   	'gender' => $array['gender_name'],
   				   	'firstname' => $array['customers_firstname'],
   				   	'lastname' => $array['customers_lastname'],
   				   	'email_address' => $array['customers_email_address'],
   					'telephone' => $array['customers_telephone'],
   					'fax' => $array['customers_fax'],
   					'newsletter' => $array['customers_newsletter'],
   					'mobile' => $array['mobile'],
   					'date_added' => $array['customers_date_added'],
   					'account_type'=> $array['account']
   				);
   				break;
   		}
		return $return_array;
   }
   	
   function yes_get_company_address_data($id,$additional_values_array=false){
   		$query_raw = sprintf("SELECT * FROM %s WHERE companies_id='%s'",TABLE_COMPANIES,$id);
   		$query = xtc_db_query($query_raw);
   		$row = xtc_db_fetch_array($query);
		if(is_array($additional_values_array) and sizeOf($additional_values_array)>0){
			$row = array_merge($row,$additional_values_array);
		}
		return $row;
   }
   	
   	/**
    * get companies list by type as array for pulldown menu
    *
    * @param string $type
    * @return array
    */
   function yes_get_companies_by_type($type=false){
   		global $conn;
   		$array = array();
   		if($type)
   			$query = sprintf("SELECT c.companies_id,c.name FROM %s c LEFT JOIN %s ct ON c.company_type=ct.company_types_id WHERE ct.code='%s' ORDER BY c.name",TABLE_COMPANIES,TABLE_COMPANY_TYPES,$type);
   		else
   			$query = sprintf("SELECT c.companies_id,c.name FROM %s c ORDER BY c.name",TABLE_COMPANIES);
   		$records_query = xtc_db_query($query);
   		while($records = xtc_db_fetch_array($records_query)){
   			$array[] = array('id'=>$records['companies_id'],'text'=>$records['name']);
   		}
   		return $array;
   }
   
   function yes_get_transport_types(){
   		$array = array(
			0=>array('id'=>'','text'=>TEXT_SELECT),
   			1=>array('id'=>1,'text'=>TEXT_AIR_CARGO),
   			2=>array('id'=>2,'text'=>TEXT_TRUCK),
   			3=>array('id'=>3,'text'=>ENTRY_SHIP),
   			4=>array('id'=>4,'text'=>ENTRY_COURIER),
   			5=>array('id'=>5,'text'=>ENTRY_OTHER)
   		);
   		return $array;
   }
   
   function yes_get_transport_type_name($id){
		$types = yes_get_transport_types();
		foreach($types as $k=>$v){
			if($v['id'] == $id)
				return $v['text'];
		}   		
   }
   /**
    * get units
    *
    * @return array
    */
   function yes_get_units(){
   		global $conn;
   		$array = array();
   		$units = xtc_db_query(sprintf("SELECT units_id,name FROM %s ORDER BY name",TABLE_UNITS));
   		while($unit = xtc_db_fetch_array($units)){
   			$array[] = array('id'=>$unit['units_id'],'text'=>$unit['name']);
   		}
   		return $array;
   }
   
   function yes_get_units_name($id){
   		$query = xtc_db_query(sprintf("SELECT name FROM %s WHERE units_id='%s'",TABLE_UNITS,$id));
   		$record = xtc_db_fetch_array($query);
   		return $record['name'];
   }

   function yes_get_delivery_conditions_import(){
		$array = array(
			0=>array('id'=>'','text'=>TEXT_SELECT)
		);
		$query = xtc_db_query(sprintf("SELECT code FROM %s ORDER BY code",TABLE_DELIVERY_CONDITIONS));
		while($record = xtc_db_fetch_array($query)){
			$array[] = array('id'=>$record['code'],'text'=>$record['code']);
		}
		return $array;
   }
   
   function yes_get_delivery_conditions_import_name($id){
		$types = yes_get_delivery_conditions_import();
		foreach($types as $k=>$v){
			if($v['id'] == $id)
				return $v['text'];
		}   		
   	}
      
   function yes_get_awb_status_name($status){
   		switch($status){
   			case 0:
   				return AWB_STATUS_OPEN;
   			case 1:
   				return AWB_STATUS_USED;
   		}
   }

   function yes_get_awb_open($airlines_id,$show_hints = false){
		$array = array(
			0=>array('id'=>'','text'=>TEXT_SELECT)
		);
   		$query = xtc_db_query(sprintf(
			"SELECT awb_number,booking_hint FROM %s WHERE airlines_id='%s' AND awb_status='0'",
			   TABLE_AWB_NUMBERS,$airlines_id
		));
   		while($row = xtc_db_fetch_array($query)){
			if($show_hints and !empty($row['booking_hint']))
				$text = $row['awb_number'].' ('.substr($row['booking_hint'],0,500).')';
			else
				$text = $row['awb_number'];
   			$array[] = array('id'=>$row['awb_number'],'text'=>$text);
   		}
   		return $array;
   }

   function yes_get_awb_status($airlines_id,$awb_number){
		$query_raw = sprintf(
			"SELECT awb_status FROM %s WHERE airlines_id='%s' AND awb_number='%s'",
			TABLE_AWB_NUMBERS,$airlines_id,$awb_number
		);
		$query = xtc_db_query($query_raw);
		if(!xtc_db_num_rows($query)){
			return -1;
		}
		$result = xtc_db_fetch_array($query);
		return $result['awb_status'];
   }
   function yes_update_awb_status($airlines_id,$awb_number,$status){
		$query_raw = sprintf(
			"UPDATE %s SET awb_status='%s',date_change=now() WHERE airlines_id='%s' and awb_number='%s'",
			TABLE_AWB_NUMBERS,$status,$airlines_id,$awb_number
		);
		xtc_db_query($query_raw);
   }

   function yes_get_airline_name($airlines_id){
	   $query_raw = sprintf(
			"SELECT name FROM %s WHERE airlines_id='%s'",
			TABLE_AIRLINES,(int)$airlines_id
	   );
	   $query = xtc_db_query($query_raw);
	   $result = xtc_db_fetch_array($query);
	   return $result['name'];
   }

   function yes_get_airline_code($airlines_id){
	   $query_raw = sprintf(
			"SELECT number_code FROM %s WHERE airlines_id='%s'",
			TABLE_AIRLINES,(int)$airlines_id
	   );
	   $query = xtc_db_query($query_raw);
	   $result = xtc_db_fetch_array($query);
	   return $result['number_code'];
   }

   function yes_get_locations(){
   		$query = xtc_db_query(sprintf("SELECT code,name FROM %s ORDER BY code",TABLE_AIRPORTS));
   		while($row = xtc_db_fetch_array($query)){
   			$array[] = array('id'=>$row['code'],'text'=>$row['code'].' ('.$row['name'].')');
   		}
   		return $array;
   }
   
   function yes_get_location_name($id){
   		$query_raw = sprintf("SELECT code FROM %s WHERE airports_id='%s'",TABLE_AIRPORTS,$id);
   		$query = xtc_db_query($query_raw);
   		$record = xtc_db_fetch_array($query);
   		return $record['code'];
   }
   
   function yes_get_location_id_by_code($code){
		global $conn;
   		$query_raw = sprintf("SELECT airports_id FROM %s WHERE code='%s'",TABLE_AIRPORTS,$code);
   		$query = $conn->CacheExecute(DB_CACHE_EXPIRE,$query_raw);
   		if($query){
   			$record = current($query);
   			return $record['airports_id'];
		}
   }
   
	function yes_cfg_pull_down_locations($location_id) {
		return xtc_draw_pull_down_menu('location', yes_get_locations(), $location_id);
	}

   function yes_get_all_ships_by_company($companies_id){
	   return yes_get_ships_by_company($companies_id,true);
   }
   function yes_get_ships_by_company($companies_id=false,$show_all=false){
   		global $conn;
   		$array = array(0=>array('id'=>'','text'=>TEXT_SELECT));
   		if($companies_id){
			if($show_all){
				$ships = xtc_db_query(sprintf("SELECT sn.ships_id,sn.name,is_default FROM %s s2c LEFT JOIN %s sn USING(ships_id) WHERE s2c.companies_id='%s' GROUP BY ship_names_id ORDER BY sn.ships_id,is_default DESC",TABLE_SHIPS_TO_COMPANIES,TABLE_SHIP_NAMES,$companies_id));
				$last_ship_id = 0;
				$default_name = '';
				while($ship = xtc_db_fetch_array($ships)){
					if($last_ship_id != $ship['ships_id']){
						$last_ship_id = $ship['ships_id'];
						if($ship['is_default'] == 1){
							$default_name = ' ('.$ship['name'].')';
						}else{
							$default_name = '';
						}
					}
					$array[] = array('id'=>$ship['ships_id'],'text'=>$ship['name'].$default_name);
				}
			}else{
				$ships = xtc_db_query(sprintf("SELECT s.ships_id,sn.name FROM %s s LEFT JOIN %s s2c USING(ships_id) LEFT JOIN %s sn USING(ships_id) WHERE s2c.companies_id='%s' and sn.is_default=1 GROUP BY s.ships_id",TABLE_SHIPS,TABLE_SHIPS_TO_COMPANIES,TABLE_SHIP_NAMES,$companies_id));
				while($ship = xtc_db_fetch_array($ships)){
					$array[] = array('id'=>$ship['ships_id'],'text'=>$ship['name'].' ('.ENTRY_SHIP.')');
				}
			}
   		}else{
	   		$array[] = array('id'=>'','text'=>TEXT_NONE);
   		}
   		return $array;
   }

   /**
    * get array of contacts for the company (by role) of a ship
    *
    * @param int $ships_id
    * @param string $role
    * @return array
    */
   function yes_get_ship_contacts($ships_id,$role = 'owner'){
		$ship_company_id = yes_get_ship_companies_id_by_role($ships_id,$role);
		$array = yes_get_company_customers($ship_company_id);
		return $array;
   }

   function yes_get_ship_names($ships_id){
   		$array = array();

   		$query_raw = sprintf("SELECT name FROM %s WHERE ships_id='%s'",TABLE_SHIP_NAMES,$ships_id);
   		$query = xtc_db_query($query_raw);
   		while($record = xtc_db_fetch_array($query)){
   			$array[] = $record['name'];
   		}
   		if(sizeOf($array)>0){
   			return $array;
   		}
   }

   function yes_get_baptismal_ship_name($ships_id){
   		$query_raw = sprintf("SELECT name FROM %s WHERE ships_id='%s' AND is_baptismal_name=1",TABLE_SHIP_NAMES,$ships_id);
   		$query = xtc_db_query($query_raw);
   		$record = xtc_db_fetch_array($query);
		return $record['name'];
   }
   /**
    * get currencies
    *
    * @return array
    */
   function yes_get_currencies(){
   		$array = array();
   		$query_raw = sprintf("SELECT currencies_id,title FROM %s ORDER BY title",TABLE_CURRENCIES);
   		$query = xtc_db_query($query_raw);
   		while($record = xtc_db_fetch_array($query)){
   			$array[] = array('id'=>$record['currencies_id'],'text'=>$record['title']);
   		}
   		return $array;
   }
   
   function yes_get_currency_name($id){
   		$query_raw = sprintf("SELECT code FROM %s WHERE currencies_id='%s'",TABLE_CURRENCIES,$id);
   		$query = xtc_db_query($query_raw);
   		$record = xtc_db_fetch_array($query);
   		return $record['code'];
   }

   function yes_get_currencies_id_from_code($code){
   		$query_raw = sprintf("SELECT currencies_id FROM %s WHERE code='%s'",TABLE_CURRENCIES,$code);
   		$query = xtc_db_query($query_raw);
   		$record = xtc_db_fetch_array($query);
   		return $record['currencies_id'];
   }

   /**
    * get ship owner
    *
    * @param int $id
    * @return int
    */
   function yes_get_ship_company_id($id){
   		global $conn;
   		$query = sprintf("SELECT companies_id FROM %s WHERE ships_id='%s' and role='owner'",TABLE_SHIPS_TO_COMPANIES,$id);
   		$records = $conn->GetRow($query);
   		return $records['companies_id'];
   }
   
   function yes_get_ship_invoice_company_id($id){
   		global $conn;
   		$query = sprintf("SELECT companies_id FROM %s WHERE ships_id='%s' and role='invoice'",TABLE_SHIPS_TO_COMPANIES,$id);
   		$records = $conn->GetRow($query);
   		return (int)$records['companies_id'];
   }
   
   /**
    * get ship name
    *
    * @param int $ships_id
    * @return string
    */
   function yes_get_ships_name($ships_id) {
   		$query_raw = sprintf("select name from %s where ships_id = '%s' and is_default='1'",TABLE_SHIP_NAMES,$ships_id);
   		$query = xtc_db_query($query_raw);
   		$record = xtc_db_fetch_array($query);
   		return $record['name'];
   }
   
 
   function yes_get_ships_id_from_export_targets_id($export_targets_id){
   		$record = xtc_db_query(sprintf("SELECT ships_id FROM %s WHERE export_targets_id='%s'",TABLE_EXPORT_TARGETS,$export_targets_id));
   		$row = xtc_db_fetch_array($record);
   		return $row['ships_id'];
   	}
   	
   	function yes_get_available_ships_id_for_new_import_ship($default_orderer_id,$imports_id){
   		$array = array(0=>array('id'=>'','text'=>TEXT_SELECT));
   		if($default_orderer_id > 0){
   			// ALS ERSTES ALLE SCHIFFE DIE NOCH NICHT IM IMPORT GESPEICHERT
	   		$query_raw = sprintf("SELECT s.ships_id FROM %s s LEFT JOIN %s ish ON s.ships_id=ish.orderer_ships_id AND ish.imports_id='%s' WHERE ish.orderer_ships_id IS NULL",TABLE_SHIPS,TABLE_IMPORT_SHIPS,$imports_id);
	   		$query = xtc_db_query($query_raw);
	   		while($record = xtc_db_fetch_array($query)){
	   			// NUN NOCH NUR DIE SCHIFFE NACH DEM OWNER FILTERN
	   			$owner_query_raw = sprintf("SELECT ships_id FROM %s WHERE companies_id='%s' AND role='owner' AND ships_id='%s'",TABLE_SHIPS_TO_COMPANIES,$default_orderer_id,$record['ships_id']);
	   			$owner_query = xtc_db_query($owner_query_raw);
	   			if(xtc_db_num_rows($owner_query)){
	   				$array[] = array('id'=>$record['ships_id'],'text'=>yes_get_ships_name($record['ships_id']));	
	   			}
	   		}
   		}
   		return $array;
   	}
   
   function yes_get_ship_companies_id_by_role($ships_id,$role = 'owner'){
   		$record = xtc_db_query(sprintf("SELECT companies_id FROM %s WHERE ships_id='%s' and role='%s'",TABLE_SHIPS_TO_COMPANIES,$ships_id,$role));
   		$row = xtc_db_fetch_array($record);
   		return $row['companies_id'];
   }
   
   /**
    * get customers name
    *
    * @param integer $customers_id
    * @return string
    */
   function yes_get_customers_name($customers_id) {
   		global $conn;
   		$query = sprintf("select concat(customers_firstname,' ',customers_lastname) as name from %s where customers_id = '%s'",TABLE_CUSTOMERS,$customers_id);
   		$records = $conn->CacheGetRow($query);
   		return $records['name'];
   }
   
	function yes_get_duane_statuses() {
		global $conn;
		$array = array();
		$records = $conn->CacheExecute(DB_CACHE_EXPIRE,sprintf("SELECT duane_status_id,name FROM %s",TABLE_DUANE_STATUSES) );
		if($records){
			while(!$records->EOF){
				$array[] = array('id'=>$records->fields['duane_status_id'],'text'=>$records->fields['name']);
				$records->MoveNext();
			}
		}
		return $array;
	}
	
   function yes_get_duane_status_name($id){
		global $conn;
		$query = sprintf("SELECT name FROM %s WHERE duane_status_id='%s'",TABLE_DUANE_STATUSES,$id);
		$records = $conn->CacheGetRow($query);
		if($records['name'])
			return $records['name'];
		else
			return TEXT_UNKNOWN;
   }
   
   
   /**
    * get company_types array for pulldown
    *
    * @return array
    */
	function yes_get_company_types() {
		global $conn;
		$array = array();
		$records = $conn->CacheExecute(DB_CACHE_EXPIRE,sprintf("SELECT company_types_id,name FROM %s ORDER BY name",TABLE_COMPANY_TYPES) );
		if($records){
			while(!$records->EOF){
				$array[] = array('id'=>$records->fields['company_types_id'],'text'=>$records->fields['name']);
				$records->MoveNext();
			}
		}
		return $array;
	}
   
   /**
    * get customer_types array for pulldown
    *
    * @return array
    */
	function yes_get_customer_types() {
		global $conn;
   		$array = array(0=>array('id'=>'','text'=>TEXT_SELECT));
		$records = $conn->CacheExecute(DB_CACHE_EXPIRE,sprintf("SELECT customer_types_id,name FROM %s ORDER BY name",TABLE_CUSTOMER_TYPES) );
		if($records){
			while(!$records->EOF){
				$array[] = array('id'=>$records->fields['customer_types_id'],'text'=>$records->fields['name']);
				$records->MoveNext();
			}
		}
		return $array;
	}

  /**
    * get company_types name
    *
    * @param int $id
    * @return string
    */
   function yes_get_company_types_name($id){
		global $conn;
		$query = sprintf("SELECT name FROM %s WHERE company_types_id='%s'",TABLE_COMPANY_TYPES,$id);
		$records = $conn->CacheGetRow($query);
		if($records['name'])
			return $records['name'];
		else
			return TEXT_UNKNOWN;
   }

   function yes_get_company_name($company_id){
	   $query_raw = sprintf(
		"SELECT name FROM %s WHERE companies_id='%s'",
		TABLE_COMPANIES,$company_id
	   );
	   $query = xtc_db_query($query_raw);
	   $result = xtc_db_fetch_array($query);
	   return $result['name'];
   }

  /**
    * get customer_types name
    *
    * @param int $id
    * @return string
    */
   function yes_get_customer_types_name($id){
		global $conn;
		$query = sprintf("SELECT name FROM %s WHERE customer_types_id='%s'",TABLE_CUSTOMER_TYPES,$id);
		$records = $conn->CacheGetRow($query);
		if($records['name'])
			return $records['name'];
		else
			return TEXT_UNKNOWN;
   }


   /**
    * get bool name
    * 
    * @param boolean $bool_value
    * @return string
    */
   function yes_get_bool_title($bool_value){
   	if($bool_value)
   		return YES;
   	return NO;
   }
   
   function yes_get_collie_formats(){
   		$array = array(0=>array('id'=>'normal','text'=>ENTRY_NORMAL),1=>array('id'=>'special','text'=>ENTRY_SPECIAL));
   		return $array;
   }
   
   function yes_get_sum_of_collies_from_import_ships($import_ships_id_array){
   		$sum = 0;
		if(!empty($import_ships_id_array) and !is_array($import_ships_id_array))
			$import_ships_id_array = array(0=>$import_ships_id_array);
		$ships_num = sizeOf($import_ships_id_array);
   		for($i=0;$i<$ships_num;$i++){
   			$records = xtc_db_query(sprintf("SELECT SUM(quantity) as qty FROM %s WHERE import_ships_id='%s'",TABLE_IMPORT_SHIP_COLLIES,$import_ships_id_array[$i]));
   			$row = xtc_db_fetch_array($records);
   			$sum += $row['qty'];
   		}
   		return $sum;
   }

   function yes_get_import_number_from_import_ships_id($id){
   		$query = xtc_db_query(sprintf("SELECT i.import_number FROM %s ish LEFT JOIN %s i USING(imports_id) WHERE ish.import_ships_id='%s'",TABLE_IMPORT_SHIPS,TABLE_IMPORTS,$id));
   		$record = xtc_db_fetch_array($query);
   		return $record['import_number'];
   }

   function yes_get_export_number_from_exports_id($id){
		$query = xtc_db_query(sprintf("SELECT e.export_number FROM %s e WHERE e.exports_id='%s'",TABLE_EXPORTS,$id));
		$record = xtc_db_fetch_array($query);
   		return $record['export_number'];
   }
   
   function yes_get_import_number_from_imports_id($id){
		$query = xtc_db_query(sprintf("SELECT i.import_number FROM %s i WHERE i.imports_id='%s'",TABLE_IMPORTS,$id));
		$record = xtc_db_fetch_array($query);
   		return $record['import_number'];
   }
   
   function yes_get_invoice_number_from_invoices_id($id){
		$query = xtc_db_query(sprintf("SELECT i.invoice_number FROM %s i WHERE i.invoices_id='%s'",TABLE_INVOICES,$id));
		$record = xtc_db_fetch_array($query);
   		return $record['invoice_number'];
   }
   
   function yes_get_invoice_status_name($id){
   		switch($id){
   			case 0:
   				return INVOICE_STATUS_CREATED;
   				break;
   			case 1:
   				return INVOICE_STATUS_OPEN;
   				break;
   			default:
   				return INVALID_STATUS_ID;
   				break;
   		}
   }
   
   function yes_get_import_ship_status_name($id){
   		switch($id){
   			case '1':
   				return IMPORT_SHIP_STATUS_EXPORTED;
   				break;
   			default:
   				return IMPORT_SHIP_STATUS_CREATED;
   				break;
   		}
   }
   
   function yes_get_imports_status_name($id){
   		return yes_get_import_ship_status_name($id);
   }
   
   function yes_get_exports_status_name($id){
   		return yes_get_import_ship_status_name($id);
   }
   //to set customers status in admin for default value, newsletter, guest...

   
   function xtc_cfg_pull_down_customers_status_list($customers_status_id, $key = '') {
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
    return xtc_draw_pull_down_menu($name, xtc_get_customers_statuses(), $customers_status_id);
  }

  // Function for collecting ip
  // return all log info for a customer_id
  function xtc_get_user_info($customer_id) {
    $user_info_array = xtc_db_query("select customers_ip, customers_ip_date, customers_host, customers_advertiser, customers_referer_url FROM " . TABLE_CUSTOMERS_IP . " where customers_id = '" . $customer_id . "'");
    return $user_info_array;
  }

  //---------------------------------------------------------------kommt wieder raus sp�ter!!
  function xtc_get_uploaded_file($filename) {
    if (isset($_FILES[$filename])) {
      $uploaded_file = array('name' => $_FILES[$filename]['name'],
                             'type' => $_FILES[$filename]['type'],
                             'size' => $_FILES[$filename]['size'],
                             'tmp_name' => $_FILES[$filename]['tmp_name']);
    } elseif (isset($_FILES[$filename])) {
      $uploaded_file = array('name' => $_FILES[$filename]['name'],
                             'type' => $_FILES[$filename]['type'],
                             'size' => $_FILES[$filename]['size'],
                             'tmp_name' => $_FILES[$filename]['tmp_name']);
    } else {
      $uploaded_file = array('name' => $GLOBALS[$filename . '_name'],
                             'type' => $GLOBALS[$filename . '_type'],
                             'size' => $GLOBALS[$filename . '_size'],
                             'tmp_name' => $GLOBALS[$filename]);
    }

    return $uploaded_file;
  }


  function format_price($price_string, $price_special, $currency, $allow_tax, $tax_rate) {
    // calculate currencies
    $currencies_query = xtc_db_query("SELECT
                                          symbol_left,
                                          symbol_right,
                                          decimal_places,
                                          value
                                      FROM
                                          " . TABLE_CURRENCIES . "
                                      WHERE
                                          code = '" . $currency . "'");
    $currencies_value = xtc_db_fetch_array($currencies_query);
    $currencies_data = array();
    $currencies_data = array(
      'SYMBOL_LEFT' => $currencies_value['symbol_left'],
      'SYMBOL_RIGHT' => $currencies_value['symbol_right'],
      'DECIMAL_PLACES' => $currencies_value['decimal_places'],
      'VALUE' => $currencies_value['value']);

    // round price
    if ($allow_tax == 1) $price_string = $price_string/((100+$tax_rate)/100);
    $price_string = precision($price_string, $currencies_data['DECIMAL_PLACES']);
    if ($price_special == '1') {
      $price_string = $currencies_data['SYMBOL_LEFT'] . ' ' . $price_string . ' ' . $currencies_data['SYMBOL_RIGHT'];
    }
    return $price_string;
  }

  function precision($number, $places) {
    $number = number_format($number, $places, '.', '');
    return $number;
  }

  function xtc_get_lang_definition($search_lang, $lang_array, $modifier) {
    $search_lang=$search_lang.$modifier;
    return $lang_array[$search_lang];
  }

  function xtc_get_status_users($status_id) {
    $status_query = xtc_db_query("SELECT count(customers_status) as count FROM " . TABLE_CUSTOMERS . " WHERE customers_status = '" . $status_id . "'");
    $status_data = xtc_db_fetch_array($status_query);
    return $status_data['count'];
  }

  function xtc_try_upload($file = '', $destination = '', $permissions = '777', $extensions = ''){
  	$file_object = new upload($file, $destination, $permissions, $extensions);
  	if ($file_object->filename != '') return $file_object; else return false;
  }

  
  function _debug($var){
  	echo '</td></tr></table></td></tr></table></td></tr></table></div></div><h1>DEBUG MODE</h1><pre>';
  	print_r($var);
  	echo '</pre>';
  	exit;
  }
  
  function convert_xml2array(&$result,$root,$rootname='root'){
   
    $n=count($root->children());

    if ($n>0){

        /**
         * start of the correction
         */
        if (!isset($result[$rootname]['@attributes'])){
            $result[$rootname]['@attributes']=array();
            foreach ($root->attributes() as $atr=>$value){
                $result[$rootname]['@attributes'][$atr]=(string)$value;
            }           
        }
        /**
         *  end of the correction
         */
       
         foreach ($root->children() as $child){
             $name=$child->getName();    
             convert_xml2array($result[$rootname][],$child,$name);                         
         }
    } else {       
        $result[$rootname]= (array) $root;
        if (!isset($result[$rootname]['@attributes'])){
            $result[$rootname]['@attributes']=array();
        }
    }
  }
  
  function get_array_fromXML($xml){       
   
    $result=array();   
   
    $doc=simplexml_load_string($xml);    
   
    convert_xml2array($result,$doc);    
   
    return $result['root'];   
  }

  /**
    * get the global area codes as array
    * array provided from a xml file: MARC Code List for Geographic Areas
    * @return array
    * 
  */
  function get_gacs_array(){
	$xml_filename="includes/gacs.xml";
	$handle = fopen($xml_filename,'r');
	$xml = fread($handle,filesize($xml_filename));
	fclose($handle);
	$codes = array();
	$array = get_array_fromXML($xml); 
	$my_root = $array[4]['gacs'];
	foreach($my_root as $k=>$row){
		if($k != '@attributes'){
			$gac = $row['gac'];
			foreach($gac as $entry_key => $entry){
				if($entry_key != '@attributes'){
					if($entry['name']){
						$codes[] = array('text'=>$gac[2]['code'][0].' ('.$entry['name'][0].')','id'=>$gac[2]['code'][0]);
					}
				}
			}
		}
	}
	return $codes;
  }
  
  function yes_get_country_data($countries_id){
    global $conn;
    $query_raw = sprintf("SELECT * FROM countries WHERE countries_id='%s'",
	  $countries_id
    );
    return $conn->CacheGetRow($query_raw);
  }