| Current Path : /home/h/a/p/happyrenas/myreco.online/includes/ |
Linux webd005.cluster105.gra.hosting.ovh.net 5.15.206-ovh-vps-grsec-zfs-classid #1 SMP Fri May 15 02:41:25 UTC 2026 x86_64 |
| Current File : /home/h/a/p/happyrenas/myreco.online/includes/fonctions.php |
<?
include("fonctions_divers.php");
include("fonctions_image.php");
include("fonctions_qrcode.php");
include("fonctions_hebergements.php");
include("fonctions_administrateur.php");
/**********************************
* đźšš ALGORITHME DE CORRESPONDANCE
*********************************/
function genererCorrespondance($token)
{
global $db;
global $pays;
global $categories;
if (!$token) {
return [
'statut' => 'erreur',
'statut_detail' => 'Pas de token',
];
}
$myquery = "SELECT * from heb WHERE token = '".$token."'";
$fiche = $db->get_row($myquery);
$hebergement_id=$fiche->id;
if (!$hebergement_id) {
return [
'statut' => 'erreur',
'statut_detail' => 'Pas de hebergement_id',
];
}
$requete_update = "UPDATE heb set visite_note_minimale='4' where id=".$hebergement_id." AND visite_note_minimale =''";
$db->query($requete_update);
$fiche->latitude = str_replace(",",".",$fiche->latitude);
$fiche->longitude = str_replace(",",".",$fiche->longitude);
$fiche->visite_note_minimale = str_replace(".",",",$fiche->visite_note_minimale);
$proche = [];
$median = [];
$lointain = [];
// ---------------------- //
// Traitement PROCHES //
// ---------------------- //
foreach ($categories as $categorie) {
$proche[$categorie] = [];
$myquery = "
SELECT
id, latitude, longitude, categorie, rating, reviews,
(CASE
WHEN is_bonus = 1 THEN (rating * 0.9 + 0.2 * log10(reviews + 1))
ELSE (rating * 0.8 + 0.2 * log10(reviews + 1))
END) AS classement
FROM vis
WHERE categorie = '" . $db->escape($categorie) . "'
AND rating >= '" . floatval($fiche->visite_note_minimale) . "'
ORDER BY classement DESC
";
$resultats = $db->get_results($myquery);
foreach ($resultats ?? [] as $visite) {
if (count($proche[$categorie]) < 60) {
$lat = str_replace(",", ".", $visite->latitude);
$lon = str_replace(",", ".", $visite->longitude);
$distance = round(calculerDistance($fiche->latitude, $fiche->longitude, $lat, $lon), 0);
if ($distance <= 30) {
$db->query("UPDATE vis SET utilise_dans_qr = 1 WHERE id = " . intval($visite->id));
$proche[$categorie][] = [
'visite_id' => $visite->id,
'distance' => $distance,
'classement' => $visite->classement
];
}
}
}
}
// ---------------------- //
// Traitement MEDIANS //
// ---------------------- //
foreach ($categories as $categorie) {
$median[$categorie] = [];
$myquery = "
SELECT
id, latitude, longitude, categorie, rating, reviews,
(CASE
WHEN is_bonus = 1 THEN (rating * 0.8 + 0.3 * log10(reviews + 1))
ELSE (rating * 0.7 + 0.3 * log10(reviews + 1))
END) AS classement
FROM vis
WHERE categorie = '" . $db->escape($categorie) . "'
AND rating >= '" . floatval($fiche->visite_note_minimale) . "'
ORDER BY classement DESC
";
$resultats = $db->get_results($myquery);
foreach ($resultats ?? [] as $visite) {
if (count($median[$categorie]) < 30) {
$lat = str_replace(",", ".", $visite->latitude);
$lon = str_replace(",", ".", $visite->longitude);
$distance = round(calculerDistance($fiche->latitude, $fiche->longitude, $lat, $lon), 0);
if ($distance > 30 && $distance <= 60) {
$db->query("UPDATE vis SET utilise_dans_qr = 1 WHERE id = " . intval($visite->id));
$median[$categorie][] = [
'visite_id' => $visite->id,
'distance' => $distance,
'classement' => $visite->classement
];
}
}
}
}
// ---------------------- //
// Traitement LOINTAINS //
// ---------------------- //
foreach ($categories as $categorie) {
$lointain[$categorie] = [];
$myquery = "
SELECT
id, latitude, longitude, categorie, rating, reviews,
(CASE
WHEN is_bonus = 1 THEN (rating * 0.6 + 0.5 * log10(reviews + 1))
ELSE (rating * 0.5 + 0.5 * log10(reviews + 1))
END) AS classement
FROM vis
WHERE categorie = '" . $db->escape($categorie) . "'
AND rating >= '" . floatval($fiche->visite_note_minimale) . "'
ORDER BY classement DESC
";
$resultats = $db->get_results($myquery);
foreach ($resultats ?? [] as $visite) {
if (count($lointain[$categorie]) < 20) {
$lat = str_replace(",", ".", $visite->latitude);
$lon = str_replace(",", ".", $visite->longitude);
$distance = round(calculerDistance($fiche->latitude, $fiche->longitude, $lat, $lon), 0);
if ($distance > 60 && $distance <= 100) {
$db->query("UPDATE vis SET utilise_dans_qr = 1 WHERE id = " . intval($visite->id));
$lointain[$categorie][] = [
'visite_id' => $visite->id,
'distance' => $distance,
'classement' => $visite->classement
];
}
}
}
}
// ---------------------- //
// Sauvegarde en base //
// ---------------------- //
$db->query("
UPDATE heb SET
proche_json = '" . $db->escape(json_encode($proche)) . "',
median_json = '" . $db->escape(json_encode($median)) . "',
lointain_json = '" . $db->escape(json_encode($lointain)) . "'
WHERE id = " . intval($hebergement_id)
);
$requete = "UPDATE heb set liste_lieux_fait= 1, liste_lieux_fait_save = 1 where id=".$hebergement_id;
$db->query($requete);
}
/************************************************
* đźšš RECUPERATION DU TABLEAU DES LIEUX DE VISITE
************************************************/
function recupererLieuxCarte($fiche, $zones, $categories, $inclureDesactives) {
global $db;
global $limites;
$tableau_liste = [];
$nombre_total = 0;
// 🛑 Préparer les lieux désactivés (qu'on filtre ou qu'on signale)
$desactivations_brut = json_decode($fiche->desactivation ?? '[]', true) ?: [];
$desactivations = [];
foreach ($desactivations_brut as $id => $data) {
if (isset($data['categorie'], $data['query'])) {
$desactivations[$data['query']][$data['categorie']][] = (int) $id;
}
}
foreach ($zones as $zone) {
$json_field = "{$zone}_json";
if (!isset($fiche->$json_field)) continue;
$decoded_json = json_decode($fiche->$json_field, true);
if (!is_array($decoded_json)) continue;
$ligne_max = $limites[$zone] ?? 20;
foreach ($categories as $categorie) {
$listeLieux = $decoded_json[$categorie] ?? [];
// ➤ Trier par classement décroissant puis prendre les meilleurs
usort($listeLieux, fn($a, $b) => $b['classement'] <=> $a['classement']);
$listeLieux = array_slice($listeLieux, 0, $ligne_max);
// ➤ Puis trier par distance croissante
usort($listeLieux, fn($a, $b) => $a['distance'] <=> $b['distance']);
foreach ($listeLieux as $lieu) {
if (!empty($lieu['visite_id'])) {
$visite_id = (int) $lieu['visite_id'];
$isDesactive = in_array($visite_id, $desactivations[$zone][$categorie] ?? []);
// Si on ne veut pas inclure les désactivés et que ce lieu l'est, on saute
if (!$inclureDesactives && $isDesactive) continue;
$reponse = $db->get_row("SELECT id, name, latitude, longitude,photo_locale,compteur_like,postal_code,city,dernier_avis,rating,full_address,place_id,token FROM vis WHERE id = $visite_id AND statut != 0");
if (!empty($reponse->latitude) && !empty($reponse->longitude)) {
$tableau_liste[] = [
'id' => $reponse->id,
'token' => $reponse->token,
'name' => $reponse->name,
'latitude' => floatval(str_replace(',', '.', $reponse->latitude)),
'longitude' => floatval(str_replace(',', '.', $reponse->longitude)),
'distance' => $lieu['distance'],
'classement' => $lieu['classement'],
'zone' => $zone,
'categorie' => $categorie,
'desactive' => $isDesactive,
'photo_locale' => $reponse->photo_locale,
'compteur_like' => $reponse->compteur_like,
'postal_code' => $reponse->postal_code,
'city' => $reponse->city,
'dernier_avis' => $reponse->dernier_avis,
'rating' => str_replace(",",".",$reponse->rating),
'rating_percent' => round(100*(str_replace(",",".",$reponse->rating)/5),0),
'googleMapsLink' => "https://www.google.com/maps/search/?api=1&query=".urlencode($reponse->full_address)."&query_place_id=$reponse->place_id",
round(100*($liste->rating/5),0)
];
$nombre_total++;
}
}
}
}
}
return $tableau_liste;
}
/*********************************************************
* đźšš RECUPERATION DU TABLEAU DES LIEUX DE VISITE PROPRIO
********************************************************/
function recupererLieuxCarteProprio($fiche) {
global $db;
$tableau_liste = [];
$nombre_total = 0;
$myquery = "SELECT * from vis_proprio where 1 and hebergement_id=".$fiche->id ." order by distance + 0";
$myquery_calls = $db->get_results($myquery);
if (!empty($myquery_calls)) {
foreach ( $myquery_calls as $reponse )
{
if (!empty($reponse->latitude) && !empty($reponse->longitude)) {
if (!$reponse->photo_locale) {
$photo_token = $reponse->token;
$prefix = substr($photo_token, 0, 2);
$prefix=strtoupper($prefix);
$photo_url = "/upload/visite/$prefix/$photo_token.jpg";
$photo_full_path = DOSSIER_RACINE."/$photo_url";
$reponse->photo_locale=$photo_url;
}
$tableau_liste[] = [
'id' => $reponse->id,
'name' => $reponse->name,
'latitude' => floatval(str_replace(',', '.', $reponse->latitude)),
'longitude' => floatval(str_replace(',', '.', $reponse->longitude)),
'distance' => $reponse->distance,
'photo_locale' => $reponse->photo_locale,
'thematique_id' => $reponse->thematique_id,
];
$nombre_total++;
}
}
}
return $tableau_liste;
}
/**************************************************************************
* đźšš COMPLETER LATITUDE ET LONGITUDE POUR ANCIENS LIEUX DE VISITE PROPRIO
**************************************************************************/
function completerLatLngPourHebergementProprio($hebergement_id, $sleepSeconds = 2) {
global $db, $apiKey, $GOOGLE_FRONT_KEY, $GOOGLE_SERVER_KEY;
// Récupérer les lieux sans coordonnées, mais avec un place_id
$rows = $db->get_results("
SELECT id, place_id, api_echecs
FROM vis_proprio
WHERE hebergement_id = '" . intval($hebergement_id) . "'
AND (latitude IS NULL OR latitude = '' OR longitude IS NULL OR longitude = '')
AND place_id != ''
");
if (!$rows) {
//echo "Aucun lieu à compléter pour l’hébergement ID $hebergement_id.\n";
return;
}
foreach ($rows as $row) {
if ($row->api_echecs >= 3) {
//echo "→ Lieu ID {$row->id} ignoré : trop d’échecs.\n";
continue;
}
$place_id = urlencode($row->place_id);
$url = "https://maps.googleapis.com/maps/api/place/details/json?place_id={$place_id}&key={$GOOGLE_SERVER_KEY}&language=fr";
$response = @file_get_contents($url);
// Historisation appel API
$db->query("UPDATE api_historique SET api_appels = api_appels + 1");
if ($response === false) {
//incrementerLatLngEchec($db, $row->id);
echo "⚠️ Échec API (network) pour ID {$row->id}\n";
sleep($sleepSeconds);
continue;
}
$details = json_decode($response, true);
if ($details['status'] === 'OK' && isset($details['result']['geometry']['location'])) {
$lat = str_replace(",", ".", $details['result']['geometry']['location']['lat']);
$lng = str_replace(",", ".", $details['result']['geometry']['location']['lng']);
$db->query("UPDATE vis_proprio SET latitude = '$lat', longitude = '$lng', api_echecs = 0 WHERE id = {$row->id}");
echo "✅ Coordonnées mises à jour pour ID {$row->id} → lat: $lat, lng: $lng\n";
} else {
//incrementerLatLngEchec($db, $row->id);
echo "⚠️ Erreur API pour ID {$row->id} : " . ($details['status'] ?? 'inconnue') . "\n";
}
sleep($sleepSeconds);
}
echo "Mise à jour terminée pour l’hébergement ID $hebergement_id.\n";
}
/***************************************
* đźšš INITIALISATION POUR UN HEBERGEMENT
**************************************/
function initialiserHebergementSiNecessaire($token)
{
global $db;
$fiche = $db->get_row("SELECT * FROM heb WHERE token = '" . addslashes($token) . "'");
if (!$fiche) {
return "Hébergement introuvable pour ce token.";
}
// Si déjà initialisé, on ne fait rien
if ($fiche->initialisation == 1) {
return "Hébergement déjà initialisé.";
}
$hebergement_id = $fiche->id;
// Appel de l'algo
genererCorrespondance($token);
// Génération du QR CODE
genererQRCodeHabilleSansEcraser($token, $fiche->country_code);
// Récupération de la latitude et longitude les lieux de visite proprio
completerLatLngPourHebergementProprio($hebergement_id);
// Récupération de la photo hebergement
verifierOuRecupererPhoto($token, "heb");
// ---------------------------------------------------------------------
// Marquer comme initialisé
$db->query("UPDATE heb SET initialisation = 1 WHERE id = $hebergement_id");
return "Initialisation effectuée pour l’hébergement ID $hebergement_id.";
}
?>