/DEV/LIB/common.functions.php
PHP | 7552 lines | 4863 code | 1106 blank | 1583 comment | 1286 complexity | 3fb67c2dde3df8b70cd34cfe9e5886d9 MD5 | raw file
- <?php
- $test = include('/data/apache/CONF_URL/conf.php');
- if (!$test)
- require('/data/apache/CONF_URL/prod.conf.php');
- //bandeaux personnalisables
- //include(realpath(dirname(__FILE__) . "/../DATA/bandeaux/libelles_bandeaux.php"));
- global $_global;
- //##############################################################################
- //# Définition des constantes fonctionnelles
- // Répertoire dans lequel les fichiers generes par les scripts des crons sont enregistres
- define('URL_DATA', '/data/apache/DATA/');
- // Appel depuis un script => Pas de DOCUMENT_ROOT !!!
- //$display = rtrim($_SERVER['DOCUMENT_ROOT'],'/');
- $display = realpath(dirname(__FILE__) . '/../DISPLAY');
- $root = dirname($display);
- // Gérer les document root de Orange (et autres), qui ont DISPLAY
- // directement à la racine !!
- if (substr($root, -4) == '/DEV')
- $root = dirname($root);
- define('ROOT_PATH', $root); // ex: /data/apache/www/www.logic-immo.com
- define('DISPLAY_PATH', $display); // ex: /data/apache/www/www.logic-immo.com/DEV/DISPLAY
- // Répertoire dans lequel les librairies (fonctions, classes) sont enregistrees
- $current_lib_dir = dirname(__FILE__);
- // PB : Si la constante a déjà été définie dans une autre page !!
- if (defined('URL_LIB')) {
- // Simuler une erreur fatale pour qu'on recoive un mail en cas de problème
- error_log("FATAL ERROR - La constante URL_LIB a deja ete definie ! (VALEUR:" . URL_LIB . ")");
- // Enregistrer le backtrace dans le fichier de log
- ob_start() or exit();
- debug_print_backtrace();
- $content = ob_get_contents();
- error_log($content);
- ob_end_clean();
- } else {
- define('URL_LIB', $current_lib_dir); // ex: /data/apache/www/www.logic-immo.com/DEV/LIB
- }
- //##############################################################################
- //# Chargement de la configuration par environnement
- // Récupérer le chemin du fichier de conf
- $conf_file = ROOT_PATH . '/CONF/conf.php';
- $test = include($conf_file);
- // Gestion en cas de configuration introuvable
- if (!$test) {
- // Utiliser la configuration de production
- $test = include(ROOT_PATH . '/CONF/prodA.conf.php');
- if (!$test) {
- // Simuler une erreur fatale pour qu'on recoive un mail en cas de problème
- error_log("FATAL ERROR - Le fichier de configuration `{$conf_file}` n\'a pas ete trouve. (DOCUMENT_ROOT:{$_SERVER['DOCUMENT_ROOT']})");
- // Enregistrer le backtrace dans le fichier de log
- ob_start() or exit();
- debug_print_backtrace();
- $content = ob_get_contents();
- error_log($content);
- ob_end_clean();
- // Ne pas plus faire de traitement avec des constantes manquantes !
- exit();
- }
- }
- //##############################################################################
- //# Inclure les librairies relatives à MMF
- include_once(URL_LIB . '/mmf.constants.php');
- include_once(URL_LIB . '/mmf.functions.php');
- //##############################################################################
- //##
- //## direct_hit($ip) -- returns true if url hits a frontal server
- //## add_parameters($url, $site = "", $lang = "", $univers = "") -- returns an url along with the environment parameters
- //## add_parameter($url, $parameter, $value) -- returns an url along with a parameter and value
- //## del_parameter($url, $parameter) -- returns an url without a parameter
- //## get_all_summary_cz($data) -- returns an array of human readable values, translated from search criteria (CZ)
- //## get_all_summary($data,$showIfAllChecked) -- returns an array of human readable values, translated from search criteria
- //## get_adv_summary($data,$extended,$showIfAllChecked) -- return an array of human readable values from advanced criterias
- //## get_summary($data, $parameters, $item, $label_all, $label_unit) -- turns a search criterion to a human readable value
- //## get_property_type_label($id) -- returns property type label depending on the code
- //## n_f($value) -- number_format shortcut
- //## currency_format($value, $from, $to, $add_currency_name = true) -- currency conversion
- //## sosex($input, $partial = false) -- Function so sex, par le so sexy oxman, da crazy man !
- //## str_limit($value, $limit) -- returns a truncated string
- //## remove_returns($value) -- returns a clean string
- //## resize_image($img, $max_width, $max_height) -- returns html height and width properties, determining the size of an image to fit required width and height
- //## spacer($height, $width) -- returns html code for a spacer
- //## set_html_title($value) -- returns html alt and title
- //##
- //## get_ad_data($page, $value, $has_premium = 0, $url = "", $idx = -1) -- returns ad and agency data
- //## get_ag_data($page, $value) -- returns agency data
- //## get_pub_data($value, $key) -- returns pub data
- //## get_mmf_type($label) -- returns mmf type index
- //##
- //## format_phone($value, $country = "FR") -- returns formatted number
- //## get_parameter_index($name, $value) -- returns parameter index
- //## is_guid($value) -- returns true if value is a guid
- //## back_to_list($page) -- returns "back to list" url
- //## build_search_url($page, $parameters) -- returns a search url
- //## from_page($previous_url, $page) -- returns true if page comes from Mars
- //## is_external() -- returns true if is external
- //## is_ref_page($page) -- returns true if is a ref page
- //## get_zip_code($data, $mode) -- returns szip / lzip
- //## writeLockFile($sLockFileName, $sLockFileDescription) --
- //## getLockFile($sLockFileName) --
- //## checkLockFile($sLockFileName) -- xx
- //## removeLockFile($sLockFileName) --
- //## truncate($chaine, $length = 50) -- Tronque un texte (mais pas les mots !) si trop long et rajoute des points de suspension
- //## loc2xiti($k1,$n1,$k2,$n2) --
- //## format_footer_link($str) --
- //## generateMd5MaintenanceString($iOperationCode, $sPreSharedKey) --
- //## checkSha1MaintenanceString($sPreSharedKey, $iOperationCode, $aOperationArray, $sKeyString) --
- //## redirection($url) -- Gere la presence des headers
- //## verif_cookie_prehome -- Gestion de la revisite Belge (modifiable pour les autres Pays)
- //## pub_relais_neuf_cookie($val_relais) -- Verification les nombres de refresh
- //## Verif_Url_BE() -- verifier la syntax de l'URL pour le site BE
- //## Get_Lockey_By_Name_Level($name, $level=1, $site="xx", $lang="xx") -- Retrouve le Loc_key en fonction d'un name et d'un level
- //## Get_Trad_Locname ($lockey, $lang) -- Retrouve la traduction d'un nom de Locname en fonction d'un LCT_ID et d'une Langue
- //## TextNoAccent($string) -- Supprime les accents d'une chaine
- //## => Déprécié : Regarder la fonction prepareToUrl($string)
- //##
- //## check_detail_exist -- Vérifie si il existe des détail spécifique sur une annonce
- //## create_block_nosearch($title)
- //## no_magic_quote() -- pour eviter les injection S-K-UL
- //## uc_strtoupper_fr($chaine) -- Amélioration du strtoupper de PHP pour gérer les accents
- //##
- //## getLocalityLabel($search_parameters,$num) -- Renvoyer la localite selon le level ("tous codes" ...)
- //## stringToHexa($string,$size) -- Convertir la chaine de 0 et 1 en hexa
- //## hexaToString($string,$size) -- Convertir la chaine hexa en 0 et 1
- //##
- //## searchPropertyTypeIdOrig($id_orig,$get_group) -- Récupérer le groupe ou la chaine de 40bits (par défaut)
- //## searchPropertyTypeIdOrigAdv($id_orig,$get_group) -- Récupérer le groupe ou la chaine de 40bits (par défaut)
- //## => Utilise les nouveaux groupes (plus nombreux et quasi unitaires)
- //##
- //##############################################################################
- //
- //
- // 20080820-XI $ad["default_sector"] should not be displayed if $ad["default_town"]==$ad["default_sector"]
- // 20090401-1-XI, Retrieving xxx_locality_2_agency field (mantis 5342)
- // 20090407-1-XI, Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO'
- // 20090410-1-XI, Retrieving xxx_tel2_agency
- // 20090610-1-XI, NOT Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO', mantis 5865
- //
- //##############################################################################
- function open_file(&$filepath, $requestType = '', $mode = 'a', $backupFolder = TRAPPED_WRITE_ERROR) {
- // Enregistrer la statistique dans le csv
- $fp = @fopen($filepath, 'a');
- if ($fp === false) {
- error_log('FATAL ERROR - Could not open file `' . $filepath . '` to save "' . $requestType . '" request !');
- // Utiliser le dossier de secours pour ne pas perdre les demandes
- $filepath = $backupFolder . $requestType . '/' . basename($filepath);
- // Enregistrer la statistique dans le csv
- $fp = @fopen($filepath, 'a');
- if ($fp === false) {
- error_log('FATAL ERROR - Could not open file `' . $filepath . '` to save "' . $requestType . '" request !');
- }
- }
- return $fp;
- }
- /**
- * Returns true if url hits a frontal server
- *
- * @param unknown_type $ip
- * @return unknown
- */
- function direct_hit($ip) {
- global $_prodServers;
- return in_array($ip, $_prodServers);
- }
- /**
- * Returns an url along with the environment parameters
- *
- * @param unknown_type $url
- * @param unknown_type $site
- * @param unknown_type $lang
- * @param unknown_type $univers
- * @return unknown
- */
- function add_parameters($url, $site = "", $lang = "", $univers = "") {
- global $_global;
- // default values
- $site = ($site == "" ? $_global["site"] : $site);
- $lang = ($lang == "" ? $_global["lang"] : $lang);
- $univers = ($univers == "" ? $_global["univers"] : $univers);
- // sets url parameters into an array
- $tmp = explode("?", $url);
- parse_str($tmp[1], $url_parameters);
- // adds site parameter
- if (!array_key_exists("site", $url_parameters)) {
- $add_parameters["site"] = $site;
- } else {
- $url_parameters["site"] = $site;
- }
- // adds universe parameter
- if (!array_key_exists("univers", $url_parameters)) {
- $add_parameters["univers"] = $univers;
- } else {
- $url_parameters["univers"] = $univers;
- }
- // adds language parameter
- if (!array_key_exists("lang", $url_parameters)) {
- $add_parameters["lang"] = $lang;
- } else {
- $url_parameters["lang"] = $lang;
- }
- // merges parameters
- if (is_array($add_parameters)) {
- $url_parameters = array_merge($add_parameters, $url_parameters);
- }
- // concatenates
- $url = $tmp[0] . "?" . http_build_query($url_parameters);
- switch ($_global["site"]) {
- case "be":
- if (strpos($url, "http:") === false) {
- $url = "/" . $lang . "/" . $url;
- $url = str_replace("//", "/", $url);
- }
- break;
- default:
- break;
- }
- // returns
- return $url;
- }
- /**
- * Returns an url along with a parameter and value
- *
- * @param unknown_type $url
- * @param unknown_type $parameter
- * @param unknown_type $value
- * @return unknown
- */
- function add_parameter($url, $parameter, $value) {
- // sets url parameters into an array
- $tmp = explode("?", $url);
- parse_str($tmp[1], $url_parameters);
- if (!array_key_exists($parameter, $url_parameters)) {
- $url_parameters[$parameter] = $value;
- // concatenates
- $url = $tmp[0] . "?" . http_build_query($url_parameters);
- }
- // returns
- return $url;
- }
- /**
- * Returns an url without a parameter
- *
- * @param unknown_type $url
- * @param unknown_type $parameter
- * @return unknown
- */
- function del_parameter($url, $parameter) {
- // sets url parameters into an array
- $tmp = explode("?", $url);
- parse_str($tmp[1], $url_parameters);
- if (array_key_exists($parameter, $url_parameters)) {
- unset($url_parameters[$parameter]);
- // concatenates
- $url = $tmp[0] . "?" . http_build_query($url_parameters);
- }
- // returns
- return $url;
- }
- /**
- * Returns an array of human readable values, translated from search criteria
- *
- * @param Array $data
- * @param Boolean $showIfAllChecked List all values (1,2,...) if all checked ?
- * @param Boolean $useAdvancedGroups Utiliser les groupes de types de bien avancés (plus nombreux)
- * @return unknown
- */
- function get_all_summary($data, $showIfAllChecked = true, $useAdvancedGroups = false) {
- global $_global;
- // summary table
- $summary = array();
- // vacances
- if ($_global["univers"] == 13) {
- // globals
- global $_LI_BEDROOMS;
- global $_LI_PEOPLE;
- // load values
- $parameters = array();
- $parameters["nb_bedrooms"] = $_LI_BEDROOMS;
- $parameters["nb_people"] = $_LI_PEOPLE;
- // univers
- $summary["univers"] = LABEL_COMMON_UNIVERSE_13;
- // localisation
- $summary["loc_name"] = $data["loc_name"];
- // property types
- if ($data["property_type"] == "" || $data["property_type"][0] == -1 || count($data["property_type"]) == 8) {
- $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
- } else {
- for ($i = 0; $i < count($data["property_type"]); $i++) {
- $data["property_type"][$i] = constant("LABEL_COMMON_PROPERTY_" . $data["property_type"][$i]);
- }
- $summary["property_type"] = implode(", ", $data["property_type"]);
- }
- // bedrooms
- $summary["nb_bedrooms"] = get_summary($data, $parameters["nb_bedrooms"], "nb_bedrooms", LABEL_ALL_BEDROOMS, LABEL_COMMON_BEDROOMS_UNIT);
- // people
- $summary["nb_people"] = get_summary($data, $parameters["nb_people"], "nb_people", LABEL_ALL_PEOPLE, LABEL_COMMON_PEOPLE_UNIT);
- } else {
- // globals
- global $_LI_PRICERANGE;
- global $_LI_ADSURFACE;
- global $_LI_ROOMS;
- // load values
- $parameters = array();
- $parameters["area"] = $_LI_ADSURFACE;
- $parameters["price"] = $_LI_PRICERANGE;
- $parameters["nb_rooms"] = $_LI_ROOMS;
- // univers
- if ($data["univers"] == 2) { // location
- $summary["univers"] = LABEL_COMMON_UNIVERSE_2;
- } else if ($data["univers"] == 8) { // colocation
- $summary["univers"] = LABEL_COMMON_UNIVERSE_8;
- } else { // vente
- $summary["univers"] = LABEL_COMMON_UNIVERSE_1;
- }
- $loc_names = array();
- if (isset($data['is_from_cookie'])) {
- for ($i = 1; $i < 4; $i++) {
- if (isset($data['loc_name' . $i]) && ($locname = $data['loc_name' . $i]) != '' && $locname != LABEL_DEFAULT_LOCALITY) {
- $loc_names[] = ucwords2(strtolower($data['loc_name1']));
- }
- $locname = implode(', ', $loc_names);
- }
- } else {
- // localisation
- $loc_name = getLocalityLabel($data, 0);
- if ($loc_name != LABEL_DEFAULT_LOCALITY)
- $loc_names[] = ucwords2(strtolower($loc_name));
- $loc_name = getLocalityLabel($data, 1);
- if ($loc_name != LABEL_DEFAULT_LOCALITY)
- $loc_names[] = ucwords2(strtolower($loc_name));
- $loc_name = getLocalityLabel($data, 2);
- if ($loc_name != LABEL_DEFAULT_LOCALITY)
- $loc_names[] = ucwords2(strtolower($loc_name));
- if ($loc_names == array()) {
- $locname = ucwords2(strtolower($data["loc_name"]));
- // Ajouter manuellement les parentheses autour des codes postaux
- // En veillant à ne pas les doubler si déjà présentes
- $locname = preg_replace('`\(?([0-9]{3,})\)?`', '($1)', $locname);
- }
- else
- $locname = implode(', ', $loc_names);
- // Remplacer les -+_ par un espace
- $locname = strtr($locname, array('-' => ' ', '+' => ' ', '_' => ' '));
- // Mettre la chaine tous codes postaux entre parentheses
- $locname = str_ireplace('TOUS CODES POSTAUX', '(Tous codes postaux)', $locname);
- // Séparer les parentheses avec une virgule
- $locname = str_replace(') ', '), ', $locname);
- // Ajouter les apostrophes devant les L et le D
- $locname = preg_replace('`\b(L|D) `i', '$1\'', $locname);
- }
- // Ajout la valeur de localité
- if ($locname != '')
- $summary["loc_name"] = $locname;
- // property types
- if (isset($data["ck_property_type"])) {
- $property_type = $data['ck_property_type'];
- // Si champ vide, ou aucun coché
- if (empty($property_type) || strpos($property_type, '1') === false) {
- $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
- // Sinon on liste tous les types de biens
- } elseif (SUMMARY_LIST_PROPERTY_TYPES) {
- $size = strlen($property_type);
- $str_property_type = '';
- /*
- for($i=0; $i<$size; $i++) {
- if( $property_type[$i]=='1' ) $str_property_type .= ', '.constant("LABEL_COMMON_PROPERTY_ID_".($i+1));
- }
- */
- $pos = -1;
- while (($pos = strpos($string, '1', $pos + 1)) !== false) {
- $str_property_type .= ', ' . constant("LABEL_COMMON_PROPERTY_ID_" . ($pos + 1));
- }
- $summary["property_type"] = substr($str_property_type, 2);
- // Sinon on liste les groupes de biens
- } else {
- if ($useAdvancedGroups) {
- global $_ADVANCED_SEARCH_TYPES, $_MASK_REALESTATETYPES_ALL_CHECKED;
- $checkedLabels = getCheckedFields($_ADVANCED_SEARCH_TYPES, $property_type, $_MASK_REALESTATETYPES_ALL_CHECKED, true);
- } else {
- global $_LI_REALESTATEGROUPS, $_MASK_REALESTATETYPES_ALL_CHECKED;
- $checkedLabels = getCheckedFields($_LI_REALESTATEGROUPS, $property_type, $_MASK_REALESTATETYPES_ALL_CHECKED, true);
- }
- // Si ce n'est pas un tableau ou qu'il est vide, c'est "Tous types de bien"
- if (!is_array($checkedLabels) || $checkedLabels == array())
- $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
- else
- $summary["property_type"] = implode(', ', $checkedLabels);
- }
- }
- else {
- global $_LI_REALESTATETYPES;
- if ($data["property_type"] == "" || $data["property_type"][0] == -1 || count($data["property_type"]) == count($_LI_REALESTATETYPES)) {
- $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
- } else {
- for ($i = 0; $i < count($data["property_type"]); $i++) {
- $data["property_type"][$i] = $_LI_REALESTATETYPES[$data["property_type"][$i]];
- }
- $summary["property_type"] = implode(", ", $data["property_type"]);
- }
- }
- // surface
- $summary["area"] = get_summary($data, $parameters["area"], "area", LABEL_ALL_AREA, LABEL_COMMON_AREA_UNIT);
- // price
- $summary["price"] = get_summary($data, $parameters["price"], "price", LABEL_ALL_BUDGET, LABEL_COMMON_PRICE_UNIT);
- // rooms
- // NB: pour la coloc., le nombre de pièces est en fait le nombre de chambres !
- if (isset($data['ck_nb_rooms'])) {
- global $_MASK_NB_ROOMS_ALL_CHECKED;
- $nb_rooms = $data['ck_nb_rooms'];
- // Convertir le tableau en chaine
- if (is_array($nb_rooms)) {
- $str_nb_rooms = str_repeat('0', 8); // 8 nombre de pieces possibles (2 octets)
- foreach ($nb_rooms as $nb_room) {
- $str_nb_rooms[intval($nb_room)] = 1;
- }
- $nb_rooms = $str_nb_rooms;
- }
- // Si champ vide, ou aucun coché ou tous cochés
- $all_checked = matchMask($nb_rooms, $_MASK_NB_ROOMS_ALL_CHECKED);
- if (empty($nb_rooms) || strpos($nb_rooms, '1') === false || $all_checked) {
- if ($showIfAllChecked)
- $summary["nb_rooms"] = ($data["univers"] == 8 ? LABEL_ALL_BEDROOMS : LABEL_ALL_ROOMS);
- }
- else {
- // Gérer le cas où seul le premier est coché (singulier)
- if (strpos($nb_rooms, '1', 1) === false && strpos($nb_rooms, '1') === 0) {
- $summary["nb_rooms"] = $_LI_ROOMS[0];
- } else {
- $limit = count($_LI_ROOMS) - 1;
- $str_nb_rooms = '';
- for ($i = 0; $i < $limit; $i++) {
- if ($nb_rooms[$i] == '1')
- $str_nb_rooms .= ', ' . ($i + 1);
- }
- // Ajouter le 'Et plus' sur le dernier si coché
- if ($nb_rooms[$i] == '1') {
- //$str_nb_rooms .= ', '.($i+1).' ';
- //$summary["nb_rooms"] = substr($str_nb_rooms,2).' '.LABEL_COMMON_ROOMS_UNIT.' '.LABEL_AND_MORE;
- if ($str_nb_rooms == '')
- $summary["nb_rooms"] = $_LI_ROOMS[$i];
- else
- $summary["nb_rooms"] = substr($str_nb_rooms, 2) . ', ' . $_LI_ROOMS[$i];
- }
- else {
- $summary["nb_rooms"] = substr($str_nb_rooms, 2) . ' ' . ($data["univers"] == 8 ? LABEL_COMMON_BEDROOMS_UNITS : LABEL_COMMON_ROOMS_UNITS);
- }
- }
- }
- } else {
- $summary["nb_rooms"] = get_summary($data, $parameters["nb_rooms"], "nb_rooms", ($data["univers"] == 8 ? LABEL_ALL_BEDROOMS : LABEL_ALL_ROOMS), ($data["univers"] == 8 ? LABEL_COMMON_BEDROOMS_UNITS : LABEL_COMMON_ROOMS_UNITS));
- }
- // bedrooms
- if (isset($data['ck_nb_bedrooms'])) {
- global $_MASK_NB_BEDROOMS_ALL_CHECKED, $_LI_BEDROOMS;
- $nb_bedrooms = $data['ck_nb_bedrooms'];
- // Convertir le tableau en chaine
- if (is_array($nb_bedrooms)) {
- $str_nb_bedrooms = str_repeat('0', 8); // 8 nombre de pieces possibles (2 octets)
- foreach ($nb_bedrooms as $nb_bedroom) {
- $str_nb_bedrooms[intval($nb_bedroom)] = 1;
- }
- $nb_bedrooms = $str_nb_bedrooms;
- }
- // Si champ vide, ou aucun coché ou tous cochés
- $all_checked = matchMask($nb_bedrooms, $_MASK_NB_BEDROOMS_ALL_CHECKED);
- if (empty($nb_bedrooms) || strpos($nb_bedrooms, '1') === false || $all_checked) {
- if ($showIfAllChecked)
- $summary["nb_bedrooms"] = 'Tous nb de chambres';
- }
- else {
- // Gérer le cas où seul le premier est coché (singulier)
- if (strpos($nb_bedrooms, '1', 1) === false && strpos($nb_bedrooms, '1') === 0) {
- $summary["nb_bedrooms"] = $_LI_BEDROOMS[0];
- } else {
- $limit = count($_LI_BEDROOMS) - 1;
- $str_nb_bedrooms = '';
- for ($i = 0; $i < $limit; $i++) {
- if ($nb_bedrooms[$i] == '1')
- $str_nb_bedrooms .= ', ' . ($i + 1);
- }
- // Ajouter le 'Et plus' sur le dernier si coché
- if ($nb_bedrooms[$i] == '1') {
- if ($str_nb_bedrooms == '')
- $summary["nb_bedrooms"] = $_LI_BEDROOMS[$i];
- else
- $summary["nb_bedrooms"] = substr($str_nb_bedrooms, 2) . ', ' . $_LI_BEDROOMS[$i];
- }
- else {
- $summary["nb_bedrooms"] = substr($str_nb_bedrooms, 2) . ' chambres';
- }
- }
- }
- }
- }
- return $summary;
- }
- /**
- * Convertit chaque critère par une valeur lisible par l'internaute
- * @param Array $data Tableau indexé des valeurs sélectionnées par l'internaute
- * @param Boolean $extended Afficher les "ou" entre parentheses [ex: chauffage (gaz,fioul) ]
- * @param Boolean $showIfAllChecked
- * @return Array Tableau indexé contenant uniquement les valeurs converties
- */
- function get_adv_summary($data, $extended = false, $showIfAllChecked = true) {
- global $_ADVANCED_SEARCH_CAT;
- $summary = array();
- // Critères avancés du bien (equipement, chauffage, fiche technique, etc.)
- if (isset($data['ck_advanced']) && strpos($data['ck_advanced'], '1') !== false) {
- $advanced = $data['ck_advanced'];
- // Récupérer la liste des critères sans les catégories
- // => Plus simple à interroger
- $advanced_search = array();
- foreach ($_ADVANCED_SEARCH_CAT as $SUB_CAT) {
- $advanced_search += $SUB_CAT;
- }
- $str_advanced = '';
- $length = strlen($advanced);
- if ($extended) {
- global $_MASK_ADV_OR;
- foreach ($_MASK_ADV_OR as $label => $mask_or) {
- $mask_value = $advanced & $mask_or;
- // Ajouter la clause OU
- if ($mask_value > 0) {
- // Equivalent d'un NON + compléter avec des 1 pour le ET ci-dessous
- $remove_mask = str_pad(strtr($mask_value, '01', '10'), $length, 1);
- // Effacer les critères de chauffage du masque principal
- $advanced = $advanced & $remove_mask;
- $pos = -1;
- $tmp_str_advanced = '';
- while (($pos = strpos($mask_value, '1', $pos + 1)) !== false) {
- $tmp_str_advanced .= ', ' . $advanced_search[$pos];
- }
- $tmp_str_advanced = substr($tmp_str_advanced, 2);
- $str_advanced .= ", $label ($tmp_str_advanced)";
- }
- }
- }
- $pos = -1;
- while (($pos = strpos($advanced, '1', $pos + 1)) !== false) {
- $str_advanced .= ', ' . $advanced_search[$pos];
- }
- $summary["advanced"] = substr($str_advanced, 2);
- }
- /*
- * *************************************************************************
- * TRAITEMENTS A ACTIVER SI UTILISES
- * (Surface du terrain, DPE, Fraicheur des annonces)
- * *************************************************************************
- *
- // Surface du terrain min / max
- $surf_min = isset($data['surf_min']) ? (int)$data['surf_min'] : 0;
- $surf_max = isset($data['surf_max']) ? (int)$data['surf_max'] : 0;
- if($surf_max>0) {
- $summary['surf'] = "Terrain entre {$surf_min} et {$surf_max} m²";
- } elseif($surf_min>0) {
- $summary['surf'] = "Terrain de plus de {$surf_min} m²";
- }
- // Consommation énergétique
- if(isset($data['dpe']) && strpos($data['dpe'],'1')!==false) {
- $ref_dpe = 'ABCDEFGH';
- $result = '';
- for($i=0, $max=strlen($data['dpe']); $i<$max; $i++) {
- if($data['dpe'][$i]==1) $result .= ', '.$ref_dpe[$i];
- }
- $summary['dpe'] = 'Energie '.substr($result,2);
- }
- // Fraicheur des annonces
- if(isset($data['fresh']) && ($fresh = (int)$data['fresh'])!==0) {
- switch(substr($data['fresh'],-1)) {
- case 'h': $unit = $fresh==1 ? 'heure' : 'heures'; break;
- case 'j': $unit = $fresh==1 ? 'jour' : 'jours'; break;
- case 's': $unit = $fresh==1 ? 'semaine' : 'semaines'; break;
- case 'm': $unit = 'mois'; break;
- case 'a': $unit = $fresh==1 ? 'an' : 'ans'; break;
- }
- if(isset($unit)) {
- $summary['fresh'] = "Annonces de moins de {$fresh} {$unit}";
- }
- }
- */
- return $summary;
- }
- /**
- * Turns a search criterion to a human readable value
- *
- * @param unknown_type $data
- * @param unknown_type $parameters
- * @param unknown_type $item
- * @param unknown_type $label_all
- * @param unknown_type $label_unit
- * @return unknown
- */
- function get_summary($data, $parameters, $item, $label_all, $label_unit) {
- // patch
- if ($data[$item] == -1) {
- $data[$item] = "";
- }
- // rooms
- if (in_array($item, array("nb_rooms", "nb_bedrooms", "nb_people"))) {
- if ($data[$item] == "" && $data[$item . "_min"] == "" && $data[$item . "_max"] == "") {
- $summary = $label_all;
- } else {
- if ($data[$item] != "") {
- $summary = $parameters[$data[$item]];
- } else {
- if ($data[$item . "_min"] != "" && $data[$item . "_max"] != "") {
- $summary = LABEL_FROM . " " . $data[$item . "_min"] . " " . LABEL_TO . " " . $data[$item . "_max"] . " " . $label_unit;
- } elseif ($data[$item . "_min"] != "" && $data[$item . "_max"] == "") {
- $summary = LABEL_MORE_THAN . " " . $data[$item . "_min"] . " " . $label_unit;
- } else {
- $summary = LABEL_LESS_THAN . " " . $data[$item . "_max"] . " " . $label_unit;
- }
- }
- }
- }
- // price, surface
- else {
- if (!is_numeric($data[$item . "_min"]))
- $data[$item . "_min"] = '';
- if (!is_numeric($data[$item . "_max"]))
- $data[$item . "_max"] = '';
- if ($data[$item] == "" && $data[$item . "_min"] == "" && $data[$item . "_max"] == "") {
- $summary = $label_all;
- } else {
- if ($data[$item] != "") {
- $value = $parameters[$data[$item]];
- if ($value["from"] == 0) {
- $summary = LABEL_LESS_THAN . " " . $value["to"] . " " . $label_unit;
- } elseif ($value["to"] == 999999999) {
- $summary = LABEL_MORE_THAN . " " . $value["from"] . " " . $label_unit;
- } else {
- $summary = LABEL_FROM . " " . $value["from"] . " " . LABEL_TO . " " . $value["to"] . " " . $label_unit;
- }
- } else {
- if ($data[$item . "_min"] != "" && $data[$item . "_max"] != "") {
- $summary = LABEL_FROM . " " . n_f($data[$item . "_min"]) . " " . LABEL_TO . " " . n_f($data[$item . "_max"]) . " " . $label_unit;
- } elseif ($data[$item . "_min"] != "" && $data[$item . "_max"] == "") {
- $summary = LABEL_MORE_THAN . " " . n_f($data[$item . "_min"]) . " " . $label_unit;
- } else {
- $summary = LABEL_LESS_THAN . " " . n_f($data[$item . "_max"]) . " " . $label_unit;
- }
- }
- }
- }
- return $summary;
- }
- /**
- * Returns property type label depending on the code
- *
- * @param unknown_type $id
- * @return unknown
- */
- function get_property_type_label($id) {
- global $_LI_REALESTATETYPES;
- foreach ($_LI_REALESTATETYPES as $property_type) {
- if ($property_type["value"] == $id) {
- return $property_type["label"];
- }
- }
- }
- /**
- * number_format shortcut
- *
- * @param unknown_type $value
- * @return unknown
- */
- function n_f($value) {
- return number_format($value, 0, "", " ");
- }
- /**
- * Currency conversion
- *
- * @param unknown_type $value
- * @param unknown_type $from
- * @param unknown_type $to
- * @param unknown_type $add_currency_name
- * @return unknown
- */
- function currency_format($value, $from, $to, $add_currency_name = true) {
- global $_global;
- global $_rates;
- if ($_rates[$from][$to] > 0) {
- $price = n_f($value * $_rates[$from][$to]);
- if ($add_currency_name) {
- switch ($_global["current_currency"]) {
- case "CZK" :
- $price = $price . " " . LABEL_COMMON_PRICE_UNIT_CZ;
- break;
- case "EUR" :
- $price = $price . " " . LABEL_COMMON_PRICE_UNIT;
- break;
- case "CHF" :
- $price = $price . " " . LABEL_COMMON_PRICE_UNIT_CH;
- break;
- default :
- $price = $price . " " . LABEL_COMMON_PRICE_UNIT;
- break;
- }
- }
- return $price;
- }
- }
- /**
- * Function so sex, par le so sexy oxman, da crazy man !
- *
- * @param unknown_type $input
- * @param unknown_type $partial
- * @return unknown
- */
- function sosex($input, $partial = false) {
- // Partial mode, the word isn't complete, typically when you're doing an ajax completion
- $input = str_replace('è', 'ai', $input);
- $input = str_replace('ê', 'ai', $input);
- $input = str_replace('é', 'ai', $input);
- $input = strtoupper($input);
- // START - Nettoiement de la recherche, suppressions de tous les caracteres parasites
- $input = preg_replace('/(.)\\1{1,}/', '\\1', $input); // 1. Suppression des lettres en doubles (exemple: pelle, femme)
- $input = preg_replace('/[-,\/;.\']/', ' ', $input); // 2. Sérateur de mot : , / ; . -
- $input = preg_replace('/(?=\b)[^ ](?=\b)/', '', $input); // 28. Suppression des caractères isolées (résultant d'un D', L', etc)
- $input = ' ' . $input . ' ';
- $input = preg_replace('/(?=\b)ST(?=\b)/', 'SAINT', $input); // 3. Attention avant la 4
- $input = preg_replace('/(?=\b)[LD]ES(?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
- $input = preg_replace('/(?=\b)SUR(?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
- $input = preg_replace('/(?=\b)SOUS(?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
- $input = preg_replace('/(?=\b)L[EA](?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
- $input = preg_replace('/(?=\b)D[EU](?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
- $input = preg_replace('/(?=\b)E[TN](?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
- $input = str_replace('ET', 'AIT', $input); // 25. Son : AI (exemple: jouet, essai), avant la regle de suppressions des lettres muettes (n°20)
- $input = preg_replace('/ES(?!\b)/', 'AIS', $input); // 26. Son : AI (exemple: jouet, essai, mais pas lourdes), avant la regle de suppressions des lettres muettes (n°20)
- $input = preg_replace('/[AE][NM](?![AEIOUY])/', 'AN', $input); // 5. Son : AN (exemple: femme, enfant), avant lettres muettes
- $input = preg_replace('/OM(?![AEIOUY])/', 'ON', $input); // 14. Son : ON (exemple: pantalom, pomtom), avant lettres muettes
- $input = preg_replace('/(?<![CSP]|\b)H/', '\\1', $input); // 6. Son muet H si il n'y a ni C,S,P devant (hyè, mammouth, pharaon), avant lettres muettes
- $input = preg_replace('/P[HF]/', 'F', $input); // 19. Son : F (exemple: PF ou PH donne le son F), avant lettres muettes
- $input = str_replace('Y', 'I', $input); // 29. Son : I, avant lettres muettes
- $input = preg_replace('/X(?=\b)/', '', $input); // 30. Son : X muet à la fin de mot
- if (!$partial) {
- $input = preg_replace('/(?!E)T(?![AEIOUYR$])/', '', $input); // 13. Son muet T si en fin de mot, où suivis d'une consonne, pas muet si c'est suivit d'un R : TRIMARAN, pas muet si précédé d'un E, car fait le son AI
- $input = preg_replace('/(?<![AEIOUY]|\b)[GLSXP](?![AEIOUY])/', '', $input); // 20. Son muet G ou, H ou L etc.. si en fin de mot, où suivis d'une consonne, et précédé d'une consonne
- $input = preg_replace('/E(?=\b)/', '', $input); // 20. Son muet E etc.. si en fin de mot, où suivis d'une voyelle, et précédé d'une voyelle
- $input = preg_replace('/ES(?=\b)/', '', $input); // 27. Son ES en fin de mot muet
- }
- // END
- $input = str_replace('EU', 'E', $input); // 25. Son : E, après la regle de suppressions des lettres muettes (n°20)
- $input = preg_replace('/E?AU/', 'O', $input); // 7. Son O : veau, pot, l'horizon
- $input = str_replace('SH', 'CH', $input); // 9. Son : CH
- $input = preg_replace('/C[CK]/', 'K', $input); // 18. Son : K (exemple: CC ou CK donne le son K)
- $input = str_replace('QU', 'K', $input); // 10. Son : K (exemple: quand, bouquet, plaque)
- $input = str_replace('KS', 'X', $input); // 28. Son : X (exemple: luksiol)
- $input = preg_replace('/C(?=[UAO]|\b)/', 'K', $input); // 16. Son : K (exemple: cutalion, carole, mais pas celine, ciboulette, candiac)
- $input = preg_replace('/C(?=[IEY])/', 'S', $input); // 17. Son : S (exemple: celine, ciboulette, cy..., mais pas cutalion, carole)
- $input = preg_replace('/G(?=[IEYL]|\b)/', 'J', $input); // 24. Son : J (exemple: gille, vregille, mais pas vrigne, zigliara)
- $input = str_replace('Z', 'S', $input); // 15. Son : Z S
- $input = preg_replace("/(.)\\1{1,}/", "\\1", $input); // 12. Suppression des lettres en doubles cré aprètransformation (tout à a fin)
- return trim($input);
- }
- /**
- * Replace only the first occurence of a string
- *
- * @param unknown_type $needle
- * @param unknown_type $replace
- * @param unknown_type $haystack
- * @return unknown
- */
- function str_replace_once($needle, $replace, $haystack) {
- // Looks for the first occurence of $needle in $haystack
- // and replaces it with $replace.
- $pos = strpos($haystack, $needle);
- if ($pos === false) {
- // Nothing found
- return $haystack;
- }
- return substr_replace($haystack, $replace, $pos, strlen($needle));
- }
- /**
- * Returns a truncated string
- *
- * @param unknown_type $value
- * @param unknown_type $limit
- * @return unknown
- */
- function str_limit($value, $limit) {
- if (strlen($value) == 0) {
- return "";
- } else {
- if (strlen($value) <= $limit) {
- return $value;
- } else {
- $tmp = explode(" ", $value);
- if (count($tmp) > 0) {
- $valV = $valVold = "";
- foreach ($tmp as $v) {
- if (strlen($valV) > $limit) {
- $value = substr($valVold, 0, -1) . "...";
- break;
- }
- else
- $valVold = $valV;
- $valV .= $v . " ";
- }
- }
- return $value;
- }
- }
- }
- /**
- * Returns html city name with arrondissement correctly written in french
- * ex: Marseille 1er => Marseille 1<sup>er</sup>, Paris 2e => Paris 2<sup>ème</sup>
- *
- * @param unknown_type $cityname_arrond
- * @return unknown
- */
- function cityname_arrond($cityname_arrond, $short_form = false) {
- $str_cityname_arrond = "";
- $arr_cityname_arrond = explode(" ", $cityname_arrond);
- $str_cityname = $arr_cityname_arrond[0];
- $str_arrond = $arr_cityname_arrond[1];
- if (strpos($str_arrond, "er") !== FALSE) {
- $str_cityname_arrond = $str_cityname . " " . str_replace("er", "<sup>er</sup>", $str_arrond);
- } else if (strpos($str_arrond, "e") !== FALSE) {
- if ($short_form) {
- $str_cityname_arrond = $str_cityname . " " . str_replace("e", "<sup>è</sup>", $str_arrond);
- } else {
- $str_cityname_arrond = $str_cityname . " " . str_replace("e", "<sup>ème</sup>", $str_arrond);
- }
- }
- return $str_cityname_arrond;
- }
- /**
- * Returns html city name without arrondissement at the end, if present
- * ex: Marseille 1er => Marseille, Paris 2e => Paris, Cannes => Cannes
- *
- * @param unknown_type $cityname_arrond
- * @return unknown
- */
- function cityname_without_arrond($cityname_arrond) {
- $str_cityname_arrond = $cityname_arrond;
- $str_cityname_arrond = preg_replace('/(\w+) (\d+)er/i', '${1}', $str_cityname_arrond);
- $str_cityname_arrond = preg_replace('/(\w+) (\d+)e/i', '${1}', $str_cityname_arrond);
- return $str_cityname_arrond;
- }
- /**
- * Returns true if the lct_id is the one of the arrondissement of a city (Paris, Lyon, Marseille)
- * ex: 36102 => true (Marseille 2è), 33109 => false (Toulon)
- *
- * @param int $lct_id
- * @return bool
- */
- function is_lct_id_arrond_of_city($lct_id) {
- if (!isset($lct_id) || empty($lct_id)) {
- return array(false, "");
- }
- $lct_ids_arrronds_paris = array(23599, 23601, 23602, 23603, 23604, 23605, 23606, 23607, 23609, 23589, 23590, 23591, 23592, 23593, 23594, 23595, 23596, 23597, 23598, 23600);
- if (in_array($lct_id, $lct_ids_arrronds_paris)) {
- return array(true, "paris");
- }
- $lct_ids_arrronds_marseille = array(36102, 36104, 36105, 36106, 36107, 36108, 36109, 36110, 36111, 36112, 36113, 36114, 36115, 36116, 36117, 36118);
- if (in_array($lct_id, $lct_ids_arrronds_marseille)) {
- return array(true, "marseille");
- }
- $lct_ids_arrronds_lyon = array(36119, 36120, 36121, 36122, 36123, 36124, 36125, 36126, 36127);
- if (in_array($lct_id, $lct_ids_arrronds_lyon)) {
- return array(true, "lyon");
- }
- return array(false, "");
- }
- /**
- * Returns true if the loc_key is the one of city with arrondissements (Paris, Lyon, Marseille)
- * ex: 421_99 => true (Marseille), 33109_2 => false (Toulon)
- *
- * @param int $lct_id
- * @return bool
- */
- function is_loc_key_city_with_arronds($loc_key) {
- if (!isset($loc_key) || empty($loc_key)) {
- return array(false, "");
- }
- $loc_key_paris = '100_1';
- if ($loc_key == $loc_key_paris) {
- return array(true, "paris");
- }
- $loc_key_marseille = '421_99';
- if ($loc_key == $loc_key_marseille) {
- return array(true, "marseille");
- }
- $loc_key_lyon = '422_99';
- if ($loc_key == $loc_key_lyon) {
- return array(true, "lyon");
- }
- return array(false, "");
- }
- /**
- * Returns a clean string
- *
- * @param unknown_type $value
- * @return unknown
- */
- function remove_returns($value) {
- $value = str_replace("\r\n", "", $value);
- $value = str_replace("\n\r", "", $value);
- $value = str_replace("\n", "", $value);
- $value = str_replace("\r", "", $value);
- return $value;
- }
- /**
- * Returns a "clean" html, without css MS Office classes
- *
- * @param unknown_type $value
- * @return unknown
- */
- function strip_mso_css_class($value) {
- $value = str_replace(" class=\"MsoPlainText\"", "", $value);
- return $value;
- }
- /**
- * Returns in a html string li tags par a dot char
- *
- * @param unknown_type $value
- * @return unknown
- */
- function replace_li_tag_dot_char($value) {
- $value = str_replace("<li>", "• ", $value);
- $value = str_replace("</li>", "<br>", $value);
- $value = str_replace("<ul>", "", $value);
- $value = str_replace("</ul>", "", $value);
- return $value;
- }
- /**
- * Returns html height and width properties, determining the size of an image to fit required width and height
- *
- * @param unknown_type $img
- * @param unknown_type $max_width
- * @param unknown_type $max_height
- * @return unknown
- */
- function resize_image($img, $max_width, $max_height) {
- $img_details = @getimagesize($img);
- $img_width = $img_details[0];
- $img_height = $img_details[1];
- if ($img_width == "" || $img_height == "") {
- return "";
- }
- $img_wratio = round($img_height / $img_width, 2);
- $img_hratio = round($img_width / $img_height, 2);
- if ($img_width > $max_width || $img_height > $max_height) {
- if ($img_width > $img_height) {
- $img_width = $max_width;
- $img_height = $img_width * $img_wratio;
- if ($img_height > $max_height) {
- $img_height = $max_height;
- $img_width = $img_height * $img_hratio;
- }
- } else {
- $img_height = $max_height;
- $img_width = $img_height * $img_hratio;
- if ($img_width > $max_width) {
- $img_width = $max_width;
- $img_height = $img_width * $img_wratio;
- }
- }
- }
- return "width=\"" . $img_width . "\" height=\"" . $img_height . "\"";
- }
- /**
- * Returns html code for a spacer
- *
- * @param unknown_type $height
- * @param unknown_type $width
- * @return unknown
- */
- function spacer($height, $width) {
- return "<img src=\"" . get_urlmmf('/spacer.gif') . "\" height=\"" . $height . "\" width=\"" . $width . "\" />";
- }
- /**
- * Returns html alt and title
- *
- * @param unknown_type $value
- * @return unknown
- */
- function set_html_title($value) {
- return "alt=\"" . $value . "\" title=\"" . $value . "\"";
- }
- /**
- * Returns ad and agency data
- *
- * @param unknown_type $page
- * @param unknown_type $value
- * @param unknown_type $has_premium
- * @param unknown_type $url
- * @param Integer $idx
- * @param Boolean $is_exclusive Annonce à afficher en haut de la page des annonces
- * @return unknown
- */
- function get_ad_data($page, $value, $has_premium = 0, $url = "", $idx = -1, $is_exclusive = false) {
-
- global $_global;
- global $_LI_REALESTATETYPES;
- global $_REF_ROOMS;
- global $_LI_BANDEAU_PERSO_FR;
- $prefix_table = '';
-
- if ( 9 != $_global['univers'] ) {
- $prefix_table = $_global["table_prefix"] . '_';
- }
-
- // arrays
- $ad = array();
- $ag = array();
- //echo '<pre>'; var_dump($value); echo '</pre>';
- $ad["idx"] = $idx;
- $ad["id"] = $value["id_annonce"];
- $ad["univers"] = $value["univers"];
- $ad["reference"] = $value[$prefix_table . "reference"];
- $ad["num_mandat"] = $value[$prefix_table . "num_mandat"];
- // ad premium
- $ad["premium"] = $value[$prefix_table . "is_premium"];
- // ad features
- $ad["type_transaction"] = $value[$prefix_table . "type_transaction"];
- $ad["id_bien"] = $value["id_bien"];
- $ad["id_bien_programme"] = $value["id_bien_programme"];
- $ad["prg_title"] = $value["prg_title"];
- $ad["property_type_id"] = $value[$prefix_table . "property_type_id"];
- $ad["property_type_id_orig"] = $value[$prefix_table . "property_type_id_orig"];
- $ad["property_type"] = html_entity_decode($value[$prefix_table . "property_type"], ENT_QUOTES, "UTF-8");
- if ($ad["type_transaction"] == "4")
- $ad["property_type"] .= LABEL_AD_LIFE_ANNUITY;
- $ad["agency_rent_fees"] = $value["rnt_agency_rent_fees"];
- $ad["rnt_property_charges"] = $value["rnt_property_charges"];
- $ad["guarantee_deposit"] = $value[$prefix_table . "guarantee_deposit"];
- //ad currency
- $ad["currency"] = $value[$prefix_table . "currency"];
- //SUSPENSION DES CHARGES
- $ad["real_price"] = $value[$prefix_table . "price"];
- $ad["price"] = ($ad["real_price"] >= AD_PRICE_LIMIT ? $ad["real_price"] : n_f($ad["real_price"]));
- if ($ad["property_type"] == "") {
- $ad["property_type"] = ($ad["property_type_id_orig"] != "" ? constant("LABEL_COMMON_PROPERTY_ID_" . $ad["property_type_id_orig"]) : "");
- }
- $ad["area"] = $value[$prefix_table . "area"];
- $ad["price"] = ($ad["real_price"] >= AD_PRICE_LIMIT ? $ad["real_price"] : n_f($ad["real_price"]));
- $ad["nb_rooms"] = $value[$prefix_table . "nb_rooms"];
- // Advanced : dependances, chauffage, amenagement, confort
- $ad["advanced_set"] = $value[$prefix_table . 'advanced_set'];
- // First online date
- $ad["first_online_date"] = $value[$prefix_table . 'first_online_date'];
- //Colocation
- if ($_global["univers"] == 8) {
- $ad["nb_bedrooms"] = $value["rnt_nb_bedrooms"];
- }
- $ad["default_text"] = str_replace("[[n]]", " ", $value[$prefix_table . "default_text"]);
- if ($_global["self"] == "resultats_refnat.php") {
- $ad["default_intro"] = strtolower(strip_tags(str_limit($ad["default_text"], 90)));
- } else {
- $ad["default_intro"] = preg_replace('`(\<[a-zA-Z]*)\.\.\.$`', '', str_limit($ad["default_text"], 200));
- }
- // vacances
- if ($_global["univers"] == 13) {
- $ad["nb_bedrooms"] = $value["rnt_nb_bedrooms"];
- $ad["nb_people"] = $value["rnt_nb_people"];
- if ($value["rnt_site_agency"] != "") {
- if (substr($value["rnt_site_agency"], 0, 7) != "http://") {
- $value["rnt_site_agency"] = "http://" . $value["rnt_site_agency"];
- }
- $ad["partner_url"] = $value["rnt_site_agency"];
- }
- $ad["external"] = ($value["id_presto"] == "CMM-PT-VACANCES" ? true : false);
- }
- if ($_global["univers"] == 13) {
- $ad["features"] = $ad["property_type"] . ($ad["area"] > 0 ? " - " . $ad["area"] . " " . LABEL_COMMON_AREA_UNIT . " " . LABEL_RESULTS_ABOUT : "") . ($ad["nb_bedrooms"] > 0 ? " - " . $ad["nb_bedrooms"] . " " . LABEL_COMMON_BEDROOMS_UNIT : "");
- } else {
- if ($ad["nb_rooms"] == 1) {
- $s_piece = LABEL_COMMON_ROOM_UNIT;
- } else {
- $s_piece = LABEL_COMMON_ROOMS_UNITS;
- }
- if ($_global["self"] == "resultats_refnat.php") {
- $ad["features"] = ($ad["area"] > 0 ? $ad["area"] . " " . LABEL_COMMON_AREA_UNIT . " " . LABEL_RESULTS_ABOUT : "") . ($ad["area"] > 0 && $ad["nb_rooms"] > 0 ? " - " : "") . ($ad["nb_rooms"] > 0 ? $ad["nb_rooms"] . " " . $s_piece : "");
- } else {
- $ad["features"] = $ad["property_type"] . ($ad["area"] > 0 ? " - " . $ad["area"] . " " . LABEL_COMMON_AREA_UNIT . " " . LABEL_RESULTS_ABOUT : "") . ($ad["nb_rooms"] > 0 ? " - " . $ad["nb_rooms"] . " " . $s_piece : "");
- }
- /** Suppression du label "OU PLUS" Mathieu 25/01
- if ($ad["nb_rooms"] == 6) {
- $ad["features"] .= " " . LABEL_COMMON_OR_MORE;
- }
- *
- */
- }
- $ad["is_exclusive"] = $value[$prefix_table . "is_exclusive"];
- $is_exclusive = $is_exclusive || CURRENT_EXCLUSIVE_NUM > 0 && CURRENT_EXCLUSIVE_NUM == $ad['is_exclusive'];
- $ad['is_pack_exclusive'] = $is_exclusive;
- //20090401-1-XI, Retrieving xxx_locality_2_agency field (mantis 5342)
- $ad["locality_2_agency"] = $value[$prefix_table . "locality_2_agency"];
- //20090610-1-XI, NOT Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO', mantis 5865
- //20090407-1-XI, Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO'
- /*
- if ($value["id_presto"]=="CMM-PT-BDL-EXPRESSO")
- $ad["locality_2_agency"] = 0;
- */
- $locality_for_url = prepareToUrl($value[$prefix_table . "default_town_2"]);
- $lang = 'FR';
- #$lang = $value[$_global["table_prefix"]."_country"];
- // ad full features
- if ($page == "detail.php" || $page == "detail_refnat.php") {
- $ad["garden_area"] = $value[$prefix_table . "garden_area"];
- $ad["terrace_area_1"] = $value[$prefix_table . "terrace_area_1"];
- $ad["balcony_area_1"] = $value[$prefix_table . "balcony_area_1"];
- $ad["is_pool"] = $value[$prefix_table . "is_pool"];
- $ad["pool_area"] = $value[$prefix_table . "pool_area"];
- $ad["nb_garage"] = $value[$prefix_table . "nb_garage"];
- $ad["nb_parking"] = $value[$prefix_table . "nb_parking"];
- $ad["is_parking_closed"] = $value[$prefix_table . "is_parking_closed"];
- $ad["nb_covered_parking"] = $value[$prefix_table . "nb_covered_parking"];
- $ad["nb_uncovered_parking"] = $value[$prefix_table . "nb_uncovered_parking"];
- $ad["is_renovated"] = $value[$prefix_table . "is_renovated"];
- $ad["renovating_date"] = $value[$prefix_table . "renovating_date"];
- $ad["need_renovating"] = $value[$prefix_table . "need_renovating"];
- $ad["floor"] = $value[$prefix_table . "floor"];
- $ad["nb_caretaker"] = $value[$prefix_table . "nb_caretaker"];
- $ad["is_interphone"] = $value[$prefix_table . "is_interphone"];
- $ad["is_doorcode"] = $value[$prefix_table . "is_doorcode"];
- $ad["is_elevator"] = $value[$prefix_table . "is_elevator"];
- $ad["nb_bath"] = $value[$prefix_table . "nb_bath"];
- $ad["nb_shower"] = $value[$prefix_table . "nb_shower"];
- $ad["is_independant_toilet"] = $value[$prefix_table . "is_independant_toilet"];
- $ad["is_first_floor_toilet"] = $value[$prefix_table . "is_first_floor_toilet"];
- $ad["is_central_heating"] = $value[$prefix_table . "is_central_heating"];
- $ad["is_individual_heating"] = $value[$prefix_table . "is_individual_heating"];
- $ad["is_electrical_heating"] = $value[$prefix_table . "is_electrical_heating"];
- $ad["is_floor_heating"] = $value[$prefix_table . "is_floor_heating"];
- $ad["is_gas_heating"] = $value[$prefix_table . "is_gas_heating"];
- $ad["is_diesel_heating"] = $value[$prefix_table . "is_diesel_heating"];
- $ad["is_aircon"] = $value[$prefix_table . "is_aircon"];
- $ad["is_chimney"] = $value[$prefix_table . "is_chimney"];
- $ad["is_wooden_floor"] = $value[$prefix_table . "is_wooden_floor"];
- $ad["is_tiled_floor"] = $value[$prefix_table . "is_tiled_floor"];
- $ad["is_alarm"] = $value[$prefix_table . "is_alarm"];
- $ad["is_sunny"] = $value[$prefix_table . "is_sunny"];
- $ad["is_calm"] = $value[$prefix_table . "is_calm"];
- $ad["facing"] = $value[$prefix_table . "facing"];
- $ad["is_handicap_access"] = $value[$prefix_table . "is_handicap_access"];
- $ad["agency_rent_fees"] = $value[$prefix_table . "agency_rent_fees"];
- $ad["is_closet"] = $value[$prefix_table . "is_closet"];
- $ad["is_basement"] = $value[$prefix_table . "is_basement"];
- }
- if ($page == 'detail.php') {
- $ad["id_programme"] = $value["id_programme"];
- // $ad["type_transaction"] = $value[$prefix_table."_type_transaction"];
- }
- //DPE
- $ad["dpe_energy"] = $value[$prefix_table . "energy"];
- $ad["dpe_energy_val"] = $value[$prefix_table . "energy_val"];
- // ad pictures
- $ad["photos_count"] = 0;
- if ($page != "resultats.php") {
- $ad_photos = array();
- $ad_photos[] = $value[$prefix_table . "photo"];
- $ad_photos[] = $value[$prefix_table . "photo_2"];
- $ad_photos[] = $value[$prefix_table . "photo_3"];
- $ad_photos[] = $value[$prefix_table . "photo_4"];
- $ad_photos[] = $value[$prefix_table . "photo_5"];
- /*
- A venir
- $ad_photos[] = $value[$prefix_table."_photo_6"];
- $ad_photos[] = $value[$prefix_table."_photo_7"];
- $ad_photos[] = $value[$prefix_table."_photo_8"];
- $ad_photos[] = $value[$prefix_table."_photo_9"];
- $ad_photos[] = $value[$prefix_table."_photo_10"];
- */
- foreach ($ad_photos as $photo) {
- if (strlen($photo) > 1) {
- $ad["photos"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
- // from detail
- if ($page == "detail_coloc.php" || $page == "detail.php" || $page == "detail_refnat.php" || $page == "fiche_visite.php" || $page == "home_ville.php" || $page == "resultats_refnat.php") {
- $ad["photos_multibox"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP_MULTIBOX, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
- $ad["thumbs"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_CROP_THUMB_DETAIL, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
- }
- // from results
- else {
- $ad["thumbs"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP_THUMB, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
- $ad["thumbs_detail"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_CROP_THUMB_DETAIL, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
- }
- $ad["photos_id"][] = $photo;
- ++$ad["photos_count"];
- }
- }
- if (isset($value[$prefix_table . "nb_photo"]) && !empty($value[$prefix_table . "nb_photo"])) {
- $ad["photos_count"] = (($value[$prefix_table . "nb_photo"] > 5) ? 5 : $value[$prefix_table . "nb_photo"]);
- }
- } else {
- if (strlen($value[$prefix_table . "photo"]) > 1) {
- $photo = $value[$prefix_table . "photo"];
- $ad["photos"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
- $ad["thumbs"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP_THUMB, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
- $ad["photos_id"][] = $value[$prefix_table . "photo"];
- $ad["photos_count"] = (($value[$prefix_table . "nb_photo"] > 5) ? 5 : $value[$prefix_table . "nb_photo"]);
- }
- }
- // ad multimedia
- for ($i = 1; $i < 6; $i++) {
- $key = $value[$prefix_table . "mmf_type_" . $i];
- $item = $value[$prefix_table . "mmf_" . $i];
- if ($key != "" && $item != "") {
- $ad["mmf"][get_mmf_type($key)][] = $item;
- }
- }
- for ($i = 1; $i < 6; $i++) {
- $ad["mmf_type_" . $i . "_count"] = count($ad["mmf"][$i]);
- }
- // ad logicode
- $ad["logicode"] = $value[$prefix_table . "logicode"];
- $ad["logicode"] = ($ad["logicode"] == "" ? $value[$prefix_table . "logicode_old"] : $ad["logicode"]);
- // ad hierarchy
- $ad["hierarchy"] = array();
- for ($i = 0; $i < 3; $i++) {
- // id de localité incohérent => pas ajouté
- if (($i == 2) && ($value[$prefix_table . "locality_" . $i] < 121)) {
- $value[$prefix_table . "locality_" . $i] = "";
- $value[$prefix_table . "default_town_" . $i] = "";
- continue;
- }
- $ad["hierarchy"][] = array("lct_id" => $value[$prefix_table . "locality_" . $i], "lct_name" => $value[$prefix_table . "default_town_" . $i]);
- }
- // ad localisation
- $ad["default_town"] = $value[$prefix_table . "default_town"];
- for ($i = 0; $i < 3; $i++) {
- // id de localité incohérent => pas ajouté
- if (($i == 2) && ($value[$prefix_table . "locality_" . $i] < 121)) {
- $value[$prefix_table . "locality_" . $i] = "";
- $value[$prefix_table . "default_town_" . $i] = "";
- continue;
- }
- $ad["default_town_" . $i] = $value[$prefix_table . "default_town_" . $i];
- }
- // Florian - 19/07/2010
- // Test temporaire pour loc/coloc pour gérer les couples clé/label de localité invalide
- // => Pourrait être étendu à la vente mais conséquences imprévisibles !
- if ($_global['univers'] == '8' || $_global['univers'] == '2') {
- for ($i = 2; $i >= 0; $i--) {
- /* * *******************************************************************
- * ANNULATION DU TEST POUR AVOIR LES lct_id/lct_level TOUT LE TEMPS
- *
- // Si la ville n'est pas vide et que la clé est valide
- if ($value[$prefix_table."_default_town_".$i]!="" && $value[$prefix_table."_locality_".$i]!='0')
- {
- * ******************************************************************** */
- if (isset($value[$prefix_table . "default_town_" . $i]) && ($value[$prefix_table . "default_town_" . $i] != "") && ($value[$prefix_table . "locality_" . $i] != '0')) {
- // Si la clé de localité est la même que le parent, on utilise le parent
- if ($value[$prefix_table . "locality_" . $i] == $value[$prefix_table . "locality_" . ($i - 1)])
- continue;
- $ad["real_town"] = $value[$prefix_table . "default_town_" . $i];
- $ad["lct_id"] = $value[$prefix_table . "locality_" . $i];
- $ad["lct_level"] = $i;
- break;
- }
- }
- }
- else {
- for ($i = 2; $i >= 0; $i--) {
- if (isset($value[$prefix_table . "default_town_" . $i]) && ($value[$prefix_table . "default_town_" . $i] != "") && ($value[$prefix_table . "locality_" . $i] != '0')) {
- $ad["real_town"] = $value[$prefix_table . "default_town_" . $i];
- $ad["lct_id"] = $value[$prefix_table . "locality_" . $i];
- $ad["lct_level"] = $i;
- break;
- }
- }
- }
- //error_log(print_r($ad, true), 3, "/tmp/bmo.log");
- if (trim($ad['default_town']) == '')
- $ad['default_town'] = $ad['default_town_2'];
- //SARA A. 12/05/09 relais lux
- $ad["lct_0"] = $value[$prefix_table . "locality_0"];
- $ad["lgm_id"] = $value["lgm_id"];
- $ad["lgc_id"] = $value["lgc_id"];
- $ad["lgn_id"] = $value["lgn_id"];
- $ad["lzip"] = $value[$prefix_table . "post_code"];
- $ad["szip"] = substr($ad["lzip"], 0, 2);
- $ad["real_zip"] = ($ad["lct_level"] == '1' ? $ad["szip"] : $ad["lzip"]); // CP correspondant à la localité calculée
- $ad["country"] = $value[$prefix_table . "country"];
- $ad["default_proximity"] = $value[$prefix_table . "default_proximity"];
- $ad["default_sector"] = $value[$prefix_table . "default_sector"];
- $ad["default_sector"] = (strtolower($value[$prefix_table . "default_sector"]) == 'a' ? '' : $value[$prefix_table . "default_sector"]);
- /*
- //-- $ad["default_sector"] should not be displayed if $ad["default_town"]==$ad["default_sector"]
- //-- 20080820-XI
- if (!empty($ad["default_town"]) && !empty($ad["default_sector"]))
- {
- if ($ad["default_town"] == $ad["default_sector"])
- $ad["default_sector"] = "";
- }
- */
- // ad dates
- $ad["created_on"] = format_date_sql2ihm($value[$prefix_table . "first_online_date"]);
- $ad["modified_on"] = format_date_sql2ihm($value[$prefix_table . "update_date"]);
- $time_int = strtotime(date('Y-m-d H:i:s')) - strtotime($value[$prefix_table . "update_date"]);
- $ad["days_old"] = intval($time_int / 86400);
- if ($page == "detail_coloc.php" || $page == "resultats_coloc.php" || $page == "detail.php" || $page == "resultats.php" || $page == "resultats_gadget.php" || $page == "resultats_agence_annonces.php" || $page == "rssResultats.php" || $page == "confier_resultats.php" || $page == "home_be" || $page == "home_ville.php" || $page == "resultats_refnat.php") {
- // ad link
- if ($page == "confier_resultats.php") {
- $infos = $url . $value["id_annonce"];
- $ad["link"] = to_nat($infos, "confier_detail");
- } else {
-
- $infos = array(
- 'id' => $value["id_annonce"],
- 'type_transaction' => $ad["type_transaction"]
- );
- $ad["link"] = to_nat($infos, "detail");
- }
- // ad template
- $ad["tpl_code"] = "";
- $ad["tpl_name"] = "annonce";
- $ad["tpl_label_type"] = "";
- // Si c'est la première annonce et qu'elle est premium
- if (($has_premium > 0 && $idx == 0) || $ad['premium'] > 0) {
- $ad["tpl_code"] = "p";
- $ad["tpl_name"] = "premium";
- $ad["tpl_label_type"] = LABEL_RESULT_PREMIUM;
- // Si c'est la première annonce et qu'elle est orpi
- } else if ($ad['is_exclusive'] == 2) {
- $ad["tpl_code"] = "o";
- $ad["tpl_name"] = "orpi";
- $ad["tpl_label_type"] = 'Eclusivité ORPI';
- } else if($ad['type_transaction'] == 5) {
- $ad["tpl_code"] = "9";
- $ad["tpl_name"] = "neuf";
- $ad["tpl_label_type"] = 'Neuf';
- } else if( ($ad["days_old"] <= DAYS_TO_BE_NEW) && !SUPP_NOUVEAUTE){
- $ad["tpl_code"] = "n";
- $ad["tpl_name"] = "nouveau";
- $ad["tpl_label_type"] = LABEL_RESULT_NEW_AD;
- }
- }
- // ad pub
- $ad["antenna"] = str_pad(get_pub_data($value[$prefix_table . "pub_code"], "area1"), 3, "0", STR_PAD_LEFT);
- // ad origin import + origin import id
- $ad["origin_import"] = $value[$prefix_table . "origin_import"];
- $ad["origin_import_id"] = $value[$prefix_table . "origin_import_id"];
- //ad disctrict
- if (is_in_district_area($ad) && (!DISABLE_DISTRICT)) {
- for ($i = 1; $i <= 3; $i++) {
- $ad["district_id_" . $i] = $value[$prefix_table . "district_id" . $i];
- $ad["district_name_" . $i] = $value[$prefix_table . "district_name" . $i];
- if ($page == 'detail.php' && isset($ad["district_id_" . $i]) && (0 != $ad["district_id_" . $i]) ) {
- $ad["district_polygone_" . $i] = getPolygoneByDistrictId($ad["district_id_" . $i]);
- }
-
- }
- $str_quartiers = (!empty($ad["district_name_1"])) ? $ad["district_name_1"] : "";
- $str_quartiers .= (!empty($ad["district_name_2"])) ? "/" . $ad["district_name_2"] : "";
- $str_quartiers .= (!empty($ad["district_name_3"])) ? "/" . $ad["district_name_3"] : "";
- $districts = explode('/', $str_quartiers);
- foreach ($districts as $k => $v) {
- $districts[$k] = ucfirst($v);
- }
- $ad['district_to_use'] = implode($districts, '/');
- }
- $ad['is_phonemandatory4contact'] = $value[$prefix_table . '_is_phonemandatory4contact'];
-
- // Bandeau personnalisable
- if ( isset($value[$prefix_table . 'personnalisable']) && !empty($value[$prefix_table . 'personnalisable']) && (0 != $value[$prefix_table . 'personnalisable']) ) {
- $ad['libelle_bandeau'] = mb_strtoupper(getLibellePersonnalisable($value[$prefix_table . 'personnalisable']),'UTF-8');
- //$ad['libelle_bandeau'] = mb_strtoupper($_LI_BANDEAU_PERSO_FR[$value[$prefix_table . '_personnalisable']], 'UTF-8');
- }
-
- // agency data
- $ag["id"] = $value["id_agence"];
- $ag["id_presto"] = $value["id_presto"];
- $ag["name"] = trim($value[$prefix_table . "name_agency"]);
- //-- Set 'AGENCE' + name of the agency if id_type_agence = 1, 2 or 3
- if (strtoupper(substr($ag["name"], 0, strlen(LABEL_COMMON_AGENCY))) != strtoupper(LABEL_COMMON_AGENCY) && ($value["id_type_agence"] == 1 || $value["id_type_agence"] == 2 || $value["id_type_agence"] == 3)) {
- $ag["name"] = strtoupper(LABEL_COMMON_AGENCY) . " " . $ag["name"];
- } elseif (strtoupper(substr($ag["name"], 0, strlen(LABEL_COMMON_CONSTRUCT))) != strtoupper(LABEL_COMMON_CONSTRUCT) && $value["id_type_agence"] == 5) {
- $ag["name"] = strtoupper(LABEL_COMMON_CONSTRUCT) . " " . $ag["name"];
- } elseif (strtoupper(substr($ag["name"], 0, strlen(LABEL_COMMON_PROMOT))) != strtoupper(LABEL_COMMON_PROMOT) && $value["id_type_agence"] == 4) {
- $ag["name"] = strtoupper(LABEL_COMMON_PROMOT) . " " . $ag["name"];
- } elseif (strtoupper(substr($ag["name"], 0, strlen(LABEL_COMMON_PUB_AGENCY))) != strtoupper(LABEL_COMMON_PUB_AGENCY) && $value["id_type_agence"] == 9) {
- $ag["name"] = strtoupper(LABEL_COMMON_PUB_AGENCY) . " " . $ag["name"];
- }
- // W.asbaiti 09/02/11 ajout ORPI au debut du nom de l'agence si c'est une annonce exlusive
- if ($is_exclusive) {
- if (stripos($ag["name"], 'orpi') === false)
- $ag["name"] = 'ORPI ' . $ag["name"];
- }
- $ag["address"] = $value[$prefix_table . "address_agency"];
- $ag["lzip"] = $value[$prefix_table . "post_code_agency"];
- $ag["town"] = $value[$prefix_table . "town_agency"];
- $ag["country"] = $value[$prefix_table . "country_agency"];
- $ag["tel"] = format_phone($value[$prefix_table . "tel_agency"], $ag["country"]);
- // 20090410-1-XI, Retrieving xxx_tel2_agency
- //if (!empty($value[$prefix_table."_tel2_agency"]))
- // $ag["tel"] .= " - ".format_phone($value[$prefix_table."_tel2_agency"], $ag["country"]);
- $ag["fax"] = format_phone($value[$prefix_table . "fax_agency"], $ag["country"]);
- $ag["email"] = $value[$prefix_table . "email_agency"];
- $website = $value[$prefix_table . "site_agency"];
- if (checkWebsite($website)) {
- $ag["site"] = $website;
-
- $ag["site_desc"] = str_limit($ag["site"], 32);
- } else {
- $value[$prefix_table . "is_website_agency"] = 0;
- $ag["site"] = '';
- $ag["site_desc"] = '';
- }
- $ag["rcs"] = $value[$prefix_table . "rcs_agency"];
- $ag["rcs"] = ($ag["rcs"] == "" ? LABEL_COMMON_RCS_UNKNOWN : $ag["rcs"]);
- $ag["logo"] = $value[$prefix_table . "logo_agency"];
- $ag['is_exclusive'] = $is_exclusive;
- if ($is_exclusive && CURRENT_EXCLUSIVE_IMG != '') {
- $ag["logo"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO . '.png';
- $ag["logo_small"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO_SMALL . '.png';
- $ag["logo_thumb"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO_THUMB . '.png';
- } else {
- $ag["logo"] = $value[$prefix_table . "logo_agency"];
- // checks if logo_agency is properly filled
- $chk_ag_logo = explode(".", $ag["logo"]);
- $ag["logo"] = ($chk_ag_logo[1] != "" ? $ag["logo"] : "");
- if ($ag["logo"] != "") {
- $ag["logo_small"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO_SMALL . '_' . $ag["logo"], $ag['id'], 'logo');
- $ag["logo_thumb"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO_THUMB . '_' . $ag["logo"], $ag['id'], 'logo');
- $ag["logo"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO . '_' . $ag["logo"], $ag['id'], 'logo');
- } else {
- $ag["logo_small"] = "";
- $ag["logo"] = "";
- }
- }
- $ag["franchising_agency"] = strtoupper(str_replace(" ", "", $value[$prefix_table . "franchising_agency"]));
- $ag["spoken_language"] = $value[$prefix_table . "spoken_language_agency"];
- // POWERSITE
- $ag["is_powersite"] = $value[$prefix_table . "is_powersite_agency"];
- $ag["powersite_url"] = $value[$prefix_table . "powersite_url_agency"];
- $ag['is_phone_required'] = $value[$prefix_table . "powersite_calltracking_agency"];
- // Modif WALID.ASBAITI 25/01/10
- // Annulation temporaire de Polco
- if (ACTIV_POLCO == 1) {
- $ag["is_logo_agency"] = $value[$prefix_table . "is_logo_agency"];
- $ag["is_directory_agency"] = $value[$prefix_table . "is_directory_agency"];
- $ag["is_website_agency"] = $value[$prefix_table . "is_website_agency"];
- } else {
- $ag["is_logo_agency"] = 1;
- $ag["is_directory_agency"] = 1;
- $ag["is_website_agency"] = 1;
- }
- $ag["is_website"] = $ag["is_website_agency"];
-
- if ($ad['type_transaction'] == '5') {
- $s_seo = '';
- if (!empty($ad['prg_title'])) {
- $s_seo .= $ad['prg_title'];
- }
- if (!empty($ad['property_type'])) {
- if ($s_seo != '') {
- $s_seo .= ' - ';
- }
- $s_seo .= $ad['property_type'];
- }
- if (!empty($ad['nb_rooms'])) {
- if ($ad["nb_rooms"] == 1) {
- $s_piece = LABEL_COMMON_ROOM_UNIT;
- } else {
- $s_piece = LABEL_COMMON_ROOMS_UNIT;
- }
- if ($s_seo != '') {
- $s_seo .= ' - ';
- }
- $s_seo .= $ad['nb_rooms'] . ' ' . $s_piece;
- }
- if (!empty($ad['area'])) {
- if ($s_seo != '') {
- $s_seo .= ' - ';
- }
- $s_seo .= $ad['area'] . LABEL_COMMON_AREA_UNIT . " " . LABEL_RESULTS_ABOUT;
- }
- if (!empty($ad['prg_title']) || !empty($ad['area']) || !empty($ad['nb_rooms'])) {
- if ($s_seo != '') {
- $s_seo .= ' - ';
- }
- }
- $ad['seo'] = $s_seo;
- }
- // debug
- if ($_global["debug"] == 1) {
- print_r($ad);
- echo("<hr>");
- }
- // return
- return array($ad, $ag);
- }
- function checkWebsite(&$website) {
- // Tester http ou https
- $website = str_replace(' ', '%20', $website);
- if (substr($website, 0, 4) != 'http')
- $website = 'http://' . $website;
- /*
- $regexp =
- '^(?#Protocol)(?:https?\:\/\/)?'.
- '(?:'.
- '(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))'.
- '|'.
- '(?#IpDomain)(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'.
- ')'.
- '(?#Port)(?::[\d]{1,5})?'.
- '(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?'.
- '(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*'.
- '(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$';
- */
- $regexp = '^(?#Protocol)(?:https?\:\/\/)?(?:(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))|(?#IpDomain)(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$';
- return preg_match('`' . $regexp . '`', $website) > 0;
- }
- /**
- * Returns agency data
- *
- * @param unknown_type $page
- * @param unknown_type $value
- * @return unknown
- */
- function get_ag_data($page, $value) {
-
- global $_global;
- // echo "<pre>";print_r($value);echo "</pre>";
- // arrays
- $ag = array();
- // agency identifiers
- $ag["id"] = $value["id_agence"];
- $ag["id_presto"] = $value["id_presto"];
- $ag["real_rcs"] = $value["agc_rcs"];
- $ag["rcs"] = ($ag["real_rcs"] == "" ? LABEL_COMMON_RCS_UNKNOWN : $ag["real_rcs"]);
- // agency data
- $ag["company_name"] = $value["agc_company_name"];
- $ag["name"] = $value["agc_name"];
- $ag["franchising"] = $value["agc_franchising"];
-
-
- /*
- * W.ASBAITI 14/12/2012 : Si la desc est vide, on remplace par un texte friendly SEO
- */
- if(empty($value["agc_description"])) {
- $ag["description"] = "L'agence immobilière ".$ag["name"]." propose des biens immobiliers pour la vente et la location. Consultez notre fiche agence et retrouvez l'intégralité de nos annonces : maison, appartement, villa, terrain.";
- }else {
- $ag["description"] = $value["agc_description"];
- }
- // agency premium
- $ag["premium"] = $value["agc_is_premium"];
- // agc_franchising_order est à 1 si pack exclu (cf search_class)
- $ag["is_exclusive"] = (bool) $value["agc_franchising_order"];
- if ($ag["is_exclusive"] && CURRENT_EXCLUSIVE_IMG != '') {
- $ag["logo"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO . '.png';
- $ag["logo_thumb"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO_THUMB . '.png';
- } else {
- // agency pictures
- $ag["logo"] = $value["agc_logo"];
- // new
- if ($ag["logo"] != "") {
- $ag["logo_thumb"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO_THUMB . '_' . $ag["logo"], $ag['id'], 'logo');
- $ag["logo"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO . '_' . $ag["logo"], $ag['id'], 'logo');
- } else {
- $ag["logo_thumb"] = "";
- $ag["logo"] = "";
- }
- }
- // ad hierarchy
- $ag["hierarchy"] = array();
- for ($i = 0; $i < 3; $i++) {
- $ag["hierarchy"][] = array("lct_id" => $value["agc_loc_id_" . $i], "lct_name" => $value["agc_town_agency_" . $i]);
- }
- // agency localisation
- $ag["town_agency"] = $value["agc_town_agency"];
- $ag["town"] = $ag["town_agency"];
- for ($i = 4; $i >= 0; $i--) {
- if ($value["agc_town_agency_" . $i] != "") {
- $ag["town_agency"] = $value["agc_town_agency_" . $i];
- $ag["lct_id"] = $value["agc_loc_id_" . $i];
- $ag["lct_level"] = $i;
- break;
- }
- }
- $ag["lgc_id"] = $value["lgc_id"];
- $ag["lgn_id"] = $value["lgn_id"];
- $ag["address"] = $value["agc_address"];
- $ag["lzip"] = $value["agc_post_code"];
- $ag["szip"] = substr($ag["lzip"], 0, 2);
- $ag["country"] = $value["agc_country"];
- // agency contact
- $ag["tel"] = format_phone($value["agc_tel"]);
- $ag["tel_2"] = (!empty($value["agc_tel_2"])) ? format_phone($value["agc_tel_2"]) : "";
- $ag["fax"] = format_phone($value["agc_fax"]);
- $ag["email"] = $value["agc_email"];
- $website = strtolower($value["agc_site"]);
- if (checkWebsite($website)) {
- $ag["site"] = $website;
- } else {
- $value[$prefix_table . "_is_website_agency"] = 0;
- $ag["site"] = '';
- }
- // agency counts
- $ag["rnt_count"] = $value["agc_rnt_count"];
- $ag["sal_count"] = $value["agc_sal_count"];
- $ag["count"] = $value["agc_count"];
- // POWERSITE
- $ag["is_powersite"] = $value["agc_is_powersite"];
- $ag["powersite_url"] = $value["agc_powersite_url"];
- $ag["powersite_calltracking"] = $value["agc_powersite_calltracking"];
- // PROJET POLCO (W.ASBAITI 14/01/10)
- if (ACTIV_POLCO == 1) {
- $ag["is_logo"] = $value["agc_is_logo"];
- $ag["is_directory"] = $value["agc_is_directory"];
- $ag["is_website"] = $value["agc_is_website"];
- } else {
- // ANNulation temporaire Polco
- // Walid ASBAITI 25/01/10
- $ag["is_logo"] = 1;
- $ag["is_directory"] = 1;
- $ag["is_website"] = 1;
- }
- // W.asbaiti 09/02/11 ajout ORPI au debut du nom de l'agence si c'est une annonce exlusive
- if ($ag["is_exclusive"]) {
- if (stripos($ag["name"], 'orpi') === false)
- $ag["name"] = 'ORPI ' . $ag["name"];
- }
- $ag['is_phonemandatory4contact'] = $value['agc_is_phonemandatory4contact'];
-
- return $ag;
- }
- /**
- * Returns image server
- *
- * @param unknown_type $id
- * @param unknown_type $key
- * @return unknown
- */
- function get_image_server($id, $key) {
- // script url
- $url = "getimage.php?v5=1&";
- // key
- switch ($key) {
- // ad
- case "AD" :
- $url .= "path=thumb&wm=440&hm=330&type=prop&id=";
- break;
- case "AD_MULTIBOX" :
- $url .= "path=thumb&wm=800&hm=600&type=prop&id=";
- break;
- case "AD_THUMB" :
- $url .= "path=thumb&wm=182&hm=136&type=prop&id=";
- break;
- case "AD_THUMB_DETAIL" :
- $url .= "path=thumb&wm=69&hm=53&type=crop&id=";
- break;
- // agency
- case "AG" :
- $url .= "db=presto&path=logo_agence_thumb&type=prop&wm=260&hm=160&id=";
- break;
- case "AG_SMALL" :
- $url .= "db=presto&path=logo_agence_thumb&type=prop&wm=60&hm=40&id=";
- break;
- case "AG_THUMB" :
- $url .= "db=presto&path=logo_agence_thumb&type=prop&wm=137&hm=105&id=";
- break;
- case "HOME_GALLERY" :
- $url .= "v5=1&path=thumb&wm=216&hm=161&type=crop&id=";
- }
- // return "http://images.logic-immo.com/".$url.$id;
- return "http://image" . (floor(hexdec(substr($id, 0, 3)) / 1024) + 2) . ".logic-immo.com/" . $url . $id;
- }
- /**
- * Returns pub data
- *
- * @param unknown_type $value
- * @param unknown_type $key
- * @return unknown
- */
- function get_pub_data($value, $key) {
- if ($value != "") {
- $value = explode(";", $value);
- for ($i = 0; $i < count($value); $i++) {
- $data = explode(":", $value[$i]);
- if ($data[0] == $key) {
- return $data[1];
- }
- }
- }
- }
- /**
- * Returns mmf type index
- *
- * @param unknown_type $label
- * @return unknown
- */
- function get_mmf_type($label) {
- for ($i = 1; $i < 6; $i++) {
- if (constant("AD_MMF_TYPE_" . $i) == $label) {
- return $i;
- }
- }
- }
- /**
- * Returns formatted number
- *
- * @param unknown_type $value
- * @param unknown_type $country
- * @return unknown
- */
- function format_phone($value, $country = "FR") {
- if ($value == "") {
- return;
- }
- if (empty($country))
- $country = 'FR';
- switch ($country) {
- case "FR" :
- $value = preg_replace("/[^0-9]/", "", $value);
- if (strlen($value) > 10) {
- $value = substr($value, -11);
- $value = preg_replace("/^3[30]/", "0", $value);
- }
- $value = preg_replace("/(..)(..)(..)(..)(..)$/", "$1 $2 $3 $4 $5", $value);
- break;
- }
- return $value;
- }
- /**
- * Returns parameter index
- *
- * @param unknown_type $name
- * @param unknown_type $value
- * @return unknown
- */
- function get_parameter_index($name, $value) {
- global $_LI_ADSURFACE;
- global $_LI_PRICERANGE;
- switch ($name) {
- case "area" :
- $values = $_LI_ADSURFACE;
- break;
- case "price" :
- $values = $_LI_PRICERANGE;
- break;
- }
- for ($i = 0; $i < count($values); $i++) {
- if ($value >= $values[$i]["from"] && $value <= $values[$i]["to"]) {
- return $i;
- }
- }
- }
- /**
- * Returns true if value is a guid
- *
- * @param unknown_type $value
- * @return unknown
- */
- function is_guid($value) {
- $pattern = "^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$";
- if (ereg($pattern, $value)) {
- return true;
- } else {
- return false;
- }
- }
- function check_email($email) {
- // Différentes parties de l'email avant l'arobase
- $atomChars = '[-a-z0-9àáâãäåæçèéêëìíîïñòóôõöœùúûüýÿß!#$%&\'*+\\/=?^_\`{|}~]';
- // Caractères autorisés après l'arobase (nom de domaine)
- $domainChars = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
- // Expression régulière finale pour l'email complet
- $regexp = '`^' . $atomChars . '+(?:\.' . $atomChars . '+)*@(' . $domainChars . '{1,63}\.)+' . $domainChars . '{2,63}$`i';
- $email = strtolower($email);
- return preg_match($regexp, $email);
- }
- /**
- * Returns "back to list" url
- *
- * @param unknown_type $page
- * @return unknown
- */
- function back_to_list($page, $is_agency = false) {
- global $_global;
- $back_to_list = "";
- switch ($page) {
- case "resultats.php":
-
- global $aLISearchHistoryCookieValue;
- // has a previous search been stored ?
- if ($_global["saved_searches"] > 0) {
- // retrieves last search parameters
- $back_to_list = build_search_url($page, $aLISearchHistoryCookieValue[0]);
- }
-
- break;
- }
- return $back_to_list;
- }
- /**
- * Returns a search url
- *
- * @param unknown_type $page
- * @param unknown_type $parameters
- * @return unknown
- */
- function build_search_url($page, $parameters) {
- global $_global;
- //$mode = ($page == "resultats_agence_annonces.php" ? "recherche_agence_annonce" : "recherche");
- if ($page == "resultats_agence_annonces.php" || $page == "resultats_agence_annonces_cz.php") {
- $mode = "recherche_agence_annonce";
- } else {
- $mode = "recherche";
- }
- $url_parameters = array();
- // loc_name
- $url_parameters["loc_name"] = $parameters["loc_name"];
- // loc_keys
- $loc_key_ok = false;
- if ($parameters["loc_key"] != "") {
- $loc_key_ok = true;
- $url_parameters["loc_key"] = $parameters["loc_key"];
- } else {
- for ($i = 1; $i <= SEARCH_FIELDS_NUMBER; $i++) {
- if (!empty($parameters["loc_key" . $i])) {
- $loc_key_ok = true;
- $url_parameters["loc_key" . $i] = $parameters["loc_key" . $i];
- $url_parameters["loc_name" . $i] = $parameters["loc_name" . $i];
- }
- }
- }
- // Si pas de loc_key, on retourne vide car l'url sera de toute facon invalide
- if (!$loc_key_ok)
- return '';
- // property type
- $url_parameters["ck_property_type"] = $parameters["ck_property_type"];
- // price
- $url_parameters["price"] = $parameters["price"];
- // patch cz
- $url_parameters["price_min"] = $parameters["price_min"];
- $url_parameters["price_max"] = $parameters["price_max"];
- // area
- $url_parameters["area"] = $parameters["area"];
- $url_parameters["area_min"] = $parameters["area_min"];
- $url_parameters["area_max"] = $parameters["area_max"];
- // nb_rooms
- /*
- $url_parameters["nb_rooms"] = $parameters["nb_rooms"];
- $url_parameters["nb_rooms_min"] = $parameters["nb_rooms_min"];
- $url_parameters["nb_rooms_max"] = $parameters["nb_rooms_max"];
- */
- $url_parameters["ck_nb_rooms"] = $parameters["ck_nb_rooms"];
- // offset
- if (isset($_REQUEST['p'])) {
- $num_row = (int) substr($_REQUEST['p'], 1);
- $url_parameters["offset"] = floor($num_row / MAX_RESULTS_PER_PAGE) + 1;
- }
- else
- $url_parameters["offset"] = $parameters["offset"];
- // order
- $url_parameters["order"] = $parameters["order"];
- // annonce visuel
- $url_parameters["an_visuel"] = $parameters["an_visuel"];
- /* START: RECHERCHE AVANCEE */
- /*
- // Avec photo, vidéo ou visite virtuelle
- $url_parameters["with_mmf"] = $parameters["with_mmf"];
- // Uniquement les nouveautés de moins de 2 semaines
- $url_parameters["recent_ads"] = $parameters["recent_ads"];
- // surface du terrain
- $url_parameters["surf"] = $parameters["surf"];
- $url_parameters["surf_min"] = $parameters["surf_min"];
- $url_parameters["surf_max"] = $parameters["surf_max"];
- // etage
- $url_parameters["floor"] = $parameters["floor"];
- $url_parameters["floor_min"] = $parameters["floor_min"];
- $url_parameters["floor_max"] = $parameters["floor_max"];
- // ascenseur
- $url_parameters["elevator"] = $parameters["elevator"];
- // gardien
- $url_parameters["caretaker"] = $parameters["caretaker"];
- // interphone
- $url_parameters["interphone"] = $parameters["interphone"];
- // balcon
- $url_parameters["balcony"] = $parameters["balcony"];
- // terrasse
- $url_parameters["terrace"] = $parameters["terrace"];
- // parquet
- $url_parameters["parquet"] = $parameters["parquet"];
- // cheminée
- $url_parameters["fireside"] = $parameters["fireside"];
- //placards
- $url_parameters["closets"] = $parameters["closets"];
- //cave
- $url_parameters["storage"] = $parameters["storage"];
- //parking
- $url_parameters["parking"] = $parameters["parking"];
- //garden
- $url_parameters["garden"] = $parameters["garden"];
- //pool
- $url_parameters["pool"] = $parameters["pool"];
- */
- /* STOP: RECHERCHE AVANCEE */
- // id agence
- if ($page == "resultats_agence_annonces.php") {
- $url_parameters["id_agence"] = $parameters["id_agence"];
- }
- if ($mode == "recherche_agence_annonce") {
- $url = add_parameters($page . "?" . http_build_query($url_parameters));
- } else {
- $url = to_nat(add_parameters($page . "?" . http_build_query($url_parameters)), $mode);
- //$url = to_nat(add_parameters($page."?".http_build_query($url_parameters)));
- }
- return $url;
- }
- /**
- * Returns true if page comes from Mars
- *
- * @param unknown_type $previous_url
- * @param unknown_type $page
- * @return unknown
- */
- function from_page($previous_url, $page) {
- if (strpos($_SERVER["HTTP_REFERER"], $_global["dns"]) && strpos($_SERVER["HTTP_REFERER"], $page)) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * Returns true if is external
- *
- * @return unknown
- */
- function is_external($check_referer = true) {
- global $_REQUEST;
- global $_global;
- if ($check_referer) {
- $is_external_referer = (
- empty($_SERVER["HTTP_REFERER"]) // Page de provenance inexistant (non précisée ou accès direct à l'url)
- || strpos($_SERVER["HTTP_REFERER"], $_global["dns"]) === false // Page de provenance n'appartient pas au site
- );
- }
- else
- $is_external_referer = false;
- return (
- isset($_REQUEST["logicode"]) && $_REQUEST["logicode"] == 1 // Recherche par logicode
- || isset($_REQUEST["gallery"]) && $_REQUEST["gallery"] == 1 // Lien de la gallerie
- || isset($_REQUEST["ext"]) && $_REQUEST["ext"] == 1 // ?
- || $is_external_referer
- );
- }
- /**
- * Returns true if is external
- *
- * @return unknown
- */
- function previous_page() {
- $subject = substr($_SERVER["HTTP_REFERER"], strlen($_global["dns"]));
- //resultats_agence_annonces.php
- $new_pattern_result_agc = 'agence-immobiliere/([^/]+)/annonces-(.*)';
- //resultats.php
- $new_pattern_result = '((vente|location|colocation)-immobilier)|(recherche-colocation)-(.*)';
- //detail.php
- $pattern_detail = 'detail-([a-z]*)-([-a-zA-Z0-9]*)';
- if (!$subject) {
- return;
- } else {
- if (preg_match("`" . $new_pattern_result . "`", $subject, $matches)) {
- return "resultats.php";
- } else if (preg_match("`" . $new_pattern_result_agc . "`", $subject, $matches)) {
- /* setcookie("id_exist", true); */
- return "resultats_agence_annonces.php";
- } else if (preg_match("`" . $pattern_detail . "`", $subject, $matches)) {
- return "detail.php";
- } else {
- return;
- }
- }
- }
- /**
- * Returns true if is a ref page
- *
- * @param unknown_type $page
- * @return unknown
- */
- function is_ref_page($page) {
- $pages = array();
- $pages[] = "annonce_dep.php";
- $pages[] = "annonce_ville.php";
- $pages[] = "annonce-ville.php";
- $pages[] = "annonce_location.php";
- $pages[] = "annonce-location.php";
- $pages[] = "annonce-region.php";
- $pages[] = "ref_ann.php";
- $pages[] = "ref_dep.php";
- $pages[] = "ref_liste_ann.php";
- $pages[] = "ref_ville.php";
- $pages[] = "ref_bien_liste.php";
- $pages[] = "ref_bien_detail.php";
- $pages[] = "rss_ville.php";
- $pages[] = "top-immobilier.php";
- return in_array($page, $pages);
- }
- /**
- * Returns szip / lzip
- *
- * @param unknown_type $data
- * @param unknown_type $mode
- * @return unknown
- */
- function get_zip_code($data, $mode) {
- $values = explode(",", $data[$mode][0]);
- return trim($values[0]);
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $sLockFileName
- * @param unknown_type $sLockFileDescription
- */
- function writeLockFile($sLockFileName, $sLockFileDescription) {
- error_log(date("d/m/Y H:i:s") . " - {$sLockFileDescription}\n", 3, "../LOCK/{$sLockFileName}.lockfile");
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $sLockFileName
- */
- function getLockFile($sLockFileName) {
-
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $sLockFileName
- * @return unknown
- */
- function checkLockFile($sLockFileName) {
- if (file_exists("../LOCK/{$sLockFileName}.lockfile") == true) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $sLockFileName
- */
- function removeLockFile($sLockFileName) {
- unlink("../LOCK/{$sLockFileName}.lockfile");
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $chaine
- * @param unknown_type $length
- * @return unknown
- */
- function truncate($chaine, $length = 50) {
- $return_chaine = "";
- $truncate = false;
- $array = preg_split("/([ .,;:!])/", $chaine, -1, PREG_SPLIT_OFFSET_CAPTURE);
- foreach ($array as $elt) {
- $chaine_ar[] = $elt[0];
- $ponctuations[] = substr($chaine, $elt[1] - 1, 1);
- }
- $return_chaine = $chaine_ar[0];
- for ($i = 1; $i < count($chaine_ar); $i++) {
- $element = $chaine_ar[$i];
- if (strlen($return_chaine . " " . $element) < $length) {
- $return_chaine .= $ponctuations[$i] . $element;
- } else {
- $truncate = true;
- }
- }
- if ($truncate) {
- $return_chaine .= "...";
- }
- $return_chaine = preg_replace("/([ .\,;:!]+?\.\.\.)$/x", "...", $return_chaine);
- return $return_chaine;
- }
- /**
- * Tronque un texte (mais pas les mots !) si trop long et rajoute des points de suspension
- *
- * @param unknown_type $text
- * @param unknown_type $ncar
- * @param unknown_type $scar
- * @return unknown
- */
- function truncate2($text, $ncar, $scar = "") {
- $trunc_text = $text;
- if (strlen($text) > $ncar) {
- $maxi_text = substr($text, 0, $ncar);
- $lpos = strrpos($maxi_text, ",");
- if ($lpos === FALSE) {
- $lpos = strrpos($maxi_text, " ");
- }
- if ($lpos == FALSE) {
- $maxi_text = substr($maxi_text, 0, ($ncar - 3));
- } else {
- $maxi_text = substr($maxi_text, 0, $lpos);
- }
- $trunc_text = $maxi_text;
- if ($scar != "") {
- $trunc_text = $trunc_text . $scar;
- }
- }
- return $trunc_text;
- }
- function truncate_article($text, $ncar) {
- $trunc_text = strip_tags(stripslashes(htmlspecialchars_decode(ucfirst($text))));
- if (strlen($trunc_text) > $ncar) {
- $trunc_text = substr($trunc_text, 0, $ncar);
- $lpos = strrpos($trunc_text, " ");
- $trunc_text = substr($trunc_text, 0, $lpos);
- }
- $trunc_text .= "...";
- return $trunc_text;
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $k1
- * @param unknown_type $n1
- * @param unknown_type $k2
- * @param unknown_type $n2
- * @return unknown
- */
- function loc2xiti($k1, $n1, $k2, $n2) {
- if ($k1 != "") {
- $a1 = explode('_', $k1);
- $a2 = explode("(", $n1);
- if ($a1[1] == 0) {
- $s1 = $a2[0];
- } else {
- $s1 = str_replace(')', '', str_replace('(', '', $a2['1']));
- }
- }
- unset($a1);
- unset($a2);
- if ($k2 != "") {
- $a1 = explode('_', $k2);
- $a2 = explode("(", $n2);
- if ($a1[1] == 0) {
- $s2 = $a2[0];
- } else {
- $s2 = str_replace(')', '', str_replace('(', '', $a2['1']));
- }
- }
- if ($s1 != "" && $s2 != "") {
- return "$s1,$s2";
- } else {
- return "$s1$s2";
- }
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $str
- * @return unknown
- */
- function format_footer_link($str) {
- global $_global;
- $replang = "";
- switch ($_global["site"]) {
- case "be":
- $replang = $_global["lang"] . "/";
- break;
- default:
- $replang = "";
- break;
- }
- if (!strstr($str, "a href=\"http"))
- $final = str_replace("a href=\"", "a href=\"/" . $replang, $str);
- else
- $final = $str;
- return($final);
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $iOperationCode
- * @param unknown_type $sPreSharedKey
- */
- function generateMd5MaintenanceString($iOperationCode, $sPreSharedKey) {
- //Generate a SHA1 key to authentify maintenance and remote script execution.
- //Get variables
- $strA = date("H"); //Current hour in 24h format with leading 0's
- $strA1 = (int) $strA; //Transform that string into an int w/o leading 0
- $strB = date("i"); //Minute in hour with trailing 0
- $strB1 = substr($strB, 0, 1); //Get ten number
- $strB2 = (int) substr($strB, 1, 1); //Get unit number
- $strC = date("w"); //Get day of week (0 = sunday, 6 = saturday
- $strD = date("n"); //Number of the month
- $strE = _FRONTSERVERID_; //Global variable defined in DB settings
- $strF = $iOperationCode; //Preset operation code - an alias to the instruction to run
- $strG = $sPreSharedKey; //Secret key.
- //Create salt: the salt format depends on the current minute (all servers must be timesynched.
- $sSalt = "";
- if ($strB2 >= 0 && $strB2 < 2) {
- $sSalt = $strA . $strB . $strC . $strD . $strE;
- } else if ($strB2 >= 2 && $strB2 < 4) {
- $sSalt = $strB . $strA . $strC . $strD . $strE;
- } else if ($strB2 >= 4 && $strB2 < 6) {
- $sSalt = $$strB . $strC . $strA . $strD . $strE;
- } else if ($strB2 >= 6 && $strB2 < 8) {
- $sSalt = $strA . $strB . $strC . $strD . $strA . $strE;
- } else {
- $sSalt = $strB . $strC . $strD . $strE . $strA;
- }
- //Create the full key. Key format depends on day of month:
- if ($strD % 2 == 0) {
- $sKey = md5($strF + $sSalt + $strG);
- } else {
- $sKey = md5($strG + $sSalt + $strF);
- }
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $sPreSharedKey
- * @param unknown_type $iOperationCode
- * @param unknown_type $aOperationArray
- * @param unknown_type $sKeyString
- * @return unknown
- */
- function checkSha1MaintenanceString($sPreSharedKey, $iOperationCode, $aOperationArray, $sKeyString) {
- //Generate a SHA1 key according to supplied variables and compare to the encoded key string
- if (generateMd5MaintenanceString($iOperationCode, $sPreSharedKey) == $sKeyString) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * Gestion de la redirection de page
- * Gére la presence des headers
- * Si les headers sont déja envoyés, on utilise la balise META
- *
- * @param unknown_type $url
- */
- function redirection($url) {
- if (headers_sent() || isset($GLOBALS[PHPSESSID])) {
- die('<meta http-equiv="refresh" content="0;URL=' . $url . '">');
- } else {
- header("Location: " . $url . "\n");
- //header("Location: http://".$_SERVER['HTTP_HOST']."".dirname($_SERVER['PHP_SELF'])."/".$url."\n");
- exit();
- }
- }
- /**
- * Gestion de la revisite Belge (modifiable pour les autres Pays)
- * Si pas de cookie on redirige sur la prehome
- *
- * @return unknown
- */
- function verif_cookie_prehome() {
- global $_global;
- $langisup = 0;
- $_global["revisite_belge"] = 0;
- if ($_global['site'] == "be") {
- $uri = split("/", $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"]);
- //var_dump($uri); //die();
- $array_uri_langue_site = array("fr", "en", "nl");
- if ($_global['site'] == "be" && in_array($uri[1], $array_uri_langue_site)) {
- $langisup = 1;
- }
- ob_start();
- $var_cook = array();
- if (!isset($_COOKIE['LI_NAVSITE']) && $langisup == 0) {
- redirection("http://" . $_SERVER["SERVER_NAME"] . "/prehome_be.php");
- ob_end_flush();
- return false;
- exit();
- }
- $var_cook = $_COOKIE["LI_NAVSITE"];
- if ($_SERVER['REQUEST_URI'] == "/") {
- setcookie("LI_NAVSITE[lang_site]", '', 0, "/");
- //On redirige dans la bonne langue si l'utilisateur accepte les cookies
- //et donc pas les moteurs de recherche
- if (setcookie("LI_NAVSITE[lang_site]", $_global['lang'], time() + (60 * 60 * 24 * 365), "/")) {
- ob_end_flush();
- //echo $var_cook["lang_site"];
- if (strpos($_SERVER["HTTP_REFERER"], "prehome") == 0) {
- //echo "REVISITE 2<hr>";
- $_global["revisite_belge"] = 1;
- }
- redirection("http://" . $_SERVER["SERVER_NAME"] . "/" . $var_cook["lang_site"] . "/");
- exit();
- }
- ob_end_flush();
- return false;
- } else {
- if (setcookie("LI_NAVSITE[lang_site]", $_global['lang'], time() + (60 * 60 * 24 * 365), "/")) {
- /*
- print_r($_COOKIE["LI_NAVSITE[lang_site]"]);
- echo "<br>COOKIE IS UPPPPPPP - ".$_global['lang']."<br>";
- */
- if (strpos($_SERVER["HTTP_REFERER"], "prehome") == 0) {
- //echo "REVISITE<hr>";
- $_global["revisite_belge"] = 1;
- }
- }
- }
- ob_end_flush();
- return true;
- }
- }
- /**
- * Vérification les nombres de refresh:
- * si<4 il affiche la pub_relais_neuf si non il passe
- *
- * @param unknown_type $val_relais
- * @return unknown
- */
- function pub_relais_neuf_cookie($val_relais) {
- $nb_relais_neuf = 0;
- if (isset($_COOKIE['nb_relais_neuf'])) {
- $nb_relais_neuf = $_COOKIE['nb_relais_neuf'];
- $nb_relais_neuf++;
- setcookie('nb_relais_neuf', $nb_relais_neuf, time() + 3600 * 12 * 24);
- } else {
- //unset($_COOKIE['nb_relais_neuf']);
- setcookie("nb_relais_neuf", 0, time() + 3600 * 12 * 24);
- }
- if ($nb_relais_neuf > $val_relais) {
- setcookie("nb_relais_neuf", 0, time() - 3600 * 12 * 24);
- }
- return ($nb_relais_neuf);
- }
- /**
- * Fonction permettant de vérifier la syntax de l'URL pour le site BE
- *
- */
- function Verif_Url_BE() {
- //Verif du site belge afin de conserver l'arborescence /fr /nl
- global $_global;
- if ($_global["site"] == "be") {
- $sub_url = 0;
- foreach ($_global["languages"]["be"] as $value) {
- //echo "VALUE LANG: ".$value;
- //if (strpos($_SERVER["HTTP_REFERER"], URL_SITE_BE.$value."/")===false)
- if (strpos($_SERVER["REQUEST_URI"], "/" . $value . "/") === false) {
- //echo "PAS DE LANGUE URL dans ".$_SERVER["HTTP_REFERER"]." pour ".URL_SITE_BE.$value."/";
- } else {
- $sub_url = 1;
- }
- }
- if ($sub_url == 0) {
- header("location: " . URL_SITE_BE);
- //echo "GO TO ==> ".URL_SITE_BE.' -- '.$_SERVER["HTTP_REFERER"];
- }
- }
- }
- /**
- * Retrouve le Loc_key en fonction d'un name et d'un level
- *
- * @param unknown_type $name
- * @param unknown_type $level
- * @param unknown_type $site
- * @param unknown_type $lang
- * @return unknown
- */
- function Get_Lockey_By_Name_Level($name, $level = 2, $site = "xx", $lang = "xx") {
- if ($site == "xx" || $lang == "xx") {
- return;
- }
- $site = strtoupper($site);
- $lang = strtolower($lang);
- $name = strtoupper($name);
- $sql = "SELECT lct_id FROM T_LOCALITY_LCT_" . $site . " ";
- $sql .= "WHERE lct_name_" . $lang . "='" . $name . "' ";
- $sql .= "AND lct_level=" . $level;
- //if (function_exists("pdoquery")){ echo "FUNCTIoN EXIST"; }
- $result_query = pdoquery($sql);
- return ($result_query[0]["lct_id"]);
- }
- /**
- * Retrouve la traduction d'un nom de Locname en fonction d'un LCT_ID et d'une Langue
- */
- function Get_Trad_Locname($lockey, $lang) {
- global $_global;
- $my_loc_id = trim($lockey);
- if (!strpos(trim($lockey), "_") === false) {
- $tab_loc_id = explode("_", trim($lockey));
- $my_loc_id = $tab_loc_id[0];
- }
- $rew_agency_locname = "";
- $sql = "SELECT lct_name_" . $lang . " as lct_name FROM T_LOCALITY_LCT_" . strtoupper($_global["site"]) . " ";
- $sql .="WHERE lct_id=" . $my_loc_id . " ";
- $sql .= $sql_where;
- //echo $sql;
- $res_agency_locname = pdoquery($sql);
- return $res_agency_locname[0]["lct_name"];
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $locname
- * @param unknown_type $lang
- * @return unknown
- */
- function Get_Trad_Locname_byname($locname, $lang) {
- global $_global;
- $locname = trim($locname);
- $pattern = array('/-/', '/_/');
- $replace = array(' ', ' ');
- $locname = preg_replace($pattern, $replace, $locname);
- if (!strpos(trim($lockey), "_") === false) {
- $tab_loc_id = explode("_", trim($lockey));
- $locname = $tab_loc_id[0];
- }
- $rew_agency_locname = "";
- $sql = "SELECT lct_name_" . $lang . " as lct_name FROM T_LOCALITY_LCT_" . strtoupper($_global["site"]) . " ";
- $sql .="WHERE lct_name_" . $_global["lang"] . "='" . $locname . "' ";
- $sql .= $sql_where;
- $res_agency_locname = pdoquery($sql);
- return $res_agency_locname[0]["lct_name"];
- }
- /**
- * Retrouve le nom et le code postal d'une localité
- *
- * @param unknown_type $loc_id
- * @param unknown_type $loc_level
- * @return unknown
- */
- function Get_CityName_PostCode_Lockey($loc_id, $loc_level) {
- global $_global;
- switch ($loc_level) {
- // code group
- case 98 :
- $sql = " SELECT '' AS name, lgc_post_code AS post_code";
- $sql .= " FROM TM_LOCGC_FR";
- $sql .= " WHERE lgc_id = '" . $loc_id . "'";
- break;
- // name group
- case 99 :
- $sql = " SELECT lgn_name_fr AS name, lgn_post_code AS post_code";
- $sql .= " FROM TM_LOCGN_FR";
- $sql .= " WHERE lgn_id = '" . $loc_id . "'";
- break;
- // standard
- default :
- $sql = " SELECT lct_name AS name, lct_post_code AS post_code";
- $sql .= " FROM TM_LOC_FR";
- $sql .= " WHERE lct_id = '" . $loc_id . "'";
- $sql .= " AND lct_level = '" . $loc_level . "'";
- break;
- }
- //echo $sql;
- $res = pdoquery($sql);
- return array($res[0]["name"], $res[0]["post_code"]);
- }
- /**
- * Fonction créée pour gérer l'affichage du libéllé 'Informations complémentaires :' dans les annonces
- * Si il n'y a pas de détail, on n'affiche pas le libéllé
- *
- * @param unknown_type $ad
- * @return unknown
- */
- function check_detail_exist($ad) {
- $val = true;
- if (
- //$ad["floor"] == "0" &&
- //$ad["garden_area"] == "0" &&
- //$ad["terrace_area_1"] == "0" &&
- //$ad["balcony_area_1"] == "0" &&
- $ad["is_pool"] == "0" &&
- $ad["pool_area"] == "0" &&
- //$ad["nb_garage"] == "0" &&
- //$ad["nb_parking"] == "0" &&
- $ad["is_parking_closed"] == "0" &&
- $ad["nb_covered_parking"] == "0" &&
- $ad["nb_uncovered_parking"] == "0" &&
- $ad["is_renovated"] == "0" &&
- //strtotime($ad["renovating_date"]) == "943916400" && //0000-00-00 00:00:00
- $ad["need_renovating"] == "0" &&
- $ad["nb_caretaker"] == "0" &&
- $ad["is_interphone"] == "0" &&
- $ad["is_doorcode"] == "0" &&
- //$ad["is_elevator"] == "0" &&
- //$ad["nb_bath"] == "0" &&
- ($ad["nb_shower"] == "0" || $ad["nb_shower"] == '') &&
- $ad["is_independant_toilet"] <> "1" &&
- $ad["is_first_floor_toilet"] <> "1" &&
- //$ad["is_central_heating"] == "" &&
- //$ad["is_individual_heating"]== "" &&
- //$ad["is_electrical_heating"]== "" &&
- //$ad["is_floor_heating"] == "" &&
- //$ad["is_gas_heating"] == "" &&
- //$ad["is_diesel_heating"] == "" &&
- $ad["is_aircon"] == "0" &&
- $ad["is_chimney"] == "0" &&
- //$ad["is_wooden_floor"] == "0" &&
- //$ad["is_tiled_floor"] == "0" &&
- $ad["is_alarm"] == "0"
- //$ad["is_sunny"] == "0" &&
- //$ad["is_calm"] == "0" &&
- //($ad["facing"] == "0" || $ad["facing"] == "") &&
- //$ad["is_handicap_access"] == "0" &&
- //$ad["agency_rent_fees"] == "" &&
- //$ad["is_closet"] == "0" &&
- //$ad["is_basement"] == "0"
- ) {
- //echo "No detail exist";
- $val = false;
- }
- return $val;
- }
- function check_equipment_exist($ad) {
- $val = true;
- if (
- $ad["floor"] == "0" &&
- $ad["garden_area"] == "0" &&
- $ad["terrace_area_1"] == "0" &&
- $ad["balcony_area_1"] == "0" &&
- $ad["nb_garage"] == "0" &&
- $ad["nb_parking"] == "0" &&
- $ad["is_elevator"] == "0" &&
- ($ad["nb_bath"] == "0" || $ad["nb_bath"] == "")
- ) {
- //echo "No equipment exist";
- $val = false;
- }
- return $val;
- }
- function check_namely_exist($ad) {
- $val = true;
- if (
- $ad["is_wooden_floor"] == "0" &&
- $ad["is_tiled_floor"] == "0" &&
- $ad["is_sunny"] == "0" &&
- $ad["is_calm"] == "0" &&
- ($ad["facing"] == "0" || $ad["facing"] == "") &&
- $ad["is_handicap_access"] == "0" &&
- $ad["is_closet"] == "0" &&
- $ad["is_basement"] == "0"
- ) {
- //echo "No namely exist";
- $val = false;
- }
- return $val;
- }
- /**
- * Permet d'afficher le bloc (bleu: type moteur de recherche) mais sans le formulaire de recherche
- * On peut passer un titre a placer dans le bloc en parametre
- *
- * @param unknown_type $title
- * @param unknown_type $classeid
- */
- function create_block_nosearch($title = "TITLE HERE .... ", $classeid = "contactus") {
- echo "<div id=\"$classeid\">";
- echo " <div id=\"contactustop\"><img class=\"fr_search_top\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
- echo " <div id=\"contactuscontent\"><h1>$title</h1></div>";
- echo " <div id=\"contactusbottom\"><img class=\"fr_search_bottom\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
- echo "</div>";
- }
- /**
- * Create_block_nosearch en deux colonnes
- *
- * @param unknown_type $title
- * @param unknown_type $classeid
- */
- function create_block_nosearch2($title = "TITLE HERE .... ", $classeid = "small_search") {
- echo "<div id=\"$classeid\">";
- echo " <div id=\"smallsearchtop\"><img src=\"" . get_urlmmf('/search/corner_top_left.gif') . "\" height=\"5\" width=\"6\" /></div>";
- echo " <div id=\"smallsearchcontent\" style=\"font-size:15px;text-transform:uppercase;\"><h1>$title</h1></div>";
- echo " <div id=\"smallsearchbottom\"><img src=\"" . get_urlmmf('/search/corner_bottom_left.gif') . "\" height=\"5\" width=\"6\" /></div>";
- echo "</div>";
- }
- /**
- * Permet d'afficher le bloc (bleu: type moteur de recherche) mais sans le formulaire de recherche
- * On peut passer un titre a placer dans le bloc en parametre pas de <h1>...</h1> ni <h2>...</h2> ni rien
- *
- * @param unknown_type $title
- * @param unknown_type $classeid
- */
- function create_block_nosearch3($title = "TITLE HERE .... ", $classeid = "contactus") {
- echo "<div id=\"$classeid\">";
- echo " <div id=\"contactustop\"><img class=\"fr_search_top\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
- echo " <div id=\"contactuscontent\" class=\"title\">$title</div>";
- echo " <div id=\"contactusbottom\"><img class=\"fr_search_bottom\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
- echo "</div>";
- }
- /**
- * Qui prend en charge les caratères accentués (Fonction type strtoupper de PHP)
- *
- * @param unknown_type $chaine
- * @return unknown
- */
- function uc_strtoupper_fr($chaine) {
- $chaine = strtoupper($chaine);
- //$chaine = utf8_decode($chaine);
- $chaine = trim($chaine);
- $chaine = strtr($chaine, "äâà áåãéèëêòóôõöøìÃîïùúûüýñçþÿæœðø", "ÄÂÀÃ�ÅÃÉÈËÊÒÓÃ�?ÕÖØÌÃ�ÃŽÃ�ÙÚÛÜÃ�ÑÇÞÃ�ÆŒÃ�Ø");
- //$chaine = utf8_encode($chaine);
- return $chaine;
- }
- /**
- * Permet de retrouver un nom de locname "EGAL A" $name (Function lié au nouveau T9 ouvert)
- *
- * @param unknown_type $name
- * @param unknown_type $like
- * @return unknown
- */
- function find_locname_by_name($name, $like = 0) {
- global $_global;
- $name = strtoupper(trim($name));
- $name = str_replace("'", "\'", $name);
- if ($like == 1)
- $operateur = "LIKE '" . $name . "%'";
- else
- $operateur = "= '" . $name . "'";
- $site = strtoupper($_global["site"]);
- $lang = $_global["lang"];
- $sql = "SELECT SQL_CALC_FOUND_ROWS lct_id, lct_name_" . $lang . ", lct_level, lct_post_code, lgn_id ";
- $sql .= "FROM TM_LOC_" . $site . " ";
- $sql .= "WHERE lct_name_" . $lang . " " . $operateur . " ";
- $sql .= "LIMIT 0, 20";
- if ($_global["debug"] == 3) {
- echo "<hr />find_locname_by_name() - 1<br />";
- echo $sql;
- echo "<hr />";
- }
- /* Count TOTAL sans le limit */
- $sql_count = "SELECT FOUND_ROWS() as count";
- if ($_global["debug"] == 3) {
- echo "<hr />find_locname_by_name() - 2<br />";
- echo $sql_count;
- echo "<hr />";
- }
- $res_locname['res'] = pdoquery($sql);
- $res_locname['count'] = pdoquery($sql_count);
- return $res_locname;
- }
- /**
- * Permet de retrouver un nom de locname "EGAL A" $name (function lié au nouveau T9 ouvert)
- *
- * @param unknown_type $name
- * @param unknown_type $like
- * @return unknown
- */
- function find_locname_by_czip($czip, $like = 0) {
- global $_global;
- $czip = trim($czip);
- if ($like == 1)
- $operateur = " LIKE ('" . $czip . "%') ";
- else
- $operateur = "= '" . $czip . "' ";
- $site = strtoupper($_global["site"]);
- $lang = $_global["lang"];
- $sql = "SELECT SQL_CALC_FOUND_ROWS lct_id, lct_name_" . $lang . ", lct_level, lct_post_code, lgc_id FROM TM_LOC_" . $site;
- $sql .= " WHERE lct_post_code " . $operateur . " AND lct_level <> 0 ORDER BY lct_level ASC LIMIT 0, 20";
- //Debug
- if ($_global["debug"] == 3) {
- echo "<hr />find_locname_by_czip() - 1<br/>";
- echo $sql;
- echo "<hr />";
- }
- /* Count TOTAL sans le limit */
- $sql_count = "SELECT FOUND_ROWS() as count";
- //Debug
- if ($_global["debug"] == 3) {
- echo "<hr />find_locname_by_czip() - 2<br/>";
- echo $sql_count;
- echo "<hr />";
- }
- $res_locname['res'] = pdoquery($sql);
- $res_locname['count'] = pdoquery($sql_count);
- return $res_locname;
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $filename
- * @return unknown
- */
- function sort_files_edito($filename) {
- $tabs = scandir($filename);
- $Idfile = array();
- foreach ($tabs as $tab) {
- if (!(preg_match("/bak/", $tab))) {
- if ($tab != "." && $tab != "..") {
- $Idfile[] = substr($tab, 0, strpos($tab, "."));
- }
- }
- }
- sort($Idfile);
- return array_reverse($Idfile);
- }
- /**
- * Generate absolute url for links (used by logic-immo.com, vacances.logic-immo.com, ville.logic-immo.com...)
- *
- * V5 : dev.www.logic-immo.com, dev.<ville>.logic-immo.com, dev.vacances.logic-immo.com... / pp.www.logic-immo.com, pp.<ville>.logic-immo.com, pp.vacances.logic-immo.com / www.logic-immo.com, <ville>.logic-immo.com, vacances.logic-immo.com
- * V6 : dev2.www.logic-immo.com, dev2.<ville>.logic-immo.com, dev2.vacances.logic-immo.com... / pp2.www.logic-immo.com, pp2.<ville>.logic-immo.com, pp2.vacances.logic-immo.com / www.logic-immo.com, <ville>.logic-immo.com, vacances.logic-immo.com
- *
- * @param string $page
- * @param string $subdomain
- * @param string $domain
- * @param string $protocol
- * @return string
- */
- function to_url($page = "", $subdomain = "", $domain = "", $protocol = "") {
- // Attention !!
- // $domain et $protocol ne sont pas pris en compte
- if ($domaine != '') {
-
- }
- if (string_begins_with($page, "http://"))
- return $page;
- if ($page != '' && $page[0] == '/')
- $page = substr($page, 1);
- if ($subdomain != '') {
- return str_replace('#SUBDOMAIN#', $subdomain, URL_DOMAIN_MASK) . $page;
- } else {
- return URL_SITE . $page;
- }
- }
- /**
- * Generate absolute domain part of url
- */
- function to_url_domain($subdomain = "", $domain = "", $protocol = "") {
- return to_url("", $subdomain, $domain, $protocol);
- }
- /**
- retourne une url en completant avec l'environement de recette
- * */
- function to_url_1($page, $s_domaine) {
- $s_environnement = get_prefix_environnement();
- $s_www = '';
- $s_www = ($s_environnement != 'www') ? 'www' : '';
- return "http://" . $s_www . $s_environnement . '.' . $s_domaine . '/' . $page;
- }
- /**
- * Retourne l'environement courant (prefix)
- * dommage on se base sur URL_DOMAIN_MASK car c'etait pas recommender de rajouter une constante dans chaque fichier de conf
- */
- function get_prefix_environnement() {
- preg_match('#\#\.(.+?)\.#', URL_DOMAIN_MASK, $a_array);
- $a_environement = array('vbx', 'rec', 'dev');
- if (in_array($a_array[1], $a_environement)) {
- return $a_array[1];
- } else {
- return "www";
- }
- }
- /**
- * Return the "host" part and the "page" part of an URL
- * (used to avoid <a href="url">txt</a> tags followed by Google Bot)
- * Ex: http://dev2.www.logic-immo.com/location-lyon/6C1E17A9-D835-913C-5735-8D902E87D11D.html
- * ==> "host" => "http://dev2.www.logic-immo.com" + "page" => "location-lyon/6C1E17A9-D835-913C-5735-8D902E87D11D.html"
- */
- function get_url_host_page($url, $keep_query_string = false) {
- $host_url = "";
- $page_url = "";
- // split the url into its different components
- $parts_url = parse_url($url);
- //echo "<pre>"; print_r($parts_url); echo "</pre>";
- if ($parts_url === FALSE) {
- return array($host_url, $page_url);
- }
- if (isset($parts_url["scheme"]) && !empty($parts_url["scheme"])) {
- $host_url .= $parts_url["scheme"] . "://";
- }
- if (isset($parts_url["host"]) && !empty($parts_url["host"])) {
- $host_url .= $parts_url["host"];
- }
- if (isset($parts_url["port"]) && !empty($parts_url["port"])) {
- $host_url .= ":" . $parts_url["port"];
- }
- // we ignore $parts_url["user"] and $parts_url["pass"] not used here for sure
- // removes an eventual trailing /
- if (string_ends_with($host_url, "/")) {
- $host_url = substr($host_url, 0, strlen($host_url) - 1);
- }
- if (isset($parts_url["path"]) && !empty($parts_url["path"])) {
- $page_url = $parts_url["path"];
- }
- if ($keep_query_string && !empty($parts_url["query"])) {
- $page_url .= "?" . $parts_url["query"];
- }
- if (!empty($parts_url["fragment"])) {
- $page_url .= "#" . $parts_url["fragment"];
- }
- // removes an eventual starting /
- if (string_begins_with($page_url, "/")) {
- $page_url = substr($page_url, 1, strlen($page_url));
- }
- return array($host_url, $page_url);
- }
- /**
- * Convertit une date venant de mysql pour l'afficher dans le back/front-office (YYYY-MM-DD -> DD/MM/YYYY)
- */
- function format_date_sql2ihm($the_date) {
- $conv_date = "";
- if (isset($the_date) && !empty($the_date) && ($the_date != "0000-00-00")) {
- $conv_date_jour = substr($the_date, 8, 2);
- $conv_date_mois = substr($the_date, 5, 2);
- $conv_date_annee = substr($the_date, 0, 4);
- if ($conv_date_jour != "00") {
- $conv_date .= $conv_date_jour;
- }
- if (($conv_date_jour != "00") && ($conv_date_mois != "00")) {
- $conv_date .= "/";
- }
- if ($conv_date_mois != "00") {
- $conv_date .= $conv_date_mois;
- }
- if (($conv_date_mois != "00") && ($conv_date_annee != "0000")) {
- $conv_date .= "/";
- }
- if ($conv_date_annee != "0000") {
- $conv_date .= $conv_date_annee;
- }
- }
- return $conv_date;
- }
- /* format une date */
- /*
- $s_date => date / datetime au format ANGLAIS (obligatoire)
- $s_format => type de formatage souhaité (ex : d-m-Y H:i:s)
- @exemple : print format_datetime('2012-01-03', 'd-m-Y H:i:s');
- */
- function format_datetime($s_date, $s_format) {
- $o_date = new DateTime($s_date);
- return $o_date->format($s_format);
- }
- /**
- * Convertit une chaîne en mettant en majuscule la première lettre de chaque mot
- * en prenant en compte les "-", et en laissant en minuscule les mots comme "en", "sur", etc.
- */
- function ucwords2($string) {
- $conv_string = $string;
- $conv_string = htmlspecialchars_decode($conv_string, ENT_QUOTES);
- $conv_string = str_replace("-", "¿ ", $conv_string);
- $conv_string = ucwords($conv_string);
- $conv_string = str_replace("¿ ", "-", $conv_string);
- $conv_string = str_replace(" D ", " d ", $conv_string);
- $conv_string = str_replace("-D ", "-d ", $conv_string);
- $conv_string = str_replace(" D'", " d'", $conv_string);
- $conv_string = str_replace("-D'", "-d'", $conv_string);
- $conv_string = str_replace(" De ", " de ", $conv_string);
- $conv_string = str_replace("-De-", "-de-", $conv_string);
- $conv_string = str_replace(" Du ", " du ", $conv_string);
- $conv_string = str_replace("-Du-", "-du-", $conv_string);
- $conv_string = str_replace(" Des ", " des ", $conv_string);
- $conv_string = str_replace("-Des-", "-des-", $conv_string);
- $conv_string = str_replace(" L ", " l ", $conv_string);
- $conv_string = str_replace("-L ", "-l ", $conv_string);
- $conv_string = str_replace(" L'", " l'", $conv_string);
- $conv_string = str_replace("-L'", "-l'", $conv_string);
- $conv_string = str_replace(" La ", " la ", $conv_string);
- $conv_string = str_replace("-La-", "-la-", $conv_string);
- $conv_string = str_replace(" Le ", " le ", $conv_string);
- $conv_string = str_replace("-Le-", "-le-", $conv_string);
- $conv_string = str_replace(" Les ", " les ", $conv_string);
- $conv_string = str_replace("-Les-", "-les-", $conv_string);
- $conv_string = str_replace(" A ", " à ", $conv_string);
- $conv_string = str_replace("-A ", "-à ", $conv_string);
- $conv_string = str_replace("-A-", "-à-", $conv_string);
- $conv_string = str_replace(" Au ", " au ", $conv_string);
- $conv_string = str_replace("-Au-", "-au-", $conv_string);
- $conv_string = str_replace(" Aux ", " aux ", $conv_string);
- $conv_string = str_replace("-Aux-", "-aux-", $conv_string);
- $conv_string = str_replace(" En ", " en ", $conv_string);
- $conv_string = str_replace("-En-", "-en-", $conv_string);
- $conv_string = str_replace(" Et ", " et ", $conv_string);
- $conv_string = str_replace("-Et-", "-et-", $conv_string);
- $conv_string = str_replace(" Sur ", " sur ", $conv_string);
- $conv_string = str_replace("-Sur-", "-sur-", $conv_string);
- $conv_string = str_replace(" Sans ", " sans ", $conv_string);
- $conv_string = str_replace("-Sans-", "-sans-", $conv_string);
- $conv_string = str_replace(" Sous ", " sous ", $conv_string);
- $conv_string = str_replace("-Sous-", "-sous-", $conv_string);
- if (strpos($conv_string, "d'") != false) {
- $pos = strpos($conv_string, "d'") + 1;
- $str = substr($conv_string, $pos + 1, 1);
- $conv_string = substr_replace($conv_string, strtoupper($str), $pos + 1, 1);
- }
- if (stripos($conv_string, "l'") !== false) {
- $pos = stripos($conv_string, "l'") + 1;
- $str = substr($conv_string, $pos + 1, 1);
- $conv_string = substr_replace($conv_string, strtoupper($str), $pos + 1, 1);
- }
- return $conv_string;
- }
- /**
- * Return the prefix to put before the french name of a departement
- */
- function prefix_dept_name($dept_code) {
- $dept_prfx = "";
- $dept_code = strtoupper($dept_code);
- if (strlen($dept_code) == 5) {
- $dept_code = str_replace('000', '', $dept_code);
- }
- if (in_array($dept_code, array("75", "974", "975", "976", "986", "98"))) {
- $dept_prfx = "à ";
- } else if (in_array($dept_code, array("01", "02", "03", "07", "09", "10", "11", "12", "27", "28", "34", "36", "37", "60", "61", "89", "91"))) {
- $dept_prfx = "dans l'";
- } else if (in_array($dept_code, array("14", "15", "18", "25", "29", "30", "32", "39", "41", "45", "46", "47", "49", "56", "59", "62", "63", "67", "68", "69", "81", "82", "83", "84", "90", "94", "95"))) {
- $dept_prfx = "dans le ";
- } else if (in_array($dept_code, array("23", "26", "42", "50", "51", "55", "58", "72", "80", "86"))) {
- $dept_prfx = "dans la ";
- } else if (in_array($dept_code, array("04", "05", "06", "08", "13", "22", "40", "64", "65", "66", "78", "79", "88", "92", "984"))) {
- $dept_prfx = "dans les ";
- } else if (in_array($dept_code, array("16", "17", "19", "20", "2A", "2B", "21", "24", "31", "33", "35", "38", "43", "44", "48", "52", "53", "54", "57", "70", "71", "73", "74", "76", "77", "85", "87", "93", "971", "972", "973", "987", "988"))) {
- $dept_prfx = "en ";
- }
- return $dept_prfx;
- }
- /**
- * Return the prefix to put before the french name of a region
- */
- function prefix_regn_name($regn_id) {
- $regn_prfx = "";
- if (in_array($regn_id, array("5", "8", "17"))) {
- $regn_prfx = "dans le ";
- } else if (in_array($regn_id, array("12"))) {
- $regn_prfx = "dans les ";
- } else if (in_array($regn_id, array("1", "2", "3", "4", "6", "7", "9", "10", "11", "13", "14", "15", "16", "18", "19", "20", "21", "22"))) {
- $regn_prfx = "en ";
- }
- return $regn_prfx;
- }
- /**
- * Vérifie qu'une chaine commence par une certaine sous-chaine
- */
- function string_begins_with($string, $search) {
- return (strncmp($string, $search, strlen($search)) == 0);
- }
- /**
- * Vérifie qu'une chaine se termine par une certaine sous-chaine
- */
- function string_ends_with($string, $search) {
- return (substr($string, strlen($string) - strlen($search)) == $search);
- }
- /**
- * Vérifie qu'une chaine contient une certaine sous-chaine
- */
- function string_contains($string, $search) {
- return (strpos($string, $search) > 0);
- }
- /**
- * Change le lien en absolus et remplace les & par des &
- *
- * @param String $links : Code HTML contenant des liens
- */
- function normalize_link($html_output) {
- // Mettre tous les liens en absolu
- preg_match_all("`href=\"[^\"]+\"`", $html_output, $match);
- /*
- echo '<pre>';
- print_r($match);
- echo '</pre>';
- */
- if (is_array($match[0])) {
- foreach ($match[0] as $k => $v) {
- if (strpos($v, "javascript") === false) {
- $url = str_replace("=\"/", "=\"http://" . $_SERVER['HTTP_HOST'] . '/', $v);
- $url = TextNoAccent($url);
- // Si l'url ne contient pas d'ID(agence, annonce ...) on met en minuscule
- $regex_url_agence = "agence-immobiliere/([-+_'a-z0-9]+)/annonces-immobilier-([-+_'A-Z0-9]+)_([0-9]+)-([-+'a-zA-Z0-9]*)\.(html)";
- $regex_url_annonce = "agence-immobiliere/([-+_'a-z0-9]+)/annonces-location-([-+_'A-Z0-9]+)_([0-9]+)-([-+'a-zA-Z0-9]*)\.(html)";
- /*
- if (!preg_match("`$regex_url_agence`", $v) && !preg_match("`$regex_url_annonce`", $v))
- $url = strtolower($url);
- */
- // Correctiopn W3C
- if (strpos($url, "&") !== false) {
- // Pour éviter de remplacer les & saisis à la main sur des urls en BD par exp
- $url = str_replace("&", "&", $url);
- }
- $url = str_replace("&", "&", $url);
- $html_output = str_replace($v, $url, $html_output);
- }
- }
- }
- // Fin traitement
- return $html_output;
- }
- /**
- * Ajoute des alts, corrige la fermeture de balise et les "&"
- *
- * @param String $html_output
- * @return String html_output
- */
- function normalize_img($html_output) {
- // Récupérer toutes les images cotenu dans le code HTML
- preg_match_all("`<img(.*?)>`is", $html_output, $match, PREG_PATTERN_ORDER);
- if (is_array($match[0])) {
- foreach ($match[0] as $k => $v) {
- $old_v = $v;
- // Vérification des alts
- $b = strpos($v, "alt");
- if ($b === false) {
- $v = str_replace("<img", "<img alt=\"\" ", $v);
- }
- // Vérification des fermeture de balise
- if (strpos($v, "/>") === false && strpos($html_output, $old_v . "</img>") === false) {
- //echo htmlentities($v)."<hr>";
- $v = str_replace(">", "/>", $v);
- }
- // Correction des src
- preg_match('#src=\"(.*?)\"#i', $v, $tr);
- $src = str_replace("&", "&", $tr[0]);
- $v = str_replace($tr[0], $src, $v);
- // MAJ du code HTML
- $html_output = str_replace($old_v, $v, $html_output);
- }
- }
- return $html_output;
- }
- /**
- * Log des erreurs 404 (Refnat)
- *
- * @author Walid ASBAITI
- * @param String $case
- * @return void
- */
- function log_404_refnat($case = "") {
- // Ne sert plus, mais pour eviter des erreurs cache, return true
- return true;
- $num_semaine = date("W");
- // $navigateur = get_browser_agent("name");
- $navigateur = $_SERVER['HTTP_USER_AGENT'];
- // $navigateur2 = get_browser_agent();
- $source = $_SERVER['HTTP_REFERER'];
- // echo $case;
- switch ($case) {
- case "ads":
- //création du msg
- $error_log = "Annonce inexistante.\n";
- $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
- $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
- $error_log .= "<b>USER AGENT</b> : " . $navigateur;
- $error_log .= "\n\n";
- break;
- case "agc":
- //création du msg
- $error_log = "Agence inactive\n";
- $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
- $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
- $error_log .= "<b>USER AGENT</b> : " . $navigateur;
- $error_log .= "\n\n";
- break;
- case "ref_ann":
- //création du msg
- $error_log = "Annonce refnat inexistante\n";
- $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
- $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
- $error_log .= "<b>USER AGENT</b> : " . $navigateur;
- $error_log .= "\n\n";
- break;
- case "ref_dep":
- //création du msg
- $error_log = "Nom de Departement different du CP\n";
- $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
- $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
- $error_log .= "<b>USER AGENT</b> : " . $navigateur;
- $error_log .= "\n\n";
- break;
- case "ref_ville":
- //création du msg
- $error_log = "Ville inexistante\n";
- $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
- $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
- $error_log .= "<b>USER AGENT</b> : " . $navigateur;
- $error_log .= "\n\n";
- break;
- default:
- $error_log = "URL incorrecte : $case\n";
- $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
- $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
- $error_log .= "<b>USER AGENT</b> : " . $navigateur;
- $error_log .= "\n\n";
- break;
- }
- $date = date("Y-m-d H:i:s");
- $sSql = "INSERT INTO TW_LOGS404_LOG values('', \"$error_log\", \"$date\",0)";
- // echo $sSql;
- // Ne pas enregistrer en PRP
- if ($_SERVER['SERVER_ADDR'] != "195.154.207.140")
- $res = pdoupdate($sSql);
- }
- /**
- * Permet de détecté le navigateur client utilisé
- *
- * @param string $return Valeur de retour demandée
- *
- * @return string|array
- */
- function get_browser_agent($return = false) {
- global $browser_agent;
- if ($return)
- $return = strtolower($return);
- // Navigateurs connu
- if ($return && $return == 'browsers') {
- return array(
- 'firefox' => 'browser',
- 'shiretoko' => 'browser', // nom de code de firefox 3.5 dev
- 'msie' => 'browser',
- 'opera' => 'browser',
- 'chrome' => 'browser',
- 'safari' => 'browser',
- 'mozilla' => 'browser',
- 'seamonkey' => 'browser',
- 'konqueror' => 'browser',
- 'netscape' => 'browser',
- 'gecko' => 'browser',
- 'navigator' => 'browser',
- 'mosaic' => 'browser',
- 'lynx' => 'browser',
- 'amaya' => 'browser',
- 'omniweb' => 'browser',
- 'avant' => 'browser',
- 'camino' => 'browser',
- 'flock' => 'browser',
- 'aol' => 'browser',
- 'Googlebot' => 'spider',
- 'msnbot' => 'spider',
- 'Yahoo' => 'spider',
- 'ask' => 'spider',
- 'Gigabot' => 'spider',
- 'itunes' => 'other',
- );
- }
- // Plateforme connue
- else if ($return && $return == 'platforms') {
- return array(
- 'android' => array('android'),
- 'freebsd' => array('freebsd'),
- 'linux' => array('linux'),
- 'iphone' => array('iphone'),
- 'ipod' => array('ipod'),
- 'zune' => array('zune'),
- 'mac' => array('macintosh', 'mac platform x', 'mac os x'),
- 'win' => array('windows', 'win32'),
- );
- }
- if (!isset($browser_agent)) {
- $browser_agent = array(
- 'name' => false,
- 'version' => 0,
- 'platform' => false,
- 'userAgent' => $_SERVER['HTTP_USER_AGENT']
- );
- // Navigateur + Version
- foreach (get_browser_agent('browsers') as $browser => $type) {
- if (preg_match("#($browser)[/ ]?([0-9.]*)#", strtolower($browser_agent['userAgent']), $match)) {
- $browser_agent['name'] = $match[1];
- // Hack safari
- if ($browser_agent['name'] == 'safari' && preg_match("#version[/ ]?([0-9.]*)#", strtolower($browser_agent['userAgent']), $match)) {
- $browser_agent['version'] = $match[1];
- }
- else
- $browser_agent['version'] = $match[2];
- if ($type == 'spider')
- $browser_agent['platform'] = $type;
- break;
- }
- }
- // OS
- if (!$browser_agent['platform']) {
- foreach (get_browser_agent('platforms') as $platform => $values) {
- if (!$browser_agent['platform']) {
- foreach ($values as $value) {
- if (strpos(strtolower($browser_agent['userAgent']), $value)) {
- $browser_agent['platform'] = $platform;
- break;
- }
- }
- }
- else
- break;
- }
- }
- }
- if ($return && isset($browser_agent[$return]))
- return $browser_agent[$return];
- else if (!$return)
- return $browser_agent;
- else
- return false;
- }
- /**
- * Check if a property type can have rooms and that unit correspond to number
- * @param $roomsNum Nombre de pieces
- * @param $roomsUnit Unité (piece ou pieces)
- * @param $propertyType Type de bien (appartement,terrain,...)
- * @return Integer Identifiant du type de bien
- */
- function checkRoomsProperty($roomsNum, $roomsUnit, $propertyType) {
- // Erreur : Nombre de pieces invalide
- if ($roomsNum < 1)
- return false;
- // Vérifier que le type de bien est autorisé
- switch ($propertyType) {
- case 'appartement':
- $idType = 1;
- break;
- case 'maison':
- $idType = 2;
- break;
- case 'loft':
- $idType = 13;
- break;
- case 'viager':
- $idType = 40;
- break;
- default:
- return 0;
- }
- // Si l'unité correspond au nombre => Okay
- if ($roomsNum == 1 && $roomsUnit == 'piece' || $roomsUnit == 'pieces')
- return $idType;
- else
- return 0;
- }
- /**
- * Return property value from property name (for bien_ville_*.php and others)
- *
- * @param unknown_type $loc
- * @param unknown_type $loc2
- * @param unknown_type $loc3
- * @return unknown
- */
- function check_locality($loc, $loc2 = NULL, $loc3 = NULL, $lvl = NULL) {
- //echo "[$loc - $loc2 - $loc3 - $lvl]";
- $loc = strtoupper($loc);
- // check si localité 2 = localité 1
- if ($loc2 != NULL) {
- $loc2 = strtoupper($loc2);
- if ($loc != $loc2) {
- return false;
- }
- }
- // check si localité 2 = localité 1
- if ($loc3 != NULL) {
- $loc3 = strtoupper($loc3);
- if (($loc != $loc2) || ($loc2 != $loc3)) {
- return false;
- }
- }
- $loc = str_replace(" ", "%", $loc);
- $loc = str_replace("'", "%", $loc);
- $sql = "
- SELECT COUNT(lct_name) AS nbr
- FROM TM_LOC_FR
- WHERE lct_name LIKE '" . $loc . "'
- ";
- // check si level localité = celui (ou ceux) demandé(s)
- if ($lvl != NULL) {
- if (is_array($lvl)) {
- $lst = implode(", ", $lvl);
- $sql .= "
- AND lct_level IN ($lst)
- ";
- } else {
- $sql .= "
- AND lct_level = $lvl
- ";
- }
- }
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- if ($res[0]["nbr"] == 0) {
- return false;
- }
- return true;
- }
- /**
- * Check the coherence between loc_name & loc_key
- *
- * @param String $loc_name
- * @param String $loc_key (lct_id & lct_level)
- * @return bool
- */
- function check_locality_by_loc_key($loc_name, $loc_key) {
- $tab_lok = explode('_', $loc_key);
- $lct_id = $tab_lok[0];
- $lct_level = $tab_lok[1];
- if (strtolower($loc_name) != "toutes communes") {
- $loc = strtoupper($loc_name);
- $loc = str_replace("-", "%", $loc);
- $loc = str_replace(" ", "%", $loc);
- $loc = str_replace("'", "\'", $loc);
- $where_loc = "AND lct_name LIKE '$loc'";
- }
- if ($lct_level == 98) {
- $where_lct = "AND lgc_id = $lct_id";
- } else if ($lct_level == 99) {
- $where_lct = "AND lgn_id = $lct_id";
- } else { // $lct_level == 0, 1, 2 a priori
- $where_lct = "AND lct_id = $lct_id AND lct_level = $lct_level";
- }
- $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE 1 $where_loc $where_lct";
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- if ($res[0]["nbr"] == 0) {
- // Florian - 19/07/10 - Inclusion de la globale !
- // (Pb avec le header si pas d'univers par exemple)
- global $_global;
- log_404_refnat("Loc erronée");
- header("HTTP/1.0 404 Not Found");
- header("status: 404");
- include($_SERVER["DOCUMENT_ROOT"] . "/404.php");
- exit();
- }
- return true;
- }
- /**
- * Check if the id(s) of a locality is(are) the one of a town (and not a departement or a region)
- *
- * @param String $lct_id
- * @param String $lgc_id
- * @param String $lgn_id
- * @return bool
- */
- function check_locality_is_town_ids($lct_id, $lgc_id = NULL, $lgn_id = NULL) {
- $ret = false;
- if (isset($lgc_id) && ($lgc_id != NULL) && ($lgc_id > 0)) {
- return true; // forcément une ville
- } else if (isset($lgn_id) && ($lgn_id != NULL) && ($lgn_id > 0)) {
- return true; // forcément une ville
- } else { // $lct_id == 0, 1, 2 a priori
- $sql = "SELECT lct_id, lct_level, lct_name FROM TM_LOC_FR WHERE lct_id = $lct_id";
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- if (count($res) > 0) {
- $loc = $res[0];
- $ret = ((($loc["lct_id"] > 120) && ($loc["lct_level"] == 2)) || (($loc["lct_id"] == 100) && ($loc["lct_level"] == 1)));
- }
- }
- return $ret;
- }
- /**
- * Check if the name of a locality is the one of a town (and not a departement or a region)
- *
- * @param String $lct_id
- * @param String $lgc_id
- * @param String $lgn_id
- * @return bool
- */
- function check_locality_is_town_text($lct_name) {
- $ret = false;
- $sql_name = htmlspecialchars_decode($lct_name, ENT_QUOTES);
- $sql_name = addslashes($sql_name);
- $sql = "SELECT lct_id, lct_level, lct_name FROM TM_LOC_FR WHERE lct_name = '" . $sql_name . "'";
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- if (count($res) > 0) {
- $loc = $res[0];
- $ret = ((($loc["lct_id"] > 120) && ($loc["lct_level"] == 2)) || (($loc["lct_id"] == 100) && ($loc["lct_level"] == 1)));
- }
- return $ret;
- }
- // Renvoie true si la clé de localité n'est pas correctement écrite (et pas si elle n'est pas valide en base !)
- function isWrongLocKey($loc_key) {
- return ( $loc_key != '' && !preg_match('`^[0-9]+_([0123]|97|98|99)$`', $loc_key) );
- }
- // Renvoie true si le couple clé de localité / nom de localité n'est pas valide en base
- function isWrongLocKeyLocName($loc_key, $loc_name) {
- $ret = true;
- if (($loc_key == '') || ($loc_name == '')) {
- return $ret;
- }
- // Récupération des infos
- $tab_lok = explode('_', $loc_key);
- $loc_id = $tab_lok[0];
- $loc_level = $tab_lok[1];
- //echo "(loc_id, loc_level) = ($loc_id, $loc_level)";
- if (($loc_id == '') || ($loc_level == '')) {
- return $ret;
- }
- $sql = "SELECT COUNT(1) AS nbr";
- // Vérification du loc_key en base
- if ($loc_level == '98') {
- $sql .= " FROM TM_LOCGC_FR WHERE lgc_id = $loc_id";
- } else if ($loc_level == '99') {
- $sql .= " FROM TM_LOCGN_FR WHERE lgn_id = $loc_id";
- } else { // $loc_level == 0, 1, 2 a priori
- $sql .= " FROM TM_LOC_FR WHERE lct_id = $loc_id AND lct_level = $loc_level";
- }
- // Vérification du loc_name en base
- $loc_name_sql = str_replace('-', '%', $loc_name);
- $loc_name_sql = strtoupper(addslashes($loc_name_sql));
- if ($loc_level == '98') {
- if ($loc_name != 'toutes-communes')
- return true;
- } else if ($loc_level == '99') {
- if (strpos($loc_name_sql, '%') === false) {
- $sql .= " AND lgn_name_fr = '" . $loc_name_sql . "'";
- } else {
- $sql .= " AND lgn_name_fr LIKE '" . $loc_name_sql . "'";
- }
- } else { // $loc_level == 0, 1, 2 a priori
- if (strpos($loc_name_sql, '%') === false) {
- $sql .= " AND lct_name = '" . $loc_name_sql . "'";
- } else {
- $sql .= " AND lct_name LIKE '" . $loc_name_sql . "'";
- }
- }
- // Exécution de la requête
- //echo "<hr>".$sql."<br>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- $ret = ($res[0]["nbr"] <= 0);
- return $ret;
- }
- // Renvoie true si le couple clé de localité / nom de localité est unique (1 localité, pas 2 ni 3)
- function isUniqLocKeyLocName($loc_key, $loc_name) {
- $ret = false;
- if (($loc_key == '') || ($loc_name == '')) {
- return $ret;
- }
- $ret = (!string_contains($loc_key, ',') && !string_contains($loc_name, ','));
- return $ret;
- }
- // Renvoie true si le triplet clé de localité / nom de localité / code postal n'est pas valide en base
- function isWrongLocKeyLocNamePostCode($loc_key, $loc_name_post_code) {
- $ret = true;
- if (($loc_key == '') || ($loc_name_post_code == '')) {
- return $ret;
- }
- // Récupération des infos
- $tab_lok = explode('_', $loc_key);
- $loc_id = $tab_lok[0];
- $loc_level = $tab_lok[1];
- //echo "(loc_id, loc_level) = ($loc_id, $loc_level)";
- if (($loc_id == '') || ($loc_level == '')) {
- return $ret;
- }
-
- if (!in_array($loc_level, array('0', '1', '2', '98', '99'))) {
- return $ret;
- }
- /*
- // Patch pour arrondissements de Marseille et Lyon qui n'ont pas le bon dans default_town_2
- // actuellement (champ calculé depuis le BOFO avec son propre référentiel)
- //echo '[AVANT:loc_key='.$loc_key.' / loc_name_post_code='.$loc_name_post_code.']';
- $arr_city = array('lct_id' => $loc_id);
- $ret_city = isArrondCity($arr_city);
- if ($ret_city[0]) {
- $sql = "SELECT CONCAT(LOWER(REPLACE(lct_name, ' ', '-')), '-', lct_post_code) AS loc_name_post_code FROM TM_LOC_FR WHERE lct_id = $loc_id AND lct_level = $loc_level";
- //echo "<hr>".$sql."<br>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- $loc_name_post_code = $res[0][0];
- //echo '[APRES:loc_name_post_code = '.$loc_name_post_code.']';
- }
- */
- $tab_lon = explode('-', $loc_name_post_code);
- $pos_lon = sizeof($tab_lon) - 1;
- if ($pos_lon < 1)
- return true; // y a déjà un pb
- if ($loc_level == '99') { // suppr 3 derniers élts ('tous codes postaux')
- $loc_post_code = $tab_lon[$pos_lon - 2] . '-' . $tab_lon[$pos_lon - 1] . '-' . $tab_lon[$pos_lon];
- unset($tab_lon[$pos_lon]);
- unset($tab_lon[$pos_lon - 1]);
- unset($tab_lon[$pos_lon - 2]);
- } else { // suppr dernier élt ('XXXXX' ou 'XXX' ou 'XX')
- $loc_post_code = $tab_lon[$pos_lon];
- unset($tab_lon[$pos_lon]);
- }
- $loc_name = implode('-', $tab_lon);
- //echo "(loc_name, loc_post_code) = ($loc_name, $loc_post_code)";
- $sql = "SELECT COUNT(1) AS nbr";
- // Vérification du loc_key en base
- if ($loc_level == '98') {
- $sql .= " FROM TM_LOCGC_FR WHERE lgc_id = $loc_id";
- } else if ($loc_level == '99') {
- $sql .= " FROM TM_LOCGN_FR WHERE lgn_id = $loc_id";
- } else { // $loc_level == 0, 1, 2 a priori
- $sql .= " FROM TM_LOC_FR WHERE lct_id = $loc_id AND lct_level = $loc_level";
- }
- // Vérification du loc_name en base
- $loc_name_sql = str_replace(' ', '%', $loc_name);
- $loc_name_sql = str_replace('-', '%', $loc_name_sql);
- $loc_name_sql = strtoupper(addslashes($loc_name_sql));
- if ($loc_level == '98') {
- if ($loc_name != 'toutes-communes')
- return true;
- } else if ($loc_level == '99') {
- if (strpos($loc_name_sql, '%') === false) {
- $sql .= " AND lgn_name_fr = '" . $loc_name_sql . "'";
- } else {
- $sql .= " AND lgn_name_fr LIKE '" . $loc_name_sql . "'";
- }
- } else { // $loc_level == 0, 1, 2 a priori
- if (strpos($loc_name_sql, '%') === false) {
- $sql .= " AND lct_name = '" . $loc_name_sql . "'";
- } else {
- $sql .= " AND lct_name LIKE '" . $loc_name_sql . "'";
- }
- }
- // Vérification du loc_post_code en base
- if ($loc_level == '98') {
- $sql .= " AND lgc_post_code = '" . $loc_post_code . "'";
- } else if ($loc_level == '99') {
- if ($loc_post_code != 'tous-codes-postaux')
- return true;
- //$sql .= "";
- } else { // $loc_level == 0, 1, 2 a priori
- if ($loc_level == '1') {
- if (in_array($loc_post_code, array('2a', '2b', '971', '972', '973', '974', '975', '976', '984', '986', '987', '988'))) {
- $sql .= " AND lct_post_code = '" . $loc_post_code . "'";
- } else {
- $sql .= " AND lct_post_code = '" . $loc_post_code . "000'";
- }
- } else {
- $sql .= " AND lct_post_code = '" . $loc_post_code . "'";
- }
- }
- // Exécution de la requête
- //echo "<hr>".$sql."<br>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- $ret = ($res[0]["nbr"] <= 0);
- return $ret;
- }
- // Renvoie true si au moins un des triplets clé de localité / nom de localité / code postal n'est pas valide en base
- function areWrongLocKeyLocNamePostCode($loc_keys, $loc_names_post_codes) {
- $ret = true;
- $lst_loc_keys = explode(',', $loc_keys);
- $lst_loc_names = explode(',', $loc_names_post_codes);
- for ($i = 0; $i < 3; $i++) {
- if (isset($lst_loc_keys[$i]) && isset($lst_loc_names[$i])) {
- $ret = $ret || !isWrongLocKeyLocNamePostCode($lst_loc_keys[$i], $lst_loc_names[$i]);
- }
- }
- return $ret;
- }
- /**
- * Check the coherence of the loc_key
- *
- * @param String $loc_key (lct_id & lct_level)
- * @return bool
- */
- function check_loc_key($loc_key, $str_cond = "") {
- $tab_lok = explode('_', $loc_key);
- $lct_id = $tab_lok[0];
- $lct_level = $tab_lok[1];
- if ($lct_level == 98) {
- $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE lgc_id = $lct_id";
- } else if ($lct_level == 99) {
- $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE lgn_id = $lct_id";
- } else { // $lct_level == 0, 1, 2 a priori
- $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE lct_id = $lct_id AND lct_level = $lct_level";
- }
- if (isset($str_cond) && !empty($str_cond)) {
- $sql .= " AND " . $str_cond; // peut utiliser le champ "lct_name"
- }
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- $ret = ($res[0]["nbr"] > 0);
- return $ret;
- }
- /**
- * Check the coherence of the loc_key
- *
- * @param String $loc_key (lct_id & lct_level)
- * @return bool
- */
- function get_loc_key($loc_key, $loc_post_code = "", $str_cond = "") {
- $tab_lok = explode('_', $loc_key);
- $lct_id = $tab_lok[0];
- $lct_level = $tab_lok[1];
- if (empty($lct_id) || empty($lct_level)) {
- $ret = NULL;
- } else {
- if ($lct_level == 98) {
- $sql = "SELECT lct_id, lct_level, lct_name, lct_post_code, lct_parent_id FROM TM_LOC_FR WHERE lgc_id = $lct_id";
- } else if ($lct_level == 99) {
- $sql = "SELECT lct_id, lct_level, lct_name, lct_post_code, lct_parent_id FROM TM_LOC_FR WHERE lgn_id = $lct_id";
- } else { // $lct_level == 0, 1, 2 a priori
- $sql = "SELECT lct_id, lct_level, lct_name, lct_post_code, lct_parent_id FROM TM_LOC_FR WHERE lct_id = $lct_id AND lct_level = $lct_level";
- }
- if (isset($loc_post_code) && !empty($loc_post_code)) {
- $sql .= " AND lct_post_code = '" . $loc_post_code . "'";
- }
- if (isset($str_cond) && !empty($str_cond)) {
- $sql .= " AND " . $str_cond;
- }
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- $ret = $res[0];
- }
- return $ret;
- }
- /**
- * Get the all the localities with the same name
- *
- * @param String $loc_name
- * @return array
- */
- function get_loc_names($lct_name, $loc_key = "", $loc_post_code = "", $str_cond = "") {
- $sql = "
- SELECT lct_id, lct_level, lct_name, lct_post_code
- FROM TM_LOC_FR
- WHERE 1
- ";
- if ($lct_name != "") {
- $lct_name_sql = strtoupper(addslashes($lct_name));
- $sql .= "AND lct_name = '" . $lct_name_sql . "'";
- }
- if (isset($loc_key) && !empty($loc_key)) {
- $tab_lok = explode('_', $loc_key);
- $lct_id = $tab_lok[0];
- $lct_level = $tab_lok[1];
- $sql .= "
- AND NOT (lct_id = '" . $lct_id . "' AND lct_level = '" . $lct_level . "')
- ";
- }
- if (isset($loc_post_code) && !empty($loc_post_code)) {
- $sql .= "
- AND NOT (lct_post_code = '" . $loc_post_code . "')
- ";
- }
- if (isset($str_cond) && !empty($str_cond)) {
- $sql .= "
- AND " . $str_cond . "
- ";
- }
- $sql .= "
- ORDER BY lct_post_code ASC
- ";
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- return $res;
- }
- /**
- * Get the all the localities with the same name v2
- *
- * @param String $loc_name
- * @return array
- */
- function get_loc_names2($lct_name, $loc_key = "", $loc_post_code = "", $str_cond = "") {
- $sql_and = "";
- if ($lct_name != "") {
- $lct_name_sql = strtoupper(addslashes($lct_name));
- $sql_and .= "AND lct_name = '" . $lct_name_sql . "'";
- }
- if (isset($loc_key) && !empty($loc_key)) {
- $tab_lok = explode('_', $loc_key);
- $lct_id = $tab_lok[0];
- $lct_level = $tab_lok[1];
- if ($lct_level == '99') {
- $sql_and .= "
- AND NOT (lgn_id = '" . $lct_id . "')
- ";
- } else {
- $sql_and .= "
- AND NOT (lct_id = '" . $lct_id . "' AND lct_level = '" . $lct_level . "')
- ";
- }
- }
- if (isset($loc_post_code) && !empty($loc_post_code) && ($loc_post_code != 'tous-codes-postaux')) {
- $sql_and .= "
- AND NOT (lct_post_code = '" . $loc_post_code . "')
- ";
- }
- if (isset($str_cond) && !empty($str_cond)) {
- $sql_and .= "
- AND " . $str_cond . "
- ";
- }
- $sql = "
- (
- SELECT lct_id, lct_level, lct_name, lct_post_code
- FROM TM_LOC_FR
- WHERE 1
- $sql_and
- AND lgn_id = 0
- ) UNION ALL (
- SELECT lgn_id AS lct_id, '99' AS lct_level, lct_name, 'tous codes postaux' AS lct_post_code
- FROM TM_LOC_FR
- WHERE 1
- $sql_and
- AND lgn_id > 0
- GROUP BY lgn_id
- )
- ORDER BY lct_post_code ASC
- ";
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- return $res;
- }
- /**
- * Get the locality infos from a lct_id
- *
- * @param String $loc_name
- * @return array
- */
- function get_loc_infos($lct_id, $str_cond = "") {
- $sql = "
- SELECT lct_id, lct_level, lct_name, lct_post_code, lgc_id, lgn_id
- FROM TM_LOC_FR
- WHERE 1
- ";
- if ($lct_id != "") {
- $sql .= "AND lct_id = '" . $lct_id . "'";
- }
- if (isset($str_cond) && !empty($str_cond)) {
- $sql .= "
- AND " . $str_cond . "
- ";
- }
- $sql .= "
- ORDER BY lct_id ASC
- ";
- //echo "<hr><br>".$sql."<br><hr>"; //exit();
- $res = pdoquery($sql);
- //var_dump($res);
- return $res;
- }
- /**
- * Get the locality infos from a lct_id
- * (used for WS /ws/url.search.li.mysql.php)
- *
- * @param String $loc_name
- * @return array
- */
- function get_loc_infos_from_post_code($lct_post_code) {
- $arr = array(
- 'ret_val' => false,
- 'ret_msg' => '',
- 'loc_key' => '',
- 'loc_name' => '',
- 'lgn_id' => '',
- 'lgc_id' => ''
- );
- $lct_post_code = strtolower($lct_post_code);
- // check format : villes (dont Monaco), dépts métropole, dépts Dom-Tom, dépts Corse
- if (!(preg_match('/[0-9]{5}|[0-9]{2}|97[0-9]|98[0-9]|2[a-b]/', $lct_post_code))) {
- $arr['ret_msg'] = 'Bad postcode regexp (lct_post_code = ' . $lct_post_code . ')';
- return $arr;
- }
- // type de CP : CP ville ou de dépt
- $len_post_code = strlen($lct_post_code);
- if (in_array($len_post_code, array(2, 3))) { // dépt
- if (strlen($lct_post_code) == 2) {
- if (!in_array($lct_post_code, array('2a', '2b'))) {
- $lct_post_code = $lct_post_code . '000';
- }
- }
- $sql = "
- SELECT lct_id, lct_level, lct_name, lct_post_code, lgn_id, lgc_id
- FROM TM_LOC_FR
- WHERE lct_post_code = '$lct_post_code'
- AND lct_level = 1
- ";
- //echo "<hr><br>".$sql."<br><hr>";
- $res = pdoquery($sql);
- //var_dump($res);
- if (count($res) > 0) {
- $ret = $res[0];
- if (strlen($ret['lct_post_code']) == 5) {
- $ret['lct_post_code'] = str_replace('000', '', $ret['lct_post_code']);
- }
- $arr = array(
- 'ret_val' => true,
- 'ret_msg' => '',
- 'loc_key' => $ret['lct_id'] . '_' . $ret['lct_level'],
- 'loc_name' => $ret['lct_name'] . '-' . $ret['lct_post_code']
- );
- } else {
- $arr['ret_msg'] = 'Departement not found (lct_post_code = ' . $lct_post_code . ')';
- return $arr;
- }
- } else if ($len_post_code == 5) { // ville
- $sql = "
- SELECT lgn_id AS lct_id, '99' AS lct_level, lgn_name_fr AS lct_name, 'tous-codes-postaux' AS lct_post_code
- FROM TM_LOCGN_FR
- WHERE lgn_post_code = '$lct_post_code'
- ";
- //echo "<hr><br>".$sql."<br><hr>";
- $res = pdoquery($sql);
- //var_dump($res);
- if (count($res) > 0) { // regroupement de ville par nom, grande ville (ie même ville avec plusieurs CP)
- $ret = $res[0];
- $arr = array(
- 'ret_val' => true,
- 'ret_msg' => '',
- 'loc_key' => $ret['lct_id'] . '_' . $ret['lct_level'],
- 'loc_name' => $ret['lct_name'] . '-' . $ret['lct_post_code']
- );
- } else { // petite ville (ie ville avec un seul CP)
- $sql = "
- SELECT lct_id, lct_level, lct_name, lct_post_code, lgc_id, lgn_id
- FROM TM_LOC_FR
- WHERE lct_post_code = '$lct_post_code'
- AND lct_level = 2
- ";
- //echo "<hr><br>".$sql."<br><hr>";
- $res = pdoquery($sql);
- //var_dump($res);
- if (count($res) > 0) {
- $ret = $res[0];
- $arr = array(
- 'ret_val' => true,
- 'ret_msg' => '',
- 'loc_key' => $ret['lct_id'] . '_' . $ret['lct_level'],
- 'loc_name' => $ret['lct_name'] . '-' . $ret['lct_post_code']
- );
- } else {
- $arr['ret_msg'] = 'Town not found (lct_post_code = ' . $lct_post_code . ')';
- return $arr;
- }
- }
- } else { // problème quelque part...
- $arr['ret_msg'] = 'Bad postcode width (lct_post_code = ' . $lct_post_code . ')';
- }
- return $arr;
- }
- /**
- * getCityOrDeptInfoByPostCode
- * Returns locality info by postcode
- *
- * @param string $postcode
- * @param bool $doGroupBy Wether to return lgn_id / lgc_id or not.
- */
- function getCityOrDeptInfoByPostCode($postcode, $doGroupBy) {
-
- $isCity = (strlen($postcode) == 5 && is_numeric($postcode));
- $isDept = ((strlen($postcode) == 2 || strlen($postcode) == 3) && (is_numeric($postcode) || in_array($postcode, array('2A', '2B'))));
-
- // Si le code postal n'est pas valide, on retourne null.
- if(!$isCity && !$isDept)
- return false;
-
- if($isDept && !in_array($postcode, array('2A', '2B')) && strlen($postcode) == 2) {
- // Si le code postal est celui d'un département
- // et que ce n'est pas la corse, on complète par des 0.
- $postcode = $postcode.'000';
- }
-
- $sql = "
- SELECT lct_id, lct_level, CONCAT(lct_name, '-', IF(lct_level = 1 AND LENGTH(lct_post_code) = 5, SUBSTRING(lct_post_code, 1, 2), lct_post_code)) AS lct_name, lct_post_code, lgc_id, lgn_id
- FROM TM_LOC_FR
- WHERE lct_post_code = '$postcode'
- AND lct_level IN (1,2)
- ORDER BY lct_level ".($isDept ? 'ASC' : 'DESC')
- ;
- $res = pdoquery($sql);
-
- if($doGroupBy && ($res[0]['lgc_id'] > 0 || $res[0]['lgn_id'] > 0)) {
- // Si $doGroupBy, on vérifie si les résultats correspondent
- // à des regroupements
-
- if($res[0]['lgn_id'] > 0) {
- $sql = "
- SELECT lgn_id AS lct_id, '99' AS lct_level, CONCAT(lgn_name_fr, '-tous-codes-postaux') AS lct_name, 'tous-codes-postaux' AS lct_post_code
- FROM TM_LOCGN_FR
- WHERE lgn_id = '".$res[0]['lgn_id']."'
- ";
- $res = pdoquery($sql);
- } else if($res[0]['lgc_id'] > 0) {
- $sql = "
- SELECT lgc_id AS lct_id, '98' AS lct_level, CONCAT('toutes-communes-', lgc_post_code) AS lct_name, lgc_post_code AS lct_post_code
- FROM TM_LOCGC_FR
- WHERE lgc_id = '".$res[0]['lgc_id']."'
- ";
- $res = pdoquery($sql);
- }
-
- }
- if(is_array($res)) {
- return $res[0];
- } else
- return false;
-
-
- }
- /**
- * Return property value from property name (for bien_ville_*.php)
- *
- * @param unknown_type $prp
- * @return unknown
- */
- function value_property($prp, $do_use_label2 = false) {
- global $_ADVANCED_SEARCH_TYPES;
- $val = -1;
- $prp = strtolower($prp);
- foreach ($_ADVANCED_SEARCH_TYPES as $type) {
- // Gérer le cas bureau / commerce, châlet ...
- if (isset($type['label2']) && !empty($type['label2'])) {
- $label = $type['label2']; // utile pour la coloc.
- } else {
- $label = $type['label'];
- }
- $label = str_replace(' / ', '-', TextNoAccent($label));
- $label = prepareToUrl($label);
- if ($prp == strtolower($label)) {
- $val = $type['value'];
- return $val;
- }
- }
- return $val;
- }
- /**
- * Return transaction value from transaction name (for bien_ville_*.php)
- *
- * @param unknown_type $trs
- * @return unknown
- */
- function value_transact($trs) {
- $val = -1;
- $trs = strtolower($trs);
- switch ($trs) {
- case "location":
- $val = 2;
- break;
- case "vente":
- case "achat":
- default:
- $val = 1;
- break;
- }
- return $val;
- }
- /**
- * Return number rooms value from number rooms passed (for bien_ville_*.php)
- *
- * @param unknown_type $num
- * @param unknown_type $pcs
- * @param unknown_type $prp
- * @return unknown
- */
- function value_roomsnum($num, $pcs, $prp) {
- $val = -1;
- if ($prp == "appartement") {
- if (in_array($num, array("1", "2", "3", "4"))) {
- if (((intval($num) == 1) && ($pcs == "piece")) || ((intval($num) >= 2) && ($pcs == "pieces"))) {
- $val = intval($num);
- }
- }
- } else if ($prp == "maison") {
- if (in_array($num, array("1", "2", "3", "4"))) {
- if (((intval($num) == 1) && ($pcs == "piece")) || ((intval($num) >= 2) && ($pcs == "pieces"))) {
- $val = intval($num);
- }
- }
- }
- return $val;
- }
- /**
- * Enter description here...
- *
- * @return unknown
- */
- function is_mobile() {
- $op = strtolower($_SERVER['HTTP_X_OPERAMINI_PHONE']);
- $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
- $ac = strtolower($_SERVER['HTTP_ACCEPT']);
- $isMobile = (strpos($ac, 'application/vnd.wap.xhtml+xml') !== false
- || $op != ''
- || strpos($ua, 'sony') !== false
- || strpos($ua, 'symbian') !== false
- || strpos($ua, 'nokia') !== false
- || strpos($ua, 'samsung') !== false
- || strpos($ua, 'mobile') !== false
- || strpos($ua, 'windows ce') !== false
- || strpos($ua, 'epoc') !== false
- || strpos($ua, 'opera mini') !== false
- || strpos($ua, 'nitro') !== false
- || strpos($ua, 'j2me') !== false
- || strpos($ua, 'midp-') !== false
- || strpos($ua, 'cldc-') !== false
- || strpos($ua, 'netfront') !== false
- || strpos($ua, 'mot') !== false
- || strpos($ua, 'up.browser') !== false
- || strpos($ua, 'up.link') !== false
- || strpos($ua, 'audiovox') !== false
- || strpos($ua, 'blackberry') !== false
- || strpos($ua, 'ericsson,') !== false
- || strpos($ua, 'panasonic') !== false
- || strpos($ua, 'philips') !== false
- || strpos($ua, 'sanyo') !== false
- || strpos($ua, 'sharp') !== false
- || strpos($ua, 'sie-') !== false
- || strpos($ua, 'portalmmm') !== false
- || strpos($ua, 'blazer') !== false
- || strpos($ua, 'avantgo') !== false
- || strpos($ua, 'danger') !== false
- || strpos($ua, 'palm') !== false
- || strpos($ua, 'series60') !== false
- || strpos($ua, 'palmsource') !== false
- || strpos($ua, 'pocketpc') !== false
- || strpos($ua, 'smartphone') !== false
- || strpos($ua, 'rover') !== false
- || strpos($ua, 'ipaq') !== false
- || strpos($ua, 'au-mic,') !== false
- || strpos($ua, 'alcatel') !== false
- || strpos($ua, 'ericy') !== false
- || strpos($ua, 'up.link') !== false
- || strpos($ua, 'vodafone/') !== false
- || strpos($ua, 'wap1.') !== false
- || strpos($ua, 'wap2.') !== false
- || strpos($ua, 'Mobile WVGA') !== false
- || strpos($ua, 'Mobile Safari') !== false)
- && strpos($ua, 'ipad') === false
- ;
- // $isMobile
- return $isMobile;
- }
- /**
- * Enter description here...
- *
- * @return unknown
- */
- function mobile_redirect($uri, $ad) {
- global $_global;
- $domaine_use = URL_SITE_MOBILE;
- if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'iphone') || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'ipod')) {
- $domaine_use = URL_SITE_IPHONE;
- }
- if (strpos($uri, "detail")) {
- $uri = str_replace("/", "", $uri);
- $uri = explode("-", $uri);
- // property
- $property = strtolower($ad["property_type"]);
- // location
- $location = strtolower($ad["hierarchy"][2]["lct_name"]);
- $location = str_replace(" ", "_", $location);
- if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'iphone') || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'ipod')) {
- $url = $domaine_use . "/detail/detail_annonce.html?id=" . $ad["id"] . "&univ=" . $_global["univers"];
- return $url;
- }
- return $domaine_use . "/annonce-" . $uri[1] . "-" . $property . "-" . $location . "-" . strtolower($ad["id"]) . ".html";
- } else {
- return $domaine_use;
- }
- }
- /**
- * Close HTML tags of an HTML string
- * voir http://www.siteduzero.com/forum-83-480977-p1-fermeture-de-balise-xhtml-automatique.html
- *
- * @param unknown_type $xhtml
- * @return unknown
- */
- function close_xhtml($xhtml) {
- $tags = array();
- for ($i = 0; preg_match('`<(/?)([a-z]+)(?:\s+[a-z]+="[^"]*")*>`i', $xhtml, $tag, PREG_OFFSET_CAPTURE, $i); $i = strlen($tag[0][0]) + $tag[0][1]) {
- if ($tag[1][0] != '/') {
- $tags[] = $tag[2][0];
- } else if ($tag[2][0] == end($tags)) {
- array_pop($tags);
- } else {
- $xhtml = substr_replace($xhtml, '', $tag[0][1], strlen($tag[0][0]));
- }
- }
- $xhtml = preg_replace('`<[^>]*$`', '', $xhtml);
- while ($tag = array_pop($tags)) {
- $xhtml .= '</' . $tag . '>';
- }
- return $xhtml;
- }
- /**
- * Close a Path with a "/"
- * SOFLOU
- * @param $path
- * @return $path."/";
- */
- function enclose_path($path) {
- if (substr($path, -1) <> "/") {
- $path .= "/";
- }
- return $path;
- }
- /**
- * Get locality label from search_parameters and field num (locname1, locname2, locname3)
- * using loc_level to find right label (1, 2, 98, 99)
- *
- * @param Array $search_parameters
- * @param Integer $num
- * @return String label
- */
- function getLocalityLabel($search_parameters, $num, &$loc_key = "") {
- if (isset($search_parameters["loc_levels"][$num])) {
- // Si la clé est incorrecte, on ignore cette localité
- if (!preg_match('`^[0-9]+_[0-9]{1,2}$`', $search_parameters["loc_keys"][$num]))
- return LABEL_DEFAULT_LOCALITY;
- // Renvoyer la clé de cette localité
- $loc_key = $search_parameters["loc_keys"][$num];
- $code_postal = $search_parameters["lzip"][$num];
- switch ($search_parameters["loc_levels"][$num]) {
- case 0:
- //Région
- return $search_parameters["loc_names"][$num] . ' (' . $code_postal . ')';
- case 1:
- // Departement
- $domtom = array('971', '972', '973', '974', '975', '976', '984', '986', '987', '988');
- // Traitement particulier pour les dom-tom
- if (in_array($code_postal, $domtom))
- return $search_parameters["loc_names"][$num] . ' (' . $code_postal . ')';
- else
- return $search_parameters["loc_names"][$num] . ' (' . $search_parameters["szip"][$num] . ')';
- case 2:
- // Ville
- return $search_parameters["loc_names"][$num] . ' (' . $code_postal . ')';
- case 98:
- // Toutes communes
- return 'TOUTES COMMUNES (' . $code_postal . ')';
- case 99:
- // Tous departements
- return $search_parameters["loc_names"][$num] . ' (TOUS CODES POSTAUX)';
- default:
- return LABEL_DEFAULT_LOCALITY;
- }
- }
- else
- return LABEL_DEFAULT_LOCALITY;
- }
- /**
- * Convertir la chaine composée de 1 et 0 en hexadecimal.
- * Si la chaine est trop petite une fois convertie, on remplie avec des 0 à droite
- * Florian Planchon
- */
- function stringToHexa($string, $size) {
- return str_pad(base_convert($string, 2, 16), $size, 0, STR_PAD_LEFT);
- }
- /**
- * Convertir la chaine hexadeimal en suite de 1 et de 0.
- * Si la chaine est trop petite une fois convertie, on remplie avec des 0 à droite
- * Florian Planchon
- */
- function hexaToString($string, $size) {
- return str_pad(base_convert($string, 16, 2), $size, 0, STR_PAD_LEFT);
- }
- /* Renvoie Vrai si la valeur binaire, qui peut être très longue, correspond au masque binaire */
- function matchMask($value, $mask) {
- if (strpos($mask, '1') === false)
- return false;
- $maxLength = PHP_INT_SIZE * 8;
- // split
- $o1 = str_split($value, $maxLength);
- $o2 = str_split(str_pad(trim($mask), strlen($value), '0'), $maxLength);
- $res = '';
- $runs = count($o1);
- for ($i = 0; $i < $runs; $i++) {
- $mask_part = bindec($o2[$i]);
- if (( bindec($o1[$i]) & $mask_part ) !== $mask_part)
- return false;
- }
- return true;
- }
- /* Faire une opération AND entre deux chaines binaires qui peuvent être très longues */
- function bitAnd($value1, $value2) {
- $maxLength = PHP_INT_SIZE * 8;
- // split
- $o1 = str_split($value1, $maxLength);
- $o2 = str_split(str_pad('', strlen($value1), $value2), $maxLength);
- $res = '';
- $runs = count($o1);
- for ($i = 0; $i < $runs; $i++)
- $res .= decbin(bindec($o1[$i]) & bindec($o2[$i]));
- return $res;
- }
- /* Faire une opération OR entre deux chaines binaires qui peuvent être très longues */
- function bitOr($value1, $value2) {
- $maxLength = PHP_INT_SIZE * 8;
- // split
- $o1 = str_split($value1, $maxLength);
- $o2 = str_split(str_pad('', strlen($value1), $value2), $maxLength);
- $res = '';
- $runs = count($o1);
- for ($i = 0; $i < $runs; $i++)
- $res .= decbin(bindec($o1[$i]) | bindec($o2[$i]));
- return $res;
- }
- /* Fonction utilisée pour convertir une ancienne valeur de types de bien en une nouvelle */
- function convert_nb_rooms($nb_room, $nb_room_min, $nb_room_max, $size = 8) {
- $nb_rooms = str_repeat('0', $size);
- if ($nb_room != 'a' && $nb_room != null) {
- if ($nb_room == 0)
- $nb_rooms[0] = '1';
- elseif ($nb_room != -1) {
- /*
- // $nb_room = 123 => 1, 2, 3 pièces
- $nb_rooms_part = preg_split('//', $nb_room, -1, PREG_SPLIT_NO_EMPTY);
- foreach( $nb_rooms_part as $part ) {
- if( --$part < $size ) $nb_rooms[ $part ] = '1';
- }
- */
- // $nb_rooms = 1 => à partir de 2 pièces
- for ($i = $nb_room; $i < $size; $i++)
- $nb_rooms[$i] = '1';
- }
- } else {
- $nb_room_min = (int) $nb_room_min;
- $nb_room_max = (int) $nb_room_max;
- // Gérer le cas où aucune valeur n'est précisée
- if ($nb_room_min == 0 && $nb_room_max == 0)
- return $nb_rooms;
- if ($nb_room_min < 1)
- $nb_room_min = 1;
- if ($nb_room_max < 1)
- $nb_room_max = 1;
- if ($nb_room_min > $nb_room_max) {
- $tmp = $nb_room_min;
- $nb_room_min = $nb_room_max;
- $nb_room_max = $tmp;
- }
- if ($nb_room_max > $size)
- $nb_room_max = $size;
- for ($i = $nb_room_min; $i <= $nb_room_max; $i++)
- $nb_rooms[$i - 1] = '1';
- }
- return $nb_rooms;
- }
- /* Fonction utilisée pour convertir une ancienne valeur de types de bien en une nouvelle */
- function convert_property_value($value, $size = 40) {
- // Faire le lien entre les anciens groupes et les valeurs actuelles
- $_LI_OLD_REALESTATEGROUPS[0] = array(1, 6);
- $_LI_OLD_REALESTATEGROUPS[1] = array(2, 7, 8, 13, 14, 15, 16);
- $_LI_OLD_REALESTATEGROUPS[2] = array(3);
- $_LI_OLD_REALESTATEGROUPS[3] = array(4);
- $_LI_OLD_REALESTATEGROUPS[4] = array(5);
- $_LI_OLD_REALESTATEGROUPS[5] = array(9);
- $_LI_OLD_REALESTATEGROUPS[6] = array(12);
- $_LI_OLD_REALESTATEGROUPS[7] = array(11, 17);
- // ex : 11111111 => 1111111110111111100000000000000000000000
- $new_value = str_repeat('0', $size);
- if (is_array($value)) {
- $max_length = count($_LI_OLD_REALESTATEGROUPS);
- foreach ($value as $group_id) {
- if (isset($_LI_OLD_REALESTATEGROUPS[$group_id])) {
- foreach ($_LI_OLD_REALESTATEGROUPS[$i] as $property_type_id_orig)
- $new_value[$property_type_id_orig - 1] = '1';
- }
- }
- } else {
- // Déterminer la taille maxi de parcours de la valeur
- $length = strlen($value);
- $max_length = count($_LI_OLD_REALESTATEGROUPS);
- if ($length > $max_length)
- $length = $max_length;
- // Mettre un 1 pour tous les types donc les groupes sont à 1
- for ($i = 0; $i < $length; $i++) {
- if ($value[$i] == '1') {
- foreach ($_LI_OLD_REALESTATEGROUPS[$i] as $property_type_id_orig)
- $new_value[$property_type_id_orig - 1] = '1';
- }
- }
- }
- return $new_value;
- }
- function searchPropertyTypeIdOrig($id_orig, $get_group = false) {
- global $_LI_REALESTATEGROUPS;
- --$id_orig;
- foreach ($_LI_REALESTATEGROUPS as $id => $group) {
- if ($group['value2'][$id_orig] == 1)
- return (bool) $get_group ? $id : $group['value2'];
- }
- return null;
- }
- function searchPropertyTypeIdOrigAdv($id_orig, $get_group = false) {
- global $_ADVANCED_SEARCH_TYPES;
- $value_orig = ",{$id_orig},";
- foreach ($_ADVANCED_SEARCH_TYPES as $id => $group) {
- if (strpos(",{$group['value']},", $value_orig) !== false) {
- if ((bool) $get_group) {
- return $id;
- } else {
- $result = '0000000000000000000000000000000000000000';
- $ids = explode(',', $group['value']);
- foreach ($ids as $id) {
- $result[$id - 1] = 1;
- }
- return $result;
- }
- }
- }
- return null;
- }
- function getCheckedFields($groups, $fieldValue, $maskAllChecked = "", $bLabel = false) {
- $length = strlen($fieldValue);
- $allChecked = ( $maskAllChecked != '' && matchMask($fieldValue, $maskAllChecked) );
- // Gerer les cas ou le resultat sera toujours un tableau vide ou si tout est coché
- if ($allChecked || !is_array($groups) || empty($groups) || strpos($fieldValue, '1') === false)
- return array();
- $result = $types = array();
- foreach ($groups as $index => $group) {
- if (isset($group['value']))
- $group = $group['value'];
- $types[$index] = explode(',', $group);
- }
- $size = count($groups);
- for ($offset = 0; $offset < $length; $offset++) {
- if ($fieldValue[$offset] == '1') {
- // Trouver le groupe qui contient cette valeur
- foreach ($groups as $index => $group) {
- $current_types = $types[$index];
- if (in_array($offset + 1, $current_types)) {
- $result[] = $bLabel ? $group['label'] : $index;
- // Mettre à 0 dans value les valeurs de ce groupe
- foreach ($current_types as $type)
- $fieldValue[$type - 1] = '0';
- // Le premier groupe trouvé est le seul qui contient la valeur
- break;
- }
- }
- }
- }
- return $result;
- }
- function debug() {
- global $_global;
- ob_start();
- echo '<div style="text-align:left; margin-bottom:10px">';
- $raw = debug_backtrace();
- $id_debug = 0;
- // Recuperer les arguments passes a la fonction debug
- $arguments = $raw[0]['args'];
- // Afficher le pseudo qui devrait etre le premier parametre
- if (empty($arguments[0]) || is_array($arguments[0]))
- $user = 'Inconnu';
- else {
- $user = $arguments[0];
- unset($arguments[0]);
- }
- echo '<h2 style="margin:8px 2px 4px">== ' . $user . ' [' . $_global['self'] . '] ==</h2>';
- // Parser les arguments passes a la fonction debug
- echo '<h2 style="margin:8px 2px 4px">Parametres :</h2><div style="padding-left:25px">';
- $args = '';
- foreach ($arguments as $arg)
- $args .= debug_getArg($arg, ++$id_debug);
- echo substr($args, 2) . '</div>';
- // On affiche pas l'appel à la fonction debug
- unset($raw[0]);
- // Afficher tous les autres appels de fonction et leurs arguments
- echo '<h2 style="margin:8px 2px 4px">BackTrace :</h2><div style="padding-left:25px">';
- foreach ($raw as $entry) {
- $args = '';
- foreach ($entry['args'] as $arg)
- $args .= debug_getArg($arg, ++$id_debug);
- echo '<p style="margin:4px 0px">',
- '<b style="display: inline-block; width: 5em; text-align: right; margin-right: 4px;">File:</b> ' . $entry['file'] . ' (Line: ' . $entry['line'] . ')<br />',
- '<b style="display: inline-block; width: 5em; text-align: right; margin-right: 4px;">Function:</b> ' . $entry['function'] . ' ( ' . substr($args, 2) . ' )',
- '</p>';
- }
- echo '</div></div>';
- ob_end_flush();
- }
- // Fonction pour afficher un paramètre sous forme de chaine
- function debug_getArg($arg, $id_debug) {
- if (is_array($arg))
- return ', [<span onmouseover="document.getElementById(\'_debug' . $id_debug . '\').style.display=\'block\';" onmouseout="document.getElementById(\'_debug' . $id_debug . '\').style.display=\'none\';" style="color:blue;">array(' . count($arg) . ')</span>]<span id="_debug' . $id_debug . '" style="display:none; position:absolute; white-space:pre; background:#fff; border:2px solid #000; padding:2px 6px; z-index:500;">' . var_export($arg, true) . '</span>';
- elseif (is_object($arg))
- return ', [<span onmouseover="document.getElementById(\'_debug' . $id_debug . '\').style.display=\'block\';" onmouseout="document.getElementById(\'_debug' . $id_debug . '\').style.display=\'none\';" style="color:blue;">object</span>]<span id="_debug' . $id_debug . '" style="display:none; position:absolute; white-space:pre; background:#fff; border:2px solid #000; padding:2px 6px; z-index:500;">' . var_export($arg, true) . '</span>';
- elseif (is_null($arg))
- return ', <span style="color:green">null</span>';
- elseif (is_string($arg))
- return ', <span style="color:gray">`' . $arg . '`</span>';
- return ', <span style="color:red">' . $arg . '</span>';
- }
- function debug2($var, $line = 0, $file = 0) {
- echo ("<div id='debug' style='width:950px; background:#F6DC12; padding:5px; text-align:left; margin:0;'><p>Etat des variables a la ligne : " . $line . " dans le fichier : " . $file . "</p>\n");
- if (is_array($var)) {
- echo '<p>';
- debug_array($var);
- echo '</p>';
- } else {
- echo "<p>" . $var . "</p>";
- }
- echo "</div>";
- }
- function debug_array($var) {
- foreach ($var as $key => $value) {
- if (is_array($value)) {
- echo '<b>- ' . $key . ' : </b>';
- echo "<ul style='margin:0 0 0 20px;'>";
- debug_array($value);
- echo "</ul>";
- } else {
- echo "<li style='list-style:none; margin: 0 0 0 20px;'>" . $key . " => " . $value . "</li>";
- }
- }
- }
- //Fonction pour transformer une chaîne de caractères en URL.
- function str_to_url($string) {
- // Supprimer tous les accents + strtolower
- $string = prepareToUrl($string);
- // Remplacer les caractères spéciaux par un tiret
- $string = str_replace(array("=", "°", "«", "»", "/", "<", ">", ",", ";", ":", "*", "…"), '-', $string);
- // Remplacer le symbole euro
- $string = str_replace('€', 'euros', $string);
- // Supprimer les doubles tirets et les tirets de fin de ligne
- $cleanUrl = preg_replace(array('/--+/', '/-$/', '/[^-a-zA-Z0-9@]/'), array('-', '', ''), $string);
- return $cleanUrl;
- }
- function uriToSeo($request_uri, $keep_quotes = false) {
- global $convert_from_to;
- // Retirer la chaine des paramètres ?param1=..¶m2=..
- $parts = explode('?', $request_uri);
- // Eviter d'avoir des caractères html encodés qui subsistent
- $uri = urldecode($parts[0]);
- // Conserver les parametres pour les rajouter à la fin
- // On ne fait pas de traitements dessus
- $params = isset($parts[1]) ? '?' . $parts[1] : '';
- // Echapper le underscore _ qui constitue le(s) lockey(s)
- // Echapper les slash qui constituent l'url
- $uri = preg_replace('`_([0-9]*[,-.])`', '£$1', $uri);
- $uri = str_replace('/', 'µ', $uri);
- if ($keep_quotes)
- $uri = str_replace('\'', '¤', $uri);
- // Supprimer tous les caractères spéciaux et remplacer par des '-'
- $uri = strtr($uri, $convert_from_to);
- // Annuler l'echappement de l'underscore et du slash
- $uri = str_replace('£', '_', $uri);
- $uri = str_replace('µ', '/', $uri);
- if ($keep_quotes)
- $uri = str_replace('¤', '\'', $uri);
- // Remplacer les tirets consecutifs par un seul
- $uri = preg_replace('`-{2,}`', '-', $uri);
- //die($_SERVER['REQUEST_URI'].'<br />'.strtolower($uri).$params);
- // Renvoyer la chaine en minsucule
- return strtolower($uri) . $params;
- }
- // Return true if city is in fact an arrondissement of a french city
- function isArrondCity($city) {
- $ret = array(false, "");
- if (isset($city["lct_id"]) && !empty($city["lct_id"])) { // si lct_id défini
- $lct_id = $city["lct_id"];
- //echo "[lct_id = $lct_id]"; //exit();
- $lct_ids_arrond_paris = array(23599, 23601, 23602, 23603, 23604, 23605, 23606, 23607, 23609, 23589, 23590, 23591, 23592, 23593, 23594, 23595, 23596, 23597, 23598, 23600);
- $lct_ids_arrond_marseille = array(36102, 36104, 36105, 36106, 36107, 36108, 36109, 36110, 36111, 36112, 36113, 36114, 36115, 36116, 36117, 36118);
- $lct_ids_arrond_lyon = array(36119, 36120, 36121, 36122, 36123, 36124, 36125, 36126, 36127);
- if (in_array($lct_id, $lct_ids_arrond_paris)) {
- $ret = array(true, "paris");
- } else if (in_array($lct_id, $lct_ids_arrond_marseille)) {
- $ret = array(true, "marseille");
- } else if (in_array($lct_id, $lct_ids_arrond_lyon)) {
- $ret = array(true, "lyon");
- }
- } else if (isset($city["lct_name"]) && !empty($city["lct_name"])) { // si lct_name défini
- $lct_name = $city["lct_name"];
- //echo "[lct_name = $lct_name]"; //exit();
- $lct_names_arrond_paris = array("paris 1er", "paris 2e", "paris 3e", "paris 4e", "paris 5e", "paris 6e", "paris 7e", "paris 8e", "paris 9e", "paris 10e", "paris 11e", "paris 12e", "paris 13e", "paris 14e", "paris 15e", "paris 16e", "paris 17e", "paris 18e", "paris 19e", "paris 20e");
- $lct_names_arrond_marseille = array("marseille 1er", "marseille 2e", "marseille 3e", "marseille 4e", "marseille 5e", "marseille 6e", "marseille 7e", "marseille 8e", "marseille 9e", "marseille 10e", "marseille 11e", "marseille 12e", "marseille 13e", "marseille 14e", "marseille 15e", "marseille 16e");
- $lct_names_arrond_lyon = array("lyon 1er", "lyon 2e", "lyon 3e", "lyon 4e", "lyon 5e", "lyon 6e", "lyon 7e", "lyon 8e", "lyon 9e");
- if (in_array($lct_name, $lct_names_arrond_paris)) {
- $ret = array(true, "paris");
- } else if (in_array($lct_name, $lct_names_arrond_marseille)) {
- $ret = array(true, "marseille");
- } else if (in_array($lct_name, $lct_names_arrond_lyon)) {
- $ret = array(true, "lyon");
- }
- }
- return $ret;
- }
- /* NEXITY */
- // returns a phone number stripped from weird characters
- function clean_phone($value, $block = false) {
- if ($value == "") {
- return;
- }
- $value = str_replace(" ", "", $value);
- $value = str_replace(".", "", $value);
- $value = str_replace("+33(0)", "0", $value);
- if ($block == true) {
- return $value;
- } else {
- return substr($value, 0, 2) . " " . substr($value, 2, 2) . " " . substr($value, 4, 2) . " " . substr($value, 6, 2) . " " . substr($value, 8, 2);
- }
- }
- // retuns linkeo string
- function build_linkeo_string($index, $number) {
- $phone = clean_phone($number, true);
- return "click_to_call(" . $index . ", " . ((date("G") > 9 && date("G") < 19) ? 1 : 0) . ", '" . $phone . "', '" . md5($phone . LINKEO_KEY_1 . LINKEO_KEY_2) . "')";
- }
- /**
- * UPDATE NEXITY STAT ON STAT DB
- *
- * @param array $prg_data program data
- * @param String $prg_id program ID
- * @param $mode UPDATE click or PRINT STATS
- *
- * @return void
- */
- function Update_nexity_stat($prg_data, $prg_id, $mode = "prints") {
- include_once(URL_LIB . '/synchrostats.class.php');
- $SynchroStats = new SynchroStats($_SERVER['SERVER_ADDR'], "neuf_relay");
- /*
- $is_nexity = 1, s'il s'agit d'un programme Nexity
- $position = 1 ou 2, selon le relais
- */
- $position = 2;
- $url = $prg_data['prg_url'];
- $id_presto = $prg_data["id_presto"];
- $id_agence = $prg_data["id_agence"];
- $post_code = $prg_data["post_code"];
- $is_nexity = 1;
- switch ($mode) {
- case "clicks":
- //-- REDIRECTION VERS LE SITE DU PARTENAIRE
- $PARTDATA["id_presto"] = $id_presto;
- $PARTDATA["id_agence"] = $id_agence;
- $PARTDATA["id_programme"] = $prg_id;
- $PARTDATA["url"] = $url;
- $PARTDATA["post_code"] = $post_code;
- $PARTDATA["is_clic"] = "1";
- $PARTDATA["is_nexity"] = $is_nexity;
- break;
- case "none":
- //-- AFFICHAGE D'AUCUN RELAI TROUVE (PAS UTILISE POUR L'INSTANT)
- $PARTDATA["post_code"] = $post_code;
- $PARTDATA["position"] = $position;
- $PARTDATA["is_shown"] = "1";
- break;
- default:
- //-- AFFICHAGE D'UN RELAI AFFICHE
- $PARTDATA["id_presto"] = $id_presto;
- $PARTDATA["id_agence"] = $id_agence;
- $PARTDATA["id_programme"] = $prg_id;
- $PARTDATA["post_code"] = $post_code;
- $PARTDATA["position"] = $position;
- $PARTDATA["url"] = $url;
- $PARTDATA["is_shown"] = "1";
- $PARTDATA["is_nexity"] = $is_nexity;
- break;
- }
- /*
- echo "<pre>";
- print_r($PARTDATA);
- echo "</pre>";
- */
- $SynchroStats->SynchroStats_Posting($PARTDATA);
- }
- // Retourne les coordonnees GPS d'une localite
- function get_loc_gps($lct_id, $lgc = false) {
- if ($lgc == 'lgc') {
- $sql = "SELECT lgc_lat as lat, lgc_long as lng FROM T_LOCGROUPCODE_LGC_FR WHERE lgc_id = $lct_id LIMIT 1";
- } elseif ($lgc == 'lgn') {
- $sql = "SELECT lgn_lat as lat, lgn_long as lng FROM T_LOCGROUPNAME_LGN_FR WHERE lgn_id = $lct_id LIMIT 1";
- } else {
- $sql = "SELECT lct_lat as lat, lct_long as lng FROM TM_LOC_FR WHERE lct_id = $lct_id LIMIT 1";
- }
- global $_global;
- if ($_global["debug"] == 3) {
- echo "get_loc_gps()<br />";
- echo $sql . "<br />";
- echo "<hr />";
- }
- $res = pdoquery($sql);
- return $res;
- }
- /*
- * Return the edition name and code from the post code of a locality
- */
- function get_edition_from_post_code($post_code) {
- $obj = null;
- $sql = "
- SELECT edt_code,
- edt_name
- FROM TM_EDT_LOC_FR el
- INNER JOIN TM_EDT_FR e
- ON el.edtloc_edt_code = e.edt_code
- WHERE el.edtloc_loc_post_code = '" . $post_code . "'
- LIMIT 1
- ";
- //echo "<hr>$sql</hr><br/>";
- $res = pdoquery($sql);
- if ($_global["debug"] == 3) {
- echo "get_edition_from_post_code()<br />";
- echo $sql . "<br />";
- echo "<hr />";
- }
- if (count($res) > 0) {
- $obj = $res[0];
- }
- return $obj;
- }
- /**
- * Generate content snapshot (img or text + link to agency)
- *
- * @param String $id_presto - Agency id presto
- * @param String $id_agence - Agency id
- * @param String $ag_website - Agency website
- * @param Boolean $return_link - Include the content into a link to agency website
- * @param Boolean $use_default_img - Return a default image instead of default string
- * @param String $default_img - Logo si pas de snapshot (notamment pour les exclus)
- * @return String snaphost
- */
- function get_snapshot_content($id_presto_agence_md5, $id_agence, $ag_website, $return_link = null, $use_default_img = false, $default_img = '', $ag_name = '') {
- //function get_snapshot_content($id_presto, $id_agence, $ag_website, $return_link = null, $use_default_img = false, $default_img = '', $ag_name = '') {
- //echo $id_presto." <<<";echo $id_agence." <<<";
- $alt_string = "Cliquez ici pour visiter le site de l'agence.";
- if ($use_default_img) {
- if ($default_img == '') {
- $default_content = '<img border="0" src="' . get_urlmmf('/snapshot/nothumb.jpg') . '" height="120" width="160" alt="' . $ag_name . '" />';
- } else {
- $default_content = '<img border="0" src="' . $default_img . '" alt="' . $ag_name . '" />';
- }
- }
- else
- $default_content = $alt_string;
- // Par défaut, on se base sur le lien du site internet (si précisé)
- if ($return_link === null)
- $return_link = empty($ag_website) ? false : true;
- // Vérifier qu'un lien est demandé et que l'agence a bien un site internet
- elseif ($return_link && empty($ag_website))
- return '';
- // Verifier les valeurs envoyées
- if (empty($id_presto_agence_md5) || empty($id_agence))
- return $default_content;
- // Récupérer le chemin du snapshot
- //$snap_name = ltrim(trim($id_presto_agence_md5), '0') . '.jpg'; NON MAIS ALLO !!!! QU'EST CE QUE C'EST QUE CA ???!!!!
- $snap_name = trim($id_presto_agence_md5). '.jpg';
- $url_mmf_img = get_urlmmf_agc($snap_name, $id_agence, 'snapshot');
- //echo $url_mmf_img;
- // Tester l'existence du snapshot
- $test_open = true;
- /*
- if($url_mmf_img[0]=='/') $test_open = file_exists($_SERVER['DOCUMENT_ROOT'].$url_mmf_img);
- //else $test_open = http_exists($url_mmf_img);
- else $test_open = fopen($url_mmf_img, "r");
- */
- /* else
- {
- echo "FUKKK IT !!";
- $test_open = is_file($url_mmf_img);
- }
- else
- {
- echo "FUCK";
- $test_open = (!filetype($url_mmf_img) == false ? true : false);
- }
- */
- //return $url_mmf_img;
- // Générer le contenu du snapshot (image ou texte)
- if ($test_open) {
- $content = '<img src="' . $url_mmf_img . '" alt="' . $alt_string . '" height="120" width="160" title="' . $ag_name . '" />';
- } elseif ($default_img != '') {
- $content = '<img src="' . $default_img . '" alt="' . $alt_string . '" title="' . $ag_name . '" />';
- } else {
- $content = $default_content;
- }
- // Ne pas générer le lien vers le site agence
- if (!$return_link)
- return $content;
- // Générer le lien vers le site de l'agence
- return '<a href="' . $ag_website . '" title="' . $ag_name . '" rel="' . $id_presto_agence_md5 . ' nofollow" target="_blank" class="snapshot_content">' . $content . '</a>';
- }
- function http_exists($url) {
- $ch = curl_init($url);
- // Définir les options Curl
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return web page
- curl_setopt($ch, CURLOPT_HEADER, false); // don't return headers
- curl_setopt($ch, CURLOPT_NOBODY, true); // don't return body
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // do not follow redirects
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // timeout on connect
- curl_setopt($ch, CURLOPT_TIMEOUT, 2); // timeout on response
- if (!curl_exec($ch))
- return false;
- $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // Renvoie True si le code est 200 (ok) ou 304 (cache)
- return ($http_code == '200' || $http_code == '304');
- }
- /////////////////////////////////////////////////////////////////////////////////
- // FONCTIONS GLOBALES DIVERSES
- /////////////////////////////////////////////////////////////////////////////////
- /*
- * Supprimer tous les caractère spéciaux (accents, cesures, cedilles, etc.)
- * Meme les caractères HTML ( â é ...)
- * Renvoie la chaine en minuscule pour l'url
- * Florian PLANCHON - 05/2010
- */
- $convert_from_to = array(
- // Traitement de tous les caractères spéciaux
- 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Ā' => 'A', 'Ă' => 'A', 'Ǎ' => 'A', 'Ạ' => 'A', 'Ả' => 'A', 'Ấ' => 'A', 'Ầ' => 'A', 'Ẩ' => 'A', 'Ẫ' => 'A', 'Ậ' => 'A', 'Ắ' => 'A', 'Ằ' => 'A', 'Ẳ' => 'A', 'Ẵ' => 'A', 'Ặ' => 'A', 'Ǻ' => 'A', 'Ą' => 'A', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'ā' => 'a', 'ă' => 'a', 'ǎ' => 'a', 'ạ' => 'a', 'ả' => 'a', 'ấ' => 'a', 'ầ' => 'a', 'ẩ' => 'a', 'ẫ' => 'a', 'ậ' => 'a', 'ắ' => 'a', 'ằ' => 'a', 'ẳ' => 'a', 'ẵ' => 'a', 'ặ' => 'a', 'ǻ' => 'a', 'ą' => 'a',
- 'Ç' => 'C', 'Ć' => 'C', 'Ĉ' => 'C', 'Ċ' => 'C', 'Č' => 'C', 'ç' => 'c', 'ć' => 'c', 'ĉ' => 'c', 'ċ' => 'c', 'č' => 'c',
- 'Ð' => 'D', 'Ď' => 'D', 'Đ' => 'D', 'ď' => 'd', 'đ' => 'd',
- 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ē' => 'E', 'Ĕ' => 'E', 'Ė' => 'E', 'Ę' => 'E', 'Ě' => 'E', 'Ẹ' => 'E', 'Ẻ' => 'E', 'Ẽ' => 'E', 'Ế' => 'E', 'Ề' => 'E', 'Ể' => 'E', 'Ễ' => 'E', 'Ệ' => 'E', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ē' => 'e', 'ĕ' => 'e', 'ė' => 'e', 'ę' => 'e', 'ě' => 'e', 'ẹ' => 'e', 'ẻ' => 'e', 'ẽ' => 'e', 'ế' => 'e', 'ề' => 'e', 'ể' => 'e', 'ễ' => 'e', 'ệ' => 'e',
- 'Ĝ' => 'G', 'Ğ' => 'G', 'Ġ' => 'G', 'Ģ' => 'G', 'ĝ' => 'g', 'ğ' => 'g', 'ġ' => 'g', 'ģ' => 'g',
- 'Ĥ' => 'H', 'Ħ' => 'H', 'ĥ' => 'h', 'ħ' => 'h',
- 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ĩ' => 'I', 'Ī' => 'I', 'Ĭ' => 'I', 'Į' => 'I', 'İ' => 'I', 'Ǐ' => 'I', 'Ỉ' => 'I', 'Ị' => 'I', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ĩ' => 'i', 'ī' => 'i', 'ĭ' => 'i', 'į' => 'i', 'i' => 'i', 'ǐ' => 'i', 'ỉ' => 'i', 'ị' => 'i',
- 'Ĵ' => 'J', 'Ķ' => 'K', 'ķ' => 'k',
- 'Ĺ' => 'L', 'Ļ' => 'L', 'Ľ' => 'L', 'Ŀ' => 'L', 'Ł' => 'L', 'ĺ' => 'l', 'ļ' => 'l', 'ľ' => 'l', 'ŀ' => 'l', 'ł' => 'l',
- 'Ñ' => 'N', 'Ń' => 'N', 'Ņ' => 'N', 'Ň' => 'N', 'ñ' => 'n', 'ń' => 'n', 'ņ' => 'n', 'ň' => 'n', 'ʼn' => 'n',
- 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ō' => 'O', 'Ŏ' => 'O', 'Ő' => 'O', 'Ơ' => 'O', 'Ǒ' => 'O', 'Ǿ' => 'O', 'Ọ' => 'O', 'Ỏ' => 'O', 'Ố' => 'O', 'Ồ' => 'O', 'Ổ' => 'O', 'Ỗ' => 'O', 'Ộ' => 'O', 'Ớ' => 'O', 'Ờ' => 'O', 'Ở' => 'O', 'Ỡ' => 'O', 'Ợ' => 'O', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ō' => 'o', 'ŏ' => 'o', 'ő' => 'o', 'ơ' => 'o', 'ǒ' => 'o', 'ǿ' => 'o', 'ọ' => 'o', 'ỏ' => 'o', 'ố' => 'o', 'ồ' => 'o', 'ổ' => 'o', 'ỗ' => 'o', 'ộ' => 'o', 'ớ' => 'o', 'ờ' => 'o', 'ở' => 'o', 'ỡ' => 'o', 'ợ' => 'o', 'ð' => 'o',
- 'Ŕ' => 'R', 'Ŗ' => 'R', 'Ř' => 'R', 'ŕ' => 'r', 'ŗ' => 'r', 'ř' => 'r',
- 'Ś' => 'S', 'Ŝ' => 'S', 'Ş' => 'S', 'Š' => 'S', 'ś' => 's', 'ŝ' => 's', 'ş' => 's', 'š' => 's',
- 'Ţ' => 'T', 'Ť' => 'T', 'Ŧ' => 'T', 'ţ' => 't', 'ť' => 't', 'ŧ' => 't',
- 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ũ' => 'U', 'Ū' => 'U', 'Ŭ' => 'U', 'Ů' => 'U', 'Ű' => 'U', 'Ų' => 'U', 'Ư' => 'U', 'Ǔ' => 'U', 'Ǖ' => 'U', 'Ǘ' => 'U', 'Ǚ' => 'U', 'Ǜ' => 'U', 'Ụ' => 'U', 'Ủ' => 'U', 'Ứ' => 'U', 'Ừ' => 'U', 'Ử' => 'U', 'Ữ' => 'U', 'Ự' => 'U', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ũ' => 'u', 'ū' => 'u', 'ŭ' => 'u', 'ů' => 'u', 'ű' => 'u', 'ų' => 'u', 'ư' => 'u', 'ǔ' => 'u', 'ǖ' => 'u', 'ǘ' => 'u', 'ǚ' => 'u', 'ǜ' => 'u', 'ụ' => 'u', 'ủ' => 'u', 'ứ' => 'u', 'ừ' => 'u', 'ử' => 'u', 'ữ' => 'u', 'ự' => 'u', 'Ŵ' => 'W', 'Ẁ' => 'W', 'Ẃ' => 'W', 'Ẅ' => 'W',
- 'ŵ' => 'w', 'ẁ' => 'w', 'ẃ' => 'w', 'ẅ' => 'w',
- 'Ý' => 'Y', 'Ŷ' => 'Y', 'Ÿ' => 'Y', 'Ỳ' => 'Y', 'Ỹ' => 'Y', 'Ỷ' => 'Y', 'Ỵ' => 'Y', 'ý' => 'y', 'ÿ' => 'y', 'ŷ' => 'y', 'ỹ' => 'y', 'ỵ' => 'y', 'ỷ' => 'y', 'ỳ' => 'y',
- 'Ź' => 'Z', 'Ż' => 'Z', 'Ž' => 'Z', 'ź' => 'z', 'ż' => 'z', 'ž' => 'z',
- // Traitements des caractères collés
- 'Æ' => 'AE', 'æ' => 'ae', 'Œ' => 'OE', 'œ' => 'oe',
- // Traitements de caractères pour l'url
- ' ' => '-', '+' => '-', '_' => '-', '\'' => '-', '’' => '-',
- // Traitements pour les chaines spéciales
- 's/' => 'sur', '/' => '-', '(' => '', ')' => '', ' ~ ' => '-', '~' => '-'
- );
- function prepareToUrl($string) {
- global $convert_from_to;
- // Eviter d'avoir des caractères html encodés qui subsistent
- $string = html_entity_decode($string, ENT_COMPAT, 'UTF-8');
- // Supprimer tous les caractères spéciaux et remplacer par des '-'
- $string = strtr($string, $convert_from_to);
- // Remplacer les tirets consecutifs par un seul
- $string = preg_replace('`-{2,}`', '-', $string);
- // Renvoyer la chaine en minsucule
- return strtolower($string);
- }
- /**
- * @author W.Asbaiti
- * @since 02/05/2011
- * Appel a un script sur le serveur RW(definit dans la conf) afin d'ecrire sur la BDD RW
- *
- * @param string adresse du serveur $server
- * @param string $url url du fichier a appeler
- * @param array $data tableau des donnees a envoyer
- */
- function RW_post($server = RW_SERVER, $url, $data) {
- // var_dump(wget($server.$url)); //die;
- $error_messages = array();
- set_time_limit(120);
- // Preparation de la partie donnees (le headr a besoin de la taille de cette partie
- $urlvars = $data;
- foreach ($data as $key => $value) {
- $export_par .= "&" . $key . "=" . rawurlencode($value);
- }
- // Préparation du header
- $header = "POST " . $url . " HTTP/1.0\r\n";
- $header .= "Host: " . $server . "\r\n";
- $header .= "Accept: */*\r\n";
- $header .= "AcceptLanguage: fr\r\n";
- $header .= "Connection: Keep-Alive\r\n";
- $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
- $header .= "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0;\r\n";
- $header .= "Content-Length: " . strlen($export_par) . "\r\n";
- $header .= "\r\n";
- $fs = fsockopen($server, 80, $errno, $errstr, 30);
- if ($fs) {
- fwrite($fs, $header . $export_par . "\r\n\r\n");
- $nb = 0;
- while (!feof($fs) && $nb < 2) {
- $line = fgets($fs);
- $http_res[] = $line;
- if (substr($line, 0, 2) == "\r\n") {
- $nb++;
- };
- };
- fclose($fs);
- return $http_res;
- } else {
- echo "ERREUR CONNECTION";
- die;
- }
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $string
- * @return unknown
- */
- //function getPropretyNameFromId($id, $do_use_label2=false) {
- function getPropretyNameFromId($id, $univ) {
- //global $_ADVANCED_SEARCH_TYPES;
- global $_ADVANCED_SEARCH_TYPES_DEFINITION;
- //foreach ($_ADVANCED_SEARCH_TYPES as $type) {
- foreach ($_ADVANCED_SEARCH_TYPES_DEFINITION[$univ] as $type) {
- $type_values = explode(',', $type['value']);
- //if ($type['value'] == $id) {
- if (in_array($id, $type_values)) {
- if (isset($type['label2']) && !empty($type['label2'])) {
- $label = $type['label2']; // utile pour la coloc.
- } else {
- $label = $type['label'];
- }
- return $label;
- }
- }
- return false;
- }
- function getPropretyValueFromId($id, $univ) {
- //global $_ADVANCED_SEARCH_TYPES;
- global $_ADVANCED_SEARCH_TYPES_DEFINITION;
- //foreach ($_ADVANCED_SEARCH_TYPES as $type) {
- foreach ($_ADVANCED_SEARCH_TYPES_DEFINITION[$univ] as $type) {
- $type_values = explode(',', $type['value']);
- if (in_array($id, $type_values)) {
- if (isset($type['value'])) {
- $value = $type['value'];
- }
- return $value;
- }
- }
- return false;
- }
- /* * *
- * Check if the property type is valid
- * (array $_ADVANCED_SEARCH_TYPES_DEFINITION definition in DEV/LIB/config.settings.php
- * @author Hoarau Melissa
- *
- * @param int id : position in ck_property_type string
- * @param int univ : id univers
- *
- * @return bool
- */
- function isInvalidIdProperty($id, $univ) {
- // Property type array
- global $_ADVANCED_SEARCH_TYPES_DEFINITION;
- //valid values
- $aType_values = array();
- foreach ($_ADVANCED_SEARCH_TYPES_DEFINITION[$univ] as $type) {
- $aType_values[] = $type['value'];
- }
- if (!in_array($id, $aType_values)) {
- return true;
- }
- else
- return false;
- }
- /* * *
- * Check if the page must be redirect to 404
- *
- * @author Hoarau Melissa
- * @param string sBinaryPropertyType : the property type (ex : '00010100110000000'...)
- * @param int univ : id univers
- *
- * @return bool
- */
- function invalidPropertyToRedirect($sBinaryPropertyType, $univ) {
- $bFindInvalid = false;
- $iCptProperty_type = 0;
- for ($i = 0; $i < strlen($sBinaryPropertyType); $i++) {
- $iProperty_type = $sBinaryPropertyType[$i];
- if (0 != $iProperty_type) {
- $iCptProperty_type++;
- if (isInvalidIdProperty(($i + 1), $univ)) {
- $bFindInvalid = true;
- }
- }
- }
- // If an invalid property type is found & if it's only in sBinaryPropertyType => redirect 404
- if ($bFindInvalid && $iCptProperty_type < 2) {
- return true;
- }
- return false;
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $string
- * @return unknown
- */
- function getPropertiesValuesFromCkPropertyType($value, $univ) {
- $array_ads_property_type = array();
- if (isset($value) && strlen($value) == 40) { // type de bien
- for ($i = 0; $i < strlen($value); $i++) {
- if ($value[$i] == 0)
- continue;
- $value_property_type = getPropretyValueFromId($i + 1, $univ);
- $value_property_type = explode(',', $value_property_type);
- foreach ($value_property_type as $type) {
- if (!in_array($type, $array_ads_property_type)) {
- array_push($array_ads_property_type, $type);
- }
- }
- }
- }
- return $array_ads_property_type;
- }
- /**
- * Enter description here...
- *
- * @param unknown_type $string
- * @return unknown
- */
- function string_cleaner($string = "") {
- $string = trim($string);
- // On remplace les tirets et underscore par un espace
- // Et on supprime les espaces consécutifs
- $arr_pattern = array("(-)", "(_)", "/\?/", "(!)", "(<)", "(>)", "(\s+)");
- $string = preg_replace($arr_pattern, ' ', $string);
- $string = srmtoupper($string, true); //Suppresion des accents
- $arr_pattern = array("/\bST\b/i", "/\bSTE\b/i", "/\bSTES\b/i");
- $arr_replace = array("SAINT", "SAINTE", "SAINTES");
- return preg_replace($arr_pattern, $arr_replace, $string);
- }
- /**
- * Génère l'url d'une page résultats annonces à partir d'une recherche sur le moteur
- * (et uniquement depuis le moteur, pas depuis un lien venant d'une page externe)
- *
- * @param String $string
- * @return Array
- */
- function uriToFinalFromSearchEngine($_GET_INFOS) {
- //var_dump($_GET_INFOS);
- //////////////////////// PROCESS FREE T9 //////////////////////////////////
- /* On verifie les loc_id Postés par le moteur dans le cas d'un T9 ouvert
- On attend deux chaines numériques séparés par un underscore "_" */
- $flag_ambigu = false;
- $flag_some_found = false;
- $loc_not_found = 0;
- $cnt = 1;
- $req_loc = array();
- $check_search = array();
- // Utilise COOKIE aulieu de SESSION
- $cookieExpires = mktime(0, 0, 0, 1, 1, 1970); // For delete cookie
- setcookie("AMBIGUITE_LOC_NAME", "", $cookieExpires);
- unset($_COOKIE["AMBIGUITE_LOC_NAME"]);
- setcookie("AMBIGUITE_CRITERIONS", "", $cookieExpires);
- unset($_COOKIE["AMBIGUITE_CRITERIONS"]);
- /*
- $tab_query_string = explode("&", $_SERVER["QUERY_STRING"]);
- $tab_result_query = array();
- for ($cpt=0; $cpt < count($tab_query_string); $cpt++)
- {
- $tab_result_query[$cpt] = explode("=",$tab_query_string[$cpt]);
- $tab_new_query[$tab_result_query[$cpt][0]] = $tab_result_query[$cpt][1];
- }
- */
- $tab_new_query = $_GET_INFOS;
- $array_page_ambg = array(
- 1 => "ambiguous_vente_fr.php",
- 2 => "ambiguous_location_fr.php",
- 8 => "ambiguous_colocation_fr.php"
- );
- $array_special_cp = array('2a', '2b', '971', '972', '973', '974', '975', '976', '984', '986', '987', '988');
- for ($cntfields = 1; $cntfields <= SEARCH_FIELDS_NUMBER; $cntfields++) {
- // cas particulier de la ville Y, seule ville à 1 caractère
- if ($_REQUEST["loc_name" . $cntfields] == 'y') {
- $_GET_INFOS["loc_name" . $cntfields] = $_REQUEST["loc_name" . $cntfields] = $tab_new_query["loc_name" . $cntfields] = 'Y (80190)';
- $_GET_INFOS["loc_key" . $cntfields] = $_REQUEST["loc_key" . $cntfields] = $tab_new_query["loc_key" . $cntfields] = '36006_2';
- }
- if (empty($_REQUEST["loc_key" . $cntfields]))
- continue;
- $current_lockey = strtolower(trim($_REQUEST["loc_key" . $cntfields]));
- $current_locname = string_cleaner($_REQUEST["loc_name" . $cntfields]);
- // Si c'est un doublon, on ne le prend pas en compte
- if (in_array($current_lockey, $check_search))
- continue;
- // Ajouter au tableau des doublons
- $check_search[$cnt] = $current_lockey;
- $req_loc[$cnt]["loc_name"] = string_cleaner($current_locname);
- $req_loc[$cnt]["loc_key"] = 0;
- $req_loc[$cnt]["level"] = 0;
- $req_loc[$cnt]["ambigue"] = 0;
- $req_loc[$cnt]["loc_get"] = $current_lockey;
- // La clé de localité n'a pas le bon format
- if (isWrongLocKey($current_lockey)) {
- // Si c'est un code postal spécial (domtom ou corse), c'est ok
- if (in_array($current_lockey, $array_special_cp)) {
- // On récupère les infos de la localité
- $res_search = find_locname_by_czip($current_lockey, 1);
- $flag_some_found = true;
- $result = $res_search['res'][0];
- $lct_name = strtoupper(strtolower($result['lct_name_fr']));
- $lct_zip = $result['lct_post_code'];
- $lockey = $result['lct_id'] . "_" . $result['lct_level'];
- $req_loc[$cnt]["loc_key"] = $result['lct_id'];
- $req_loc[$cnt]["level"] = $result['lct_level'];
- $req_loc[$cnt]["loc_get"] = $lockey;
- $req_loc[$cnt]["loc_name"] = $lct_name . " (" . $lct_zip . ")"; //(strtolower($lct_name));
- $tab_new_query["loc_name" . $cnt] = urlencode($lct_name . "-" . $lct_zip);
- $tab_new_query["loc_key" . $cnt] = $lockey;
- ++$cnt;
- // Passer au champ suivant
- continue;
- }
- // On vérifie si la saisie est un code postal
- if (preg_match('`^[0-9]{2,5}$`', $current_lockey)) {
- if (strlen($current_lockey) == 2) {
- $mode_departement = 1;
- $current_lockey .= '000';
- } else {
- $mode_departement = 0;
- // Remplir à droite avec des 0 pour obtenir 5 caractères
- $current_lockey = str_pad($current_lockey, 5, 0);
- }
- $res_search = find_locname_by_czip($current_lockey, 1);
- //var_dump($res_search);
- $res_nb_results = $res_search['count'][0]['count'];
- if ($res_nb_results >= 1) {
- //Modification par Soflou pour gérer les villes dont le CP est égal XX000
- //
- //On vérifie si on a un level 2 (ville)
- $count_ville = 0;
- for ($cnt_res = 0; $cnt_res < $nb_results; $cnt_res++) {
- if ($res_search['res'][$cnt_res]['lct_level'] == 2)
- $count_ville++;
- }
- //Si une seule ville trouvée on affiche les resultats pour cette ville
- if ($count_ville == 1 && !$mode_departement == 1) {
- $last_id = count($res_search['res']) - 1;
- $res_ville = $res_search['res'][$last_id];
- // Remplacer les resultats par le dernier
- $res_search['res'] = array(0 => $res_ville);
- $res_nb_results = 1;
- }
- //On force pour gérer le département
- if ($res_search['res'][0]['lct_level'] == 1 && $count_ville == 0) {
- $res_nb_results = 1;
- }
- }
- // Gérer les différents cas du nombre de résultats
- switch ($res_nb_results) {
- case 0: //Aucun résultat
- // "No ZIP relationship"
- $loc_not_found++;
- $req_loc[$cnt]["loc_key"] = ""; //$val_zip_code;
- $req_loc[$cnt]["loc_get"] = ""; //$val_zip_code;
- $req_loc[$cnt]["level"] = 0;
- $req_loc[$cnt]["loc_get"] = "";
- $tab_new_query["loc_key" . $cnt] = "";
- break;
- case 1: //Un résultat unique
- $flag_some_found = true;
- $result = $res_search['res'][0];
- $lct_name = strtoupper(strtolower($result['lct_name_fr']));
- $lct_zip = $result['lct_post_code'];
- if ($result['lct_level'] == 1) { // Dépt
- if (string_begins_with($lct_zip, '97') || string_begins_with($lct_zip, '98')) { // Dom-Tom
- $lct_zip = substr($lct_zip, 0, 3);
- } else {
- $lct_zip = substr($lct_zip, 0, 2);
- }
- }
- $lockey = $result['lct_id'] . "_" . $result['lct_level'];
- $req_loc[$cnt]["loc_key"] = $result['lct_id'];
- $req_loc[$cnt]["level"] = $result['lct_level'];
- $req_loc[$cnt]["loc_get"] = $lockey;
- $req_loc[$cnt]["loc_name"] = $lct_name . " (" . $lct_zip . ")";
- $tab_new_query["loc_name" . $cnt] = urlencode($lct_name . "-" . $lct_zip);
- $tab_new_query["loc_key" . $cnt] = $lockey;
- break;
- default: //Multi résultat
- $flag_some_found = true;
- if ($mode_departement == 1) {
- $result = $res_search['res'][0];
- $lct_name = strtoupper(strtolower($result['lct_name_fr']));
- $lct_zip = substr($result['lct_post_code'], 0, 2);
- $lgc_id = ($result['lgc_id'] == 0 ? $result['lct_id'] : $result['lgc_id']);
- $lockey = $lgc_id . "_1";
- $req_loc[$cnt]["level"] = 1;
- } else {
- $result = $res_search['res'][1];
- $lct_name = "TOUTES-COMMUNES";
- $lct_zip = ($result['lct_post_code'] == '75000' ? '75' : $result['lct_post_code']);
- $lgc_id = empty($result['lgc_id']) ? $result['lct_id'] : $result['lgc_id'];
- $lockey = $lgc_id . "_98";
- $req_loc[$cnt]["level"] = "98";
- }
- $req_loc[$cnt]["loc_key"] = $lgc_id;
- $req_loc[$cnt]["loc_get"] = $lockey;
- $req_loc[$cnt]["loc_name"] = $lct_name . " (" . $lct_zip . ")"; //(strtolower($lct_name));
- $tab_new_query["loc_name" . $cnt] = urlencode($lct_name . "-" . $lct_zip);
- $tab_new_query["loc_key" . $cnt] = $lockey;
- break;
- }
- if ($cnt <> $cntfields) {
- $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
- $_GET_INFOS["loc_key" . $cntfields] = "";
- }
- }
- // Sinon, on vérifie si la saisie est bien une localité
- else {
- //saisie mode text
- // Supprimer la chaine de la localité par défaut
- // => Beaucoup d'url sont en erreur car la localité contenait cette chaine
- // => C'est dû à la durée avant effacement du t9 en entrant dans le champ pour modification
- $current_locname = str_ireplace(LABEL_DEFAULT_LOCALITY, '', $current_locname);
- // Gérer le cas où il y a le code postal dans la localité (entre parentheses)
- // On récupère la chaine qui se trouve avant la paranthese ouvrante.
- if (($pos = strpos($current_locname, '(')) > 3)
- $current_locname = substr($current_locname, 0, $pos);
- // Chercher par une requete du type " ='LOCNAME' "
- $res_search = find_locname_by_name($current_locname, 0);
- $liste_villes = $res_search['res'];
- $count_list_ville_total = $res_search['count'];
- $flag_count_over = in_array(strtoupper($current_locname), $no_freeT9_cities);
- // "Rien trouvé..."
- if (count($liste_villes) == 0) {
- // Chercher par une requete du type " LIKE 'LOCNAME' "
- $res_search = find_locname_by_name($current_locname, 1);
- $liste_villes = $res_search['res'];
- $count_list_ville_total = $res_search['count'];
- }
- $count_total_ville = $count_list_ville_total[0]['count'];
- $res_nb_results = count($liste_villes);
- if ($res_nb_results == 0) {
- //Si la localité n'existe pas on forme l'URL avec les parametre recu
- //J'ai détaché le fait que ca peut etre ambigue ou non trouvé
- $loc_not_found++;
- //$flag_ambigu=true;
- $locname = strtoupper(strtolower($current_locname));
- $req_loc[$cnt]["loc_name"] = $locname;
- $req_loc[$cnt]["loc_key"] = "0";
- $req_loc[$cnt]["level"] = "0";
- $req_loc[$cnt]["loc_get"] = "";
- $tab_new_query["loc_name" . $cnt] = $locname . "-";
- $tab_new_query["loc_key" . $cnt] = "";
- } elseif ($res_nb_results > 1) {
- //Rajout d'une fonction d'agrégation des codes postaux
- //On peut avoir des regroupement de code postaux pour une même ville
- $tab_grp_zip = array();
- $lgn_sav = $liste_villes[0]['lgn_id'];
- $cnt_lgn = 0;
- if ($lgn_sav <> 0) {
- for ($cnt_zip = 0; $cnt_zip < $res_nb_results; $cnt_zip++) {
- if ($liste_villes[$cnt_zip]['lgn_id'] == $lgn_sav)
- ++$cnt_lgn;
- }
- }
- // si $cnt_lgn = count(list_ville) alors regroupement sinon ambiguité
- if ($cnt_lgn == $res_nb_results) {
- $flag_some_found = true;
- $locname = strtoupper(strtolower($liste_villes[0]['lct_name_fr']));
- //Simili cas unique regroupement cpostaux
- $lct_id = $liste_villes[0]['lgn_id'];
- $req_loc[$cnt]["loc_name"] = $locname . " (" . LABEL_LGN_ALL . ")";
- $req_loc[$cnt]["loc_key"] = $lct_id;
- $req_loc[$cnt]["level"] = 99;
- $req_loc[$cnt]["loc_get"] = $_GET_INFOS["loc_key" . $cnt];
- $tab_new_query["loc_name" . $cnt] = urlencode($locname . "-" . str_replace(" ", "-", LABEL_LGN_ALL));
- $tab_new_query["loc_key" . $cnt] = $lct_id . "_99";
- if ($cnt <> $cntfields) {
- $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
- $_GET_INFOS["loc_key" . $cntfields] = "";
- }
- } else {
- /// sinon ambiguité de niveau 1
- //Si la localité n'existe pas on forme l'URL avec les parametre recu
- //J'ai détaché le fait que ca peut etre ambigue ou non trouvé
- $loc_not_found++;
- //$flag_ambigu=true;
- $locname = strtoupper(strtolower($current_locname));
- $req_loc[$cnt]["loc_name"] = $locname;
- $req_loc[$cnt]["loc_key"] = "0";
- $req_loc[$cnt]["level"] = "0";
- $req_loc[$cnt]["ambigue"] = 1;
- $tab_new_query["loc_name" . $cnt] = urlencode($locname) . "-";
- $tab_new_query["loc_key" . $cnt] = ""; //urlencode("0_0");
- $flag_ambigu = true;
- }
- } elseif ($res_nb_results > 19999999) {
- // 1 - Ambiguité simple
- // 2 - Trop de résultats
- if ($flag_count_over) {
- $req_loc[$cnt]["ambigue"] = 1;
- //Trop de résultats normalement = 2
- $flag_ambigu = true;
- } else {
- //On peut avoir des regroupement de code pôstaux pour une même ville
- $tab_grp_zip = array();
- $lgn_sav = $liste_villes[0]['lgn_id'];
- $cnt_lgn = 0;
- if ($lgn_sav <> 0) {
- for ($cnt_zip = 0; $cnt_zip < $res_nb_results; $cnt_zip++) {
- if ($liste_villes[$cnt_zip]['lgn_id'] == $lgn_sav)
- ++$cnt_lgn;
- }
- }
- // si $cnt_lgn = count(list_ville) alors regroupement sinon ambiguité
- if ($cnt_lgn == $res_nb_results) {
- $flag_some_found = true;
- $locname = strtoupper(strtolower($liste_villes[0][1]));
- $lockey = $liste_villes[0]['lgn_id'] . "_99";
- //Simili cas unique regroupement cpostaux
- $lct_post_code = $liste_villes[0][3];
- if ($lct_level == 1) { // Dépt
- if (string_begins_with($lct_post_code, '97') || string_begins_with($lct_post_code, '98')) { // Dom-Tom
- $lct_post_code = substr($lct_post_code, 0, 3);
- } else {
- $lct_post_code = substr($lct_post_code, 0, 2);
- }
- }
- $req_loc[$cnt]["loc_name"] = $locname . " (" . $lct_post_code . ")";
- $req_loc[$cnt]["loc_key"] = $liste_villes[0]['lgn_id'];
- $req_loc[$cnt]["level"] = 99; //$liste_villes[0][2];
- $req_loc[$cnt]["loc_get"] = $lockey;
- $tab_new_query["loc_name" . $cnt] = urlencode($locname . "_TOUS-CODES-POSTAUX");
- $tab_new_query["loc_key" . $cnt] = $lockey;
- if ($cnt <> $cntfields) {
- $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
- $_GET_INFOS["loc_key" . $cntfields] = "";
- }
- } else {
- /// sinon ambiguité de niveau 1
- $req_loc[$cnt]["ambigue"] = 1;
- $flag_ambigu = true;
- }
- }
- } else {
- //Résultat Unique
- $flag_some_found = true;
- $locname = strtoupper(strtolower($liste_villes[0][1]));
- $lct_id = $liste_villes[0][0];
- $lct_level = $liste_villes[0][2];
- $lockey = $lct_id . '_' . $lct_level;
- $lct_post_code = $liste_villes[0][3];
- if ($lct_level == 1) { // Dépt
- if (string_begins_with($lct_post_code, '97') || string_begins_with($lct_post_code, '98')) { // Dom-Tom
- $lct_post_code = substr($lct_post_code, 0, 3);
- } else {
- $lct_post_code = substr($lct_post_code, 0, 2);
- }
- }
- $req_loc[$cnt]["loc_name"] = $locname . " (" . $lct_post_code . ")";
- $req_loc[$cnt]["loc_key"] = $lct_id;
- $req_loc[$cnt]["level"] = $lct_level;
- $req_loc[$cnt]["loc_get"] = $lockey;
- $tab_new_query["loc_name" . $cnt] = urlencode($locname . "-" . $lct_post_code);
- $tab_new_query["loc_key" . $cnt] = $lockey;
- if ($cnt <> $cntfields) {
- $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
- $_GET_INFOS["loc_key" . $cntfields] = "";
- }
- }
- }
- } else {
- $flag_some_found = true;
- //Value from Closed-T9
- $tab_lockey = explode("_", $current_lockey);
- $req_loc[$cnt]["loc_key"] = $tab_lockey[0];
- $req_loc[$cnt]["level"] = $tab_lockey[1];
- }
- $cnt++;
- }
- if ($_REQUEST['dbg'] == 'flo') {
- echo '<pre>$_GET_INFOS :<br />';
- var_export($_GET_INFOS);
- echo '</pre><pre>$tab_new_query (utilise si OK) :<br />';
- var_export($tab_new_query);
- echo '</pre><pre>$req_loc (utilise si NOK) :<br />';
- var_export($req_loc);
- echo '</pre>';
- if ($flag_ambigu == true || $loc_not_found > 0)
- echo '<p style="color:red">Ambiguite ou localite non trouvee => Page ambiguite</p>';
- else
- echo '<p style="color:green">Aucune ambiguite => Page de resultats</p>';
- die();
- }
- if ($flag_ambigu == true || $loc_not_found > 0) {
- //On rajoute les critères
- /*
- if(isset($_GET_INFOS['ck_property_group']) && is_array($_GET_INFOS['ck_property_group']) ) {
- $property_types = $_GET_INFOS['ck_property_group'];
- $property_type = str_repeat('0',40 );
- foreach($property_types as $type_id) $property_type[$type_id-1] = '1';
- $req_criterion['property_type'] = $property_type;
- }
- */
- $req_criterion['price'] = $_GET_INFOS['price'];
- $req_criterion['price_min'] = $_GET_INFOS['price_min'];
- $req_criterion['price_max'] = $_GET_INFOS['price_max'];
- $req_criterion['area'] = $_GET_INFOS['area'];
- $req_criterion['area_min'] = $_GET_INFOS['area_min'];
- $req_criterion['area_max'] = $_GET_INFOS['area_max'];
- $req_criterion['ck_nb_rooms'] = $_GET_INFOS['ck_nb_rooms'];
- $req_criterion['ck_property_type'] = $_GET_INFOS['ck_property_type'];
- setcookie("AMBIGUITE_LOC_NAME", serialize($req_loc));
- $_COOKIE["AMBIGUITE_LOC_NAME"] = serialize($req_loc);
- setcookie("AMBIGUITE_CRITERIONS", serialize($req_criterion));
- $_COOKIE["AMBIGUITE_CRITERIONS"] = serialize($req_criterion);
- //On ne redirige vers pas d'ambiguité que si aucun resultat direct
- if ($flag_some_found == false) {
- redirection($_global['dns'] . $array_page_ambg[$_GET_INFOS["univers"]]);
- }
- }
- /* FIN VERIF du T9 ouvert */
- $page = (isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "/recherche_nat.php");
- //$page = "/recherche_nat.php";
- //echo "[common.functions : uriToFinalFromSearchEngine : page = $page]\n";
- switch ($_global['site']) {
- case "be":
- /* NE PAS EFFACER */
- $page = explode('/', $page);
- $page = $page[count($page) - 1];
- //list($trash, $page) = explode('/', $page);
- break;
- default:
- list($trash, $page) = explode('/', $page);
- break;
- }
- list($page) = explode('_', $page, 2);
- // On check si ca existe ou pas encore
- // Par défault si l'univers est location, on trie par date
- $saved_searches = unserialize($_COOKIE[SEARCH_HISTORY_COOKIE_NAME]);
- $saved_search = unserialize($saved_searches[0]);
- if ((!$saved_search || ($saved_search && ($saved_search['univers'] != $_global['univers']))) && $_global['univers'] == '2') {
- /*$tab_new_query['ordre'] = 'update_date';
- $tab_new_query['hi_order'] = '1';
- $tab_new_query['ck_property_type'] = '0000000000000000000000000000000000000000';
- *
- */
- $tab_new_query['ck_property_type'] = '1100001000000000000000000000000000000000';
- } else if ((!$saved_search || ($saved_search && ($saved_search['univers'] != $_global['univers']))) && $_global['univers'] == '1') {
- $tab_new_query['ck_property_type'] = '1100001000000000000000000000000000000000';
- }
- $tab_new_query['type_transaction'] = $_GET_INFOS["univers"];
- // Générer la nouvelle url seo correspondant à la recherche
- //echo "[common.functions : uriToFinalFromSearchEngine : tab_new_query = ".print_r($tab_new_query, true).", page = ".$page.", dns = ".$_global['dns']."]<br>\n";
-
- $url = to_nat($tab_new_query, $page, $_global['dns']);
-
- //echo "[common.functions : uriToFinalFromSearchEngine : url = $url]<br>\n"; //exit();
- // Ajouter le paramètre dbg pour rester dans le mode debug
- if (isset($_REQUEST['dbg'])) {
- if (strpos($url, '?') === false)
- $url = $url . '?dbg=' . $_REQUEST['dbg'];
- else
- $url = $url . '&dbg=' . $_REQUEST['dbg'];
- }
- //echo "[common.functions : uriToFinalFromSearchEngine : url = $url]\n";
- return $url;
- }
- /**
- * Génère l'url d'une page résultats annonces à partir d'une page externe au site
- * (et uniquement depuis une page externe, pas depuis un recherche sur le moteur)
- *
- * @param String $string
- * @return Array
- */
- function uriToFinalFromDirectLink($_GET_INFOS) {
- //echo "[common.functions : uriToFinalFromDirectLink : _GET_INFOS = ".print_r($_GET_INFOS, true)."]\n"; //exit();
- $url = '';
- ###############################################################################################################################################
- # URL courte modèle 1 (localité) : /annonces-{univ_name}-{loc_name}-{post_name}-{loc_key}-{offset}.html
- # URL courte modèle 2 (localité + type bien) : /{prop_type}-{loc_name}/{univ_name}-{prop_type}-{loc_name}-{post_name}-{loc_key}-{offset}.html
- # URL courte modèle 3 (localité + type bien + nbre pièces) : /{prop_type}-{loc_name}/{univ_name}-{prop_type}-{loc_name}/{prop_type}-{room_nbr}-{loc_name}-{post_code}-{loc_key}-{offset}.html
- ###############################################################################################################################################
- ###############################################################################################################################################
- # Vérifs communes aux modèles
- ###############################################################################################################################################
- // vérif univers défini et valide (vente, loc., coloc.)
- $string = $_GET_INFOS['univers'];
- $is_universe_valid = in_array($string, array('1', '2', '8'));
- if (!$is_universe_valid) {
- return $url;
- }
- // vérif localité définie et unique si oui, est bien valide (triplet loc_key/loc_name/post_code présent et valide)
- $string1 = $_GET_INFOS['lockeys'];
- $string2 = $_GET_INFOS['locnames'];
- $is_locality_uniq = isUniqLocKeyLocName($string1, $string2); // localité et lockey unique
- if (!$is_locality_uniq) {
- return $url;
- }
- $is_locality_valid = !isWrongLocKeyLocNamePostCode($string1, $string2); // localité, lockey et code postal cohérents
- if (!$is_locality_valid) {
- return $url;
- }
- // récup niveau et id niveau localité
- $url_loc_key = $_GET_INFOS['lockeys'];
- list($loc_key_val, $loc_key_lvl) = explode('_', $_GET_INFOS['lockeys']);
- // récup code postal et nom localité
- if ($loc_key_lvl == '98') {
- $url_loc_name = 'toutes-communes';
- $url_post_code = str_replace('toutes-communes-', '', $_GET_INFOS['locnames']);
- } else if ($loc_key_lvl == '99') {
- $url_loc_name = str_replace('-tous-codes-postaux', '', $_GET_INFOS['locnames']);
- $url_post_code = 'tous-codes-postaux';
- } else { // $loc_key_lvl == '1', '2', '99'
- $array = explode('-', $_GET_INFOS['locnames']);
- $url_post_code = $array[sizeof($array) - 1];
- $url_loc_name = str_replace('-' . $url_post_code, '', $_GET_INFOS['locnames']);
- }
- // récup pagination en cours
- $array = explode('-', $_GET_INFOS['query']);
- $is_offet_default = ($array[12] == '1');
- $url_offset = ($is_offet_default ? '' : $array[12]);
- //echo "[common.functions : uriToFinalFromDirectLink : url_loc_name=".$url_loc_name.", url_post_code=".$url_post_code.", url_loc_key=".$url_loc_key.", loc_key_val=".$loc_key_val.", loc_key_lvl=".$loc_key_lvl.", url_offset=".$url_offset."]\n";
- ###############################################################################################################################################
- # Vérifs spécifiques aux modèles
- ###############################################################################################################################################
- // vérif aucun ou tous types de bien demandé (maison + appartement + etc. + autre)
- $string = $_GET_INFOS['ck_property_type'];
- //echo "[common.functions : uriToFinalFromDirectLink : ck_property_type = ".$string."]\n"; //exit();
- $is_property_all = false;
- if ($_GET_INFOS['univers'] == '1') {
- switch ($string) {
- case '0000000000' : $is_property_all = true;
- break;
- case 'ffbf800001' : $is_property_all = true;
- break;
- }
- } else if ($_GET_INFOS['univers'] == '2') {
- switch ($string) {
- case '0000000000' : $is_property_all = true;
- break;
- case 'ffbf800001' : $is_property_all = true;
- break;
- }
- } else if ($_GET_INFOS['univers'] == '8') {
- switch ($string) {
- case '0000000000' : $is_property_all = true;
- break;
- case 'cb0f000000' : $is_property_all = true;
- break;
- }
- }
- // vérif type de bien unique demandé et si oui lequel (maison | appartement | etc. | autre)
- $is_property_one = false;
- if ($_GET_INFOS['univers'] == '1') {
- switch ($string) {
- case '8000000000' : $url_property = 'appartement';
- break;
- case '4000000000' : $url_property = 'maison';
- break;
- case '0006000000' : $url_property = 'propriete';
- break;
- case '0001000000' : $url_property = 'hotel-particulier';
- break;
- case '0020000000' : $url_property = 'chateau';
- break;
- case '0008000000' : $url_property = 'ferme';
- break;
- case '1080000000' : $url_property = 'bureau-commerce';
- break;
- case '0400000000' : $url_property = 'loft-atelier';
- break;
- case '0800000000' : $url_property = 'immeuble';
- break;
- case '0010000000' : $url_property = 'parking';
- break;
- case '2000000000' : $url_property = 'terrain';
- break;
- case '0000000001' : $url_property = 'viager';
- break;
- case '0100000000' : $url_property = 'chalet';
- break;
- case '0200000000' : $url_property = 'villa';
- break;
- case '0000800000' : $url_property = 'autre';
- break;
- }
- } else if ($_GET_INFOS['univers'] == '2') {
- switch ($string) {
- case '8000000000' : $url_property = 'appartement';
- break;
- case '4000000000' : $url_property = 'maison';
- break;
- case '0006000000' : $url_property = 'propriete';
- break;
- case '0001000000' : $url_property = 'hotel-particulier';
- break;
- case '0020000000' : $url_property = 'chateau';
- break;
- case '0008000000' : $url_property = 'ferme';
- break;
- case '1080000000' : $url_property = 'bureau-commerce';
- break;
- case '0400000000' : $url_property = 'loft-atelier';
- break;
- case '0800000000' : $url_property = 'immeuble';
- break;
- case '0010000000' : $url_property = 'parking';
- break;
- case '0100000000' : $url_property = 'chalet';
- break;
- case '0200000000' : $url_property = 'villa';
- break;
- case '0000800000' : $url_property = 'autre';
- break;
- }
- } else if ($_GET_INFOS['univers'] == '8') {
- switch ($string) {
- case '430f000000' : $url_property = 'maison-villa';
- break;
- case '8800000000' : $url_property = 'immeuble-appartement';
- break;
- }
- }
- if (isset($url_property)) {
- $is_property_one = true;
- }
- // vérif aucun ou tous nombres de pièces défini (1 + 2 + etc. + 6+)
- $array = explode('-', $_GET_INFOS['query']);
- $string = $array[3];
- $is_rooms_all = ($string == '00');
- // vérif nombre de pièces (vente/loc.) ou chambres (coloc.) unique demandé et si oui lequel (1 | 2 | etc. | 6+)
- $is_rooms_one = false;
- if (
- (($_GET_INFOS['univers'] == '1') && in_array($url_property, array('appartement', 'maison', 'propriete', 'hotel-particulier', 'chateau', 'loft-atelier', 'viager', 'chalet', 'villa'))) ||
- (($_GET_INFOS['univers'] == '2') && in_array($url_property, array('appartement', 'maison', 'propriete', 'hotel-particulier', 'chateau', 'loft-atelier', 'chalet', 'villa'))) ||
- (($_GET_INFOS['univers'] == '8') && in_array($url_property, array('maison-villa', 'immeuble-appartement')))
- ) {
- switch ($string) {
- case '80' : $url_rooms = '1';
- break;
- case '40' : $url_rooms = '2';
- break;
- case '20' : $url_rooms = '3';
- break;
- case '10' : $url_rooms = '4';
- break;
- case '08' : $url_rooms = '5';
- break;
- case '04' : $url_rooms = '6';
- break;
- }
- }
- if (isset($url_rooms)) {
- if (($_GET_INFOS['univers'] == '1') || ($_GET_INFOS['univers'] == '2')) {
- $url_rooms .= '-piece' . (intval($url_rooms) > 1 ? 's' : '');
- } else if ($_GET_INFOS['univers'] == '8') {
- $url_rooms .= '-chambre' . (intval($url_rooms) > 1 ? 's' : '');
- }
- $is_rooms_one = true; // un nbre de pièce (vente/loc.) ou un nbre de chambre (coloc.) en fait
- }
- // vérif du cas studio (= appartement-1-piece), modèle 3 qui se ramène à un modèle 2 d'URL (type de bien = studio, nbr de pièces = tous)
- if (
- (($_GET_INFOS['univers'] == '1') || ($_GET_INFOS['univers'] == '2')) &&
- ($url_property == 'appartement') && ($url_rooms == '1-piece')
- ) {
- $url_property = 'studio';
- $is_rooms_one = false;
- $is_rooms_all = true;
- }
- // vérif critères supplémentaires indiqués (surface min/max, prix min/max, nombre de chambres, etc.)
- // voir ficier rw.encode.php, fonction to_nat(), lignes 719+
- $array = explode('-', $_GET_INFOS['query']);
- $is_price_default = ($array[0] == '0,0');
- $is_surftot_default = ($array[1] == '0,0');
- $is_surfter_default = ($array[2] == '0,0');
- $is_bedrooms_default = ($array[4] == '00');
- $is_extended_default = ($array[5] == '000000000000');
- $is_dpe_default = ($array[6] == '00');
- $is_fresh_default = ($array[7] == '0');
- //$is_???_default = ($array[8] == '0');
- $is_order_default = ($array[9] == '3'); // price
- $is_hi_order_default = ($array[10] == '0'); // asc
- $is_an_visuel_default = ($array[11] == '0');
- $is_critera_default = ($is_price_default && $is_surftot_default && $is_surfter_default && $is_bedrooms_default && $is_extended_default && $is_dpe_default && $is_fresh_default && $is_order_default && $is_hi_order_default && $is_an_visuel_default);
- //echo "[common.functions : uriToFinalFromDirectLink : [is_property_all:".($is_property_all?'true':'false')."][is_property_one:".($is_property_one?'true':'false')."][is_rooms_all:".($is_rooms_all?'true':'false')."][is_rooms_one:".($is_rooms_one?'true':'false')."]"."\n";
- //echo "[common.functions : uriToFinalFromDirectLink : [is_price_default:".($is_price_default?'true':'false')."][is_surftot_default:".($is_surftot_default?'true':'false')."][is_surfter_default:".($is_surfter_default?'true':'false')."][is_bedrooms_default:".($is_bedrooms_default?'true':'false')."][is_extended_default:".($is_extended_default?'true':'false')."][is_critera_default:".($is_critera_default?'true':'false')."]"."\n";
- ###############################################################################################################################################
- # URL courte modèle 1 (localité) : /annonces-{univ_name}-{loc_name}-{post_name}-{loc_key}-{offset}.html
- ###############################################################################################################################################
- if ($is_property_all && $is_rooms_all && $is_critera_default) {
- $string = $_GET_INFOS['univers'];
- switch ($string) {
- case '1' : $url_unv_name = 'immobilier';
- break;
- case '2' : $url_unv_name = 'location';
- break;
- case '8' : $url_unv_name = 'colocation';
- break;
- }
- $url = '/annonces-' . $url_unv_name . '-' . $url_loc_name . '-' . $url_post_code . '-' . $url_loc_key . ($is_offet_default ? '' : '-' . $url_offset) . '.html';
- }
- ###############################################################################################################################################
- # URL courte modèle 2 (localité + type bien) : /{prop_type}-{loc_name}/{univ_name}-{prop_type}-{loc_name}-{post_name}-{loc_key}-{offset}.html
- ###############################################################################################################################################
- else if ($is_property_one && $is_rooms_all && $is_critera_default) {
- $string = $_GET_INFOS['univers'];
- switch ($string) {
- case '1' : $url_unv_name = 'vente';
- break;
- case '2' : $url_unv_name = 'location';
- break;
- case '8' : $url_unv_name = 'colocation';
- break;
- }
- $url = '/' . $url_property . '-' . $url_loc_name . '/' . $url_unv_name . '-' . $url_property . '-' . $url_loc_name . '-' . $url_post_code . '-' . $url_loc_key . ($is_offet_default ? '' : '-' . $url_offset) . '.html';
- }
- ###############################################################################################################################################
- # URL courte modèle 3 (localité + type bien + nbre pièces) : /{prop_type}-{loc_name}/{univ_name}-{prop_type}-{loc_name}/{prop_type}-{room_nbr}-{loc_name}-{post_code}-{loc_key}-{offset}.html
- ###############################################################################################################################################
- else if ($is_property_one && $is_rooms_one && $is_critera_default) {
- $string = $_GET_INFOS['univers'];
- switch ($string) {
- case '1' : $url_unv_name = 'vente';
- break;
- case '2' : $url_unv_name = 'location';
- break;
- case '8' : $url_unv_name = 'colocation';
- break;
- }
- $url = '/' . $url_property . '-' . $url_loc_name . '/' . $url_unv_name . '-' . $url_property . '-' . $url_loc_name . '/' . $url_property . '-' . $url_rooms . '-' . $url_loc_name . '-' . $url_post_code . '-' . $url_loc_key . ($is_offet_default ? '' : '-' . $url_offset) . '.html';
- }
- //echo "[common.functions : uriToFinalFromDirectLink : url = $url]\n"; //exit();
- return $url;
- }
- /**
- * @author B.Moinet
- * @since 13/12/2011
- * Retourne une chaine formatté pour être utilisée par la variable XiTi 'xtpage' (cf p.15 PDF XiTi)
- * Seuls caractères acceptés : abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123467890./-_~
- *
- * @param string str chaine à traiter
- */
- function clean_xiti($str) {
- $ret = TextNoAccent($str);
- $pattern = '/([^a-zA-Z²0-9.\/_:~-])/';
- $replace = '_';
- $ret = preg_replace($pattern, $replace, $ret);
- return $ret;
- }
- /**
- * @author B.Moinet
- * @since 13/12/2011
- * Retourne une chaine au pluriel (ajoute un 's' final, uniquement si besoin)
- *
- * @param string str chaine à traiter
- */
- function make_plurial($str) {
- $ret = $str;
- $last_char = $str[strlen($str) - 1];
- if ($last_char != 's')
- $ret .= 's';
- return $ret;
- }
- function genereAdvX($type, $str) {
- global $_ADVANCED_SEARCH_CAT;
- $advanced = $str;
- // Récupérer la liste des critères sans les catégories
- // => Plus simple à interroger
- $advanced_search = array();
- foreach ($_ADVANCED_SEARCH_CAT as $SUB_CAT) {
- $advanced_search += $SUB_CAT;
- }
- $advanced_search = $_ADVANCED_SEARCH_CAT[$type];
- $str_advanced = '';
- $length = strlen($advanced);
- $pos = -1;
- while (($pos = strpos($advanced, '1', $pos + 1)) !== false) {
- if ($advanced_search[$pos]) {
- $elt_advanced = $advanced_search[$pos];
- $elt_advanced = str_replace(' ', '', $elt_advanced);
- $elt_advanced = str_replace('/', '', $elt_advanced);
- $elt_advanced = strtolower($elt_advanced);
- $elt_advanced = TextNoAccent($elt_advanced);
- $str_advanced .= ',[' . $elt_advanced . ']';
- }
- }
- return substr($str_advanced, 1);
- }
- /**
- *
- * @param array $nav_array tableau des elements du menu
- * @return aray tableau avec les elements de la sous nav
- */
- function get_sous_nav($nav_array) {
- foreach ($nav_array as $item) {
- if (is_array($item)) {
- $sous_nav[] = $item;
- }
- }
- return $sous_nav;
- }
- /**
- *
- * @param string $count nombre initial
- * @return aray tableau des chiffres
- */
- function split_counter($count) {
- $tab_chiffre = str_split($count);
- foreach ($tab_chiffre as $k => &$chf) {
- if ($chf != ' ') {
- $class = 'chf_hp' . $chf;
- }else
- $class = 'chf_hp_break';
- $chf = "<span class='$class nobackground'>$chf</span>";
- }
- return implode('', $tab_chiffre);
- }
- function get_suggestion_links($univers_id) {
- // 'locname' est la valeur a donner pour le input text 'loc_name1' et 'lockey' celle pour le input hidden 'loc_key1'
- // pour sauvegarder ces valeurs dans le cookie 'user_srch' au moment du clic sur le lien avant d'afficher la PR
- // (fait via la fonction JS update_inputs_hp(locname, lockey) qui met a jour les champs de la HP)
- $groupLinks = array(
- 'rentLinks' => array(
- array(
- 'url' => '/appartement-paris/location-appartement-paris-75-100_1.html',
- 'text' => 'Paris',
- 'title' => 'Appartement Paris',
- 'locname' => 'PARIS (75)',
- 'lockey' => '100_1'
- ),
- array(
- 'url' => '/appartement-marseille/location-appartement-marseille-tous-codes-postaux-421_99.html',
- 'text' => 'Marseille',
- 'title' => 'Appartement Marseille',
- 'locname' => 'MARSEILLE (TOUS CODES POSTAUX)',
- 'lockey' => '421_99'
- ),
- array(
- 'url' => '/appartement-lyon/location-appartement-lyon-tous-codes-postaux-422_99.html',
- 'text' => 'Lyon',
- 'title' => 'Appartement Lyon',
- 'locname' => 'LYON (TOUS CODES POSTAUX)',
- 'lockey' => '422_99'
- ),
- array(
- 'url' => '/appartement-calvados/location-appartement-calvados-14-36_1.html',
- 'text' => 'Calvados',
- 'title' => 'Appartement Calvados',
- 'locname' => 'CALVADOS (14)',
- 'lockey' => '36_1'
- ),
- array(
- 'url' => '/appartement-paris-17e/location-appartement-paris-17e-75017-23596_2.html',
- 'text' => '75017',
- 'title' => 'Appartement 75017',
- 'locname' => 'PARIS 17E (75017)',
- 'lockey' => '23596_2'
- )
- ),
- 'salesLinks' => array(
- array(
- 'url' => '/appartement-paris/vente-appartement-paris-75-100_1.html',
- 'text' => 'Paris',
- 'title' => 'Appartement Paris',
- 'locname' => 'PARIS (75)',
- 'lockey' => '100_1'
- ),
- array(
- 'url' => '/appartement-marseille/vente-appartement-marseille-tous-codes-postaux-421_99.html',
- 'text' => 'Marseille',
- 'title' => 'Appartement Marseille',
- 'locname' => 'MARSEILLE (TOUS CODES POSTAUX)',
- 'lockey' => '421_99'
- ),
- array(
- 'url' => '/appartement-lyon/vente-appartement-lyon-tous-codes-postaux-422_99.html',
- 'text' => 'Lyon',
- 'title' => 'Appartement Lyon',
- 'locname' => 'LYON (TOUS CODES POSTAUX)',
- 'lockey' => '422_99'
- ),
- array(
- 'url' => '/appartement-calvados/vente-appartement-calvados-14-36_1.html',
- 'text' => 'Calvados',
- 'title' => 'Appartement Calvados',
- 'locname' => 'CALVADOS (14)',
- 'lockey' => '36_1'
- ),
- array(
- 'url' => '/appartement-paris-17e/vente-appartement-paris-17e-75017-23596_2.html',
- 'text' => '75017',
- 'title' => 'Appartement 75017',
- 'locname' => 'PARIS 17E (75017)',
- 'lockey' => '23596_2'
- )
- )
- );
- $html = array(
- 'rentLinks' => array(),
- 'salesLinks' => array()
- );
- foreach ($groupLinks['rentLinks'] as $link) {
- $html['rentLinks'][] = '<a onclick="update_inputs_hp(\'' . $link['locname'] . '\', \'' . $link['lockey'] . '\')" href="' . to_url($link['url']) . '" title="' . $link['title'] . '">' . $link['text'] . '</a>';
- }
- foreach ($groupLinks['salesLinks'] as $link) {
- $html['salesLinks'][] = '<a onclick="update_inputs_hp(\'' . $link['locname'] . '\', \'' . $link['lockey'] . '\')" href="' . to_url($link['url']) . '" title="' . $link['title'] . '">' . $link['text'] . '</a>';
- }
-
- return $html;
- }
- function is_in_poi_area($ad) {
- //Les POI ne doivent apparaître que sur Paris, Marseille, Lyon, Toulouse, Bordeaux, Strasbourg et Lille :
- //Annonce ciblée sur :
- // 1) un code postal correspondant à l'une de ces villes
- // 2) le département Paris
- $lgn_ids = array(
- 421, //Marseille
- 422, //Lyon
- 393, //Toulouse
- 49, //Bordeaux
- 382, //Strasbourg
- 193 //Lille
- );
- if (in_array($ad['lgn_id'], $lgn_ids) || $ad['hierarchy'][1]['lct_id'] == 100) {
- return true;
- } else
- return false;
- }
- function is_in_district_area($ad) {
- //Les Quartiers ne doivent apparaître que sur Paris, Lyon, Marseille, Lille, Toulouse, Montpellier, Nice et Strasbourg
- //Annonce ciblée sur :
- // 1) un code postal correspondant à l'une de ces villes
- // 2) le département Paris
- $lgn_ids = array(
- 421, //Marseille
- 422, //Lyon
- 393, //Toulouse
- 382, //Strasbourg
- 193, //Lille
- 244, // Nice
- 232, // Montpellier
- 49 //Bordeaux
- );
- if (in_array($ad['lgn_id'], $lgn_ids) || $ad['hierarchy'][1]['lct_id'] == 100) {
- return true;
- } else
- return false;
- }
- /**
- * Checking if the specified lctid is a DomTom
- * @param string $lctid
- * @return bool
- */
- function is_domtom($post_code) {
- if (substr($post_code, 0, 2) > '95' && $post_code != '98000') {
- return true;
- } else
- return false;
- }
- /**
- * Transforme un fichier xml en tableau PHP
- * @param type $fname
- * @return type
- */
- function xml2array($fname) {
- $sxi = new SimpleXmlIterator($fname, null, true);
- return sxiToArray($sxi);
- }
- function sxiToArray($sxi) {
- $a = array();
- for ($sxi->rewind(); $sxi->valid(); $sxi->next()) {
- if (!array_key_exists($sxi->key(), $a)) {
- $a[$sxi->key()] = array();
- }
- if ($sxi->hasChildren()) {
- $a[$sxi->key()][] = sxiToArray($sxi->current());
- } else {
- $a[$sxi->key()] = strval($sxi->current());
- }
- }
- return $a;
- }
- /**
- * Localiser l internaute en fonction de son IP en se basant sur le cache MAXMIND
- * @param bool $no_cookie : Ignorer le cookie ou pas
- * @author: W.ASBAITI
- * @since: 12/06/2012
- * @return stdobject $data avec les ville, departement et region de l'ip a localiser
- */
- function geoLocateByIp($no_cookie = false) {
- /*
- echo "no_cookie = "; var_dump($no_cookie);
- echo "user_geoloc = "; var_dump($_COOKIE['user_geoloc']);
- echo "geoip = "; var_dump($_REQUEST['geoip']);
- */
- // Si la valeur est deja stockee ds cookie, renvoie le contenue du cookie
- if (!empty($_COOKIE['user_geoloc']) && !$no_cookie && empty($_REQUEST['geoip'])) {
- //echo "Cas 1";
- return json_decode($_COOKIE['user_geoloc']);
- exit;
- } else if ($_REQUEST['geoip']) {
- $longIP = $_REQUEST['geoip'];
- //echo "Cas 2 : longIP = ".$longIP;
- } else {
- $ip = $_SERVER['REMOTE_ADDR'];
- // GEOLOC A PARTIR DU FICHER DE CACHE
- $longIP = ip2long($ip);
- //echo "Cas 3 : longIP = $longIP";
- }
- // echo $longIP."\n";
- // pour test => ip situé a GENNEVILLIER (cf bastien)
- // $ip = '81.56.88.137';
- // Repertoire contenant les localites proches de l'IP
- $cacheDir = CACHE_GEOLOC . substr($longIP, 0, 3) . '/' . substr($longIP, 3, 3);
- // liste des fichiers de cache
- $cacheFiles = glob($cacheDir . '/*.txt');
- if (sizeof($cacheFiles) > 0) {
- foreach ($cacheFiles as $cacheFile) {
- // le nom du fichier => ip2longmin-ip2longmax.txt qui sont situé dans une ville
- $interval = explode('-', str_replace('.txt', '', basename($cacheFile)));
- if ($longIP <= $interval[1] && $longIP >= $interval[0]) {
- $data = json_decode(file_get_contents($cacheFile));
- //echo "Trouve : longIP = "; var_dump($longIP);
- //echo "Trouve : cacheFile = "; var_dump($cacheFile);
- // var_dump($data); die;
- return $data;
- }
- }
- }
- //echo "PAS TROUVE dans $cacheDir";
- }
- /**
- * Prise en charge des accent sur strtoupper (pas fait dans l'autre version)
- * @param type $chaine
- * @return type
- */
- function v7_uc_strtoupper_fr($chaine) {
- $chaine = strtoupper($chaine);
- $chaine = trim($chaine);
- $chaine = strtr($chaine, äâàáåãéèëêòóôõöøìíîïùúûüýñçþÿæðø, ÄÂÀÁÅÃÉÈËÊÒÓÔÕÖØÌÍÎÏÙÚÛÜÝÑÇÞÝÆÐØ);
- return $chaine;
- }
- function getPolygoneByDistrictId($id = null) {
- $sql = "SELECT polygone_quartier FROM T_DISTRICT_DIS";
- $sql .= " WHERE id_quartier ='" . $id . "' ";
- //if (function_exists("pdoquery")){ echo "FUNCTIoN EXIST"; }
- $result_query = pdoquery($sql);
- return ($result_query[0]['polygone_quartier']);
- }
- /**
- * Redirection des mini sites villes sans ciontenu vers la page de l edition liee a cette ville (M INFORMEr)
- * @param String $ville : Le nom de la ville
- * @return void Ne retourne rien, mais redirige vers la bonne page
- */
- function msVilleToHpInformer($ville) {
- // Tableau dans session.settings.php
- global $cp_editions;
- global $dpt_edition;
- // Include des fichiers necessaires a la recup de l edition
- $real_file = dirname(__FILE__);
- require_once $real_file . '/../DISPLAY/ajax/json.php';
- require_once("$real_file/../DISPLAY/informer/infos.functions.php");
- require_once("$real_file/informer_static.class.php");
- require_once("$real_file/informer_article.class.php");
- require_once("$real_file/informer_chapitre.class.php");
- require_once("$real_file/informer_insert.class.php");
- require_once("$real_file/informer_dossier.class.php");
- require_once("$real_file/informer_edition.class.php");
- // Recuperer le CP de la ville courante
- $ville_data = get_loc_names($ville);
- if (sizeof($ville_data) > 0) {
- $CP = $ville_data[0]['lct_post_code'];
- $dptCP = substr($CP, 0, 2);
- // Recuperation de l id de l edition a partir du CP de l annonce
- foreach ($cp_editions as $k => $edition) {
- $key = array_search($CP, $edition);
- if ($key !== false) {
- $id_edition = $k;
- break;
- }
- }
- if (empty($id_edition)) {
- // Recuperation de l id de l edition a partir du CP d'une annonce
- foreach ($dpt_edition as $k => $edition) {
- $key = array_search($dptCP, $edition);
- if ($key !== false) {
- $id_edition = $k;
- break;
- }
- }
- }
- if (empty($id_edition)) {// REDIRECTION vers la HP INFORMER (localisee en fnction de la recherche)
- informer_static::localiser_hp();
- exit();
- } else {
- $url = informer_static::get_hp_url('edition', $k, $edition_number[$k]);
- header("location: $url");
- exit();
- }
- } else { // REDIRECTION vers la HP INFORMER (localisee en fnction de la recherche)
- informer_static::localiser_hp();
- }
- }
- function storecookie($inKey, $inValue, $inExpire) {
- $decode = serialize($inValue);
- $decode = gzcompress($decode);
- $decode = base64_encode($decode);
- $split = str_split($decode, 4000); //4k pieces
- $count = count($split);
- for ($index = 0; $index < $count; $index += 1) {
- $result = setcookie(( $index > 0 ) ? $inKey . COOKIE_PORTIONS . $index : $inKey, $split[$index], $inExpire, '/', '', 0);
- }
- clearpieces($inKey, $count);
- }
- function fetchcookie($inKey) {
- $decode = $_COOKIE[$inKey];
- for ($index = 1; array_key_exists($inKey . COOKIE_PORTIONS . $index, $_COOKIE); $index += 1) {
- $decode .= $_COOKIE[$inKey . COOKIE_PORTIONS . $index];
- }
- if (!empty($decode)) {
- $decode = base64_decode($decode);
- $decode = gzuncompress($decode);
- }
- return unserialize($decode);
- }
- function clearpieces($inKey, $inFirst) {
- $expire = time() - 3600;
- for ($index = $inFirst; array_key_exists($inKey . COOKIE_PORTIONS . $index, $_COOKIE); $index += 1) {
- setcookie($inKey . COOKIE_PORTIONS . $index, '', $expire, '/', '', 0);
- unset($_COOKIE[$inKey . COOKIE_PORTIONS . $index]);
- }
- }
- /**
- * Function getAdvancedParams : format advanced params from BDD
- * @author Melissa Hoarau
- * @params $aAdvancedParams : array of advanced params for an ad
- * @Return $aFinalAdvancedParams : array of formated and classed advanced params
- *
- */
- function getAdvancedParams($aAdvancedParams) {
- global $_ADVANCED_SEARCH_CRIT;
- global $_ADVANCED_SEARCH_CAT;
- $dependances = array();
- $chauffage = array();
- $amenagementInterieur = array();
- $confortSecurite = array();
- $aFinalAdvancedParams = array();
- foreach ($aAdvancedParams as $sAdvancedparam) {
- foreach ($_ADVANCED_SEARCH_CRIT as $critId => $critVarName) {
- if ($sAdvancedparam == $critVarName) {
- // si ce critère fait partie de dépendances
- if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['dépendances']))) {
- $critName = $_ADVANCED_SEARCH_CAT['dépendances'][$critId];
- $dependances[] = "[$critName]";
- // si ce critère fait partie de chauffage
- } else if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['chauffage']))) {
- $critName = $_ADVANCED_SEARCH_CAT['chauffage'][$critId];
- $chauffage[] = "[$critName]";
- // si ce critère fait partie de aménagement
- } else if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['aménagement intérieur']))) {
- $critName = $_ADVANCED_SEARCH_CAT['aménagement intérieur'][$critId];
- $amenagementInterieur[] = "[$critName]";
- // si ce critère fait partie de confort
- } else if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['confort et sécurité']))) {
- $critName = $_ADVANCED_SEARCH_CAT['confort et sécurité'][$critId];
- $confortSecurite[] = "[$critName]";
- }
- }
- }
- }
- $aFinalAdvancedParams = array('dependances' => $dependances, 'chauffage' => $chauffage, 'amenagementInterieur' => $amenagementInterieur, 'confortSecurite' => $confortSecurite);
- return $aFinalAdvancedParams;
- }
- function recursive_loc($idtown, $level, $nblevel = 3, &$tab_hierarchy_loc = array()) {
-
- $sql = "SELECT lct_name, lct_id, lct_parent_id, lct_level, lct_name, lct_post_code, lgn_id, lgc_id ";
- $sql .= "FROM db1.T_LOCALITY_LCT_FR ";
- //$sql .= "WHERE lct_id = $idtown ";
- //$sql .= "AND lct_id = $idtown ";
- if ($level == 98) {
- $level = 2;
- $sql .= "WHERE lgc_id = $idtown ";
- } elseif ($level == 99) {
- $level = 2;
- $sql .= "WHERE lgn_id = $idtown ";
- } else {
- $sql .= "WHERE lct_id = $idtown ";
- }
- $sql .= "LIMIT 1 ";
- $res_loc = pdoquery($sql);
- //echo "\n".$sql."\n";
- $idtown = $res_loc[0]['lct_parent_id'];
- //var_dump($res_loc);
- $tlevel = $res_loc[0]['lct_level'];
- if (count($res_loc) == 0) {
- //echo "\n SORTIE DE BOUCLE :: $nblevel \n";
- return false;
- }
- $tab_hierarchy_loc[$tlevel] = $res_loc[0];
- //echo "\n Y :: $nblevel\n";
- //echo "\n$idtown\n";
- if ($nblevel > 0) {
- return (recursive_loc($idtown, $level, $nblevel - 1, $tab_hierarchy_loc));
- }
- return $idtown;
- }
- function xiti_string($str) {
- $str = str_replace(array("'", "'"), '', $str);
- $str = preg_replace('~(#[0-9]*;)~', '', $str);
- $str = str_replace('&', '', $str);
- return $str;
- }
- /**
- * retourne un tableau avec les infos de l agence correspondant a l id presto donne
- * @param string $id_presto
- * @return array
- */
- function findAgcByIdPresto($id_presto){
- $sQuery = "SELECT
- id_agence AS id, agc_name AS name, agc_company_name, agc_post_code AS lzip, agc_town_agency AS town,
- agc_country AS country, agc_default_town_2, agc_default_town_1, agc_default_town_0, lgc_id, lgn_id, agc_loc_id_0,
- agc_loc_id_1, agc_loc_id_2, agc_site, agc_is_powersite, agc_powersite_url, agc_powersite_calltracking, agc_is_logo,
- agc_is_directory, agc_is_website
-
- FROM T_AGENCY_AGC
- WHERE md5(id_presto) = '$id_presto'
- LIMIT 1"
- ;
-
- $result = pdoquery($sQuery, null, null, null, false, true);
-
- $return = $result[0];
-
- return $return;
- }
- /**
- * Function getLibellePersonnalisable : retourne le libelle du bandeau selon l'id
- * @param int $iIdPersonnalisable
- * @return string $sLibelleBandeau
- */
- function getLibellePersonnalisable($iIdPersonnalisable){
- $sQuery = 'SELECT T_BANDEAUX_LIBELLE FROM T_BANDEAUX_PERSO WHERE T_BANDEAUX_ID = ' . $iIdPersonnalisable;
-
- $result = pdoquery($sQuery, null, null, null, false, true);
-
- $sLibelleBandeau = $result[0]['T_BANDEAUX_LIBELLE'];
-
- return $sLibelleBandeau;
- }
- /**
- * Function getCodeDescXitiPubAffich : retourne le code de description du hit d'affichage
- * @global array of string $_ARR_CODE_PUBLISHER_AFFICH : contient les codes par page et type d'annonce
- * @param string $page
- * @param string $tpl_code
- * @param string $lib_bandeau
- * @return string $sCodeDesc
- */
- function getCodeDescXitiPubAffich($page, $tpl_code, $lib_bandeau = '') {
-
- global $_ARR_CODE_PUBLISHER_AFFICH;
- global $_global;
-
- $sCodeDesc = '';
-
- // Exclusivité
- if ($tpl_code == 'o') {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['ORPI'];
- // if ($page == 'PR') {
- // echo '<br/>ORPI' . $sCodeDesc . '<br/>';
- // }
- }
- // Neuf
- else if ($tpl_code == '9') {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['NEUF'];
- // if ($page == 'PR') {
- // echo '<br/>NEUF' . $sCodeDesc . '<br/>';
- // }
- }
- // Perso
- else if (($_global['dev'] || $_global['pre_prod']) && !empty($lib_bandeau)) {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['PERSO'];
- // if ($page == 'PR') {
- // echo '<br/>PERSO' . $sCodeDesc . '<br/>';
- // }
- }
- // Ala une
- else if ($tpl_code == 'p') {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['ALAUNE'];
- // if ($page == 'PR') {
- // echo '<br/>ALAUNE' . $sCodeDesc . '<br/>';
- // }
- }
- // Standard
- else {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['STD'];
- // if ($page == 'PR') {
- // echo '<br/>STD' . $sCodeDesc . '<br/>';
- // }
- }
-
- return $sCodeDesc;
- }
- /*
- * Récupération du code postal et du loc_key
- * - de la dernière recherche de l'internaute (stockée dans cookie), si existante
- * - sinon de la localité de l'internaute (basée du son IP), si existante
- * - sinon de la localité de Paris
- */
- function getParamSearchOrGeolocByIP() {
-
- $param_search = array();
-
-
- /* Accès au cookie de recherche */
-
- $val_cookie = "";
- if ( isset($_COOKIE[SEARCH_HISTORY_COOKIE_NAME]) ) {
- // revisite de l'utilisateur
- $val_cookie = $_COOKIE[SEARCH_HISTORY_COOKIE_NAME];
- }
-
-
- // revisite (après recherche)
-
- if (trim($val_cookie) <> "") {
-
- $firstvisit = false;
-
- /* Décomposition du cookies */
- $param_search = fetchcookie(SEARCH_HISTORY_COOKIE_NAME);
-
- // the real last search is always at the row number 0
- $param_search = unserialize($param_search[0]);
- //echo "param_search : "; var_dump($param_search);
-
- if (!isset($param_search['szip'])) {
- $param_search['szip'] = '75';
- $param_search['loc_key1'] = '100_1';
- } else if ($param_search['szip'] > 95) { // DOM TOM
- $param_search['szip'] = substr($param_search['lzip'], 0, 3);
- }
- //echo "param_search : "; var_dump($param_search);
-
- /* Cookie a moitié vide (arrive notamment quand on fait une 1ère visite puisqu'on clique sur le bon plan et qu'on retourne en HP) */
-
- if (!isset($param_search['loc_key1']) || empty($param_search['loc_key1']) || ($param_search['loc_key1']=='_')) {
-
- $firstvisit = true;
-
- $user_loc_data = get_object_vars(geoLocateByIp());
-
- if (is_array($user_loc_data) && !empty($user_loc_data['postalCode'])) {
- $param_search['szip'] = substr($user_loc_data['postalCode'], 0,2);
- for($i=2; $i>=0; $i--){
- // var_dump($user_loc_data["loc_id_$i"]);
- if($user_loc_data["loc_id_$i"]) {
- $param_search['loc_key1'] = $user_loc_data["loc_id_$i"]."_$i";
- break;
- }
- }
- } else {
- // on part sur Paris, à défaut d'avoir un service de géoloc
- $param_search['szip'] = '75';
- $param_search['loc_key1'] = '100_1';
- }
-
- }
-
- } else {
-
- // première recherche
-
- $firstvisit = true;
-
- $user_loc_data = get_object_vars(geoLocateByIp());
-
- if (is_array($user_loc_data) && !empty($user_loc_data['postalCode'])) {
- $param_search['szip'] = substr($user_loc_data['postalCode'], 0,2);
- for($i=2; $i>=0; $i--){
- // var_dump($user_loc_data["loc_id_$i"]);
- if($user_loc_data["loc_id_$i"]) {
- $param_search['loc_key1'] = $user_loc_data["loc_id_$i"]."_$i";
- break;
- }
- }
- } else {
- // on part sur Paris, à défaut d'avoir un service de géoloc
- $param_search['szip'] = '75';
- $param_search['loc_key1'] = '100_1';
- }
-
- }
-
- //echo "param_search : "; var_dump($param_search);
- return $param_search;
-
- }
- /**
- * Function getCodeDescXitiPubAction : retourne le code de description du hit d'action
- * @global array of string $_ARR_CODE_PUBLISHER_ACTION : contient les codes par page et type d'annonce
- * @param string $action
- * @param string $tpl_code
- * @param string $page
- * @param string $lib_bandeau
- * @return string $sCodeDesc
- */
- function getCodeDescXitiPubAction($action, $page, $tpl_code, $lib_bandeau = '') {
-
- global $_ARR_CODE_PUBLISHER_ACTION;
- global $_global;
-
- $sCodeDesc = '';
-
- // Exclusivité
- if ($tpl_code == 'o') {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['ORPI'];
- }
- // Neuf
- else if ($tpl_code == '9') {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['NEUF'];
- }
- // Perso
- else if (($_global['dev'] || $_global['pre_prod']) && !empty($lib_bandeau)) {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['PERSO'];
- }
- // Ala une
- else if ($tpl_code == 'p') {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['ALAUNE'];
- }
- // Standard
- else {
- $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['STD'];
- }
-
- return $sCodeDesc;
- }
- function get_search_summary_from_cookie() {
- $LISearchCookie = fetchcookie('LISearchHistoryCookieCompressed');
- if($LISearchCookie != null) {
- $aSearchParameters = unserialize($LISearchCookie[0]);
- $summary = get_all_summary($aSearchParameters);
- return $summary;
- } else {
- return null;
- }
- }
- function is_appartager($sIdPresto) {
- $aAppartagerIdPrestos = array('1103802', 'CMM-PT-APPARTAGER');
- if(in_array($sIdPresto, $aAppartagerIdPrestos))
- return true;
- else
- return false;
- }
- /*
- * Retourne le nom d'une transaction sous sa forme "normale" (avec
- * des espaces entre les mots) à partir d'un nom de transaction sous
- * sa forme CamelCase (ex: VenteNeuf => Vente Neuf)
- */
- function get_transaction_name_from_camel_case($trans_name) {
-
- //echo "[trans_name = $trans_name]";
-
- $trans_name_new = preg_replace('/(?!^)[[:upper:]]/',' \0', $trans_name);
-
- return $trans_name_new;
-
- }
- /*
- * Retourne 'horizontal' ou 'vertical' selon si la photo est
- * d'orientation portrait ou paysage. Si image carrée, retourne 'horizontal'.
- * Si problème de chargement de l'image, retourne false.
- */
- function get_image_orientation_from_image_path($image_path) {
-
- //echo "[image_path = $image_path]";
-
- // image introuvable sur disque
- if (!file_exists($filename)) return false;
-
- // NB: cette fonction ne nécessite pas la bibliothèque GD
- // voir http://www.php.net/manual/fr/function.getimagesize.php
- $arr_infos = getimagesize($image_path);
-
- // erreur lors de la lecture de l'image
- if (empty($arr_infos)) return false;
-
- list($width, $height, $type, $attr) = $arr_infos;
- //echo "[arr_infos = ".var_dump($arr_infos."]";
-
- // image vide
- if (((int)$width == 0) && ((int)$height == 0)) return false;
-
- if ((int)$width == (int)$height) return 'horizontal'; // photo carrée
- else if ((int)$width < (int)$height) return 'horizontal'; // photo paysage
- else return 'vertical'; // photo portrait
-
- }
- function get_dept_by_postcode($postcode) {
- $query = "SELECT lct_parent_id, lct_id, lct_name, lct_name_fr, lct_post_code, lct_prg_pondering, lct_level
- FROM T_LOCALITY_LCT_FR
- WHERE lct_level = 1
- AND lct_post_code = '$postcode'
- ";
- $result = pdoquery($query);
- return $result;
- }
- ?>