[SI-LINDER-PARTNER-2][OSC] - Refonte du site Internet pour supporter le Responsive Design
/*
ATTENTION - le design du site ne peut pas être passé en doctype html (html 5) dans la révision 1 du design.
bien qu'une révision 2 sera instanciée plus tard (l'année prochaine), il faudra se contenter de nombreux workaround en restant en HTML TRANSITIONAL 4.01
Du fait du nombre massif des éléments DE CETTE PAGE (et de ce qui en découlerait) qui seront à revoir pour transformer le design en design responsive..
.. il est alors plus judicieux de globaliser un TAG unique pour cette tâche pour ne pas alourdir de commentaires le code déjà suffisemment alourdi comme cela!
En gros, ici, pour cette méga-tâche, je vais utiliser un format maison de commentaires pour cette tâche précise:
--> pour en comprendre les méandres, voir le fichier /[!] - Saphyra-Interactive-TaskList-Explanations/[SI-LINDER-PARTNER-2][OSC]--semantic.php
*/
// <- [SI-LINDER-PARTNER-2][OSC] - Refonte du site Internet pour supporter le Responsive Design
?> OSC-78: Gestion de catégories réservées aux professionnels
// Création d'une constante php qui servira à la fonction: find_pro_cat_sql_filter
define(CATPRO_METHOD,'constant');
// <- OSC-78: Gestion de catégories réservées aux professionnels
//
////
// Stop from parsing any further PHP code
function tep_exit() {
tep_session_close();
exit();
}
////
// Redirect to another page or site
function tep_redirect($url) {
if ( (strstr($url, "\n") != false) || (strstr($url, "\r") != false) ) {
tep_redirect(tep_href_link(FILENAME_DEFAULT, '', 'NONSSL', false));
}
if ( (ENABLE_SSL == true) && (getenv('HTTPS') == 'on') ) { // We are loading an SSL page
if (substr($url, 0, strlen(HTTP_SERVER)) == HTTP_SERVER) { // NONSSL url
$url = HTTPS_SERVER . substr($url, strlen(HTTP_SERVER)); // Change it to SSL
}
}
header('Location: ' . $url);
tep_exit();
}
////
// Parse the data used in the html tags to ensure the tags will not break
function tep_parse_input_field_data($data, $parse) {
return strtr(trim($data), $parse);
}
function tep_output_string($string, $translate = false, $protected = false) {
if ($protected == true) {
return htmlspecialchars($string);
} else {
if ($translate == false) {
return tep_parse_input_field_data($string, array('"' => '"'));
} else {
return tep_parse_input_field_data($string, $translate);
}
}
}
function tep_output_string_protected($string) {
return tep_output_string($string, false, true);
}
function tep_sanitize_string($string) {
$string = ereg_replace(' +', ' ', trim($string));
return preg_replace("/[<>]/", '_', $string);
}
////
// Return a random row from a database query
function tep_random_select($query) {
$random_product = '';
$random_query = tep_db_query($query);
$num_rows = tep_db_num_rows($random_query);
if ($num_rows > 0) {
$random_row = tep_rand(0, ($num_rows - 1));
tep_db_data_seek($random_query, $random_row);
$random_product = tep_db_fetch_array($random_query);
}
return $random_product;
}
////
// Return a product's name
// TABLES: products
function tep_get_products_name($product_id, $language = '') {
global $languages_id;
if (empty($language)) $language = $languages_id;
$product_query = tep_db_query("select products_name from " . TABLE_PRODUCTS_DESCRIPTION . " where products_id = '" . (int)$product_id . "' and language_id = '" . (int)$language . "'");
$product = tep_db_fetch_array($product_query);
return $product['products_name'];
}
////
// Return a product's special price (returns nothing if there is no offer)
// TABLES: products
function tep_get_products_special_price($product_id) {
$product_query = tep_db_query("select specials_new_products_price from " . TABLE_SPECIALS . " where products_id = '" . (int)$product_id . "' and status");
$product = tep_db_fetch_array($product_query);
return $product['specials_new_products_price'];
}
// Return the product price
function tep_get_products_price($product_id) {
$product_price_query = tep_db_query(
"SELECT products_price
FROM " . TABLE_PRODUCTS . "
WHERE products_status = 1
AND products_id = " . (int)$product_id
);
$product_price = tep_db_fetch_array($product_price_query);
return $product_price['products_price'];
}
// Return the product price
function tep_get_products_cost($product_id) {
$product_price_query = tep_db_query(
"SELECT products_cost
FROM " . TABLE_PRODUCTS . "
WHERE products_status = 1
AND products_id = " . (int)$product_id
);
$product_price = tep_db_fetch_array($product_price_query);
return $product_price['products_cost'];
}
function tep_get_sales_percentage($products_price, $specials_new_products_price ){
return number_format(100 - (((float)$specials_new_products_price / (float)$products_price) * 100)) . '%';
}
function tep_get_specials_indicator($products_price, $specials_new_products_price){
if (LPOSC_SALES_ENABLED == "True"){
return 'SOLDES: -' . tep_get_sales_percentage($products_price, $specials_new_products_price);
}
else{
return 'PROMOTION';
}
}
function tep_get_sales_percentage_vip($products_cost, $coeff_partner, $specials_new_products_price){
if($specials_new_products_price > ((float)$products_cost * $coeff_partner)){
return Null;
}
$percent_vip = number_format(100 - (((float)$specials_new_products_price / ((float)$products_cost*$coeff_partner)) * 100));
if($percent_vip > 0 && $percent_vip < 100)
return '- ' .$percent_vip . '%';
else{
return Null;
}
}
function tep_get_specials_indicator_vip($products_cost, $coeff_partner, $specials_new_products_price){
if (LPOSC_SALES_ENABLED == "True"){
$percent_vip = tep_get_sales_percentage_vip($products_cost, $coeff_partner, $specials_new_products_price);
if($percent_vip == Null || $percent_vip == ''){
return '';
}
else{
return 'SOLDES: ' . tep_get_sales_percentage_vip($products_cost, $coeff_partner, $specials_new_products_price);
}
}
else{
return '';
}
}
////
// Return a product's stock
// TABLES: products
function tep_get_products_stock($products_id) {
$products_id = tep_get_prid($products_id);
$stock_query = tep_db_query("select products_quantity from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
$stock_values = tep_db_fetch_array($stock_query);
return $stock_values['products_quantity'];
}
////
// Check if the required stock is available
// If insufficent stock is available return an out of stock message
function tep_check_stock($products_id, $products_quantity) {
$stock_left = tep_get_products_stock($products_id) - $products_quantity;
$out_of_stock = '';
if ($stock_left < 0) {
$out_of_stock = '' . STOCK_MARK_PRODUCT_OUT_OF_STOCK . '';
}
return $out_of_stock;
}
////
// Break a word in a string if it is longer than a specified length ($len)
function tep_break_string($string, $len, $break_char = '-') {
$l = 0;
$output = '';
for ($i=0, $n=strlen($string); $i<$n; $i++) {
$char = substr($string, $i, 1);
if ($char != ' ') {
$l++;
} else {
$l = 0;
}
if ($l > $len) {
$l = 1;
$output .= $break_char;
}
$output .= $char;
}
return $output;
}
////
// Return all HTTP GET variables, except those passed as a parameter
function tep_get_all_get_params($exclude_array = '') {
global $HTTP_GET_VARS;
if (!is_array($exclude_array)) $exclude_array = array();
$get_url = '';
if (is_array($HTTP_GET_VARS) && (sizeof($HTTP_GET_VARS) > 0)) {
reset($HTTP_GET_VARS);
while (list($key, $value) = each($HTTP_GET_VARS)) {
if ( (strlen($value) > 0) && ($key != tep_session_name()) && ($key != 'error') && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') ) {
$get_url .= $key . '=' . rawurlencode(stripslashes($value)) . '&';
}
}
}
return $get_url;
}
////
// Returns an array with countries
// TABLES: countries
function tep_get_countries($countries_id = '', $with_iso_codes = false) {
$countries_array = array();
if (tep_not_null($countries_id)) {
if ($with_iso_codes == true) {
$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");
$countries_values = tep_db_fetch_array($countries);
$countries_array = array('countries_name' => $countries_values['countries_name'],
'countries_iso_code_2' => $countries_values['countries_iso_code_2'],
'countries_iso_code_3' => $countries_values['countries_iso_code_3']);
} else {
$countries = tep_db_query("select countries_name from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$countries_id . "'");
$countries_values = tep_db_fetch_array($countries);
$countries_array = array('countries_name' => $countries_values['countries_name']);
}
} else {
$countries = tep_db_query("select countries_id, countries_name from " . TABLE_COUNTRIES . " order by countries_name");
while ($countries_values = tep_db_fetch_array($countries)) {
$countries_array[] = array('countries_id' => $countries_values['countries_id'],
'countries_name' => $countries_values['countries_name']);
}
}
return $countries_array;
}
////
// Alias function to tep_get_countries, which also returns the countries iso codes
function tep_get_countries_with_iso_codes($countries_id) {
return tep_get_countries($countries_id, true);
}
////
// Generate a path to categories
function tep_get_path($current_category_id = '') {
global $cPath_array;
if (tep_not_null($current_category_id)) {
$cp_size = sizeof($cPath_array);
if ($cp_size == 0) {
$cPath_new = $current_category_id;
} else {
$cPath_new = '';
$last_category_query = tep_db_query("select parent_id from " . TABLE_CATEGORIES . " where categories_id = '" . (int)$cPath_array[($cp_size-1)] . "'");
$last_category = tep_db_fetch_array($last_category_query);
$current_category_query = tep_db_query("select parent_id from " . TABLE_CATEGORIES . " where categories_id = '" . (int)$current_category_id . "'");
$current_category = tep_db_fetch_array($current_category_query);
if ($last_category['parent_id'] == $current_category['parent_id']) {
for ($i=0; $i<($cp_size-1); $i++) {
$cPath_new .= '_' . $cPath_array[$i];
}
} else {
for ($i=0; $i<$cp_size; $i++) {
$cPath_new .= '_' . $cPath_array[$i];
}
}
$cPath_new .= '_' . $current_category_id;
if (substr($cPath_new, 0, 1) == '_') {
$cPath_new = substr($cPath_new, 1);
}
}
} else {
$cPath_new = implode('_', $cPath_array);
}
return 'cPath=' . $cPath_new;
}
////
// Returns the clients browser
function tep_browser_detect($component) {
global $HTTP_USER_AGENT;
return stristr($HTTP_USER_AGENT, $component);
}
////
// Alias function to tep_get_countries()
function tep_get_country_name($country_id) {
$country_array = tep_get_countries($country_id);
return $country_array['countries_name'];
}
////
// Returns the zone (State/Province) name
// TABLES: zones
function tep_get_zone_name($country_id, $zone_id, $default_zone) {
$zone_query = tep_db_query("select zone_name from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_id = '" . (int)$zone_id . "'");
if (tep_db_num_rows($zone_query)) {
$zone = tep_db_fetch_array($zone_query);
return $zone['zone_name'];
} else {
return $default_zone;
}
}
////
// Returns the zone (State/Province) code
// TABLES: zones
function tep_get_zone_code($country_id, $zone_id, $default_zone) {
$zone_query = tep_db_query("select zone_code from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_id = '" . (int)$zone_id . "'");
if (tep_db_num_rows($zone_query)) {
$zone = tep_db_fetch_array($zone_query);
return $zone['zone_code'];
} else {
return $default_zone;
}
}
////
// Wrapper function for round()
function tep_round($number, $precision) {
if (strpos($number, '.') && (strlen(substr($number, strpos($number, '.')+1)) > $precision)) {
$number = substr($number, 0, strpos($number, '.') + 1 + $precision + 1);
if (substr($number, -1) >= 5) {
if ($precision > 1) {
$number = substr($number, 0, -1) + ('0.' . str_repeat(0, $precision-1) . '1');
} elseif ($precision == 1) {
$number = substr($number, 0, -1) + 0.1;
} else {
$number = substr($number, 0, -1) + 1;
}
} else {
$number = substr($number, 0, -1);
}
}
return $number;
}
////
// Returns the tax rate for a zone / class
// TABLES: tax_rates, zones_to_geo_zones
function tep_get_tax_rate($class_id, $country_id = -1, $zone_id = -1) {
global $customer_zone_id, $customer_country_id;
if ( ($country_id == -1) && ($zone_id == -1) ) {
if (!tep_session_is_registered('customer_id')) {
$country_id = STORE_COUNTRY;
$zone_id = STORE_ZONE;
} else {
$country_id = $customer_country_id;
$zone_id = $customer_zone_id;
}
}
$tax_query = tep_db_query("select sum(tax_rate) as tax_rate from " . TABLE_TAX_RATES . " tr left join " . TABLE_ZONES_TO_GEO_ZONES . " za on (tr.tax_zone_id = za.geo_zone_id) left join " . TABLE_GEO_ZONES . " tz on (tz.geo_zone_id = tr.tax_zone_id) where (za.zone_country_id is null or za.zone_country_id = '0' or za.zone_country_id = '" . (int)$country_id . "') and (za.zone_id is null or za.zone_id = '0' or za.zone_id = '" . (int)$zone_id . "') and tr.tax_class_id = '" . (int)$class_id . "' group by tr.tax_priority");
if (tep_db_num_rows($tax_query)) {
$tax_multiplier = 1.0;
while ($tax = tep_db_fetch_array($tax_query)) {
$tax_multiplier *= 1.0 + ($tax['tax_rate'] / 100);
}
return ($tax_multiplier - 1.0) * 100;
} else {
return 0;
}
}
////
// Return the tax description for a zone / class
// TABLES: tax_rates;
function tep_get_tax_description($class_id, $country_id, $zone_id) {
$tax_query = tep_db_query("select tax_description from " . TABLE_TAX_RATES . " tr left join " . TABLE_ZONES_TO_GEO_ZONES . " za on (tr.tax_zone_id = za.geo_zone_id) left join " . TABLE_GEO_ZONES . " tz on (tz.geo_zone_id = tr.tax_zone_id) where (za.zone_country_id is null or za.zone_country_id = '0' or za.zone_country_id = '" . (int)$country_id . "') and (za.zone_id is null or za.zone_id = '0' or za.zone_id = '" . (int)$zone_id . "') and tr.tax_class_id = '" . (int)$class_id . "' order by tr.tax_priority");
if (tep_db_num_rows($tax_query)) {
$tax_description = '';
while ($tax = tep_db_fetch_array($tax_query)) {
$tax_description .= $tax['tax_description'] . ' + ';
}
$tax_description = substr($tax_description, 0, -3);
return $tax_description;
} else {
return TEXT_UNKNOWN_TAX_RATE;
}
}
////
// Add tax to a products price
function tep_add_tax($price, $tax) {
global $currencies;
if ( (DISPLAY_PRICE_WITH_TAX == 'true') && ($tax > 0) ) {
// -> FAQARR
return round($price, '3') + tep_calculate_tax($price, $tax);
} else {
return round($price, '3');
// <- FAQARR
}
}
// -> OSC-70 : Gestion HT/TTC : affichage prix HT et TTC
/*
* Ajoute la taxe au prix actuel du produit
*/
function prix_avec_taxes($price, $tax) {
global $currencies;
return round($price, '3') + tep_calculate_tax($price, $tax);
}
// <- OSC-70 : Gestion HT/TTC : affichage prix HT et TTC
// Calculates Tax rounding the result
function tep_calculate_tax($price, $tax) {
global $currencies;
// -> FAQARR
return round($price * $tax / 100, '3');
// <- FAQARR
}
////
// Return the number of products in a category
// TABLES: products, products_to_categories, categories
function tep_count_products_in_category($category_id, $include_inactive = false) {
$products_count = 0;
if ($include_inactive == true) {
$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 . "'");
} else {
$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 . "'");
}
$products = tep_db_fetch_array($products_query);
$products_count += $products['total'];
$child_categories_query = tep_db_query("select categories_id from " . TABLE_CATEGORIES . " where parent_id = '" . (int)$category_id . "'");
if (tep_db_num_rows($child_categories_query)) {
while ($child_categories = tep_db_fetch_array($child_categories_query)) {
$products_count += tep_count_products_in_category($child_categories['categories_id'], $include_inactive);
}
}
return $products_count;
}
////
// Return true if the category has subcategories
// TABLES: categories
function tep_has_category_subcategories($category_id) {
$child_category_query = tep_db_query("select count(*) as count from " . TABLE_CATEGORIES . " where parent_id = '" . (int)$category_id . "'");
$child_category = tep_db_fetch_array($child_category_query);
if ($child_category['count'] > 0) {
return true;
} else {
return false;
}
}
////
// Returns the address_format_id for the given country
// TABLES: countries;
function tep_get_address_format_id($country_id) {
$address_format_query = tep_db_query("select address_format_id as format_id from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$country_id . "'");
if (tep_db_num_rows($address_format_query)) {
$address_format = tep_db_fetch_array($address_format_query);
return $address_format['format_id'];
} else {
return '1';
}
}
////
// Return a formatted address
// TABLES: address_format
function tep_address_format($address_format_id, $address, $html, $boln, $eoln) {
// -> 0000026: certaines commandes ont des adresses affichées incomplètes
// il arrive que certaines commandes n'ont pas de format d'adresse
if ( $address_format_id == 0 ) { $address_format_id="1"; }
// <- 0000026
$address_format_query = tep_db_query("select address_format as format from " . TABLE_ADDRESS_FORMAT . " where address_format_id = '" . (int)$address_format_id . "'");
$address_format = tep_db_fetch_array($address_format_query);
$company = tep_output_string_protected($address['company']);
// -> TVAINT
$tva_intracom = tep_output_string_protected($address['tva_intracom']);
// <- TVAINT
if (isset($address['firstname']) && tep_not_null($address['firstname'])) {
$firstname = tep_output_string_protected($address['firstname']);
$lastname = tep_output_string_protected($address['lastname']);
} elseif (isset($address['name']) && tep_not_null($address['name'])) {
$firstname = tep_output_string_protected($address['name']);
$lastname = '';
} else {
$firstname = '';
$lastname = '';
}
$street = tep_output_string_protected($address['street_address']);
$suburb = tep_output_string_protected($address['suburb']);
$city = tep_output_string_protected($address['city']);
// -> VD: suppression de la région
// $state = tep_output_string_protected($address['state']);
// <- VD
if (isset($address['country_id']) && tep_not_null($address['country_id'])) {
$country = tep_get_country_name($address['country_id']);
if (isset($address['zone_id']) && tep_not_null($address['zone_id'])) {
// -> VD: suppression de la région
// $state = tep_get_zone_code($address['country_id'], $address['zone_id'], $state);
// <- VD
}
} elseif (isset($address['country']) && tep_not_null($address['country'])) {
// -> VD: correction bug pays tronqué dans la facture utilisateur
$country = tep_output_string_protected($address['country']);
// <- VD
} else {
$country = '';
}
$postcode = tep_output_string_protected($address['postcode']);
$zip = $postcode;
if ($html) {
// HTML Mode
$HR = '
';
$hr = '
';
if ( ($boln == '') && ($eoln == "\n") ) { // Values not specified, use rational defaults
$CR = '
';
$cr = '
';
$eoln = $cr;
} else { // Use values supplied
$CR = $eoln . $boln;
$cr = $CR;
}
} else {
// Text Mode
$CR = $eoln;
$cr = $CR;
$HR = '----------------------------------------';
$hr = '----------------------------------------';
}
$statecomma = '';
$streets = $street;
// -> VDVOISIN: gestion des voisins
if ($suburb != '') $streets = $street . $cr . "(Voisin : " . $suburb . ")";
// <- VDVOISIN
if ($state != '') $statecomma = $state . ', ';
$fmt = $address_format['format'];
eval("\$address = \"$fmt\";");
// -> TVAINT
if (ACCOUNT_COMPANY == 'true') {
if (tep_not_null($company)) {
$address = $company . $cr . $address;
}
if (tep_not_null($tva_intracom)) {
$address = $address . $cr . ENTRY_TVA_INTRACOM . $cr . $tva_intracom;
}
}
// <- TVAINT
return $address;
}
////
// Return a formatted address
// TABLES: customers, address_book
function tep_address_label($customers_id, $address_id = 1, $html = false, $boln = '', $eoln = "\n") {
// -> TVAINT
$address_query = tep_db_query("select entry_firstname as firstname, entry_lastname as lastname, entry_company as company, entry_tva_intracom as tva_intracom, 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 . "'");
// <- TVAINT
$address = tep_db_fetch_array($address_query);
$format_id = tep_get_address_format_id($address['country_id']);
return tep_address_format($format_id, $address, $html, $boln, $eoln);
}
function tep_row_number_format($number) {
if ( ($number < 10) && (substr($number, 0, 1) != '0') ) $number = '0' . $number;
return $number;
}
function tep_get_categories($categories_array = '', $parent_id = '0', $indent = '') {
global $languages_id;
if (!is_array($categories_array)) $categories_array = array();
$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");
while ($categories = tep_db_fetch_array($categories_query)) {
$categories_array[] = array('id' => $categories['categories_id'],
'text' => $indent . $categories['categories_name']);
if ($categories['categories_id'] != $parent_id) {
$categories_array = tep_get_categories($categories_array, $categories['categories_id'], $indent . ' ');
}
}
return $categories_array;
}
function tep_get_manufacturers($manufacturers_array = '') {
if (!is_array($manufacturers_array)) $manufacturers_array = array();
$manufacturers_query = tep_db_query("select manufacturers_id, manufacturers_name from " . TABLE_MANUFACTURERS . " order by manufacturers_name");
while ($manufacturers = tep_db_fetch_array($manufacturers_query)) {
$manufacturers_array[] = array('id' => $manufacturers['manufacturers_id'], 'text' => $manufacturers['manufacturers_name']);
}
return $manufacturers_array;
}
////
// Return all subcategory IDs
// TABLES: categories
function tep_get_subcategories(&$subcategories_array, $parent_id = 0) {
$subcategories_query = tep_db_query("select categories_id from " . TABLE_CATEGORIES . " where parent_id = '" . (int)$parent_id . "'");
while ($subcategories = tep_db_fetch_array($subcategories_query)) {
$subcategories_array[sizeof($subcategories_array)] = $subcategories['categories_id'];
if ($subcategories['categories_id'] != $parent_id) {
tep_get_subcategories($subcategories_array, $subcategories['categories_id']);
}
}
}
// 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
function tep_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 utf8_encode(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 tep_date_short($raw_date) {
if ( ($raw_date == '0000-00-00 00:00:00') || empty($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)));
}
}
////
// Parse search string into indivual objects
function tep_parse_search_string($search_str = '', &$objects) {
$search_str = trim(strtolower($search_str));
// Break up $search_str on whitespace; quoted string will be reconstructed later
$pieces = split('[[:space:]]+', $search_str);
$objects = array();
$tmpstring = '';
$flag = '';
for ($k=0; $k 1) {
$pieces[$k] = substr($pieces[$k], 1);
} else {
$pieces[$k] = '';
}
}
$post_objects = array();
while (substr($pieces[$k], -1) == ')') {
$post_objects[] = ')';
if (strlen($pieces[$k]) > 1) {
$pieces[$k] = substr($pieces[$k], 0, -1);
} else {
$pieces[$k] = '';
}
}
// Check individual words
if ( (substr($pieces[$k], -1) != '"') && (substr($pieces[$k], 0, 1) != '"') ) {
$objects[] = trim($pieces[$k]);
for ($j=0; $j 1) {
$pieces[$k] = substr($pieces[$k], 0, -1);
} else {
$pieces[$k] = '';
}
}
// If the word doesn't end in double quotes, append it to the $tmpstring.
if (substr($pieces[$k], -1) != '"') {
// Tack this word onto the current string entity
$tmpstring .= ' ' . $pieces[$k];
// Move on to the next word
$k++;
continue;
} else {
/* If the $piece ends in double quotes, strip the double quotes, tack the
$piece onto the tail of the string, push the $tmpstring onto the $haves,
kill the $tmpstring, turn the $flag "off", and return.
*/
$tmpstring .= ' ' . trim(ereg_replace('"', ' ', $pieces[$k]));
// Push the $tmpstring onto the array of stuff to search for
$objects[] = trim($tmpstring);
for ($j=0; $j 12 || $month < 1) {
return false;
}
if ($day < 1) {
return false;
}
if (tep_is_leap_year($year)) {
$no_of_days[1] = 29;
}
if ($day > $no_of_days[$month - 1]) {
return false;
}
$date_array = array($year, $month, $day);
return true;
}
////
// Check if year is a leap year
function tep_is_leap_year($year) {
if ($year % 100 == 0) {
if ($year % 400 == 0) return true;
} else {
if (($year % 4) == 0) return true;
}
return false;
}
////
// Return table heading with sorting capabilities
function tep_create_sort_heading($sortby, $colnum, $heading) {
global $PHP_SELF;
$sort_prefix = '';
$sort_suffix = '';
if ($sortby) {
$sort_prefix = '' ;
$sort_suffix = (substr($sortby, 0, 1) == $colnum ? (substr($sortby, 1, 1) == 'a' ? '+' : '-') : '') . '';
}
return $sort_prefix . $heading . $sort_suffix;
}
////
// Recursively go through the categories and retreive all parent categories IDs
// TABLES: categories
function tep_get_parent_categories(&$categories, $categories_id) {
$parent_categories_query = tep_db_query("select parent_id from " . TABLE_CATEGORIES . " where categories_id = '" . (int)$categories_id . "'");
while ($parent_categories = tep_db_fetch_array($parent_categories_query)) {
if ($parent_categories['parent_id'] == 0) return true;
$categories[sizeof($categories)] = $parent_categories['parent_id'];
if ($parent_categories['parent_id'] != $categories_id) {
tep_get_parent_categories($categories, $parent_categories['parent_id']);
}
}
}
////
// Construct a category path to the product
// TABLES: products_to_categories
function tep_get_product_path($products_id) {
$cPath = '';
$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");
if (tep_db_num_rows($category_query)) {
$category = tep_db_fetch_array($category_query);
$categories = array();
tep_get_parent_categories($categories, $category['categories_id']);
$categories = array_reverse($categories);
$cPath = implode('_', $categories);
if (tep_not_null($cPath)) $cPath .= '_';
$cPath .= $category['categories_id'];
}
return $cPath;
}
////
// Return a product ID with attributes
function tep_get_uprid($prid, $params) {
if (is_numeric($prid)) {
$uprid = $prid;
if (is_array($params) && (sizeof($params) > 0)) {
$attributes_check = true;
$attributes_ids = '';
reset($params);
while (list($option, $value) = each($params)) {
if (is_numeric($option) && is_numeric($value)) {
$attributes_ids .= '{' . (int)$option . '}' . (int)$value;
} else {
$attributes_check = false;
break;
}
}
if ($attributes_check == true) {
$uprid .= $attributes_ids;
}
}
} else {
$uprid = tep_get_prid($prid);
if (is_numeric($uprid)) {
if (strpos($prid, '{') !== false) {
$attributes_check = true;
$attributes_ids = '';
// strpos()+1 to remove up to and including the first { which would create an empty array element in explode()
$attributes = explode('{', substr($prid, strpos($prid, '{')+1));
for ($i=0, $n=sizeof($attributes); $i<$n; $i++) {
$pair = explode('}', $attributes[$i]);
if (is_numeric($pair[0]) && is_numeric($pair[1])) {
$attributes_ids .= '{' . (int)$pair[0] . '}' . (int)$pair[1];
} else {
$attributes_check = false;
break;
}
}
if ($attributes_check == true) {
$uprid .= $attributes_ids;
}
}
} else {
return false;
}
}
return $uprid;
}
////
// Return a product ID from a product ID with attributes
function tep_get_prid($uprid) {
$pieces = explode('{', $uprid);
if (is_numeric($pieces[0])) {
return $pieces[0];
} else {
return false;
}
}
////
// Return a customer greeting
function tep_customer_greeting() {
global $customer_id, $customer_first_name;
if (tep_session_is_registered('customer_first_name') && tep_session_is_registered('customer_id')) {
$greeting_string = sprintf(TEXT_GREETING_PERSONAL, tep_output_string_protected($customer_first_name), tep_href_link(FILENAME_PRODUCTS_NEW));
} else {
$greeting_string = sprintf(TEXT_GREETING_GUEST, tep_href_link(FILENAME_LOGIN, '', 'SSL'), tep_href_link(FILENAME_CREATE_ACCOUNT, '', 'SSL'));
}
return $greeting_string;
}
////
//! Send email (text/html) using MIME
// This is the central mail function. The SMTP Server should be configured
// correct in php.ini
// Parameters:
// $to_name The name of the recipient, e.g. "Jan Wildeboer"
// $to_email_address The eMail address of the recipient,
// e.g. jan.wildeboer@gmx.de
// $email_subject The subject of the eMail
// $email_text The text of the eMail, may contain HTML entities
// $from_email_name The name of the sender, e.g. Shop Administration
// $from_email_adress The eMail address of the sender,
// e.g. info@mytepshop.com
function tep_mail($to_name, $to_email_address, $email_subject, $email_text, $from_email_name, $from_email_address) {
/*
************************************************************************
[SI-LINDER-PARTNER-2][OSC][MultiTaskDescriptions]:{
- 1/ on procède à une modification de cette fonction afin de supprimer tout (ou au moins une grande partie de) les problèmes d'accents avec les envois de mails,
- 2/ déjà on créé une variable de type tableau associatif qui contiendra différents index
les index BAD seront utilisés comme ce qui est mal corrigé en accents (chercher)
les index CORRECT seront utilisés comme ce qui est bien corrigé en accents (remplacer)
ce tableau sera uniquement utilisé pour fixer quelques problèmes vraiment spécifiques (plutôt que de casser la routine globale de réparation des accents, on rusera pour ces cas-ci)
MODULE_PAYMENT_DEVIS_TEXT_* = tout ces textes sont censés fixer les problèmes émanant du type de paiement par devis par France Métropolitaine: includes/languages/french/modules/payment/devis.php
- 3/ ici on se charge de réparer les problèmes d'accents situés dans le corps de texte,
on garde l'ancien code en référence seulement et si cela tient au-bout de 3 semaines, on pourra êtres en mesure de s'en séparer!
- 4/ finalement là on va fixer des problèmes qui sont situés dans des cas bien spécifiques
et pour ce faire, on va se servir du tableau défini en [2]
- 5/ ici on se charge de réparer les problèmes d'accents situés dans le sujet de texte,
on garde l'ancien code en référence seulement et si cela tient au-bout de 3 semaines, on pourra êtres en mesure de s'en séparer!
- 6/ il s'agit d'un test de debug, entres commentaires
}
*/
// ([1])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::BEGIN
if (SEND_EMAILS != 'true') return false;
// Instantiate a new mail object
$message = new email(array('X-Mailer: osCommerce Mailer'));
// Build the text version
// -> VDMAILTXT
// ([2])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::BEGIN
$badAccentuedStringsReferencers = array(
'MONTH_TEXT_FEVRIER_BAD' => 'f?vrier',
'MONTH_TEXT_AOUT_BAD' => 'ao?t',
'MONTH_TEXT_DECEMBRE_BAD' => 'd?cembre',
'GENERIC_TEXT_RECONTACT_BAD' => 'recontacté',
'MODULE_PAYMENT_DEVIS_TEXT_TITLE_BAD' => 'Devis hors France M�tropolitaine',
'MODULE_PAYMENT_DEVIS_TEXT_MAIL_DESCRIPTION_BAD' => 'Comme indiqu? dans nos conditions g?n?rales de vente, les ventes vers les DOMTOMS et ? l\'export sont soumises ? des frais de transport suppl?mentaires.
Nous allons peser votre colis afin de d?terminer ces frais (selon le tarif de la poste).
Nous vous communiquerons ensuite le montant total de votre devis.',
'MONTH_TEXT_FEVRIER_CORRECT' => utf8_decode('février'),
'MONTH_TEXT_AOUT_CORRECT' => utf8_decode('août'),
'MONTH_TEXT_DECEMBRE_CORRECT' => utf8_decode('décembre'),
'GENERIC_TEXT_RECONTACT_CORRECT' => utf8_decode('recontacté'),
'MODULE_PAYMENT_DEVIS_TEXT_TITLE_CORRECT' => utf8_decode('Devis hors France M�tropolitaine'),
'MODULE_PAYMENT_DEVIS_TEXT_MAIL_DESCRIPTION_CORRECT' => utf8_decode('Comme indiqué dans nos conditions générales de vente, les ventes vers les DOMTOMS et à l\'export sont soumises à des frais de transport supplémentaires.
Nous allons peser votre colis afin de déterminer ces frais (selon le tarif de la poste).
Nous vous communiquerons ensuite le montant total de votre devis.'),
);
// ([2])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::END
// ([3])-->BEGIN[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::END
$text = html_entity_decode(strip_tags(utf8_decode($email_text)));//$text = html_entity_decode(strip_tags($email_text));
// ([4])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::BEGIN
$text = str_replace(
array(
$badAccentuedStringsReferencers['MONTH_TEXT_FEVRIER_BAD'],
$badAccentuedStringsReferencers['MONTH_TEXT_AOUT_BAD'],
$badAccentuedStringsReferencers['MONTH_TEXT_DECEMBRE_BAD'],
$badAccentuedStringsReferencers['GENERIC_TEXT_RECONTACT_BAD'],
$badAccentuedStringsReferencers['MODULE_PAYMENT_DEVIS_TEXT_TITLE_BAD'],
$badAccentuedStringsReferencers['MODULE_PAYMENT_DEVIS_TEXT_MAIL_DESCRIPTION_BAD'],
),
array(
$badAccentuedStringsReferencers['MONTH_TEXT_FEVRIER_CORRECT'],
$badAccentuedStringsReferencers['MONTH_TEXT_AOUT_CORRECT'],
$badAccentuedStringsReferencers['MONTH_TEXT_DECEMBRE_CORRECT'],
$badAccentuedStringsReferencers['GENERIC_TEXT_RECONTACT_CORRECT'],
$badAccentuedStringsReferencers['MODULE_PAYMENT_DEVIS_TEXT_TITLE_CORRECT'],
$badAccentuedStringsReferencers['MODULE_PAYMENT_DEVIS_TEXT_MAIL_DESCRIPTION_CORRECT'],
),
$text
);
// ([4])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::END
// <- VDMAILTXT
if (EMAIL_USE_HTML == 'true') {
$message->add_html($email_text, $text);
} else {
$message->add_text($text);
}
// Send message
$message->build_message();
// ([6])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::BEGIN
//echo '';
//die('STOP_MAIL');
// ([6])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::END
// ([5])-->BEGIN[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::END
$message->send($to_name, $to_email_address, $from_email_name, $from_email_address, utf8_decode($email_subject));//$message->send($to_name, $to_email_address, $from_email_name, $from_email_address, $email_subject);
// ([1])-->[SI-LINDER-PARTNER-2][OSC][SubTaskDescription]::END
/*
[SI-LINDER-PARTNER-2][OSC][MultiTaskDescriptions]
************************************************************************
*/
}
////
// Check if product has attributes
function tep_has_product_attributes($products_id) {
$attributes_query = tep_db_query("select count(*) as count from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$products_id . "'");
$attributes = tep_db_fetch_array($attributes_query);
if ($attributes['count'] > 0) {
return true;
} else {
return false;
}
}
////
// Get the number of times a word/character is present in a string
function tep_word_count($string, $needle) {
$temp_array = split($needle, $string);
return sizeof($temp_array);
}
function tep_count_modules($modules = '') {
$count = 0;
if (empty($modules)) return $count;
$modules_array = split(';', $modules);
for ($i=0, $n=sizeof($modules_array); $i<$n; $i++) {
$class = substr($modules_array[$i], 0, strrpos($modules_array[$i], '.'));
if (is_object($GLOBALS[$class])) {
if ($GLOBALS[$class]->enabled) {
$count++;
}
}
}
return $count;
}
function tep_count_payment_modules() {
return tep_count_modules(MODULE_PAYMENT_INSTALLED);
}
function tep_count_shipping_modules() {
return tep_count_modules(MODULE_SHIPPING_INSTALLED);
}
function tep_create_random_value($length, $type = 'mixed') {
if ( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits')) return false;
$rand_value = '';
while (strlen($rand_value) < $length) {
if ($type == 'digits') {
$char = tep_rand(0,9);
} else {
$char = chr(tep_rand(0,255));
}
if ($type == 'mixed') {
if (eregi('^[a-z0-9]$', $char)) $rand_value .= $char;
} elseif ($type == 'chars') {
if (eregi('^[a-z]$', $char)) $rand_value .= $char;
} elseif ($type == 'digits') {
if (ereg('^[0-9]$', $char)) $rand_value .= $char;
}
}
return $rand_value;
}
function tep_array_to_string($array, $exclude = '', $equals = '=', $separator = '&') {
if (!is_array($exclude)) $exclude = array();
$get_string = '';
if (sizeof($array) > 0) {
while (list($key, $value) = each($array)) {
if ( (!in_array($key, $exclude)) && ($key != 'x') && ($key != 'y') ) {
$get_string .= $key . $equals . $value . $separator;
}
}
$remove_chars = strlen($separator);
$get_string = substr($get_string, 0, -$remove_chars);
}
return $get_string;
}
function tep_not_null($value) {
if (is_array($value)) {
if (sizeof($value) > 0) {
return true;
} else {
return false;
}
} else {
if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
return true;
} else {
return false;
}
}
}
////
// Output the tax percentage with optional padded decimals
function tep_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;
}
////
// Checks to see if the currency code exists as a currency
// TABLES: currencies
function tep_currency_exists($code) {
$code = tep_db_prepare_input($code);
$currency_code = tep_db_query("select currencies_id from " . TABLE_CURRENCIES . " where code = '" . tep_db_input($code) . "'");
if (tep_db_num_rows($currency_code)) {
return $code;
} else {
return false;
}
}
function tep_string_to_int($string) {
return (int)$string;
}
////
// Parse and secure the cPath parameter values
function tep_parse_category_path($cPath) {
// make sure the category IDs are integers
$cPath_array = array_map('tep_string_to_int', explode('_', $cPath));
// make sure no duplicate category IDs exist which could lock the server in a loop
$tmp_array = array();
$n = sizeof($cPath_array);
for ($i=0; $i<$n; $i++) {
if (!in_array($cPath_array[$i], $tmp_array)) {
$tmp_array[] = $cPath_array[$i];
}
}
return $tmp_array;
}
////
// Return a random value
function tep_rand($min = null, $max = null) {
static $seeded;
if (!isset($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();
}
}
function tep_setcookie($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = 0) {
setcookie($name, $value, $expire, $path, (tep_not_null($domain) ? $domain : ''), $secure);
}
function tep_get_ip_address() {
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
} else {
$ip = getenv('REMOTE_ADDR');
}
}
return $ip;
}
function tep_count_customer_orders($id = '', $check_session = true) {
global $customer_id;
if (is_numeric($id) == false) {
if (tep_session_is_registered('customer_id')) {
$id = $customer_id;
} else {
return 0;
}
}
if ($check_session == true) {
if ( (tep_session_is_registered('customer_id') == false) || ($id != $customer_id) ) {
return 0;
}
}
$orders_check_query = tep_db_query("select count(*) as total from " . TABLE_ORDERS . " where customers_id = '" . (int)$id . "'");
$orders_check = tep_db_fetch_array($orders_check_query);
return $orders_check['total'];
}
function tep_count_customer_address_book_entries($id = '', $check_session = true) {
global $customer_id;
if (is_numeric($id) == false) {
if (tep_session_is_registered('customer_id')) {
$id = $customer_id;
} else {
return 0;
}
}
if ($check_session == true) {
if ( (tep_session_is_registered('customer_id') == false) || ($id != $customer_id) ) {
return 0;
}
}
$addresses_query = tep_db_query("select count(*) as total from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$id . "'");
$addresses = tep_db_fetch_array($addresses_query);
return $addresses['total'];
}
// nl2br() prior PHP 4.2.0 did not convert linefeeds on all OSs (it only converted \n)
function tep_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);
}
}
// -> PDF209
function tep_get_languages_directory($code) {
global $languages_id;
$language_query = tep_db_query("select languages_id, directory from " . TABLE_LANGUAGES . " where code = '" . tep_db_input($code) . "'");
if (tep_db_num_rows($language_query)) {
$language = tep_db_fetch_array($language_query);
$languages_id = $language['languages_id'];
return $language['directory'];
} else {
return false;
}
}
function tep_get_languages() {
$languages_query = tep_db_query("select languages_id, name, code, image, directory from " . TABLE_LANGUAGES . " order by sort_order");
while ($languages = tep_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;
}
// <- PDF209
// -> OSCTHUMB112
////
// START oscThumb
function tep_cfg_readonly($value){
$single[]= array('id' => $value,
'text' => $value);
return tep_draw_pull_down_menu('configuration_value', $single, $value);
}
function tep_cfg_pull_down_installed_fonts($font_name) {
if ($root=@opendir(DIR_FS_DOCUMENT_ROOT.'phpThumb/fonts')){
while ($file=readdir($root)){
if($file=="." || $file==".." || is_dir($dir."/".$file)) continue;
$files[]= array('id' => $file,
'text' => $file);
}
}
return tep_draw_pull_down_menu('configuration_value', $files, $font_name);
}
function tep_cfg_pull_down_installed_watermarks($watermark_name) {
if ($root=@opendir(DIR_FS_DOCUMENT_ROOT.'phpThumb/watermarks')){
while ($file=readdir($root)){
if($file=="." || $file==".." || is_dir($dir."/".$file)) continue;
$files[]= array('id' => $file,
'text' => $file);
}
}
return tep_draw_pull_down_menu('configuration_value', $files, $watermark_name);
}
function tep_cfg_pull_down_watermark_alignment($watermark_alignment) {
$align[]= array('id' => '*',
'text' => 'Tiled');
$align[]= array('id' => 'T',
'text' => 'Top');
$align[]= array('id' => 'TL',
'text' => 'Top Left');
$align[]= array('id' => 'TR',
'text' => 'Top Right');
$align[]= array('id' => 'C',
'text' => 'Center');
$align[]= array('id' => 'B',
'text' => 'Bottom');
$align[]= array('id' => 'BL',
'text' => 'Bottom Left');
$align[]= array('id' => 'BR',
'text' => 'Bottom Right');
return tep_draw_pull_down_menu('configuration_value', $align, $watermark_alignment);
}
// END oscThumb
// <- OSCTHUMB112
// -> 0000013: ajustement quantité affichée selon fournisseur
// il arrive que certains fournisseurs ont des délais de livraison tellement court qu'on peut considérer
// que leurs produits sont disponibles jusqu'à une certaine quantité
function find_qty_by_manufacturer($id, $qty, $neg_is_zero=true) {
$ret = $qty;
// pour l'instant l'ajustement est défini dans le code ci dessous,
// on pourrait ajouter un champ 'ajust_products_quantity' dans la table manufacturers
// <- OSC-76 : annulation de l'ajustement des quantités disponibles
// if ( $id == '12' ) { $ret += 200; } // 12=rainbow
// -> OSC-76 : annulation de l'ajustement des quantités disponibles
if ( $ret < 0 and $neg_is_zero ) { $ret = 0; }
return $ret;
// <- 0000013
}
// <- OSC-77 :
// certains fournisseurs ont des délais de livraison plus ou moins
function find_delivery_time_by_manufacturer($id) {
// pour l'instant l'ajustement est défini dans le code ci dessous,
if ( $id == '12' ) { return 2; } // 12=rainbow
return 10;
}
// -> OSC-77 :
// -> OSC-45: Modification de l'intitulé du message préventif de Date D'évènement obligatoire (du à la non-compréhension de certains clients)
// système d'infobulle
// basé sur le travail réalisé dans la tâche OSC-29 par Vincent Detzel.
// copié/collé pur.
// ajout du signet fictif #infos.
// la classe css utilisée n'est plus "infobulle" mais "dov_infobulle" (date of event).
// nom de fonction modifiée.
function tep_get_date_ofevent_infobulle($keyword, $text) {
return "$keyword$text"; // cf include/stylesheet.css
}
// <- OSC-45: Modification de l'intitulé du message préventif de Date D'évènement obligatoire (du à la non-compréhension de certains clients)
// <- OSC-78: Gestion de catégories réservées aux professionnels
//
// fonction afin de vérifier si un client est doté de l'accès professionnels ou non.
// Ainsi, si on doit modifier cette routine il sera plus facile de modifier cette fonction universelle que des vingtaines de fichiers séparés..
// idée: réutilisation (ça serait joli) de l'image autrefois servant de bouton bascule au double affichage des prix HT/TTC, (OSC-48).
// Selon l'accès de la personne:
// image particulier -> client particulier
// image professionnel -> client professionnel
// A voir ?
function is_pro_customer_by_id($customer_id) {
// On effectue une requête dans la base de données pour vérifier si le champs customers_group_id est égal à 1 ou 0.
$tmp_sql_request = tep_db_query("select customers_group_id from " . TABLE_CUSTOMERS . " where customers_id = '" . tep_db_input($customer_id) . "'");
$tmp_what_is = tep_db_fetch_array($tmp_sql_request);
// Vérification de l'accès:
switch ($tmp_what_is['customers_group_id'])
{
// Par défaut ou si $osc_78_what_is['customers_group_id'] == 0
default:
case 0:
// accès particulier..
return (false);
break;
// Si $osc_78_what_is['customers_group_id'] == 1
case 1:
// accès professionnels..
return (true);
break;
}
}
// fonction qui va tester si l'utilisateur est professionnel ou non (ce, sans contacter la base de données (économie de requêtes SQL))
// Attends en paramètre l'ID du client ($customer_id)
// -> OSC-94 - Prix par palier reservé aux professionnels
function is_pro_customer($customer_id_par=NULL) {
// je suis non identifié/visiteur, donc forcément un utilisateur anonyme.
// Ainsi, je ne suis donc pas un professionnel (fatalement..)
if ( CATPRO_FOR_ALL == 'true' ) return(true);
if (!tep_session_is_registered('customer_id'))
{
// le client n'est pas identifié ou est un bot ou est un visiteur, bref, on retourne false!
return (false);
} else {
// sinon je dois tester via is_pro_customer_by_id() déclarée juste en haut.
global $customer_id;
if ( is_null($customer_id_par) ) $customer_id_par = $customer_id;
return is_pro_customer_by_id($customer_id_par);
}
}
// <- OSC-94 - Prix par palier reservé aux professionnels
//
// fonction afin d'analyser si une catégorie est reservée aux pro ou non
function is_category_for_pro($category_id) {
// Vérification de la méthode d'analyse
switch (CATPRO_METHOD)
{
// Méthode constant:
// Ce mode se servira de la configuration dans la table "configuration" de la clef de configuration: CATPRO_CAT_IDS
// Son id est le configuration_id: 9364
// si $category_id est trouvé parmis les ids stockés dans la constante CATPRO_CAT_IDS
// (via l'expréssion régulière) alors, la fonction renverra true, sinon false
case 'constant':
if ( in_array($category_id, explode(',', CATPRO_CAT_IDS)) ) {
// la catégorie est pour les pros
return (true);
} else {
// la catégorie n'est pas pour les pros
return (false);
}
break;
}
}
// fonction afin de vérifier si un produit est dans une catégorie reservée aux pro ou pas!
// -- à certains endroits de OSCommerce la variable $category_id ou $cPath est inexistante..
// -- seul réside dans l'url l'id du produit, et donc, afin de trouver si LE produit en vue est dans une catégorie PRO..
// -- il faut alors ruser en recherchant l'id de catégorie dans lequel est inscrit le produit!
function is_product_in_pro_category($product_id) {
// Effectues une sélection de la catégorie (categories_id) du (product_id) dans la table products_to_categories.
$tmp_sql_request = tep_db_query("select categories_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . tep_db_input($product_id) . "'");
$tmp_which_category_is = tep_db_fetch_array($tmp_sql_request);
//
// Une fois la catégorie du produit trouvée..
// On va vérifier si la catégorie est une catégorie PRO ou non.
// Pour cela, on retourne seulement le résultat de notre autre fonction is_category_for_pro() avec comme paramètre l'id de catégorie retourné par MySQL.
//
return (is_category_for_pro($tmp_which_category_is['categories_id']));
}
//
// fonction afin de filtrer en temps réél la requête SQL contactant la table products_to_categories
//
// Elle retournera la clause sql WHERE qui permettra de filtrer les produits qui ne sont pas notifiés comme étant pro
// Un exemple très clair ci-dessous:
//
// pour les catégories pro : 12,13,14
//
// on appelle la fonction avec en paramètres:
// $pc2_table = "p2c."
// $operator_if_not_null = "AND"
// $customer_id = l'ID du client.. (exemple: 25 ou '' (si non-identifié)).
// la fonction retournera la chaîne suivante :
// "AND ( p2c.categories_id != 12 AND p2c.categories_id != 13 AND p2c.categories_id != 14 )"
//
function find_pro_cat_sql_filter($p2c_table, $operator_if_not_null, $customer_id) {
// Vérification de la méthode d'analyse
// (définie dans une constante php CATPRO_METHOD juste en haut de ce fichier).
switch (CATPRO_METHOD) {
default:
case 'constant':
// aucun filtre n'est appliqué quand on est un pro, la fonction is_pro_customer() vérifiera ça.
if ( is_pro_customer($customer_id) ) return "";
$sql = "";
// Liste des catégories réservées aux pro, dans une constante chaine "X,Y,Z,...": (ex: 12,13,14,8367,6365)
// CATPRO_CAT_IDS est une constante PHP créée par OSCommerce (qui lui, la trouve dans la base de données, dans la table 'configuration', configuration_id: 9364)
$arrayCategoriesForPro = explode(',', CATPRO_CAT_IDS);
foreach ( $arrayCategoriesForPro as $cat_id ) {
if ( $sql != "" ) $sql .= " AND ";
$sql .= $p2c_table . "categories_id != '" . $cat_id . "'";
}
// on doit grouper/lier les contraintes entre elles par des "(" ")"
// et surtout pas par des '(' ')' sinon il y aurait une erreur de syntaxe SQL
return $operator_if_not_null . " (" . $sql . ")";
}
}
// fonction qui va simplement retourner la balise html de redirection pour la zone professionnelle
function get_cat_pro_html_redirect() {
echo '';
}
// <- OSC-78: Gestion de catégories réservées aux professionnels
////
// AP URL Rewriting
function tep_url_rewriting_cast($str) {
$tmp = strtr($str, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$tmp = preg_replace('/([^a-z0-9]+)/i', '-', $tmp);
$tmp = strtolower($tmp);
return $tmp;
}
function tep_get_categories_name($category_id, $language = '') {
global $languages_id;
if (empty($language)) $language = $languages_id;
$category_query = tep_db_query("select categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " where categories_id = '" . (int)$category_id . "' and language_id = '" . (int)$language . "'");
$category = tep_db_fetch_array($category_query);
return $category['categories_name'];
}
function tep_get_manufacturers_name($manufacturer_id) {
$manufacturer_query = tep_db_query("select manufacturers_name from " . TABLE_MANUFACTURERS . " where manufacturers_id = '" . (int)$manufacturer_id . "'");
$manufacturer = tep_db_fetch_array($manufacturer_query);
return $manufacturer['manufacturers_name'];
}
// AP URL Rewriting
////
?>