Publier Globinours 1.0.0-rc.3

This commit is contained in:
Alexandre NOEL 2026-09-03 12:39:15 +02:00
commit 9a2b4068da
46 changed files with 38230 additions and 20 deletions

View file

@ -0,0 +1,192 @@
<?php
require_once __DIR__ . '/DB.php';
require_once __DIR__ . '/GeocodeService.php';
class AdoptionService
{
public static function adopt(array $data): void
{
$db = DB::pdo();
$db->beginTransaction();
try {
$animalId = (int) $data['animal_id'];
$date = $data['adoption_date'] ?? date('Y-m-d');
$beforeStmt = $db->prepare(
'SELECT status,refuge_room,care_box_key,current_address FROM animals WHERE id=:id',
);
$beforeStmt->execute([':id' => $animalId]);
$beforeLocation = $beforeStmt->fetch(PDO::FETCH_ASSOC) ?: [];
// 1. Enregistrement de l’adoption
$stmt = $db->prepare('
INSERT INTO adoptions (
animal_id,
adopter_name,
adopter_phone,
adopter_email,
adopter_address,
adopter_postal_code,
adopter_city,
adoption_date,
notes,
adopter_contact_id,
created_at
) VALUES (
:animal_id,
:name,
:phone,
:email,
:address,
:postal,
:city,
:date,
:notes,
:contact_id,
CURRENT_TIMESTAMP
)
');
$stmt->execute([
':animal_id' => $animalId,
':name' => $data['adopter_name'],
':phone' => $data['adopter_phone'] ?: null,
':email' => $data['adopter_email'] ?: null,
':address' => $data['adopter_address'] ?: null,
':postal' => $data['adopter_postal_code'] ?: null,
':city' => $data['adopter_city'] ?: null,
':date' => $date,
':notes' => $data['notes'] ?: null,
':contact_id' => $data['adopter_contact_id'] ?? null,
]);
$adoptionId = (int) $db->lastInsertId();
$db->prepare(
"INSERT INTO animal_placements(animal_id,event_type,event_date,contact_id,reason,notes,adoption_id,created_by) VALUES(:animal,'adoption',:date,:contact,'Adoption définitive',:notes,:adoption,:user)",
)->execute([
':animal' => $animalId,
':date' => $date,
':contact' => $data['adopter_contact_id'] ?? null,
':notes' => $data['notes'] ?: null,
':adoption' => $adoptionId,
':user' => Auth::id(),
]);
// 2. Mise à jour du statut de l’animal
$currentAddress = implode(
' ',
array_filter([
$data['adopter_address'] ?? '',
$data['adopter_postal_code'] ?? '',
$data['adopter_city'] ?? '',
]),
);
$lat = null;
$lng = null;
if (!empty($currentAddress)) {
$coords = GeocodeService::geocode($currentAddress);
if ($coords) {
$lat = $coords['lat'] ?? null;
$lng = $coords['lng'] ?? null;
}
}
$db->prepare(
"
UPDATE animals
SET
status = 'adopte',
refuge_room = NULL,
care_box_key = NULL,
updated_at = CURRENT_TIMESTAMP,
current_address = :currentAddress,
current_lat = :lat,
current_lng = :lng
WHERE id = :id
",
)->execute([':id' => $animalId, ':currentAddress' => $currentAddress, ':lat' => $lat, ':lng' => $lng]);
LocationHistoryService::record(
$db,
$animalId,
$beforeLocation,
[
'status' => 'adopte',
'refuge_room' => null,
'care_box_key' => null,
'current_address' => $currentAddress,
],
'adoption',
'Adoption finalisée',
$date . ' 12:00:00',
);
// 3. Ajout dans les mouvements administratifs (sortie)
$stmt = $db->prepare("
INSERT INTO animal_movements (
animal_id,
kind,
place,
lieu,
contact_name,
contact_phone,
contact_email,
note,
created_at
) VALUES (
:animal_id,
'exit',
:place,
'Adoption',
:contact_name,
:contact_phone,
:contact_email,
:note,
CURRENT_TIMESTAMP
)
");
$stmt->execute([
':animal_id' => $animalId,
':place' => $data['adopter_address'] ?: null,
':contact_name' => $data['adopter_name'] ?: null,
':contact_phone' => $data['adopter_phone'] ?: null,
':contact_email' => $data['adopter_email'] ?: null,
':note' => 'Adoption finalisée',
]);
// 4. Ajout dans l’historique
$stmt = $db->prepare("
INSERT INTO animal_history (
animal_id,
type,
label,
details,
user_id,
created_at
) VALUES (
:animal_id,
'adoption',
'Adoption finalisée',
:details,
:user_id,
CURRENT_TIMESTAMP
)
");
$stmt->execute([
':animal_id' => $animalId,
':details' => 'Par ' . $data['adopter_name'] . ' - Note(s) : ' . $data['notes'],
':user_id' => Auth::id(),
]);
$db->commit();
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
}
}

View file

@ -0,0 +1,351 @@
<?php
declare(strict_types=1);
final class AgendaService
{
public const TYPES = ['appointment', 'veterinary', 'transport', 'pre_adoption', 'task', 'other'];
public static function save(array $data, ?int $id = null): int
{
$type = (string) ($data['item_type'] ?? 'task');
$title = trim((string) ($data['title'] ?? ''));
$date = trim((string) ($data['date'] ?? ''));
$time = trim((string) ($data['time'] ?? ''));
$allDay = isset($data['all_day']);
if (!in_array($type, self::TYPES, true) || $title === '' || !self::date($date)) {
throw new RuntimeException(t('agenda.invalid'));
}
if (!$allDay && !preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time)) {
throw new RuntimeException(t('agenda.invalid_time'));
}
$start = $date . ' ' . ($allDay ? '00:00:00' : $time . ':00');
$endDate = trim((string) ($data['end_date'] ?? ''));
$endTime = trim((string) ($data['end_time'] ?? ''));
$end = null;
if ($endDate !== '' || $endTime !== '') {
if (!self::date($endDate) || !preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $endTime)) {
throw new RuntimeException(t('agenda.invalid_end'));
}
$end = $endDate . ' ' . $endTime . ':00';
if ($end < $start) {
throw new RuntimeException(t('agenda.end_before_start'));
}
}
$repeat = (string) ($data['repeat_rule'] ?? 'none');
if (!in_array($repeat, ['none', 'daily', 'weekly', 'monthly'], true)) {
$repeat = 'none';
}
$until = trim((string) ($data['repeat_until'] ?? ''));
if ($until !== '' && !self::date($until)) {
throw new RuntimeException(t('agenda.invalid_repeat'));
}
$values = [
':type' => $type,
':title' => mb_substr($title, 0, 180),
':description' => trim((string) ($data['description'] ?? '')) ?: null,
':start' => $start,
':end' => $end,
':all_day' => $allDay ? 1 : 0,
':location' => trim((string) ($data['location'] ?? '')) ?: null,
':priority' => in_array(
$p = (string) ($data['priority'] ?? 'normal'),
['low', 'normal', 'high', 'urgent'],
true,
)
? $p
: 'normal',
':assigned' => (int) ($data['assigned_user_id'] ?? 0) ?: null,
':animal' => (int) ($data['animal_id'] ?? 0) ?: null,
':contact' => (int) ($data['contact_id'] ?? 0) ?: null,
':reminder' => ($data['reminder_minutes'] ?? '') === '' ? null : max(0, (int) $data['reminder_minutes']),
':repeat' => $repeat,
':until' => $until ?: null,
':user' => Auth::id(),
];
$db = DB::pdo();
$db->beginTransaction();
try {
if ($id) {
$values[':id'] = $id;
$db->prepare(
"UPDATE agenda_items SET item_type=:type,title=:title,description=:description,starts_at=:start,ends_at=:end,all_day=:all_day,location=:location,priority=:priority,assigned_user_id=:assigned,animal_id=:animal,contact_id=:contact,reminder_minutes=:reminder,repeat_rule=:repeat,repeat_until=:until,updated_at=datetime('now') WHERE id=:id",
)->execute($values);
} else {
$db->prepare(
'INSERT INTO agenda_items(item_type,title,description,starts_at,ends_at,all_day,location,priority,assigned_user_id,animal_id,contact_id,reminder_minutes,repeat_rule,repeat_until,created_by) VALUES(:type,:title,:description,:start,:end,:all_day,:location,:priority,:assigned,:animal,:contact,:reminder,:repeat,:until,:user)',
)->execute($values);
$id = (int) $db->lastInsertId();
}
self::saveVolunteers($id, $data['volunteer_contact_ids'] ?? []);
$db->commit();
return $id;
} catch (Throwable $e) {
if ($db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
}
public static function find(int $id): ?array
{
$s = DB::pdo()->prepare(
"SELECT ai.*,(SELECT group_concat(contact_id,',') FROM agenda_volunteers WHERE agenda_item_id=ai.id) volunteer_ids FROM agenda_items ai WHERE ai.id=?",
);
$s->execute([$id]);
return $s->fetch(PDO::FETCH_ASSOC) ?: null;
}
public static function setStatus(int $id, string $status): void
{
if (!in_array($status, ['planned', 'completed', 'cancelled'], true)) {
throw new RuntimeException(t('agenda.invalid'));
}
DB::pdo()
->prepare(
"UPDATE agenda_items SET status=?,completed_at=CASE WHEN ?='completed' THEN datetime('now') ELSE NULL END,completed_by=CASE WHEN ?='completed' THEN ? ELSE NULL END,updated_at=datetime('now') WHERE id=?",
)
->execute([$status, $status, $status, Auth::id(), $id]);
}
public static function conflicts(int $id): array
{
$db = DB::pdo();
$s = $db->prepare(
"SELECT DISTINCT other.id,other.title,other.starts_at FROM agenda_items current JOIN agenda_items other ON other.id<>current.id AND other.status='planned' AND datetime(other.starts_at)<datetime(COALESCE(current.ends_at,CASE WHEN current.all_day=1 THEN datetime(current.starts_at,'+1 day') ELSE datetime(current.starts_at,'+1 hour') END)) AND datetime(COALESCE(other.ends_at,CASE WHEN other.all_day=1 THEN datetime(other.starts_at,'+1 day') ELSE datetime(other.starts_at,'+1 hour') END))>datetime(current.starts_at) WHERE current.id=:id AND current.status='planned' AND ((current.assigned_user_id IS NOT NULL AND other.assigned_user_id=current.assigned_user_id) OR EXISTS(SELECT 1 FROM agenda_volunteers mine JOIN agenda_volunteers theirs ON theirs.contact_id=mine.contact_id AND theirs.agenda_item_id=other.id WHERE mine.agenda_item_id=current.id)) ORDER BY datetime(other.starts_at)",
);
$s->execute([':id' => $id]);
return $s->fetchAll(PDO::FETCH_ASSOC);
}
public static function month(DateTimeImmutable $month): array
{
return self::between(
$month->modify('first day of this month')->setTime(0, 0),
$month->modify('last day of this month')->setTime(23, 59, 59),
);
}
public static function week(DateTimeImmutable $date): array
{
$start = $date->modify('monday this week')->setTime(0, 0);
return self::between($start, $start->modify('+6 days')->setTime(23, 59, 59));
}
public static function range(DateTimeImmutable $from, DateTimeImmutable $to): array
{
return self::between($from, $to);
}
public static function upcoming(int $days = 30): array
{
return self::between(new DateTimeImmutable('today'), new DateTimeImmutable('+' . $days . ' days 23:59:59'));
}
public static function due(): array
{
$db = DB::pdo();
$overdue = $db
->query(
"SELECT ai.*,ai.starts_at instance_starts_at,a.name animal_name,COALESCE(u.display_name,u.username) assigned_name FROM agenda_items ai LEFT JOIN animals a ON a.id=ai.animal_id LEFT JOIN users u ON u.id=ai.assigned_user_id WHERE ai.status='planned' AND ai.repeat_rule='none' AND datetime(ai.starts_at)<datetime('now') ORDER BY datetime(ai.starts_at) LIMIT 25",
)
->fetchAll(PDO::FETCH_ASSOC);
$soon = array_values(
array_filter(
self::upcoming(2),
static fn($row) => $row['status'] === 'planned' &&
strtotime($row['instance_starts_at']) <= strtotime('+1 day'),
),
);
$seen = [];
$out = [];
foreach ([...$overdue, ...$soon] as $row) {
$key = (int) $row['id'] . '|' . ($row['instance_starts_at'] ?? $row['starts_at']);
if (isset($seen[$key])) {
continue;
}
$seen[$key] = true;
$out[] = $row;
}
usort(
$out,
static fn($a, $b) => strcmp(
(string) ($a['instance_starts_at'] ?? $a['starts_at']),
(string) ($b['instance_starts_at'] ?? $b['starts_at']),
),
);
return array_slice($out, 0, 25);
}
private static function between(DateTimeImmutable $from, DateTimeImmutable $to): array
{
$db = DB::pdo();
$s = $db->prepare(
"SELECT ai.*,a.name animal_name,dc.name contact_name,COALESCE(u.display_name,u.username) assigned_name,(SELECT group_concat(vdc.name,', ') FROM agenda_volunteers av JOIN directory_contacts vdc ON vdc.id=av.contact_id WHERE av.agenda_item_id=ai.id) volunteer_names,(SELECT group_concat(av.contact_id,',') FROM agenda_volunteers av WHERE av.agenda_item_id=ai.id) volunteer_ids FROM agenda_items ai LEFT JOIN animals a ON a.id=ai.animal_id LEFT JOIN directory_contacts dc ON dc.id=ai.contact_id LEFT JOIN users u ON u.id=ai.assigned_user_id WHERE date(ai.starts_at)<=:to AND (ai.repeat_rule<>'none' OR datetime(ai.starts_at)>=:from) AND ai.status<>'cancelled' ORDER BY datetime(ai.starts_at),ai.priority DESC",
);
$s->execute([':from' => $from->format('Y-m-d H:i:s'), ':to' => $to->format('Y-m-d')]);
$out = [];
foreach ($s->fetchAll(PDO::FETCH_ASSOC) as $row) {
$start = new DateTimeImmutable($row['starts_at']);
$end = $row['ends_at'] ? new DateTimeImmutable($row['ends_at']) : null;
$step = match ($row['repeat_rule']) {
'daily' => '+1 day',
'weekly' => '+1 week',
'monthly' => '+1 month',
default => null,
};
while ($start < $from && $step) {
$start = $start->modify($step);
}
do {
if ($start > $to) {
break;
}
if (!$row['repeat_until'] || $start->format('Y-m-d') <= $row['repeat_until']) {
$instance = $row;
$instance['instance_starts_at'] = $start->format('Y-m-d H:i:s');
$instance['instance_ends_at'] = $end
? $end
->modify(
$start->getTimestamp() -
new DateTimeImmutable($row['starts_at'])->getTimestamp() .
' seconds',
)
->format('Y-m-d H:i:s')
: null;
$instance['source_type'] = 'agenda';
if (!empty($instance['volunteer_names'])) {
$instance['title'] .= ' · 👥 ' . $instance['volunteer_names'];
}
$out[] = $instance;
}
if (!$step) {
break;
}
$start = $start->modify($step);
} while (!$row['repeat_until'] || $start->format('Y-m-d') <= $row['repeat_until']);
}
$vaccines = $db->prepare(
"SELECT v.id,v.due_date,rv.name vaccine_name,a.id animal_id,a.name animal_name FROM vaccinations v JOIN ref_vaccines rv ON rv.id=v.vaccine_id JOIN animals a ON a.id=v.animal_id WHERE v.due_date IS NOT NULL AND date(v.due_date) BETWEEN :from AND :to AND a.deleted_at IS NULL AND a.archived_at IS NULL AND lower(a.status) NOT IN ('adopte','adopté','decede','décédé') AND NOT EXISTS(SELECT 1 FROM vaccinations newer WHERE newer.animal_id=v.animal_id AND newer.vaccine_id=v.vaccine_id AND date(newer.done_date)>date(v.done_date)) ORDER BY date(v.due_date),a.name COLLATE NOCASE",
);
$vaccines->execute([':from' => $from->format('Y-m-d'), ':to' => $to->format('Y-m-d')]);
foreach ($vaccines->fetchAll(PDO::FETCH_ASSOC) as $v) {
$out[] = self::reminder(
-(100000000 + (int) $v['id']),
(int) $v['id'],
'vaccine',
'vaccine',
t('agenda.vaccine_reminder', ['vaccine' => $v['vaccine_name']]),
$v['due_date'],
(int) $v['animal_id'],
$v['animal_name'],
'high',
);
}
$dewormings = $db->prepare(
"SELECT d.id,d.next_due_date,COALESCE(rd.name,'') dewormer_name,a.id animal_id,a.name animal_name FROM dewormings d LEFT JOIN ref_dewormers rd ON rd.id=d.dewormer_id JOIN animals a ON a.id=d.animal_id WHERE d.next_due_date IS NOT NULL AND date(d.next_due_date) BETWEEN :from AND :to AND a.deleted_at IS NULL AND a.archived_at IS NULL AND lower(a.status) NOT IN ('adopte','adopté','decede','décédé') AND NOT EXISTS(SELECT 1 FROM dewormings newer WHERE newer.animal_id=d.animal_id AND (date(newer.administered_on)>date(d.administered_on) OR (date(newer.administered_on)=date(d.administered_on) AND newer.id>d.id))) ORDER BY date(d.next_due_date),a.name COLLATE NOCASE",
);
$dewormings->execute([':from' => $from->format('Y-m-d'), ':to' => $to->format('Y-m-d')]);
foreach ($dewormings->fetchAll(PDO::FETCH_ASSOC) as $d) {
$out[] = self::reminder(
-(200000000 + (int) $d['id']),
(int) $d['id'],
'deworming',
'deworming',
t('agenda.deworming_reminder', ['product' => $d['dewormer_name'] ?: t('agenda.deworming')]),
$d['next_due_date'],
(int) $d['animal_id'],
$d['animal_name'],
'high',
);
}
$treatments = $db->prepare(
"SELECT t.id,t.start_date,t.end_date,m.name medication_name,a.id animal_id,a.name animal_name FROM treatments t JOIN ref_medications m ON m.id=t.medication_id JOIN animals a ON a.id=t.animal_id WHERE t.ongoing=1 AND (date(t.start_date) BETWEEN :from AND :to OR (t.end_date IS NOT NULL AND date(t.end_date) BETWEEN :from AND :to)) AND a.deleted_at IS NULL AND a.archived_at IS NULL AND lower(a.status) NOT IN ('adopte','adopté','decede','décédé') ORDER BY date(t.start_date),a.name COLLATE NOCASE",
);
$treatments->execute([':from' => $from->format('Y-m-d'), ':to' => $to->format('Y-m-d')]);
foreach ($treatments->fetchAll(PDO::FETCH_ASSOC) as $t) {
if ($t['start_date'] >= $from->format('Y-m-d') && $t['start_date'] <= $to->format('Y-m-d')) {
$out[] = self::reminder(
-(300000000 + (int) $t['id']),
(int) $t['id'],
'treatment_start',
'treatment_start',
t('agenda.treatment_start', ['medication' => $t['medication_name']]),
$t['start_date'],
(int) $t['animal_id'],
$t['animal_name'],
'high',
);
}
if ($t['end_date'] && $t['end_date'] >= $from->format('Y-m-d') && $t['end_date'] <= $to->format('Y-m-d')) {
$out[] = self::reminder(
-(400000000 + (int) $t['id']),
(int) $t['id'],
'treatment_end',
'treatment_end',
t('agenda.treatment_end', ['medication' => $t['medication_name']]),
$t['end_date'],
(int) $t['animal_id'],
$t['animal_name'],
'high',
);
}
}
usort($out, static fn($a, $b) => strcmp($a['instance_starts_at'], $b['instance_starts_at']));
return $out;
}
private static function reminder(
int $id,
int $sourceId,
string $sourceType,
string $itemType,
string $title,
string $date,
int $animalId,
string $animalName,
string $priority,
): array {
return [
'id' => $id,
'source_id' => $sourceId,
'source_type' => $sourceType,
'item_type' => $itemType,
'title' => $title,
'description' => null,
'starts_at' => $date . ' 00:00:00',
'instance_starts_at' => $date . ' 00:00:00',
'instance_ends_at' => null,
'all_day' => 1,
'location' => null,
'status' => 'planned',
'priority' => $priority,
'assigned_user_id' => null,
'assigned_name' => null,
'volunteer_names' => null,
'volunteer_ids' => null,
'animal_id' => $animalId,
'animal_name' => $animalName,
'contact_id' => null,
'contact_name' => null,
'reminder_minutes' => null,
'repeat_rule' => 'none',
'repeat_until' => null,
];
}
private static function saveVolunteers(int $itemId, mixed $input): void
{
$ids = is_array($input) ? array_values(array_unique(array_filter(array_map('intval', $input)))) : [];
$db = DB::pdo();
$db->prepare('DELETE FROM agenda_volunteers WHERE agenda_item_id=?')->execute([$itemId]);
if (!$ids) {
return;
}
$check = $db->prepare(
"SELECT 1 FROM directory_contacts dc JOIN directory_contact_roles r ON r.contact_id=dc.id AND r.role='benevole' WHERE dc.id=? AND dc.deleted_at IS NULL",
);
$insert = $db->prepare('INSERT INTO agenda_volunteers(agenda_item_id,contact_id) VALUES(?,?)');
foreach ($ids as $id) {
$check->execute([$id]);
if ($check->fetchColumn()) {
$insert->execute([$itemId, $id]);
}
}
}
private static function date(string $v): bool
{
$d = DateTimeImmutable::createFromFormat('!Y-m-d', $v);
return $d && $d->format('Y-m-d') === $v;
}
}

View file

@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
final class AppSettings
{
private const DEFAULTS = [
'association_name' => 'Association',
'association_address' => '',
'association_postal_code' => '',
'association_city' => '',
'association_phone' => '',
'association_email' => '',
'association_siret' => '',
'association_rna' => '',
'association_latitude' => '',
'association_longitude' => '',
'adoption_fee_sterilized' => '220',
'adoption_fee_unsterilized' => '200',
'quarantine_days' => '15',
'backup_retention' => '10',
'app_language' => 'fr',
'public_site_enabled' => '0',
'public_site_theme' => 'warm',
'public_site_routing' => 'integrated',
'public_site_home_title' => 'Ils attendent une famille',
'public_site_home_text' => 'Découvrez les animaux actuellement proposés à l’adoption par notre association.',
'public_site_about_enabled' => '1',
'public_site_about_title' => 'Notre association',
'public_site_about_text' => 'Présentez ici votre association, son histoire et ses missions.',
'public_site_donation_title' => 'Nous soutenir',
'public_site_donation_text' =>
'Chaque don contribue directement aux soins, à l’alimentation et à la protection des animaux.',
'public_site_donation_url' => '',
'public_site_contact_text' => 'Une question sur une adoption ou sur l’association ? Contactez-nous.',
'public_site_facebook_url' => '',
'public_site_instagram_url' => '',
'notification_email_enabled' => '0',
'notification_email_frequency' => 'weekly',
'notification_email_recipient' => '',
'notification_last_sent_at' => '',
'privacy_retention_years' => '5',
'privacy_retention_adopter_years' => '5',
'privacy_retention_foster_years' => '5',
'privacy_retention_volunteer_years' => '5',
'privacy_access_log_months' => '24',
'backup_schedule_enabled' => '0',
'backup_schedule_frequency' => 'daily',
'backup_last_run_at' => '',
'backup_last_verified_at' => '',
'public_site_legal_text' => '',
'public_site_privacy_text' => '',
];
private static ?array $cache = null;
public static function all(): array
{
if (self::$cache !== null) {
return self::$cache;
}
$values = self::DEFAULTS;
try {
foreach (
DB::pdo()->query('SELECT setting_key,setting_value FROM app_settings')->fetchAll(PDO::FETCH_ASSOC)
as $row
) {
if (array_key_exists($row['setting_key'], $values)) {
$values[$row['setting_key']] = (string) $row['setting_value'];
}
}
} catch (Throwable) {
}
return self::$cache = $values;
}
public static function get(string $key): string
{
return (string) (self::all()[$key] ?? '');
}
public static function int(string $key, int $min = 0, int $max = PHP_INT_MAX): int
{
return max($min, min($max, (int) self::get($key)));
}
public static function save(array $values, ?int $userId): void
{
$allowed = array_keys(self::DEFAULTS);
$stmt = DB::pdo()->prepare(
"INSERT INTO app_settings(setting_key,setting_value,updated_by,updated_at) VALUES(:key,:value,:user,datetime('now')) ON CONFLICT(setting_key) DO UPDATE SET setting_value=excluded.setting_value,updated_by=excluded.updated_by,updated_at=datetime('now')",
);
foreach ($allowed as $key) {
if (array_key_exists($key, $values)) {
$stmt->execute([':key' => $key, ':value' => (string) $values[$key], ':user' => $userId]);
}
}
self::$cache = null;
}
}

View file

@ -0,0 +1,490 @@
<?php
declare(strict_types=1);
final class Asm3Analyzer
{
private const DOMAINS = [
'animal' => ['Animaux', 'animals', 'ready'],
'owner' => ['Contacts et structures', 'directory_contacts', 'planned'],
'adoption' => ['Mouvements, FA et adoptions', 'animal_placements / adoptions', 'planned'],
'animalvaccination' => ['Vaccinations', 'vaccinations', 'planned'],
'medical' => ['Traitements et actes médicaux', 'medical_notes / treatments', 'planned'],
'animalmedical' => ['Traitements et actes médicaux', 'medical_notes / treatments', 'planned'],
'media' => ['Médias', 'animal_photos / medical_photos', 'planned'],
'animallitter' => ['Portées', 'litters', 'planned'],
'animalcontrol' => ['Incidents et contrôles', 'non pris en charge', 'review'],
'animaltest' => ['Tests médicaux', 'medical_notes', 'planned'],
];
public static function analyze(string $path): array
{
if (!is_file($path) || !is_readable($path)) {
throw new RuntimeException(t('asm3.unreadable'));
}
if (self::isCopyDump($path)) {
return self::analyzeCopy($path);
}
$handle = fopen($path, 'rb');
if (!$handle) {
throw new RuntimeException(t('asm3.open_failed'));
}
$counts = [];
$columns = [];
$animalStats = [
'active' => 0,
'archived' => 0,
'adoptable' => 0,
'not_adoptable' => 0,
'deceased' => 0,
'microchip' => 0,
'tattoo' => 0,
'neutered' => 0,
'missing_name' => 0,
'missing_birth_date' => 0,
'species' => [],
];
$statement = '';
$quoted = false;
$bytes = 0;
try {
while (($chunk = fgets($handle)) !== false) {
$bytes += strlen($chunk);
$statement .= $chunk;
$length = strlen($statement);
$quoted = false;
for ($i = 0; $i < $length; $i++) {
if ($statement[$i] !== "'") {
continue;
}
if ($quoted && $i + 1 < $length && $statement[$i + 1] === "'") {
$i++;
continue;
}
$quoted = !$quoted;
}
if ($quoted || !preg_match('/;\s*$/s', $statement)) {
continue;
}
self::consume($statement, $counts, $columns, $animalStats);
$statement = '';
}
if (trim($statement) !== '') {
self::consume($statement, $counts, $columns, $animalStats);
}
} finally {
fclose($handle);
}
arsort($counts);
$domains = [];
foreach (self::DOMAINS as $table => [$label, $target, $status]) {
$domains[] = [
'table' => $table,
'label' => $label,
'target' => $target,
'status' => $status,
'rows' => $counts[$table] ?? 0,
'present' => isset($counts[$table]),
];
}
$warnings = [];
if (!isset($counts['animal'])) {
$warnings[] = t('asm3.animal_table_missing');
}
if (($counts['animal'] ?? 0) > 0 && $animalStats['missing_name'] > 0) {
$warnings[] = t('asm3.animals_without_name', ['count' => $animalStats['missing_name']]);
}
if (($counts['animal'] ?? 0) > 0 && $animalStats['missing_birth_date'] > 0) {
$warnings[] = t('asm3.animals_without_birth', ['count' => $animalStats['missing_birth_date']]);
}
$unsupported = [];
foreach ($counts as $table => $count) {
if (!isset(self::DOMAINS[$table]) && $count > 0) {
$unsupported[$table] = $count;
}
}
return [
'format' => 'ASM3 SQL INSERT',
'source' => basename($path),
'size_bytes' => filesize($path),
'read_bytes' => $bytes,
'generated_at' => date(DATE_ATOM),
'tables' => $counts,
'columns' => $columns,
'domains' => $domains,
'animals' => $animalStats,
'warnings' => $warnings,
'unmapped_tables' => $unsupported,
'read_only' => true,
];
}
public static function rows(string $path, array $wantedTables): array
{
if (self::isCopyDump($path)) {
return self::copyRows($path, $wantedTables);
}
$wanted = array_fill_keys(array_map('strtolower', $wantedTables), true);
$rows = [];
$columns = [];
$handle = fopen($path, 'rb');
if (!$handle) {
throw new RuntimeException(t('asm3.open_failed'));
}
$statement = '';
try {
while (($chunk = fgets($handle)) !== false) {
$statement .= $chunk;
$quoted = false;
$length = strlen($statement);
for ($i = 0; $i < $length; $i++) {
if ($statement[$i] !== "'") {
continue;
}
if ($quoted && $i + 1 < $length && $statement[$i + 1] === "'") {
$i++;
continue;
}
$quoted = !$quoted;
}
if ($quoted || !preg_match('/;\s*$/s', $statement)) {
continue;
}
if (
preg_match(
'/^\s*INSERT\s+INTO\s+[`"]?([a-zA-Z0-9_]+)[`"]?\s*\((.*?)\)\s*VALUES\s*\((.*)\)\s*;\s*$/is',
$statement,
$m,
)
) {
$table = strtolower($m[1]);
if (isset($wanted[$table])) {
$cols = $columns[$table] ??= array_map(
static fn($v) => strtoupper(trim($v, " \t\r\n`\"")),
explode(',', $m[2]),
);
$values = self::values($m[3]);
$row = [];
foreach ($cols as $i => $column) {
$row[$column] = $values[$i] ?? null;
}
$rows[$table][] = $row;
}
}
$statement = '';
}
} finally {
fclose($handle);
}
return $rows;
}
private static function consume(string $sql, array &$counts, array &$columns, array &$animalStats): void
{
if (
!preg_match(
'/^\s*INSERT\s+INTO\s+[`"]?([a-zA-Z0-9_]+)[`"]?\s*\((.*?)\)\s*VALUES\s*\((.*)\)\s*;\s*$/is',
$sql,
$m,
)
) {
return;
}
$table = strtolower($m[1]);
$counts[$table] = ($counts[$table] ?? 0) + 1;
if (!isset($columns[$table])) {
$columns[$table] = array_map(static fn($v) => strtoupper(trim($v, " \t\r\n`\"")), explode(',', $m[2]));
}
if ($table !== 'animal') {
return;
}
$values = self::values($m[3]);
$row = [];
foreach ($columns[$table] as $i => $column) {
$row[$column] = $values[$i] ?? null;
}
$truthy = static fn($v): bool => (string) $v === '1';
$blank = static fn($v): bool => $v === null || trim((string) $v) === '';
$animalStats[$truthy($row['ARCHIVED'] ?? 0) ? 'archived' : 'active']++;
$animalStats[$truthy($row['ADOPTABLE'] ?? 0) ? 'adoptable' : 'not_adoptable']++;
if (!$blank($row['DECEASEDDATE'] ?? null) || $truthy($row['PUTTOSLEEP'] ?? 0)) {
$animalStats['deceased']++;
}
if (!$blank($row['IDENTICHIPNUMBER'] ?? null) || $truthy($row['IDENTICHIPPED'] ?? 0)) {
$animalStats['microchip']++;
}
if (!$blank($row['TATTOONUMBER'] ?? null) || $truthy($row['TATTOO'] ?? 0)) {
$animalStats['tattoo']++;
}
if ($truthy($row['NEUTERED'] ?? 0)) {
$animalStats['neutered']++;
}
if ($blank($row['ANIMALNAME'] ?? null)) {
$animalStats['missing_name']++;
}
if ($blank($row['DATEOFBIRTH'] ?? null)) {
$animalStats['missing_birth_date']++;
}
$species = (string) ($row['SPECIESID'] ?? 'unknown');
$animalStats['species'][$species] = ($animalStats['species'][$species] ?? 0) + 1;
}
private static function isCopyDump(string $path): bool
{
$handle = @fopen($path, 'rb');
if (!$handle) {
return false;
}
$sample = (string) fread($handle, 262144);
fclose($handle);
return preg_match('/^COPY\s+(?:public\.)?[a-zA-Z0-9_]+\s*\(/mi', $sample) === 1;
}
private static function analyzeCopy(string $path): array
{
$counts = [];
$columns = [];
$animalStats = [
'active' => 0,
'archived' => 0,
'adoptable' => 0,
'not_adoptable' => 0,
'deceased' => 0,
'microchip' => 0,
'tattoo' => 0,
'neutered' => 0,
'missing_name' => 0,
'missing_birth_date' => 0,
'species' => [],
];
$handle = fopen($path, 'rb');
if (!$handle) {
throw new RuntimeException(t('asm3.open_failed'));
}
$table = null;
$tableColumns = [];
$bytes = 0;
try {
while (($line = fgets($handle)) !== false) {
$bytes += strlen($line);
$line = rtrim($line, "\r\n");
if ($table === null) {
if (
preg_match(
'/^COPY\s+(?:public\.)?[`"]?([a-zA-Z0-9_]+)[`"]?\s*\((.*?)\)\s+FROM\s+stdin;$/i',
$line,
$m,
)
) {
$table = strtolower($m[1]);
$tableColumns = array_map(static fn($v) => strtoupper(trim($v, " \t`\"")), explode(',', $m[2]));
$columns[$table] = $tableColumns;
$counts[$table] ??= 0;
}
continue;
}
if ($line === '\\.') {
$table = null;
$tableColumns = [];
continue;
}
$counts[$table]++;
if ($table === 'animal') {
self::accumulateAnimalStats(self::copyRow($line, $tableColumns), $animalStats);
}
}
} finally {
fclose($handle);
}
arsort($counts);
$domains = [];
foreach (self::DOMAINS as $name => [$label, $target, $status]) {
$domains[] = [
'table' => $name,
'label' => $label,
'target' => $target,
'status' => $status,
'rows' => $counts[$name] ?? 0,
'present' => isset($counts[$name]),
];
}
$warnings = [];
if (!isset($counts['animal'])) {
$warnings[] = t('asm3.animal_table_missing');
}
if (($counts['animal'] ?? 0) > 0 && $animalStats['missing_name'] > 0) {
$warnings[] = t('asm3.animals_without_name', ['count' => $animalStats['missing_name']]);
}
if (($counts['animal'] ?? 0) > 0 && $animalStats['missing_birth_date'] > 0) {
$warnings[] = t('asm3.animals_without_birth', ['count' => $animalStats['missing_birth_date']]);
}
$unsupported = [];
foreach ($counts as $name => $count) {
if (!isset(self::DOMAINS[$name]) && $count > 0) {
$unsupported[$name] = $count;
}
}
return [
'format' => 'ASM3 PostgreSQL COPY',
'source' => basename($path),
'size_bytes' => filesize($path),
'read_bytes' => $bytes,
'generated_at' => date(DATE_ATOM),
'tables' => $counts,
'columns' => $columns,
'domains' => $domains,
'animals' => $animalStats,
'warnings' => $warnings,
'unmapped_tables' => $unsupported,
'read_only' => true,
];
}
private static function copyRows(string $path, array $wantedTables): array
{
$wanted = array_fill_keys(array_map('strtolower', $wantedTables), true);
$rows = [];
$handle = fopen($path, 'rb');
if (!$handle) {
throw new RuntimeException(t('asm3.open_failed'));
}
$table = null;
$columns = [];
$capture = false;
try {
while (($line = fgets($handle)) !== false) {
$line = rtrim($line, "\r\n");
if ($table === null) {
if (
preg_match(
'/^COPY\s+(?:public\.)?[`"]?([a-zA-Z0-9_]+)[`"]?\s*\((.*?)\)\s+FROM\s+stdin;$/i',
$line,
$m,
)
) {
$table = strtolower($m[1]);
$capture = isset($wanted[$table]);
$columns = $capture
? array_map(static fn($v) => strtoupper(trim($v, " \t`\"")), explode(',', $m[2]))
: [];
}
continue;
}
if ($line === '\\.') {
$table = null;
$columns = [];
$capture = false;
continue;
}
if ($capture) {
$rows[$table][] = self::copyRow($line, $columns);
}
}
} finally {
fclose($handle);
}
return $rows;
}
private static function copyRow(string $line, array $columns): array
{
$values = explode("\t", $line);
$row = [];
foreach ($columns as $i => $column) {
$row[$column] = self::copyScalar($values[$i] ?? '\\N');
}
return $row;
}
private static function copyScalar(string $value): ?string
{
if ($value === '\\N') {
return null;
}
return preg_replace_callback(
'/\\\\([0-7]{1,3}|.)/s',
static function (array $m): string {
$escape = $m[1];
if (ctype_digit($escape)) {
return chr(octdec($escape));
}
return match ($escape) {
'b' => "\x08",
'f' => "\x0c",
'n' => "\n",
'r' => "\r",
't' => "\t",
'v' => "\x0b",
'\\' => '\\',
default => $escape,
};
},
$value,
) ?? $value;
}
private static function accumulateAnimalStats(array $row, array &$animalStats): void
{
$truthy = static fn($v): bool => (string) $v === '1';
$blank = static fn($v): bool => $v === null || trim((string) $v) === '';
$animalStats[$truthy($row['ARCHIVED'] ?? 0) ? 'archived' : 'active']++;
$animalStats[$truthy($row['ADOPTABLE'] ?? 0) ? 'adoptable' : 'not_adoptable']++;
if (!$blank($row['DECEASEDDATE'] ?? null) || $truthy($row['PUTTOSLEEP'] ?? 0)) {
$animalStats['deceased']++;
}
if (!$blank($row['IDENTICHIPNUMBER'] ?? null) || $truthy($row['IDENTICHIPPED'] ?? 0)) {
$animalStats['microchip']++;
}
if (!$blank($row['TATTOONUMBER'] ?? null) || $truthy($row['TATTOO'] ?? 0)) {
$animalStats['tattoo']++;
}
if ($truthy($row['NEUTERED'] ?? 0)) {
$animalStats['neutered']++;
}
if ($blank($row['ANIMALNAME'] ?? null)) {
$animalStats['missing_name']++;
}
if ($blank($row['DATEOFBIRTH'] ?? null)) {
$animalStats['missing_birth_date']++;
}
$species = (string) ($row['SPECIESID'] ?? 'unknown');
$animalStats['species'][$species] = ($animalStats['species'][$species] ?? 0) + 1;
}
private static function values(string $input): array
{
$values = [];
$value = '';
$quoted = false;
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
$char = $input[$i];
if ($char === "'") {
if ($quoted && $i + 1 < $length && $input[$i + 1] === "'") {
$value .= "'";
$i++;
continue;
}
$quoted = !$quoted;
continue;
}
if ($char === ',' && !$quoted) {
$values[] = self::scalar($value);
$value = '';
continue;
}
$value .= $char;
}
$values[] = self::scalar($value);
return $values;
}
private static function scalar(string $value): mixed
{
$value = trim($value);
if (strcasecmp($value, 'null') === 0) {
return null;
}
return $value;
}
}

View file

@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
final class Asm3AnimalImporter
{
public static function run(string $path, PDO $db, bool $apply = false, bool $createBackup = true): array
{
$plan = Asm3MigrationPlanner::plan($path, $db);
$hash = hash_file('sha256', $path);
if ($hash === false) {
throw new RuntimeException(t('asm3.hash_failed'));
}
$result = [
'mode' => $apply ? 'apply' : 'dry-run',
'source' => basename($path),
'source_sha256' => $hash,
'planned' => $plan['summary'],
'created' => 0,
'linked_matches' => 0,
'skipped_existing_import' => 0,
'skipped_match' => 0,
'skipped_review' => $plan['summary']['review'],
'backup' => null,
'read_only' => !$apply,
];
if (!$apply) {
$result['would_create'] = $plan['summary']['create'];
return $result;
}
if ($createBackup) {
$backup = BackupService::create('pre-asm3-import');
$result['backup'] = $backup['name'] ?? null;
}
$ownsTransaction = !$db->inTransaction();
if ($ownsTransaction) {
$db->beginTransaction();
}
try {
$run = $db->prepare(
"INSERT INTO asm3_import_runs(source_name,source_sha256,status,summary_json,backup_name) VALUES(:name,:hash,'completed','{}',:backup)",
);
$run->execute([':name' => basename($path), ':hash' => $hash, ':backup' => $result['backup']]);
$runId = (int) $db->lastInsertId();
foreach ($plan['items'] as $item) {
if ($item['action'] === 'review') {
continue;
}
$check = $db->prepare(
"SELECT target_id FROM asm3_import_links WHERE source_sha256=:hash AND entity_type='animal' AND source_id=:source",
);
$check->execute([':hash' => $hash, ':source' => $item['asm3_id']]);
if ($check->fetchColumn()) {
$result['skipped_existing_import']++;
continue;
}
if ($item['action'] === 'match') {
$target = (int) ($item['globinours_candidates'][0]['id'] ?? 0);
if ($target <= 0) {
$result['skipped_match']++;
continue;
}
$result['linked_matches']++;
} else {
$target = self::insert($db, $item['mapped'], $item['asm3_id']);
$result['created']++;
}
$db->prepare(
"INSERT INTO asm3_import_links(source_sha256,entity_type,source_id,target_id,import_run_id) VALUES(:hash,'animal',:source,:target,:run)",
)->execute([':hash' => $hash, ':source' => $item['asm3_id'], ':target' => $target, ':run' => $runId]);
}
$db->prepare('UPDATE asm3_import_runs SET summary_json=:summary WHERE id=:id')->execute([
':summary' => json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
':id' => $runId,
]);
if ($ownsTransaction) {
$db->commit();
}
} catch (Throwable $e) {
if ($ownsTransaction && $db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
return $result;
}
private static function insert(PDO $db, array $a, int $sourceId): int
{
$code = trim((string) $a['internal_code']);
if ($code === '') {
$code = 'ASM3-' . $sourceId;
}
$exists = $db->prepare('SELECT 1 FROM animals WHERE internal_code=:code');
$exists->execute([':code' => $code]);
if ($exists->fetchColumn()) {
$code .= '-ASM3-' . $sourceId;
}
$stmt = $db->prepare(
"INSERT INTO animals(internal_code,name,species,sex,birth_date,birth_is_estimated,chip_id,status,sterilized,sterilization_status,sterilization_date,color,breed,notes,intake_date,archived_at,identification_type,identification_date,identification_registration_status,adoption_availability,adoption_available_from,adoption_unavailability_reason,compatibility_dogs,compatibility_cats,compatibility_children,house_trained,created_at,updated_at) VALUES(:code,:name,:species,:sex,:birth,:estimated,:chip,:status,:sterilized,:sterilization_status,:sterilization_date,:color,:breed,:notes,:intake,:archived,:identification_type,:identification_date,:registration,:availability,:available_from,:unavailable_reason,:dogs,:cats,:children,:trained,datetime('now'),datetime('now'))",
);
$stmt->execute([
':code' => $code,
':name' => $a['name'] ?: 'Animal ASM3 ' . $sourceId,
':species' => $a['species'] ?: 'inconnu',
':sex' => $a['sex'],
':birth' => $a['birth_date'],
':estimated' => $a['birth_is_estimated'],
':chip' => $a['chip_id'] ?: null,
':status' => $a['status'],
':sterilized' => $a['sterilization_status'] === 'yes' ? 1 : 0,
':sterilization_status' => $a['sterilization_status'],
':sterilization_date' => $a['sterilization_date'],
':color' => $a['color'],
':breed' => $a['breed'] ?: null,
':notes' => $a['notes'] ?: null,
':intake' => $a['intake_date'],
':archived' => $a['archived'] ? date('Y-m-d H:i:s') : null,
':identification_type' => $a['identification_type'],
':identification_date' => $a['identification_date'],
':registration' => $a['identification_registration_status'],
':availability' => $a['adoption_availability'],
':available_from' => $a['adoption_available_from'],
':unavailable_reason' => $a['adoption_unavailability_reason'] ?: null,
':dogs' => $a['compatibility_dogs'],
':cats' => $a['compatibility_cats'],
':children' => $a['compatibility_children'],
':trained' => $a['house_trained'],
]);
$id = (int) $db->lastInsertId();
if ($a['deceased_date']) {
$db->prepare(
"INSERT INTO animal_deaths(animal_id,deceased_date,cause_code,cause_details,place_type,body_disposition,notes) VALUES(:animal,:date,'unknown',NULL,'inconnu','pending',:notes)",
)->execute([':animal' => $id, ':date' => $a['deceased_date'], ':notes' => 'Importé depuis ASM3']);
}
return $id;
}
}

View file

@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
final class Asm3ClinicalImporter
{
public static function run(string $path, PDO $db, bool $apply = false, bool $createBackup = true): array
{
$hash = hash_file('sha256', $path);
$src = Asm3Analyzer::rows($path, ['animalvaccination', 'vaccinationtype', 'log', 'logtype']);
$links = self::animalLinks($db, $hash);
$types = [];
foreach ($src['vaccinationtype'] ?? [] as $r) {
$types[(int) $r['ID']] = trim((string) $r['VACCINATIONTYPE']);
}
$logTypes = [];
foreach ($src['logtype'] ?? [] as $r) {
$logTypes[(int) $r['ID']] = trim((string) $r['LOGTYPENAME']);
}
$result = [
'mode' => $apply ? 'apply' : 'dry-run',
'read_only' => !$apply,
'vaccinations' => 0,
'medical_notes' => 0,
'weights' => 0,
'unresolved' => 0,
'already_imported' => 0,
'backup' => null,
];
foreach ($src['animalvaccination'] ?? [] as $r) {
$result['vaccinations']++;
if (!isset($links[(int) $r['ANIMALID']])) {
$result['unresolved']++;
}
}
foreach ($src['log'] ?? [] as $r) {
if ((int) ($r['LINKTYPE'] ?? -1) === 0) {
if (!isset($links[(int) $r['LINKID']])) {
$result['unresolved']++;
}
$name = mb_strtolower($logTypes[(int) $r['LOGTYPEID']] ?? '');
if ($name === 'poids') {
$result['weights']++;
} else {
$result['medical_notes']++;
}
}
}
if (!$apply) {
return $result;
}
if ($createBackup) {
$b = BackupService::create('pre-asm3-import');
$result['backup'] = $b['name'] ?? null;
}
$ownsTransaction = !$db->inTransaction();
if ($ownsTransaction) {
$db->beginTransaction();
}
try {
$runId = self::runId($db, $path, $hash, $result['backup'], 'médical');
foreach ($src['animalvaccination'] ?? [] as $r) {
$animal = $links[(int) $r['ANIMALID']] ?? 0;
if (!$animal) {
continue;
}
$source = (int) $r['ID'];
if (self::seen($db, $hash, 'vaccination', $source)) {
$result['already_imported']++;
continue;
}
$name = $types[(int) $r['VACCINATIONID']] ?? 'Vaccin ASM3 ' . (int) $r['VACCINATIONID'];
$db->prepare('INSERT OR IGNORE INTO ref_vaccines(name) VALUES(:name)')->execute([':name' => $name]);
$q = $db->prepare('SELECT id FROM ref_vaccines WHERE name=:name');
$q->execute([':name' => $name]);
$vaccine = (int) $q->fetchColumn();
$db->prepare(
'INSERT INTO vaccinations(animal_id,vaccine_id,done_date,due_date,lot,notes,manufacturer,batch_expires_on,administered_by_name) VALUES(:animal,:vaccine,:done,:due,:lot,:notes,:manufacturer,:expires,:by)',
)->execute([
':animal' => $animal,
':vaccine' => $vaccine,
':done' =>
self::date($r['DATEOFVACCINATION'] ?? null) ?:
self::date($r['DATEREQUIRED'] ?? null) ?:
date('Y-m-d'),
':due' => self::date($r['DATEREQUIRED'] ?? null),
':lot' => trim((string) $r['BATCHNUMBER']) ?: null,
':notes' => trim((string) $r['COMMENTS']) ?: null,
':manufacturer' => trim((string) $r['MANUFACTURER']) ?: null,
':expires' => self::date($r['BATCHEXPIRYDATE'] ?? null),
':by' => trim((string) $r['GIVENBY']) ?: null,
]);
self::link($db, $hash, 'vaccination', $source, (int) $db->lastInsertId(), $runId);
}
foreach ($src['log'] ?? [] as $r) {
if ((int) ($r['LINKTYPE'] ?? -1) !== 0) {
continue;
}
$animal = $links[(int) $r['LINKID']] ?? 0;
if (!$animal) {
continue;
}
$source = (int) $r['ID'];
$name = $logTypes[(int) $r['LOGTYPEID']] ?? 'Historique';
$entity = mb_strtolower($name) === 'poids' ? 'measurement' : 'medical-log';
if (self::seen($db, $hash, $entity, $source)) {
continue;
}
$text = trim((string) $r['COMMENTS']);
$date = self::date($r['DATE'] ?? null) ?: date('Y-m-d');
if ($entity === 'measurement' && preg_match('/([0-9]+(?:[.,][0-9]+)?)/', $text, $m)) {
$value = (float) str_replace(',', '.', $m[1]);
$db->prepare(
"INSERT INTO measurements(animal_id,measured_at,type,value,unit,notes) VALUES(:animal,:date,'weight',:value,'kg',:notes)",
)->execute([':animal' => $animal, ':date' => $date, ':value' => $value, ':notes' => $text]);
} else {
$db->prepare(
"INSERT INTO medical_notes(animal_id,noted_at,kind,reason,plan) VALUES(:animal,:date,'autre',:reason,:plan)",
)->execute([':animal' => $animal, ':date' => $date, ':reason' => $name, ':plan' => $text ?: null]);
}
self::link($db, $hash, $entity, $source, (int) $db->lastInsertId(), $runId);
}
if ($ownsTransaction) {
$db->commit();
}
} catch (Throwable $e) {
if ($ownsTransaction && $db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
return $result;
}
private static function animalLinks(PDO $db, string $hash): array
{
$s = $db->prepare(
"SELECT source_id,target_id FROM asm3_import_links WHERE source_sha256=:h AND entity_type='animal'",
);
$s->execute([':h' => $hash]);
$o = [];
foreach ($s as $r) {
$o[(int) $r['source_id']] = (int) $r['target_id'];
}
return $o;
}
private static function runId(PDO $db, string $p, string $h, ?string $b, string $label): int
{
$db->prepare(
"INSERT INTO asm3_import_runs(source_name,source_sha256,status,summary_json,backup_name) VALUES(:n,:h,'completed','{}',:b)",
)->execute([':n' => basename($p) . ' · ' . $label, ':h' => $h, ':b' => $b]);
return (int) $db->lastInsertId();
}
private static function seen(PDO $db, string $h, string $e, int $s): bool
{
$q = $db->prepare('SELECT 1 FROM asm3_import_links WHERE source_sha256=:h AND entity_type=:e AND source_id=:s');
$q->execute([':h' => $h, ':e' => $e, ':s' => $s]);
return (bool) $q->fetchColumn();
}
private static function link(PDO $db, string $h, string $e, int $s, int $t, int $r): void
{
$db->prepare(
'INSERT INTO asm3_import_links(source_sha256,entity_type,source_id,target_id,import_run_id) VALUES(:h,:e,:s,:t,:r)',
)->execute([':h' => $h, ':e' => $e, ':s' => $s, ':t' => $t, ':r' => $r]);
}
private static function date(mixed $v): ?string
{
return $v && preg_match('/^\d{4}-\d{2}-\d{2}/', (string) $v, $m) ? $m[0] : null;
}
}

View file

@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
final class Asm3ContactImporter
{
public static function run(string $path, PDO $db, bool $apply = false, bool $createBackup = true): array
{
$plan = Asm3ContactPlanner::plan($path, $db);
$hash = hash_file('sha256', $path);
if ($hash === false) {
throw new RuntimeException(t('asm3.hash_unavailable'));
}
$result = [
'mode' => $apply ? 'apply' : 'dry-run',
'entity' => 'contacts',
'planned' => $plan['summary'],
'created' => 0,
'linked_matches' => 0,
'skipped_match' => 0,
'skipped_review' => $plan['summary']['review'],
'backup' => null,
'read_only' => !$apply,
'would_create' => $plan['summary']['create'],
];
if (!$apply) {
return $result;
}
if ($createBackup) {
$backup = BackupService::create('pre-asm3-import');
$result['backup'] = $backup['name'] ?? null;
}
$ownsTransaction = !$db->inTransaction();
if ($ownsTransaction) {
$db->beginTransaction();
}
try {
$db->prepare(
"INSERT INTO asm3_import_runs(source_name,source_sha256,status,summary_json,backup_name) VALUES(:name,:hash,'completed','{}',:backup)",
)->execute([':name' => basename($path) . ' · contacts', ':hash' => $hash, ':backup' => $result['backup']]);
$runId = (int) $db->lastInsertId();
foreach ($plan['items'] as $item) {
if ($item['action'] === 'review') {
continue;
}
$check = $db->prepare(
"SELECT target_id FROM asm3_import_links WHERE source_sha256=:hash AND entity_type='contact' AND source_id=:source",
);
$check->execute([':hash' => $hash, ':source' => $item['asm3_id']]);
if ($check->fetchColumn()) {
continue;
}
$c = $item['mapped'];
if ($item['action'] === 'match') {
$target = (int) ($item['globinours_candidates'][0]['id'] ?? 0);
if ($target <= 0) {
$result['skipped_match']++;
continue;
}
$result['linked_matches']++;
} else {
$db->prepare(
'INSERT INTO directory_contacts(kind,name,phone,email,address,postal_code,city,country,notes) VALUES(:kind,:name,:phone,:email,:address,:postal,:city,:country,:notes)',
)->execute([
':kind' => $c['kind'],
':name' => $c['name'],
':phone' => $c['phone'],
':email' => $c['email'],
':address' => $c['address'],
':postal' => $c['postal_code'],
':city' => $c['city'],
':country' => $c['country'],
':notes' => $c['notes'],
]);
$target = (int) $db->lastInsertId();
$result['created']++;
}
$role = $db->prepare(
'INSERT OR IGNORE INTO directory_contact_roles(contact_id,role) VALUES(:contact,:role)',
);
foreach ($c['roles'] as $value) {
$role->execute([':contact' => $target, ':role' => $value]);
}
$db->prepare(
"INSERT INTO asm3_import_links(source_sha256,entity_type,source_id,target_id,import_run_id) VALUES(:hash,'contact',:source,:target,:run)",
)->execute([':hash' => $hash, ':source' => $item['asm3_id'], ':target' => $target, ':run' => $runId]);
}
$db->prepare('UPDATE asm3_import_runs SET summary_json=:summary WHERE id=:id')->execute([
':summary' => json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
':id' => $runId,
]);
if ($ownsTransaction) {
$db->commit();
}
} catch (Throwable $e) {
if ($ownsTransaction && $db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
return $result;
}
}

View file

@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
final class Asm3ContactPlanner
{
public static function plan(string $path, PDO $db): array
{
$source = Asm3Analyzer::rows($path, ['owner', 'animal', 'adoption', 'animalvaccination']);
$adopters = [];
$depositors = [];
$vets = [];
foreach ($source['adoption'] ?? [] as $r) {
if ((int) ($r['OWNERID'] ?? 0) > 0) {
$adopters[(int) $r['OWNERID']] = true;
}
}
foreach ($source['animal'] ?? [] as $r) {
foreach (['BROUGHTINBYOWNERID', 'ORIGINALOWNERID'] as $field) {
if ((int) ($r[$field] ?? 0) > 0) {
$depositors[(int) $r[$field]] = true;
}
}
foreach (['CURRENTVETID', 'OWNERSVETID'] as $field) {
if ((int) ($r[$field] ?? 0) > 0) {
$vets[(int) $r[$field]] = true;
}
}
}
foreach ($source['animalvaccination'] ?? [] as $r) {
if ((int) ($r['ADMINISTERINGVETID'] ?? 0) > 0) {
$vets[(int) $r['ADMINISTERINGVETID']] = true;
}
}
$existing = $db
->query('SELECT id,kind,name,phone,email,city FROM directory_contacts WHERE deleted_at IS NULL')
->fetchAll(PDO::FETCH_ASSOC);
$items = [];
$summary = ['create' => 0, 'match' => 0, 'review' => 0];
foreach ($source['owner'] ?? [] as $row) {
$mapped = self::map(
$row,
isset($adopters[(int) $row['ID']]),
isset($depositors[(int) $row['ID']]),
isset($vets[(int) $row['ID']]),
);
$strong = [];
$weak = [];
$reasons = [];
foreach ($existing as $contact) {
$email = self::text($mapped['email']);
$phone = self::phone($mapped['phone']);
$sameEmail = $email !== '' && $email === self::text($contact['email']);
$samePhone = $phone !== '' && $phone === self::phone($contact['phone']);
$sameIdentity =
self::text($mapped['name']) === self::text($contact['name']) &&
self::text($mapped['city']) === self::text($contact['city']);
if ($sameEmail || $samePhone || $sameIdentity) {
$strong[(int) $contact['id']] = $contact;
if ($sameEmail) {
$reasons[] = 'même adresse e-mail';
}
if ($samePhone) {
$reasons[] = 'même téléphone';
}
if ($sameIdentity) {
$reasons[] = 'même nom et ville';
}
} elseif (
self::text($mapped['name']) !== '' &&
self::text($mapped['name']) === self::text($contact['name'])
) {
$weak[(int) $contact['id']] = $contact;
}
}
if (count($strong) === 1) {
$action = 'match';
$candidates = $strong;
} elseif (count($strong) > 1) {
$action = 'review';
$candidates = $strong;
} elseif ($weak) {
$action = 'review';
$candidates = $weak;
$reasons[] = 'même nom uniquement';
} else {
$action = 'create';
$candidates = [];
}
$summary[$action]++;
$items[] = [
'asm3_id' => (int) $row['ID'],
'action' => $action,
'match_reasons' => array_values(array_unique($reasons)),
'globinours_candidates' => array_values(
array_map(
static fn($c) => ['id' => (int) $c['id'], 'name' => $c['name'], 'city' => $c['city']],
$candidates,
),
),
'mapped' => $mapped,
];
}
return ['source' => basename($path), 'read_only' => true, 'summary' => $summary, 'items' => $items];
}
private static function map(array $r, bool $adopter, bool $depositor, bool $vetReferenced): array
{
$yes = static fn($v) => (string) $v === '1';
$name = trim(
(string) ($r['OWNERNAME'] ?? '' ?:
trim((string) ($r['OWNERFORENAMES'] ?? '') . ' ' . (string) ($r['OWNERSURNAME'] ?? ''))),
);
$organization =
(bool) preg_match('/\b(cabinet|clinique|cr[eé]matorium|association|refuge|fourri[eè]re)\b/iu', $name) ||
$yes($r['ISSHELTER'] ?? 0) ||
$yes($r['ISSUPPLIER'] ?? 0);
$roles = [];
if ($adopter || $yes($r['ISADOPTER'] ?? 0)) {
$roles[] = 'adoptant';
}
if ($yes($r['ISFOSTERER'] ?? 0)) {
$roles[] = 'fa';
}
if ($yes($r['ISVOLUNTEER'] ?? 0)) {
$roles[] = 'benevole';
}
if ($depositor) {
$roles[] = 'deposant';
}
if ($vetReferenced || $yes($r['ISVET'] ?? 0)) {
$roles[] = $organization ? 'cabinet' : 'veterinaire';
}
if (preg_match('/cr[eé]matorium/iu', $name)) {
$roles[] = 'crematorium';
}
$phones = array_values(
array_filter([
trim((string) ($r['MOBILETELEPHONE'] ?? '')),
trim((string) ($r['HOMETELEPHONE'] ?? '')),
trim((string) ($r['WORKTELEPHONE'] ?? '')),
]),
);
return [
'kind' => $organization ? 'organization' : 'person',
'name' => $name ?: 'Contact ASM3 ' . (int) $r['ID'],
'phone' => $phones[0] ?? null,
'email' => trim((string) ($r['EMAILADDRESS'] ?? '')) ?: null,
'address' => trim((string) ($r['OWNERADDRESS'] ?? '')) ?: null,
'postal_code' => trim((string) ($r['OWNERPOSTCODE'] ?? '')) ?: null,
'city' => trim((string) ($r['OWNERTOWN'] ?? '')) ?: null,
'country' => trim((string) ($r['OWNERCOUNTRY'] ?? '')) ?: 'France',
'notes' => trim((string) ($r['COMMENTS'] ?? '')) ?: null,
'roles' => array_values(array_unique($roles)),
];
}
private static function text(mixed $v): string
{
return mb_strtolower(trim((string) $v));
}
private static function phone(mixed $v): string
{
return (string) preg_replace('/\D+/', '', (string) $v);
}
}

View file

@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
final class Asm3IntakeRecovery
{
private const CITIES = [
'Betton' => ['betton', 'beton'],
'Brignogan-Plages' => ['brignogan'],
'Fougères' => ['fougère', 'fougeres'],
'Gouesnou' => ['gouesnou'],
'Goulven' => ['goulven'],
'Guissény' => ['guissény', 'guisseny'],
'Kernouës' => ['kernouës', 'kernoues'],
'Kerlouan' => ['kerlouan'],
'Landerneau' => ['landerneau'],
'Lanhouarneau' => ['lanhouarneau'],
'Landivisiau' => ['landivisiau'],
'Le Drennec' => ['le drennec'],
'Le Folgoët' => ['le folgoët', 'le folgoet', 'du folgoët', 'du folgoet'],
'Lesneven' => ['lesneven', 'lesnevenet'],
'Perros-Guirec' => ['perros guirec', 'perros guierrec'],
'Ploudaniel' => ['ploudaniel'],
'Plouescat' => ['plouescat'],
'Plouguerneau' => ['plouguerneau'],
'Plouider' => ['plouider'],
'Plounéour-Brignogan-Plages' => [
'plounéour trez',
'plouneour trez',
'plounéour brignogan plage',
'plouneour brignogan plage',
],
'Plounévez-Lochrist' => ['plounevez lochrist', 'plounévez lochrist'],
'Plouzané' => ['plouzané', 'plouzane'],
'Saint-Frégant' => ['saint frégant', 'saint fregant'],
'Saint-Méen' => ['saint méen', 'saint meen'],
'Saint-Pol-de-Léon' => ['saint pol de leon', 'saint-pol-de-léon'],
];
public static function reason(array $row): string
{
return trim((string) ($row['REASONFORENTRY'] ?? ''));
}
public static function municipality(string $reason): ?string
{
$text = self::plain($reason);
if ($text === '') {
return null;
}
$found = [];
foreach (self::CITIES as $city => $aliases) {
foreach ($aliases as $alias) {
if (str_contains($text, self::plain($alias))) {
$found[$city] = true;
break;
}
}
}
if (count($found) !== 1) {
return null;
}
$city = (string) array_key_first($found);
$words =
'trouv|errant|recueill|recup|ramass|vient|arriv|fourriere|mairie|police municipale|jardin|terrain|ferme|hangar|grange|ne dans|abandonn|signal';
if (preg_match('/^\s*' . self::cityPattern($city) . '\b/u', $text)) {
return $city;
}
if (preg_match('/(?:' . $words . ').{0,100}' . self::cityPattern($city) . '/u', $text)) {
return $city;
}
if (preg_match('/' . self::cityPattern($city) . '.{0,55}(?:' . $words . ')/u', $text)) {
return $city;
}
return null;
}
private static function cityPattern(string $city): string
{
$parts = [];
foreach (self::CITIES[$city] as $alias) {
$parts[] = preg_quote(self::plain($alias), '/');
}
return '(?:' . implode('|', $parts) . ')';
}
private static function plain(string $value): string
{
$value = mb_strtolower(trim($value));
$v = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value);
return preg_replace('/\s+/u', ' ', is_string($v) ? $v : $value) ?? $value;
}
}

View file

@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
final class Asm3LitterImporter
{
public static function run(string $path, PDO $db, bool $apply = false, bool $createBackup = true): array
{
$hash = hash_file('sha256', $path);
$src = Asm3Analyzer::rows($path, ['animallitter', 'animal']);
$links = [];
$q = $db->prepare(
"SELECT source_id,target_id FROM asm3_import_links WHERE source_sha256=:h AND entity_type='animal'",
);
$q->execute([':h' => $hash]);
foreach ($q as $r) {
$links[(int) $r['source_id']] = (int) $r['target_id'];
}
$animals = [];
foreach ($src['animal'] ?? [] as $a) {
$animals[(string) $a['ACCEPTANCENUMBER']][] = (int) $a['ID'];
}
$result = [
'mode' => $apply ? 'apply' : 'dry-run',
'read_only' => !$apply,
'litters' => count($src['animallitter'] ?? []),
'would_import' => 0,
'unresolved' => 0,
'created' => 0,
'kittens_linked' => 0,
'backup' => null,
];
foreach ($src['animallitter'] ?? [] as $l) {
$parent = (int) $l['PARENTANIMALID'];
$kids = array_filter($animals[(string) $l['ACCEPTANCENUMBER']] ?? [], fn($id) => $id !== $parent);
if (!isset($links[$parent]) || array_filter($kids, fn($id) => !isset($links[$id]))) {
$result['unresolved']++;
continue;
}
$result['would_import']++;
}
if (!$apply) {
return $result;
}
if ($createBackup) {
$b = BackupService::create('pre-asm3-import');
$result['backup'] = $b['name'] ?? null;
}
$owns = !$db->inTransaction();
if ($owns) {
$db->beginTransaction();
}
try {
$db->prepare(
"INSERT INTO asm3_import_runs(source_name,source_sha256,status,summary_json,backup_name) VALUES(:n,:h,'completed','{}',:b)",
)->execute([':n' => basename($path) . ' · portées', ':h' => $hash, ':b' => $result['backup']]);
$run = (int) $db->lastInsertId();
foreach ($src['animallitter'] ?? [] as $l) {
$source = (int) $l['ID'];
$seen = $db->prepare(
"SELECT 1 FROM asm3_import_links WHERE source_sha256=:h AND entity_type='litter' AND source_id=:s",
);
$seen->execute([':h' => $hash, ':s' => $source]);
if ($seen->fetchColumn()) {
continue;
}
$parent = (int) $l['PARENTANIMALID'];
$kids = array_values(
array_filter($animals[(string) $l['ACCEPTANCENUMBER']] ?? [], fn($id) => $id !== $parent),
);
if (!isset($links[$parent]) || array_filter($kids, fn($id) => !isset($links[$id]))) {
continue;
}
$db->prepare('INSERT INTO litters(mother_id,birth_date,notes) VALUES(:parent,:date,:notes)')->execute([
':parent' => $links[$parent],
':date' => substr((string) $l['DATE'], 0, 10),
':notes' => trim((string) $l['COMMENTS']) ?: null,
]);
$target = (int) $db->lastInsertId();
$ins = $db->prepare(
'INSERT OR IGNORE INTO litter_kittens(litter_id,animal_id,position) VALUES(:litter,:animal,:position)',
);
foreach ($kids as $i => $kid) {
$ins->execute([':litter' => $target, ':animal' => $links[$kid], ':position' => $i + 1]);
$result['kittens_linked']++;
}
$db->prepare(
"INSERT INTO asm3_import_links(source_sha256,entity_type,source_id,target_id,import_run_id) VALUES(:h,'litter',:s,:t,:r)",
)->execute([':h' => $hash, ':s' => $source, ':t' => $target, ':r' => $run]);
$result['created']++;
}
if ($owns) {
$db->commit();
}
} catch (Throwable $e) {
if ($owns && $db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
return $result;
}
}

View file

@ -0,0 +1,199 @@
<?php
declare(strict_types=1);
final class Asm3MigrationPlanner
{
public static function plan(string $path, PDO $db): array
{
$source = Asm3Analyzer::rows($path, ['animal', 'species', 'basecolour', 'lksex']);
$species = self::lookup($source['species'] ?? [], 'ID', 'SPECIESNAME');
$colors = self::lookup($source['basecolour'] ?? [], 'ID', 'BASECOLOUR');
$sexes = self::lookup($source['lksex'] ?? [], 'ID', 'SEX');
$existing = $db
->query('SELECT id,name,internal_code,chip_id,birth_date FROM animals')
->fetchAll(PDO::FETCH_ASSOC);
$byChip = [];
$byCode = [];
$byIdentity = [];
$byName = [];
foreach ($existing as $animal) {
$chip = self::identifier($animal['chip_id'] ?? '');
if ($chip !== '') {
$byChip[$chip][] = $animal;
}
$code = self::text($animal['internal_code'] ?? '');
if ($code !== '') {
$byCode[$code][] = $animal;
}
$identity = self::identity($animal['name'] ?? '', $animal['birth_date'] ?? '');
if ($identity !== '') {
$byIdentity[$identity][] = $animal;
}
$name = self::text($animal['name'] ?? '');
if ($name !== '') {
$byName[$name][] = $animal;
}
}
$items = [];
$summary = ['create' => 0, 'match' => 0, 'review' => 0];
foreach ($source['animal'] ?? [] as $row) {
$mapped = self::mapAnimal($row, $species, $colors, $sexes);
$candidates = [];
$reasons = [];
$chip = self::identifier($mapped['chip_id']);
if ($chip !== '' && !empty($byChip[$chip])) {
foreach ($byChip[$chip] as $a) {
$candidates[(int) $a['id']] = $a;
}
$reasons[] = 'même identification';
}
// Les codes refuge peuvent être réutilisés après une remise à zéro d’ASM3.
// Un code seul n’est donc jamais une preuve suffisante entre deux sauvegardes historiques.
$code = self::text($mapped['internal_code']);
$identity = self::identity($mapped['name'], $mapped['birth_date']);
if ($identity !== '' && !empty($byIdentity[$identity])) {
foreach ($byIdentity[$identity] as $a) {
$candidates[(int) $a['id']] = $a;
}
$reasons[] = 'même nom et naissance';
}
$strongMatch = count($candidates) > 0;
if (!$strongMatch) {
$name = self::text($mapped['name']);
if ($name !== '' && !empty($byName[$name])) {
$weakByName = $byName[$name];
$knownDifferentBirths = $mapped['birth_date'] !== '' && $mapped['birth_date'] !== null;
foreach ($weakByName as $a) {
$knownDifferentBirths =
$knownDifferentBirths &&
!empty($a['birth_date']) &&
$a['birth_date'] !== $mapped['birth_date'];
}
if (!$knownDifferentBirths) {
foreach ($weakByName as $a) {
$candidates[(int) $a['id']] = $a;
}
$reasons[] = 'même nom uniquement';
}
}
}
// Un code isolé et réutilisé ne doit ni fusionner, ni bloquer la création.
// Asm3AnimalImporter suffixera le code technique si nécessaire.
if (!$strongMatch && count($candidates) === 0) {
$action = 'create';
} elseif ($strongMatch && count($candidates) === 1) {
$action = 'match';
} else {
$action = 'review';
}
$summary[$action]++;
$items[] = [
'asm3_id' => (int) ($row['ID'] ?? 0),
'action' => $action,
'match_reasons' => array_values(array_unique($reasons)),
'globinours_candidates' => array_values(
array_map(
static fn($a) => ['id' => (int) $a['id'], 'name' => $a['name'], 'code' => $a['internal_code']],
$candidates,
),
),
'mapped' => $mapped,
];
}
return [
'source' => basename($path),
'generated_at' => date(DATE_ATOM),
'read_only' => true,
'summary' => $summary,
'items' => $items,
'lookups' => ['species' => $species, 'colors' => $colors, 'sexes' => $sexes],
];
}
private static function mapAnimal(array $r, array $species, array $colors, array $sexes): array
{
$date = static fn($v) => $v && preg_match('/^\d{4}-\d{2}-\d{2}/', (string) $v, $m) ? $m[0] : null;
$yes = static fn($v) => (string) $v === '1';
$tri = static fn($v) => match ((string) $v) {
'0' => 'no',
'1' => 'yes',
default => 'unknown',
};
$chip = trim((string) ($r['IDENTICHIPNUMBER'] ?? ''));
$tattoo = trim((string) ($r['TATTOONUMBER'] ?? ''));
$identifier = $chip !== '' ? $chip : $tattoo;
$deceased = $date($r['DECEASEDDATE'] ?? null) !== null || $yes($r['PUTTOSLEEP'] ?? 0);
$availability = $yes($r['ISNOTAVAILABLEFORADOPTION'] ?? 0)
? 'not_available'
: ($yes($r['ADOPTABLE'] ?? 0)
? 'available'
: 'unknown');
return [
'name' => trim((string) ($r['ANIMALNAME'] ?? '')),
'internal_code' => trim((string) ($r['SHELTERCODE'] ?? '' ?: $r['SHORTCODE'] ?? '')),
'species' => self::species($species[(string) ($r['SPECIESID'] ?? '')] ?? ''),
'sex' => match (mb_strtolower((string) ($sexes[(string) ($r['SEX'] ?? '')] ?? ''))) {
'mâle' => 'M',
'femelle' => 'F',
default => 'U',
},
'birth_date' => $date($r['DATEOFBIRTH'] ?? null),
'birth_is_estimated' => $yes($r['ESTIMATEDDOB'] ?? 0) ? 1 : 0,
'breed' => trim((string) ($r['BREEDNAME'] ?? '')),
'color' => $colors[(string) ($r['BASECOLOURID'] ?? '')] ?? null,
'notes' => trim((string) ($r['ANIMALCOMMENTS'] ?? '')),
'intake_date' => $date($r['MOSTRECENTENTRYDATE'] ?? null ?: $r['DATEBROUGHTIN'] ?? null),
'status' => $deceased ? 'decede' : ($yes($r['ISQUARANTINE'] ?? 0) ? 'quarantaine' : 'refuge'),
'archived' => $yes($r['ARCHIVED'] ?? 0),
'deceased_date' => $date($r['DECEASEDDATE'] ?? null),
'identification_type' => $chip !== '' ? 'microchip' : ($tattoo !== '' ? 'tattoo' : 'unknown'),
'chip_id' => $identifier,
'identification_date' => $date($chip !== '' ? $r['IDENTICHIPDATE'] ?? null : $r['TATTOODATE'] ?? null),
'identification_registration_status' => match ((string) ($r['IDENTICHIPSTATUS'] ?? '')) {
'1' => 'registered',
'0' => 'pending',
default => 'unknown',
},
'sterilization_status' => $yes($r['NEUTERED'] ?? 0) ? 'yes' : 'unknown',
'sterilization_date' => $date($r['NEUTEREDDATE'] ?? null),
'adoption_availability' => $availability,
'adoption_available_from' => $date($r['HOLDUNTILDATE'] ?? null),
'adoption_unavailability_reason' => trim((string) ($r['REASONNO'] ?? '')),
'compatibility_dogs' => $tri($r['ISGOODWITHDOGS'] ?? null),
'compatibility_cats' => $tri($r['ISGOODWITHCATS'] ?? null),
'compatibility_children' => $tri($r['ISGOODWITHCHILDREN'] ?? null),
'house_trained' => $tri($r['ISHOUSETRAINED'] ?? null),
];
}
private static function lookup(array $rows, string $key, string $value): array
{
$out = [];
foreach ($rows as $row) {
$out[(string) $row[$key]] = (string) $row[$value];
}
return $out;
}
private static function species(string $value): string
{
return match (mb_strtolower($value)) {
'chat' => 'chat',
'chien' => 'chien',
default => mb_strtolower($value) ?: 'inconnu',
};
}
private static function identifier(mixed $value): string
{
return strtoupper((string) preg_replace('/[^a-zA-Z0-9]/', '', (string) $value));
}
private static function text(mixed $value): string
{
return mb_strtolower(trim((string) $value));
}
private static function identity(mixed $name, mixed $birth): string
{
$name = self::text($name);
$birth = trim((string) $birth);
return $name !== '' && $birth !== '' ? $name . '|' . $birth : '';
}
}

View file

@ -0,0 +1,271 @@
<?php
declare(strict_types=1);
final class Asm3MovementImporter
{
public static function run(string $path, PDO $db, bool $apply = false, bool $createBackup = true): array
{
$hash = hash_file('sha256', $path);
if ($hash === false) {
throw new RuntimeException(t('asm3.hash_unavailable'));
}
$rows = Asm3Analyzer::rows($path, ['adoption'])['adoption'] ?? [];
$events = [];
$unsupported = 0;
foreach ($rows as $row) {
$source = (int) ($row['ID'] ?? 0);
$type = (int) ($row['MOVEMENTTYPE'] ?? 0);
$movementDate = self::date($row['MOVEMENTDATE'] ?? null);
$returnDate = self::date($row['RETURNDATE'] ?? null);
$reservationDate = self::date($row['RESERVATIONDATE'] ?? null);
$cancelDate = self::date($row['RESERVATIONCANCELLEDDATE'] ?? null);
if ($reservationDate) {
$events[] = self::event($row, $source, 'reservation', $reservationDate, 'Réservation ASM3');
}
if ($cancelDate) {
$events[] = self::event($row, $source, 'cancellation', $cancelDate, 'Annulation de réservation ASM3');
}
if ($movementDate && $type === 1) {
$events[] = self::event($row, $source, 'adoption', $movementDate, 'Adoption définitive ASM3');
} elseif ($movementDate && in_array($type, [2, 12], true)) {
$events[] = self::event(
$row,
$source,
'foster',
$movementDate,
$type === 12 || (string) ($row['ISPERMANENTFOSTER'] ?? 0) === '1'
? 'FA permanente ASM3'
: 'Famille d’accueil ASM3',
);
} elseif ($movementDate && !in_array($type, [0, 9, 10], true)) {
$unsupported++;
}
if ($returnDate && in_array($type, [1, 2, 12], true)) {
$events[] = self::event(
$row,
$source,
'return',
$returnDate,
trim((string) ($row['REASONFORRETURN'] ?? '')) ?: 'Retour enregistré dans ASM3',
);
}
}
$links = self::links($db, $hash);
$summary = [
'events' => count($events),
'adoptions' => 0,
'fosters' => 0,
'returns' => 0,
'reservations' => 0,
'cancellations' => 0,
'unresolved_animals' => 0,
'unresolved_contacts' => 0,
'unsupported_movements' => $unsupported,
'would_import' => 0,
'created' => 0,
'already_imported' => 0,
];
foreach ($events as $event) {
$summary[
$event['type'] === 'adoption'
? 'adoptions'
: ($event['type'] === 'foster'
? 'fosters'
: ($event['type'] === 'return'
? 'returns'
: ($event['type'] === 'reservation'
? 'reservations'
: 'cancellations')))
]++;
if (!isset($links['animal'][$event['animal_source_id']])) {
$summary['unresolved_animals']++;
continue;
}
if ($event['contact_source_id'] > 0 && !isset($links['contact'][$event['contact_source_id']])) {
$summary['unresolved_contacts']++;
}
$summary['would_import']++;
}
if (!$apply) {
return ['mode' => 'dry-run', 'read_only' => true, 'summary' => $summary];
}
if ($createBackup) {
$backup = BackupService::create('pre-asm3-import');
$backupName = $backup['name'] ?? null;
} else {
$backupName = null;
}
$ownsTransaction = !$db->inTransaction();
if ($ownsTransaction) {
$db->beginTransaction();
}
try {
$db->prepare(
"INSERT INTO asm3_import_runs(source_name,source_sha256,status,summary_json,backup_name) VALUES(:name,:hash,'completed','{}',:backup)",
)->execute([':name' => basename($path) . ' · mouvements', ':hash' => $hash, ':backup' => $backupName]);
$runId = (int) $db->lastInsertId();
$affected = [];
foreach ($events as $event) {
$animalId = $links['animal'][$event['animal_source_id']] ?? 0;
if (!$animalId) {
continue;
}
$affected[$animalId] = true;
$entity = 'placement-' . $event['type'];
$exists = $db->prepare(
'SELECT target_id FROM asm3_import_links WHERE source_sha256=:hash AND entity_type=:entity AND source_id=:source',
);
$exists->execute([':hash' => $hash, ':entity' => $entity, ':source' => $event['source_id']]);
if ($exists->fetchColumn()) {
$summary['already_imported']++;
continue;
}
$contactId = $links['contact'][$event['contact_source_id']] ?? null;
$adoptionId = null;
if ($event['type'] === 'adoption') {
$contact = self::contact($db, $contactId);
$db->prepare(
'INSERT INTO adoptions(animal_id,adopter_name,adopter_phone,adopter_email,adopter_address,adopter_postal_code,adopter_city,adopter_country,adoption_date,notes,adopter_contact_id) VALUES(:animal,:name,:phone,:email,:address,:postal,:city,:country,:date,:notes,:contact)',
)->execute([
':animal' => $animalId,
':name' => $contact['name'] ?? 'Adoptant ASM3 non retrouvé',
':phone' => $contact['phone'] ?? null,
':email' => $contact['email'] ?? null,
':address' => $contact['address'] ?? null,
':postal' => $contact['postal_code'] ?? null,
':city' => $contact['city'] ?? null,
':country' => $contact['country'] ?? 'France',
':date' => $event['date'],
':notes' => $event['notes'] ?: null,
':contact' => $contactId,
]);
$adoptionId = (int) $db->lastInsertId();
}
$db->prepare(
'INSERT INTO animal_placements(animal_id,event_type,event_date,contact_id,reason,notes,adoption_id) VALUES(:animal,:type,:date,:contact,:reason,:notes,:adoption)',
)->execute([
':animal' => $animalId,
':type' => $event['type'],
':date' => $event['date'],
':contact' => $contactId,
':reason' => $event['reason'],
':notes' => $event['notes'] ?: null,
':adoption' => $adoptionId,
]);
$placementId = (int) $db->lastInsertId();
$db->prepare(
'INSERT INTO asm3_import_links(source_sha256,entity_type,source_id,target_id,import_run_id) VALUES(:hash,:entity,:source,:target,:run)',
)->execute([
':hash' => $hash,
':entity' => $entity,
':source' => $event['source_id'],
':target' => $placementId,
':run' => $runId,
]);
$summary['created']++;
}
self::syncAnimalStates($db, array_keys($affected));
$db->prepare('UPDATE asm3_import_runs SET summary_json=:summary WHERE id=:id')->execute([
':summary' => json_encode($summary, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
':id' => $runId,
]);
if ($ownsTransaction) {
$db->commit();
}
} catch (Throwable $e) {
if ($ownsTransaction && $db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
return ['mode' => 'apply', 'read_only' => false, 'backup' => $backupName, 'summary' => $summary];
}
private static function event(array $row, int $source, string $type, string $date, string $reason): array
{
return [
'source_id' => $source,
'type' => $type,
'date' => $date,
'animal_source_id' => (int) ($row['ANIMALID'] ?? 0),
'contact_source_id' => (int) ($row['OWNERID'] ?? 0),
'reason' => $reason,
'notes' => trim((string) ($row['COMMENTS'] ?? '')),
];
}
private static function date(mixed $value): ?string
{
return $value && preg_match('/^\d{4}-\d{2}-\d{2}/', (string) $value, $m) ? $m[0] : null;
}
private static function links(PDO $db, string $hash): array
{
$out = ['animal' => [], 'contact' => []];
$s = $db->prepare(
"SELECT entity_type,source_id,target_id FROM asm3_import_links WHERE source_sha256=:hash AND entity_type IN ('animal','contact')",
);
$s->execute([':hash' => $hash]);
foreach ($s as $r) {
$out[$r['entity_type']][(int) $r['source_id']] = (int) $r['target_id'];
}
return $out;
}
private static function contact(PDO $db, ?int $id): ?array
{
if (!$id) {
return null;
}
$s = $db->prepare('SELECT * FROM directory_contacts WHERE id=:id');
$s->execute([':id' => $id]);
return $s->fetch(PDO::FETCH_ASSOC) ?: null;
}
private static function syncAnimalStates(PDO $db, array $animalIds): void
{
$latest = $db->prepare(
'SELECT ap.*,dc.name contact_name,dc.address,dc.postal_code,dc.city FROM animal_placements ap LEFT JOIN directory_contacts dc ON dc.id=ap.contact_id WHERE ap.animal_id=:animal ORDER BY date(ap.event_date) DESC,ap.id DESC LIMIT 1',
);
foreach ($animalIds as $animalId) {
$death = $db->prepare('SELECT 1 FROM animal_deaths WHERE animal_id=?');
$death->execute([$animalId]);
if ($death->fetchColumn()) {
continue;
}
$latest->execute([':animal' => $animalId]);
$event = $latest->fetch(PDO::FETCH_ASSOC);
if (!$event) {
continue;
}
$address = implode(
' ',
array_filter([$event['address'] ?? null, $event['postal_code'] ?? null, $event['city'] ?? null]),
);
if ($event['event_type'] === 'adoption') {
$db->prepare(
"UPDATE animals SET status='adopte',is_archived=1,archived_at=:archived,current_address=:address,refuge_room=NULL,care_box_key=NULL,quarantine_until=NULL,updated_at=datetime('now') WHERE id=:id",
)->execute([
':archived' => $event['event_date'] . ' 12:00:00',
':address' =>
$address !== ''
? $address
: 'Adopté par ' . ($event['contact_name'] ?: 'un adoptant non renseigné'),
':id' => $animalId,
]);
} elseif ($event['event_type'] === 'foster') {
$db->prepare(
"UPDATE animals SET status=CASE WHEN lower(COALESCE(reason,'')) LIKE '%permanente%' THEN 'fa_permanente' ELSE 'fa' END,is_archived=0,archived_at=NULL,current_address=:address,refuge_room=NULL,care_box_key=NULL,updated_at=datetime('now') WHERE id=:id",
)->execute([
':address' =>
$address !== '' ? $address : 'Chez ' . ($event['contact_name'] ?: 'une famille d’accueil'),
':id' => $animalId,
]);
} elseif (in_array($event['event_type'], ['return', 'cancellation'], true)) {
$db->prepare(
"UPDATE animals SET status='refuge',is_archived=0,archived_at=NULL,current_address=NULL,updated_at=datetime('now') WHERE id=?",
)->execute([$animalId]);
} elseif ($event['event_type'] === 'reservation') {
$db->prepare(
"UPDATE animals SET status='reserve',is_archived=0,archived_at=NULL,updated_at=datetime('now') WHERE id=?",
)->execute([$animalId]);
}
}
}
}

View file

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
final class Asm3ResetService
{
public static function clear(PDO $db): array
{
$before = [
'animals' => (int) $db->query('SELECT COUNT(*) FROM animals')->fetchColumn(),
'contacts' => (int) $db->query('SELECT COUNT(*) FROM directory_contacts')->fetchColumn(),
];
$tables = [
'agenda_volunteers',
'agenda_items',
'prescription_treatments',
'lab_results',
'medical_prescriptions',
'lab_reports',
'treatment_administrations',
'care_round_observations',
'animal_photos',
'medical_photos',
'animal_health_conditions',
'vaccinations',
'treatments',
'medical_notes',
'measurements',
'animal_placements',
'adoptions',
'animal_movements',
'animal_deaths',
'animal_location_history',
'animal_history',
'litter_kittens',
'litters',
'bonded_group_members',
'bonded_groups',
'care_rounds',
'icad_cache',
'asm3_import_links',
'asm3_import_runs',
'directory_contact_roles',
'animals',
'directory_contacts',
];
foreach ($tables as $table) {
$db->exec('DELETE FROM ' . $table);
}
return $before;
}
public static function clearMedia(): void
{
foreach (
[dirname(__DIR__, 2) . '/public/media/animals', dirname(__DIR__, 2) . '/data/medical-documents']
as $root
) {
if (!is_dir($root)) {
continue;
}
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST,
);
foreach ($iterator as $file) {
$path = $file->getPathname();
if ($file->isLink()) {
unlink($path);
} elseif ($file->isDir()) {
rmdir($path);
} else {
unlink($path);
}
}
}
}
}

View file

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
final class AssociationBrand
{
private const MAX_BYTES = 5_000_000;
private const MIME_EXTENSIONS = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp'];
public static function path(): ?string
{
$files = glob(self::directory() . '/logo.*') ?: [];
foreach ($files as $file) {
if (is_file($file)) {
return $file;
}
}
return null;
}
public static function store(array $upload): void
{
$error = (int) ($upload['error'] ?? UPLOAD_ERR_NO_FILE);
if ($error === UPLOAD_ERR_NO_FILE) {
return;
}
if ($error !== UPLOAD_ERR_OK || !is_uploaded_file((string) ($upload['tmp_name'] ?? ''))) {
throw new RuntimeException(t('service.logo.upload_failed'));
}
if ((int) ($upload['size'] ?? 0) > self::MAX_BYTES) {
throw new RuntimeException(t('service.logo.too_large'));
}
$tmp = (string) $upload['tmp_name'];
$mime = new finfo(FILEINFO_MIME_TYPE)->file($tmp);
$extension = self::MIME_EXTENSIONS[$mime] ?? null;
if (!$extension) {
throw new RuntimeException(t('service.logo.format'));
}
$dimensions = @getimagesize($tmp);
if (!$dimensions || $dimensions[0] * $dimensions[1] > 40_000_000) {
throw new RuntimeException(t('service.logo.dimensions'));
}
$dir = self::directory();
$stored = ImageService::storeUploaded($tmp, $dir, 'association', 'logo');
$target = $dir . '/logo.' . $stored['extension'];
foreach (glob($dir . '/logo.*') ?: [] as $old) {
if ($old !== $stored['path']) {
@unlink($old);
}
}
if (!rename($stored['path'], $target)) {
@unlink($stored['path']);
throw new RuntimeException(t('service.logo.finalize_failed'));
}
}
public static function delete(): void
{
foreach (glob(self::directory() . '/logo.*') ?: [] as $file) {
if (is_file($file)) {
@unlink($file);
}
}
}
private static function directory(): string
{
return dirname(__DIR__, 2) . '/data/association';
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
final class AuditService
{
public static function log(
string $action,
string $path,
?string $summary = null,
?string $entityType = null,
?int $entityId = null,
array $metadata = [],
): void {
$safe = [];
foreach ($metadata as $key => $value) {
if (in_array(strtolower((string) $key), ['password', 'password_confirm', 'csrf'], true)) {
continue;
}
if (is_scalar($value) || $value === null) {
$safe[$key] = $value;
}
}
DB::pdo()
->prepare(
'INSERT INTO audit_log(user_id,action,method,path,entity_type,entity_id,summary,metadata,ip_address) VALUES(:user,:action,:method,:path,:type,:entity,:summary,:meta,:ip)',
)
->execute([
':user' => Auth::id(),
':action' => $action,
':method' => $_SERVER['REQUEST_METHOD'] ?? 'CLI',
':path' => $path,
':type' => $entityType,
':entity' => $entityId,
':summary' => $summary,
':meta' => $safe ? json_encode($safe, JSON_UNESCAPED_UNICODE) : null,
':ip' => $_SERVER['REMOTE_ADDR'] ?? null,
]);
}
}

201
app/Services/Auth.php Normal file
View file

@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
final class Auth
{
private static ?array $user = null;
public static function start(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
return;
}
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');
session_name('globinours_session');
session_set_cookie_params([
'httponly' => true,
'secure' => self::isSecureRequest(),
'samesite' => 'Strict',
'path' => '/',
]);
session_start();
$now = time();
$idle = max(300, (int) (getenv('GLOBINOURS_SESSION_IDLE') ?: 1800));
$absolute = max($idle, (int) (getenv('GLOBINOURS_SESSION_ABSOLUTE') ?: 43200));
if (
!empty($_SESSION['user_id']) &&
((isset($_SESSION['last_activity']) && $now - (int) $_SESSION['last_activity'] > $idle) ||
(isset($_SESSION['authenticated_at']) && $now - (int) $_SESSION['authenticated_at'] > $absolute))
) {
self::logout(false);
session_regenerate_id(true);
}
if (
empty($_SESSION['user_id']) &&
class_exists(TrustedDeviceService::class) &&
($id = TrustedDeviceService::authenticate())
) {
session_regenerate_id(true);
$_SESSION['user_id'] = $id;
$_SESSION['authenticated_at'] = $now;
}
if (!empty($_SESSION['user_id'])) {
$_SESSION['last_activity'] = $now;
}
}
public static function countUsers(): int
{
return (int) DB::pdo()->query('SELECT COUNT(*) FROM users')->fetchColumn();
}
public static function user(): ?array
{
if (self::$user !== null) {
return self::$user;
}
$id = (int) ($_SESSION['user_id'] ?? 0);
if (!$id) {
return null;
}
$s = DB::pdo()->prepare(
'SELECT id,username,display_name,role,active,last_login_at,animal_list_view,agenda_view FROM users WHERE id=:id AND active=1',
);
$s->execute([':id' => $id]);
$u = $s->fetch(PDO::FETCH_ASSOC);
if (!$u) {
self::logout(false);
return null;
}
return self::$user = $u;
}
public static function id(): ?int
{
return ($u = self::user()) ? (int) $u['id'] : null;
}
public static function login(
string $username,
string $password,
bool $remember = false,
string $deviceName = '',
): bool {
$db = DB::pdo();
$username = trim($username);
$ip = mb_substr((string) ($_SERVER['REMOTE_ADDR'] ?? ''), 0, 64);
$db->exec("DELETE FROM login_attempts WHERE attempted_at<datetime('now','-7 days')");
$rate = $db->prepare(
"SELECT COUNT(*) FROM login_attempts WHERE succeeded=0 AND ip_address=? AND attempted_at>=datetime('now','-15 minutes')",
);
$rate->execute([$ip ?: null]);
if ((int) $rate->fetchColumn() >= 20) {
self::recordAttempt($username, $ip, false);
return false;
}
$s = $db->prepare('SELECT * FROM users WHERE lower(username)=lower(:u) LIMIT 1');
$s->execute([':u' => $username]);
$u = $s->fetch(PDO::FETCH_ASSOC);
$valid =
$u &&
(int) $u['active'] === 1 &&
(empty($u['locked_until']) || strtotime($u['locked_until']) <= time()) &&
password_verify($password, (string) $u['password_hash']);
if (!$u) {
password_verify($password, '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.');
}
if (!$valid) {
if ($u) {
$failed = (int) $u['failed_attempts'] + 1;
$lock = $failed >= 5 ? date('Y-m-d H:i:s', time() + 900) : null;
$db->prepare('UPDATE users SET failed_attempts=:f,locked_until=:l WHERE id=:id')->execute([
':f' => $failed,
':l' => $lock,
':id' => $u['id'],
]);
}
self::recordAttempt($username, $ip, false);
return false;
}
session_regenerate_id(true);
$_SESSION['user_id'] = (int) $u['id'];
$_SESSION['authenticated_at'] = time();
$_SESSION['last_activity'] = time();
self::$user = null;
$db->prepare(
"UPDATE users SET failed_attempts=0,locked_until=NULL,last_login_at=datetime('now') WHERE id=:id",
)->execute([':id' => $u['id']]);
self::recordAttempt($username, $ip, true);
if ($remember && class_exists(TrustedDeviceService::class)) {
TrustedDeviceService::create((int) $u['id'], $deviceName);
}
return true;
}
public static function logout(bool $destroy = true): void
{
if ($destroy && class_exists(TrustedDeviceService::class)) {
TrustedDeviceService::revokeCurrent();
}
self::$user = null;
unset($_SESSION['user_id']);
if ($destroy) {
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$p['path'],
$p['domain'] ?? '',
(bool) $p['secure'],
(bool) $p['httponly'],
);
}
session_destroy();
}
}
public static function csrf(): string
{
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
return (string) $_SESSION['csrf'];
}
public static function validCsrf(?string $token): bool
{
return is_string($token) && hash_equals(self::csrf(), $token);
}
public static function is(string $role): bool
{
return (self::user()['role'] ?? '') === $role;
}
public static function canWrite(string $path): bool
{
$module = PermissionService::moduleForPath($path);
return $module === null || PermissionService::can($module, 'edit');
}
public static function isSecureRequest(): bool
{
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
return true;
}
if (str_starts_with(strtolower((string) getenv('APP_URL')), 'https://')) {
return true;
}
$remote = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
$trusted = array_filter(array_map('trim', explode(',', (string) getenv('GLOBINOURS_TRUSTED_PROXIES'))));
if (in_array($remote, ['127.0.0.1', '::1'], true) || in_array($remote, $trusted, true)) {
return strtolower(trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''))[0] ?? '')) ===
'https';
}
return false;
}
private static function recordAttempt(string $username, string $ip, bool $success): void
{
try {
DB::pdo()
->prepare('INSERT INTO login_attempts(username_hash,ip_address,succeeded) VALUES(?,?,?)')
->execute([hash('sha256', mb_strtolower($username)), $ip ?: null, $success ? 1 : 0]);
} catch (Throwable) {
}
}
}

View file

@ -0,0 +1,467 @@
<?php
declare(strict_types=1);
final class BackupService
{
private const FORMAT_VERSION = 1;
public static function create(string $reason = 'manual'): array
{
if (!class_exists(ZipArchive::class)) {
throw new RuntimeException(t('service.backup.zip_missing'));
}
$root = dirname(__DIR__, 2);
$backupDir = $root . '/storage/backups';
if (!is_dir($backupDir) && !mkdir($backupDir, 0775, true) && !is_dir($backupDir)) {
throw new RuntimeException(t('service.backup.directory_failed'));
}
$stamp = new DateTimeImmutable('now', new DateTimeZone('Europe/Paris'))->format('Ymd-His');
$suffix = $reason === 'pre-restore' ? '-avant-restauration' : '';
$target = $backupDir . '/globinours-' . $stamp . $suffix . '.zip';
// Certains volumes synchronisés acceptent les ZIP mais SQLite ne peut pas
// y créer de base avec VACUUM INTO. Le snapshot transitoire appartient au
// répertoire temporaire système ; seule l'archive finale va dans backups/.
$snapshot = tempnam(sys_get_temp_dir(), 'globinours-snapshot-');
if ($snapshot === false) {
throw new RuntimeException(t('service.backup.prepare_failed'));
}
@unlink($snapshot); // VACUUM INTO exige que la destination n'existe pas.
$pdo = DB::pdo();
$pdo->exec('PRAGMA wal_checkpoint(FULL)');
$pdo->exec('VACUUM INTO ' . $pdo->quote($snapshot));
$zip = new ZipArchive();
if ($zip->open($target, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
@unlink($snapshot);
throw new RuntimeException(t('service.backup.create_failed'));
}
$files = [];
try {
self::addFile($zip, $snapshot, 'database/refuge.sqlite', $files);
if (getenv('GLOBINOURS_BACKUP_DATA_ONLY') !== '1') {
self::addTree($zip, $root . '/public/media', 'public/media', $files);
self::addTree($zip, $root . '/data/association', 'data/association', $files);
self::addTree($zip, $root . '/data/grants', 'data/grants', $files);
self::addTree($zip, $root . '/data/medical-documents', 'data/medical-documents', $files);
self::addTree($zip, $root . '/data/private-media', 'data/private-media', $files);
}
$manifest = [
'application' => 'Globinours',
'format_version' => self::FORMAT_VERSION,
'created_at' => new DateTimeImmutable('now', new DateTimeZone('Europe/Paris'))->format(
DateTimeInterface::ATOM,
),
'reason' => $reason,
'php_version' => PHP_VERSION,
'files' => $files,
];
$zip->addFromString(
'manifest.json',
json_encode(
$manifest,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR,
),
);
} finally {
$zip->close();
@unlink($snapshot);
}
@chmod($target, 0600);
self::prune($backupDir);
return self::describe($target);
}
public static function list(): array
{
$dir = dirname(__DIR__, 2) . '/storage/backups';
$files = glob($dir . '/globinours-*.zip') ?: [];
usort($files, static fn(string $a, string $b): int => filemtime($b) <=> filemtime($a));
return array_map([self::class, 'describe'], $files);
}
public static function path(string $name): ?string
{
if (
$name !== basename($name) ||
!preg_match('/^globinours-[0-9]{8}-[0-9]{6}(?:-avant-restauration)?\.zip$/', $name)
) {
return null;
}
$path = dirname(__DIR__, 2) . '/storage/backups/' . $name;
return is_file($path) ? $path : null;
}
public static function delete(string $name): void
{
$path = self::path($name);
if (!$path) {
throw new RuntimeException(t('service.backup.not_found'));
}
if (!unlink($path)) {
throw new RuntimeException(t('service.backup.delete_failed'));
}
}
public static function verify(string $name): array
{
$path = self::path($name);
if (!$path) {
throw new RuntimeException(t('service.backup.not_found'));
}
$zip = new ZipArchive();
if ($zip->open($path) !== true) {
throw new RuntimeException(t('service.backup.unreadable'));
}
try {
$raw = $zip->getFromName('manifest.json');
if ($raw === false) {
throw new RuntimeException(t('service.backup.manifest_missing'));
}
$manifest = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if (
($manifest['application'] ?? '') !== 'Globinours' ||
(int) ($manifest['format_version'] ?? 0) !== self::FORMAT_VERSION
) {
throw new RuntimeException(t('service.backup.incompatible'));
}
foreach ($manifest['files'] ?? [] as $file => $meta) {
$stream = $zip->getStream((string) $file);
if (!$stream) {
throw new RuntimeException(t('service.backup.file_altered', ['name' => $file]));
}
$context = hash_init('sha256');
hash_update_stream($context, $stream);
fclose($stream);
if (!hash_equals((string) ($meta['sha256'] ?? ''), hash_final($context))) {
throw new RuntimeException(t('service.backup.file_altered', ['name' => $file]));
}
}
$tmp = tempnam(sys_get_temp_dir(), 'globinours-verify-');
if ($tmp === false) {
throw new RuntimeException(t('service.backup.prepare_failed'));
}
$dbBytes = $zip->getFromName('database/refuge.sqlite');
if ($dbBytes === false) {
@unlink($tmp);
throw new RuntimeException(t('service.backup.database_missing'));
}
file_put_contents($tmp, $dbBytes);
self::validateDatabase($tmp);
@unlink($tmp);
return [
'valid' => true,
'name' => $name,
'created_at' => (string) ($manifest['created_at'] ?? ''),
'files' => count($manifest['files'] ?? []),
];
} finally {
$zip->close();
}
}
public static function runScheduled(bool $force = false): array
{
if (AppSettings::get('backup_schedule_enabled') !== '1' && !$force) {
return ['created' => false, 'reason' => 'disabled'];
}
$frequency = AppSettings::get('backup_schedule_frequency');
$last = AppSettings::get('backup_last_run_at');
$minimum = $frequency === 'weekly' ? 6 * 86400 : 20 * 3600;
if (!$force && $last !== '' && time() - (strtotime($last) ?: 0) < $minimum) {
return ['created' => false, 'reason' => 'not_due'];
}
$backup = self::create('scheduled');
$verification = self::verify($backup['name']);
AppSettings::save(
['backup_last_run_at' => date('Y-m-d H:i:s'), 'backup_last_verified_at' => date('Y-m-d H:i:s')],
null,
);
return ['created' => true, 'backup' => $backup, 'verification' => $verification];
}
public static function restore(string $uploadedPath): array
{
if (!is_file($uploadedPath)) {
throw new RuntimeException(t('service.backup.restore_missing'));
}
$root = dirname(__DIR__, 2);
$stage = $root . '/storage/restore-stage-' . bin2hex(random_bytes(6));
if (!mkdir($stage, 0700, true)) {
throw new RuntimeException(t('service.backup.prepare_failed'));
}
$zip = new ZipArchive();
if ($zip->open($uploadedPath) !== true) {
self::removeTree($stage);
throw new RuntimeException(t('service.backup.unreadable'));
}
try {
if ($zip->numFiles > 10000) {
throw new RuntimeException(t('service.backup.too_many_files'));
}
$total = 0;
$seen = [];
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
$name = (string) ($stat['name'] ?? '');
if (isset($seen[$name])) {
throw new RuntimeException(t('service.backup.unsafe_path'));
}
$seen[$name] = true;
$total += (int) ($stat['size'] ?? 0);
if ($total > 2_000_000_000) {
throw new RuntimeException(t('service.backup.too_large'));
}
if (
$name === '' ||
str_contains($name, "\0") ||
str_starts_with($name, '/') ||
preg_match('#(^|/)\.\.(/|$)#', $name)
) {
throw new RuntimeException(t('service.backup.unsafe_path'));
}
}
$manifestRaw = $zip->getFromName('manifest.json');
if ($manifestRaw === false) {
throw new RuntimeException(t('service.backup.manifest_missing'));
}
$manifest = json_decode($manifestRaw, true, 512, JSON_THROW_ON_ERROR);
if (
($manifest['application'] ?? '') !== 'Globinours' ||
(int) ($manifest['format_version'] ?? 0) !== self::FORMAT_VERSION
) {
throw new RuntimeException(t('service.backup.incompatible'));
}
$manifestFiles = array_keys(is_array($manifest['files'] ?? null) ? $manifest['files'] : []);
$allowed = array_fill_keys(array_merge(['manifest.json'], $manifestFiles), true);
for ($i = 0; $i < $zip->numFiles; $i++) {
$stat = $zip->statIndex($i);
$name = (string) ($stat['name'] ?? '');
if (str_ends_with($name, '/')) {
continue;
}
if (!isset($allowed[$name])) {
throw new RuntimeException(t('service.backup.manifest_path'));
}
if (method_exists($zip, 'getExternalAttributesIndex')) {
$opsys = 0;
$attr = 0;
if ($zip->getExternalAttributesIndex($i, $opsys, $attr) && (($attr >> 16) & 0170000) === 0120000) {
throw new RuntimeException(t('service.backup.unsafe_path'));
}
}
}
$written = 0;
foreach ($manifestFiles as $name) {
$source = $zip->getStream($name);
if (!$source) {
throw new RuntimeException(t('service.backup.extract_failed'));
}
$target = $stage . '/' . $name;
$dir = dirname($target);
if (!is_dir($dir) && !mkdir($dir, 0700, true) && !is_dir($dir)) {
fclose($source);
throw new RuntimeException(t('service.backup.extract_failed'));
}
$dest = fopen($target, 'xb');
if (!$dest) {
fclose($source);
throw new RuntimeException(t('service.backup.extract_failed'));
}
while (!feof($source)) {
$chunk = fread($source, 1048576);
if ($chunk === false) {
fclose($source);
fclose($dest);
throw new RuntimeException(t('service.backup.extract_failed'));
}
$written += strlen($chunk);
if ($written > 2_000_000_000) {
fclose($source);
fclose($dest);
throw new RuntimeException(t('service.backup.too_large'));
}
fwrite($dest, $chunk);
}
fclose($source);
fclose($dest);
@chmod($target, 0600);
}
} finally {
$zip->close();
}
try {
foreach ($manifest['files'] ?? [] as $name => $metadata) {
if (
!is_string($name) ||
!preg_match(
'#^(database/refuge\.sqlite|public/media/.+|data/grants/.+|data/medical-documents/.+|data/private-media/.+|data/documents/.+|data/association/logo\.(?:png|jpg|webp)|data/(?:Logo_Globinours_64\.png|Logo_Globinours_maxi\.png|favicon\.ico))$#',
$name,
)
) {
throw new RuntimeException(t('service.backup.manifest_path'));
}
$restored = $stage . '/' . $name;
$hash = (string) ($metadata['sha256'] ?? '');
if (!is_file($restored) || $hash === '' || !hash_equals($hash, hash_file('sha256', $restored))) {
throw new RuntimeException(t('service.backup.file_altered', ['name' => $name]));
}
}
$database = $stage . '/database/refuge.sqlite';
if (!is_file($database)) {
throw new RuntimeException(t('service.backup.database_missing'));
}
$expected = $manifest['files']['database/refuge.sqlite']['sha256'] ?? '';
if ($expected === '' || !hash_equals($expected, hash_file('sha256', $database))) {
throw new RuntimeException(t('service.backup.database_hash'));
}
self::validateDatabase($database);
$emergency = self::create('pre-restore');
self::replaceInstallation($stage, $root);
return ['emergency' => $emergency, 'created_at' => (string) ($manifest['created_at'] ?? '')];
} finally {
self::removeTree($stage);
}
}
private static function validateDatabase(string $path): void
{
$db = new SQLite3($path, SQLITE3_OPEN_READONLY);
try {
if ($db->querySingle('PRAGMA integrity_check') !== 'ok') {
throw new RuntimeException(t('service.backup.database_corrupt'));
}
foreach (['animals', 'users', 'animal_history'] as $table) {
$safe = SQLite3::escapeString($table);
if (!(int) $db->querySingle("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='$safe'")) {
throw new RuntimeException(t('service.backup.table_missing', ['table' => $table]));
}
}
} finally {
$db->close();
}
}
private static function replaceInstallation(string $stage, string $root): void
{
$rollback = $root . '/storage/restore-rollback-' . bin2hex(random_bytes(5));
mkdir($rollback, 0700, true);
$targets = ['public/media', 'data/association', 'data/grants', 'data/medical-documents', 'data/private-media'];
$moved = [];
try {
foreach ($targets as $relative) {
$live = $root . '/' . $relative;
$saved = $rollback . '/' . str_replace('/', '__', $relative);
$incoming = $stage . '/' . $relative;
if (is_dir($live) && !rename($live, $saved)) {
throw new RuntimeException(t('service.backup.secure_failed', ['path' => $relative]));
}
if (is_dir($saved)) {
$moved[$relative] = $saved;
}
if (is_dir($incoming) && !rename($incoming, $live)) {
throw new RuntimeException(t('service.backup.restore_path_failed', ['path' => $relative]));
}
if (!is_dir($live)) {
mkdir($live, 0775, true);
}
}
$pdo = DB::pdo();
$pdo->exec('PRAGMA wal_checkpoint(TRUNCATE)');
unset($pdo);
DB::close();
foreach (['-wal', '-shm'] as $suffix) {
@unlink($root . '/data/refuge.sqlite' . $suffix);
}
if (!rename($root . '/data/refuge.sqlite', $rollback . '/refuge.sqlite')) {
throw new RuntimeException(t('service.backup.secure_database_failed'));
}
if (!copy($stage . '/database/refuge.sqlite', $root . '/data/refuge.sqlite')) {
throw new RuntimeException(t('service.backup.restore_database_failed'));
}
@chmod($root . '/data/refuge.sqlite', 0600);
self::removeTree($rollback);
} catch (Throwable $e) {
DB::close();
if (is_file($rollback . '/refuge.sqlite')) {
@unlink($root . '/data/refuge.sqlite');
@rename($rollback . '/refuge.sqlite', $root . '/data/refuge.sqlite');
}
foreach ($targets as $relative) {
$live = $root . '/' . $relative;
$saved = $rollback . '/' . str_replace('/', '__', $relative);
if (is_dir($saved)) {
self::removeTree($live);
@rename($saved, $live);
}
}
self::removeTree($rollback);
throw $e;
}
}
private static function addTree(ZipArchive $zip, string $dir, string $prefix, array &$files): void
{
if (!is_dir($dir)) {
return;
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
foreach ($iterator as $file) {
if ($file->isFile() && !$file->isLink()) {
self::addFile(
$zip,
$file->getPathname(),
$prefix . '/' . substr($file->getPathname(), strlen($dir) + 1),
$files,
);
}
}
}
private static function addFile(ZipArchive $zip, string $source, string $name, array &$files): void
{
if (!is_file($source)) {
return;
}
$name = str_replace('\\', '/', $name);
if (!$zip->addFile($source, $name)) {
throw new RuntimeException(t('service.backup.add_failed', ['name' => $name]));
}
$files[$name] = ['size' => filesize($source), 'sha256' => hash_file('sha256', $source)];
}
private static function describe(string $path): array
{
$modified = new DateTimeImmutable('@' . (filemtime($path) ?: time()))->setTimezone(
new DateTimeZone('Europe/Paris'),
);
return ['name' => basename($path), 'size' => filesize($path) ?: 0, 'date' => $modified->format('d/m/Y H:i:s')];
}
private static function prune(string $dir): void
{
$files = glob($dir . '/globinours-*.zip') ?: [];
usort($files, static fn($a, $b) => filemtime($b) <=> filemtime($a));
$keep = class_exists(AppSettings::class) ? AppSettings::int('backup_retention', 1, 50) : 10;
foreach (array_slice($files, $keep) as $file) {
@unlink($file);
}
}
private static function removeTree(string $dir): void
{
if (!is_dir($dir)) {
return;
}
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST,
);
foreach ($it as $item) {
$item->isDir() ? @rmdir($item->getPathname()) : @unlink($item->getPathname());
}
@rmdir($dir);
}
}

View file

@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
final class CalendarFeedService
{
public static function generateToken(int $userId): string
{
$token = bin2hex(random_bytes(32));
DB::pdo()
->prepare(
"UPDATE users SET agenda_feed_token_hash=:hash,agenda_feed_created_at=datetime('now'),updated_at=datetime('now') WHERE id=:id AND active=1",
)
->execute([':hash' => hash('sha256', $token), ':id' => $userId]);
return $token;
}
public static function revoke(int $userId): void
{
DB::pdo()
->prepare(
"UPDATE users SET agenda_feed_token_hash=NULL,agenda_feed_created_at=NULL,updated_at=datetime('now') WHERE id=?",
)
->execute([$userId]);
}
public static function userForToken(string $token): ?array
{
if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
return null;
}
$s = DB::pdo()->prepare('SELECT id,role FROM users WHERE agenda_feed_token_hash=? AND active=1 LIMIT 1');
$s->execute([hash('sha256', $token)]);
$user = $s->fetch(PDO::FETCH_ASSOC) ?: null;
if (!$user || !PermissionService::can('agenda', 'view', (string) $user['role'])) {
return null;
}
return $user;
}
public static function absoluteUrl(string $path): string
{
$configured = rtrim((string) getenv('APP_URL'), '/');
if ($configured !== '' && preg_match('~^https?://~i', $configured)) {
return $configured . $path;
}
$proto = (string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '');
if (!in_array($proto, ['http', 'https'], true)) {
$proto = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
}
$host = (string) ($_SERVER['HTTP_X_FORWARDED_HOST'] ?? ($_SERVER['HTTP_HOST'] ?? 'localhost'));
$host = trim(explode(',', $host)[0]);
if (!preg_match('/^[a-z0-9.:-]+$/i', $host)) {
$host = 'localhost';
}
return $proto . '://' . $host . $path;
}
public static function render(array $items, string $name): string
{
$lines = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//Globinours//Agenda refuge//FR',
'CALSCALE:GREGORIAN',
'METHOD:PUBLISH',
'X-WR-CALNAME:' . self::escape($name),
'X-WR-TIMEZONE:Europe/Paris',
];
$stamp = gmdate('Ymd\THis\Z');
foreach ($items as $item) {
$source = (string) ($item['source_type'] ?? 'agenda');
$sourceId = (int) ($item['source_id'] ?? $item['id']);
$instance = (string) $item['instance_starts_at'];
$uid = $source . '-' . $sourceId . '-' . substr(hash('sha256', $instance), 0, 12) . '@globinours';
$lines[] = 'BEGIN:VEVENT';
$lines[] = 'UID:' . $uid;
$lines[] = 'DTSTAMP:' . $stamp;
if ((int) $item['all_day'] === 1) {
$start = new DateTimeImmutable(substr($instance, 0, 10));
$lines[] = 'DTSTART;VALUE=DATE:' . $start->format('Ymd');
$lines[] = 'DTEND;VALUE=DATE:' . $start->modify('+1 day')->format('Ymd');
} else {
$start = new DateTimeImmutable($instance, new DateTimeZone('Europe/Paris'));
$end = !empty($item['instance_ends_at'])
? new DateTimeImmutable($item['instance_ends_at'], new DateTimeZone('Europe/Paris'))
: $start->modify('+1 hour');
$lines[] = 'DTSTART;TZID=Europe/Paris:' . $start->format('Ymd\THis');
$lines[] = 'DTEND;TZID=Europe/Paris:' . $end->format('Ymd\THis');
}
$lines[] = 'SUMMARY:' . self::escape((string) $item['title']);
$description = trim((string) ($item['description'] ?? ''));
if (!empty($item['animal_name'])) {
$description = trim($description . "\n" . t('animal.animal') . ' : ' . $item['animal_name']);
}
if ($description !== '') {
$lines[] = 'DESCRIPTION:' . self::escape($description);
}
if (!empty($item['location'])) {
$lines[] = 'LOCATION:' . self::escape((string) $item['location']);
}
if (!empty($item['animal_id'])) {
$lines[] = 'URL:' . self::escape(self::absoluteUrl('/animal?id=' . (int) $item['animal_id']));
}
$lines[] = 'STATUS:' . (($item['status'] ?? 'planned') === 'completed' ? 'COMPLETED' : 'CONFIRMED');
$lines[] = 'END:VEVENT';
}
$lines[] = 'END:VCALENDAR';
return implode("\r\n", array_map([self::class, 'fold'], $lines)) . "\r\n";
}
private static function escape(string $value): string
{
return str_replace(['\\', "\r\n", "\n", "\r", ';', ','], ['\\\\', '\\n', '\\n', '\\n', '\\;', '\\,'], $value);
}
private static function fold(string $line): string
{
$out = '';
while (strlen($line) > 73) {
$cut = 73;
while ($cut > 0 && (ord($line[$cut]) & 0xc0) === 0x80) {
$cut--;
}
$out .= substr($line, 0, $cut) . "\r\n ";
$line = substr($line, $cut);
}
return $out . $line;
}
}

41
app/Services/DB.php Normal file
View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
final class DB
{
private static ?PDO $pdo = null;
public static function pdo(): PDO
{
if (self::$pdo instanceof PDO) {
return self::$pdo;
}
$dbPath = getenv('GLOBINOURS_DB_PATH') ?: __DIR__ . '/../../data/refuge.sqlite';
$dir = dirname($dbPath);
if (!is_dir($dir)) {
mkdir($dir, 0775, true);
}
$pdo = new PDO('sqlite:' . $dbPath, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$pdo->exec('PRAGMA foreign_keys = ON;');
$pdo->exec('PRAGMA journal_mode = WAL;');
$pdo->exec('PRAGMA busy_timeout = 3000;');
@chmod($dbPath, 0600);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
self::$pdo = $pdo;
return $pdo;
}
public static function close(): void
{
self::$pdo = null;
}
}

View file

@ -0,0 +1,536 @@
<?php
declare(strict_types=1);
final class DemoDataService
{
private const TABLES = [
'agenda_volunteers',
'agenda_items',
'prescription_treatments',
'lab_results',
'medical_prescriptions',
'lab_reports',
'treatment_administrations',
'care_round_observations',
'care_rounds',
'medical_photos',
'animal_photos',
'animal_expenses',
'animal_surgeries',
'animal_health_conditions',
'dewormings',
'vaccinations',
'treatments',
'medical_notes',
'measurements',
'animal_placements',
'adoptions',
'animal_movements',
'animal_deaths',
'animal_location_history',
'animal_history',
'litter_kittens',
'litters',
'bonded_group_members',
'bonded_groups',
'icad_cache',
'asm3_import_links',
'asm3_import_runs',
'asm3_import_jobs',
'directory_contact_roles',
'animals',
'directory_contacts',
'grant_documents',
'grant_applications',
'grant_years',
'care_room_layouts',
'clinics',
'geocode_cache',
'audit_log',
];
public static function reset(PDO $db): array
{
$before = [
'animals' => (int) $db->query('SELECT COUNT(*) FROM animals')->fetchColumn(),
'contacts' => (int) $db->query('SELECT COUNT(*) FROM directory_contacts')->fetchColumn(),
];
$sequence = $db->prepare('DELETE FROM sqlite_sequence WHERE name=?');
$exists = $db->prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?");
foreach (self::TABLES as $table) {
$exists->execute([$table]);
if (!$exists->fetchColumn()) {
continue;
}
$db->exec('DELETE FROM ' . $table);
$sequence->execute([$table]);
}
return $before;
}
public static function seed(PDO $db, ?int $userId): array
{
$contacts = [
'fa' => [
'person',
'Alice Martin',
'06 00 00 00 01',
'alice.demo@example.org',
'12 rue des Lilas',
'29260',
'Lesneven',
],
'adopter' => [
'person',
'Marc Durand',
'06 00 00 00 02',
'marc.demo@example.org',
'8 rue du Port',
'29200',
'Brest',
],
'depositor' => [
'person',
'Sophie Le Gall',
'06 00 00 00 03',
'sophie.demo@example.org',
'4 place du Marché',
'29000',
'Ville fictive',
],
'vet' => [
'person',
'Dr Camille Morel',
'02 00 00 00 04',
'veterinaire.demo@example.org',
'2 avenue des Chats',
'29260',
'Lesneven',
],
'clinic' => [
'organization',
'Clinique vétérinaire Démo',
'02 00 00 00 05',
'clinique.demo@example.org',
'2 avenue des Chats',
'29260',
'Lesneven',
],
'crematorium' => [
'organization',
'Crématorium animalier Démo',
'02 00 00 00 06',
'crematorium.demo@example.org',
'1 route du Souvenir',
'29400',
'Landivisiau',
],
];
$contactIds = [];
$insert = $db->prepare(
'INSERT INTO directory_contacts(kind,name,phone,email,address,postal_code,city,notes) VALUES(?,?,?,?,?,?,?,?)',
);
$role = $db->prepare('INSERT INTO directory_contact_roles(contact_id,role) VALUES(?,?)');
foreach ($contacts as $key => $c) {
$insert->execute([...$c, 'Donnée fictive de démonstration']);
$contactIds[$key] = (int) $db->lastInsertId();
$roleName = match ($key) {
'adopter' => 'adoptant',
'vet' => 'veterinaire',
'clinic' => 'cabinet',
'crematorium' => 'crematorium',
'depositor' => 'deposant',
default => 'fa',
};
$role->execute([$contactIds[$key], $roleName]);
}
$animals = [
[
'DEMO-001',
'Moka',
'F',
'2019-05-14',
'refuge',
'silver',
'Bicolore Noir / Blanc',
'yes',
'yes',
'yes',
'yes',
'yes',
'available',
],
[
'DEMO-002',
'Pixel',
'M',
'2021-09-03',
'refuge',
'twix',
'Roux',
'yes',
'yes',
'yes',
'yes',
'no',
'available',
],
[
'DEMO-003',
'Twix',
'M',
'2019-04-15',
'quarantaine',
null,
'Roux',
'yes',
'yes',
'yes',
'yes',
'yes',
'not_available',
],
[
'DEMO-004',
'Nox',
'M',
'2023-02-18',
'soin',
null,
'Noir',
'no',
'yes',
'unknown',
'yes',
'no',
'not_available',
],
[
'DEMO-005',
'Caramel',
'F',
'2020-07-21',
'fa',
null,
'Écaille de tortue',
'yes',
'yes',
'yes',
'yes',
'yes',
'available',
],
[
'DEMO-006',
'Plume',
'F',
'2022-04-08',
'refuge',
'silver',
'Tricolore / Calico',
'yes',
'yes',
'yes',
'yes',
'yes',
'available',
],
[
'DEMO-007',
'Plume-Bébé-1',
'F',
date('Y-m-d', strtotime('-4 months')),
'refuge',
'silver',
'Bicolore Gris / Blanc',
'unknown',
'yes',
'unknown',
'unknown',
'unknown',
'not_available',
],
[
'DEMO-008',
'Plume-Bébé-2',
'M',
date('Y-m-d', strtotime('-4 months')),
'refuge',
'silver',
'Gris',
'unknown',
'yes',
'unknown',
'unknown',
'unknown',
'not_available',
],
[
'DEMO-009',
'Plume-Bébé-3',
'U',
date('Y-m-d', strtotime('-4 months')),
'refuge',
'silver',
'Tigré / Tabby',
'unknown',
'yes',
'unknown',
'unknown',
'unknown',
'not_available',
],
[
'DEMO-010',
'Lune',
'F',
'2021-01-12',
'refuge',
'twix',
'Blanc',
'yes',
'no',
'yes',
'yes',
'yes',
'available',
],
[
'DEMO-011',
'Soleil',
'M',
'2021-01-12',
'refuge',
'twix',
'Roux',
'yes',
'no',
'yes',
'yes',
'yes',
'available',
],
[
'DEMO-012',
'Étoile',
'F',
'2012-06-01',
'decede',
null,
'Noir',
'yes',
'unknown',
'unknown',
'unknown',
'unknown',
'not_available',
],
];
$animalIds = [];
$animal = $db->prepare(
"INSERT INTO animals(internal_code,name,species,sex,birth_date,status,refuge_room,care_box_key,color,sterilized,sterilization_status,compatibility_cats,compatibility_dogs,compatibility_children,house_trained,adoption_availability,intake_date,intake_type,intake_reason,rescue_location_name,current_address,chip_id,identification_type,identification_registration_status,archived_at,notes) VALUES(:code,:name,'chat',:sex,:birth,:status,:room,:box,:color,:sterilized,:sterilization,:cats,:dogs,:children,:clean,:availability,date('now','-'||:days||' days'),'found','stray_found','Commune fictive','5 rue de la Démonstration, 29260 Lesneven',:chip,:identification,:registration,:archived,'Donnée fictive de démonstration')",
);
foreach ($animals as $i => $a) {
[
$code,
$name,
$sex,
$birth,
$status,
$room,
$color,
$sterilization,
$cats,
$dogs,
$children,
$clean,
$availability,
] = $a;
$sterilized = $sterilization === 'yes' ? 1 : 0;
$chip = $i < 6 ? '250269900' . str_pad((string) ($i + 1), 6, '0', STR_PAD_LEFT) : null;
$animal->execute([
':code' => $code,
':name' => $name,
':sex' => $sex,
':birth' => $birth,
':status' => $status,
':room' => $room,
':box' => $status === 'soin' ? 'care-top-1' : null,
':color' => $color,
':sterilized' => $sterilized,
':sterilization' => $sterilization,
':cats' => $cats,
':dogs' => $dogs,
':children' => $children,
':clean' => $clean,
':availability' => $availability,
':days' => 90 + $i * 12,
':chip' => $chip,
':identification' => $chip ? 'microchip' : 'unknown',
':registration' => $chip ? 'registered' : 'unknown',
':archived' => $status === 'decede' ? date('Y-m-d H:i:s') : null,
]);
$animalIds[$name] = (int) $db->lastInsertId();
}
$db->prepare('INSERT INTO litters(mother_id,birth_date,notes) VALUES(?,?,?)')->execute([
$animalIds['Plume'],
$animals[6][3],
'Portée fictive de démonstration',
]);
$litter = (int) $db->lastInsertId();
$link = $db->prepare('INSERT INTO litter_kittens(litter_id,animal_id,position) VALUES(?,?,?)');
foreach (['Plume-Bébé-1', 'Plume-Bébé-2', 'Plume-Bébé-3'] as $i => $name) {
$link->execute([$litter, $animalIds[$name], $i + 1]);
}
$db->prepare('INSERT INTO bonded_groups(name,notes) VALUES(?,?)')->execute([
'Duo Lune & Soleil',
'Chats fictifs à adopter ensemble',
]);
$group = (int) $db->lastInsertId();
$member = $db->prepare('INSERT INTO bonded_group_members(group_id,animal_id,position) VALUES(?,?,?)');
$member->execute([$group, $animalIds['Lune'], 1]);
$member->execute([$group, $animalIds['Soleil'], 2]);
$twix = $animalIds['Twix'];
$db->prepare(
"UPDATE animals SET breed='Européen',birth_is_estimated=0,fiv=0,felv=0,quarantine_until=date('now','+10 days'),intake_circumstances='Trouvé seul, bilan sanitaire programmé à l’arrivée.',depositor_contact_id=?,rescue_location_name='Commune fictive',current_address='Quarantaine — box supérieur gauche',identification_date=date('now','-2 years'),notes='Fiche vitrine entièrement fictive : elle illustre un dossier animal complet.' WHERE id=?",
)->execute([$contactIds['depositor'], $twix]);
$db->prepare(
"INSERT OR IGNORE INTO ref_medications(name,molecule,form,notes) VALUES('Doxybactin','doxycycline','comprimé','Référence de démonstration')",
)->execute();
$med = (int) $db->query("SELECT id FROM ref_medications WHERE name='Doxybactin'")->fetchColumn();
$db->prepare(
"INSERT INTO treatments(animal_id,medication_id,route,dose_text,start_date,end_date,ongoing,notes,created_by,give_morning,give_evening) VALUES(?,?,'PO','1/2 comprimé matin et soir',date('now','-2 days'),date('now','+5 days'),1,'Traitement fictif de démonstration',?,1,1)",
)->execute([$twix, $med, $userId]);
$db->prepare(
"INSERT INTO medical_notes(animal_id,noted_at,kind,reason,symptoms,exam,diagnosis,plan,weight_kg,temperature_c,created_by,vet_contact_id,clinic_contact_id) VALUES(?,datetime('now','-1 day'),'consult','Visite sanitaire d’entrée','Éternuements occasionnels','État général satisfaisant, auscultation sans anomalie','Coryza léger','Surveillance, traitement court et contrôle avant sortie de quarantaine',4.8,38.4,?,?,?)",
)->execute([$twix, $userId, $contactIds['vet'], $contactIds['clinic']]);
$weight = $db->prepare(
"INSERT INTO measurements(animal_id,type,value,unit,measured_at,notes,created_by) VALUES(?,'weight',?,'kg',datetime('now',?),'Mesure fictive',?)",
);
foreach ([[4.6, '-30 days'], [4.7, '-14 days'], [4.8, '-1 day']] as $w) {
$weight->execute([$twix, $w[0], $w[1], $userId]);
}
$db->prepare(
"INSERT OR IGNORE INTO ref_vaccines(name,notes) VALUES('TCL','Vaccin de démonstration')",
)->execute();
$vaccine = (int) $db->query("SELECT id FROM ref_vaccines WHERE name='TCL'")->fetchColumn();
$db->prepare(
"INSERT INTO vaccinations(animal_id,vaccine_id,done_date,due_date,lot,manufacturer,notes,created_by,vet_contact_id,clinic_contact_id) VALUES(?,?,date('now','-11 months'),date('now','+1 month'),'LOT-DEMO-1','Laboratoire Démo','Vaccination fictive à jour',?,?,?)",
)->execute([$twix, $vaccine, $userId, $contactIds['vet'], $contactIds['clinic']]);
$dewormer = (int) $db->query('SELECT id FROM ref_dewormers ORDER BY id LIMIT 1')->fetchColumn();
$db->prepare(
"INSERT INTO dewormings(animal_id,dewormer_id,administered_on,dose_text,weight_kg,next_due_date,notes,created_by) VALUES(?,?,date('now','-10 days'),'1 pipette',4.7,date('now','+80 days'),'Administration fictive',?)",
)->execute([$twix, $dewormer, $userId]);
$db->prepare(
"INSERT INTO animal_health_conditions(animal_id,name,status,diagnosed_at,resolved_at,notes) VALUES(?,'Gingivite légère','resolved',date('now','-6 months'),date('now','-5 months'),'Antécédent fictif résolu')",
)->execute([$twix]);
$db->prepare(
"INSERT INTO lab_reports(animal_id,sampled_on,report_type,laboratory_name,veterinarian_contact_id,clinic_contact_id,notes,created_by) VALUES(?,date('now','-1 day'),'Bilan complet','Laboratoire Démo',?,?,'Prise de sang fictive — valeurs dans les intervalles usuels',?)",
)->execute([$twix, $contactIds['vet'], $contactIds['clinic'], $userId]);
$report = (int) $db->lastInsertId();
$result = $db->prepare(
'INSERT INTO lab_results(report_id,parameter_name,value,unit,reference_min,reference_max,notes,position) VALUES(?,?,?,?,?,?,?,?)',
);
foreach (
[
['Leucocytes', 8.4, '10⁹/L', 3.5, 20.7, 10],
['Érythrocytes', 9.6, '10¹²/L', 7.7, 12.8, 20],
['Hémoglobine', 13.8, 'g/dL', 10, 17, 30],
['Hématocrite', 42.1, '%', 33.7, 55.4, 40],
['Plaquettes', 312, '10⁹/L', 125, 618, 50],
['Créatinine', 12, 'mg/L', 3, 21, 60],
['Urée', 0.42, 'g/L', 0.214, 0.642, 70],
]
as $r
) {
$result->execute([$report, $r[0], $r[1], $r[2], $r[3], $r[4], 'Résultat fictif', $r[5]]);
}
$db->prepare(
"INSERT INTO animal_photos(animal_id,filename,original_name,mime,size_bytes,is_primary,is_public,caption) VALUES(?,'twix.webp','twix.jpg','image/webp',0,1,1,'Twix — photographie de démonstration')",
)->execute([$twix]);
$db->prepare(
"INSERT INTO agenda_items(item_type,title,description,starts_at,ends_at,location,status,priority,animal_id,contact_id,reminder_minutes,created_by) VALUES('veterinary','Contrôle de sortie de quarantaine','Rendez-vous fictif : contrôle clinique et validation de la sortie.',datetime('now','+7 days','09:00'),datetime('now','+7 days','09:30'),'Clinique vétérinaire Démo','planned','high',?,?,60,?)",
)->execute([$twix, $contactIds['clinic'], $userId]);
$db->prepare(
"INSERT INTO animal_placements(animal_id,event_type,event_date,contact_id,reason,notes,created_by) VALUES(?,'foster',date('now','-30 days'),?,'Placement de démonstration','Donnée fictive',?)",
)->execute([$animalIds['Caramel'], $contactIds['fa'], $userId]);
$db->prepare(
"INSERT INTO animal_deaths(animal_id,deceased_date,cause_code,cause_details,occurred_in_care,place_type,euthanized,veterinarian_contact_id,crematorium_contact_id,body_disposition,created_by) VALUES(?,date('now','-60 days'),'old_age','Décès fictif',1,'veterinaire',1,?,?,'collective_cremation',?)",
)->execute([$animalIds['Étoile'], $contactIds['vet'], $contactIds['crematorium'], $userId]);
$history = $db->prepare(
"INSERT INTO animal_history(animal_id,action,field,new_value,user_id,created_at) VALUES(?,'created','demo','Donnée entièrement fictive',?,datetime('now'))",
);
foreach ($animalIds as $id) {
$history->execute([$id, $userId]);
}
return [
'animals' => count($animalIds),
'contacts' => count($contactIds),
'litters' => 1,
'bonded_groups' => 1,
'treatments' => 1,
'vaccinations' => 1,
'lab_reports' => 1,
'agenda_items' => 1,
'photos' => 1,
];
}
public static function clearFiles(): void
{
foreach (
[
dirname(__DIR__, 2) . '/public/media/animals',
dirname(__DIR__, 2) . '/data/grants',
dirname(__DIR__, 2) . '/data/medical-documents',
]
as $root
) {
if (!is_dir($root)) {
continue;
}
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST,
);
foreach ($it as $file) {
$path = $file->getPathname();
if ($file->isLink() || $file->isFile()) {
@unlink($path);
} elseif ($file->isDir()) {
@rmdir($path);
}
}
}
}
public static function installFiles(PDO $db): void
{
$animalId = (int) $db->query("SELECT id FROM animals WHERE internal_code='DEMO-003' LIMIT 1")->fetchColumn();
if ($animalId <= 0) {
return;
}
$source = dirname(__DIR__, 2) . '/resources/demo/twix.webp';
$directory = dirname(__DIR__, 2) . '/public/media/animals/' . $animalId;
$target = $directory . '/twix.webp';
if (!is_file($source)) {
throw new RuntimeException(t('service.image.invalid_upload'));
}
if (!is_dir($directory) && !mkdir($directory, 0755, true) && !is_dir($directory)) {
throw new RuntimeException(t('service.image.directory_failed'));
}
if (!copy($source, $target)) {
throw new RuntimeException(t('service.image.save_failed'));
}
@chmod($target, 0644);
$db->prepare("UPDATE animal_photos SET size_bytes=? WHERE animal_id=? AND filename='twix.webp'")->execute([
filesize($target),
$animalId,
]);
}
}

Some files were not shown because too many files have changed in this diff Show more