PageRenderTime 99ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/DEV/LIB/common.functions.php

https://github.com/chrisbst35/LI_LEMONDE
PHP | 7552 lines | 4863 code | 1106 blank | 1583 comment | 1286 complexity | 3fb67c2dde3df8b70cd34cfe9e5886d9 MD5 | raw file
  1. <?php
  2. $test = include('/data/apache/CONF_URL/conf.php');
  3. if (!$test)
  4. require('/data/apache/CONF_URL/prod.conf.php');
  5. //bandeaux personnalisables
  6. //include(realpath(dirname(__FILE__) . "/../DATA/bandeaux/libelles_bandeaux.php"));
  7. global $_global;
  8. //##############################################################################
  9. //# Définition des constantes fonctionnelles
  10. // Répertoire dans lequel les fichiers generes par les scripts des crons sont enregistres
  11. define('URL_DATA', '/data/apache/DATA/');
  12. // Appel depuis un script => Pas de DOCUMENT_ROOT !!!
  13. //$display = rtrim($_SERVER['DOCUMENT_ROOT'],'/');
  14. $display = realpath(dirname(__FILE__) . '/../DISPLAY');
  15. $root = dirname($display);
  16. // Gérer les document root de Orange (et autres), qui ont DISPLAY
  17. // directement à la racine !!
  18. if (substr($root, -4) == '/DEV')
  19. $root = dirname($root);
  20. define('ROOT_PATH', $root); // ex: /data/apache/www/www.logic-immo.com
  21. define('DISPLAY_PATH', $display); // ex: /data/apache/www/www.logic-immo.com/DEV/DISPLAY
  22. // Répertoire dans lequel les librairies (fonctions, classes) sont enregistrees
  23. $current_lib_dir = dirname(__FILE__);
  24. // PB : Si la constante a déjà été définie dans une autre page !!
  25. if (defined('URL_LIB')) {
  26. // Simuler une erreur fatale pour qu'on recoive un mail en cas de problème
  27. error_log("FATAL ERROR - La constante URL_LIB a deja ete definie ! (VALEUR:" . URL_LIB . ")");
  28. // Enregistrer le backtrace dans le fichier de log
  29. ob_start() or exit();
  30. debug_print_backtrace();
  31. $content = ob_get_contents();
  32. error_log($content);
  33. ob_end_clean();
  34. } else {
  35. define('URL_LIB', $current_lib_dir); // ex: /data/apache/www/www.logic-immo.com/DEV/LIB
  36. }
  37. //##############################################################################
  38. //# Chargement de la configuration par environnement
  39. // Récupérer le chemin du fichier de conf
  40. $conf_file = ROOT_PATH . '/CONF/conf.php';
  41. $test = include($conf_file);
  42. // Gestion en cas de configuration introuvable
  43. if (!$test) {
  44. // Utiliser la configuration de production
  45. $test = include(ROOT_PATH . '/CONF/prodA.conf.php');
  46. if (!$test) {
  47. // Simuler une erreur fatale pour qu'on recoive un mail en cas de problème
  48. error_log("FATAL ERROR - Le fichier de configuration `{$conf_file}` n\'a pas ete trouve. (DOCUMENT_ROOT:{$_SERVER['DOCUMENT_ROOT']})");
  49. // Enregistrer le backtrace dans le fichier de log
  50. ob_start() or exit();
  51. debug_print_backtrace();
  52. $content = ob_get_contents();
  53. error_log($content);
  54. ob_end_clean();
  55. // Ne pas plus faire de traitement avec des constantes manquantes !
  56. exit();
  57. }
  58. }
  59. //##############################################################################
  60. //# Inclure les librairies relatives à MMF
  61. include_once(URL_LIB . '/mmf.constants.php');
  62. include_once(URL_LIB . '/mmf.functions.php');
  63. //##############################################################################
  64. //##
  65. //## direct_hit($ip) -- returns true if url hits a frontal server
  66. //## add_parameters($url, $site = "", $lang = "", $univers = "") -- returns an url along with the environment parameters
  67. //## add_parameter($url, $parameter, $value) -- returns an url along with a parameter and value
  68. //## del_parameter($url, $parameter) -- returns an url without a parameter
  69. //## get_all_summary_cz($data) -- returns an array of human readable values, translated from search criteria (CZ)
  70. //## get_all_summary($data,$showIfAllChecked) -- returns an array of human readable values, translated from search criteria
  71. //## get_adv_summary($data,$extended,$showIfAllChecked) -- return an array of human readable values from advanced criterias
  72. //## get_summary($data, $parameters, $item, $label_all, $label_unit) -- turns a search criterion to a human readable value
  73. //## get_property_type_label($id) -- returns property type label depending on the code
  74. //## n_f($value) -- number_format shortcut
  75. //## currency_format($value, $from, $to, $add_currency_name = true) -- currency conversion
  76. //## sosex($input, $partial = false) -- Function so sex, par le so sexy oxman, da crazy man !
  77. //## str_limit($value, $limit) -- returns a truncated string
  78. //## remove_returns($value) -- returns a clean string
  79. //## 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
  80. //## spacer($height, $width) -- returns html code for a spacer
  81. //## set_html_title($value) -- returns html alt and title
  82. //##
  83. //## get_ad_data($page, $value, $has_premium = 0, $url = "", $idx = -1) -- returns ad and agency data
  84. //## get_ag_data($page, $value) -- returns agency data
  85. //## get_pub_data($value, $key) -- returns pub data
  86. //## get_mmf_type($label) -- returns mmf type index
  87. //##
  88. //## format_phone($value, $country = "FR") -- returns formatted number
  89. //## get_parameter_index($name, $value) -- returns parameter index
  90. //## is_guid($value) -- returns true if value is a guid
  91. //## back_to_list($page) -- returns "back to list" url
  92. //## build_search_url($page, $parameters) -- returns a search url
  93. //## from_page($previous_url, $page) -- returns true if page comes from Mars
  94. //## is_external() -- returns true if is external
  95. //## is_ref_page($page) -- returns true if is a ref page
  96. //## get_zip_code($data, $mode) -- returns szip / lzip
  97. //## writeLockFile($sLockFileName, $sLockFileDescription) --
  98. //## getLockFile($sLockFileName) --
  99. //## checkLockFile($sLockFileName) -- xx
  100. //## removeLockFile($sLockFileName) --
  101. //## truncate($chaine, $length = 50) -- Tronque un texte (mais pas les mots !) si trop long et rajoute des points de suspension
  102. //## loc2xiti($k1,$n1,$k2,$n2) --
  103. //## format_footer_link($str) --
  104. //## generateMd5MaintenanceString($iOperationCode, $sPreSharedKey) --
  105. //## checkSha1MaintenanceString($sPreSharedKey, $iOperationCode, $aOperationArray, $sKeyString) --
  106. //## redirection($url) -- Gere la presence des headers
  107. //## verif_cookie_prehome -- Gestion de la revisite Belge (modifiable pour les autres Pays)
  108. //## pub_relais_neuf_cookie($val_relais) -- Verification les nombres de refresh
  109. //## Verif_Url_BE() -- verifier la syntax de l'URL pour le site BE
  110. //## 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
  111. //## Get_Trad_Locname ($lockey, $lang) -- Retrouve la traduction d'un nom de Locname en fonction d'un LCT_ID et d'une Langue
  112. //## TextNoAccent($string) -- Supprime les accents d'une chaine
  113. //## => Déprécié : Regarder la fonction prepareToUrl($string)
  114. //##
  115. //## check_detail_exist -- Vérifie si il existe des détail spécifique sur une annonce
  116. //## create_block_nosearch($title)
  117. //## no_magic_quote() -- pour eviter les injection S-K-UL
  118. //## uc_strtoupper_fr($chaine) -- Amélioration du strtoupper de PHP pour gérer les accents
  119. //##
  120. //## getLocalityLabel($search_parameters,$num) -- Renvoyer la localite selon le level ("tous codes" ...)
  121. //## stringToHexa($string,$size) -- Convertir la chaine de 0 et 1 en hexa
  122. //## hexaToString($string,$size) -- Convertir la chaine hexa en 0 et 1
  123. //##
  124. //## searchPropertyTypeIdOrig($id_orig,$get_group) -- Récupérer le groupe ou la chaine de 40bits (par défaut)
  125. //## searchPropertyTypeIdOrigAdv($id_orig,$get_group) -- Récupérer le groupe ou la chaine de 40bits (par défaut)
  126. //## => Utilise les nouveaux groupes (plus nombreux et quasi unitaires)
  127. //##
  128. //##############################################################################
  129. //
  130. //
  131. // 20080820-XI $ad["default_sector"] should not be displayed if $ad["default_town"]==$ad["default_sector"]
  132. // 20090401-1-XI, Retrieving xxx_locality_2_agency field (mantis 5342)
  133. // 20090407-1-XI, Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO'
  134. // 20090410-1-XI, Retrieving xxx_tel2_agency
  135. // 20090610-1-XI, NOT Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO', mantis 5865
  136. //
  137. //##############################################################################
  138. function open_file(&$filepath, $requestType = '', $mode = 'a', $backupFolder = TRAPPED_WRITE_ERROR) {
  139. // Enregistrer la statistique dans le csv
  140. $fp = @fopen($filepath, 'a');
  141. if ($fp === false) {
  142. error_log('FATAL ERROR - Could not open file `' . $filepath . '` to save "' . $requestType . '" request !');
  143. // Utiliser le dossier de secours pour ne pas perdre les demandes
  144. $filepath = $backupFolder . $requestType . '/' . basename($filepath);
  145. // Enregistrer la statistique dans le csv
  146. $fp = @fopen($filepath, 'a');
  147. if ($fp === false) {
  148. error_log('FATAL ERROR - Could not open file `' . $filepath . '` to save "' . $requestType . '" request !');
  149. }
  150. }
  151. return $fp;
  152. }
  153. /**
  154. * Returns true if url hits a frontal server
  155. *
  156. * @param unknown_type $ip
  157. * @return unknown
  158. */
  159. function direct_hit($ip) {
  160. global $_prodServers;
  161. return in_array($ip, $_prodServers);
  162. }
  163. /**
  164. * Returns an url along with the environment parameters
  165. *
  166. * @param unknown_type $url
  167. * @param unknown_type $site
  168. * @param unknown_type $lang
  169. * @param unknown_type $univers
  170. * @return unknown
  171. */
  172. function add_parameters($url, $site = "", $lang = "", $univers = "") {
  173. global $_global;
  174. // default values
  175. $site = ($site == "" ? $_global["site"] : $site);
  176. $lang = ($lang == "" ? $_global["lang"] : $lang);
  177. $univers = ($univers == "" ? $_global["univers"] : $univers);
  178. // sets url parameters into an array
  179. $tmp = explode("?", $url);
  180. parse_str($tmp[1], $url_parameters);
  181. // adds site parameter
  182. if (!array_key_exists("site", $url_parameters)) {
  183. $add_parameters["site"] = $site;
  184. } else {
  185. $url_parameters["site"] = $site;
  186. }
  187. // adds universe parameter
  188. if (!array_key_exists("univers", $url_parameters)) {
  189. $add_parameters["univers"] = $univers;
  190. } else {
  191. $url_parameters["univers"] = $univers;
  192. }
  193. // adds language parameter
  194. if (!array_key_exists("lang", $url_parameters)) {
  195. $add_parameters["lang"] = $lang;
  196. } else {
  197. $url_parameters["lang"] = $lang;
  198. }
  199. // merges parameters
  200. if (is_array($add_parameters)) {
  201. $url_parameters = array_merge($add_parameters, $url_parameters);
  202. }
  203. // concatenates
  204. $url = $tmp[0] . "?" . http_build_query($url_parameters);
  205. switch ($_global["site"]) {
  206. case "be":
  207. if (strpos($url, "http:") === false) {
  208. $url = "/" . $lang . "/" . $url;
  209. $url = str_replace("//", "/", $url);
  210. }
  211. break;
  212. default:
  213. break;
  214. }
  215. // returns
  216. return $url;
  217. }
  218. /**
  219. * Returns an url along with a parameter and value
  220. *
  221. * @param unknown_type $url
  222. * @param unknown_type $parameter
  223. * @param unknown_type $value
  224. * @return unknown
  225. */
  226. function add_parameter($url, $parameter, $value) {
  227. // sets url parameters into an array
  228. $tmp = explode("?", $url);
  229. parse_str($tmp[1], $url_parameters);
  230. if (!array_key_exists($parameter, $url_parameters)) {
  231. $url_parameters[$parameter] = $value;
  232. // concatenates
  233. $url = $tmp[0] . "?" . http_build_query($url_parameters);
  234. }
  235. // returns
  236. return $url;
  237. }
  238. /**
  239. * Returns an url without a parameter
  240. *
  241. * @param unknown_type $url
  242. * @param unknown_type $parameter
  243. * @return unknown
  244. */
  245. function del_parameter($url, $parameter) {
  246. // sets url parameters into an array
  247. $tmp = explode("?", $url);
  248. parse_str($tmp[1], $url_parameters);
  249. if (array_key_exists($parameter, $url_parameters)) {
  250. unset($url_parameters[$parameter]);
  251. // concatenates
  252. $url = $tmp[0] . "?" . http_build_query($url_parameters);
  253. }
  254. // returns
  255. return $url;
  256. }
  257. /**
  258. * Returns an array of human readable values, translated from search criteria
  259. *
  260. * @param Array $data
  261. * @param Boolean $showIfAllChecked List all values (1,2,...) if all checked ?
  262. * @param Boolean $useAdvancedGroups Utiliser les groupes de types de bien avancés (plus nombreux)
  263. * @return unknown
  264. */
  265. function get_all_summary($data, $showIfAllChecked = true, $useAdvancedGroups = false) {
  266. global $_global;
  267. // summary table
  268. $summary = array();
  269. // vacances
  270. if ($_global["univers"] == 13) {
  271. // globals
  272. global $_LI_BEDROOMS;
  273. global $_LI_PEOPLE;
  274. // load values
  275. $parameters = array();
  276. $parameters["nb_bedrooms"] = $_LI_BEDROOMS;
  277. $parameters["nb_people"] = $_LI_PEOPLE;
  278. // univers
  279. $summary["univers"] = LABEL_COMMON_UNIVERSE_13;
  280. // localisation
  281. $summary["loc_name"] = $data["loc_name"];
  282. // property types
  283. if ($data["property_type"] == "" || $data["property_type"][0] == -1 || count($data["property_type"]) == 8) {
  284. $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
  285. } else {
  286. for ($i = 0; $i < count($data["property_type"]); $i++) {
  287. $data["property_type"][$i] = constant("LABEL_COMMON_PROPERTY_" . $data["property_type"][$i]);
  288. }
  289. $summary["property_type"] = implode(", ", $data["property_type"]);
  290. }
  291. // bedrooms
  292. $summary["nb_bedrooms"] = get_summary($data, $parameters["nb_bedrooms"], "nb_bedrooms", LABEL_ALL_BEDROOMS, LABEL_COMMON_BEDROOMS_UNIT);
  293. // people
  294. $summary["nb_people"] = get_summary($data, $parameters["nb_people"], "nb_people", LABEL_ALL_PEOPLE, LABEL_COMMON_PEOPLE_UNIT);
  295. } else {
  296. // globals
  297. global $_LI_PRICERANGE;
  298. global $_LI_ADSURFACE;
  299. global $_LI_ROOMS;
  300. // load values
  301. $parameters = array();
  302. $parameters["area"] = $_LI_ADSURFACE;
  303. $parameters["price"] = $_LI_PRICERANGE;
  304. $parameters["nb_rooms"] = $_LI_ROOMS;
  305. // univers
  306. if ($data["univers"] == 2) { // location
  307. $summary["univers"] = LABEL_COMMON_UNIVERSE_2;
  308. } else if ($data["univers"] == 8) { // colocation
  309. $summary["univers"] = LABEL_COMMON_UNIVERSE_8;
  310. } else { // vente
  311. $summary["univers"] = LABEL_COMMON_UNIVERSE_1;
  312. }
  313. $loc_names = array();
  314. if (isset($data['is_from_cookie'])) {
  315. for ($i = 1; $i < 4; $i++) {
  316. if (isset($data['loc_name' . $i]) && ($locname = $data['loc_name' . $i]) != '' && $locname != LABEL_DEFAULT_LOCALITY) {
  317. $loc_names[] = ucwords2(strtolower($data['loc_name1']));
  318. }
  319. $locname = implode(', ', $loc_names);
  320. }
  321. } else {
  322. // localisation
  323. $loc_name = getLocalityLabel($data, 0);
  324. if ($loc_name != LABEL_DEFAULT_LOCALITY)
  325. $loc_names[] = ucwords2(strtolower($loc_name));
  326. $loc_name = getLocalityLabel($data, 1);
  327. if ($loc_name != LABEL_DEFAULT_LOCALITY)
  328. $loc_names[] = ucwords2(strtolower($loc_name));
  329. $loc_name = getLocalityLabel($data, 2);
  330. if ($loc_name != LABEL_DEFAULT_LOCALITY)
  331. $loc_names[] = ucwords2(strtolower($loc_name));
  332. if ($loc_names == array()) {
  333. $locname = ucwords2(strtolower($data["loc_name"]));
  334. // Ajouter manuellement les parentheses autour des codes postaux
  335. // En veillant à ne pas les doubler si déjà présentes
  336. $locname = preg_replace('`\(?([0-9]{3,})\)?`', '($1)', $locname);
  337. }
  338. else
  339. $locname = implode(', ', $loc_names);
  340. // Remplacer les -+_ par un espace
  341. $locname = strtr($locname, array('-' => ' ', '+' => ' ', '_' => ' '));
  342. // Mettre la chaine tous codes postaux entre parentheses
  343. $locname = str_ireplace('TOUS CODES POSTAUX', '(Tous codes postaux)', $locname);
  344. // Séparer les parentheses avec une virgule
  345. $locname = str_replace(') ', '), ', $locname);
  346. // Ajouter les apostrophes devant les L et le D
  347. $locname = preg_replace('`\b(L|D) `i', '$1\'', $locname);
  348. }
  349. // Ajout la valeur de localité
  350. if ($locname != '')
  351. $summary["loc_name"] = $locname;
  352. // property types
  353. if (isset($data["ck_property_type"])) {
  354. $property_type = $data['ck_property_type'];
  355. // Si champ vide, ou aucun coché
  356. if (empty($property_type) || strpos($property_type, '1') === false) {
  357. $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
  358. // Sinon on liste tous les types de biens
  359. } elseif (SUMMARY_LIST_PROPERTY_TYPES) {
  360. $size = strlen($property_type);
  361. $str_property_type = '';
  362. /*
  363. for($i=0; $i<$size; $i++) {
  364. if( $property_type[$i]=='1' ) $str_property_type .= ', '.constant("LABEL_COMMON_PROPERTY_ID_".($i+1));
  365. }
  366. */
  367. $pos = -1;
  368. while (($pos = strpos($string, '1', $pos + 1)) !== false) {
  369. $str_property_type .= ', ' . constant("LABEL_COMMON_PROPERTY_ID_" . ($pos + 1));
  370. }
  371. $summary["property_type"] = substr($str_property_type, 2);
  372. // Sinon on liste les groupes de biens
  373. } else {
  374. if ($useAdvancedGroups) {
  375. global $_ADVANCED_SEARCH_TYPES, $_MASK_REALESTATETYPES_ALL_CHECKED;
  376. $checkedLabels = getCheckedFields($_ADVANCED_SEARCH_TYPES, $property_type, $_MASK_REALESTATETYPES_ALL_CHECKED, true);
  377. } else {
  378. global $_LI_REALESTATEGROUPS, $_MASK_REALESTATETYPES_ALL_CHECKED;
  379. $checkedLabels = getCheckedFields($_LI_REALESTATEGROUPS, $property_type, $_MASK_REALESTATETYPES_ALL_CHECKED, true);
  380. }
  381. // Si ce n'est pas un tableau ou qu'il est vide, c'est "Tous types de bien"
  382. if (!is_array($checkedLabels) || $checkedLabels == array())
  383. $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
  384. else
  385. $summary["property_type"] = implode(', ', $checkedLabels);
  386. }
  387. }
  388. else {
  389. global $_LI_REALESTATETYPES;
  390. if ($data["property_type"] == "" || $data["property_type"][0] == -1 || count($data["property_type"]) == count($_LI_REALESTATETYPES)) {
  391. $summary["property_type"] = LABEL_ALL_PROPERTY_TYPE;
  392. } else {
  393. for ($i = 0; $i < count($data["property_type"]); $i++) {
  394. $data["property_type"][$i] = $_LI_REALESTATETYPES[$data["property_type"][$i]];
  395. }
  396. $summary["property_type"] = implode(", ", $data["property_type"]);
  397. }
  398. }
  399. // surface
  400. $summary["area"] = get_summary($data, $parameters["area"], "area", LABEL_ALL_AREA, LABEL_COMMON_AREA_UNIT);
  401. // price
  402. $summary["price"] = get_summary($data, $parameters["price"], "price", LABEL_ALL_BUDGET, LABEL_COMMON_PRICE_UNIT);
  403. // rooms
  404. // NB: pour la coloc., le nombre de pièces est en fait le nombre de chambres !
  405. if (isset($data['ck_nb_rooms'])) {
  406. global $_MASK_NB_ROOMS_ALL_CHECKED;
  407. $nb_rooms = $data['ck_nb_rooms'];
  408. // Convertir le tableau en chaine
  409. if (is_array($nb_rooms)) {
  410. $str_nb_rooms = str_repeat('0', 8); // 8 nombre de pieces possibles (2 octets)
  411. foreach ($nb_rooms as $nb_room) {
  412. $str_nb_rooms[intval($nb_room)] = 1;
  413. }
  414. $nb_rooms = $str_nb_rooms;
  415. }
  416. // Si champ vide, ou aucun coché ou tous cochés
  417. $all_checked = matchMask($nb_rooms, $_MASK_NB_ROOMS_ALL_CHECKED);
  418. if (empty($nb_rooms) || strpos($nb_rooms, '1') === false || $all_checked) {
  419. if ($showIfAllChecked)
  420. $summary["nb_rooms"] = ($data["univers"] == 8 ? LABEL_ALL_BEDROOMS : LABEL_ALL_ROOMS);
  421. }
  422. else {
  423. // Gérer le cas où seul le premier est coché (singulier)
  424. if (strpos($nb_rooms, '1', 1) === false && strpos($nb_rooms, '1') === 0) {
  425. $summary["nb_rooms"] = $_LI_ROOMS[0];
  426. } else {
  427. $limit = count($_LI_ROOMS) - 1;
  428. $str_nb_rooms = '';
  429. for ($i = 0; $i < $limit; $i++) {
  430. if ($nb_rooms[$i] == '1')
  431. $str_nb_rooms .= ', ' . ($i + 1);
  432. }
  433. // Ajouter le 'Et plus' sur le dernier si coché
  434. if ($nb_rooms[$i] == '1') {
  435. //$str_nb_rooms .= ', '.($i+1).' ';
  436. //$summary["nb_rooms"] = substr($str_nb_rooms,2).' '.LABEL_COMMON_ROOMS_UNIT.' '.LABEL_AND_MORE;
  437. if ($str_nb_rooms == '')
  438. $summary["nb_rooms"] = $_LI_ROOMS[$i];
  439. else
  440. $summary["nb_rooms"] = substr($str_nb_rooms, 2) . ', ' . $_LI_ROOMS[$i];
  441. }
  442. else {
  443. $summary["nb_rooms"] = substr($str_nb_rooms, 2) . ' ' . ($data["univers"] == 8 ? LABEL_COMMON_BEDROOMS_UNITS : LABEL_COMMON_ROOMS_UNITS);
  444. }
  445. }
  446. }
  447. } else {
  448. $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));
  449. }
  450. // bedrooms
  451. if (isset($data['ck_nb_bedrooms'])) {
  452. global $_MASK_NB_BEDROOMS_ALL_CHECKED, $_LI_BEDROOMS;
  453. $nb_bedrooms = $data['ck_nb_bedrooms'];
  454. // Convertir le tableau en chaine
  455. if (is_array($nb_bedrooms)) {
  456. $str_nb_bedrooms = str_repeat('0', 8); // 8 nombre de pieces possibles (2 octets)
  457. foreach ($nb_bedrooms as $nb_bedroom) {
  458. $str_nb_bedrooms[intval($nb_bedroom)] = 1;
  459. }
  460. $nb_bedrooms = $str_nb_bedrooms;
  461. }
  462. // Si champ vide, ou aucun coché ou tous cochés
  463. $all_checked = matchMask($nb_bedrooms, $_MASK_NB_BEDROOMS_ALL_CHECKED);
  464. if (empty($nb_bedrooms) || strpos($nb_bedrooms, '1') === false || $all_checked) {
  465. if ($showIfAllChecked)
  466. $summary["nb_bedrooms"] = 'Tous nb de chambres';
  467. }
  468. else {
  469. // Gérer le cas où seul le premier est coché (singulier)
  470. if (strpos($nb_bedrooms, '1', 1) === false && strpos($nb_bedrooms, '1') === 0) {
  471. $summary["nb_bedrooms"] = $_LI_BEDROOMS[0];
  472. } else {
  473. $limit = count($_LI_BEDROOMS) - 1;
  474. $str_nb_bedrooms = '';
  475. for ($i = 0; $i < $limit; $i++) {
  476. if ($nb_bedrooms[$i] == '1')
  477. $str_nb_bedrooms .= ', ' . ($i + 1);
  478. }
  479. // Ajouter le 'Et plus' sur le dernier si coché
  480. if ($nb_bedrooms[$i] == '1') {
  481. if ($str_nb_bedrooms == '')
  482. $summary["nb_bedrooms"] = $_LI_BEDROOMS[$i];
  483. else
  484. $summary["nb_bedrooms"] = substr($str_nb_bedrooms, 2) . ', ' . $_LI_BEDROOMS[$i];
  485. }
  486. else {
  487. $summary["nb_bedrooms"] = substr($str_nb_bedrooms, 2) . ' chambres';
  488. }
  489. }
  490. }
  491. }
  492. }
  493. return $summary;
  494. }
  495. /**
  496. * Convertit chaque critère par une valeur lisible par l'internaute
  497. * @param Array $data Tableau indexé des valeurs sélectionnées par l'internaute
  498. * @param Boolean $extended Afficher les "ou" entre parentheses [ex: chauffage (gaz,fioul) ]
  499. * @param Boolean $showIfAllChecked
  500. * @return Array Tableau indexé contenant uniquement les valeurs converties
  501. */
  502. function get_adv_summary($data, $extended = false, $showIfAllChecked = true) {
  503. global $_ADVANCED_SEARCH_CAT;
  504. $summary = array();
  505. // Critères avancés du bien (equipement, chauffage, fiche technique, etc.)
  506. if (isset($data['ck_advanced']) && strpos($data['ck_advanced'], '1') !== false) {
  507. $advanced = $data['ck_advanced'];
  508. // Récupérer la liste des critères sans les catégories
  509. // => Plus simple à interroger
  510. $advanced_search = array();
  511. foreach ($_ADVANCED_SEARCH_CAT as $SUB_CAT) {
  512. $advanced_search += $SUB_CAT;
  513. }
  514. $str_advanced = '';
  515. $length = strlen($advanced);
  516. if ($extended) {
  517. global $_MASK_ADV_OR;
  518. foreach ($_MASK_ADV_OR as $label => $mask_or) {
  519. $mask_value = $advanced & $mask_or;
  520. // Ajouter la clause OU
  521. if ($mask_value > 0) {
  522. // Equivalent d'un NON + compléter avec des 1 pour le ET ci-dessous
  523. $remove_mask = str_pad(strtr($mask_value, '01', '10'), $length, 1);
  524. // Effacer les critères de chauffage du masque principal
  525. $advanced = $advanced & $remove_mask;
  526. $pos = -1;
  527. $tmp_str_advanced = '';
  528. while (($pos = strpos($mask_value, '1', $pos + 1)) !== false) {
  529. $tmp_str_advanced .= ', ' . $advanced_search[$pos];
  530. }
  531. $tmp_str_advanced = substr($tmp_str_advanced, 2);
  532. $str_advanced .= ", $label ($tmp_str_advanced)";
  533. }
  534. }
  535. }
  536. $pos = -1;
  537. while (($pos = strpos($advanced, '1', $pos + 1)) !== false) {
  538. $str_advanced .= ', ' . $advanced_search[$pos];
  539. }
  540. $summary["advanced"] = substr($str_advanced, 2);
  541. }
  542. /*
  543. * *************************************************************************
  544. * TRAITEMENTS A ACTIVER SI UTILISES
  545. * (Surface du terrain, DPE, Fraicheur des annonces)
  546. * *************************************************************************
  547. *
  548. // Surface du terrain min / max
  549. $surf_min = isset($data['surf_min']) ? (int)$data['surf_min'] : 0;
  550. $surf_max = isset($data['surf_max']) ? (int)$data['surf_max'] : 0;
  551. if($surf_max>0) {
  552. $summary['surf'] = "Terrain entre {$surf_min} et {$surf_max} m²";
  553. } elseif($surf_min>0) {
  554. $summary['surf'] = "Terrain de plus de {$surf_min} m²";
  555. }
  556. // Consommation énergétique
  557. if(isset($data['dpe']) && strpos($data['dpe'],'1')!==false) {
  558. $ref_dpe = 'ABCDEFGH';
  559. $result = '';
  560. for($i=0, $max=strlen($data['dpe']); $i<$max; $i++) {
  561. if($data['dpe'][$i]==1) $result .= ', '.$ref_dpe[$i];
  562. }
  563. $summary['dpe'] = 'Energie '.substr($result,2);
  564. }
  565. // Fraicheur des annonces
  566. if(isset($data['fresh']) && ($fresh = (int)$data['fresh'])!==0) {
  567. switch(substr($data['fresh'],-1)) {
  568. case 'h': $unit = $fresh==1 ? 'heure' : 'heures'; break;
  569. case 'j': $unit = $fresh==1 ? 'jour' : 'jours'; break;
  570. case 's': $unit = $fresh==1 ? 'semaine' : 'semaines'; break;
  571. case 'm': $unit = 'mois'; break;
  572. case 'a': $unit = $fresh==1 ? 'an' : 'ans'; break;
  573. }
  574. if(isset($unit)) {
  575. $summary['fresh'] = "Annonces de moins de {$fresh} {$unit}";
  576. }
  577. }
  578. */
  579. return $summary;
  580. }
  581. /**
  582. * Turns a search criterion to a human readable value
  583. *
  584. * @param unknown_type $data
  585. * @param unknown_type $parameters
  586. * @param unknown_type $item
  587. * @param unknown_type $label_all
  588. * @param unknown_type $label_unit
  589. * @return unknown
  590. */
  591. function get_summary($data, $parameters, $item, $label_all, $label_unit) {
  592. // patch
  593. if ($data[$item] == -1) {
  594. $data[$item] = "";
  595. }
  596. // rooms
  597. if (in_array($item, array("nb_rooms", "nb_bedrooms", "nb_people"))) {
  598. if ($data[$item] == "" && $data[$item . "_min"] == "" && $data[$item . "_max"] == "") {
  599. $summary = $label_all;
  600. } else {
  601. if ($data[$item] != "") {
  602. $summary = $parameters[$data[$item]];
  603. } else {
  604. if ($data[$item . "_min"] != "" && $data[$item . "_max"] != "") {
  605. $summary = LABEL_FROM . " " . $data[$item . "_min"] . " " . LABEL_TO . " " . $data[$item . "_max"] . " " . $label_unit;
  606. } elseif ($data[$item . "_min"] != "" && $data[$item . "_max"] == "") {
  607. $summary = LABEL_MORE_THAN . " " . $data[$item . "_min"] . " " . $label_unit;
  608. } else {
  609. $summary = LABEL_LESS_THAN . " " . $data[$item . "_max"] . " " . $label_unit;
  610. }
  611. }
  612. }
  613. }
  614. // price, surface
  615. else {
  616. if (!is_numeric($data[$item . "_min"]))
  617. $data[$item . "_min"] = '';
  618. if (!is_numeric($data[$item . "_max"]))
  619. $data[$item . "_max"] = '';
  620. if ($data[$item] == "" && $data[$item . "_min"] == "" && $data[$item . "_max"] == "") {
  621. $summary = $label_all;
  622. } else {
  623. if ($data[$item] != "") {
  624. $value = $parameters[$data[$item]];
  625. if ($value["from"] == 0) {
  626. $summary = LABEL_LESS_THAN . " " . $value["to"] . " " . $label_unit;
  627. } elseif ($value["to"] == 999999999) {
  628. $summary = LABEL_MORE_THAN . " " . $value["from"] . " " . $label_unit;
  629. } else {
  630. $summary = LABEL_FROM . " " . $value["from"] . " " . LABEL_TO . " " . $value["to"] . " " . $label_unit;
  631. }
  632. } else {
  633. if ($data[$item . "_min"] != "" && $data[$item . "_max"] != "") {
  634. $summary = LABEL_FROM . " " . n_f($data[$item . "_min"]) . " " . LABEL_TO . " " . n_f($data[$item . "_max"]) . " " . $label_unit;
  635. } elseif ($data[$item . "_min"] != "" && $data[$item . "_max"] == "") {
  636. $summary = LABEL_MORE_THAN . " " . n_f($data[$item . "_min"]) . " " . $label_unit;
  637. } else {
  638. $summary = LABEL_LESS_THAN . " " . n_f($data[$item . "_max"]) . " " . $label_unit;
  639. }
  640. }
  641. }
  642. }
  643. return $summary;
  644. }
  645. /**
  646. * Returns property type label depending on the code
  647. *
  648. * @param unknown_type $id
  649. * @return unknown
  650. */
  651. function get_property_type_label($id) {
  652. global $_LI_REALESTATETYPES;
  653. foreach ($_LI_REALESTATETYPES as $property_type) {
  654. if ($property_type["value"] == $id) {
  655. return $property_type["label"];
  656. }
  657. }
  658. }
  659. /**
  660. * number_format shortcut
  661. *
  662. * @param unknown_type $value
  663. * @return unknown
  664. */
  665. function n_f($value) {
  666. return number_format($value, 0, "", " ");
  667. }
  668. /**
  669. * Currency conversion
  670. *
  671. * @param unknown_type $value
  672. * @param unknown_type $from
  673. * @param unknown_type $to
  674. * @param unknown_type $add_currency_name
  675. * @return unknown
  676. */
  677. function currency_format($value, $from, $to, $add_currency_name = true) {
  678. global $_global;
  679. global $_rates;
  680. if ($_rates[$from][$to] > 0) {
  681. $price = n_f($value * $_rates[$from][$to]);
  682. if ($add_currency_name) {
  683. switch ($_global["current_currency"]) {
  684. case "CZK" :
  685. $price = $price . " " . LABEL_COMMON_PRICE_UNIT_CZ;
  686. break;
  687. case "EUR" :
  688. $price = $price . " " . LABEL_COMMON_PRICE_UNIT;
  689. break;
  690. case "CHF" :
  691. $price = $price . " " . LABEL_COMMON_PRICE_UNIT_CH;
  692. break;
  693. default :
  694. $price = $price . " " . LABEL_COMMON_PRICE_UNIT;
  695. break;
  696. }
  697. }
  698. return $price;
  699. }
  700. }
  701. /**
  702. * Function so sex, par le so sexy oxman, da crazy man !
  703. *
  704. * @param unknown_type $input
  705. * @param unknown_type $partial
  706. * @return unknown
  707. */
  708. function sosex($input, $partial = false) {
  709. // Partial mode, the word isn't complete, typically when you're doing an ajax completion
  710. $input = str_replace('è', 'ai', $input);
  711. $input = str_replace('ê', 'ai', $input);
  712. $input = str_replace('é', 'ai', $input);
  713. $input = strtoupper($input);
  714. // START - Nettoiement de la recherche, suppressions de tous les caracteres parasites
  715. $input = preg_replace('/(.)\\1{1,}/', '\\1', $input); // 1. Suppression des lettres en doubles (exemple: pelle, femme)
  716. $input = preg_replace('/[-,\/;.\']/', ' ', $input); // 2. Sérateur de mot : , / ; . -
  717. $input = preg_replace('/(?=\b)[^ ](?=\b)/', '', $input); // 28. Suppression des caractères isolées (résultant d'un D', L', etc)
  718. $input = ' ' . $input . ' ';
  719. $input = preg_replace('/(?=\b)ST(?=\b)/', 'SAINT', $input); // 3. Attention avant la 4
  720. $input = preg_replace('/(?=\b)[LD]ES(?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
  721. $input = preg_replace('/(?=\b)SUR(?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
  722. $input = preg_replace('/(?=\b)SOUS(?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
  723. $input = preg_replace('/(?=\b)L[EA](?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
  724. $input = preg_replace('/(?=\b)D[EU](?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
  725. $input = preg_replace('/(?=\b)E[TN](?=\b)/', '', $input); // 4. Suppression des dérminants (exemple: nos, mes, du, les, la)
  726. $input = str_replace('ET', 'AIT', $input); // 25. Son : AI (exemple: jouet, essai), avant la regle de suppressions des lettres muettes (n°20)
  727. $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)
  728. $input = preg_replace('/[AE][NM](?![AEIOUY])/', 'AN', $input); // 5. Son : AN (exemple: femme, enfant), avant lettres muettes
  729. $input = preg_replace('/OM(?![AEIOUY])/', 'ON', $input); // 14. Son : ON (exemple: pantalom, pomtom), avant lettres muettes
  730. $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
  731. $input = preg_replace('/P[HF]/', 'F', $input); // 19. Son : F (exemple: PF ou PH donne le son F), avant lettres muettes
  732. $input = str_replace('Y', 'I', $input); // 29. Son : I, avant lettres muettes
  733. $input = preg_replace('/X(?=\b)/', '', $input); // 30. Son : X muet à la fin de mot
  734. if (!$partial) {
  735. $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
  736. $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
  737. $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
  738. $input = preg_replace('/ES(?=\b)/', '', $input); // 27. Son ES en fin de mot muet
  739. }
  740. // END
  741. $input = str_replace('EU', 'E', $input); // 25. Son : E, après la regle de suppressions des lettres muettes (n°20)
  742. $input = preg_replace('/E?AU/', 'O', $input); // 7. Son O : veau, pot, l'horizon
  743. $input = str_replace('SH', 'CH', $input); // 9. Son : CH
  744. $input = preg_replace('/C[CK]/', 'K', $input); // 18. Son : K (exemple: CC ou CK donne le son K)
  745. $input = str_replace('QU', 'K', $input); // 10. Son : K (exemple: quand, bouquet, plaque)
  746. $input = str_replace('KS', 'X', $input); // 28. Son : X (exemple: luksiol)
  747. $input = preg_replace('/C(?=[UAO]|\b)/', 'K', $input); // 16. Son : K (exemple: cutalion, carole, mais pas celine, ciboulette, candiac)
  748. $input = preg_replace('/C(?=[IEY])/', 'S', $input); // 17. Son : S (exemple: celine, ciboulette, cy..., mais pas cutalion, carole)
  749. $input = preg_replace('/G(?=[IEYL]|\b)/', 'J', $input); // 24. Son : J (exemple: gille, vregille, mais pas vrigne, zigliara)
  750. $input = str_replace('Z', 'S', $input); // 15. Son : Z S
  751. $input = preg_replace("/(.)\\1{1,}/", "\\1", $input); // 12. Suppression des lettres en doubles cré aprètransformation (tout àa fin)
  752. return trim($input);
  753. }
  754. /**
  755. * Replace only the first occurence of a string
  756. *
  757. * @param unknown_type $needle
  758. * @param unknown_type $replace
  759. * @param unknown_type $haystack
  760. * @return unknown
  761. */
  762. function str_replace_once($needle, $replace, $haystack) {
  763. // Looks for the first occurence of $needle in $haystack
  764. // and replaces it with $replace.
  765. $pos = strpos($haystack, $needle);
  766. if ($pos === false) {
  767. // Nothing found
  768. return $haystack;
  769. }
  770. return substr_replace($haystack, $replace, $pos, strlen($needle));
  771. }
  772. /**
  773. * Returns a truncated string
  774. *
  775. * @param unknown_type $value
  776. * @param unknown_type $limit
  777. * @return unknown
  778. */
  779. function str_limit($value, $limit) {
  780. if (strlen($value) == 0) {
  781. return "";
  782. } else {
  783. if (strlen($value) <= $limit) {
  784. return $value;
  785. } else {
  786. $tmp = explode(" ", $value);
  787. if (count($tmp) > 0) {
  788. $valV = $valVold = "";
  789. foreach ($tmp as $v) {
  790. if (strlen($valV) > $limit) {
  791. $value = substr($valVold, 0, -1) . "...";
  792. break;
  793. }
  794. else
  795. $valVold = $valV;
  796. $valV .= $v . " ";
  797. }
  798. }
  799. return $value;
  800. }
  801. }
  802. }
  803. /**
  804. * Returns html city name with arrondissement correctly written in french
  805. * ex: Marseille 1er => Marseille 1<sup>er</sup>, Paris 2e => Paris 2<sup>ème</sup>
  806. *
  807. * @param unknown_type $cityname_arrond
  808. * @return unknown
  809. */
  810. function cityname_arrond($cityname_arrond, $short_form = false) {
  811. $str_cityname_arrond = "";
  812. $arr_cityname_arrond = explode(" ", $cityname_arrond);
  813. $str_cityname = $arr_cityname_arrond[0];
  814. $str_arrond = $arr_cityname_arrond[1];
  815. if (strpos($str_arrond, "er") !== FALSE) {
  816. $str_cityname_arrond = $str_cityname . " " . str_replace("er", "<sup>er</sup>", $str_arrond);
  817. } else if (strpos($str_arrond, "e") !== FALSE) {
  818. if ($short_form) {
  819. $str_cityname_arrond = $str_cityname . " " . str_replace("e", "<sup>è</sup>", $str_arrond);
  820. } else {
  821. $str_cityname_arrond = $str_cityname . " " . str_replace("e", "<sup>ème</sup>", $str_arrond);
  822. }
  823. }
  824. return $str_cityname_arrond;
  825. }
  826. /**
  827. * Returns html city name without arrondissement at the end, if present
  828. * ex: Marseille 1er => Marseille, Paris 2e => Paris, Cannes => Cannes
  829. *
  830. * @param unknown_type $cityname_arrond
  831. * @return unknown
  832. */
  833. function cityname_without_arrond($cityname_arrond) {
  834. $str_cityname_arrond = $cityname_arrond;
  835. $str_cityname_arrond = preg_replace('/(\w+) (\d+)er/i', '${1}', $str_cityname_arrond);
  836. $str_cityname_arrond = preg_replace('/(\w+) (\d+)e/i', '${1}', $str_cityname_arrond);
  837. return $str_cityname_arrond;
  838. }
  839. /**
  840. * Returns true if the lct_id is the one of the arrondissement of a city (Paris, Lyon, Marseille)
  841. * ex: 36102 => true (Marseille 2è), 33109 => false (Toulon)
  842. *
  843. * @param int $lct_id
  844. * @return bool
  845. */
  846. function is_lct_id_arrond_of_city($lct_id) {
  847. if (!isset($lct_id) || empty($lct_id)) {
  848. return array(false, "");
  849. }
  850. $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);
  851. if (in_array($lct_id, $lct_ids_arrronds_paris)) {
  852. return array(true, "paris");
  853. }
  854. $lct_ids_arrronds_marseille = array(36102, 36104, 36105, 36106, 36107, 36108, 36109, 36110, 36111, 36112, 36113, 36114, 36115, 36116, 36117, 36118);
  855. if (in_array($lct_id, $lct_ids_arrronds_marseille)) {
  856. return array(true, "marseille");
  857. }
  858. $lct_ids_arrronds_lyon = array(36119, 36120, 36121, 36122, 36123, 36124, 36125, 36126, 36127);
  859. if (in_array($lct_id, $lct_ids_arrronds_lyon)) {
  860. return array(true, "lyon");
  861. }
  862. return array(false, "");
  863. }
  864. /**
  865. * Returns true if the loc_key is the one of city with arrondissements (Paris, Lyon, Marseille)
  866. * ex: 421_99 => true (Marseille), 33109_2 => false (Toulon)
  867. *
  868. * @param int $lct_id
  869. * @return bool
  870. */
  871. function is_loc_key_city_with_arronds($loc_key) {
  872. if (!isset($loc_key) || empty($loc_key)) {
  873. return array(false, "");
  874. }
  875. $loc_key_paris = '100_1';
  876. if ($loc_key == $loc_key_paris) {
  877. return array(true, "paris");
  878. }
  879. $loc_key_marseille = '421_99';
  880. if ($loc_key == $loc_key_marseille) {
  881. return array(true, "marseille");
  882. }
  883. $loc_key_lyon = '422_99';
  884. if ($loc_key == $loc_key_lyon) {
  885. return array(true, "lyon");
  886. }
  887. return array(false, "");
  888. }
  889. /**
  890. * Returns a clean string
  891. *
  892. * @param unknown_type $value
  893. * @return unknown
  894. */
  895. function remove_returns($value) {
  896. $value = str_replace("\r\n", "", $value);
  897. $value = str_replace("\n\r", "", $value);
  898. $value = str_replace("\n", "", $value);
  899. $value = str_replace("\r", "", $value);
  900. return $value;
  901. }
  902. /**
  903. * Returns a "clean" html, without css MS Office classes
  904. *
  905. * @param unknown_type $value
  906. * @return unknown
  907. */
  908. function strip_mso_css_class($value) {
  909. $value = str_replace(" class=\"MsoPlainText\"", "", $value);
  910. return $value;
  911. }
  912. /**
  913. * Returns in a html string li tags par a dot char
  914. *
  915. * @param unknown_type $value
  916. * @return unknown
  917. */
  918. function replace_li_tag_dot_char($value) {
  919. $value = str_replace("<li>", "&#149;&nbsp;&nbsp;", $value);
  920. $value = str_replace("</li>", "<br>", $value);
  921. $value = str_replace("<ul>", "", $value);
  922. $value = str_replace("</ul>", "", $value);
  923. return $value;
  924. }
  925. /**
  926. * Returns html height and width properties, determining the size of an image to fit required width and height
  927. *
  928. * @param unknown_type $img
  929. * @param unknown_type $max_width
  930. * @param unknown_type $max_height
  931. * @return unknown
  932. */
  933. function resize_image($img, $max_width, $max_height) {
  934. $img_details = @getimagesize($img);
  935. $img_width = $img_details[0];
  936. $img_height = $img_details[1];
  937. if ($img_width == "" || $img_height == "") {
  938. return "";
  939. }
  940. $img_wratio = round($img_height / $img_width, 2);
  941. $img_hratio = round($img_width / $img_height, 2);
  942. if ($img_width > $max_width || $img_height > $max_height) {
  943. if ($img_width > $img_height) {
  944. $img_width = $max_width;
  945. $img_height = $img_width * $img_wratio;
  946. if ($img_height > $max_height) {
  947. $img_height = $max_height;
  948. $img_width = $img_height * $img_hratio;
  949. }
  950. } else {
  951. $img_height = $max_height;
  952. $img_width = $img_height * $img_hratio;
  953. if ($img_width > $max_width) {
  954. $img_width = $max_width;
  955. $img_height = $img_width * $img_wratio;
  956. }
  957. }
  958. }
  959. return "width=\"" . $img_width . "\" height=\"" . $img_height . "\"";
  960. }
  961. /**
  962. * Returns html code for a spacer
  963. *
  964. * @param unknown_type $height
  965. * @param unknown_type $width
  966. * @return unknown
  967. */
  968. function spacer($height, $width) {
  969. return "<img src=\"" . get_urlmmf('/spacer.gif') . "\" height=\"" . $height . "\" width=\"" . $width . "\" />";
  970. }
  971. /**
  972. * Returns html alt and title
  973. *
  974. * @param unknown_type $value
  975. * @return unknown
  976. */
  977. function set_html_title($value) {
  978. return "alt=\"" . $value . "\" title=\"" . $value . "\"";
  979. }
  980. /**
  981. * Returns ad and agency data
  982. *
  983. * @param unknown_type $page
  984. * @param unknown_type $value
  985. * @param unknown_type $has_premium
  986. * @param unknown_type $url
  987. * @param Integer $idx
  988. * @param Boolean $is_exclusive Annonce à afficher en haut de la page des annonces
  989. * @return unknown
  990. */
  991. function get_ad_data($page, $value, $has_premium = 0, $url = "", $idx = -1, $is_exclusive = false) {
  992. global $_global;
  993. global $_LI_REALESTATETYPES;
  994. global $_REF_ROOMS;
  995. global $_LI_BANDEAU_PERSO_FR;
  996. $prefix_table = '';
  997. if ( 9 != $_global['univers'] ) {
  998. $prefix_table = $_global["table_prefix"] . '_';
  999. }
  1000. // arrays
  1001. $ad = array();
  1002. $ag = array();
  1003. //echo '<pre>'; var_dump($value); echo '</pre>';
  1004. $ad["idx"] = $idx;
  1005. $ad["id"] = $value["id_annonce"];
  1006. $ad["univers"] = $value["univers"];
  1007. $ad["reference"] = $value[$prefix_table . "reference"];
  1008. $ad["num_mandat"] = $value[$prefix_table . "num_mandat"];
  1009. // ad premium
  1010. $ad["premium"] = $value[$prefix_table . "is_premium"];
  1011. // ad features
  1012. $ad["type_transaction"] = $value[$prefix_table . "type_transaction"];
  1013. $ad["id_bien"] = $value["id_bien"];
  1014. $ad["id_bien_programme"] = $value["id_bien_programme"];
  1015. $ad["prg_title"] = $value["prg_title"];
  1016. $ad["property_type_id"] = $value[$prefix_table . "property_type_id"];
  1017. $ad["property_type_id_orig"] = $value[$prefix_table . "property_type_id_orig"];
  1018. $ad["property_type"] = html_entity_decode($value[$prefix_table . "property_type"], ENT_QUOTES, "UTF-8");
  1019. if ($ad["type_transaction"] == "4")
  1020. $ad["property_type"] .= LABEL_AD_LIFE_ANNUITY;
  1021. $ad["agency_rent_fees"] = $value["rnt_agency_rent_fees"];
  1022. $ad["rnt_property_charges"] = $value["rnt_property_charges"];
  1023. $ad["guarantee_deposit"] = $value[$prefix_table . "guarantee_deposit"];
  1024. //ad currency
  1025. $ad["currency"] = $value[$prefix_table . "currency"];
  1026. //SUSPENSION DES CHARGES
  1027. $ad["real_price"] = $value[$prefix_table . "price"];
  1028. $ad["price"] = ($ad["real_price"] >= AD_PRICE_LIMIT ? $ad["real_price"] : n_f($ad["real_price"]));
  1029. if ($ad["property_type"] == "") {
  1030. $ad["property_type"] = ($ad["property_type_id_orig"] != "" ? constant("LABEL_COMMON_PROPERTY_ID_" . $ad["property_type_id_orig"]) : "");
  1031. }
  1032. $ad["area"] = $value[$prefix_table . "area"];
  1033. $ad["price"] = ($ad["real_price"] >= AD_PRICE_LIMIT ? $ad["real_price"] : n_f($ad["real_price"]));
  1034. $ad["nb_rooms"] = $value[$prefix_table . "nb_rooms"];
  1035. // Advanced : dependances, chauffage, amenagement, confort
  1036. $ad["advanced_set"] = $value[$prefix_table . 'advanced_set'];
  1037. // First online date
  1038. $ad["first_online_date"] = $value[$prefix_table . 'first_online_date'];
  1039. //Colocation
  1040. if ($_global["univers"] == 8) {
  1041. $ad["nb_bedrooms"] = $value["rnt_nb_bedrooms"];
  1042. }
  1043. $ad["default_text"] = str_replace("[[n]]", " ", $value[$prefix_table . "default_text"]);
  1044. if ($_global["self"] == "resultats_refnat.php") {
  1045. $ad["default_intro"] = strtolower(strip_tags(str_limit($ad["default_text"], 90)));
  1046. } else {
  1047. $ad["default_intro"] = preg_replace('`(\<[a-zA-Z]*)\.\.\.$`', '', str_limit($ad["default_text"], 200));
  1048. }
  1049. // vacances
  1050. if ($_global["univers"] == 13) {
  1051. $ad["nb_bedrooms"] = $value["rnt_nb_bedrooms"];
  1052. $ad["nb_people"] = $value["rnt_nb_people"];
  1053. if ($value["rnt_site_agency"] != "") {
  1054. if (substr($value["rnt_site_agency"], 0, 7) != "http://") {
  1055. $value["rnt_site_agency"] = "http://" . $value["rnt_site_agency"];
  1056. }
  1057. $ad["partner_url"] = $value["rnt_site_agency"];
  1058. }
  1059. $ad["external"] = ($value["id_presto"] == "CMM-PT-VACANCES" ? true : false);
  1060. }
  1061. if ($_global["univers"] == 13) {
  1062. $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 : "");
  1063. } else {
  1064. if ($ad["nb_rooms"] == 1) {
  1065. $s_piece = LABEL_COMMON_ROOM_UNIT;
  1066. } else {
  1067. $s_piece = LABEL_COMMON_ROOMS_UNITS;
  1068. }
  1069. if ($_global["self"] == "resultats_refnat.php") {
  1070. $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 : "");
  1071. } else {
  1072. $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 : "");
  1073. }
  1074. /** Suppression du label "OU PLUS" Mathieu 25/01
  1075. if ($ad["nb_rooms"] == 6) {
  1076. $ad["features"] .= " " . LABEL_COMMON_OR_MORE;
  1077. }
  1078. *
  1079. */
  1080. }
  1081. $ad["is_exclusive"] = $value[$prefix_table . "is_exclusive"];
  1082. $is_exclusive = $is_exclusive || CURRENT_EXCLUSIVE_NUM > 0 && CURRENT_EXCLUSIVE_NUM == $ad['is_exclusive'];
  1083. $ad['is_pack_exclusive'] = $is_exclusive;
  1084. //20090401-1-XI, Retrieving xxx_locality_2_agency field (mantis 5342)
  1085. $ad["locality_2_agency"] = $value[$prefix_table . "locality_2_agency"];
  1086. //20090610-1-XI, NOT Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO', mantis 5865
  1087. //20090407-1-XI, Setting agc loc of ads to 0 if id_presto='CMM-PT-BDL-EXPRESSO'
  1088. /*
  1089. if ($value["id_presto"]=="CMM-PT-BDL-EXPRESSO")
  1090. $ad["locality_2_agency"] = 0;
  1091. */
  1092. $locality_for_url = prepareToUrl($value[$prefix_table . "default_town_2"]);
  1093. $lang = 'FR';
  1094. #$lang = $value[$_global["table_prefix"]."_country"];
  1095. // ad full features
  1096. if ($page == "detail.php" || $page == "detail_refnat.php") {
  1097. $ad["garden_area"] = $value[$prefix_table . "garden_area"];
  1098. $ad["terrace_area_1"] = $value[$prefix_table . "terrace_area_1"];
  1099. $ad["balcony_area_1"] = $value[$prefix_table . "balcony_area_1"];
  1100. $ad["is_pool"] = $value[$prefix_table . "is_pool"];
  1101. $ad["pool_area"] = $value[$prefix_table . "pool_area"];
  1102. $ad["nb_garage"] = $value[$prefix_table . "nb_garage"];
  1103. $ad["nb_parking"] = $value[$prefix_table . "nb_parking"];
  1104. $ad["is_parking_closed"] = $value[$prefix_table . "is_parking_closed"];
  1105. $ad["nb_covered_parking"] = $value[$prefix_table . "nb_covered_parking"];
  1106. $ad["nb_uncovered_parking"] = $value[$prefix_table . "nb_uncovered_parking"];
  1107. $ad["is_renovated"] = $value[$prefix_table . "is_renovated"];
  1108. $ad["renovating_date"] = $value[$prefix_table . "renovating_date"];
  1109. $ad["need_renovating"] = $value[$prefix_table . "need_renovating"];
  1110. $ad["floor"] = $value[$prefix_table . "floor"];
  1111. $ad["nb_caretaker"] = $value[$prefix_table . "nb_caretaker"];
  1112. $ad["is_interphone"] = $value[$prefix_table . "is_interphone"];
  1113. $ad["is_doorcode"] = $value[$prefix_table . "is_doorcode"];
  1114. $ad["is_elevator"] = $value[$prefix_table . "is_elevator"];
  1115. $ad["nb_bath"] = $value[$prefix_table . "nb_bath"];
  1116. $ad["nb_shower"] = $value[$prefix_table . "nb_shower"];
  1117. $ad["is_independant_toilet"] = $value[$prefix_table . "is_independant_toilet"];
  1118. $ad["is_first_floor_toilet"] = $value[$prefix_table . "is_first_floor_toilet"];
  1119. $ad["is_central_heating"] = $value[$prefix_table . "is_central_heating"];
  1120. $ad["is_individual_heating"] = $value[$prefix_table . "is_individual_heating"];
  1121. $ad["is_electrical_heating"] = $value[$prefix_table . "is_electrical_heating"];
  1122. $ad["is_floor_heating"] = $value[$prefix_table . "is_floor_heating"];
  1123. $ad["is_gas_heating"] = $value[$prefix_table . "is_gas_heating"];
  1124. $ad["is_diesel_heating"] = $value[$prefix_table . "is_diesel_heating"];
  1125. $ad["is_aircon"] = $value[$prefix_table . "is_aircon"];
  1126. $ad["is_chimney"] = $value[$prefix_table . "is_chimney"];
  1127. $ad["is_wooden_floor"] = $value[$prefix_table . "is_wooden_floor"];
  1128. $ad["is_tiled_floor"] = $value[$prefix_table . "is_tiled_floor"];
  1129. $ad["is_alarm"] = $value[$prefix_table . "is_alarm"];
  1130. $ad["is_sunny"] = $value[$prefix_table . "is_sunny"];
  1131. $ad["is_calm"] = $value[$prefix_table . "is_calm"];
  1132. $ad["facing"] = $value[$prefix_table . "facing"];
  1133. $ad["is_handicap_access"] = $value[$prefix_table . "is_handicap_access"];
  1134. $ad["agency_rent_fees"] = $value[$prefix_table . "agency_rent_fees"];
  1135. $ad["is_closet"] = $value[$prefix_table . "is_closet"];
  1136. $ad["is_basement"] = $value[$prefix_table . "is_basement"];
  1137. }
  1138. if ($page == 'detail.php') {
  1139. $ad["id_programme"] = $value["id_programme"];
  1140. // $ad["type_transaction"] = $value[$prefix_table."_type_transaction"];
  1141. }
  1142. //DPE
  1143. $ad["dpe_energy"] = $value[$prefix_table . "energy"];
  1144. $ad["dpe_energy_val"] = $value[$prefix_table . "energy_val"];
  1145. // ad pictures
  1146. $ad["photos_count"] = 0;
  1147. if ($page != "resultats.php") {
  1148. $ad_photos = array();
  1149. $ad_photos[] = $value[$prefix_table . "photo"];
  1150. $ad_photos[] = $value[$prefix_table . "photo_2"];
  1151. $ad_photos[] = $value[$prefix_table . "photo_3"];
  1152. $ad_photos[] = $value[$prefix_table . "photo_4"];
  1153. $ad_photos[] = $value[$prefix_table . "photo_5"];
  1154. /*
  1155. A venir
  1156. $ad_photos[] = $value[$prefix_table."_photo_6"];
  1157. $ad_photos[] = $value[$prefix_table."_photo_7"];
  1158. $ad_photos[] = $value[$prefix_table."_photo_8"];
  1159. $ad_photos[] = $value[$prefix_table."_photo_9"];
  1160. $ad_photos[] = $value[$prefix_table."_photo_10"];
  1161. */
  1162. foreach ($ad_photos as $photo) {
  1163. if (strlen($photo) > 1) {
  1164. $ad["photos"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
  1165. // from detail
  1166. if ($page == "detail_coloc.php" || $page == "detail.php" || $page == "detail_refnat.php" || $page == "fiche_visite.php" || $page == "home_ville.php" || $page == "resultats_refnat.php") {
  1167. $ad["photos_multibox"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP_MULTIBOX, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
  1168. $ad["thumbs"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_CROP_THUMB_DETAIL, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
  1169. }
  1170. // from results
  1171. else {
  1172. $ad["thumbs"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP_THUMB, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
  1173. $ad["thumbs_detail"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_CROP_THUMB_DETAIL, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
  1174. }
  1175. $ad["photos_id"][] = $photo;
  1176. ++$ad["photos_count"];
  1177. }
  1178. }
  1179. if (isset($value[$prefix_table . "nb_photo"]) && !empty($value[$prefix_table . "nb_photo"])) {
  1180. $ad["photos_count"] = (($value[$prefix_table . "nb_photo"] > 5) ? 5 : $value[$prefix_table . "nb_photo"]);
  1181. }
  1182. } else {
  1183. if (strlen($value[$prefix_table . "photo"]) > 1) {
  1184. $photo = $value[$prefix_table . "photo"];
  1185. $ad["photos"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
  1186. $ad["thumbs"][] = get_urlmmf_anc_seo(MMF_FORMAT_FR_ANC_PROP_THUMB, $photo, $ad['id'], $ad['property_type'], $locality_for_url, $lang);
  1187. $ad["photos_id"][] = $value[$prefix_table . "photo"];
  1188. $ad["photos_count"] = (($value[$prefix_table . "nb_photo"] > 5) ? 5 : $value[$prefix_table . "nb_photo"]);
  1189. }
  1190. }
  1191. // ad multimedia
  1192. for ($i = 1; $i < 6; $i++) {
  1193. $key = $value[$prefix_table . "mmf_type_" . $i];
  1194. $item = $value[$prefix_table . "mmf_" . $i];
  1195. if ($key != "" && $item != "") {
  1196. $ad["mmf"][get_mmf_type($key)][] = $item;
  1197. }
  1198. }
  1199. for ($i = 1; $i < 6; $i++) {
  1200. $ad["mmf_type_" . $i . "_count"] = count($ad["mmf"][$i]);
  1201. }
  1202. // ad logicode
  1203. $ad["logicode"] = $value[$prefix_table . "logicode"];
  1204. $ad["logicode"] = ($ad["logicode"] == "" ? $value[$prefix_table . "logicode_old"] : $ad["logicode"]);
  1205. // ad hierarchy
  1206. $ad["hierarchy"] = array();
  1207. for ($i = 0; $i < 3; $i++) {
  1208. // id de localité incohérent => pas ajouté
  1209. if (($i == 2) && ($value[$prefix_table . "locality_" . $i] < 121)) {
  1210. $value[$prefix_table . "locality_" . $i] = "";
  1211. $value[$prefix_table . "default_town_" . $i] = "";
  1212. continue;
  1213. }
  1214. $ad["hierarchy"][] = array("lct_id" => $value[$prefix_table . "locality_" . $i], "lct_name" => $value[$prefix_table . "default_town_" . $i]);
  1215. }
  1216. // ad localisation
  1217. $ad["default_town"] = $value[$prefix_table . "default_town"];
  1218. for ($i = 0; $i < 3; $i++) {
  1219. // id de localité incohérent => pas ajouté
  1220. if (($i == 2) && ($value[$prefix_table . "locality_" . $i] < 121)) {
  1221. $value[$prefix_table . "locality_" . $i] = "";
  1222. $value[$prefix_table . "default_town_" . $i] = "";
  1223. continue;
  1224. }
  1225. $ad["default_town_" . $i] = $value[$prefix_table . "default_town_" . $i];
  1226. }
  1227. // Florian - 19/07/2010
  1228. // Test temporaire pour loc/coloc pour gérer les couples clé/label de localité invalide
  1229. // => Pourrait être étendu à la vente mais conséquences imprévisibles !
  1230. if ($_global['univers'] == '8' || $_global['univers'] == '2') {
  1231. for ($i = 2; $i >= 0; $i--) {
  1232. /* * *******************************************************************
  1233. * ANNULATION DU TEST POUR AVOIR LES lct_id/lct_level TOUT LE TEMPS
  1234. *
  1235. // Si la ville n'est pas vide et que la clé est valide
  1236. if ($value[$prefix_table."_default_town_".$i]!="" && $value[$prefix_table."_locality_".$i]!='0')
  1237. {
  1238. * ******************************************************************** */
  1239. if (isset($value[$prefix_table . "default_town_" . $i]) && ($value[$prefix_table . "default_town_" . $i] != "") && ($value[$prefix_table . "locality_" . $i] != '0')) {
  1240. // Si la clé de localité est la même que le parent, on utilise le parent
  1241. if ($value[$prefix_table . "locality_" . $i] == $value[$prefix_table . "locality_" . ($i - 1)])
  1242. continue;
  1243. $ad["real_town"] = $value[$prefix_table . "default_town_" . $i];
  1244. $ad["lct_id"] = $value[$prefix_table . "locality_" . $i];
  1245. $ad["lct_level"] = $i;
  1246. break;
  1247. }
  1248. }
  1249. }
  1250. else {
  1251. for ($i = 2; $i >= 0; $i--) {
  1252. if (isset($value[$prefix_table . "default_town_" . $i]) && ($value[$prefix_table . "default_town_" . $i] != "") && ($value[$prefix_table . "locality_" . $i] != '0')) {
  1253. $ad["real_town"] = $value[$prefix_table . "default_town_" . $i];
  1254. $ad["lct_id"] = $value[$prefix_table . "locality_" . $i];
  1255. $ad["lct_level"] = $i;
  1256. break;
  1257. }
  1258. }
  1259. }
  1260. //error_log(print_r($ad, true), 3, "/tmp/bmo.log");
  1261. if (trim($ad['default_town']) == '')
  1262. $ad['default_town'] = $ad['default_town_2'];
  1263. //SARA A. 12/05/09 relais lux
  1264. $ad["lct_0"] = $value[$prefix_table . "locality_0"];
  1265. $ad["lgm_id"] = $value["lgm_id"];
  1266. $ad["lgc_id"] = $value["lgc_id"];
  1267. $ad["lgn_id"] = $value["lgn_id"];
  1268. $ad["lzip"] = $value[$prefix_table . "post_code"];
  1269. $ad["szip"] = substr($ad["lzip"], 0, 2);
  1270. $ad["real_zip"] = ($ad["lct_level"] == '1' ? $ad["szip"] : $ad["lzip"]); // CP correspondant à la localité calculée
  1271. $ad["country"] = $value[$prefix_table . "country"];
  1272. $ad["default_proximity"] = $value[$prefix_table . "default_proximity"];
  1273. $ad["default_sector"] = $value[$prefix_table . "default_sector"];
  1274. $ad["default_sector"] = (strtolower($value[$prefix_table . "default_sector"]) == 'a' ? '' : $value[$prefix_table . "default_sector"]);
  1275. /*
  1276. //-- $ad["default_sector"] should not be displayed if $ad["default_town"]==$ad["default_sector"]
  1277. //-- 20080820-XI
  1278. if (!empty($ad["default_town"]) && !empty($ad["default_sector"]))
  1279. {
  1280. if ($ad["default_town"] == $ad["default_sector"])
  1281. $ad["default_sector"] = "";
  1282. }
  1283. */
  1284. // ad dates
  1285. $ad["created_on"] = format_date_sql2ihm($value[$prefix_table . "first_online_date"]);
  1286. $ad["modified_on"] = format_date_sql2ihm($value[$prefix_table . "update_date"]);
  1287. $time_int = strtotime(date('Y-m-d H:i:s')) - strtotime($value[$prefix_table . "update_date"]);
  1288. $ad["days_old"] = intval($time_int / 86400);
  1289. 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") {
  1290. // ad link
  1291. if ($page == "confier_resultats.php") {
  1292. $infos = $url . $value["id_annonce"];
  1293. $ad["link"] = to_nat($infos, "confier_detail");
  1294. } else {
  1295. $infos = array(
  1296. 'id' => $value["id_annonce"],
  1297. 'type_transaction' => $ad["type_transaction"]
  1298. );
  1299. $ad["link"] = to_nat($infos, "detail");
  1300. }
  1301. // ad template
  1302. $ad["tpl_code"] = "";
  1303. $ad["tpl_name"] = "annonce";
  1304. $ad["tpl_label_type"] = "";
  1305. // Si c'est la première annonce et qu'elle est premium
  1306. if (($has_premium > 0 && $idx == 0) || $ad['premium'] > 0) {
  1307. $ad["tpl_code"] = "p";
  1308. $ad["tpl_name"] = "premium";
  1309. $ad["tpl_label_type"] = LABEL_RESULT_PREMIUM;
  1310. // Si c'est la première annonce et qu'elle est orpi
  1311. } else if ($ad['is_exclusive'] == 2) {
  1312. $ad["tpl_code"] = "o";
  1313. $ad["tpl_name"] = "orpi";
  1314. $ad["tpl_label_type"] = 'Eclusivité ORPI';
  1315. } else if($ad['type_transaction'] == 5) {
  1316. $ad["tpl_code"] = "9";
  1317. $ad["tpl_name"] = "neuf";
  1318. $ad["tpl_label_type"] = 'Neuf';
  1319. } else if( ($ad["days_old"] <= DAYS_TO_BE_NEW) && !SUPP_NOUVEAUTE){
  1320. $ad["tpl_code"] = "n";
  1321. $ad["tpl_name"] = "nouveau";
  1322. $ad["tpl_label_type"] = LABEL_RESULT_NEW_AD;
  1323. }
  1324. }
  1325. // ad pub
  1326. $ad["antenna"] = str_pad(get_pub_data($value[$prefix_table . "pub_code"], "area1"), 3, "0", STR_PAD_LEFT);
  1327. // ad origin import + origin import id
  1328. $ad["origin_import"] = $value[$prefix_table . "origin_import"];
  1329. $ad["origin_import_id"] = $value[$prefix_table . "origin_import_id"];
  1330. //ad disctrict
  1331. if (is_in_district_area($ad) && (!DISABLE_DISTRICT)) {
  1332. for ($i = 1; $i <= 3; $i++) {
  1333. $ad["district_id_" . $i] = $value[$prefix_table . "district_id" . $i];
  1334. $ad["district_name_" . $i] = $value[$prefix_table . "district_name" . $i];
  1335. if ($page == 'detail.php' && isset($ad["district_id_" . $i]) && (0 != $ad["district_id_" . $i]) ) {
  1336. $ad["district_polygone_" . $i] = getPolygoneByDistrictId($ad["district_id_" . $i]);
  1337. }
  1338. }
  1339. $str_quartiers = (!empty($ad["district_name_1"])) ? $ad["district_name_1"] : "";
  1340. $str_quartiers .= (!empty($ad["district_name_2"])) ? "/" . $ad["district_name_2"] : "";
  1341. $str_quartiers .= (!empty($ad["district_name_3"])) ? "/" . $ad["district_name_3"] : "";
  1342. $districts = explode('/', $str_quartiers);
  1343. foreach ($districts as $k => $v) {
  1344. $districts[$k] = ucfirst($v);
  1345. }
  1346. $ad['district_to_use'] = implode($districts, '/');
  1347. }
  1348. $ad['is_phonemandatory4contact'] = $value[$prefix_table . '_is_phonemandatory4contact'];
  1349. // Bandeau personnalisable
  1350. if ( isset($value[$prefix_table . 'personnalisable']) && !empty($value[$prefix_table . 'personnalisable']) && (0 != $value[$prefix_table . 'personnalisable']) ) {
  1351. $ad['libelle_bandeau'] = mb_strtoupper(getLibellePersonnalisable($value[$prefix_table . 'personnalisable']),'UTF-8');
  1352. //$ad['libelle_bandeau'] = mb_strtoupper($_LI_BANDEAU_PERSO_FR[$value[$prefix_table . '_personnalisable']], 'UTF-8');
  1353. }
  1354. // agency data
  1355. $ag["id"] = $value["id_agence"];
  1356. $ag["id_presto"] = $value["id_presto"];
  1357. $ag["name"] = trim($value[$prefix_table . "name_agency"]);
  1358. //-- Set 'AGENCE' + name of the agency if id_type_agence = 1, 2 or 3
  1359. 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)) {
  1360. $ag["name"] = strtoupper(LABEL_COMMON_AGENCY) . " " . $ag["name"];
  1361. } elseif (strtoupper(substr($ag["name"], 0, strlen(LABEL_COMMON_CONSTRUCT))) != strtoupper(LABEL_COMMON_CONSTRUCT) && $value["id_type_agence"] == 5) {
  1362. $ag["name"] = strtoupper(LABEL_COMMON_CONSTRUCT) . " " . $ag["name"];
  1363. } elseif (strtoupper(substr($ag["name"], 0, strlen(LABEL_COMMON_PROMOT))) != strtoupper(LABEL_COMMON_PROMOT) && $value["id_type_agence"] == 4) {
  1364. $ag["name"] = strtoupper(LABEL_COMMON_PROMOT) . " " . $ag["name"];
  1365. } elseif (strtoupper(substr($ag["name"], 0, strlen(LABEL_COMMON_PUB_AGENCY))) != strtoupper(LABEL_COMMON_PUB_AGENCY) && $value["id_type_agence"] == 9) {
  1366. $ag["name"] = strtoupper(LABEL_COMMON_PUB_AGENCY) . " " . $ag["name"];
  1367. }
  1368. // W.asbaiti 09/02/11 ajout ORPI au debut du nom de l'agence si c'est une annonce exlusive
  1369. if ($is_exclusive) {
  1370. if (stripos($ag["name"], 'orpi') === false)
  1371. $ag["name"] = 'ORPI ' . $ag["name"];
  1372. }
  1373. $ag["address"] = $value[$prefix_table . "address_agency"];
  1374. $ag["lzip"] = $value[$prefix_table . "post_code_agency"];
  1375. $ag["town"] = $value[$prefix_table . "town_agency"];
  1376. $ag["country"] = $value[$prefix_table . "country_agency"];
  1377. $ag["tel"] = format_phone($value[$prefix_table . "tel_agency"], $ag["country"]);
  1378. // 20090410-1-XI, Retrieving xxx_tel2_agency
  1379. //if (!empty($value[$prefix_table."_tel2_agency"]))
  1380. // $ag["tel"] .= " - ".format_phone($value[$prefix_table."_tel2_agency"], $ag["country"]);
  1381. $ag["fax"] = format_phone($value[$prefix_table . "fax_agency"], $ag["country"]);
  1382. $ag["email"] = $value[$prefix_table . "email_agency"];
  1383. $website = $value[$prefix_table . "site_agency"];
  1384. if (checkWebsite($website)) {
  1385. $ag["site"] = $website;
  1386. $ag["site_desc"] = str_limit($ag["site"], 32);
  1387. } else {
  1388. $value[$prefix_table . "is_website_agency"] = 0;
  1389. $ag["site"] = '';
  1390. $ag["site_desc"] = '';
  1391. }
  1392. $ag["rcs"] = $value[$prefix_table . "rcs_agency"];
  1393. $ag["rcs"] = ($ag["rcs"] == "" ? LABEL_COMMON_RCS_UNKNOWN : $ag["rcs"]);
  1394. $ag["logo"] = $value[$prefix_table . "logo_agency"];
  1395. $ag['is_exclusive'] = $is_exclusive;
  1396. if ($is_exclusive && CURRENT_EXCLUSIVE_IMG != '') {
  1397. $ag["logo"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO . '.png';
  1398. $ag["logo_small"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO_SMALL . '.png';
  1399. $ag["logo_thumb"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO_THUMB . '.png';
  1400. } else {
  1401. $ag["logo"] = $value[$prefix_table . "logo_agency"];
  1402. // checks if logo_agency is properly filled
  1403. $chk_ag_logo = explode(".", $ag["logo"]);
  1404. $ag["logo"] = ($chk_ag_logo[1] != "" ? $ag["logo"] : "");
  1405. if ($ag["logo"] != "") {
  1406. $ag["logo_small"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO_SMALL . '_' . $ag["logo"], $ag['id'], 'logo');
  1407. $ag["logo_thumb"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO_THUMB . '_' . $ag["logo"], $ag['id'], 'logo');
  1408. $ag["logo"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO . '_' . $ag["logo"], $ag['id'], 'logo');
  1409. } else {
  1410. $ag["logo_small"] = "";
  1411. $ag["logo"] = "";
  1412. }
  1413. }
  1414. $ag["franchising_agency"] = strtoupper(str_replace(" ", "", $value[$prefix_table . "franchising_agency"]));
  1415. $ag["spoken_language"] = $value[$prefix_table . "spoken_language_agency"];
  1416. // POWERSITE
  1417. $ag["is_powersite"] = $value[$prefix_table . "is_powersite_agency"];
  1418. $ag["powersite_url"] = $value[$prefix_table . "powersite_url_agency"];
  1419. $ag['is_phone_required'] = $value[$prefix_table . "powersite_calltracking_agency"];
  1420. // Modif WALID.ASBAITI 25/01/10
  1421. // Annulation temporaire de Polco
  1422. if (ACTIV_POLCO == 1) {
  1423. $ag["is_logo_agency"] = $value[$prefix_table . "is_logo_agency"];
  1424. $ag["is_directory_agency"] = $value[$prefix_table . "is_directory_agency"];
  1425. $ag["is_website_agency"] = $value[$prefix_table . "is_website_agency"];
  1426. } else {
  1427. $ag["is_logo_agency"] = 1;
  1428. $ag["is_directory_agency"] = 1;
  1429. $ag["is_website_agency"] = 1;
  1430. }
  1431. $ag["is_website"] = $ag["is_website_agency"];
  1432. if ($ad['type_transaction'] == '5') {
  1433. $s_seo = '';
  1434. if (!empty($ad['prg_title'])) {
  1435. $s_seo .= $ad['prg_title'];
  1436. }
  1437. if (!empty($ad['property_type'])) {
  1438. if ($s_seo != '') {
  1439. $s_seo .= ' - ';
  1440. }
  1441. $s_seo .= $ad['property_type'];
  1442. }
  1443. if (!empty($ad['nb_rooms'])) {
  1444. if ($ad["nb_rooms"] == 1) {
  1445. $s_piece = LABEL_COMMON_ROOM_UNIT;
  1446. } else {
  1447. $s_piece = LABEL_COMMON_ROOMS_UNIT;
  1448. }
  1449. if ($s_seo != '') {
  1450. $s_seo .= ' - ';
  1451. }
  1452. $s_seo .= $ad['nb_rooms'] . ' ' . $s_piece;
  1453. }
  1454. if (!empty($ad['area'])) {
  1455. if ($s_seo != '') {
  1456. $s_seo .= ' - ';
  1457. }
  1458. $s_seo .= $ad['area'] . LABEL_COMMON_AREA_UNIT . " " . LABEL_RESULTS_ABOUT;
  1459. }
  1460. if (!empty($ad['prg_title']) || !empty($ad['area']) || !empty($ad['nb_rooms'])) {
  1461. if ($s_seo != '') {
  1462. $s_seo .= ' - ';
  1463. }
  1464. }
  1465. $ad['seo'] = $s_seo;
  1466. }
  1467. // debug
  1468. if ($_global["debug"] == 1) {
  1469. print_r($ad);
  1470. echo("<hr>");
  1471. }
  1472. // return
  1473. return array($ad, $ag);
  1474. }
  1475. function checkWebsite(&$website) {
  1476. // Tester http ou https
  1477. $website = str_replace(' ', '%20', $website);
  1478. if (substr($website, 0, 4) != 'http')
  1479. $website = 'http://' . $website;
  1480. /*
  1481. $regexp =
  1482. '^(?#Protocol)(?:https?\:\/\/)?'.
  1483. '(?:'.
  1484. '(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))'.
  1485. '|'.
  1486. '(?#IpDomain)(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'.
  1487. ')'.
  1488. '(?#Port)(?::[\d]{1,5})?'.
  1489. '(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?'.
  1490. '(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*'.
  1491. '(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$';
  1492. */
  1493. $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})*)?$';
  1494. return preg_match('`' . $regexp . '`', $website) > 0;
  1495. }
  1496. /**
  1497. * Returns agency data
  1498. *
  1499. * @param unknown_type $page
  1500. * @param unknown_type $value
  1501. * @return unknown
  1502. */
  1503. function get_ag_data($page, $value) {
  1504. global $_global;
  1505. // echo "<pre>";print_r($value);echo "</pre>";
  1506. // arrays
  1507. $ag = array();
  1508. // agency identifiers
  1509. $ag["id"] = $value["id_agence"];
  1510. $ag["id_presto"] = $value["id_presto"];
  1511. $ag["real_rcs"] = $value["agc_rcs"];
  1512. $ag["rcs"] = ($ag["real_rcs"] == "" ? LABEL_COMMON_RCS_UNKNOWN : $ag["real_rcs"]);
  1513. // agency data
  1514. $ag["company_name"] = $value["agc_company_name"];
  1515. $ag["name"] = $value["agc_name"];
  1516. $ag["franchising"] = $value["agc_franchising"];
  1517. /*
  1518. * W.ASBAITI 14/12/2012 : Si la desc est vide, on remplace par un texte friendly SEO
  1519. */
  1520. if(empty($value["agc_description"])) {
  1521. $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.";
  1522. }else {
  1523. $ag["description"] = $value["agc_description"];
  1524. }
  1525. // agency premium
  1526. $ag["premium"] = $value["agc_is_premium"];
  1527. // agc_franchising_order est à 1 si pack exclu (cf search_class)
  1528. $ag["is_exclusive"] = (bool) $value["agc_franchising_order"];
  1529. if ($ag["is_exclusive"] && CURRENT_EXCLUSIVE_IMG != '') {
  1530. $ag["logo"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO . '.png';
  1531. $ag["logo_thumb"] = CURRENT_EXCLUSIVE_IMG . '_' . MMF_FORMAT_AGC_LOGO_THUMB . '.png';
  1532. } else {
  1533. // agency pictures
  1534. $ag["logo"] = $value["agc_logo"];
  1535. // new
  1536. if ($ag["logo"] != "") {
  1537. $ag["logo_thumb"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO_THUMB . '_' . $ag["logo"], $ag['id'], 'logo');
  1538. $ag["logo"] = get_urlmmf_agc(MMF_FORMAT_AGC_LOGO . '_' . $ag["logo"], $ag['id'], 'logo');
  1539. } else {
  1540. $ag["logo_thumb"] = "";
  1541. $ag["logo"] = "";
  1542. }
  1543. }
  1544. // ad hierarchy
  1545. $ag["hierarchy"] = array();
  1546. for ($i = 0; $i < 3; $i++) {
  1547. $ag["hierarchy"][] = array("lct_id" => $value["agc_loc_id_" . $i], "lct_name" => $value["agc_town_agency_" . $i]);
  1548. }
  1549. // agency localisation
  1550. $ag["town_agency"] = $value["agc_town_agency"];
  1551. $ag["town"] = $ag["town_agency"];
  1552. for ($i = 4; $i >= 0; $i--) {
  1553. if ($value["agc_town_agency_" . $i] != "") {
  1554. $ag["town_agency"] = $value["agc_town_agency_" . $i];
  1555. $ag["lct_id"] = $value["agc_loc_id_" . $i];
  1556. $ag["lct_level"] = $i;
  1557. break;
  1558. }
  1559. }
  1560. $ag["lgc_id"] = $value["lgc_id"];
  1561. $ag["lgn_id"] = $value["lgn_id"];
  1562. $ag["address"] = $value["agc_address"];
  1563. $ag["lzip"] = $value["agc_post_code"];
  1564. $ag["szip"] = substr($ag["lzip"], 0, 2);
  1565. $ag["country"] = $value["agc_country"];
  1566. // agency contact
  1567. $ag["tel"] = format_phone($value["agc_tel"]);
  1568. $ag["tel_2"] = (!empty($value["agc_tel_2"])) ? format_phone($value["agc_tel_2"]) : "";
  1569. $ag["fax"] = format_phone($value["agc_fax"]);
  1570. $ag["email"] = $value["agc_email"];
  1571. $website = strtolower($value["agc_site"]);
  1572. if (checkWebsite($website)) {
  1573. $ag["site"] = $website;
  1574. } else {
  1575. $value[$prefix_table . "_is_website_agency"] = 0;
  1576. $ag["site"] = '';
  1577. }
  1578. // agency counts
  1579. $ag["rnt_count"] = $value["agc_rnt_count"];
  1580. $ag["sal_count"] = $value["agc_sal_count"];
  1581. $ag["count"] = $value["agc_count"];
  1582. // POWERSITE
  1583. $ag["is_powersite"] = $value["agc_is_powersite"];
  1584. $ag["powersite_url"] = $value["agc_powersite_url"];
  1585. $ag["powersite_calltracking"] = $value["agc_powersite_calltracking"];
  1586. // PROJET POLCO (W.ASBAITI 14/01/10)
  1587. if (ACTIV_POLCO == 1) {
  1588. $ag["is_logo"] = $value["agc_is_logo"];
  1589. $ag["is_directory"] = $value["agc_is_directory"];
  1590. $ag["is_website"] = $value["agc_is_website"];
  1591. } else {
  1592. // ANNulation temporaire Polco
  1593. // Walid ASBAITI 25/01/10
  1594. $ag["is_logo"] = 1;
  1595. $ag["is_directory"] = 1;
  1596. $ag["is_website"] = 1;
  1597. }
  1598. // W.asbaiti 09/02/11 ajout ORPI au debut du nom de l'agence si c'est une annonce exlusive
  1599. if ($ag["is_exclusive"]) {
  1600. if (stripos($ag["name"], 'orpi') === false)
  1601. $ag["name"] = 'ORPI ' . $ag["name"];
  1602. }
  1603. $ag['is_phonemandatory4contact'] = $value['agc_is_phonemandatory4contact'];
  1604. return $ag;
  1605. }
  1606. /**
  1607. * Returns image server
  1608. *
  1609. * @param unknown_type $id
  1610. * @param unknown_type $key
  1611. * @return unknown
  1612. */
  1613. function get_image_server($id, $key) {
  1614. // script url
  1615. $url = "getimage.php?v5=1&";
  1616. // key
  1617. switch ($key) {
  1618. // ad
  1619. case "AD" :
  1620. $url .= "path=thumb&wm=440&hm=330&type=prop&id=";
  1621. break;
  1622. case "AD_MULTIBOX" :
  1623. $url .= "path=thumb&wm=800&hm=600&type=prop&id=";
  1624. break;
  1625. case "AD_THUMB" :
  1626. $url .= "path=thumb&wm=182&hm=136&type=prop&id=";
  1627. break;
  1628. case "AD_THUMB_DETAIL" :
  1629. $url .= "path=thumb&wm=69&hm=53&type=crop&id=";
  1630. break;
  1631. // agency
  1632. case "AG" :
  1633. $url .= "db=presto&path=logo_agence_thumb&type=prop&wm=260&hm=160&id=";
  1634. break;
  1635. case "AG_SMALL" :
  1636. $url .= "db=presto&path=logo_agence_thumb&type=prop&wm=60&hm=40&id=";
  1637. break;
  1638. case "AG_THUMB" :
  1639. $url .= "db=presto&path=logo_agence_thumb&type=prop&wm=137&hm=105&id=";
  1640. break;
  1641. case "HOME_GALLERY" :
  1642. $url .= "v5=1&path=thumb&wm=216&hm=161&type=crop&id=";
  1643. }
  1644. // return "http://images.logic-immo.com/".$url.$id;
  1645. return "http://image" . (floor(hexdec(substr($id, 0, 3)) / 1024) + 2) . ".logic-immo.com/" . $url . $id;
  1646. }
  1647. /**
  1648. * Returns pub data
  1649. *
  1650. * @param unknown_type $value
  1651. * @param unknown_type $key
  1652. * @return unknown
  1653. */
  1654. function get_pub_data($value, $key) {
  1655. if ($value != "") {
  1656. $value = explode(";", $value);
  1657. for ($i = 0; $i < count($value); $i++) {
  1658. $data = explode(":", $value[$i]);
  1659. if ($data[0] == $key) {
  1660. return $data[1];
  1661. }
  1662. }
  1663. }
  1664. }
  1665. /**
  1666. * Returns mmf type index
  1667. *
  1668. * @param unknown_type $label
  1669. * @return unknown
  1670. */
  1671. function get_mmf_type($label) {
  1672. for ($i = 1; $i < 6; $i++) {
  1673. if (constant("AD_MMF_TYPE_" . $i) == $label) {
  1674. return $i;
  1675. }
  1676. }
  1677. }
  1678. /**
  1679. * Returns formatted number
  1680. *
  1681. * @param unknown_type $value
  1682. * @param unknown_type $country
  1683. * @return unknown
  1684. */
  1685. function format_phone($value, $country = "FR") {
  1686. if ($value == "") {
  1687. return;
  1688. }
  1689. if (empty($country))
  1690. $country = 'FR';
  1691. switch ($country) {
  1692. case "FR" :
  1693. $value = preg_replace("/[^0-9]/", "", $value);
  1694. if (strlen($value) > 10) {
  1695. $value = substr($value, -11);
  1696. $value = preg_replace("/^3[30]/", "0", $value);
  1697. }
  1698. $value = preg_replace("/(..)(..)(..)(..)(..)$/", "$1 $2 $3 $4 $5", $value);
  1699. break;
  1700. }
  1701. return $value;
  1702. }
  1703. /**
  1704. * Returns parameter index
  1705. *
  1706. * @param unknown_type $name
  1707. * @param unknown_type $value
  1708. * @return unknown
  1709. */
  1710. function get_parameter_index($name, $value) {
  1711. global $_LI_ADSURFACE;
  1712. global $_LI_PRICERANGE;
  1713. switch ($name) {
  1714. case "area" :
  1715. $values = $_LI_ADSURFACE;
  1716. break;
  1717. case "price" :
  1718. $values = $_LI_PRICERANGE;
  1719. break;
  1720. }
  1721. for ($i = 0; $i < count($values); $i++) {
  1722. if ($value >= $values[$i]["from"] && $value <= $values[$i]["to"]) {
  1723. return $i;
  1724. }
  1725. }
  1726. }
  1727. /**
  1728. * Returns true if value is a guid
  1729. *
  1730. * @param unknown_type $value
  1731. * @return unknown
  1732. */
  1733. function is_guid($value) {
  1734. $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}$";
  1735. if (ereg($pattern, $value)) {
  1736. return true;
  1737. } else {
  1738. return false;
  1739. }
  1740. }
  1741. function check_email($email) {
  1742. // Différentes parties de l'email avant l'arobase
  1743. $atomChars = '[-a-z0-9àáâãäåæçèéêëìíîïñòóôõöœùúûüýÿß!#$%&\'*+\\/=?^_\`{|}~]';
  1744. // Caractères autorisés après l'arobase (nom de domaine)
  1745. $domainChars = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
  1746. // Expression régulière finale pour l'email complet
  1747. $regexp = '`^' . $atomChars . '+(?:\.' . $atomChars . '+)*@(' . $domainChars . '{1,63}\.)+' . $domainChars . '{2,63}$`i';
  1748. $email = strtolower($email);
  1749. return preg_match($regexp, $email);
  1750. }
  1751. /**
  1752. * Returns "back to list" url
  1753. *
  1754. * @param unknown_type $page
  1755. * @return unknown
  1756. */
  1757. function back_to_list($page, $is_agency = false) {
  1758. global $_global;
  1759. $back_to_list = "";
  1760. switch ($page) {
  1761. case "resultats.php":
  1762. global $aLISearchHistoryCookieValue;
  1763. // has a previous search been stored ?
  1764. if ($_global["saved_searches"] > 0) {
  1765. // retrieves last search parameters
  1766. $back_to_list = build_search_url($page, $aLISearchHistoryCookieValue[0]);
  1767. }
  1768. break;
  1769. }
  1770. return $back_to_list;
  1771. }
  1772. /**
  1773. * Returns a search url
  1774. *
  1775. * @param unknown_type $page
  1776. * @param unknown_type $parameters
  1777. * @return unknown
  1778. */
  1779. function build_search_url($page, $parameters) {
  1780. global $_global;
  1781. //$mode = ($page == "resultats_agence_annonces.php" ? "recherche_agence_annonce" : "recherche");
  1782. if ($page == "resultats_agence_annonces.php" || $page == "resultats_agence_annonces_cz.php") {
  1783. $mode = "recherche_agence_annonce";
  1784. } else {
  1785. $mode = "recherche";
  1786. }
  1787. $url_parameters = array();
  1788. // loc_name
  1789. $url_parameters["loc_name"] = $parameters["loc_name"];
  1790. // loc_keys
  1791. $loc_key_ok = false;
  1792. if ($parameters["loc_key"] != "") {
  1793. $loc_key_ok = true;
  1794. $url_parameters["loc_key"] = $parameters["loc_key"];
  1795. } else {
  1796. for ($i = 1; $i <= SEARCH_FIELDS_NUMBER; $i++) {
  1797. if (!empty($parameters["loc_key" . $i])) {
  1798. $loc_key_ok = true;
  1799. $url_parameters["loc_key" . $i] = $parameters["loc_key" . $i];
  1800. $url_parameters["loc_name" . $i] = $parameters["loc_name" . $i];
  1801. }
  1802. }
  1803. }
  1804. // Si pas de loc_key, on retourne vide car l'url sera de toute facon invalide
  1805. if (!$loc_key_ok)
  1806. return '';
  1807. // property type
  1808. $url_parameters["ck_property_type"] = $parameters["ck_property_type"];
  1809. // price
  1810. $url_parameters["price"] = $parameters["price"];
  1811. // patch cz
  1812. $url_parameters["price_min"] = $parameters["price_min"];
  1813. $url_parameters["price_max"] = $parameters["price_max"];
  1814. // area
  1815. $url_parameters["area"] = $parameters["area"];
  1816. $url_parameters["area_min"] = $parameters["area_min"];
  1817. $url_parameters["area_max"] = $parameters["area_max"];
  1818. // nb_rooms
  1819. /*
  1820. $url_parameters["nb_rooms"] = $parameters["nb_rooms"];
  1821. $url_parameters["nb_rooms_min"] = $parameters["nb_rooms_min"];
  1822. $url_parameters["nb_rooms_max"] = $parameters["nb_rooms_max"];
  1823. */
  1824. $url_parameters["ck_nb_rooms"] = $parameters["ck_nb_rooms"];
  1825. // offset
  1826. if (isset($_REQUEST['p'])) {
  1827. $num_row = (int) substr($_REQUEST['p'], 1);
  1828. $url_parameters["offset"] = floor($num_row / MAX_RESULTS_PER_PAGE) + 1;
  1829. }
  1830. else
  1831. $url_parameters["offset"] = $parameters["offset"];
  1832. // order
  1833. $url_parameters["order"] = $parameters["order"];
  1834. // annonce visuel
  1835. $url_parameters["an_visuel"] = $parameters["an_visuel"];
  1836. /* START: RECHERCHE AVANCEE */
  1837. /*
  1838. // Avec photo, vidéo ou visite virtuelle
  1839. $url_parameters["with_mmf"] = $parameters["with_mmf"];
  1840. // Uniquement les nouveautés de moins de 2 semaines
  1841. $url_parameters["recent_ads"] = $parameters["recent_ads"];
  1842. // surface du terrain
  1843. $url_parameters["surf"] = $parameters["surf"];
  1844. $url_parameters["surf_min"] = $parameters["surf_min"];
  1845. $url_parameters["surf_max"] = $parameters["surf_max"];
  1846. // etage
  1847. $url_parameters["floor"] = $parameters["floor"];
  1848. $url_parameters["floor_min"] = $parameters["floor_min"];
  1849. $url_parameters["floor_max"] = $parameters["floor_max"];
  1850. // ascenseur
  1851. $url_parameters["elevator"] = $parameters["elevator"];
  1852. // gardien
  1853. $url_parameters["caretaker"] = $parameters["caretaker"];
  1854. // interphone
  1855. $url_parameters["interphone"] = $parameters["interphone"];
  1856. // balcon
  1857. $url_parameters["balcony"] = $parameters["balcony"];
  1858. // terrasse
  1859. $url_parameters["terrace"] = $parameters["terrace"];
  1860. // parquet
  1861. $url_parameters["parquet"] = $parameters["parquet"];
  1862. // cheminée
  1863. $url_parameters["fireside"] = $parameters["fireside"];
  1864. //placards
  1865. $url_parameters["closets"] = $parameters["closets"];
  1866. //cave
  1867. $url_parameters["storage"] = $parameters["storage"];
  1868. //parking
  1869. $url_parameters["parking"] = $parameters["parking"];
  1870. //garden
  1871. $url_parameters["garden"] = $parameters["garden"];
  1872. //pool
  1873. $url_parameters["pool"] = $parameters["pool"];
  1874. */
  1875. /* STOP: RECHERCHE AVANCEE */
  1876. // id agence
  1877. if ($page == "resultats_agence_annonces.php") {
  1878. $url_parameters["id_agence"] = $parameters["id_agence"];
  1879. }
  1880. if ($mode == "recherche_agence_annonce") {
  1881. $url = add_parameters($page . "?" . http_build_query($url_parameters));
  1882. } else {
  1883. $url = to_nat(add_parameters($page . "?" . http_build_query($url_parameters)), $mode);
  1884. //$url = to_nat(add_parameters($page."?".http_build_query($url_parameters)));
  1885. }
  1886. return $url;
  1887. }
  1888. /**
  1889. * Returns true if page comes from Mars
  1890. *
  1891. * @param unknown_type $previous_url
  1892. * @param unknown_type $page
  1893. * @return unknown
  1894. */
  1895. function from_page($previous_url, $page) {
  1896. if (strpos($_SERVER["HTTP_REFERER"], $_global["dns"]) && strpos($_SERVER["HTTP_REFERER"], $page)) {
  1897. return true;
  1898. } else {
  1899. return false;
  1900. }
  1901. }
  1902. /**
  1903. * Returns true if is external
  1904. *
  1905. * @return unknown
  1906. */
  1907. function is_external($check_referer = true) {
  1908. global $_REQUEST;
  1909. global $_global;
  1910. if ($check_referer) {
  1911. $is_external_referer = (
  1912. empty($_SERVER["HTTP_REFERER"]) // Page de provenance inexistant (non précisée ou accès direct à l'url)
  1913. || strpos($_SERVER["HTTP_REFERER"], $_global["dns"]) === false // Page de provenance n'appartient pas au site
  1914. );
  1915. }
  1916. else
  1917. $is_external_referer = false;
  1918. return (
  1919. isset($_REQUEST["logicode"]) && $_REQUEST["logicode"] == 1 // Recherche par logicode
  1920. || isset($_REQUEST["gallery"]) && $_REQUEST["gallery"] == 1 // Lien de la gallerie
  1921. || isset($_REQUEST["ext"]) && $_REQUEST["ext"] == 1 // ?
  1922. || $is_external_referer
  1923. );
  1924. }
  1925. /**
  1926. * Returns true if is external
  1927. *
  1928. * @return unknown
  1929. */
  1930. function previous_page() {
  1931. $subject = substr($_SERVER["HTTP_REFERER"], strlen($_global["dns"]));
  1932. //resultats_agence_annonces.php
  1933. $new_pattern_result_agc = 'agence-immobiliere/([^/]+)/annonces-(.*)';
  1934. //resultats.php
  1935. $new_pattern_result = '((vente|location|colocation)-immobilier)|(recherche-colocation)-(.*)';
  1936. //detail.php
  1937. $pattern_detail = 'detail-([a-z]*)-([-a-zA-Z0-9]*)';
  1938. if (!$subject) {
  1939. return;
  1940. } else {
  1941. if (preg_match("`" . $new_pattern_result . "`", $subject, $matches)) {
  1942. return "resultats.php";
  1943. } else if (preg_match("`" . $new_pattern_result_agc . "`", $subject, $matches)) {
  1944. /* setcookie("id_exist", true); */
  1945. return "resultats_agence_annonces.php";
  1946. } else if (preg_match("`" . $pattern_detail . "`", $subject, $matches)) {
  1947. return "detail.php";
  1948. } else {
  1949. return;
  1950. }
  1951. }
  1952. }
  1953. /**
  1954. * Returns true if is a ref page
  1955. *
  1956. * @param unknown_type $page
  1957. * @return unknown
  1958. */
  1959. function is_ref_page($page) {
  1960. $pages = array();
  1961. $pages[] = "annonce_dep.php";
  1962. $pages[] = "annonce_ville.php";
  1963. $pages[] = "annonce-ville.php";
  1964. $pages[] = "annonce_location.php";
  1965. $pages[] = "annonce-location.php";
  1966. $pages[] = "annonce-region.php";
  1967. $pages[] = "ref_ann.php";
  1968. $pages[] = "ref_dep.php";
  1969. $pages[] = "ref_liste_ann.php";
  1970. $pages[] = "ref_ville.php";
  1971. $pages[] = "ref_bien_liste.php";
  1972. $pages[] = "ref_bien_detail.php";
  1973. $pages[] = "rss_ville.php";
  1974. $pages[] = "top-immobilier.php";
  1975. return in_array($page, $pages);
  1976. }
  1977. /**
  1978. * Returns szip / lzip
  1979. *
  1980. * @param unknown_type $data
  1981. * @param unknown_type $mode
  1982. * @return unknown
  1983. */
  1984. function get_zip_code($data, $mode) {
  1985. $values = explode(",", $data[$mode][0]);
  1986. return trim($values[0]);
  1987. }
  1988. /**
  1989. * Enter description here...
  1990. *
  1991. * @param unknown_type $sLockFileName
  1992. * @param unknown_type $sLockFileDescription
  1993. */
  1994. function writeLockFile($sLockFileName, $sLockFileDescription) {
  1995. error_log(date("d/m/Y H:i:s") . " - {$sLockFileDescription}\n", 3, "../LOCK/{$sLockFileName}.lockfile");
  1996. }
  1997. /**
  1998. * Enter description here...
  1999. *
  2000. * @param unknown_type $sLockFileName
  2001. */
  2002. function getLockFile($sLockFileName) {
  2003. }
  2004. /**
  2005. * Enter description here...
  2006. *
  2007. * @param unknown_type $sLockFileName
  2008. * @return unknown
  2009. */
  2010. function checkLockFile($sLockFileName) {
  2011. if (file_exists("../LOCK/{$sLockFileName}.lockfile") == true) {
  2012. return true;
  2013. } else {
  2014. return false;
  2015. }
  2016. }
  2017. /**
  2018. * Enter description here...
  2019. *
  2020. * @param unknown_type $sLockFileName
  2021. */
  2022. function removeLockFile($sLockFileName) {
  2023. unlink("../LOCK/{$sLockFileName}.lockfile");
  2024. }
  2025. /**
  2026. * Enter description here...
  2027. *
  2028. * @param unknown_type $chaine
  2029. * @param unknown_type $length
  2030. * @return unknown
  2031. */
  2032. function truncate($chaine, $length = 50) {
  2033. $return_chaine = "";
  2034. $truncate = false;
  2035. $array = preg_split("/([ .,;:!])/", $chaine, -1, PREG_SPLIT_OFFSET_CAPTURE);
  2036. foreach ($array as $elt) {
  2037. $chaine_ar[] = $elt[0];
  2038. $ponctuations[] = substr($chaine, $elt[1] - 1, 1);
  2039. }
  2040. $return_chaine = $chaine_ar[0];
  2041. for ($i = 1; $i < count($chaine_ar); $i++) {
  2042. $element = $chaine_ar[$i];
  2043. if (strlen($return_chaine . " " . $element) < $length) {
  2044. $return_chaine .= $ponctuations[$i] . $element;
  2045. } else {
  2046. $truncate = true;
  2047. }
  2048. }
  2049. if ($truncate) {
  2050. $return_chaine .= "...";
  2051. }
  2052. $return_chaine = preg_replace("/([ .\,;:!]+?\.\.\.)$/x", "...", $return_chaine);
  2053. return $return_chaine;
  2054. }
  2055. /**
  2056. * Tronque un texte (mais pas les mots !) si trop long et rajoute des points de suspension
  2057. *
  2058. * @param unknown_type $text
  2059. * @param unknown_type $ncar
  2060. * @param unknown_type $scar
  2061. * @return unknown
  2062. */
  2063. function truncate2($text, $ncar, $scar = "") {
  2064. $trunc_text = $text;
  2065. if (strlen($text) > $ncar) {
  2066. $maxi_text = substr($text, 0, $ncar);
  2067. $lpos = strrpos($maxi_text, ",");
  2068. if ($lpos === FALSE) {
  2069. $lpos = strrpos($maxi_text, " ");
  2070. }
  2071. if ($lpos == FALSE) {
  2072. $maxi_text = substr($maxi_text, 0, ($ncar - 3));
  2073. } else {
  2074. $maxi_text = substr($maxi_text, 0, $lpos);
  2075. }
  2076. $trunc_text = $maxi_text;
  2077. if ($scar != "") {
  2078. $trunc_text = $trunc_text . $scar;
  2079. }
  2080. }
  2081. return $trunc_text;
  2082. }
  2083. function truncate_article($text, $ncar) {
  2084. $trunc_text = strip_tags(stripslashes(htmlspecialchars_decode(ucfirst($text))));
  2085. if (strlen($trunc_text) > $ncar) {
  2086. $trunc_text = substr($trunc_text, 0, $ncar);
  2087. $lpos = strrpos($trunc_text, " ");
  2088. $trunc_text = substr($trunc_text, 0, $lpos);
  2089. }
  2090. $trunc_text .= "...";
  2091. return $trunc_text;
  2092. }
  2093. /**
  2094. * Enter description here...
  2095. *
  2096. * @param unknown_type $k1
  2097. * @param unknown_type $n1
  2098. * @param unknown_type $k2
  2099. * @param unknown_type $n2
  2100. * @return unknown
  2101. */
  2102. function loc2xiti($k1, $n1, $k2, $n2) {
  2103. if ($k1 != "") {
  2104. $a1 = explode('_', $k1);
  2105. $a2 = explode("(", $n1);
  2106. if ($a1[1] == 0) {
  2107. $s1 = $a2[0];
  2108. } else {
  2109. $s1 = str_replace(')', '', str_replace('(', '', $a2['1']));
  2110. }
  2111. }
  2112. unset($a1);
  2113. unset($a2);
  2114. if ($k2 != "") {
  2115. $a1 = explode('_', $k2);
  2116. $a2 = explode("(", $n2);
  2117. if ($a1[1] == 0) {
  2118. $s2 = $a2[0];
  2119. } else {
  2120. $s2 = str_replace(')', '', str_replace('(', '', $a2['1']));
  2121. }
  2122. }
  2123. if ($s1 != "" && $s2 != "") {
  2124. return "$s1,$s2";
  2125. } else {
  2126. return "$s1$s2";
  2127. }
  2128. }
  2129. /**
  2130. * Enter description here...
  2131. *
  2132. * @param unknown_type $str
  2133. * @return unknown
  2134. */
  2135. function format_footer_link($str) {
  2136. global $_global;
  2137. $replang = "";
  2138. switch ($_global["site"]) {
  2139. case "be":
  2140. $replang = $_global["lang"] . "/";
  2141. break;
  2142. default:
  2143. $replang = "";
  2144. break;
  2145. }
  2146. if (!strstr($str, "a href=\"http"))
  2147. $final = str_replace("a href=\"", "a href=\"/" . $replang, $str);
  2148. else
  2149. $final = $str;
  2150. return($final);
  2151. }
  2152. /**
  2153. * Enter description here...
  2154. *
  2155. * @param unknown_type $iOperationCode
  2156. * @param unknown_type $sPreSharedKey
  2157. */
  2158. function generateMd5MaintenanceString($iOperationCode, $sPreSharedKey) {
  2159. //Generate a SHA1 key to authentify maintenance and remote script execution.
  2160. //Get variables
  2161. $strA = date("H"); //Current hour in 24h format with leading 0's
  2162. $strA1 = (int) $strA; //Transform that string into an int w/o leading 0
  2163. $strB = date("i"); //Minute in hour with trailing 0
  2164. $strB1 = substr($strB, 0, 1); //Get ten number
  2165. $strB2 = (int) substr($strB, 1, 1); //Get unit number
  2166. $strC = date("w"); //Get day of week (0 = sunday, 6 = saturday
  2167. $strD = date("n"); //Number of the month
  2168. $strE = _FRONTSERVERID_; //Global variable defined in DB settings
  2169. $strF = $iOperationCode; //Preset operation code - an alias to the instruction to run
  2170. $strG = $sPreSharedKey; //Secret key.
  2171. //Create salt: the salt format depends on the current minute (all servers must be timesynched.
  2172. $sSalt = "";
  2173. if ($strB2 >= 0 && $strB2 < 2) {
  2174. $sSalt = $strA . $strB . $strC . $strD . $strE;
  2175. } else if ($strB2 >= 2 && $strB2 < 4) {
  2176. $sSalt = $strB . $strA . $strC . $strD . $strE;
  2177. } else if ($strB2 >= 4 && $strB2 < 6) {
  2178. $sSalt = $$strB . $strC . $strA . $strD . $strE;
  2179. } else if ($strB2 >= 6 && $strB2 < 8) {
  2180. $sSalt = $strA . $strB . $strC . $strD . $strA . $strE;
  2181. } else {
  2182. $sSalt = $strB . $strC . $strD . $strE . $strA;
  2183. }
  2184. //Create the full key. Key format depends on day of month:
  2185. if ($strD % 2 == 0) {
  2186. $sKey = md5($strF + $sSalt + $strG);
  2187. } else {
  2188. $sKey = md5($strG + $sSalt + $strF);
  2189. }
  2190. }
  2191. /**
  2192. * Enter description here...
  2193. *
  2194. * @param unknown_type $sPreSharedKey
  2195. * @param unknown_type $iOperationCode
  2196. * @param unknown_type $aOperationArray
  2197. * @param unknown_type $sKeyString
  2198. * @return unknown
  2199. */
  2200. function checkSha1MaintenanceString($sPreSharedKey, $iOperationCode, $aOperationArray, $sKeyString) {
  2201. //Generate a SHA1 key according to supplied variables and compare to the encoded key string
  2202. if (generateMd5MaintenanceString($iOperationCode, $sPreSharedKey) == $sKeyString) {
  2203. return true;
  2204. } else {
  2205. return false;
  2206. }
  2207. }
  2208. /**
  2209. * Gestion de la redirection de page
  2210. * Gére la presence des headers
  2211. * Si les headers sont déja envoyés, on utilise la balise META
  2212. *
  2213. * @param unknown_type $url
  2214. */
  2215. function redirection($url) {
  2216. if (headers_sent() || isset($GLOBALS[PHPSESSID])) {
  2217. die('<meta http-equiv="refresh" content="0;URL=' . $url . '">');
  2218. } else {
  2219. header("Location: " . $url . "\n");
  2220. //header("Location: http://".$_SERVER['HTTP_HOST']."".dirname($_SERVER['PHP_SELF'])."/".$url."\n");
  2221. exit();
  2222. }
  2223. }
  2224. /**
  2225. * Gestion de la revisite Belge (modifiable pour les autres Pays)
  2226. * Si pas de cookie on redirige sur la prehome
  2227. *
  2228. * @return unknown
  2229. */
  2230. function verif_cookie_prehome() {
  2231. global $_global;
  2232. $langisup = 0;
  2233. $_global["revisite_belge"] = 0;
  2234. if ($_global['site'] == "be") {
  2235. $uri = split("/", $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"]);
  2236. //var_dump($uri); //die();
  2237. $array_uri_langue_site = array("fr", "en", "nl");
  2238. if ($_global['site'] == "be" && in_array($uri[1], $array_uri_langue_site)) {
  2239. $langisup = 1;
  2240. }
  2241. ob_start();
  2242. $var_cook = array();
  2243. if (!isset($_COOKIE['LI_NAVSITE']) && $langisup == 0) {
  2244. redirection("http://" . $_SERVER["SERVER_NAME"] . "/prehome_be.php");
  2245. ob_end_flush();
  2246. return false;
  2247. exit();
  2248. }
  2249. $var_cook = $_COOKIE["LI_NAVSITE"];
  2250. if ($_SERVER['REQUEST_URI'] == "/") {
  2251. setcookie("LI_NAVSITE[lang_site]", '', 0, "/");
  2252. //On redirige dans la bonne langue si l'utilisateur accepte les cookies
  2253. //et donc pas les moteurs de recherche
  2254. if (setcookie("LI_NAVSITE[lang_site]", $_global['lang'], time() + (60 * 60 * 24 * 365), "/")) {
  2255. ob_end_flush();
  2256. //echo $var_cook["lang_site"];
  2257. if (strpos($_SERVER["HTTP_REFERER"], "prehome") == 0) {
  2258. //echo "REVISITE 2<hr>";
  2259. $_global["revisite_belge"] = 1;
  2260. }
  2261. redirection("http://" . $_SERVER["SERVER_NAME"] . "/" . $var_cook["lang_site"] . "/");
  2262. exit();
  2263. }
  2264. ob_end_flush();
  2265. return false;
  2266. } else {
  2267. if (setcookie("LI_NAVSITE[lang_site]", $_global['lang'], time() + (60 * 60 * 24 * 365), "/")) {
  2268. /*
  2269. print_r($_COOKIE["LI_NAVSITE[lang_site]"]);
  2270. echo "<br>COOKIE IS UPPPPPPP - ".$_global['lang']."<br>";
  2271. */
  2272. if (strpos($_SERVER["HTTP_REFERER"], "prehome") == 0) {
  2273. //echo "REVISITE<hr>";
  2274. $_global["revisite_belge"] = 1;
  2275. }
  2276. }
  2277. }
  2278. ob_end_flush();
  2279. return true;
  2280. }
  2281. }
  2282. /**
  2283. * Vérification les nombres de refresh:
  2284. * si<4 il affiche la pub_relais_neuf si non il passe
  2285. *
  2286. * @param unknown_type $val_relais
  2287. * @return unknown
  2288. */
  2289. function pub_relais_neuf_cookie($val_relais) {
  2290. $nb_relais_neuf = 0;
  2291. if (isset($_COOKIE['nb_relais_neuf'])) {
  2292. $nb_relais_neuf = $_COOKIE['nb_relais_neuf'];
  2293. $nb_relais_neuf++;
  2294. setcookie('nb_relais_neuf', $nb_relais_neuf, time() + 3600 * 12 * 24);
  2295. } else {
  2296. //unset($_COOKIE['nb_relais_neuf']);
  2297. setcookie("nb_relais_neuf", 0, time() + 3600 * 12 * 24);
  2298. }
  2299. if ($nb_relais_neuf > $val_relais) {
  2300. setcookie("nb_relais_neuf", 0, time() - 3600 * 12 * 24);
  2301. }
  2302. return ($nb_relais_neuf);
  2303. }
  2304. /**
  2305. * Fonction permettant de vérifier la syntax de l'URL pour le site BE
  2306. *
  2307. */
  2308. function Verif_Url_BE() {
  2309. //Verif du site belge afin de conserver l'arborescence /fr /nl
  2310. global $_global;
  2311. if ($_global["site"] == "be") {
  2312. $sub_url = 0;
  2313. foreach ($_global["languages"]["be"] as $value) {
  2314. //echo "VALUE LANG: ".$value;
  2315. //if (strpos($_SERVER["HTTP_REFERER"], URL_SITE_BE.$value."/")===false)
  2316. if (strpos($_SERVER["REQUEST_URI"], "/" . $value . "/") === false) {
  2317. //echo "PAS DE LANGUE URL dans ".$_SERVER["HTTP_REFERER"]." pour ".URL_SITE_BE.$value."/";
  2318. } else {
  2319. $sub_url = 1;
  2320. }
  2321. }
  2322. if ($sub_url == 0) {
  2323. header("location: " . URL_SITE_BE);
  2324. //echo "GO TO ==> ".URL_SITE_BE.' -- '.$_SERVER["HTTP_REFERER"];
  2325. }
  2326. }
  2327. }
  2328. /**
  2329. * Retrouve le Loc_key en fonction d'un name et d'un level
  2330. *
  2331. * @param unknown_type $name
  2332. * @param unknown_type $level
  2333. * @param unknown_type $site
  2334. * @param unknown_type $lang
  2335. * @return unknown
  2336. */
  2337. function Get_Lockey_By_Name_Level($name, $level = 2, $site = "xx", $lang = "xx") {
  2338. if ($site == "xx" || $lang == "xx") {
  2339. return;
  2340. }
  2341. $site = strtoupper($site);
  2342. $lang = strtolower($lang);
  2343. $name = strtoupper($name);
  2344. $sql = "SELECT lct_id FROM T_LOCALITY_LCT_" . $site . " ";
  2345. $sql .= "WHERE lct_name_" . $lang . "='" . $name . "' ";
  2346. $sql .= "AND lct_level=" . $level;
  2347. //if (function_exists("pdoquery")){ echo "FUNCTIoN EXIST"; }
  2348. $result_query = pdoquery($sql);
  2349. return ($result_query[0]["lct_id"]);
  2350. }
  2351. /**
  2352. * Retrouve la traduction d'un nom de Locname en fonction d'un LCT_ID et d'une Langue
  2353. */
  2354. function Get_Trad_Locname($lockey, $lang) {
  2355. global $_global;
  2356. $my_loc_id = trim($lockey);
  2357. if (!strpos(trim($lockey), "_") === false) {
  2358. $tab_loc_id = explode("_", trim($lockey));
  2359. $my_loc_id = $tab_loc_id[0];
  2360. }
  2361. $rew_agency_locname = "";
  2362. $sql = "SELECT lct_name_" . $lang . " as lct_name FROM T_LOCALITY_LCT_" . strtoupper($_global["site"]) . " ";
  2363. $sql .="WHERE lct_id=" . $my_loc_id . " ";
  2364. $sql .= $sql_where;
  2365. //echo $sql;
  2366. $res_agency_locname = pdoquery($sql);
  2367. return $res_agency_locname[0]["lct_name"];
  2368. }
  2369. /**
  2370. * Enter description here...
  2371. *
  2372. * @param unknown_type $locname
  2373. * @param unknown_type $lang
  2374. * @return unknown
  2375. */
  2376. function Get_Trad_Locname_byname($locname, $lang) {
  2377. global $_global;
  2378. $locname = trim($locname);
  2379. $pattern = array('/-/', '/_/');
  2380. $replace = array(' ', ' ');
  2381. $locname = preg_replace($pattern, $replace, $locname);
  2382. if (!strpos(trim($lockey), "_") === false) {
  2383. $tab_loc_id = explode("_", trim($lockey));
  2384. $locname = $tab_loc_id[0];
  2385. }
  2386. $rew_agency_locname = "";
  2387. $sql = "SELECT lct_name_" . $lang . " as lct_name FROM T_LOCALITY_LCT_" . strtoupper($_global["site"]) . " ";
  2388. $sql .="WHERE lct_name_" . $_global["lang"] . "='" . $locname . "' ";
  2389. $sql .= $sql_where;
  2390. $res_agency_locname = pdoquery($sql);
  2391. return $res_agency_locname[0]["lct_name"];
  2392. }
  2393. /**
  2394. * Retrouve le nom et le code postal d'une localité
  2395. *
  2396. * @param unknown_type $loc_id
  2397. * @param unknown_type $loc_level
  2398. * @return unknown
  2399. */
  2400. function Get_CityName_PostCode_Lockey($loc_id, $loc_level) {
  2401. global $_global;
  2402. switch ($loc_level) {
  2403. // code group
  2404. case 98 :
  2405. $sql = " SELECT '' AS name, lgc_post_code AS post_code";
  2406. $sql .= " FROM TM_LOCGC_FR";
  2407. $sql .= " WHERE lgc_id = '" . $loc_id . "'";
  2408. break;
  2409. // name group
  2410. case 99 :
  2411. $sql = " SELECT lgn_name_fr AS name, lgn_post_code AS post_code";
  2412. $sql .= " FROM TM_LOCGN_FR";
  2413. $sql .= " WHERE lgn_id = '" . $loc_id . "'";
  2414. break;
  2415. // standard
  2416. default :
  2417. $sql = " SELECT lct_name AS name, lct_post_code AS post_code";
  2418. $sql .= " FROM TM_LOC_FR";
  2419. $sql .= " WHERE lct_id = '" . $loc_id . "'";
  2420. $sql .= " AND lct_level = '" . $loc_level . "'";
  2421. break;
  2422. }
  2423. //echo $sql;
  2424. $res = pdoquery($sql);
  2425. return array($res[0]["name"], $res[0]["post_code"]);
  2426. }
  2427. /**
  2428. * Fonction créée pour gérer l'affichage du libéllé 'Informations complémentaires :' dans les annonces
  2429. * Si il n'y a pas de détail, on n'affiche pas le libéllé
  2430. *
  2431. * @param unknown_type $ad
  2432. * @return unknown
  2433. */
  2434. function check_detail_exist($ad) {
  2435. $val = true;
  2436. if (
  2437. //$ad["floor"] == "0" &&
  2438. //$ad["garden_area"] == "0" &&
  2439. //$ad["terrace_area_1"] == "0" &&
  2440. //$ad["balcony_area_1"] == "0" &&
  2441. $ad["is_pool"] == "0" &&
  2442. $ad["pool_area"] == "0" &&
  2443. //$ad["nb_garage"] == "0" &&
  2444. //$ad["nb_parking"] == "0" &&
  2445. $ad["is_parking_closed"] == "0" &&
  2446. $ad["nb_covered_parking"] == "0" &&
  2447. $ad["nb_uncovered_parking"] == "0" &&
  2448. $ad["is_renovated"] == "0" &&
  2449. //strtotime($ad["renovating_date"]) == "943916400" && //0000-00-00 00:00:00
  2450. $ad["need_renovating"] == "0" &&
  2451. $ad["nb_caretaker"] == "0" &&
  2452. $ad["is_interphone"] == "0" &&
  2453. $ad["is_doorcode"] == "0" &&
  2454. //$ad["is_elevator"] == "0" &&
  2455. //$ad["nb_bath"] == "0" &&
  2456. ($ad["nb_shower"] == "0" || $ad["nb_shower"] == '') &&
  2457. $ad["is_independant_toilet"] <> "1" &&
  2458. $ad["is_first_floor_toilet"] <> "1" &&
  2459. //$ad["is_central_heating"] == "" &&
  2460. //$ad["is_individual_heating"]== "" &&
  2461. //$ad["is_electrical_heating"]== "" &&
  2462. //$ad["is_floor_heating"] == "" &&
  2463. //$ad["is_gas_heating"] == "" &&
  2464. //$ad["is_diesel_heating"] == "" &&
  2465. $ad["is_aircon"] == "0" &&
  2466. $ad["is_chimney"] == "0" &&
  2467. //$ad["is_wooden_floor"] == "0" &&
  2468. //$ad["is_tiled_floor"] == "0" &&
  2469. $ad["is_alarm"] == "0"
  2470. //$ad["is_sunny"] == "0" &&
  2471. //$ad["is_calm"] == "0" &&
  2472. //($ad["facing"] == "0" || $ad["facing"] == "") &&
  2473. //$ad["is_handicap_access"] == "0" &&
  2474. //$ad["agency_rent_fees"] == "" &&
  2475. //$ad["is_closet"] == "0" &&
  2476. //$ad["is_basement"] == "0"
  2477. ) {
  2478. //echo "No detail exist";
  2479. $val = false;
  2480. }
  2481. return $val;
  2482. }
  2483. function check_equipment_exist($ad) {
  2484. $val = true;
  2485. if (
  2486. $ad["floor"] == "0" &&
  2487. $ad["garden_area"] == "0" &&
  2488. $ad["terrace_area_1"] == "0" &&
  2489. $ad["balcony_area_1"] == "0" &&
  2490. $ad["nb_garage"] == "0" &&
  2491. $ad["nb_parking"] == "0" &&
  2492. $ad["is_elevator"] == "0" &&
  2493. ($ad["nb_bath"] == "0" || $ad["nb_bath"] == "")
  2494. ) {
  2495. //echo "No equipment exist";
  2496. $val = false;
  2497. }
  2498. return $val;
  2499. }
  2500. function check_namely_exist($ad) {
  2501. $val = true;
  2502. if (
  2503. $ad["is_wooden_floor"] == "0" &&
  2504. $ad["is_tiled_floor"] == "0" &&
  2505. $ad["is_sunny"] == "0" &&
  2506. $ad["is_calm"] == "0" &&
  2507. ($ad["facing"] == "0" || $ad["facing"] == "") &&
  2508. $ad["is_handicap_access"] == "0" &&
  2509. $ad["is_closet"] == "0" &&
  2510. $ad["is_basement"] == "0"
  2511. ) {
  2512. //echo "No namely exist";
  2513. $val = false;
  2514. }
  2515. return $val;
  2516. }
  2517. /**
  2518. * Permet d'afficher le bloc (bleu: type moteur de recherche) mais sans le formulaire de recherche
  2519. * On peut passer un titre a placer dans le bloc en parametre
  2520. *
  2521. * @param unknown_type $title
  2522. * @param unknown_type $classeid
  2523. */
  2524. function create_block_nosearch($title = "TITLE HERE .... ", $classeid = "contactus") {
  2525. echo "<div id=\"$classeid\">";
  2526. echo " <div id=\"contactustop\"><img class=\"fr_search_top\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
  2527. echo " <div id=\"contactuscontent\"><h1>$title</h1></div>";
  2528. echo " <div id=\"contactusbottom\"><img class=\"fr_search_bottom\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
  2529. echo "</div>";
  2530. }
  2531. /**
  2532. * Create_block_nosearch en deux colonnes
  2533. *
  2534. * @param unknown_type $title
  2535. * @param unknown_type $classeid
  2536. */
  2537. function create_block_nosearch2($title = "TITLE HERE .... ", $classeid = "small_search") {
  2538. echo "<div id=\"$classeid\">";
  2539. echo " <div id=\"smallsearchtop\"><img src=\"" . get_urlmmf('/search/corner_top_left.gif') . "\" height=\"5\" width=\"6\" /></div>";
  2540. echo " <div id=\"smallsearchcontent\" style=\"font-size:15px;text-transform:uppercase;\"><h1>$title</h1></div>";
  2541. echo " <div id=\"smallsearchbottom\"><img src=\"" . get_urlmmf('/search/corner_bottom_left.gif') . "\" height=\"5\" width=\"6\" /></div>";
  2542. echo "</div>";
  2543. }
  2544. /**
  2545. * Permet d'afficher le bloc (bleu: type moteur de recherche) mais sans le formulaire de recherche
  2546. * On peut passer un titre a placer dans le bloc en parametre pas de <h1>...</h1> ni <h2>...</h2> ni rien
  2547. *
  2548. * @param unknown_type $title
  2549. * @param unknown_type $classeid
  2550. */
  2551. function create_block_nosearch3($title = "TITLE HERE .... ", $classeid = "contactus") {
  2552. echo "<div id=\"$classeid\">";
  2553. echo " <div id=\"contactustop\"><img class=\"fr_search_top\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
  2554. echo " <div id=\"contactuscontent\" class=\"title\">$title</div>";
  2555. echo " <div id=\"contactusbottom\"><img class=\"fr_search_bottom\" src=\"" . get_urlmmf('/spacer.gif') . "\" /></div>";
  2556. echo "</div>";
  2557. }
  2558. /**
  2559. * Qui prend en charge les caratères accentués (Fonction type strtoupper de PHP)
  2560. *
  2561. * @param unknown_type $chaine
  2562. * @return unknown
  2563. */
  2564. function uc_strtoupper_fr($chaine) {
  2565. $chaine = strtoupper($chaine);
  2566. //$chaine = utf8_decode($chaine);
  2567. $chaine = trim($chaine);
  2568. $chaine = strtr($chaine, "äâàáåãéèëêòóôõöøìíîïùúûüýñçþÿæœðø", "ÄÂÀ�ÅÃÉÈËÊÒÓ�?ÕÖØÌ�Î�ÙÚÛÜ�ÑÇÞ�ÆŒ�Ø");
  2569. //$chaine = utf8_encode($chaine);
  2570. return $chaine;
  2571. }
  2572. /**
  2573. * Permet de retrouver un nom de locname "EGAL A" $name (Function lié au nouveau T9 ouvert)
  2574. *
  2575. * @param unknown_type $name
  2576. * @param unknown_type $like
  2577. * @return unknown
  2578. */
  2579. function find_locname_by_name($name, $like = 0) {
  2580. global $_global;
  2581. $name = strtoupper(trim($name));
  2582. $name = str_replace("'", "\'", $name);
  2583. if ($like == 1)
  2584. $operateur = "LIKE '" . $name . "%'";
  2585. else
  2586. $operateur = "= '" . $name . "'";
  2587. $site = strtoupper($_global["site"]);
  2588. $lang = $_global["lang"];
  2589. $sql = "SELECT SQL_CALC_FOUND_ROWS lct_id, lct_name_" . $lang . ", lct_level, lct_post_code, lgn_id ";
  2590. $sql .= "FROM TM_LOC_" . $site . " ";
  2591. $sql .= "WHERE lct_name_" . $lang . " " . $operateur . " ";
  2592. $sql .= "LIMIT 0, 20";
  2593. if ($_global["debug"] == 3) {
  2594. echo "<hr />find_locname_by_name() - 1<br />";
  2595. echo $sql;
  2596. echo "<hr />";
  2597. }
  2598. /* Count TOTAL sans le limit */
  2599. $sql_count = "SELECT FOUND_ROWS() as count";
  2600. if ($_global["debug"] == 3) {
  2601. echo "<hr />find_locname_by_name() - 2<br />";
  2602. echo $sql_count;
  2603. echo "<hr />";
  2604. }
  2605. $res_locname['res'] = pdoquery($sql);
  2606. $res_locname['count'] = pdoquery($sql_count);
  2607. return $res_locname;
  2608. }
  2609. /**
  2610. * Permet de retrouver un nom de locname "EGAL A" $name (function lié au nouveau T9 ouvert)
  2611. *
  2612. * @param unknown_type $name
  2613. * @param unknown_type $like
  2614. * @return unknown
  2615. */
  2616. function find_locname_by_czip($czip, $like = 0) {
  2617. global $_global;
  2618. $czip = trim($czip);
  2619. if ($like == 1)
  2620. $operateur = " LIKE ('" . $czip . "%') ";
  2621. else
  2622. $operateur = "= '" . $czip . "' ";
  2623. $site = strtoupper($_global["site"]);
  2624. $lang = $_global["lang"];
  2625. $sql = "SELECT SQL_CALC_FOUND_ROWS lct_id, lct_name_" . $lang . ", lct_level, lct_post_code, lgc_id FROM TM_LOC_" . $site;
  2626. $sql .= " WHERE lct_post_code " . $operateur . " AND lct_level <> 0 ORDER BY lct_level ASC LIMIT 0, 20";
  2627. //Debug
  2628. if ($_global["debug"] == 3) {
  2629. echo "<hr />find_locname_by_czip() - 1<br/>";
  2630. echo $sql;
  2631. echo "<hr />";
  2632. }
  2633. /* Count TOTAL sans le limit */
  2634. $sql_count = "SELECT FOUND_ROWS() as count";
  2635. //Debug
  2636. if ($_global["debug"] == 3) {
  2637. echo "<hr />find_locname_by_czip() - 2<br/>";
  2638. echo $sql_count;
  2639. echo "<hr />";
  2640. }
  2641. $res_locname['res'] = pdoquery($sql);
  2642. $res_locname['count'] = pdoquery($sql_count);
  2643. return $res_locname;
  2644. }
  2645. /**
  2646. * Enter description here...
  2647. *
  2648. * @param unknown_type $filename
  2649. * @return unknown
  2650. */
  2651. function sort_files_edito($filename) {
  2652. $tabs = scandir($filename);
  2653. $Idfile = array();
  2654. foreach ($tabs as $tab) {
  2655. if (!(preg_match("/bak/", $tab))) {
  2656. if ($tab != "." && $tab != "..") {
  2657. $Idfile[] = substr($tab, 0, strpos($tab, "."));
  2658. }
  2659. }
  2660. }
  2661. sort($Idfile);
  2662. return array_reverse($Idfile);
  2663. }
  2664. /**
  2665. * Generate absolute url for links (used by logic-immo.com, vacances.logic-immo.com, ville.logic-immo.com...)
  2666. *
  2667. * 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
  2668. * 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
  2669. *
  2670. * @param string $page
  2671. * @param string $subdomain
  2672. * @param string $domain
  2673. * @param string $protocol
  2674. * @return string
  2675. */
  2676. function to_url($page = "", $subdomain = "", $domain = "", $protocol = "") {
  2677. // Attention !!
  2678. // $domain et $protocol ne sont pas pris en compte
  2679. if ($domaine != '') {
  2680. }
  2681. if (string_begins_with($page, "http://"))
  2682. return $page;
  2683. if ($page != '' && $page[0] == '/')
  2684. $page = substr($page, 1);
  2685. if ($subdomain != '') {
  2686. return str_replace('#SUBDOMAIN#', $subdomain, URL_DOMAIN_MASK) . $page;
  2687. } else {
  2688. return URL_SITE . $page;
  2689. }
  2690. }
  2691. /**
  2692. * Generate absolute domain part of url
  2693. */
  2694. function to_url_domain($subdomain = "", $domain = "", $protocol = "") {
  2695. return to_url("", $subdomain, $domain, $protocol);
  2696. }
  2697. /**
  2698. retourne une url en completant avec l'environement de recette
  2699. * */
  2700. function to_url_1($page, $s_domaine) {
  2701. $s_environnement = get_prefix_environnement();
  2702. $s_www = '';
  2703. $s_www = ($s_environnement != 'www') ? 'www' : '';
  2704. return "http://" . $s_www . $s_environnement . '.' . $s_domaine . '/' . $page;
  2705. }
  2706. /**
  2707. * Retourne l'environement courant (prefix)
  2708. * dommage on se base sur URL_DOMAIN_MASK car c'etait pas recommender de rajouter une constante dans chaque fichier de conf
  2709. */
  2710. function get_prefix_environnement() {
  2711. preg_match('#\#\.(.+?)\.#', URL_DOMAIN_MASK, $a_array);
  2712. $a_environement = array('vbx', 'rec', 'dev');
  2713. if (in_array($a_array[1], $a_environement)) {
  2714. return $a_array[1];
  2715. } else {
  2716. return "www";
  2717. }
  2718. }
  2719. /**
  2720. * Return the "host" part and the "page" part of an URL
  2721. * (used to avoid <a href="url">txt</a> tags followed by Google Bot)
  2722. * Ex: http://dev2.www.logic-immo.com/location-lyon/6C1E17A9-D835-913C-5735-8D902E87D11D.html
  2723. * ==> "host" => "http://dev2.www.logic-immo.com" + "page" => "location-lyon/6C1E17A9-D835-913C-5735-8D902E87D11D.html"
  2724. */
  2725. function get_url_host_page($url, $keep_query_string = false) {
  2726. $host_url = "";
  2727. $page_url = "";
  2728. // split the url into its different components
  2729. $parts_url = parse_url($url);
  2730. //echo "<pre>"; print_r($parts_url); echo "</pre>";
  2731. if ($parts_url === FALSE) {
  2732. return array($host_url, $page_url);
  2733. }
  2734. if (isset($parts_url["scheme"]) && !empty($parts_url["scheme"])) {
  2735. $host_url .= $parts_url["scheme"] . "://";
  2736. }
  2737. if (isset($parts_url["host"]) && !empty($parts_url["host"])) {
  2738. $host_url .= $parts_url["host"];
  2739. }
  2740. if (isset($parts_url["port"]) && !empty($parts_url["port"])) {
  2741. $host_url .= ":" . $parts_url["port"];
  2742. }
  2743. // we ignore $parts_url["user"] and $parts_url["pass"] not used here for sure
  2744. // removes an eventual trailing /
  2745. if (string_ends_with($host_url, "/")) {
  2746. $host_url = substr($host_url, 0, strlen($host_url) - 1);
  2747. }
  2748. if (isset($parts_url["path"]) && !empty($parts_url["path"])) {
  2749. $page_url = $parts_url["path"];
  2750. }
  2751. if ($keep_query_string && !empty($parts_url["query"])) {
  2752. $page_url .= "?" . $parts_url["query"];
  2753. }
  2754. if (!empty($parts_url["fragment"])) {
  2755. $page_url .= "#" . $parts_url["fragment"];
  2756. }
  2757. // removes an eventual starting /
  2758. if (string_begins_with($page_url, "/")) {
  2759. $page_url = substr($page_url, 1, strlen($page_url));
  2760. }
  2761. return array($host_url, $page_url);
  2762. }
  2763. /**
  2764. * Convertit une date venant de mysql pour l'afficher dans le back/front-office (YYYY-MM-DD -> DD/MM/YYYY)
  2765. */
  2766. function format_date_sql2ihm($the_date) {
  2767. $conv_date = "";
  2768. if (isset($the_date) && !empty($the_date) && ($the_date != "0000-00-00")) {
  2769. $conv_date_jour = substr($the_date, 8, 2);
  2770. $conv_date_mois = substr($the_date, 5, 2);
  2771. $conv_date_annee = substr($the_date, 0, 4);
  2772. if ($conv_date_jour != "00") {
  2773. $conv_date .= $conv_date_jour;
  2774. }
  2775. if (($conv_date_jour != "00") && ($conv_date_mois != "00")) {
  2776. $conv_date .= "/";
  2777. }
  2778. if ($conv_date_mois != "00") {
  2779. $conv_date .= $conv_date_mois;
  2780. }
  2781. if (($conv_date_mois != "00") && ($conv_date_annee != "0000")) {
  2782. $conv_date .= "/";
  2783. }
  2784. if ($conv_date_annee != "0000") {
  2785. $conv_date .= $conv_date_annee;
  2786. }
  2787. }
  2788. return $conv_date;
  2789. }
  2790. /* format une date */
  2791. /*
  2792. $s_date => date / datetime au format ANGLAIS (obligatoire)
  2793. $s_format => type de formatage souhaité (ex : d-m-Y H:i:s)
  2794. @exemple : print format_datetime('2012-01-03', 'd-m-Y H:i:s');
  2795. */
  2796. function format_datetime($s_date, $s_format) {
  2797. $o_date = new DateTime($s_date);
  2798. return $o_date->format($s_format);
  2799. }
  2800. /**
  2801. * Convertit une chaîne en mettant en majuscule la première lettre de chaque mot
  2802. * en prenant en compte les "-", et en laissant en minuscule les mots comme "en", "sur", etc.
  2803. */
  2804. function ucwords2($string) {
  2805. $conv_string = $string;
  2806. $conv_string = htmlspecialchars_decode($conv_string, ENT_QUOTES);
  2807. $conv_string = str_replace("-", "¿ ", $conv_string);
  2808. $conv_string = ucwords($conv_string);
  2809. $conv_string = str_replace("¿ ", "-", $conv_string);
  2810. $conv_string = str_replace(" D ", " d ", $conv_string);
  2811. $conv_string = str_replace("-D ", "-d ", $conv_string);
  2812. $conv_string = str_replace(" D'", " d'", $conv_string);
  2813. $conv_string = str_replace("-D'", "-d'", $conv_string);
  2814. $conv_string = str_replace(" De ", " de ", $conv_string);
  2815. $conv_string = str_replace("-De-", "-de-", $conv_string);
  2816. $conv_string = str_replace(" Du ", " du ", $conv_string);
  2817. $conv_string = str_replace("-Du-", "-du-", $conv_string);
  2818. $conv_string = str_replace(" Des ", " des ", $conv_string);
  2819. $conv_string = str_replace("-Des-", "-des-", $conv_string);
  2820. $conv_string = str_replace(" L ", " l ", $conv_string);
  2821. $conv_string = str_replace("-L ", "-l ", $conv_string);
  2822. $conv_string = str_replace(" L'", " l'", $conv_string);
  2823. $conv_string = str_replace("-L'", "-l'", $conv_string);
  2824. $conv_string = str_replace(" La ", " la ", $conv_string);
  2825. $conv_string = str_replace("-La-", "-la-", $conv_string);
  2826. $conv_string = str_replace(" Le ", " le ", $conv_string);
  2827. $conv_string = str_replace("-Le-", "-le-", $conv_string);
  2828. $conv_string = str_replace(" Les ", " les ", $conv_string);
  2829. $conv_string = str_replace("-Les-", "-les-", $conv_string);
  2830. $conv_string = str_replace(" A ", " à ", $conv_string);
  2831. $conv_string = str_replace("-A ", "-à ", $conv_string);
  2832. $conv_string = str_replace("-A-", "-à-", $conv_string);
  2833. $conv_string = str_replace(" Au ", " au ", $conv_string);
  2834. $conv_string = str_replace("-Au-", "-au-", $conv_string);
  2835. $conv_string = str_replace(" Aux ", " aux ", $conv_string);
  2836. $conv_string = str_replace("-Aux-", "-aux-", $conv_string);
  2837. $conv_string = str_replace(" En ", " en ", $conv_string);
  2838. $conv_string = str_replace("-En-", "-en-", $conv_string);
  2839. $conv_string = str_replace(" Et ", " et ", $conv_string);
  2840. $conv_string = str_replace("-Et-", "-et-", $conv_string);
  2841. $conv_string = str_replace(" Sur ", " sur ", $conv_string);
  2842. $conv_string = str_replace("-Sur-", "-sur-", $conv_string);
  2843. $conv_string = str_replace(" Sans ", " sans ", $conv_string);
  2844. $conv_string = str_replace("-Sans-", "-sans-", $conv_string);
  2845. $conv_string = str_replace(" Sous ", " sous ", $conv_string);
  2846. $conv_string = str_replace("-Sous-", "-sous-", $conv_string);
  2847. if (strpos($conv_string, "d'") != false) {
  2848. $pos = strpos($conv_string, "d'") + 1;
  2849. $str = substr($conv_string, $pos + 1, 1);
  2850. $conv_string = substr_replace($conv_string, strtoupper($str), $pos + 1, 1);
  2851. }
  2852. if (stripos($conv_string, "l'") !== false) {
  2853. $pos = stripos($conv_string, "l'") + 1;
  2854. $str = substr($conv_string, $pos + 1, 1);
  2855. $conv_string = substr_replace($conv_string, strtoupper($str), $pos + 1, 1);
  2856. }
  2857. return $conv_string;
  2858. }
  2859. /**
  2860. * Return the prefix to put before the french name of a departement
  2861. */
  2862. function prefix_dept_name($dept_code) {
  2863. $dept_prfx = "";
  2864. $dept_code = strtoupper($dept_code);
  2865. if (strlen($dept_code) == 5) {
  2866. $dept_code = str_replace('000', '', $dept_code);
  2867. }
  2868. if (in_array($dept_code, array("75", "974", "975", "976", "986", "98"))) {
  2869. $dept_prfx = "à ";
  2870. } else if (in_array($dept_code, array("01", "02", "03", "07", "09", "10", "11", "12", "27", "28", "34", "36", "37", "60", "61", "89", "91"))) {
  2871. $dept_prfx = "dans l'";
  2872. } 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"))) {
  2873. $dept_prfx = "dans le ";
  2874. } else if (in_array($dept_code, array("23", "26", "42", "50", "51", "55", "58", "72", "80", "86"))) {
  2875. $dept_prfx = "dans la ";
  2876. } else if (in_array($dept_code, array("04", "05", "06", "08", "13", "22", "40", "64", "65", "66", "78", "79", "88", "92", "984"))) {
  2877. $dept_prfx = "dans les ";
  2878. } 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"))) {
  2879. $dept_prfx = "en ";
  2880. }
  2881. return $dept_prfx;
  2882. }
  2883. /**
  2884. * Return the prefix to put before the french name of a region
  2885. */
  2886. function prefix_regn_name($regn_id) {
  2887. $regn_prfx = "";
  2888. if (in_array($regn_id, array("5", "8", "17"))) {
  2889. $regn_prfx = "dans le ";
  2890. } else if (in_array($regn_id, array("12"))) {
  2891. $regn_prfx = "dans les ";
  2892. } 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"))) {
  2893. $regn_prfx = "en ";
  2894. }
  2895. return $regn_prfx;
  2896. }
  2897. /**
  2898. * Vérifie qu'une chaine commence par une certaine sous-chaine
  2899. */
  2900. function string_begins_with($string, $search) {
  2901. return (strncmp($string, $search, strlen($search)) == 0);
  2902. }
  2903. /**
  2904. * Vérifie qu'une chaine se termine par une certaine sous-chaine
  2905. */
  2906. function string_ends_with($string, $search) {
  2907. return (substr($string, strlen($string) - strlen($search)) == $search);
  2908. }
  2909. /**
  2910. * Vérifie qu'une chaine contient une certaine sous-chaine
  2911. */
  2912. function string_contains($string, $search) {
  2913. return (strpos($string, $search) > 0);
  2914. }
  2915. /**
  2916. * Change le lien en absolus et remplace les & par des &amp;
  2917. *
  2918. * @param String $links : Code HTML contenant des liens
  2919. */
  2920. function normalize_link($html_output) {
  2921. // Mettre tous les liens en absolu
  2922. preg_match_all("`href=\"[^\"]+\"`", $html_output, $match);
  2923. /*
  2924. echo '<pre>';
  2925. print_r($match);
  2926. echo '</pre>';
  2927. */
  2928. if (is_array($match[0])) {
  2929. foreach ($match[0] as $k => $v) {
  2930. if (strpos($v, "javascript") === false) {
  2931. $url = str_replace("=\"/", "=\"http://" . $_SERVER['HTTP_HOST'] . '/', $v);
  2932. $url = TextNoAccent($url);
  2933. // Si l'url ne contient pas d'ID(agence, annonce ...) on met en minuscule
  2934. $regex_url_agence = "agence-immobiliere/([-+_'a-z0-9]+)/annonces-immobilier-([-+_'A-Z0-9]+)_([0-9]+)-([-+'a-zA-Z0-9]*)\.(html)";
  2935. $regex_url_annonce = "agence-immobiliere/([-+_'a-z0-9]+)/annonces-location-([-+_'A-Z0-9]+)_([0-9]+)-([-+'a-zA-Z0-9]*)\.(html)";
  2936. /*
  2937. if (!preg_match("`$regex_url_agence`", $v) && !preg_match("`$regex_url_annonce`", $v))
  2938. $url = strtolower($url);
  2939. */
  2940. // Correctiopn W3C
  2941. if (strpos($url, "&amp") !== false) {
  2942. // Pour éviter de remplacer les &amp saisis à la main sur des urls en BD par exp
  2943. $url = str_replace("&amp;", "&", $url);
  2944. }
  2945. $url = str_replace("&", "&amp;", $url);
  2946. $html_output = str_replace($v, $url, $html_output);
  2947. }
  2948. }
  2949. }
  2950. // Fin traitement
  2951. return $html_output;
  2952. }
  2953. /**
  2954. * Ajoute des alts, corrige la fermeture de balise et les "&"
  2955. *
  2956. * @param String $html_output
  2957. * @return String html_output
  2958. */
  2959. function normalize_img($html_output) {
  2960. // Récupérer toutes les images cotenu dans le code HTML
  2961. preg_match_all("`<img(.*?)>`is", $html_output, $match, PREG_PATTERN_ORDER);
  2962. if (is_array($match[0])) {
  2963. foreach ($match[0] as $k => $v) {
  2964. $old_v = $v;
  2965. // Vérification des alts
  2966. $b = strpos($v, "alt");
  2967. if ($b === false) {
  2968. $v = str_replace("<img", "<img alt=\"\" ", $v);
  2969. }
  2970. // Vérification des fermeture de balise
  2971. if (strpos($v, "/>") === false && strpos($html_output, $old_v . "</img>") === false) {
  2972. //echo htmlentities($v)."<hr>";
  2973. $v = str_replace(">", "/>", $v);
  2974. }
  2975. // Correction des src
  2976. preg_match('#src=\"(.*?)\"#i', $v, $tr);
  2977. $src = str_replace("&", "&amp;", $tr[0]);
  2978. $v = str_replace($tr[0], $src, $v);
  2979. // MAJ du code HTML
  2980. $html_output = str_replace($old_v, $v, $html_output);
  2981. }
  2982. }
  2983. return $html_output;
  2984. }
  2985. /**
  2986. * Log des erreurs 404 (Refnat)
  2987. *
  2988. * @author Walid ASBAITI
  2989. * @param String $case
  2990. * @return void
  2991. */
  2992. function log_404_refnat($case = "") {
  2993. // Ne sert plus, mais pour eviter des erreurs cache, return true
  2994. return true;
  2995. $num_semaine = date("W");
  2996. // $navigateur = get_browser_agent("name");
  2997. $navigateur = $_SERVER['HTTP_USER_AGENT'];
  2998. // $navigateur2 = get_browser_agent();
  2999. $source = $_SERVER['HTTP_REFERER'];
  3000. // echo $case;
  3001. switch ($case) {
  3002. case "ads":
  3003. //création du msg
  3004. $error_log = "Annonce inexistante.\n";
  3005. $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
  3006. $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
  3007. $error_log .= "<b>USER AGENT</b> : " . $navigateur;
  3008. $error_log .= "\n\n";
  3009. break;
  3010. case "agc":
  3011. //création du msg
  3012. $error_log = "Agence inactive\n";
  3013. $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
  3014. $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
  3015. $error_log .= "<b>USER AGENT</b> : " . $navigateur;
  3016. $error_log .= "\n\n";
  3017. break;
  3018. case "ref_ann":
  3019. //création du msg
  3020. $error_log = "Annonce refnat inexistante\n";
  3021. $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
  3022. $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
  3023. $error_log .= "<b>USER AGENT</b> : " . $navigateur;
  3024. $error_log .= "\n\n";
  3025. break;
  3026. case "ref_dep":
  3027. //création du msg
  3028. $error_log = "Nom de Departement different du CP\n";
  3029. $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
  3030. $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
  3031. $error_log .= "<b>USER AGENT</b> : " . $navigateur;
  3032. $error_log .= "\n\n";
  3033. break;
  3034. case "ref_ville":
  3035. //création du msg
  3036. $error_log = "Ville inexistante\n";
  3037. $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
  3038. $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
  3039. $error_log .= "<b>USER AGENT</b> : " . $navigateur;
  3040. $error_log .= "\n\n";
  3041. break;
  3042. default:
  3043. $error_log = "URL incorrecte : $case\n";
  3044. $error_log .= "<b>Date</b> : " . date("d-m-Y h:i:s") . " | ";
  3045. $error_log .= "<b>URL</b> : " . $_SERVER["REQUEST_URI"] . " | <b>SOURCE</b> : " . $source . " \n";
  3046. $error_log .= "<b>USER AGENT</b> : " . $navigateur;
  3047. $error_log .= "\n\n";
  3048. break;
  3049. }
  3050. $date = date("Y-m-d H:i:s");
  3051. $sSql = "INSERT INTO TW_LOGS404_LOG values('', \"$error_log\", \"$date\",0)";
  3052. // echo $sSql;
  3053. // Ne pas enregistrer en PRP
  3054. if ($_SERVER['SERVER_ADDR'] != "195.154.207.140")
  3055. $res = pdoupdate($sSql);
  3056. }
  3057. /**
  3058. * Permet de détecté le navigateur client utilisé
  3059. *
  3060. * @param string $return Valeur de retour demandée
  3061. *
  3062. * @return string|array
  3063. */
  3064. function get_browser_agent($return = false) {
  3065. global $browser_agent;
  3066. if ($return)
  3067. $return = strtolower($return);
  3068. // Navigateurs connu
  3069. if ($return && $return == 'browsers') {
  3070. return array(
  3071. 'firefox' => 'browser',
  3072. 'shiretoko' => 'browser', // nom de code de firefox 3.5 dev
  3073. 'msie' => 'browser',
  3074. 'opera' => 'browser',
  3075. 'chrome' => 'browser',
  3076. 'safari' => 'browser',
  3077. 'mozilla' => 'browser',
  3078. 'seamonkey' => 'browser',
  3079. 'konqueror' => 'browser',
  3080. 'netscape' => 'browser',
  3081. 'gecko' => 'browser',
  3082. 'navigator' => 'browser',
  3083. 'mosaic' => 'browser',
  3084. 'lynx' => 'browser',
  3085. 'amaya' => 'browser',
  3086. 'omniweb' => 'browser',
  3087. 'avant' => 'browser',
  3088. 'camino' => 'browser',
  3089. 'flock' => 'browser',
  3090. 'aol' => 'browser',
  3091. 'Googlebot' => 'spider',
  3092. 'msnbot' => 'spider',
  3093. 'Yahoo' => 'spider',
  3094. 'ask' => 'spider',
  3095. 'Gigabot' => 'spider',
  3096. 'itunes' => 'other',
  3097. );
  3098. }
  3099. // Plateforme connue
  3100. else if ($return && $return == 'platforms') {
  3101. return array(
  3102. 'android' => array('android'),
  3103. 'freebsd' => array('freebsd'),
  3104. 'linux' => array('linux'),
  3105. 'iphone' => array('iphone'),
  3106. 'ipod' => array('ipod'),
  3107. 'zune' => array('zune'),
  3108. 'mac' => array('macintosh', 'mac platform x', 'mac os x'),
  3109. 'win' => array('windows', 'win32'),
  3110. );
  3111. }
  3112. if (!isset($browser_agent)) {
  3113. $browser_agent = array(
  3114. 'name' => false,
  3115. 'version' => 0,
  3116. 'platform' => false,
  3117. 'userAgent' => $_SERVER['HTTP_USER_AGENT']
  3118. );
  3119. // Navigateur + Version
  3120. foreach (get_browser_agent('browsers') as $browser => $type) {
  3121. if (preg_match("#($browser)[/ ]?([0-9.]*)#", strtolower($browser_agent['userAgent']), $match)) {
  3122. $browser_agent['name'] = $match[1];
  3123. // Hack safari
  3124. if ($browser_agent['name'] == 'safari' && preg_match("#version[/ ]?([0-9.]*)#", strtolower($browser_agent['userAgent']), $match)) {
  3125. $browser_agent['version'] = $match[1];
  3126. }
  3127. else
  3128. $browser_agent['version'] = $match[2];
  3129. if ($type == 'spider')
  3130. $browser_agent['platform'] = $type;
  3131. break;
  3132. }
  3133. }
  3134. // OS
  3135. if (!$browser_agent['platform']) {
  3136. foreach (get_browser_agent('platforms') as $platform => $values) {
  3137. if (!$browser_agent['platform']) {
  3138. foreach ($values as $value) {
  3139. if (strpos(strtolower($browser_agent['userAgent']), $value)) {
  3140. $browser_agent['platform'] = $platform;
  3141. break;
  3142. }
  3143. }
  3144. }
  3145. else
  3146. break;
  3147. }
  3148. }
  3149. }
  3150. if ($return && isset($browser_agent[$return]))
  3151. return $browser_agent[$return];
  3152. else if (!$return)
  3153. return $browser_agent;
  3154. else
  3155. return false;
  3156. }
  3157. /**
  3158. * Check if a property type can have rooms and that unit correspond to number
  3159. * @param $roomsNum Nombre de pieces
  3160. * @param $roomsUnit Unité (piece ou pieces)
  3161. * @param $propertyType Type de bien (appartement,terrain,...)
  3162. * @return Integer Identifiant du type de bien
  3163. */
  3164. function checkRoomsProperty($roomsNum, $roomsUnit, $propertyType) {
  3165. // Erreur : Nombre de pieces invalide
  3166. if ($roomsNum < 1)
  3167. return false;
  3168. // Vérifier que le type de bien est autorisé
  3169. switch ($propertyType) {
  3170. case 'appartement':
  3171. $idType = 1;
  3172. break;
  3173. case 'maison':
  3174. $idType = 2;
  3175. break;
  3176. case 'loft':
  3177. $idType = 13;
  3178. break;
  3179. case 'viager':
  3180. $idType = 40;
  3181. break;
  3182. default:
  3183. return 0;
  3184. }
  3185. // Si l'unité correspond au nombre => Okay
  3186. if ($roomsNum == 1 && $roomsUnit == 'piece' || $roomsUnit == 'pieces')
  3187. return $idType;
  3188. else
  3189. return 0;
  3190. }
  3191. /**
  3192. * Return property value from property name (for bien_ville_*.php and others)
  3193. *
  3194. * @param unknown_type $loc
  3195. * @param unknown_type $loc2
  3196. * @param unknown_type $loc3
  3197. * @return unknown
  3198. */
  3199. function check_locality($loc, $loc2 = NULL, $loc3 = NULL, $lvl = NULL) {
  3200. //echo "[$loc - $loc2 - $loc3 - $lvl]";
  3201. $loc = strtoupper($loc);
  3202. // check si localité 2 = localité 1
  3203. if ($loc2 != NULL) {
  3204. $loc2 = strtoupper($loc2);
  3205. if ($loc != $loc2) {
  3206. return false;
  3207. }
  3208. }
  3209. // check si localité 2 = localité 1
  3210. if ($loc3 != NULL) {
  3211. $loc3 = strtoupper($loc3);
  3212. if (($loc != $loc2) || ($loc2 != $loc3)) {
  3213. return false;
  3214. }
  3215. }
  3216. $loc = str_replace(" ", "%", $loc);
  3217. $loc = str_replace("'", "%", $loc);
  3218. $sql = "
  3219. SELECT COUNT(lct_name) AS nbr
  3220. FROM TM_LOC_FR
  3221. WHERE lct_name LIKE '" . $loc . "'
  3222. ";
  3223. // check si level localité = celui (ou ceux) demandé(s)
  3224. if ($lvl != NULL) {
  3225. if (is_array($lvl)) {
  3226. $lst = implode(", ", $lvl);
  3227. $sql .= "
  3228. AND lct_level IN ($lst)
  3229. ";
  3230. } else {
  3231. $sql .= "
  3232. AND lct_level = $lvl
  3233. ";
  3234. }
  3235. }
  3236. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3237. $res = pdoquery($sql);
  3238. //var_dump($res);
  3239. if ($res[0]["nbr"] == 0) {
  3240. return false;
  3241. }
  3242. return true;
  3243. }
  3244. /**
  3245. * Check the coherence between loc_name & loc_key
  3246. *
  3247. * @param String $loc_name
  3248. * @param String $loc_key (lct_id & lct_level)
  3249. * @return bool
  3250. */
  3251. function check_locality_by_loc_key($loc_name, $loc_key) {
  3252. $tab_lok = explode('_', $loc_key);
  3253. $lct_id = $tab_lok[0];
  3254. $lct_level = $tab_lok[1];
  3255. if (strtolower($loc_name) != "toutes communes") {
  3256. $loc = strtoupper($loc_name);
  3257. $loc = str_replace("-", "%", $loc);
  3258. $loc = str_replace(" ", "%", $loc);
  3259. $loc = str_replace("'", "\'", $loc);
  3260. $where_loc = "AND lct_name LIKE '$loc'";
  3261. }
  3262. if ($lct_level == 98) {
  3263. $where_lct = "AND lgc_id = $lct_id";
  3264. } else if ($lct_level == 99) {
  3265. $where_lct = "AND lgn_id = $lct_id";
  3266. } else { // $lct_level == 0, 1, 2 a priori
  3267. $where_lct = "AND lct_id = $lct_id AND lct_level = $lct_level";
  3268. }
  3269. $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE 1 $where_loc $where_lct";
  3270. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3271. $res = pdoquery($sql);
  3272. //var_dump($res);
  3273. if ($res[0]["nbr"] == 0) {
  3274. // Florian - 19/07/10 - Inclusion de la globale !
  3275. // (Pb avec le header si pas d'univers par exemple)
  3276. global $_global;
  3277. log_404_refnat("Loc erronée");
  3278. header("HTTP/1.0 404 Not Found");
  3279. header("status: 404");
  3280. include($_SERVER["DOCUMENT_ROOT"] . "/404.php");
  3281. exit();
  3282. }
  3283. return true;
  3284. }
  3285. /**
  3286. * Check if the id(s) of a locality is(are) the one of a town (and not a departement or a region)
  3287. *
  3288. * @param String $lct_id
  3289. * @param String $lgc_id
  3290. * @param String $lgn_id
  3291. * @return bool
  3292. */
  3293. function check_locality_is_town_ids($lct_id, $lgc_id = NULL, $lgn_id = NULL) {
  3294. $ret = false;
  3295. if (isset($lgc_id) && ($lgc_id != NULL) && ($lgc_id > 0)) {
  3296. return true; // forcément une ville
  3297. } else if (isset($lgn_id) && ($lgn_id != NULL) && ($lgn_id > 0)) {
  3298. return true; // forcément une ville
  3299. } else { // $lct_id == 0, 1, 2 a priori
  3300. $sql = "SELECT lct_id, lct_level, lct_name FROM TM_LOC_FR WHERE lct_id = $lct_id";
  3301. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3302. $res = pdoquery($sql);
  3303. //var_dump($res);
  3304. if (count($res) > 0) {
  3305. $loc = $res[0];
  3306. $ret = ((($loc["lct_id"] > 120) && ($loc["lct_level"] == 2)) || (($loc["lct_id"] == 100) && ($loc["lct_level"] == 1)));
  3307. }
  3308. }
  3309. return $ret;
  3310. }
  3311. /**
  3312. * Check if the name of a locality is the one of a town (and not a departement or a region)
  3313. *
  3314. * @param String $lct_id
  3315. * @param String $lgc_id
  3316. * @param String $lgn_id
  3317. * @return bool
  3318. */
  3319. function check_locality_is_town_text($lct_name) {
  3320. $ret = false;
  3321. $sql_name = htmlspecialchars_decode($lct_name, ENT_QUOTES);
  3322. $sql_name = addslashes($sql_name);
  3323. $sql = "SELECT lct_id, lct_level, lct_name FROM TM_LOC_FR WHERE lct_name = '" . $sql_name . "'";
  3324. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3325. $res = pdoquery($sql);
  3326. //var_dump($res);
  3327. if (count($res) > 0) {
  3328. $loc = $res[0];
  3329. $ret = ((($loc["lct_id"] > 120) && ($loc["lct_level"] == 2)) || (($loc["lct_id"] == 100) && ($loc["lct_level"] == 1)));
  3330. }
  3331. return $ret;
  3332. }
  3333. // Renvoie true si la clé de localité n'est pas correctement écrite (et pas si elle n'est pas valide en base !)
  3334. function isWrongLocKey($loc_key) {
  3335. return ( $loc_key != '' && !preg_match('`^[0-9]+_([0123]|97|98|99)$`', $loc_key) );
  3336. }
  3337. // Renvoie true si le couple clé de localité / nom de localité n'est pas valide en base
  3338. function isWrongLocKeyLocName($loc_key, $loc_name) {
  3339. $ret = true;
  3340. if (($loc_key == '') || ($loc_name == '')) {
  3341. return $ret;
  3342. }
  3343. // Récupération des infos
  3344. $tab_lok = explode('_', $loc_key);
  3345. $loc_id = $tab_lok[0];
  3346. $loc_level = $tab_lok[1];
  3347. //echo "(loc_id, loc_level) = ($loc_id, $loc_level)";
  3348. if (($loc_id == '') || ($loc_level == '')) {
  3349. return $ret;
  3350. }
  3351. $sql = "SELECT COUNT(1) AS nbr";
  3352. // Vérification du loc_key en base
  3353. if ($loc_level == '98') {
  3354. $sql .= " FROM TM_LOCGC_FR WHERE lgc_id = $loc_id";
  3355. } else if ($loc_level == '99') {
  3356. $sql .= " FROM TM_LOCGN_FR WHERE lgn_id = $loc_id";
  3357. } else { // $loc_level == 0, 1, 2 a priori
  3358. $sql .= " FROM TM_LOC_FR WHERE lct_id = $loc_id AND lct_level = $loc_level";
  3359. }
  3360. // Vérification du loc_name en base
  3361. $loc_name_sql = str_replace('-', '%', $loc_name);
  3362. $loc_name_sql = strtoupper(addslashes($loc_name_sql));
  3363. if ($loc_level == '98') {
  3364. if ($loc_name != 'toutes-communes')
  3365. return true;
  3366. } else if ($loc_level == '99') {
  3367. if (strpos($loc_name_sql, '%') === false) {
  3368. $sql .= " AND lgn_name_fr = '" . $loc_name_sql . "'";
  3369. } else {
  3370. $sql .= " AND lgn_name_fr LIKE '" . $loc_name_sql . "'";
  3371. }
  3372. } else { // $loc_level == 0, 1, 2 a priori
  3373. if (strpos($loc_name_sql, '%') === false) {
  3374. $sql .= " AND lct_name = '" . $loc_name_sql . "'";
  3375. } else {
  3376. $sql .= " AND lct_name LIKE '" . $loc_name_sql . "'";
  3377. }
  3378. }
  3379. // Exécution de la requête
  3380. //echo "<hr>".$sql."<br>"; //exit();
  3381. $res = pdoquery($sql);
  3382. //var_dump($res);
  3383. $ret = ($res[0]["nbr"] <= 0);
  3384. return $ret;
  3385. }
  3386. // Renvoie true si le couple clé de localité / nom de localité est unique (1 localité, pas 2 ni 3)
  3387. function isUniqLocKeyLocName($loc_key, $loc_name) {
  3388. $ret = false;
  3389. if (($loc_key == '') || ($loc_name == '')) {
  3390. return $ret;
  3391. }
  3392. $ret = (!string_contains($loc_key, ',') && !string_contains($loc_name, ','));
  3393. return $ret;
  3394. }
  3395. // Renvoie true si le triplet clé de localité / nom de localité / code postal n'est pas valide en base
  3396. function isWrongLocKeyLocNamePostCode($loc_key, $loc_name_post_code) {
  3397. $ret = true;
  3398. if (($loc_key == '') || ($loc_name_post_code == '')) {
  3399. return $ret;
  3400. }
  3401. // Récupération des infos
  3402. $tab_lok = explode('_', $loc_key);
  3403. $loc_id = $tab_lok[0];
  3404. $loc_level = $tab_lok[1];
  3405. //echo "(loc_id, loc_level) = ($loc_id, $loc_level)";
  3406. if (($loc_id == '') || ($loc_level == '')) {
  3407. return $ret;
  3408. }
  3409. if (!in_array($loc_level, array('0', '1', '2', '98', '99'))) {
  3410. return $ret;
  3411. }
  3412. /*
  3413. // Patch pour arrondissements de Marseille et Lyon qui n'ont pas le bon dans default_town_2
  3414. // actuellement (champ calculé depuis le BOFO avec son propre référentiel)
  3415. //echo '[AVANT:loc_key='.$loc_key.' / loc_name_post_code='.$loc_name_post_code.']';
  3416. $arr_city = array('lct_id' => $loc_id);
  3417. $ret_city = isArrondCity($arr_city);
  3418. if ($ret_city[0]) {
  3419. $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";
  3420. //echo "<hr>".$sql."<br>"; //exit();
  3421. $res = pdoquery($sql);
  3422. //var_dump($res);
  3423. $loc_name_post_code = $res[0][0];
  3424. //echo '[APRES:loc_name_post_code = '.$loc_name_post_code.']';
  3425. }
  3426. */
  3427. $tab_lon = explode('-', $loc_name_post_code);
  3428. $pos_lon = sizeof($tab_lon) - 1;
  3429. if ($pos_lon < 1)
  3430. return true; // y a déjà un pb
  3431. if ($loc_level == '99') { // suppr 3 derniers élts ('tous codes postaux')
  3432. $loc_post_code = $tab_lon[$pos_lon - 2] . '-' . $tab_lon[$pos_lon - 1] . '-' . $tab_lon[$pos_lon];
  3433. unset($tab_lon[$pos_lon]);
  3434. unset($tab_lon[$pos_lon - 1]);
  3435. unset($tab_lon[$pos_lon - 2]);
  3436. } else { // suppr dernier élt ('XXXXX' ou 'XXX' ou 'XX')
  3437. $loc_post_code = $tab_lon[$pos_lon];
  3438. unset($tab_lon[$pos_lon]);
  3439. }
  3440. $loc_name = implode('-', $tab_lon);
  3441. //echo "(loc_name, loc_post_code) = ($loc_name, $loc_post_code)";
  3442. $sql = "SELECT COUNT(1) AS nbr";
  3443. // Vérification du loc_key en base
  3444. if ($loc_level == '98') {
  3445. $sql .= " FROM TM_LOCGC_FR WHERE lgc_id = $loc_id";
  3446. } else if ($loc_level == '99') {
  3447. $sql .= " FROM TM_LOCGN_FR WHERE lgn_id = $loc_id";
  3448. } else { // $loc_level == 0, 1, 2 a priori
  3449. $sql .= " FROM TM_LOC_FR WHERE lct_id = $loc_id AND lct_level = $loc_level";
  3450. }
  3451. // Vérification du loc_name en base
  3452. $loc_name_sql = str_replace(' ', '%', $loc_name);
  3453. $loc_name_sql = str_replace('-', '%', $loc_name_sql);
  3454. $loc_name_sql = strtoupper(addslashes($loc_name_sql));
  3455. if ($loc_level == '98') {
  3456. if ($loc_name != 'toutes-communes')
  3457. return true;
  3458. } else if ($loc_level == '99') {
  3459. if (strpos($loc_name_sql, '%') === false) {
  3460. $sql .= " AND lgn_name_fr = '" . $loc_name_sql . "'";
  3461. } else {
  3462. $sql .= " AND lgn_name_fr LIKE '" . $loc_name_sql . "'";
  3463. }
  3464. } else { // $loc_level == 0, 1, 2 a priori
  3465. if (strpos($loc_name_sql, '%') === false) {
  3466. $sql .= " AND lct_name = '" . $loc_name_sql . "'";
  3467. } else {
  3468. $sql .= " AND lct_name LIKE '" . $loc_name_sql . "'";
  3469. }
  3470. }
  3471. // Vérification du loc_post_code en base
  3472. if ($loc_level == '98') {
  3473. $sql .= " AND lgc_post_code = '" . $loc_post_code . "'";
  3474. } else if ($loc_level == '99') {
  3475. if ($loc_post_code != 'tous-codes-postaux')
  3476. return true;
  3477. //$sql .= "";
  3478. } else { // $loc_level == 0, 1, 2 a priori
  3479. if ($loc_level == '1') {
  3480. if (in_array($loc_post_code, array('2a', '2b', '971', '972', '973', '974', '975', '976', '984', '986', '987', '988'))) {
  3481. $sql .= " AND lct_post_code = '" . $loc_post_code . "'";
  3482. } else {
  3483. $sql .= " AND lct_post_code = '" . $loc_post_code . "000'";
  3484. }
  3485. } else {
  3486. $sql .= " AND lct_post_code = '" . $loc_post_code . "'";
  3487. }
  3488. }
  3489. // Exécution de la requête
  3490. //echo "<hr>".$sql."<br>"; //exit();
  3491. $res = pdoquery($sql);
  3492. //var_dump($res);
  3493. $ret = ($res[0]["nbr"] <= 0);
  3494. return $ret;
  3495. }
  3496. // Renvoie true si au moins un des triplets clé de localité / nom de localité / code postal n'est pas valide en base
  3497. function areWrongLocKeyLocNamePostCode($loc_keys, $loc_names_post_codes) {
  3498. $ret = true;
  3499. $lst_loc_keys = explode(',', $loc_keys);
  3500. $lst_loc_names = explode(',', $loc_names_post_codes);
  3501. for ($i = 0; $i < 3; $i++) {
  3502. if (isset($lst_loc_keys[$i]) && isset($lst_loc_names[$i])) {
  3503. $ret = $ret || !isWrongLocKeyLocNamePostCode($lst_loc_keys[$i], $lst_loc_names[$i]);
  3504. }
  3505. }
  3506. return $ret;
  3507. }
  3508. /**
  3509. * Check the coherence of the loc_key
  3510. *
  3511. * @param String $loc_key (lct_id & lct_level)
  3512. * @return bool
  3513. */
  3514. function check_loc_key($loc_key, $str_cond = "") {
  3515. $tab_lok = explode('_', $loc_key);
  3516. $lct_id = $tab_lok[0];
  3517. $lct_level = $tab_lok[1];
  3518. if ($lct_level == 98) {
  3519. $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE lgc_id = $lct_id";
  3520. } else if ($lct_level == 99) {
  3521. $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE lgn_id = $lct_id";
  3522. } else { // $lct_level == 0, 1, 2 a priori
  3523. $sql = "SELECT COUNT(lct_id) AS nbr FROM TM_LOC_FR WHERE lct_id = $lct_id AND lct_level = $lct_level";
  3524. }
  3525. if (isset($str_cond) && !empty($str_cond)) {
  3526. $sql .= " AND " . $str_cond; // peut utiliser le champ "lct_name"
  3527. }
  3528. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3529. $res = pdoquery($sql);
  3530. //var_dump($res);
  3531. $ret = ($res[0]["nbr"] > 0);
  3532. return $ret;
  3533. }
  3534. /**
  3535. * Check the coherence of the loc_key
  3536. *
  3537. * @param String $loc_key (lct_id & lct_level)
  3538. * @return bool
  3539. */
  3540. function get_loc_key($loc_key, $loc_post_code = "", $str_cond = "") {
  3541. $tab_lok = explode('_', $loc_key);
  3542. $lct_id = $tab_lok[0];
  3543. $lct_level = $tab_lok[1];
  3544. if (empty($lct_id) || empty($lct_level)) {
  3545. $ret = NULL;
  3546. } else {
  3547. if ($lct_level == 98) {
  3548. $sql = "SELECT lct_id, lct_level, lct_name, lct_post_code, lct_parent_id FROM TM_LOC_FR WHERE lgc_id = $lct_id";
  3549. } else if ($lct_level == 99) {
  3550. $sql = "SELECT lct_id, lct_level, lct_name, lct_post_code, lct_parent_id FROM TM_LOC_FR WHERE lgn_id = $lct_id";
  3551. } else { // $lct_level == 0, 1, 2 a priori
  3552. $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";
  3553. }
  3554. if (isset($loc_post_code) && !empty($loc_post_code)) {
  3555. $sql .= " AND lct_post_code = '" . $loc_post_code . "'";
  3556. }
  3557. if (isset($str_cond) && !empty($str_cond)) {
  3558. $sql .= " AND " . $str_cond;
  3559. }
  3560. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3561. $res = pdoquery($sql);
  3562. //var_dump($res);
  3563. $ret = $res[0];
  3564. }
  3565. return $ret;
  3566. }
  3567. /**
  3568. * Get the all the localities with the same name
  3569. *
  3570. * @param String $loc_name
  3571. * @return array
  3572. */
  3573. function get_loc_names($lct_name, $loc_key = "", $loc_post_code = "", $str_cond = "") {
  3574. $sql = "
  3575. SELECT lct_id, lct_level, lct_name, lct_post_code
  3576. FROM TM_LOC_FR
  3577. WHERE 1
  3578. ";
  3579. if ($lct_name != "") {
  3580. $lct_name_sql = strtoupper(addslashes($lct_name));
  3581. $sql .= "AND lct_name = '" . $lct_name_sql . "'";
  3582. }
  3583. if (isset($loc_key) && !empty($loc_key)) {
  3584. $tab_lok = explode('_', $loc_key);
  3585. $lct_id = $tab_lok[0];
  3586. $lct_level = $tab_lok[1];
  3587. $sql .= "
  3588. AND NOT (lct_id = '" . $lct_id . "' AND lct_level = '" . $lct_level . "')
  3589. ";
  3590. }
  3591. if (isset($loc_post_code) && !empty($loc_post_code)) {
  3592. $sql .= "
  3593. AND NOT (lct_post_code = '" . $loc_post_code . "')
  3594. ";
  3595. }
  3596. if (isset($str_cond) && !empty($str_cond)) {
  3597. $sql .= "
  3598. AND " . $str_cond . "
  3599. ";
  3600. }
  3601. $sql .= "
  3602. ORDER BY lct_post_code ASC
  3603. ";
  3604. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3605. $res = pdoquery($sql);
  3606. //var_dump($res);
  3607. return $res;
  3608. }
  3609. /**
  3610. * Get the all the localities with the same name v2
  3611. *
  3612. * @param String $loc_name
  3613. * @return array
  3614. */
  3615. function get_loc_names2($lct_name, $loc_key = "", $loc_post_code = "", $str_cond = "") {
  3616. $sql_and = "";
  3617. if ($lct_name != "") {
  3618. $lct_name_sql = strtoupper(addslashes($lct_name));
  3619. $sql_and .= "AND lct_name = '" . $lct_name_sql . "'";
  3620. }
  3621. if (isset($loc_key) && !empty($loc_key)) {
  3622. $tab_lok = explode('_', $loc_key);
  3623. $lct_id = $tab_lok[0];
  3624. $lct_level = $tab_lok[1];
  3625. if ($lct_level == '99') {
  3626. $sql_and .= "
  3627. AND NOT (lgn_id = '" . $lct_id . "')
  3628. ";
  3629. } else {
  3630. $sql_and .= "
  3631. AND NOT (lct_id = '" . $lct_id . "' AND lct_level = '" . $lct_level . "')
  3632. ";
  3633. }
  3634. }
  3635. if (isset($loc_post_code) && !empty($loc_post_code) && ($loc_post_code != 'tous-codes-postaux')) {
  3636. $sql_and .= "
  3637. AND NOT (lct_post_code = '" . $loc_post_code . "')
  3638. ";
  3639. }
  3640. if (isset($str_cond) && !empty($str_cond)) {
  3641. $sql_and .= "
  3642. AND " . $str_cond . "
  3643. ";
  3644. }
  3645. $sql = "
  3646. (
  3647. SELECT lct_id, lct_level, lct_name, lct_post_code
  3648. FROM TM_LOC_FR
  3649. WHERE 1
  3650. $sql_and
  3651. AND lgn_id = 0
  3652. ) UNION ALL (
  3653. SELECT lgn_id AS lct_id, '99' AS lct_level, lct_name, 'tous codes postaux' AS lct_post_code
  3654. FROM TM_LOC_FR
  3655. WHERE 1
  3656. $sql_and
  3657. AND lgn_id > 0
  3658. GROUP BY lgn_id
  3659. )
  3660. ORDER BY lct_post_code ASC
  3661. ";
  3662. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3663. $res = pdoquery($sql);
  3664. //var_dump($res);
  3665. return $res;
  3666. }
  3667. /**
  3668. * Get the locality infos from a lct_id
  3669. *
  3670. * @param String $loc_name
  3671. * @return array
  3672. */
  3673. function get_loc_infos($lct_id, $str_cond = "") {
  3674. $sql = "
  3675. SELECT lct_id, lct_level, lct_name, lct_post_code, lgc_id, lgn_id
  3676. FROM TM_LOC_FR
  3677. WHERE 1
  3678. ";
  3679. if ($lct_id != "") {
  3680. $sql .= "AND lct_id = '" . $lct_id . "'";
  3681. }
  3682. if (isset($str_cond) && !empty($str_cond)) {
  3683. $sql .= "
  3684. AND " . $str_cond . "
  3685. ";
  3686. }
  3687. $sql .= "
  3688. ORDER BY lct_id ASC
  3689. ";
  3690. //echo "<hr><br>".$sql."<br><hr>"; //exit();
  3691. $res = pdoquery($sql);
  3692. //var_dump($res);
  3693. return $res;
  3694. }
  3695. /**
  3696. * Get the locality infos from a lct_id
  3697. * (used for WS /ws/url.search.li.mysql.php)
  3698. *
  3699. * @param String $loc_name
  3700. * @return array
  3701. */
  3702. function get_loc_infos_from_post_code($lct_post_code) {
  3703. $arr = array(
  3704. 'ret_val' => false,
  3705. 'ret_msg' => '',
  3706. 'loc_key' => '',
  3707. 'loc_name' => '',
  3708. 'lgn_id' => '',
  3709. 'lgc_id' => ''
  3710. );
  3711. $lct_post_code = strtolower($lct_post_code);
  3712. // check format : villes (dont Monaco), dépts métropole, dépts Dom-Tom, dépts Corse
  3713. if (!(preg_match('/[0-9]{5}|[0-9]{2}|97[0-9]|98[0-9]|2[a-b]/', $lct_post_code))) {
  3714. $arr['ret_msg'] = 'Bad postcode regexp (lct_post_code = ' . $lct_post_code . ')';
  3715. return $arr;
  3716. }
  3717. // type de CP : CP ville ou de dépt
  3718. $len_post_code = strlen($lct_post_code);
  3719. if (in_array($len_post_code, array(2, 3))) { // dépt
  3720. if (strlen($lct_post_code) == 2) {
  3721. if (!in_array($lct_post_code, array('2a', '2b'))) {
  3722. $lct_post_code = $lct_post_code . '000';
  3723. }
  3724. }
  3725. $sql = "
  3726. SELECT lct_id, lct_level, lct_name, lct_post_code, lgn_id, lgc_id
  3727. FROM TM_LOC_FR
  3728. WHERE lct_post_code = '$lct_post_code'
  3729. AND lct_level = 1
  3730. ";
  3731. //echo "<hr><br>".$sql."<br><hr>";
  3732. $res = pdoquery($sql);
  3733. //var_dump($res);
  3734. if (count($res) > 0) {
  3735. $ret = $res[0];
  3736. if (strlen($ret['lct_post_code']) == 5) {
  3737. $ret['lct_post_code'] = str_replace('000', '', $ret['lct_post_code']);
  3738. }
  3739. $arr = array(
  3740. 'ret_val' => true,
  3741. 'ret_msg' => '',
  3742. 'loc_key' => $ret['lct_id'] . '_' . $ret['lct_level'],
  3743. 'loc_name' => $ret['lct_name'] . '-' . $ret['lct_post_code']
  3744. );
  3745. } else {
  3746. $arr['ret_msg'] = 'Departement not found (lct_post_code = ' . $lct_post_code . ')';
  3747. return $arr;
  3748. }
  3749. } else if ($len_post_code == 5) { // ville
  3750. $sql = "
  3751. SELECT lgn_id AS lct_id, '99' AS lct_level, lgn_name_fr AS lct_name, 'tous-codes-postaux' AS lct_post_code
  3752. FROM TM_LOCGN_FR
  3753. WHERE lgn_post_code = '$lct_post_code'
  3754. ";
  3755. //echo "<hr><br>".$sql."<br><hr>";
  3756. $res = pdoquery($sql);
  3757. //var_dump($res);
  3758. if (count($res) > 0) { // regroupement de ville par nom, grande ville (ie même ville avec plusieurs CP)
  3759. $ret = $res[0];
  3760. $arr = array(
  3761. 'ret_val' => true,
  3762. 'ret_msg' => '',
  3763. 'loc_key' => $ret['lct_id'] . '_' . $ret['lct_level'],
  3764. 'loc_name' => $ret['lct_name'] . '-' . $ret['lct_post_code']
  3765. );
  3766. } else { // petite ville (ie ville avec un seul CP)
  3767. $sql = "
  3768. SELECT lct_id, lct_level, lct_name, lct_post_code, lgc_id, lgn_id
  3769. FROM TM_LOC_FR
  3770. WHERE lct_post_code = '$lct_post_code'
  3771. AND lct_level = 2
  3772. ";
  3773. //echo "<hr><br>".$sql."<br><hr>";
  3774. $res = pdoquery($sql);
  3775. //var_dump($res);
  3776. if (count($res) > 0) {
  3777. $ret = $res[0];
  3778. $arr = array(
  3779. 'ret_val' => true,
  3780. 'ret_msg' => '',
  3781. 'loc_key' => $ret['lct_id'] . '_' . $ret['lct_level'],
  3782. 'loc_name' => $ret['lct_name'] . '-' . $ret['lct_post_code']
  3783. );
  3784. } else {
  3785. $arr['ret_msg'] = 'Town not found (lct_post_code = ' . $lct_post_code . ')';
  3786. return $arr;
  3787. }
  3788. }
  3789. } else { // problème quelque part...
  3790. $arr['ret_msg'] = 'Bad postcode width (lct_post_code = ' . $lct_post_code . ')';
  3791. }
  3792. return $arr;
  3793. }
  3794. /**
  3795. * getCityOrDeptInfoByPostCode
  3796. * Returns locality info by postcode
  3797. *
  3798. * @param string $postcode
  3799. * @param bool $doGroupBy Wether to return lgn_id / lgc_id or not.
  3800. */
  3801. function getCityOrDeptInfoByPostCode($postcode, $doGroupBy) {
  3802. $isCity = (strlen($postcode) == 5 && is_numeric($postcode));
  3803. $isDept = ((strlen($postcode) == 2 || strlen($postcode) == 3) && (is_numeric($postcode) || in_array($postcode, array('2A', '2B'))));
  3804. // Si le code postal n'est pas valide, on retourne null.
  3805. if(!$isCity && !$isDept)
  3806. return false;
  3807. if($isDept && !in_array($postcode, array('2A', '2B')) && strlen($postcode) == 2) {
  3808. // Si le code postal est celui d'un département
  3809. // et que ce n'est pas la corse, on complète par des 0.
  3810. $postcode = $postcode.'000';
  3811. }
  3812. $sql = "
  3813. 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
  3814. FROM TM_LOC_FR
  3815. WHERE lct_post_code = '$postcode'
  3816. AND lct_level IN (1,2)
  3817. ORDER BY lct_level ".($isDept ? 'ASC' : 'DESC')
  3818. ;
  3819. $res = pdoquery($sql);
  3820. if($doGroupBy && ($res[0]['lgc_id'] > 0 || $res[0]['lgn_id'] > 0)) {
  3821. // Si $doGroupBy, on vérifie si les résultats correspondent
  3822. // à des regroupements
  3823. if($res[0]['lgn_id'] > 0) {
  3824. $sql = "
  3825. 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
  3826. FROM TM_LOCGN_FR
  3827. WHERE lgn_id = '".$res[0]['lgn_id']."'
  3828. ";
  3829. $res = pdoquery($sql);
  3830. } else if($res[0]['lgc_id'] > 0) {
  3831. $sql = "
  3832. 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
  3833. FROM TM_LOCGC_FR
  3834. WHERE lgc_id = '".$res[0]['lgc_id']."'
  3835. ";
  3836. $res = pdoquery($sql);
  3837. }
  3838. }
  3839. if(is_array($res)) {
  3840. return $res[0];
  3841. } else
  3842. return false;
  3843. }
  3844. /**
  3845. * Return property value from property name (for bien_ville_*.php)
  3846. *
  3847. * @param unknown_type $prp
  3848. * @return unknown
  3849. */
  3850. function value_property($prp, $do_use_label2 = false) {
  3851. global $_ADVANCED_SEARCH_TYPES;
  3852. $val = -1;
  3853. $prp = strtolower($prp);
  3854. foreach ($_ADVANCED_SEARCH_TYPES as $type) {
  3855. // Gérer le cas bureau / commerce, châlet ...
  3856. if (isset($type['label2']) && !empty($type['label2'])) {
  3857. $label = $type['label2']; // utile pour la coloc.
  3858. } else {
  3859. $label = $type['label'];
  3860. }
  3861. $label = str_replace(' / ', '-', TextNoAccent($label));
  3862. $label = prepareToUrl($label);
  3863. if ($prp == strtolower($label)) {
  3864. $val = $type['value'];
  3865. return $val;
  3866. }
  3867. }
  3868. return $val;
  3869. }
  3870. /**
  3871. * Return transaction value from transaction name (for bien_ville_*.php)
  3872. *
  3873. * @param unknown_type $trs
  3874. * @return unknown
  3875. */
  3876. function value_transact($trs) {
  3877. $val = -1;
  3878. $trs = strtolower($trs);
  3879. switch ($trs) {
  3880. case "location":
  3881. $val = 2;
  3882. break;
  3883. case "vente":
  3884. case "achat":
  3885. default:
  3886. $val = 1;
  3887. break;
  3888. }
  3889. return $val;
  3890. }
  3891. /**
  3892. * Return number rooms value from number rooms passed (for bien_ville_*.php)
  3893. *
  3894. * @param unknown_type $num
  3895. * @param unknown_type $pcs
  3896. * @param unknown_type $prp
  3897. * @return unknown
  3898. */
  3899. function value_roomsnum($num, $pcs, $prp) {
  3900. $val = -1;
  3901. if ($prp == "appartement") {
  3902. if (in_array($num, array("1", "2", "3", "4"))) {
  3903. if (((intval($num) == 1) && ($pcs == "piece")) || ((intval($num) >= 2) && ($pcs == "pieces"))) {
  3904. $val = intval($num);
  3905. }
  3906. }
  3907. } else if ($prp == "maison") {
  3908. if (in_array($num, array("1", "2", "3", "4"))) {
  3909. if (((intval($num) == 1) && ($pcs == "piece")) || ((intval($num) >= 2) && ($pcs == "pieces"))) {
  3910. $val = intval($num);
  3911. }
  3912. }
  3913. }
  3914. return $val;
  3915. }
  3916. /**
  3917. * Enter description here...
  3918. *
  3919. * @return unknown
  3920. */
  3921. function is_mobile() {
  3922. $op = strtolower($_SERVER['HTTP_X_OPERAMINI_PHONE']);
  3923. $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
  3924. $ac = strtolower($_SERVER['HTTP_ACCEPT']);
  3925. $isMobile = (strpos($ac, 'application/vnd.wap.xhtml+xml') !== false
  3926. || $op != ''
  3927. || strpos($ua, 'sony') !== false
  3928. || strpos($ua, 'symbian') !== false
  3929. || strpos($ua, 'nokia') !== false
  3930. || strpos($ua, 'samsung') !== false
  3931. || strpos($ua, 'mobile') !== false
  3932. || strpos($ua, 'windows ce') !== false
  3933. || strpos($ua, 'epoc') !== false
  3934. || strpos($ua, 'opera mini') !== false
  3935. || strpos($ua, 'nitro') !== false
  3936. || strpos($ua, 'j2me') !== false
  3937. || strpos($ua, 'midp-') !== false
  3938. || strpos($ua, 'cldc-') !== false
  3939. || strpos($ua, 'netfront') !== false
  3940. || strpos($ua, 'mot') !== false
  3941. || strpos($ua, 'up.browser') !== false
  3942. || strpos($ua, 'up.link') !== false
  3943. || strpos($ua, 'audiovox') !== false
  3944. || strpos($ua, 'blackberry') !== false
  3945. || strpos($ua, 'ericsson,') !== false
  3946. || strpos($ua, 'panasonic') !== false
  3947. || strpos($ua, 'philips') !== false
  3948. || strpos($ua, 'sanyo') !== false
  3949. || strpos($ua, 'sharp') !== false
  3950. || strpos($ua, 'sie-') !== false
  3951. || strpos($ua, 'portalmmm') !== false
  3952. || strpos($ua, 'blazer') !== false
  3953. || strpos($ua, 'avantgo') !== false
  3954. || strpos($ua, 'danger') !== false
  3955. || strpos($ua, 'palm') !== false
  3956. || strpos($ua, 'series60') !== false
  3957. || strpos($ua, 'palmsource') !== false
  3958. || strpos($ua, 'pocketpc') !== false
  3959. || strpos($ua, 'smartphone') !== false
  3960. || strpos($ua, 'rover') !== false
  3961. || strpos($ua, 'ipaq') !== false
  3962. || strpos($ua, 'au-mic,') !== false
  3963. || strpos($ua, 'alcatel') !== false
  3964. || strpos($ua, 'ericy') !== false
  3965. || strpos($ua, 'up.link') !== false
  3966. || strpos($ua, 'vodafone/') !== false
  3967. || strpos($ua, 'wap1.') !== false
  3968. || strpos($ua, 'wap2.') !== false
  3969. || strpos($ua, 'Mobile WVGA') !== false
  3970. || strpos($ua, 'Mobile Safari') !== false)
  3971. && strpos($ua, 'ipad') === false
  3972. ;
  3973. // $isMobile
  3974. return $isMobile;
  3975. }
  3976. /**
  3977. * Enter description here...
  3978. *
  3979. * @return unknown
  3980. */
  3981. function mobile_redirect($uri, $ad) {
  3982. global $_global;
  3983. $domaine_use = URL_SITE_MOBILE;
  3984. if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'iphone') || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'ipod')) {
  3985. $domaine_use = URL_SITE_IPHONE;
  3986. }
  3987. if (strpos($uri, "detail")) {
  3988. $uri = str_replace("/", "", $uri);
  3989. $uri = explode("-", $uri);
  3990. // property
  3991. $property = strtolower($ad["property_type"]);
  3992. // location
  3993. $location = strtolower($ad["hierarchy"][2]["lct_name"]);
  3994. $location = str_replace(" ", "_", $location);
  3995. if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'iphone') || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'ipod')) {
  3996. $url = $domaine_use . "/detail/detail_annonce.html?id=" . $ad["id"] . "&univ=" . $_global["univers"];
  3997. return $url;
  3998. }
  3999. return $domaine_use . "/annonce-" . $uri[1] . "-" . $property . "-" . $location . "-" . strtolower($ad["id"]) . ".html";
  4000. } else {
  4001. return $domaine_use;
  4002. }
  4003. }
  4004. /**
  4005. * Close HTML tags of an HTML string
  4006. * voir http://www.siteduzero.com/forum-83-480977-p1-fermeture-de-balise-xhtml-automatique.html
  4007. *
  4008. * @param unknown_type $xhtml
  4009. * @return unknown
  4010. */
  4011. function close_xhtml($xhtml) {
  4012. $tags = array();
  4013. 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]) {
  4014. if ($tag[1][0] != '/') {
  4015. $tags[] = $tag[2][0];
  4016. } else if ($tag[2][0] == end($tags)) {
  4017. array_pop($tags);
  4018. } else {
  4019. $xhtml = substr_replace($xhtml, '', $tag[0][1], strlen($tag[0][0]));
  4020. }
  4021. }
  4022. $xhtml = preg_replace('`<[^>]*$`', '', $xhtml);
  4023. while ($tag = array_pop($tags)) {
  4024. $xhtml .= '</' . $tag . '>';
  4025. }
  4026. return $xhtml;
  4027. }
  4028. /**
  4029. * Close a Path with a "/"
  4030. * SOFLOU
  4031. * @param $path
  4032. * @return $path."/";
  4033. */
  4034. function enclose_path($path) {
  4035. if (substr($path, -1) <> "/") {
  4036. $path .= "/";
  4037. }
  4038. return $path;
  4039. }
  4040. /**
  4041. * Get locality label from search_parameters and field num (locname1, locname2, locname3)
  4042. * using loc_level to find right label (1, 2, 98, 99)
  4043. *
  4044. * @param Array $search_parameters
  4045. * @param Integer $num
  4046. * @return String label
  4047. */
  4048. function getLocalityLabel($search_parameters, $num, &$loc_key = "") {
  4049. if (isset($search_parameters["loc_levels"][$num])) {
  4050. // Si la clé est incorrecte, on ignore cette localité
  4051. if (!preg_match('`^[0-9]+_[0-9]{1,2}$`', $search_parameters["loc_keys"][$num]))
  4052. return LABEL_DEFAULT_LOCALITY;
  4053. // Renvoyer la clé de cette localité
  4054. $loc_key = $search_parameters["loc_keys"][$num];
  4055. $code_postal = $search_parameters["lzip"][$num];
  4056. switch ($search_parameters["loc_levels"][$num]) {
  4057. case 0:
  4058. //Région
  4059. return $search_parameters["loc_names"][$num] . ' (' . $code_postal . ')';
  4060. case 1:
  4061. // Departement
  4062. $domtom = array('971', '972', '973', '974', '975', '976', '984', '986', '987', '988');
  4063. // Traitement particulier pour les dom-tom
  4064. if (in_array($code_postal, $domtom))
  4065. return $search_parameters["loc_names"][$num] . ' (' . $code_postal . ')';
  4066. else
  4067. return $search_parameters["loc_names"][$num] . ' (' . $search_parameters["szip"][$num] . ')';
  4068. case 2:
  4069. // Ville
  4070. return $search_parameters["loc_names"][$num] . ' (' . $code_postal . ')';
  4071. case 98:
  4072. // Toutes communes
  4073. return 'TOUTES COMMUNES (' . $code_postal . ')';
  4074. case 99:
  4075. // Tous departements
  4076. return $search_parameters["loc_names"][$num] . ' (TOUS CODES POSTAUX)';
  4077. default:
  4078. return LABEL_DEFAULT_LOCALITY;
  4079. }
  4080. }
  4081. else
  4082. return LABEL_DEFAULT_LOCALITY;
  4083. }
  4084. /**
  4085. * Convertir la chaine composée de 1 et 0 en hexadecimal.
  4086. * Si la chaine est trop petite une fois convertie, on remplie avec des 0 à droite
  4087. * Florian Planchon
  4088. */
  4089. function stringToHexa($string, $size) {
  4090. return str_pad(base_convert($string, 2, 16), $size, 0, STR_PAD_LEFT);
  4091. }
  4092. /**
  4093. * Convertir la chaine hexadeimal en suite de 1 et de 0.
  4094. * Si la chaine est trop petite une fois convertie, on remplie avec des 0 à droite
  4095. * Florian Planchon
  4096. */
  4097. function hexaToString($string, $size) {
  4098. return str_pad(base_convert($string, 16, 2), $size, 0, STR_PAD_LEFT);
  4099. }
  4100. /* Renvoie Vrai si la valeur binaire, qui peut être très longue, correspond au masque binaire */
  4101. function matchMask($value, $mask) {
  4102. if (strpos($mask, '1') === false)
  4103. return false;
  4104. $maxLength = PHP_INT_SIZE * 8;
  4105. // split
  4106. $o1 = str_split($value, $maxLength);
  4107. $o2 = str_split(str_pad(trim($mask), strlen($value), '0'), $maxLength);
  4108. $res = '';
  4109. $runs = count($o1);
  4110. for ($i = 0; $i < $runs; $i++) {
  4111. $mask_part = bindec($o2[$i]);
  4112. if (( bindec($o1[$i]) & $mask_part ) !== $mask_part)
  4113. return false;
  4114. }
  4115. return true;
  4116. }
  4117. /* Faire une opération AND entre deux chaines binaires qui peuvent être très longues */
  4118. function bitAnd($value1, $value2) {
  4119. $maxLength = PHP_INT_SIZE * 8;
  4120. // split
  4121. $o1 = str_split($value1, $maxLength);
  4122. $o2 = str_split(str_pad('', strlen($value1), $value2), $maxLength);
  4123. $res = '';
  4124. $runs = count($o1);
  4125. for ($i = 0; $i < $runs; $i++)
  4126. $res .= decbin(bindec($o1[$i]) & bindec($o2[$i]));
  4127. return $res;
  4128. }
  4129. /* Faire une opération OR entre deux chaines binaires qui peuvent être très longues */
  4130. function bitOr($value1, $value2) {
  4131. $maxLength = PHP_INT_SIZE * 8;
  4132. // split
  4133. $o1 = str_split($value1, $maxLength);
  4134. $o2 = str_split(str_pad('', strlen($value1), $value2), $maxLength);
  4135. $res = '';
  4136. $runs = count($o1);
  4137. for ($i = 0; $i < $runs; $i++)
  4138. $res .= decbin(bindec($o1[$i]) | bindec($o2[$i]));
  4139. return $res;
  4140. }
  4141. /* Fonction utilisée pour convertir une ancienne valeur de types de bien en une nouvelle */
  4142. function convert_nb_rooms($nb_room, $nb_room_min, $nb_room_max, $size = 8) {
  4143. $nb_rooms = str_repeat('0', $size);
  4144. if ($nb_room != 'a' && $nb_room != null) {
  4145. if ($nb_room == 0)
  4146. $nb_rooms[0] = '1';
  4147. elseif ($nb_room != -1) {
  4148. /*
  4149. // $nb_room = 123 => 1, 2, 3 pièces
  4150. $nb_rooms_part = preg_split('//', $nb_room, -1, PREG_SPLIT_NO_EMPTY);
  4151. foreach( $nb_rooms_part as $part ) {
  4152. if( --$part < $size ) $nb_rooms[ $part ] = '1';
  4153. }
  4154. */
  4155. // $nb_rooms = 1 => à partir de 2 pièces
  4156. for ($i = $nb_room; $i < $size; $i++)
  4157. $nb_rooms[$i] = '1';
  4158. }
  4159. } else {
  4160. $nb_room_min = (int) $nb_room_min;
  4161. $nb_room_max = (int) $nb_room_max;
  4162. // Gérer le cas où aucune valeur n'est précisée
  4163. if ($nb_room_min == 0 && $nb_room_max == 0)
  4164. return $nb_rooms;
  4165. if ($nb_room_min < 1)
  4166. $nb_room_min = 1;
  4167. if ($nb_room_max < 1)
  4168. $nb_room_max = 1;
  4169. if ($nb_room_min > $nb_room_max) {
  4170. $tmp = $nb_room_min;
  4171. $nb_room_min = $nb_room_max;
  4172. $nb_room_max = $tmp;
  4173. }
  4174. if ($nb_room_max > $size)
  4175. $nb_room_max = $size;
  4176. for ($i = $nb_room_min; $i <= $nb_room_max; $i++)
  4177. $nb_rooms[$i - 1] = '1';
  4178. }
  4179. return $nb_rooms;
  4180. }
  4181. /* Fonction utilisée pour convertir une ancienne valeur de types de bien en une nouvelle */
  4182. function convert_property_value($value, $size = 40) {
  4183. // Faire le lien entre les anciens groupes et les valeurs actuelles
  4184. $_LI_OLD_REALESTATEGROUPS[0] = array(1, 6);
  4185. $_LI_OLD_REALESTATEGROUPS[1] = array(2, 7, 8, 13, 14, 15, 16);
  4186. $_LI_OLD_REALESTATEGROUPS[2] = array(3);
  4187. $_LI_OLD_REALESTATEGROUPS[3] = array(4);
  4188. $_LI_OLD_REALESTATEGROUPS[4] = array(5);
  4189. $_LI_OLD_REALESTATEGROUPS[5] = array(9);
  4190. $_LI_OLD_REALESTATEGROUPS[6] = array(12);
  4191. $_LI_OLD_REALESTATEGROUPS[7] = array(11, 17);
  4192. // ex : 11111111 => 1111111110111111100000000000000000000000
  4193. $new_value = str_repeat('0', $size);
  4194. if (is_array($value)) {
  4195. $max_length = count($_LI_OLD_REALESTATEGROUPS);
  4196. foreach ($value as $group_id) {
  4197. if (isset($_LI_OLD_REALESTATEGROUPS[$group_id])) {
  4198. foreach ($_LI_OLD_REALESTATEGROUPS[$i] as $property_type_id_orig)
  4199. $new_value[$property_type_id_orig - 1] = '1';
  4200. }
  4201. }
  4202. } else {
  4203. // Déterminer la taille maxi de parcours de la valeur
  4204. $length = strlen($value);
  4205. $max_length = count($_LI_OLD_REALESTATEGROUPS);
  4206. if ($length > $max_length)
  4207. $length = $max_length;
  4208. // Mettre un 1 pour tous les types donc les groupes sont à 1
  4209. for ($i = 0; $i < $length; $i++) {
  4210. if ($value[$i] == '1') {
  4211. foreach ($_LI_OLD_REALESTATEGROUPS[$i] as $property_type_id_orig)
  4212. $new_value[$property_type_id_orig - 1] = '1';
  4213. }
  4214. }
  4215. }
  4216. return $new_value;
  4217. }
  4218. function searchPropertyTypeIdOrig($id_orig, $get_group = false) {
  4219. global $_LI_REALESTATEGROUPS;
  4220. --$id_orig;
  4221. foreach ($_LI_REALESTATEGROUPS as $id => $group) {
  4222. if ($group['value2'][$id_orig] == 1)
  4223. return (bool) $get_group ? $id : $group['value2'];
  4224. }
  4225. return null;
  4226. }
  4227. function searchPropertyTypeIdOrigAdv($id_orig, $get_group = false) {
  4228. global $_ADVANCED_SEARCH_TYPES;
  4229. $value_orig = ",{$id_orig},";
  4230. foreach ($_ADVANCED_SEARCH_TYPES as $id => $group) {
  4231. if (strpos(",{$group['value']},", $value_orig) !== false) {
  4232. if ((bool) $get_group) {
  4233. return $id;
  4234. } else {
  4235. $result = '0000000000000000000000000000000000000000';
  4236. $ids = explode(',', $group['value']);
  4237. foreach ($ids as $id) {
  4238. $result[$id - 1] = 1;
  4239. }
  4240. return $result;
  4241. }
  4242. }
  4243. }
  4244. return null;
  4245. }
  4246. function getCheckedFields($groups, $fieldValue, $maskAllChecked = "", $bLabel = false) {
  4247. $length = strlen($fieldValue);
  4248. $allChecked = ( $maskAllChecked != '' && matchMask($fieldValue, $maskAllChecked) );
  4249. // Gerer les cas ou le resultat sera toujours un tableau vide ou si tout est coché
  4250. if ($allChecked || !is_array($groups) || empty($groups) || strpos($fieldValue, '1') === false)
  4251. return array();
  4252. $result = $types = array();
  4253. foreach ($groups as $index => $group) {
  4254. if (isset($group['value']))
  4255. $group = $group['value'];
  4256. $types[$index] = explode(',', $group);
  4257. }
  4258. $size = count($groups);
  4259. for ($offset = 0; $offset < $length; $offset++) {
  4260. if ($fieldValue[$offset] == '1') {
  4261. // Trouver le groupe qui contient cette valeur
  4262. foreach ($groups as $index => $group) {
  4263. $current_types = $types[$index];
  4264. if (in_array($offset + 1, $current_types)) {
  4265. $result[] = $bLabel ? $group['label'] : $index;
  4266. // Mettre à 0 dans value les valeurs de ce groupe
  4267. foreach ($current_types as $type)
  4268. $fieldValue[$type - 1] = '0';
  4269. // Le premier groupe trouvé est le seul qui contient la valeur
  4270. break;
  4271. }
  4272. }
  4273. }
  4274. }
  4275. return $result;
  4276. }
  4277. function debug() {
  4278. global $_global;
  4279. ob_start();
  4280. echo '<div style="text-align:left; margin-bottom:10px">';
  4281. $raw = debug_backtrace();
  4282. $id_debug = 0;
  4283. // Recuperer les arguments passes a la fonction debug
  4284. $arguments = $raw[0]['args'];
  4285. // Afficher le pseudo qui devrait etre le premier parametre
  4286. if (empty($arguments[0]) || is_array($arguments[0]))
  4287. $user = 'Inconnu';
  4288. else {
  4289. $user = $arguments[0];
  4290. unset($arguments[0]);
  4291. }
  4292. echo '<h2 style="margin:8px 2px 4px">== ' . $user . ' [' . $_global['self'] . '] ==</h2>';
  4293. // Parser les arguments passes a la fonction debug
  4294. echo '<h2 style="margin:8px 2px 4px">Parametres :</h2><div style="padding-left:25px">';
  4295. $args = '';
  4296. foreach ($arguments as $arg)
  4297. $args .= debug_getArg($arg, ++$id_debug);
  4298. echo substr($args, 2) . '</div>';
  4299. // On affiche pas l'appel à la fonction debug
  4300. unset($raw[0]);
  4301. // Afficher tous les autres appels de fonction et leurs arguments
  4302. echo '<h2 style="margin:8px 2px 4px">BackTrace :</h2><div style="padding-left:25px">';
  4303. foreach ($raw as $entry) {
  4304. $args = '';
  4305. foreach ($entry['args'] as $arg)
  4306. $args .= debug_getArg($arg, ++$id_debug);
  4307. echo '<p style="margin:4px 0px">',
  4308. '<b style="display: inline-block; width: 5em; text-align: right; margin-right: 4px;">File:</b> ' . $entry['file'] . ' (Line: ' . $entry['line'] . ')<br />',
  4309. '<b style="display: inline-block; width: 5em; text-align: right; margin-right: 4px;">Function:</b> ' . $entry['function'] . ' ( ' . substr($args, 2) . ' )',
  4310. '</p>';
  4311. }
  4312. echo '</div></div>';
  4313. ob_end_flush();
  4314. }
  4315. // Fonction pour afficher un paramètre sous forme de chaine
  4316. function debug_getArg($arg, $id_debug) {
  4317. if (is_array($arg))
  4318. 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>';
  4319. elseif (is_object($arg))
  4320. 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>';
  4321. elseif (is_null($arg))
  4322. return ', <span style="color:green">null</span>';
  4323. elseif (is_string($arg))
  4324. return ', <span style="color:gray">`' . $arg . '`</span>';
  4325. return ', <span style="color:red">' . $arg . '</span>';
  4326. }
  4327. function debug2($var, $line = 0, $file = 0) {
  4328. 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");
  4329. if (is_array($var)) {
  4330. echo '<p>';
  4331. debug_array($var);
  4332. echo '</p>';
  4333. } else {
  4334. echo "<p>" . $var . "</p>";
  4335. }
  4336. echo "</div>";
  4337. }
  4338. function debug_array($var) {
  4339. foreach ($var as $key => $value) {
  4340. if (is_array($value)) {
  4341. echo '<b>- ' . $key . ' : </b>';
  4342. echo "<ul style='margin:0 0 0 20px;'>";
  4343. debug_array($value);
  4344. echo "</ul>";
  4345. } else {
  4346. echo "<li style='list-style:none; margin: 0 0 0 20px;'>" . $key . " => " . $value . "</li>";
  4347. }
  4348. }
  4349. }
  4350. //Fonction pour transformer une chaîne de caractères en URL.
  4351. function str_to_url($string) {
  4352. // Supprimer tous les accents + strtolower
  4353. $string = prepareToUrl($string);
  4354. // Remplacer les caractères spéciaux par un tiret
  4355. $string = str_replace(array("=", "°", "«", "»", "/", "<", ">", ",", ";", ":", "*", "…"), '-', $string);
  4356. // Remplacer le symbole euro
  4357. $string = str_replace('€', 'euros', $string);
  4358. // Supprimer les doubles tirets et les tirets de fin de ligne
  4359. $cleanUrl = preg_replace(array('/--+/', '/-$/', '/[^-a-zA-Z0-9@]/'), array('-', '', ''), $string);
  4360. return $cleanUrl;
  4361. }
  4362. function uriToSeo($request_uri, $keep_quotes = false) {
  4363. global $convert_from_to;
  4364. // Retirer la chaine des paramètres ?param1=..&param2=..
  4365. $parts = explode('?', $request_uri);
  4366. // Eviter d'avoir des caractères html encodés qui subsistent
  4367. $uri = urldecode($parts[0]);
  4368. // Conserver les parametres pour les rajouter à la fin
  4369. // On ne fait pas de traitements dessus
  4370. $params = isset($parts[1]) ? '?' . $parts[1] : '';
  4371. // Echapper le underscore _ qui constitue le(s) lockey(s)
  4372. // Echapper les slash qui constituent l'url
  4373. $uri = preg_replace('`_([0-9]*[,-.])`', '£$1', $uri);
  4374. $uri = str_replace('/', 'µ', $uri);
  4375. if ($keep_quotes)
  4376. $uri = str_replace('\'', '¤', $uri);
  4377. // Supprimer tous les caractères spéciaux et remplacer par des '-'
  4378. $uri = strtr($uri, $convert_from_to);
  4379. // Annuler l'echappement de l'underscore et du slash
  4380. $uri = str_replace('£', '_', $uri);
  4381. $uri = str_replace('µ', '/', $uri);
  4382. if ($keep_quotes)
  4383. $uri = str_replace('¤', '\'', $uri);
  4384. // Remplacer les tirets consecutifs par un seul
  4385. $uri = preg_replace('`-{2,}`', '-', $uri);
  4386. //die($_SERVER['REQUEST_URI'].'<br />'.strtolower($uri).$params);
  4387. // Renvoyer la chaine en minsucule
  4388. return strtolower($uri) . $params;
  4389. }
  4390. // Return true if city is in fact an arrondissement of a french city
  4391. function isArrondCity($city) {
  4392. $ret = array(false, "");
  4393. if (isset($city["lct_id"]) && !empty($city["lct_id"])) { // si lct_id défini
  4394. $lct_id = $city["lct_id"];
  4395. //echo "[lct_id = $lct_id]"; //exit();
  4396. $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);
  4397. $lct_ids_arrond_marseille = array(36102, 36104, 36105, 36106, 36107, 36108, 36109, 36110, 36111, 36112, 36113, 36114, 36115, 36116, 36117, 36118);
  4398. $lct_ids_arrond_lyon = array(36119, 36120, 36121, 36122, 36123, 36124, 36125, 36126, 36127);
  4399. if (in_array($lct_id, $lct_ids_arrond_paris)) {
  4400. $ret = array(true, "paris");
  4401. } else if (in_array($lct_id, $lct_ids_arrond_marseille)) {
  4402. $ret = array(true, "marseille");
  4403. } else if (in_array($lct_id, $lct_ids_arrond_lyon)) {
  4404. $ret = array(true, "lyon");
  4405. }
  4406. } else if (isset($city["lct_name"]) && !empty($city["lct_name"])) { // si lct_name défini
  4407. $lct_name = $city["lct_name"];
  4408. //echo "[lct_name = $lct_name]"; //exit();
  4409. $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");
  4410. $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");
  4411. $lct_names_arrond_lyon = array("lyon 1er", "lyon 2e", "lyon 3e", "lyon 4e", "lyon 5e", "lyon 6e", "lyon 7e", "lyon 8e", "lyon 9e");
  4412. if (in_array($lct_name, $lct_names_arrond_paris)) {
  4413. $ret = array(true, "paris");
  4414. } else if (in_array($lct_name, $lct_names_arrond_marseille)) {
  4415. $ret = array(true, "marseille");
  4416. } else if (in_array($lct_name, $lct_names_arrond_lyon)) {
  4417. $ret = array(true, "lyon");
  4418. }
  4419. }
  4420. return $ret;
  4421. }
  4422. /* NEXITY */
  4423. // returns a phone number stripped from weird characters
  4424. function clean_phone($value, $block = false) {
  4425. if ($value == "") {
  4426. return;
  4427. }
  4428. $value = str_replace(" ", "", $value);
  4429. $value = str_replace(".", "", $value);
  4430. $value = str_replace("+33(0)", "0", $value);
  4431. if ($block == true) {
  4432. return $value;
  4433. } else {
  4434. return substr($value, 0, 2) . " " . substr($value, 2, 2) . " " . substr($value, 4, 2) . " " . substr($value, 6, 2) . " " . substr($value, 8, 2);
  4435. }
  4436. }
  4437. // retuns linkeo string
  4438. function build_linkeo_string($index, $number) {
  4439. $phone = clean_phone($number, true);
  4440. return "click_to_call(" . $index . ", " . ((date("G") > 9 && date("G") < 19) ? 1 : 0) . ", '" . $phone . "', '" . md5($phone . LINKEO_KEY_1 . LINKEO_KEY_2) . "')";
  4441. }
  4442. /**
  4443. * UPDATE NEXITY STAT ON STAT DB
  4444. *
  4445. * @param array $prg_data program data
  4446. * @param String $prg_id program ID
  4447. * @param $mode UPDATE click or PRINT STATS
  4448. *
  4449. * @return void
  4450. */
  4451. function Update_nexity_stat($prg_data, $prg_id, $mode = "prints") {
  4452. include_once(URL_LIB . '/synchrostats.class.php');
  4453. $SynchroStats = new SynchroStats($_SERVER['SERVER_ADDR'], "neuf_relay");
  4454. /*
  4455. $is_nexity = 1, s'il s'agit d'un programme Nexity
  4456. $position = 1 ou 2, selon le relais
  4457. */
  4458. $position = 2;
  4459. $url = $prg_data['prg_url'];
  4460. $id_presto = $prg_data["id_presto"];
  4461. $id_agence = $prg_data["id_agence"];
  4462. $post_code = $prg_data["post_code"];
  4463. $is_nexity = 1;
  4464. switch ($mode) {
  4465. case "clicks":
  4466. //-- REDIRECTION VERS LE SITE DU PARTENAIRE
  4467. $PARTDATA["id_presto"] = $id_presto;
  4468. $PARTDATA["id_agence"] = $id_agence;
  4469. $PARTDATA["id_programme"] = $prg_id;
  4470. $PARTDATA["url"] = $url;
  4471. $PARTDATA["post_code"] = $post_code;
  4472. $PARTDATA["is_clic"] = "1";
  4473. $PARTDATA["is_nexity"] = $is_nexity;
  4474. break;
  4475. case "none":
  4476. //-- AFFICHAGE D'AUCUN RELAI TROUVE (PAS UTILISE POUR L'INSTANT)
  4477. $PARTDATA["post_code"] = $post_code;
  4478. $PARTDATA["position"] = $position;
  4479. $PARTDATA["is_shown"] = "1";
  4480. break;
  4481. default:
  4482. //-- AFFICHAGE D'UN RELAI AFFICHE
  4483. $PARTDATA["id_presto"] = $id_presto;
  4484. $PARTDATA["id_agence"] = $id_agence;
  4485. $PARTDATA["id_programme"] = $prg_id;
  4486. $PARTDATA["post_code"] = $post_code;
  4487. $PARTDATA["position"] = $position;
  4488. $PARTDATA["url"] = $url;
  4489. $PARTDATA["is_shown"] = "1";
  4490. $PARTDATA["is_nexity"] = $is_nexity;
  4491. break;
  4492. }
  4493. /*
  4494. echo "<pre>";
  4495. print_r($PARTDATA);
  4496. echo "</pre>";
  4497. */
  4498. $SynchroStats->SynchroStats_Posting($PARTDATA);
  4499. }
  4500. // Retourne les coordonnees GPS d'une localite
  4501. function get_loc_gps($lct_id, $lgc = false) {
  4502. if ($lgc == 'lgc') {
  4503. $sql = "SELECT lgc_lat as lat, lgc_long as lng FROM T_LOCGROUPCODE_LGC_FR WHERE lgc_id = $lct_id LIMIT 1";
  4504. } elseif ($lgc == 'lgn') {
  4505. $sql = "SELECT lgn_lat as lat, lgn_long as lng FROM T_LOCGROUPNAME_LGN_FR WHERE lgn_id = $lct_id LIMIT 1";
  4506. } else {
  4507. $sql = "SELECT lct_lat as lat, lct_long as lng FROM TM_LOC_FR WHERE lct_id = $lct_id LIMIT 1";
  4508. }
  4509. global $_global;
  4510. if ($_global["debug"] == 3) {
  4511. echo "get_loc_gps()<br />";
  4512. echo $sql . "<br />";
  4513. echo "<hr />";
  4514. }
  4515. $res = pdoquery($sql);
  4516. return $res;
  4517. }
  4518. /*
  4519. * Return the edition name and code from the post code of a locality
  4520. */
  4521. function get_edition_from_post_code($post_code) {
  4522. $obj = null;
  4523. $sql = "
  4524. SELECT edt_code,
  4525. edt_name
  4526. FROM TM_EDT_LOC_FR el
  4527. INNER JOIN TM_EDT_FR e
  4528. ON el.edtloc_edt_code = e.edt_code
  4529. WHERE el.edtloc_loc_post_code = '" . $post_code . "'
  4530. LIMIT 1
  4531. ";
  4532. //echo "<hr>$sql</hr><br/>";
  4533. $res = pdoquery($sql);
  4534. if ($_global["debug"] == 3) {
  4535. echo "get_edition_from_post_code()<br />";
  4536. echo $sql . "<br />";
  4537. echo "<hr />";
  4538. }
  4539. if (count($res) > 0) {
  4540. $obj = $res[0];
  4541. }
  4542. return $obj;
  4543. }
  4544. /**
  4545. * Generate content snapshot (img or text + link to agency)
  4546. *
  4547. * @param String $id_presto - Agency id presto
  4548. * @param String $id_agence - Agency id
  4549. * @param String $ag_website - Agency website
  4550. * @param Boolean $return_link - Include the content into a link to agency website
  4551. * @param Boolean $use_default_img - Return a default image instead of default string
  4552. * @param String $default_img - Logo si pas de snapshot (notamment pour les exclus)
  4553. * @return String snaphost
  4554. */
  4555. function get_snapshot_content($id_presto_agence_md5, $id_agence, $ag_website, $return_link = null, $use_default_img = false, $default_img = '', $ag_name = '') {
  4556. //function get_snapshot_content($id_presto, $id_agence, $ag_website, $return_link = null, $use_default_img = false, $default_img = '', $ag_name = '') {
  4557. //echo $id_presto." <<<";echo $id_agence." <<<";
  4558. $alt_string = "Cliquez ici pour visiter le site de l'agence.";
  4559. if ($use_default_img) {
  4560. if ($default_img == '') {
  4561. $default_content = '<img border="0" src="' . get_urlmmf('/snapshot/nothumb.jpg') . '" height="120" width="160" alt="' . $ag_name . '" />';
  4562. } else {
  4563. $default_content = '<img border="0" src="' . $default_img . '" alt="' . $ag_name . '" />';
  4564. }
  4565. }
  4566. else
  4567. $default_content = $alt_string;
  4568. // Par défaut, on se base sur le lien du site internet (si précisé)
  4569. if ($return_link === null)
  4570. $return_link = empty($ag_website) ? false : true;
  4571. // Vérifier qu'un lien est demandé et que l'agence a bien un site internet
  4572. elseif ($return_link && empty($ag_website))
  4573. return '';
  4574. // Verifier les valeurs envoyées
  4575. if (empty($id_presto_agence_md5) || empty($id_agence))
  4576. return $default_content;
  4577. // Récupérer le chemin du snapshot
  4578. //$snap_name = ltrim(trim($id_presto_agence_md5), '0') . '.jpg'; NON MAIS ALLO !!!! QU'EST CE QUE C'EST QUE CA ???!!!!
  4579. $snap_name = trim($id_presto_agence_md5). '.jpg';
  4580. $url_mmf_img = get_urlmmf_agc($snap_name, $id_agence, 'snapshot');
  4581. //echo $url_mmf_img;
  4582. // Tester l'existence du snapshot
  4583. $test_open = true;
  4584. /*
  4585. if($url_mmf_img[0]=='/') $test_open = file_exists($_SERVER['DOCUMENT_ROOT'].$url_mmf_img);
  4586. //else $test_open = http_exists($url_mmf_img);
  4587. else $test_open = fopen($url_mmf_img, "r");
  4588. */
  4589. /* else
  4590. {
  4591. echo "FUKKK IT !!";
  4592. $test_open = is_file($url_mmf_img);
  4593. }
  4594. else
  4595. {
  4596. echo "FUCK";
  4597. $test_open = (!filetype($url_mmf_img) == false ? true : false);
  4598. }
  4599. */
  4600. //return $url_mmf_img;
  4601. // Générer le contenu du snapshot (image ou texte)
  4602. if ($test_open) {
  4603. $content = '<img src="' . $url_mmf_img . '" alt="' . $alt_string . '" height="120" width="160" title="' . $ag_name . '" />';
  4604. } elseif ($default_img != '') {
  4605. $content = '<img src="' . $default_img . '" alt="' . $alt_string . '" title="' . $ag_name . '" />';
  4606. } else {
  4607. $content = $default_content;
  4608. }
  4609. // Ne pas générer le lien vers le site agence
  4610. if (!$return_link)
  4611. return $content;
  4612. // Générer le lien vers le site de l'agence
  4613. return '<a href="' . $ag_website . '" title="' . $ag_name . '" rel="' . $id_presto_agence_md5 . ' nofollow" target="_blank" class="snapshot_content">' . $content . '</a>';
  4614. }
  4615. function http_exists($url) {
  4616. $ch = curl_init($url);
  4617. // Définir les options Curl
  4618. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return web page
  4619. curl_setopt($ch, CURLOPT_HEADER, false); // don't return headers
  4620. curl_setopt($ch, CURLOPT_NOBODY, true); // don't return body
  4621. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // do not follow redirects
  4622. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // timeout on connect
  4623. curl_setopt($ch, CURLOPT_TIMEOUT, 2); // timeout on response
  4624. if (!curl_exec($ch))
  4625. return false;
  4626. $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  4627. // Renvoie True si le code est 200 (ok) ou 304 (cache)
  4628. return ($http_code == '200' || $http_code == '304');
  4629. }
  4630. /////////////////////////////////////////////////////////////////////////////////
  4631. // FONCTIONS GLOBALES DIVERSES
  4632. /////////////////////////////////////////////////////////////////////////////////
  4633. /*
  4634. * Supprimer tous les caractère spéciaux (accents, cesures, cedilles, etc.)
  4635. * Meme les caractères HTML ( &acirc; &eacute; ...)
  4636. * Renvoie la chaine en minuscule pour l'url
  4637. * Florian PLANCHON - 05/2010
  4638. */
  4639. $convert_from_to = array(
  4640. // Traitement de tous les caractères spéciaux
  4641. 'À' => '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',
  4642. 'Ç' => 'C', 'Ć' => 'C', 'Ĉ' => 'C', 'Ċ' => 'C', 'Č' => 'C', 'ç' => 'c', 'ć' => 'c', 'ĉ' => 'c', 'ċ' => 'c', 'č' => 'c',
  4643. 'Ð' => 'D', 'Ď' => 'D', 'Đ' => 'D', 'ď' => 'd', 'đ' => 'd',
  4644. 'È' => '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',
  4645. 'Ĝ' => 'G', 'Ğ' => 'G', 'Ġ' => 'G', 'Ģ' => 'G', 'ĝ' => 'g', 'ğ' => 'g', 'ġ' => 'g', 'ģ' => 'g',
  4646. 'Ĥ' => 'H', 'Ħ' => 'H', 'ĥ' => 'h', 'ħ' => 'h',
  4647. 'Ì' => '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',
  4648. 'Ĵ' => 'J', 'Ķ' => 'K', 'ķ' => 'k',
  4649. 'Ĺ' => 'L', 'Ļ' => 'L', 'Ľ' => 'L', 'Ŀ' => 'L', 'Ł' => 'L', 'ĺ' => 'l', 'ļ' => 'l', 'ľ' => 'l', 'ŀ' => 'l', 'ł' => 'l',
  4650. 'Ñ' => 'N', 'Ń' => 'N', 'Ņ' => 'N', 'Ň' => 'N', 'ñ' => 'n', 'ń' => 'n', 'ņ' => 'n', 'ň' => 'n', 'ʼn' => 'n',
  4651. 'Ò' => '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',
  4652. 'Ŕ' => 'R', 'Ŗ' => 'R', 'Ř' => 'R', 'ŕ' => 'r', 'ŗ' => 'r', 'ř' => 'r',
  4653. 'Ś' => 'S', 'Ŝ' => 'S', 'Ş' => 'S', 'Š' => 'S', 'ś' => 's', 'ŝ' => 's', 'ş' => 's', 'š' => 's',
  4654. 'Ţ' => 'T', 'Ť' => 'T', 'Ŧ' => 'T', 'ţ' => 't', 'ť' => 't', 'ŧ' => 't',
  4655. 'Ù' => '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',
  4656. 'ŵ' => 'w', 'ẁ' => 'w', 'ẃ' => 'w', 'ẅ' => 'w',
  4657. 'Ý' => 'Y', 'Ŷ' => 'Y', 'Ÿ' => 'Y', 'Ỳ' => 'Y', 'Ỹ' => 'Y', 'Ỷ' => 'Y', 'Ỵ' => 'Y', 'ý' => 'y', 'ÿ' => 'y', 'ŷ' => 'y', 'ỹ' => 'y', 'ỵ' => 'y', 'ỷ' => 'y', 'ỳ' => 'y',
  4658. 'Ź' => 'Z', 'Ż' => 'Z', 'Ž' => 'Z', 'ź' => 'z', 'ż' => 'z', 'ž' => 'z',
  4659. // Traitements des caractères collés
  4660. 'Æ' => 'AE', 'æ' => 'ae', 'Œ' => 'OE', 'œ' => 'oe',
  4661. // Traitements de caractères pour l'url
  4662. ' ' => '-', '+' => '-', '_' => '-', '\'' => '-', '’' => '-',
  4663. // Traitements pour les chaines spéciales
  4664. 's/' => 'sur', '/' => '-', '(' => '', ')' => '', ' ~ ' => '-', '~' => '-'
  4665. );
  4666. function prepareToUrl($string) {
  4667. global $convert_from_to;
  4668. // Eviter d'avoir des caractères html encodés qui subsistent
  4669. $string = html_entity_decode($string, ENT_COMPAT, 'UTF-8');
  4670. // Supprimer tous les caractères spéciaux et remplacer par des '-'
  4671. $string = strtr($string, $convert_from_to);
  4672. // Remplacer les tirets consecutifs par un seul
  4673. $string = preg_replace('`-{2,}`', '-', $string);
  4674. // Renvoyer la chaine en minsucule
  4675. return strtolower($string);
  4676. }
  4677. /**
  4678. * @author W.Asbaiti
  4679. * @since 02/05/2011
  4680. * Appel a un script sur le serveur RW(definit dans la conf) afin d'ecrire sur la BDD RW
  4681. *
  4682. * @param string adresse du serveur $server
  4683. * @param string $url url du fichier a appeler
  4684. * @param array $data tableau des donnees a envoyer
  4685. */
  4686. function RW_post($server = RW_SERVER, $url, $data) {
  4687. // var_dump(wget($server.$url)); //die;
  4688. $error_messages = array();
  4689. set_time_limit(120);
  4690. // Preparation de la partie donnees (le headr a besoin de la taille de cette partie
  4691. $urlvars = $data;
  4692. foreach ($data as $key => $value) {
  4693. $export_par .= "&" . $key . "=" . rawurlencode($value);
  4694. }
  4695. // Préparation du header
  4696. $header = "POST " . $url . " HTTP/1.0\r\n";
  4697. $header .= "Host: " . $server . "\r\n";
  4698. $header .= "Accept: */*\r\n";
  4699. $header .= "AcceptLanguage: fr\r\n";
  4700. $header .= "Connection: Keep-Alive\r\n";
  4701. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  4702. $header .= "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0;\r\n";
  4703. $header .= "Content-Length: " . strlen($export_par) . "\r\n";
  4704. $header .= "\r\n";
  4705. $fs = fsockopen($server, 80, $errno, $errstr, 30);
  4706. if ($fs) {
  4707. fwrite($fs, $header . $export_par . "\r\n\r\n");
  4708. $nb = 0;
  4709. while (!feof($fs) && $nb < 2) {
  4710. $line = fgets($fs);
  4711. $http_res[] = $line;
  4712. if (substr($line, 0, 2) == "\r\n") {
  4713. $nb++;
  4714. };
  4715. };
  4716. fclose($fs);
  4717. return $http_res;
  4718. } else {
  4719. echo "ERREUR CONNECTION";
  4720. die;
  4721. }
  4722. }
  4723. /**
  4724. * Enter description here...
  4725. *
  4726. * @param unknown_type $string
  4727. * @return unknown
  4728. */
  4729. //function getPropretyNameFromId($id, $do_use_label2=false) {
  4730. function getPropretyNameFromId($id, $univ) {
  4731. //global $_ADVANCED_SEARCH_TYPES;
  4732. global $_ADVANCED_SEARCH_TYPES_DEFINITION;
  4733. //foreach ($_ADVANCED_SEARCH_TYPES as $type) {
  4734. foreach ($_ADVANCED_SEARCH_TYPES_DEFINITION[$univ] as $type) {
  4735. $type_values = explode(',', $type['value']);
  4736. //if ($type['value'] == $id) {
  4737. if (in_array($id, $type_values)) {
  4738. if (isset($type['label2']) && !empty($type['label2'])) {
  4739. $label = $type['label2']; // utile pour la coloc.
  4740. } else {
  4741. $label = $type['label'];
  4742. }
  4743. return $label;
  4744. }
  4745. }
  4746. return false;
  4747. }
  4748. function getPropretyValueFromId($id, $univ) {
  4749. //global $_ADVANCED_SEARCH_TYPES;
  4750. global $_ADVANCED_SEARCH_TYPES_DEFINITION;
  4751. //foreach ($_ADVANCED_SEARCH_TYPES as $type) {
  4752. foreach ($_ADVANCED_SEARCH_TYPES_DEFINITION[$univ] as $type) {
  4753. $type_values = explode(',', $type['value']);
  4754. if (in_array($id, $type_values)) {
  4755. if (isset($type['value'])) {
  4756. $value = $type['value'];
  4757. }
  4758. return $value;
  4759. }
  4760. }
  4761. return false;
  4762. }
  4763. /* * *
  4764. * Check if the property type is valid
  4765. * (array $_ADVANCED_SEARCH_TYPES_DEFINITION definition in DEV/LIB/config.settings.php
  4766. * @author Hoarau Melissa
  4767. *
  4768. * @param int id : position in ck_property_type string
  4769. * @param int univ : id univers
  4770. *
  4771. * @return bool
  4772. */
  4773. function isInvalidIdProperty($id, $univ) {
  4774. // Property type array
  4775. global $_ADVANCED_SEARCH_TYPES_DEFINITION;
  4776. //valid values
  4777. $aType_values = array();
  4778. foreach ($_ADVANCED_SEARCH_TYPES_DEFINITION[$univ] as $type) {
  4779. $aType_values[] = $type['value'];
  4780. }
  4781. if (!in_array($id, $aType_values)) {
  4782. return true;
  4783. }
  4784. else
  4785. return false;
  4786. }
  4787. /* * *
  4788. * Check if the page must be redirect to 404
  4789. *
  4790. * @author Hoarau Melissa
  4791. * @param string sBinaryPropertyType : the property type (ex : '00010100110000000'...)
  4792. * @param int univ : id univers
  4793. *
  4794. * @return bool
  4795. */
  4796. function invalidPropertyToRedirect($sBinaryPropertyType, $univ) {
  4797. $bFindInvalid = false;
  4798. $iCptProperty_type = 0;
  4799. for ($i = 0; $i < strlen($sBinaryPropertyType); $i++) {
  4800. $iProperty_type = $sBinaryPropertyType[$i];
  4801. if (0 != $iProperty_type) {
  4802. $iCptProperty_type++;
  4803. if (isInvalidIdProperty(($i + 1), $univ)) {
  4804. $bFindInvalid = true;
  4805. }
  4806. }
  4807. }
  4808. // If an invalid property type is found & if it's only in sBinaryPropertyType => redirect 404
  4809. if ($bFindInvalid && $iCptProperty_type < 2) {
  4810. return true;
  4811. }
  4812. return false;
  4813. }
  4814. /**
  4815. * Enter description here...
  4816. *
  4817. * @param unknown_type $string
  4818. * @return unknown
  4819. */
  4820. function getPropertiesValuesFromCkPropertyType($value, $univ) {
  4821. $array_ads_property_type = array();
  4822. if (isset($value) && strlen($value) == 40) { // type de bien
  4823. for ($i = 0; $i < strlen($value); $i++) {
  4824. if ($value[$i] == 0)
  4825. continue;
  4826. $value_property_type = getPropretyValueFromId($i + 1, $univ);
  4827. $value_property_type = explode(',', $value_property_type);
  4828. foreach ($value_property_type as $type) {
  4829. if (!in_array($type, $array_ads_property_type)) {
  4830. array_push($array_ads_property_type, $type);
  4831. }
  4832. }
  4833. }
  4834. }
  4835. return $array_ads_property_type;
  4836. }
  4837. /**
  4838. * Enter description here...
  4839. *
  4840. * @param unknown_type $string
  4841. * @return unknown
  4842. */
  4843. function string_cleaner($string = "") {
  4844. $string = trim($string);
  4845. // On remplace les tirets et underscore par un espace
  4846. // Et on supprime les espaces consécutifs
  4847. $arr_pattern = array("(-)", "(_)", "/\?/", "(!)", "(<)", "(>)", "(\s+)");
  4848. $string = preg_replace($arr_pattern, ' ', $string);
  4849. $string = srmtoupper($string, true); //Suppresion des accents
  4850. $arr_pattern = array("/\bST\b/i", "/\bSTE\b/i", "/\bSTES\b/i");
  4851. $arr_replace = array("SAINT", "SAINTE", "SAINTES");
  4852. return preg_replace($arr_pattern, $arr_replace, $string);
  4853. }
  4854. /**
  4855. * Génère l'url d'une page résultats annonces à partir d'une recherche sur le moteur
  4856. * (et uniquement depuis le moteur, pas depuis un lien venant d'une page externe)
  4857. *
  4858. * @param String $string
  4859. * @return Array
  4860. */
  4861. function uriToFinalFromSearchEngine($_GET_INFOS) {
  4862. //var_dump($_GET_INFOS);
  4863. //////////////////////// PROCESS FREE T9 //////////////////////////////////
  4864. /* On verifie les loc_id Postés par le moteur dans le cas d'un T9 ouvert
  4865. On attend deux chaines numériques séparés par un underscore "_" */
  4866. $flag_ambigu = false;
  4867. $flag_some_found = false;
  4868. $loc_not_found = 0;
  4869. $cnt = 1;
  4870. $req_loc = array();
  4871. $check_search = array();
  4872. // Utilise COOKIE aulieu de SESSION
  4873. $cookieExpires = mktime(0, 0, 0, 1, 1, 1970); // For delete cookie
  4874. setcookie("AMBIGUITE_LOC_NAME", "", $cookieExpires);
  4875. unset($_COOKIE["AMBIGUITE_LOC_NAME"]);
  4876. setcookie("AMBIGUITE_CRITERIONS", "", $cookieExpires);
  4877. unset($_COOKIE["AMBIGUITE_CRITERIONS"]);
  4878. /*
  4879. $tab_query_string = explode("&", $_SERVER["QUERY_STRING"]);
  4880. $tab_result_query = array();
  4881. for ($cpt=0; $cpt < count($tab_query_string); $cpt++)
  4882. {
  4883. $tab_result_query[$cpt] = explode("=",$tab_query_string[$cpt]);
  4884. $tab_new_query[$tab_result_query[$cpt][0]] = $tab_result_query[$cpt][1];
  4885. }
  4886. */
  4887. $tab_new_query = $_GET_INFOS;
  4888. $array_page_ambg = array(
  4889. 1 => "ambiguous_vente_fr.php",
  4890. 2 => "ambiguous_location_fr.php",
  4891. 8 => "ambiguous_colocation_fr.php"
  4892. );
  4893. $array_special_cp = array('2a', '2b', '971', '972', '973', '974', '975', '976', '984', '986', '987', '988');
  4894. for ($cntfields = 1; $cntfields <= SEARCH_FIELDS_NUMBER; $cntfields++) {
  4895. // cas particulier de la ville Y, seule ville à 1 caractère
  4896. if ($_REQUEST["loc_name" . $cntfields] == 'y') {
  4897. $_GET_INFOS["loc_name" . $cntfields] = $_REQUEST["loc_name" . $cntfields] = $tab_new_query["loc_name" . $cntfields] = 'Y (80190)';
  4898. $_GET_INFOS["loc_key" . $cntfields] = $_REQUEST["loc_key" . $cntfields] = $tab_new_query["loc_key" . $cntfields] = '36006_2';
  4899. }
  4900. if (empty($_REQUEST["loc_key" . $cntfields]))
  4901. continue;
  4902. $current_lockey = strtolower(trim($_REQUEST["loc_key" . $cntfields]));
  4903. $current_locname = string_cleaner($_REQUEST["loc_name" . $cntfields]);
  4904. // Si c'est un doublon, on ne le prend pas en compte
  4905. if (in_array($current_lockey, $check_search))
  4906. continue;
  4907. // Ajouter au tableau des doublons
  4908. $check_search[$cnt] = $current_lockey;
  4909. $req_loc[$cnt]["loc_name"] = string_cleaner($current_locname);
  4910. $req_loc[$cnt]["loc_key"] = 0;
  4911. $req_loc[$cnt]["level"] = 0;
  4912. $req_loc[$cnt]["ambigue"] = 0;
  4913. $req_loc[$cnt]["loc_get"] = $current_lockey;
  4914. // La clé de localité n'a pas le bon format
  4915. if (isWrongLocKey($current_lockey)) {
  4916. // Si c'est un code postal spécial (domtom ou corse), c'est ok
  4917. if (in_array($current_lockey, $array_special_cp)) {
  4918. // On récupère les infos de la localité
  4919. $res_search = find_locname_by_czip($current_lockey, 1);
  4920. $flag_some_found = true;
  4921. $result = $res_search['res'][0];
  4922. $lct_name = strtoupper(strtolower($result['lct_name_fr']));
  4923. $lct_zip = $result['lct_post_code'];
  4924. $lockey = $result['lct_id'] . "_" . $result['lct_level'];
  4925. $req_loc[$cnt]["loc_key"] = $result['lct_id'];
  4926. $req_loc[$cnt]["level"] = $result['lct_level'];
  4927. $req_loc[$cnt]["loc_get"] = $lockey;
  4928. $req_loc[$cnt]["loc_name"] = $lct_name . " (" . $lct_zip . ")"; //(strtolower($lct_name));
  4929. $tab_new_query["loc_name" . $cnt] = urlencode($lct_name . "-" . $lct_zip);
  4930. $tab_new_query["loc_key" . $cnt] = $lockey;
  4931. ++$cnt;
  4932. // Passer au champ suivant
  4933. continue;
  4934. }
  4935. // On vérifie si la saisie est un code postal
  4936. if (preg_match('`^[0-9]{2,5}$`', $current_lockey)) {
  4937. if (strlen($current_lockey) == 2) {
  4938. $mode_departement = 1;
  4939. $current_lockey .= '000';
  4940. } else {
  4941. $mode_departement = 0;
  4942. // Remplir à droite avec des 0 pour obtenir 5 caractères
  4943. $current_lockey = str_pad($current_lockey, 5, 0);
  4944. }
  4945. $res_search = find_locname_by_czip($current_lockey, 1);
  4946. //var_dump($res_search);
  4947. $res_nb_results = $res_search['count'][0]['count'];
  4948. if ($res_nb_results >= 1) {
  4949. //Modification par Soflou pour gérer les villes dont le CP est égal XX000
  4950. //
  4951. //On vérifie si on a un level 2 (ville)
  4952. $count_ville = 0;
  4953. for ($cnt_res = 0; $cnt_res < $nb_results; $cnt_res++) {
  4954. if ($res_search['res'][$cnt_res]['lct_level'] == 2)
  4955. $count_ville++;
  4956. }
  4957. //Si une seule ville trouvée on affiche les resultats pour cette ville
  4958. if ($count_ville == 1 && !$mode_departement == 1) {
  4959. $last_id = count($res_search['res']) - 1;
  4960. $res_ville = $res_search['res'][$last_id];
  4961. // Remplacer les resultats par le dernier
  4962. $res_search['res'] = array(0 => $res_ville);
  4963. $res_nb_results = 1;
  4964. }
  4965. //On force pour gérer le département
  4966. if ($res_search['res'][0]['lct_level'] == 1 && $count_ville == 0) {
  4967. $res_nb_results = 1;
  4968. }
  4969. }
  4970. // Gérer les différents cas du nombre de résultats
  4971. switch ($res_nb_results) {
  4972. case 0: //Aucun résultat
  4973. // "No ZIP relationship"
  4974. $loc_not_found++;
  4975. $req_loc[$cnt]["loc_key"] = ""; //$val_zip_code;
  4976. $req_loc[$cnt]["loc_get"] = ""; //$val_zip_code;
  4977. $req_loc[$cnt]["level"] = 0;
  4978. $req_loc[$cnt]["loc_get"] = "";
  4979. $tab_new_query["loc_key" . $cnt] = "";
  4980. break;
  4981. case 1: //Un résultat unique
  4982. $flag_some_found = true;
  4983. $result = $res_search['res'][0];
  4984. $lct_name = strtoupper(strtolower($result['lct_name_fr']));
  4985. $lct_zip = $result['lct_post_code'];
  4986. if ($result['lct_level'] == 1) { // Dépt
  4987. if (string_begins_with($lct_zip, '97') || string_begins_with($lct_zip, '98')) { // Dom-Tom
  4988. $lct_zip = substr($lct_zip, 0, 3);
  4989. } else {
  4990. $lct_zip = substr($lct_zip, 0, 2);
  4991. }
  4992. }
  4993. $lockey = $result['lct_id'] . "_" . $result['lct_level'];
  4994. $req_loc[$cnt]["loc_key"] = $result['lct_id'];
  4995. $req_loc[$cnt]["level"] = $result['lct_level'];
  4996. $req_loc[$cnt]["loc_get"] = $lockey;
  4997. $req_loc[$cnt]["loc_name"] = $lct_name . " (" . $lct_zip . ")";
  4998. $tab_new_query["loc_name" . $cnt] = urlencode($lct_name . "-" . $lct_zip);
  4999. $tab_new_query["loc_key" . $cnt] = $lockey;
  5000. break;
  5001. default: //Multi résultat
  5002. $flag_some_found = true;
  5003. if ($mode_departement == 1) {
  5004. $result = $res_search['res'][0];
  5005. $lct_name = strtoupper(strtolower($result['lct_name_fr']));
  5006. $lct_zip = substr($result['lct_post_code'], 0, 2);
  5007. $lgc_id = ($result['lgc_id'] == 0 ? $result['lct_id'] : $result['lgc_id']);
  5008. $lockey = $lgc_id . "_1";
  5009. $req_loc[$cnt]["level"] = 1;
  5010. } else {
  5011. $result = $res_search['res'][1];
  5012. $lct_name = "TOUTES-COMMUNES";
  5013. $lct_zip = ($result['lct_post_code'] == '75000' ? '75' : $result['lct_post_code']);
  5014. $lgc_id = empty($result['lgc_id']) ? $result['lct_id'] : $result['lgc_id'];
  5015. $lockey = $lgc_id . "_98";
  5016. $req_loc[$cnt]["level"] = "98";
  5017. }
  5018. $req_loc[$cnt]["loc_key"] = $lgc_id;
  5019. $req_loc[$cnt]["loc_get"] = $lockey;
  5020. $req_loc[$cnt]["loc_name"] = $lct_name . " (" . $lct_zip . ")"; //(strtolower($lct_name));
  5021. $tab_new_query["loc_name" . $cnt] = urlencode($lct_name . "-" . $lct_zip);
  5022. $tab_new_query["loc_key" . $cnt] = $lockey;
  5023. break;
  5024. }
  5025. if ($cnt <> $cntfields) {
  5026. $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
  5027. $_GET_INFOS["loc_key" . $cntfields] = "";
  5028. }
  5029. }
  5030. // Sinon, on vérifie si la saisie est bien une localité
  5031. else {
  5032. //saisie mode text
  5033. // Supprimer la chaine de la localité par défaut
  5034. // => Beaucoup d'url sont en erreur car la localité contenait cette chaine
  5035. // => C'est dû à la durée avant effacement du t9 en entrant dans le champ pour modification
  5036. $current_locname = str_ireplace(LABEL_DEFAULT_LOCALITY, '', $current_locname);
  5037. // Gérer le cas où il y a le code postal dans la localité (entre parentheses)
  5038. // On récupère la chaine qui se trouve avant la paranthese ouvrante.
  5039. if (($pos = strpos($current_locname, '(')) > 3)
  5040. $current_locname = substr($current_locname, 0, $pos);
  5041. // Chercher par une requete du type " ='LOCNAME' "
  5042. $res_search = find_locname_by_name($current_locname, 0);
  5043. $liste_villes = $res_search['res'];
  5044. $count_list_ville_total = $res_search['count'];
  5045. $flag_count_over = in_array(strtoupper($current_locname), $no_freeT9_cities);
  5046. // "Rien trouvé..."
  5047. if (count($liste_villes) == 0) {
  5048. // Chercher par une requete du type " LIKE 'LOCNAME' "
  5049. $res_search = find_locname_by_name($current_locname, 1);
  5050. $liste_villes = $res_search['res'];
  5051. $count_list_ville_total = $res_search['count'];
  5052. }
  5053. $count_total_ville = $count_list_ville_total[0]['count'];
  5054. $res_nb_results = count($liste_villes);
  5055. if ($res_nb_results == 0) {
  5056. //Si la localité n'existe pas on forme l'URL avec les parametre recu
  5057. //J'ai détaché le fait que ca peut etre ambigue ou non trouvé
  5058. $loc_not_found++;
  5059. //$flag_ambigu=true;
  5060. $locname = strtoupper(strtolower($current_locname));
  5061. $req_loc[$cnt]["loc_name"] = $locname;
  5062. $req_loc[$cnt]["loc_key"] = "0";
  5063. $req_loc[$cnt]["level"] = "0";
  5064. $req_loc[$cnt]["loc_get"] = "";
  5065. $tab_new_query["loc_name" . $cnt] = $locname . "-";
  5066. $tab_new_query["loc_key" . $cnt] = "";
  5067. } elseif ($res_nb_results > 1) {
  5068. //Rajout d'une fonction d'agrégation des codes postaux
  5069. //On peut avoir des regroupement de code postaux pour une même ville
  5070. $tab_grp_zip = array();
  5071. $lgn_sav = $liste_villes[0]['lgn_id'];
  5072. $cnt_lgn = 0;
  5073. if ($lgn_sav <> 0) {
  5074. for ($cnt_zip = 0; $cnt_zip < $res_nb_results; $cnt_zip++) {
  5075. if ($liste_villes[$cnt_zip]['lgn_id'] == $lgn_sav)
  5076. ++$cnt_lgn;
  5077. }
  5078. }
  5079. // si $cnt_lgn = count(list_ville) alors regroupement sinon ambiguité
  5080. if ($cnt_lgn == $res_nb_results) {
  5081. $flag_some_found = true;
  5082. $locname = strtoupper(strtolower($liste_villes[0]['lct_name_fr']));
  5083. //Simili cas unique regroupement cpostaux
  5084. $lct_id = $liste_villes[0]['lgn_id'];
  5085. $req_loc[$cnt]["loc_name"] = $locname . " (" . LABEL_LGN_ALL . ")";
  5086. $req_loc[$cnt]["loc_key"] = $lct_id;
  5087. $req_loc[$cnt]["level"] = 99;
  5088. $req_loc[$cnt]["loc_get"] = $_GET_INFOS["loc_key" . $cnt];
  5089. $tab_new_query["loc_name" . $cnt] = urlencode($locname . "-" . str_replace(" ", "-", LABEL_LGN_ALL));
  5090. $tab_new_query["loc_key" . $cnt] = $lct_id . "_99";
  5091. if ($cnt <> $cntfields) {
  5092. $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
  5093. $_GET_INFOS["loc_key" . $cntfields] = "";
  5094. }
  5095. } else {
  5096. /// sinon ambiguité de niveau 1
  5097. //Si la localité n'existe pas on forme l'URL avec les parametre recu
  5098. //J'ai détaché le fait que ca peut etre ambigue ou non trouvé
  5099. $loc_not_found++;
  5100. //$flag_ambigu=true;
  5101. $locname = strtoupper(strtolower($current_locname));
  5102. $req_loc[$cnt]["loc_name"] = $locname;
  5103. $req_loc[$cnt]["loc_key"] = "0";
  5104. $req_loc[$cnt]["level"] = "0";
  5105. $req_loc[$cnt]["ambigue"] = 1;
  5106. $tab_new_query["loc_name" . $cnt] = urlencode($locname) . "-";
  5107. $tab_new_query["loc_key" . $cnt] = ""; //urlencode("0_0");
  5108. $flag_ambigu = true;
  5109. }
  5110. } elseif ($res_nb_results > 19999999) {
  5111. // 1 - Ambiguité simple
  5112. // 2 - Trop de résultats
  5113. if ($flag_count_over) {
  5114. $req_loc[$cnt]["ambigue"] = 1;
  5115. //Trop de résultats normalement = 2
  5116. $flag_ambigu = true;
  5117. } else {
  5118. //On peut avoir des regroupement de code pôstaux pour une même ville
  5119. $tab_grp_zip = array();
  5120. $lgn_sav = $liste_villes[0]['lgn_id'];
  5121. $cnt_lgn = 0;
  5122. if ($lgn_sav <> 0) {
  5123. for ($cnt_zip = 0; $cnt_zip < $res_nb_results; $cnt_zip++) {
  5124. if ($liste_villes[$cnt_zip]['lgn_id'] == $lgn_sav)
  5125. ++$cnt_lgn;
  5126. }
  5127. }
  5128. // si $cnt_lgn = count(list_ville) alors regroupement sinon ambiguité
  5129. if ($cnt_lgn == $res_nb_results) {
  5130. $flag_some_found = true;
  5131. $locname = strtoupper(strtolower($liste_villes[0][1]));
  5132. $lockey = $liste_villes[0]['lgn_id'] . "_99";
  5133. //Simili cas unique regroupement cpostaux
  5134. $lct_post_code = $liste_villes[0][3];
  5135. if ($lct_level == 1) { // Dépt
  5136. if (string_begins_with($lct_post_code, '97') || string_begins_with($lct_post_code, '98')) { // Dom-Tom
  5137. $lct_post_code = substr($lct_post_code, 0, 3);
  5138. } else {
  5139. $lct_post_code = substr($lct_post_code, 0, 2);
  5140. }
  5141. }
  5142. $req_loc[$cnt]["loc_name"] = $locname . " (" . $lct_post_code . ")";
  5143. $req_loc[$cnt]["loc_key"] = $liste_villes[0]['lgn_id'];
  5144. $req_loc[$cnt]["level"] = 99; //$liste_villes[0][2];
  5145. $req_loc[$cnt]["loc_get"] = $lockey;
  5146. $tab_new_query["loc_name" . $cnt] = urlencode($locname . "_TOUS-CODES-POSTAUX");
  5147. $tab_new_query["loc_key" . $cnt] = $lockey;
  5148. if ($cnt <> $cntfields) {
  5149. $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
  5150. $_GET_INFOS["loc_key" . $cntfields] = "";
  5151. }
  5152. } else {
  5153. /// sinon ambiguité de niveau 1
  5154. $req_loc[$cnt]["ambigue"] = 1;
  5155. $flag_ambigu = true;
  5156. }
  5157. }
  5158. } else {
  5159. //Résultat Unique
  5160. $flag_some_found = true;
  5161. $locname = strtoupper(strtolower($liste_villes[0][1]));
  5162. $lct_id = $liste_villes[0][0];
  5163. $lct_level = $liste_villes[0][2];
  5164. $lockey = $lct_id . '_' . $lct_level;
  5165. $lct_post_code = $liste_villes[0][3];
  5166. if ($lct_level == 1) { // Dépt
  5167. if (string_begins_with($lct_post_code, '97') || string_begins_with($lct_post_code, '98')) { // Dom-Tom
  5168. $lct_post_code = substr($lct_post_code, 0, 3);
  5169. } else {
  5170. $lct_post_code = substr($lct_post_code, 0, 2);
  5171. }
  5172. }
  5173. $req_loc[$cnt]["loc_name"] = $locname . " (" . $lct_post_code . ")";
  5174. $req_loc[$cnt]["loc_key"] = $lct_id;
  5175. $req_loc[$cnt]["level"] = $lct_level;
  5176. $req_loc[$cnt]["loc_get"] = $lockey;
  5177. $tab_new_query["loc_name" . $cnt] = urlencode($locname . "-" . $lct_post_code);
  5178. $tab_new_query["loc_key" . $cnt] = $lockey;
  5179. if ($cnt <> $cntfields) {
  5180. $_GET_INFOS["loc_name" . $cntfields] = LABEL_DEFAULT_LOCALITY;
  5181. $_GET_INFOS["loc_key" . $cntfields] = "";
  5182. }
  5183. }
  5184. }
  5185. } else {
  5186. $flag_some_found = true;
  5187. //Value from Closed-T9
  5188. $tab_lockey = explode("_", $current_lockey);
  5189. $req_loc[$cnt]["loc_key"] = $tab_lockey[0];
  5190. $req_loc[$cnt]["level"] = $tab_lockey[1];
  5191. }
  5192. $cnt++;
  5193. }
  5194. if ($_REQUEST['dbg'] == 'flo') {
  5195. echo '<pre>$_GET_INFOS :<br />';
  5196. var_export($_GET_INFOS);
  5197. echo '</pre><pre>$tab_new_query (utilise si OK) :<br />';
  5198. var_export($tab_new_query);
  5199. echo '</pre><pre>$req_loc (utilise si NOK) :<br />';
  5200. var_export($req_loc);
  5201. echo '</pre>';
  5202. if ($flag_ambigu == true || $loc_not_found > 0)
  5203. echo '<p style="color:red">Ambiguite ou localite non trouvee => Page ambiguite</p>';
  5204. else
  5205. echo '<p style="color:green">Aucune ambiguite => Page de resultats</p>';
  5206. die();
  5207. }
  5208. if ($flag_ambigu == true || $loc_not_found > 0) {
  5209. //On rajoute les critères
  5210. /*
  5211. if(isset($_GET_INFOS['ck_property_group']) && is_array($_GET_INFOS['ck_property_group']) ) {
  5212. $property_types = $_GET_INFOS['ck_property_group'];
  5213. $property_type = str_repeat('0',40 );
  5214. foreach($property_types as $type_id) $property_type[$type_id-1] = '1';
  5215. $req_criterion['property_type'] = $property_type;
  5216. }
  5217. */
  5218. $req_criterion['price'] = $_GET_INFOS['price'];
  5219. $req_criterion['price_min'] = $_GET_INFOS['price_min'];
  5220. $req_criterion['price_max'] = $_GET_INFOS['price_max'];
  5221. $req_criterion['area'] = $_GET_INFOS['area'];
  5222. $req_criterion['area_min'] = $_GET_INFOS['area_min'];
  5223. $req_criterion['area_max'] = $_GET_INFOS['area_max'];
  5224. $req_criterion['ck_nb_rooms'] = $_GET_INFOS['ck_nb_rooms'];
  5225. $req_criterion['ck_property_type'] = $_GET_INFOS['ck_property_type'];
  5226. setcookie("AMBIGUITE_LOC_NAME", serialize($req_loc));
  5227. $_COOKIE["AMBIGUITE_LOC_NAME"] = serialize($req_loc);
  5228. setcookie("AMBIGUITE_CRITERIONS", serialize($req_criterion));
  5229. $_COOKIE["AMBIGUITE_CRITERIONS"] = serialize($req_criterion);
  5230. //On ne redirige vers pas d'ambiguité que si aucun resultat direct
  5231. if ($flag_some_found == false) {
  5232. redirection($_global['dns'] . $array_page_ambg[$_GET_INFOS["univers"]]);
  5233. }
  5234. }
  5235. /* FIN VERIF du T9 ouvert */
  5236. $page = (isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "/recherche_nat.php");
  5237. //$page = "/recherche_nat.php";
  5238. //echo "[common.functions : uriToFinalFromSearchEngine : page = $page]\n";
  5239. switch ($_global['site']) {
  5240. case "be":
  5241. /* NE PAS EFFACER */
  5242. $page = explode('/', $page);
  5243. $page = $page[count($page) - 1];
  5244. //list($trash, $page) = explode('/', $page);
  5245. break;
  5246. default:
  5247. list($trash, $page) = explode('/', $page);
  5248. break;
  5249. }
  5250. list($page) = explode('_', $page, 2);
  5251. // On check si ca existe ou pas encore
  5252. // Par défault si l'univers est location, on trie par date
  5253. $saved_searches = unserialize($_COOKIE[SEARCH_HISTORY_COOKIE_NAME]);
  5254. $saved_search = unserialize($saved_searches[0]);
  5255. if ((!$saved_search || ($saved_search && ($saved_search['univers'] != $_global['univers']))) && $_global['univers'] == '2') {
  5256. /*$tab_new_query['ordre'] = 'update_date';
  5257. $tab_new_query['hi_order'] = '1';
  5258. $tab_new_query['ck_property_type'] = '0000000000000000000000000000000000000000';
  5259. *
  5260. */
  5261. $tab_new_query['ck_property_type'] = '1100001000000000000000000000000000000000';
  5262. } else if ((!$saved_search || ($saved_search && ($saved_search['univers'] != $_global['univers']))) && $_global['univers'] == '1') {
  5263. $tab_new_query['ck_property_type'] = '1100001000000000000000000000000000000000';
  5264. }
  5265. $tab_new_query['type_transaction'] = $_GET_INFOS["univers"];
  5266. // Générer la nouvelle url seo correspondant à la recherche
  5267. //echo "[common.functions : uriToFinalFromSearchEngine : tab_new_query = ".print_r($tab_new_query, true).", page = ".$page.", dns = ".$_global['dns']."]<br>\n";
  5268. $url = to_nat($tab_new_query, $page, $_global['dns']);
  5269. //echo "[common.functions : uriToFinalFromSearchEngine : url = $url]<br>\n"; //exit();
  5270. // Ajouter le paramètre dbg pour rester dans le mode debug
  5271. if (isset($_REQUEST['dbg'])) {
  5272. if (strpos($url, '?') === false)
  5273. $url = $url . '?dbg=' . $_REQUEST['dbg'];
  5274. else
  5275. $url = $url . '&dbg=' . $_REQUEST['dbg'];
  5276. }
  5277. //echo "[common.functions : uriToFinalFromSearchEngine : url = $url]\n";
  5278. return $url;
  5279. }
  5280. /**
  5281. * Génère l'url d'une page résultats annonces à partir d'une page externe au site
  5282. * (et uniquement depuis une page externe, pas depuis un recherche sur le moteur)
  5283. *
  5284. * @param String $string
  5285. * @return Array
  5286. */
  5287. function uriToFinalFromDirectLink($_GET_INFOS) {
  5288. //echo "[common.functions : uriToFinalFromDirectLink : _GET_INFOS = ".print_r($_GET_INFOS, true)."]\n"; //exit();
  5289. $url = '';
  5290. ###############################################################################################################################################
  5291. # URL courte modèle 1 (localité) : /annonces-{univ_name}-{loc_name}-{post_name}-{loc_key}-{offset}.html
  5292. # URL courte modèle 2 (localité + type bien) : /{prop_type}-{loc_name}/{univ_name}-{prop_type}-{loc_name}-{post_name}-{loc_key}-{offset}.html
  5293. # 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
  5294. ###############################################################################################################################################
  5295. ###############################################################################################################################################
  5296. # Vérifs communes aux modèles
  5297. ###############################################################################################################################################
  5298. // vérif univers défini et valide (vente, loc., coloc.)
  5299. $string = $_GET_INFOS['univers'];
  5300. $is_universe_valid = in_array($string, array('1', '2', '8'));
  5301. if (!$is_universe_valid) {
  5302. return $url;
  5303. }
  5304. // vérif localité définie et unique si oui, est bien valide (triplet loc_key/loc_name/post_code présent et valide)
  5305. $string1 = $_GET_INFOS['lockeys'];
  5306. $string2 = $_GET_INFOS['locnames'];
  5307. $is_locality_uniq = isUniqLocKeyLocName($string1, $string2); // localité et lockey unique
  5308. if (!$is_locality_uniq) {
  5309. return $url;
  5310. }
  5311. $is_locality_valid = !isWrongLocKeyLocNamePostCode($string1, $string2); // localité, lockey et code postal cohérents
  5312. if (!$is_locality_valid) {
  5313. return $url;
  5314. }
  5315. // récup niveau et id niveau localité
  5316. $url_loc_key = $_GET_INFOS['lockeys'];
  5317. list($loc_key_val, $loc_key_lvl) = explode('_', $_GET_INFOS['lockeys']);
  5318. // récup code postal et nom localité
  5319. if ($loc_key_lvl == '98') {
  5320. $url_loc_name = 'toutes-communes';
  5321. $url_post_code = str_replace('toutes-communes-', '', $_GET_INFOS['locnames']);
  5322. } else if ($loc_key_lvl == '99') {
  5323. $url_loc_name = str_replace('-tous-codes-postaux', '', $_GET_INFOS['locnames']);
  5324. $url_post_code = 'tous-codes-postaux';
  5325. } else { // $loc_key_lvl == '1', '2', '99'
  5326. $array = explode('-', $_GET_INFOS['locnames']);
  5327. $url_post_code = $array[sizeof($array) - 1];
  5328. $url_loc_name = str_replace('-' . $url_post_code, '', $_GET_INFOS['locnames']);
  5329. }
  5330. // récup pagination en cours
  5331. $array = explode('-', $_GET_INFOS['query']);
  5332. $is_offet_default = ($array[12] == '1');
  5333. $url_offset = ($is_offet_default ? '' : $array[12]);
  5334. //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";
  5335. ###############################################################################################################################################
  5336. # Vérifs spécifiques aux modèles
  5337. ###############################################################################################################################################
  5338. // vérif aucun ou tous types de bien demandé (maison + appartement + etc. + autre)
  5339. $string = $_GET_INFOS['ck_property_type'];
  5340. //echo "[common.functions : uriToFinalFromDirectLink : ck_property_type = ".$string."]\n"; //exit();
  5341. $is_property_all = false;
  5342. if ($_GET_INFOS['univers'] == '1') {
  5343. switch ($string) {
  5344. case '0000000000' : $is_property_all = true;
  5345. break;
  5346. case 'ffbf800001' : $is_property_all = true;
  5347. break;
  5348. }
  5349. } else if ($_GET_INFOS['univers'] == '2') {
  5350. switch ($string) {
  5351. case '0000000000' : $is_property_all = true;
  5352. break;
  5353. case 'ffbf800001' : $is_property_all = true;
  5354. break;
  5355. }
  5356. } else if ($_GET_INFOS['univers'] == '8') {
  5357. switch ($string) {
  5358. case '0000000000' : $is_property_all = true;
  5359. break;
  5360. case 'cb0f000000' : $is_property_all = true;
  5361. break;
  5362. }
  5363. }
  5364. // vérif type de bien unique demandé et si oui lequel (maison | appartement | etc. | autre)
  5365. $is_property_one = false;
  5366. if ($_GET_INFOS['univers'] == '1') {
  5367. switch ($string) {
  5368. case '8000000000' : $url_property = 'appartement';
  5369. break;
  5370. case '4000000000' : $url_property = 'maison';
  5371. break;
  5372. case '0006000000' : $url_property = 'propriete';
  5373. break;
  5374. case '0001000000' : $url_property = 'hotel-particulier';
  5375. break;
  5376. case '0020000000' : $url_property = 'chateau';
  5377. break;
  5378. case '0008000000' : $url_property = 'ferme';
  5379. break;
  5380. case '1080000000' : $url_property = 'bureau-commerce';
  5381. break;
  5382. case '0400000000' : $url_property = 'loft-atelier';
  5383. break;
  5384. case '0800000000' : $url_property = 'immeuble';
  5385. break;
  5386. case '0010000000' : $url_property = 'parking';
  5387. break;
  5388. case '2000000000' : $url_property = 'terrain';
  5389. break;
  5390. case '0000000001' : $url_property = 'viager';
  5391. break;
  5392. case '0100000000' : $url_property = 'chalet';
  5393. break;
  5394. case '0200000000' : $url_property = 'villa';
  5395. break;
  5396. case '0000800000' : $url_property = 'autre';
  5397. break;
  5398. }
  5399. } else if ($_GET_INFOS['univers'] == '2') {
  5400. switch ($string) {
  5401. case '8000000000' : $url_property = 'appartement';
  5402. break;
  5403. case '4000000000' : $url_property = 'maison';
  5404. break;
  5405. case '0006000000' : $url_property = 'propriete';
  5406. break;
  5407. case '0001000000' : $url_property = 'hotel-particulier';
  5408. break;
  5409. case '0020000000' : $url_property = 'chateau';
  5410. break;
  5411. case '0008000000' : $url_property = 'ferme';
  5412. break;
  5413. case '1080000000' : $url_property = 'bureau-commerce';
  5414. break;
  5415. case '0400000000' : $url_property = 'loft-atelier';
  5416. break;
  5417. case '0800000000' : $url_property = 'immeuble';
  5418. break;
  5419. case '0010000000' : $url_property = 'parking';
  5420. break;
  5421. case '0100000000' : $url_property = 'chalet';
  5422. break;
  5423. case '0200000000' : $url_property = 'villa';
  5424. break;
  5425. case '0000800000' : $url_property = 'autre';
  5426. break;
  5427. }
  5428. } else if ($_GET_INFOS['univers'] == '8') {
  5429. switch ($string) {
  5430. case '430f000000' : $url_property = 'maison-villa';
  5431. break;
  5432. case '8800000000' : $url_property = 'immeuble-appartement';
  5433. break;
  5434. }
  5435. }
  5436. if (isset($url_property)) {
  5437. $is_property_one = true;
  5438. }
  5439. // vérif aucun ou tous nombres de pièces défini (1 + 2 + etc. + 6+)
  5440. $array = explode('-', $_GET_INFOS['query']);
  5441. $string = $array[3];
  5442. $is_rooms_all = ($string == '00');
  5443. // vérif nombre de pièces (vente/loc.) ou chambres (coloc.) unique demandé et si oui lequel (1 | 2 | etc. | 6+)
  5444. $is_rooms_one = false;
  5445. if (
  5446. (($_GET_INFOS['univers'] == '1') && in_array($url_property, array('appartement', 'maison', 'propriete', 'hotel-particulier', 'chateau', 'loft-atelier', 'viager', 'chalet', 'villa'))) ||
  5447. (($_GET_INFOS['univers'] == '2') && in_array($url_property, array('appartement', 'maison', 'propriete', 'hotel-particulier', 'chateau', 'loft-atelier', 'chalet', 'villa'))) ||
  5448. (($_GET_INFOS['univers'] == '8') && in_array($url_property, array('maison-villa', 'immeuble-appartement')))
  5449. ) {
  5450. switch ($string) {
  5451. case '80' : $url_rooms = '1';
  5452. break;
  5453. case '40' : $url_rooms = '2';
  5454. break;
  5455. case '20' : $url_rooms = '3';
  5456. break;
  5457. case '10' : $url_rooms = '4';
  5458. break;
  5459. case '08' : $url_rooms = '5';
  5460. break;
  5461. case '04' : $url_rooms = '6';
  5462. break;
  5463. }
  5464. }
  5465. if (isset($url_rooms)) {
  5466. if (($_GET_INFOS['univers'] == '1') || ($_GET_INFOS['univers'] == '2')) {
  5467. $url_rooms .= '-piece' . (intval($url_rooms) > 1 ? 's' : '');
  5468. } else if ($_GET_INFOS['univers'] == '8') {
  5469. $url_rooms .= '-chambre' . (intval($url_rooms) > 1 ? 's' : '');
  5470. }
  5471. $is_rooms_one = true; // un nbre de pièce (vente/loc.) ou un nbre de chambre (coloc.) en fait
  5472. }
  5473. // 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)
  5474. if (
  5475. (($_GET_INFOS['univers'] == '1') || ($_GET_INFOS['univers'] == '2')) &&
  5476. ($url_property == 'appartement') && ($url_rooms == '1-piece')
  5477. ) {
  5478. $url_property = 'studio';
  5479. $is_rooms_one = false;
  5480. $is_rooms_all = true;
  5481. }
  5482. // vérif critères supplémentaires indiqués (surface min/max, prix min/max, nombre de chambres, etc.)
  5483. // voir ficier rw.encode.php, fonction to_nat(), lignes 719+
  5484. $array = explode('-', $_GET_INFOS['query']);
  5485. $is_price_default = ($array[0] == '0,0');
  5486. $is_surftot_default = ($array[1] == '0,0');
  5487. $is_surfter_default = ($array[2] == '0,0');
  5488. $is_bedrooms_default = ($array[4] == '00');
  5489. $is_extended_default = ($array[5] == '000000000000');
  5490. $is_dpe_default = ($array[6] == '00');
  5491. $is_fresh_default = ($array[7] == '0');
  5492. //$is_???_default = ($array[8] == '0');
  5493. $is_order_default = ($array[9] == '3'); // price
  5494. $is_hi_order_default = ($array[10] == '0'); // asc
  5495. $is_an_visuel_default = ($array[11] == '0');
  5496. $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);
  5497. //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";
  5498. //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";
  5499. ###############################################################################################################################################
  5500. # URL courte modèle 1 (localité) : /annonces-{univ_name}-{loc_name}-{post_name}-{loc_key}-{offset}.html
  5501. ###############################################################################################################################################
  5502. if ($is_property_all && $is_rooms_all && $is_critera_default) {
  5503. $string = $_GET_INFOS['univers'];
  5504. switch ($string) {
  5505. case '1' : $url_unv_name = 'immobilier';
  5506. break;
  5507. case '2' : $url_unv_name = 'location';
  5508. break;
  5509. case '8' : $url_unv_name = 'colocation';
  5510. break;
  5511. }
  5512. $url = '/annonces-' . $url_unv_name . '-' . $url_loc_name . '-' . $url_post_code . '-' . $url_loc_key . ($is_offet_default ? '' : '-' . $url_offset) . '.html';
  5513. }
  5514. ###############################################################################################################################################
  5515. # URL courte modèle 2 (localité + type bien) : /{prop_type}-{loc_name}/{univ_name}-{prop_type}-{loc_name}-{post_name}-{loc_key}-{offset}.html
  5516. ###############################################################################################################################################
  5517. else if ($is_property_one && $is_rooms_all && $is_critera_default) {
  5518. $string = $_GET_INFOS['univers'];
  5519. switch ($string) {
  5520. case '1' : $url_unv_name = 'vente';
  5521. break;
  5522. case '2' : $url_unv_name = 'location';
  5523. break;
  5524. case '8' : $url_unv_name = 'colocation';
  5525. break;
  5526. }
  5527. $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';
  5528. }
  5529. ###############################################################################################################################################
  5530. # 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
  5531. ###############################################################################################################################################
  5532. else if ($is_property_one && $is_rooms_one && $is_critera_default) {
  5533. $string = $_GET_INFOS['univers'];
  5534. switch ($string) {
  5535. case '1' : $url_unv_name = 'vente';
  5536. break;
  5537. case '2' : $url_unv_name = 'location';
  5538. break;
  5539. case '8' : $url_unv_name = 'colocation';
  5540. break;
  5541. }
  5542. $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';
  5543. }
  5544. //echo "[common.functions : uriToFinalFromDirectLink : url = $url]\n"; //exit();
  5545. return $url;
  5546. }
  5547. /**
  5548. * @author B.Moinet
  5549. * @since 13/12/2011
  5550. * Retourne une chaine formatté pour être utilisée par la variable XiTi 'xtpage' (cf p.15 PDF XiTi)
  5551. * Seuls caractères acceptés : abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123467890./-_~
  5552. *
  5553. * @param string str chaine à traiter
  5554. */
  5555. function clean_xiti($str) {
  5556. $ret = TextNoAccent($str);
  5557. $pattern = '/([^a-zA-Z²0-9.\/_:~-])/';
  5558. $replace = '_';
  5559. $ret = preg_replace($pattern, $replace, $ret);
  5560. return $ret;
  5561. }
  5562. /**
  5563. * @author B.Moinet
  5564. * @since 13/12/2011
  5565. * Retourne une chaine au pluriel (ajoute un 's' final, uniquement si besoin)
  5566. *
  5567. * @param string str chaine à traiter
  5568. */
  5569. function make_plurial($str) {
  5570. $ret = $str;
  5571. $last_char = $str[strlen($str) - 1];
  5572. if ($last_char != 's')
  5573. $ret .= 's';
  5574. return $ret;
  5575. }
  5576. function genereAdvX($type, $str) {
  5577. global $_ADVANCED_SEARCH_CAT;
  5578. $advanced = $str;
  5579. // Récupérer la liste des critères sans les catégories
  5580. // => Plus simple à interroger
  5581. $advanced_search = array();
  5582. foreach ($_ADVANCED_SEARCH_CAT as $SUB_CAT) {
  5583. $advanced_search += $SUB_CAT;
  5584. }
  5585. $advanced_search = $_ADVANCED_SEARCH_CAT[$type];
  5586. $str_advanced = '';
  5587. $length = strlen($advanced);
  5588. $pos = -1;
  5589. while (($pos = strpos($advanced, '1', $pos + 1)) !== false) {
  5590. if ($advanced_search[$pos]) {
  5591. $elt_advanced = $advanced_search[$pos];
  5592. $elt_advanced = str_replace(' ', '', $elt_advanced);
  5593. $elt_advanced = str_replace('/', '', $elt_advanced);
  5594. $elt_advanced = strtolower($elt_advanced);
  5595. $elt_advanced = TextNoAccent($elt_advanced);
  5596. $str_advanced .= ',[' . $elt_advanced . ']';
  5597. }
  5598. }
  5599. return substr($str_advanced, 1);
  5600. }
  5601. /**
  5602. *
  5603. * @param array $nav_array tableau des elements du menu
  5604. * @return aray tableau avec les elements de la sous nav
  5605. */
  5606. function get_sous_nav($nav_array) {
  5607. foreach ($nav_array as $item) {
  5608. if (is_array($item)) {
  5609. $sous_nav[] = $item;
  5610. }
  5611. }
  5612. return $sous_nav;
  5613. }
  5614. /**
  5615. *
  5616. * @param string $count nombre initial
  5617. * @return aray tableau des chiffres
  5618. */
  5619. function split_counter($count) {
  5620. $tab_chiffre = str_split($count);
  5621. foreach ($tab_chiffre as $k => &$chf) {
  5622. if ($chf != ' ') {
  5623. $class = 'chf_hp' . $chf;
  5624. }else
  5625. $class = 'chf_hp_break';
  5626. $chf = "<span class='$class nobackground'>$chf</span>";
  5627. }
  5628. return implode('', $tab_chiffre);
  5629. }
  5630. function get_suggestion_links($univers_id) {
  5631. // 'locname' est la valeur a donner pour le input text 'loc_name1' et 'lockey' celle pour le input hidden 'loc_key1'
  5632. // pour sauvegarder ces valeurs dans le cookie 'user_srch' au moment du clic sur le lien avant d'afficher la PR
  5633. // (fait via la fonction JS update_inputs_hp(locname, lockey) qui met a jour les champs de la HP)
  5634. $groupLinks = array(
  5635. 'rentLinks' => array(
  5636. array(
  5637. 'url' => '/appartement-paris/location-appartement-paris-75-100_1.html',
  5638. 'text' => 'Paris',
  5639. 'title' => 'Appartement Paris',
  5640. 'locname' => 'PARIS (75)',
  5641. 'lockey' => '100_1'
  5642. ),
  5643. array(
  5644. 'url' => '/appartement-marseille/location-appartement-marseille-tous-codes-postaux-421_99.html',
  5645. 'text' => 'Marseille',
  5646. 'title' => 'Appartement Marseille',
  5647. 'locname' => 'MARSEILLE (TOUS CODES POSTAUX)',
  5648. 'lockey' => '421_99'
  5649. ),
  5650. array(
  5651. 'url' => '/appartement-lyon/location-appartement-lyon-tous-codes-postaux-422_99.html',
  5652. 'text' => 'Lyon',
  5653. 'title' => 'Appartement Lyon',
  5654. 'locname' => 'LYON (TOUS CODES POSTAUX)',
  5655. 'lockey' => '422_99'
  5656. ),
  5657. array(
  5658. 'url' => '/appartement-calvados/location-appartement-calvados-14-36_1.html',
  5659. 'text' => 'Calvados',
  5660. 'title' => 'Appartement Calvados',
  5661. 'locname' => 'CALVADOS (14)',
  5662. 'lockey' => '36_1'
  5663. ),
  5664. array(
  5665. 'url' => '/appartement-paris-17e/location-appartement-paris-17e-75017-23596_2.html',
  5666. 'text' => '75017',
  5667. 'title' => 'Appartement 75017',
  5668. 'locname' => 'PARIS 17E (75017)',
  5669. 'lockey' => '23596_2'
  5670. )
  5671. ),
  5672. 'salesLinks' => array(
  5673. array(
  5674. 'url' => '/appartement-paris/vente-appartement-paris-75-100_1.html',
  5675. 'text' => 'Paris',
  5676. 'title' => 'Appartement Paris',
  5677. 'locname' => 'PARIS (75)',
  5678. 'lockey' => '100_1'
  5679. ),
  5680. array(
  5681. 'url' => '/appartement-marseille/vente-appartement-marseille-tous-codes-postaux-421_99.html',
  5682. 'text' => 'Marseille',
  5683. 'title' => 'Appartement Marseille',
  5684. 'locname' => 'MARSEILLE (TOUS CODES POSTAUX)',
  5685. 'lockey' => '421_99'
  5686. ),
  5687. array(
  5688. 'url' => '/appartement-lyon/vente-appartement-lyon-tous-codes-postaux-422_99.html',
  5689. 'text' => 'Lyon',
  5690. 'title' => 'Appartement Lyon',
  5691. 'locname' => 'LYON (TOUS CODES POSTAUX)',
  5692. 'lockey' => '422_99'
  5693. ),
  5694. array(
  5695. 'url' => '/appartement-calvados/vente-appartement-calvados-14-36_1.html',
  5696. 'text' => 'Calvados',
  5697. 'title' => 'Appartement Calvados',
  5698. 'locname' => 'CALVADOS (14)',
  5699. 'lockey' => '36_1'
  5700. ),
  5701. array(
  5702. 'url' => '/appartement-paris-17e/vente-appartement-paris-17e-75017-23596_2.html',
  5703. 'text' => '75017',
  5704. 'title' => 'Appartement 75017',
  5705. 'locname' => 'PARIS 17E (75017)',
  5706. 'lockey' => '23596_2'
  5707. )
  5708. )
  5709. );
  5710. $html = array(
  5711. 'rentLinks' => array(),
  5712. 'salesLinks' => array()
  5713. );
  5714. foreach ($groupLinks['rentLinks'] as $link) {
  5715. $html['rentLinks'][] = '<a onclick="update_inputs_hp(\'' . $link['locname'] . '\', \'' . $link['lockey'] . '\')" href="' . to_url($link['url']) . '" title="' . $link['title'] . '">' . $link['text'] . '</a>';
  5716. }
  5717. foreach ($groupLinks['salesLinks'] as $link) {
  5718. $html['salesLinks'][] = '<a onclick="update_inputs_hp(\'' . $link['locname'] . '\', \'' . $link['lockey'] . '\')" href="' . to_url($link['url']) . '" title="' . $link['title'] . '">' . $link['text'] . '</a>';
  5719. }
  5720. return $html;
  5721. }
  5722. function is_in_poi_area($ad) {
  5723. //Les POI ne doivent apparaître que sur Paris, Marseille, Lyon, Toulouse, Bordeaux, Strasbourg et Lille :
  5724. //Annonce ciblée sur :
  5725. // 1) un code postal correspondant à l'une de ces villes
  5726. // 2) le département Paris
  5727. $lgn_ids = array(
  5728. 421, //Marseille
  5729. 422, //Lyon
  5730. 393, //Toulouse
  5731. 49, //Bordeaux
  5732. 382, //Strasbourg
  5733. 193 //Lille
  5734. );
  5735. if (in_array($ad['lgn_id'], $lgn_ids) || $ad['hierarchy'][1]['lct_id'] == 100) {
  5736. return true;
  5737. } else
  5738. return false;
  5739. }
  5740. function is_in_district_area($ad) {
  5741. //Les Quartiers ne doivent apparaître que sur Paris, Lyon, Marseille, Lille, Toulouse, Montpellier, Nice et Strasbourg
  5742. //Annonce ciblée sur :
  5743. // 1) un code postal correspondant à l'une de ces villes
  5744. // 2) le département Paris
  5745. $lgn_ids = array(
  5746. 421, //Marseille
  5747. 422, //Lyon
  5748. 393, //Toulouse
  5749. 382, //Strasbourg
  5750. 193, //Lille
  5751. 244, // Nice
  5752. 232, // Montpellier
  5753. 49 //Bordeaux
  5754. );
  5755. if (in_array($ad['lgn_id'], $lgn_ids) || $ad['hierarchy'][1]['lct_id'] == 100) {
  5756. return true;
  5757. } else
  5758. return false;
  5759. }
  5760. /**
  5761. * Checking if the specified lctid is a DomTom
  5762. * @param string $lctid
  5763. * @return bool
  5764. */
  5765. function is_domtom($post_code) {
  5766. if (substr($post_code, 0, 2) > '95' && $post_code != '98000') {
  5767. return true;
  5768. } else
  5769. return false;
  5770. }
  5771. /**
  5772. * Transforme un fichier xml en tableau PHP
  5773. * @param type $fname
  5774. * @return type
  5775. */
  5776. function xml2array($fname) {
  5777. $sxi = new SimpleXmlIterator($fname, null, true);
  5778. return sxiToArray($sxi);
  5779. }
  5780. function sxiToArray($sxi) {
  5781. $a = array();
  5782. for ($sxi->rewind(); $sxi->valid(); $sxi->next()) {
  5783. if (!array_key_exists($sxi->key(), $a)) {
  5784. $a[$sxi->key()] = array();
  5785. }
  5786. if ($sxi->hasChildren()) {
  5787. $a[$sxi->key()][] = sxiToArray($sxi->current());
  5788. } else {
  5789. $a[$sxi->key()] = strval($sxi->current());
  5790. }
  5791. }
  5792. return $a;
  5793. }
  5794. /**
  5795. * Localiser l internaute en fonction de son IP en se basant sur le cache MAXMIND
  5796. * @param bool $no_cookie : Ignorer le cookie ou pas
  5797. * @author: W.ASBAITI
  5798. * @since: 12/06/2012
  5799. * @return stdobject $data avec les ville, departement et region de l'ip a localiser
  5800. */
  5801. function geoLocateByIp($no_cookie = false) {
  5802. /*
  5803. echo "no_cookie = "; var_dump($no_cookie);
  5804. echo "user_geoloc = "; var_dump($_COOKIE['user_geoloc']);
  5805. echo "geoip = "; var_dump($_REQUEST['geoip']);
  5806. */
  5807. // Si la valeur est deja stockee ds cookie, renvoie le contenue du cookie
  5808. if (!empty($_COOKIE['user_geoloc']) && !$no_cookie && empty($_REQUEST['geoip'])) {
  5809. //echo "Cas 1";
  5810. return json_decode($_COOKIE['user_geoloc']);
  5811. exit;
  5812. } else if ($_REQUEST['geoip']) {
  5813. $longIP = $_REQUEST['geoip'];
  5814. //echo "Cas 2 : longIP = ".$longIP;
  5815. } else {
  5816. $ip = $_SERVER['REMOTE_ADDR'];
  5817. // GEOLOC A PARTIR DU FICHER DE CACHE
  5818. $longIP = ip2long($ip);
  5819. //echo "Cas 3 : longIP = $longIP";
  5820. }
  5821. // echo $longIP."\n";
  5822. // pour test => ip situé a GENNEVILLIER (cf bastien)
  5823. // $ip = '81.56.88.137';
  5824. // Repertoire contenant les localites proches de l'IP
  5825. $cacheDir = CACHE_GEOLOC . substr($longIP, 0, 3) . '/' . substr($longIP, 3, 3);
  5826. // liste des fichiers de cache
  5827. $cacheFiles = glob($cacheDir . '/*.txt');
  5828. if (sizeof($cacheFiles) > 0) {
  5829. foreach ($cacheFiles as $cacheFile) {
  5830. // le nom du fichier => ip2longmin-ip2longmax.txt qui sont situé dans une ville
  5831. $interval = explode('-', str_replace('.txt', '', basename($cacheFile)));
  5832. if ($longIP <= $interval[1] && $longIP >= $interval[0]) {
  5833. $data = json_decode(file_get_contents($cacheFile));
  5834. //echo "Trouve : longIP = "; var_dump($longIP);
  5835. //echo "Trouve : cacheFile = "; var_dump($cacheFile);
  5836. // var_dump($data); die;
  5837. return $data;
  5838. }
  5839. }
  5840. }
  5841. //echo "PAS TROUVE dans $cacheDir";
  5842. }
  5843. /**
  5844. * Prise en charge des accent sur strtoupper (pas fait dans l'autre version)
  5845. * @param type $chaine
  5846. * @return type
  5847. */
  5848. function v7_uc_strtoupper_fr($chaine) {
  5849. $chaine = strtoupper($chaine);
  5850. $chaine = trim($chaine);
  5851. $chaine = strtr($chaine, “äâàáåãéèëêòóôõöøìíîïùúûüýñçþÿæœðø”, ”ÄÂÀÁÅÃÉÈËÊÒÓÔÕÖØÌÍÎÏÙÚÛÜÝÑÇÞÝƌÐؔ);
  5852. return $chaine;
  5853. }
  5854. function getPolygoneByDistrictId($id = null) {
  5855. $sql = "SELECT polygone_quartier FROM T_DISTRICT_DIS";
  5856. $sql .= " WHERE id_quartier ='" . $id . "' ";
  5857. //if (function_exists("pdoquery")){ echo "FUNCTIoN EXIST"; }
  5858. $result_query = pdoquery($sql);
  5859. return ($result_query[0]['polygone_quartier']);
  5860. }
  5861. /**
  5862. * Redirection des mini sites villes sans ciontenu vers la page de l edition liee a cette ville (M INFORMEr)
  5863. * @param String $ville : Le nom de la ville
  5864. * @return void Ne retourne rien, mais redirige vers la bonne page
  5865. */
  5866. function msVilleToHpInformer($ville) {
  5867. // Tableau dans session.settings.php
  5868. global $cp_editions;
  5869. global $dpt_edition;
  5870. // Include des fichiers necessaires a la recup de l edition
  5871. $real_file = dirname(__FILE__);
  5872. require_once $real_file . '/../DISPLAY/ajax/json.php';
  5873. require_once("$real_file/../DISPLAY/informer/infos.functions.php");
  5874. require_once("$real_file/informer_static.class.php");
  5875. require_once("$real_file/informer_article.class.php");
  5876. require_once("$real_file/informer_chapitre.class.php");
  5877. require_once("$real_file/informer_insert.class.php");
  5878. require_once("$real_file/informer_dossier.class.php");
  5879. require_once("$real_file/informer_edition.class.php");
  5880. // Recuperer le CP de la ville courante
  5881. $ville_data = get_loc_names($ville);
  5882. if (sizeof($ville_data) > 0) {
  5883. $CP = $ville_data[0]['lct_post_code'];
  5884. $dptCP = substr($CP, 0, 2);
  5885. // Recuperation de l id de l edition a partir du CP de l annonce
  5886. foreach ($cp_editions as $k => $edition) {
  5887. $key = array_search($CP, $edition);
  5888. if ($key !== false) {
  5889. $id_edition = $k;
  5890. break;
  5891. }
  5892. }
  5893. if (empty($id_edition)) {
  5894. // Recuperation de l id de l edition a partir du CP d'une annonce
  5895. foreach ($dpt_edition as $k => $edition) {
  5896. $key = array_search($dptCP, $edition);
  5897. if ($key !== false) {
  5898. $id_edition = $k;
  5899. break;
  5900. }
  5901. }
  5902. }
  5903. if (empty($id_edition)) {// REDIRECTION vers la HP INFORMER (localisee en fnction de la recherche)
  5904. informer_static::localiser_hp();
  5905. exit();
  5906. } else {
  5907. $url = informer_static::get_hp_url('edition', $k, $edition_number[$k]);
  5908. header("location: $url");
  5909. exit();
  5910. }
  5911. } else { // REDIRECTION vers la HP INFORMER (localisee en fnction de la recherche)
  5912. informer_static::localiser_hp();
  5913. }
  5914. }
  5915. function storecookie($inKey, $inValue, $inExpire) {
  5916. $decode = serialize($inValue);
  5917. $decode = gzcompress($decode);
  5918. $decode = base64_encode($decode);
  5919. $split = str_split($decode, 4000); //4k pieces
  5920. $count = count($split);
  5921. for ($index = 0; $index < $count; $index += 1) {
  5922. $result = setcookie(( $index > 0 ) ? $inKey . COOKIE_PORTIONS . $index : $inKey, $split[$index], $inExpire, '/', '', 0);
  5923. }
  5924. clearpieces($inKey, $count);
  5925. }
  5926. function fetchcookie($inKey) {
  5927. $decode = $_COOKIE[$inKey];
  5928. for ($index = 1; array_key_exists($inKey . COOKIE_PORTIONS . $index, $_COOKIE); $index += 1) {
  5929. $decode .= $_COOKIE[$inKey . COOKIE_PORTIONS . $index];
  5930. }
  5931. if (!empty($decode)) {
  5932. $decode = base64_decode($decode);
  5933. $decode = gzuncompress($decode);
  5934. }
  5935. return unserialize($decode);
  5936. }
  5937. function clearpieces($inKey, $inFirst) {
  5938. $expire = time() - 3600;
  5939. for ($index = $inFirst; array_key_exists($inKey . COOKIE_PORTIONS . $index, $_COOKIE); $index += 1) {
  5940. setcookie($inKey . COOKIE_PORTIONS . $index, '', $expire, '/', '', 0);
  5941. unset($_COOKIE[$inKey . COOKIE_PORTIONS . $index]);
  5942. }
  5943. }
  5944. /**
  5945. * Function getAdvancedParams : format advanced params from BDD
  5946. * @author Melissa Hoarau
  5947. * @params $aAdvancedParams : array of advanced params for an ad
  5948. * @Return $aFinalAdvancedParams : array of formated and classed advanced params
  5949. *
  5950. */
  5951. function getAdvancedParams($aAdvancedParams) {
  5952. global $_ADVANCED_SEARCH_CRIT;
  5953. global $_ADVANCED_SEARCH_CAT;
  5954. $dependances = array();
  5955. $chauffage = array();
  5956. $amenagementInterieur = array();
  5957. $confortSecurite = array();
  5958. $aFinalAdvancedParams = array();
  5959. foreach ($aAdvancedParams as $sAdvancedparam) {
  5960. foreach ($_ADVANCED_SEARCH_CRIT as $critId => $critVarName) {
  5961. if ($sAdvancedparam == $critVarName) {
  5962. // si ce critère fait partie de dépendances
  5963. if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['dépendances']))) {
  5964. $critName = $_ADVANCED_SEARCH_CAT['dépendances'][$critId];
  5965. $dependances[] = "[$critName]";
  5966. // si ce critère fait partie de chauffage
  5967. } else if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['chauffage']))) {
  5968. $critName = $_ADVANCED_SEARCH_CAT['chauffage'][$critId];
  5969. $chauffage[] = "[$critName]";
  5970. // si ce critère fait partie de aménagement
  5971. } else if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['aménagement intérieur']))) {
  5972. $critName = $_ADVANCED_SEARCH_CAT['aménagement intérieur'][$critId];
  5973. $amenagementInterieur[] = "[$critName]";
  5974. // si ce critère fait partie de confort
  5975. } else if (in_array($critId, array_keys($_ADVANCED_SEARCH_CAT['confort et sécurité']))) {
  5976. $critName = $_ADVANCED_SEARCH_CAT['confort et sécurité'][$critId];
  5977. $confortSecurite[] = "[$critName]";
  5978. }
  5979. }
  5980. }
  5981. }
  5982. $aFinalAdvancedParams = array('dependances' => $dependances, 'chauffage' => $chauffage, 'amenagementInterieur' => $amenagementInterieur, 'confortSecurite' => $confortSecurite);
  5983. return $aFinalAdvancedParams;
  5984. }
  5985. function recursive_loc($idtown, $level, $nblevel = 3, &$tab_hierarchy_loc = array()) {
  5986. $sql = "SELECT lct_name, lct_id, lct_parent_id, lct_level, lct_name, lct_post_code, lgn_id, lgc_id ";
  5987. $sql .= "FROM db1.T_LOCALITY_LCT_FR ";
  5988. //$sql .= "WHERE lct_id = $idtown ";
  5989. //$sql .= "AND lct_id = $idtown ";
  5990. if ($level == 98) {
  5991. $level = 2;
  5992. $sql .= "WHERE lgc_id = $idtown ";
  5993. } elseif ($level == 99) {
  5994. $level = 2;
  5995. $sql .= "WHERE lgn_id = $idtown ";
  5996. } else {
  5997. $sql .= "WHERE lct_id = $idtown ";
  5998. }
  5999. $sql .= "LIMIT 1 ";
  6000. $res_loc = pdoquery($sql);
  6001. //echo "\n".$sql."\n";
  6002. $idtown = $res_loc[0]['lct_parent_id'];
  6003. //var_dump($res_loc);
  6004. $tlevel = $res_loc[0]['lct_level'];
  6005. if (count($res_loc) == 0) {
  6006. //echo "\n SORTIE DE BOUCLE :: $nblevel \n";
  6007. return false;
  6008. }
  6009. $tab_hierarchy_loc[$tlevel] = $res_loc[0];
  6010. //echo "\n Y :: $nblevel\n";
  6011. //echo "\n$idtown\n";
  6012. if ($nblevel > 0) {
  6013. return (recursive_loc($idtown, $level, $nblevel - 1, $tab_hierarchy_loc));
  6014. }
  6015. return $idtown;
  6016. }
  6017. function xiti_string($str) {
  6018. $str = str_replace(array("'", "&#039;"), '', $str);
  6019. $str = preg_replace('~(#[0-9]*;)~', '', $str);
  6020. $str = str_replace('&', '', $str);
  6021. return $str;
  6022. }
  6023. /**
  6024. * retourne un tableau avec les infos de l agence correspondant a l id presto donne
  6025. * @param string $id_presto
  6026. * @return array
  6027. */
  6028. function findAgcByIdPresto($id_presto){
  6029. $sQuery = "SELECT
  6030. id_agence AS id, agc_name AS name, agc_company_name, agc_post_code AS lzip, agc_town_agency AS town,
  6031. agc_country AS country, agc_default_town_2, agc_default_town_1, agc_default_town_0, lgc_id, lgn_id, agc_loc_id_0,
  6032. agc_loc_id_1, agc_loc_id_2, agc_site, agc_is_powersite, agc_powersite_url, agc_powersite_calltracking, agc_is_logo,
  6033. agc_is_directory, agc_is_website
  6034. FROM T_AGENCY_AGC
  6035. WHERE md5(id_presto) = '$id_presto'
  6036. LIMIT 1"
  6037. ;
  6038. $result = pdoquery($sQuery, null, null, null, false, true);
  6039. $return = $result[0];
  6040. return $return;
  6041. }
  6042. /**
  6043. * Function getLibellePersonnalisable : retourne le libelle du bandeau selon l'id
  6044. * @param int $iIdPersonnalisable
  6045. * @return string $sLibelleBandeau
  6046. */
  6047. function getLibellePersonnalisable($iIdPersonnalisable){
  6048. $sQuery = 'SELECT T_BANDEAUX_LIBELLE FROM T_BANDEAUX_PERSO WHERE T_BANDEAUX_ID = ' . $iIdPersonnalisable;
  6049. $result = pdoquery($sQuery, null, null, null, false, true);
  6050. $sLibelleBandeau = $result[0]['T_BANDEAUX_LIBELLE'];
  6051. return $sLibelleBandeau;
  6052. }
  6053. /**
  6054. * Function getCodeDescXitiPubAffich : retourne le code de description du hit d'affichage
  6055. * @global array of string $_ARR_CODE_PUBLISHER_AFFICH : contient les codes par page et type d'annonce
  6056. * @param string $page
  6057. * @param string $tpl_code
  6058. * @param string $lib_bandeau
  6059. * @return string $sCodeDesc
  6060. */
  6061. function getCodeDescXitiPubAffich($page, $tpl_code, $lib_bandeau = '') {
  6062. global $_ARR_CODE_PUBLISHER_AFFICH;
  6063. global $_global;
  6064. $sCodeDesc = '';
  6065. // Exclusivité
  6066. if ($tpl_code == 'o') {
  6067. $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['ORPI'];
  6068. // if ($page == 'PR') {
  6069. // echo '<br/>ORPI' . $sCodeDesc . '<br/>';
  6070. // }
  6071. }
  6072. // Neuf
  6073. else if ($tpl_code == '9') {
  6074. $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['NEUF'];
  6075. // if ($page == 'PR') {
  6076. // echo '<br/>NEUF' . $sCodeDesc . '<br/>';
  6077. // }
  6078. }
  6079. // Perso
  6080. else if (($_global['dev'] || $_global['pre_prod']) && !empty($lib_bandeau)) {
  6081. $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['PERSO'];
  6082. // if ($page == 'PR') {
  6083. // echo '<br/>PERSO' . $sCodeDesc . '<br/>';
  6084. // }
  6085. }
  6086. // Ala une
  6087. else if ($tpl_code == 'p') {
  6088. $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['ALAUNE'];
  6089. // if ($page == 'PR') {
  6090. // echo '<br/>ALAUNE' . $sCodeDesc . '<br/>';
  6091. // }
  6092. }
  6093. // Standard
  6094. else {
  6095. $sCodeDesc = $_ARR_CODE_PUBLISHER_AFFICH[$page]['STD'];
  6096. // if ($page == 'PR') {
  6097. // echo '<br/>STD' . $sCodeDesc . '<br/>';
  6098. // }
  6099. }
  6100. return $sCodeDesc;
  6101. }
  6102. /*
  6103. * Récupération du code postal et du loc_key
  6104. * - de la dernière recherche de l'internaute (stockée dans cookie), si existante
  6105. * - sinon de la localité de l'internaute (basée du son IP), si existante
  6106. * - sinon de la localité de Paris
  6107. */
  6108. function getParamSearchOrGeolocByIP() {
  6109. $param_search = array();
  6110. /* Accès au cookie de recherche */
  6111. $val_cookie = "";
  6112. if ( isset($_COOKIE[SEARCH_HISTORY_COOKIE_NAME]) ) {
  6113. // revisite de l'utilisateur
  6114. $val_cookie = $_COOKIE[SEARCH_HISTORY_COOKIE_NAME];
  6115. }
  6116. // revisite (après recherche)
  6117. if (trim($val_cookie) <> "") {
  6118. $firstvisit = false;
  6119. /* Décomposition du cookies */
  6120. $param_search = fetchcookie(SEARCH_HISTORY_COOKIE_NAME);
  6121. // the real last search is always at the row number 0
  6122. $param_search = unserialize($param_search[0]);
  6123. //echo "param_search : "; var_dump($param_search);
  6124. if (!isset($param_search['szip'])) {
  6125. $param_search['szip'] = '75';
  6126. $param_search['loc_key1'] = '100_1';
  6127. } else if ($param_search['szip'] > 95) { // DOM TOM
  6128. $param_search['szip'] = substr($param_search['lzip'], 0, 3);
  6129. }
  6130. //echo "param_search : "; var_dump($param_search);
  6131. /* 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) */
  6132. if (!isset($param_search['loc_key1']) || empty($param_search['loc_key1']) || ($param_search['loc_key1']=='_')) {
  6133. $firstvisit = true;
  6134. $user_loc_data = get_object_vars(geoLocateByIp());
  6135. if (is_array($user_loc_data) && !empty($user_loc_data['postalCode'])) {
  6136. $param_search['szip'] = substr($user_loc_data['postalCode'], 0,2);
  6137. for($i=2; $i>=0; $i--){
  6138. // var_dump($user_loc_data["loc_id_$i"]);
  6139. if($user_loc_data["loc_id_$i"]) {
  6140. $param_search['loc_key1'] = $user_loc_data["loc_id_$i"]."_$i";
  6141. break;
  6142. }
  6143. }
  6144. } else {
  6145. // on part sur Paris, à défaut d'avoir un service de géoloc
  6146. $param_search['szip'] = '75';
  6147. $param_search['loc_key1'] = '100_1';
  6148. }
  6149. }
  6150. } else {
  6151. // première recherche
  6152. $firstvisit = true;
  6153. $user_loc_data = get_object_vars(geoLocateByIp());
  6154. if (is_array($user_loc_data) && !empty($user_loc_data['postalCode'])) {
  6155. $param_search['szip'] = substr($user_loc_data['postalCode'], 0,2);
  6156. for($i=2; $i>=0; $i--){
  6157. // var_dump($user_loc_data["loc_id_$i"]);
  6158. if($user_loc_data["loc_id_$i"]) {
  6159. $param_search['loc_key1'] = $user_loc_data["loc_id_$i"]."_$i";
  6160. break;
  6161. }
  6162. }
  6163. } else {
  6164. // on part sur Paris, à défaut d'avoir un service de géoloc
  6165. $param_search['szip'] = '75';
  6166. $param_search['loc_key1'] = '100_1';
  6167. }
  6168. }
  6169. //echo "param_search : "; var_dump($param_search);
  6170. return $param_search;
  6171. }
  6172. /**
  6173. * Function getCodeDescXitiPubAction : retourne le code de description du hit d'action
  6174. * @global array of string $_ARR_CODE_PUBLISHER_ACTION : contient les codes par page et type d'annonce
  6175. * @param string $action
  6176. * @param string $tpl_code
  6177. * @param string $page
  6178. * @param string $lib_bandeau
  6179. * @return string $sCodeDesc
  6180. */
  6181. function getCodeDescXitiPubAction($action, $page, $tpl_code, $lib_bandeau = '') {
  6182. global $_ARR_CODE_PUBLISHER_ACTION;
  6183. global $_global;
  6184. $sCodeDesc = '';
  6185. // Exclusivité
  6186. if ($tpl_code == 'o') {
  6187. $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['ORPI'];
  6188. }
  6189. // Neuf
  6190. else if ($tpl_code == '9') {
  6191. $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['NEUF'];
  6192. }
  6193. // Perso
  6194. else if (($_global['dev'] || $_global['pre_prod']) && !empty($lib_bandeau)) {
  6195. $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['PERSO'];
  6196. }
  6197. // Ala une
  6198. else if ($tpl_code == 'p') {
  6199. $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['ALAUNE'];
  6200. }
  6201. // Standard
  6202. else {
  6203. $sCodeDesc = $_ARR_CODE_PUBLISHER_ACTION[$action][$page]['STD'];
  6204. }
  6205. return $sCodeDesc;
  6206. }
  6207. function get_search_summary_from_cookie() {
  6208. $LISearchCookie = fetchcookie('LISearchHistoryCookieCompressed');
  6209. if($LISearchCookie != null) {
  6210. $aSearchParameters = unserialize($LISearchCookie[0]);
  6211. $summary = get_all_summary($aSearchParameters);
  6212. return $summary;
  6213. } else {
  6214. return null;
  6215. }
  6216. }
  6217. function is_appartager($sIdPresto) {
  6218. $aAppartagerIdPrestos = array('1103802', 'CMM-PT-APPARTAGER');
  6219. if(in_array($sIdPresto, $aAppartagerIdPrestos))
  6220. return true;
  6221. else
  6222. return false;
  6223. }
  6224. /*
  6225. * Retourne le nom d'une transaction sous sa forme "normale" (avec
  6226. * des espaces entre les mots) à partir d'un nom de transaction sous
  6227. * sa forme CamelCase (ex: VenteNeuf => Vente Neuf)
  6228. */
  6229. function get_transaction_name_from_camel_case($trans_name) {
  6230. //echo "[trans_name = $trans_name]";
  6231. $trans_name_new = preg_replace('/(?!^)[[:upper:]]/',' \0', $trans_name);
  6232. return $trans_name_new;
  6233. }
  6234. /*
  6235. * Retourne 'horizontal' ou 'vertical' selon si la photo est
  6236. * d'orientation portrait ou paysage. Si image carrée, retourne 'horizontal'.
  6237. * Si problème de chargement de l'image, retourne false.
  6238. */
  6239. function get_image_orientation_from_image_path($image_path) {
  6240. //echo "[image_path = $image_path]";
  6241. // image introuvable sur disque
  6242. if (!file_exists($filename)) return false;
  6243. // NB: cette fonction ne nécessite pas la bibliothèque GD
  6244. // voir http://www.php.net/manual/fr/function.getimagesize.php
  6245. $arr_infos = getimagesize($image_path);
  6246. // erreur lors de la lecture de l'image
  6247. if (empty($arr_infos)) return false;
  6248. list($width, $height, $type, $attr) = $arr_infos;
  6249. //echo "[arr_infos = ".var_dump($arr_infos."]";
  6250. // image vide
  6251. if (((int)$width == 0) && ((int)$height == 0)) return false;
  6252. if ((int)$width == (int)$height) return 'horizontal'; // photo carrée
  6253. else if ((int)$width < (int)$height) return 'horizontal'; // photo paysage
  6254. else return 'vertical'; // photo portrait
  6255. }
  6256. function get_dept_by_postcode($postcode) {
  6257. $query = "SELECT lct_parent_id, lct_id, lct_name, lct_name_fr, lct_post_code, lct_prg_pondering, lct_level
  6258. FROM T_LOCALITY_LCT_FR
  6259. WHERE lct_level = 1
  6260. AND lct_post_code = '$postcode'
  6261. ";
  6262. $result = pdoquery($query);
  6263. return $result;
  6264. }
  6265. ?>