Plateforme web de commande de panier bio
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

824 lines
34 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. <?php
  2. define('DEFAULT_TITLE', 'Mon panier bio');
  3. define('SUPPLIER_REGEX', '[A-Za-z]\w{0,31}');
  4. define('EVENT_REGEX', '\d{4}\-[01]\d\-[0123]\d');
  5. define('REQUEST_REGEX', '/^https?:\/\/.+\/(?<supplier>' . SUPPLIER_REGEX . ')\/?(?<event>' . EVENT_REGEX . ')?\/?$/');
  6. define('ACTION_REGEX', '/^[a-z]{1,16}$/i');
  7. $baseUrl = trim((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], '/');
  8. if (($pos = strpos($baseUrl, '?')) !== false)
  9. $baseUrl = substr($baseUrl, 0, $pos);
  10. $requestUrl = trim(array_key_exists('QUERY_STRING', $_SERVER) ? str_replace($_SERVER['QUERY_STRING'], '', $baseUrl) : $baseUrl, '?');
  11. if (preg_match(REQUEST_REGEX, $requestUrl, $match)) {
  12. $requestSupplier = array_key_exists('supplier', $match) ? $match['supplier'] : null;
  13. $requestEvent = array_key_exists('event', $match) ? $match['event'] : null;
  14. if (!is_null($requestEvent))
  15. $requestUrl = rtrim(str_replace($requestEvent, '', $requestUrl), '/');
  16. if (!is_null($requestSupplier))
  17. $requestUrl = rtrim(str_replace($requestSupplier, '', $requestUrl), '/');
  18. } else {
  19. $requestSupplier = null;
  20. $requestEvent = null;
  21. }
  22. function ago($value) {
  23. $now = new \DateTimeImmutable('now 00:00:00');
  24. $value = (clone $value)->setTime(0, 0, 0);
  25. $diff = $now->diff($value, false);
  26. if (abs($diff->y) > 0) $output = sprintf('%d an%s', $diff->y, $diff->y > 1 ? 's' : '');
  27. elseif (abs($diff->m) > 0) $output = sprintf('%d mois', $diff->m);
  28. elseif (abs($diff->d) > 1) $output = sprintf('%d jours', $diff->d);
  29. if (isset($output)) $output = sprintf('%s %s', ($diff->invert === 1 ? 'il y a' : 'dans'), $output);
  30. elseif (abs($diff->d) > 0) $output = $diff->invert ? 'hier' : 'demain';
  31. else $output = 'aujourd\'hui';
  32. return $output;
  33. }
  34. function generatePassword($length = 20) {
  35. $chars = array_merge(
  36. range('A', 'Z'),
  37. range('a', 'z'),
  38. range('0', '9'),
  39. [ '!', '?', '~', '@', '#', '$', '%', '*', ';', ':', '-', '+', '=', ',', '.', '_' ]
  40. );
  41. while ($length-- > 0)
  42. $value .= $chars[mt_rand(0, count($chars) - 1)];
  43. return $value;
  44. }
  45. function generateUrl($supplier = null, $event = null) {
  46. global $requestUrl;
  47. if (is_null($supplier))
  48. return $requestUrl;
  49. if (is_null($event))
  50. return sprintf('%s/%s', $requestUrl, $supplier);
  51. return sprintf('%s/%s/%s', $requestUrl, $supplier, $event);
  52. }
  53. function findNext($start, $frequency, $excludes = [], $vsNow = true, $maxIterations = 1000, $direction = +1) {
  54. $now = new \DateTime('now');
  55. $current = clone $start;
  56. $frequency = \DateInterval::createFromDateString($frequency);
  57. do {
  58. if ($direction === abs($direction)) {
  59. if (!$vsNow and ($maxIterations-- > 0)) {
  60. $current->add($frequency);
  61. } else {
  62. while (
  63. ($current->getTimestamp() < $now->getTimestamp())
  64. and ($maxIterations-- > 0)
  65. ) $current->add($frequency);
  66. }
  67. } else {
  68. if (!$vsNow and ($maxIterations-- > 0)) {
  69. $current->sub($frequency);
  70. } else {
  71. while (
  72. ($current->getTimestamp() > $now->getTimestamp())
  73. and ($maxIterations-- > 0)
  74. ) $current->sub($frequency);
  75. }
  76. }
  77. $nextEvent = $current->format('Y-m-d');
  78. } while (
  79. in_array($nextEvent, $excludes)
  80. and ($maxIterations > 0)
  81. );
  82. return $current;
  83. }
  84. function findPrevious($start, $frequency, $excludes = [], $vsNow = true, $maxIterations = 1000) {
  85. return findNext($start, $frequency, $excludes, $vsNow, $maxIterations, -1);
  86. }
  87. define('CONFIG_FILE', __DIR__ . DIRECTORY_SEPARATOR . 'config.php');
  88. define('DATA_FILE', __DIR__ . DIRECTORY_SEPARATOR . 'data.php');
  89. if (file_exists(CONFIG_FILE)) require_once CONFIG_FILE;
  90. if (!isset($config)) $config = [];
  91. $action = (isset($_REQUEST['action']) and preg_match(ACTION_REGEX, $_REQUEST['action'])) ? $_REQUEST['action'] : null;
  92. $supplier = array_key_exists('supplier', $_REQUEST) ? $_REQUEST['supplier'] : $requestSupplier;
  93. $hasSupplier = is_string($supplier) and preg_match('/^' . SUPPLIER_REGEX . '$/', $supplier);
  94. $excludesFormatter = new \IntlDateFormatter('fr_FR.UTF8', \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, 'Europe/Paris');
  95. $supplierIsNew = false;
  96. if ($hasSupplier) {
  97. if (!isset($config[$supplier])) {
  98. $config[$supplier] = [];
  99. $supplierIsNew = true;
  100. }
  101. $config[$supplier] = array_merge(
  102. [
  103. 'title' => '',
  104. 'subtitle' => '<small class="text-muted text-nowrap d-block d-sm-inline">%date% (%ago%)</small>',
  105. 'description' => '',
  106. 'choices' => [],
  107. 'start' => 'now 00:00:00',
  108. 'end' => '+1 year 23:59:59',
  109. 'frequency' => '1 day',
  110. 'password' => '',
  111. 'excludes' => [],
  112. ],
  113. $config[$supplier]
  114. );
  115. $hasPassword = !empty($config[$supplier]['password']);
  116. if ($action === 'config') {
  117. if ($hasPassword) {
  118. if (!isset($_SERVER['PHP_AUTH_USER'])) {
  119. header(sprintf('WWW-Authenticate: Basic realm="Configuration de mon panier bio pour %s"', $supplier));
  120. header('HTTP/1.0 401 Unauthorized');
  121. printf('Cette configuration est protégée par mot de passe !');
  122. exit;
  123. } elseif (
  124. ($_SERVER['PHP_AUTH_USER'] !== $supplier)
  125. or ($_SERVER['PHP_AUTH_PW'] !== $config[$supplier]['password'])
  126. ) {
  127. header('HTTP/1.0 403 Forbidden');
  128. printf('Cette configuration est protégée par mot de passe !');
  129. exit;
  130. }
  131. }
  132. foreach (array_keys($config[$supplier]) as $key)
  133. if (isset($_REQUEST[$key]))
  134. $config[$supplier][$key] = (!in_array($key, ['title', 'subtitle', 'description']) ? filter_var($_REQUEST[$key], FILTER_SANITIZE_STRING) : $_REQUEST[$key]);
  135. }
  136. if (empty($config[$supplier]['start']))
  137. $config[$supplier]['start'] = 'now 00:00:00';
  138. foreach (['choices', 'excludes'] as $key) {
  139. if (is_string($config[$supplier][$key]))
  140. $config[$supplier][$key] = explode(PHP_EOL, $config[$supplier][$key]);
  141. if (!is_array($config[$supplier][$key]))
  142. $config[$supplier][$key] = [];
  143. $config[$supplier][$key] = array_filter(
  144. $config[$supplier][$key],
  145. function ($choice) {
  146. return is_string($choice) and !empty(trim($choice));
  147. }
  148. );
  149. $config[$supplier][$key] = array_map('trim', $config[$supplier][$key]);
  150. }
  151. $config[$supplier]['excludes'] = array_filter(
  152. array_map(
  153. function ($value) use ($excludesFormatter) {
  154. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value))
  155. return $value;
  156. $timestamp = $excludesFormatter->parse($value, $offset);
  157. if ($timestamp !== false)
  158. return (new \DateTimeImmutable('@' . $timestamp, new \DateTimeZone('Europe/Paris')))->format('Y-m-d');
  159. try {
  160. return (new \DateTimeImmutable($value, new \DateTimeZone('Europe/Paris')))->format('Y-m-d');
  161. } catch (\Exception $exception) {
  162. return null;
  163. }
  164. },
  165. $config[$supplier]['excludes']
  166. ),
  167. function ($value) {
  168. return !is_null($value);
  169. }
  170. );
  171. }
  172. $isConfig = false;
  173. if ($action === 'config') {
  174. $output = fopen(CONFIG_FILE, 'w+');
  175. if ($output) {
  176. if (flock($output, LOCK_EX)) {
  177. fwrite($output, '<?php' . PHP_EOL);
  178. fprintf(
  179. $output,
  180. '$config = %s;' . PHP_EOL,
  181. var_export($config, true)
  182. );
  183. flock($output, LOCK_UN);
  184. }
  185. fclose($output);
  186. }
  187. $isConfig = true;
  188. }
  189. $suppliers = array_keys($config);
  190. sort($suppliers);
  191. try {
  192. $event = array_key_exists('event', $_REQUEST) ? $_REQUEST['event'] : $requestEvent;
  193. $hasEvent = (
  194. is_string($event)
  195. and preg_match('/^' . EVENT_REGEX . '$/', $event)
  196. and ((new \DateTimeImmutable($event)) instanceof \DateTimeImmutable)
  197. );
  198. } catch (\Exception $exception) {
  199. $hasEvent = false;
  200. }
  201. if (!$isConfig and !$supplierIsNew and $hasSupplier) {
  202. $start = new \DateTime($config[$supplier]['start']);
  203. if (!$hasEvent) {
  204. $next = findNext($start, $config[$supplier]['frequency'], $config[$supplier]['excludes'], true);
  205. $nextEvent = $next->format('Y-m-d');
  206. header('Location: ' . generateUrl($supplier, $nextEvent));
  207. die();
  208. } else {
  209. $current = new \DateTime($event);
  210. $previous = findPrevious($current, $config[$supplier]['frequency'], $config[$supplier]['excludes'], false);
  211. $previousEvent = $previous->format('Y-m-d');
  212. if (false and !array_key_exists($previousEvent, $data[$supplier]))
  213. unset($previousEvent);
  214. $first = new \DateTime($config[$supplier]['start']);
  215. if (true and ($previous->getTimestamp() < $first->getTimestamp()))
  216. unset($previousEvent);
  217. $next = findNext($current, $config[$supplier]['frequency'], $config[$supplier]['excludes'], false);
  218. $nextEvent = $next->format('Y-m-d');
  219. if (false and !array_key_exists($nextEvent, $data[$supplier]))
  220. unset($nextEvent);
  221. $last = new \DateTime($config[$supplier]['end']);
  222. if (true and ($next->getTimestamp() > $last->getTimestamp()))
  223. unset($nextEvent);
  224. }
  225. switch ($action) {
  226. case 'insert' :
  227. case 'delete' :
  228. $item = [];
  229. foreach (['name', 'choice', 'action'] as $field)
  230. $item[$field] = filter_var($_REQUEST[$field], FILTER_SANITIZE_STRING);
  231. $item['timestamp'] = time();
  232. $hash = md5(implode([ $item['name'], $item['choice'], ]));
  233. $item['hash'] = $hash;
  234. $isBeginning = (!file_exists(DATA_FILE) or in_array(filesize(DATA_FILE), [ false, 0 ]));
  235. $output = fopen(DATA_FILE, 'a+');
  236. if (!$output) break;
  237. if (!flock($output, LOCK_EX)) break;
  238. if ($isBeginning)
  239. fwrite($output, '<?php' . PHP_EOL);
  240. fprintf(
  241. $output,
  242. '$data[%s][%s][] = %s;' . PHP_EOL,
  243. var_export($supplier, true),
  244. var_export($event, true),
  245. str_replace(PHP_EOL, '', var_export($item, true))
  246. );
  247. flock($output, LOCK_UN);
  248. fclose($output);
  249. header('Location: ' . generateUrl($supplier, $event));
  250. die();
  251. }
  252. if (!isset($data)) $data = [];
  253. if (file_exists(DATA_FILE)) include DATA_FILE;
  254. $items = [];
  255. $allItems = isset($data[$supplier][$event]) ? $data[$supplier][$event] : [];
  256. usort($allItems, function ($a, $b) {
  257. $a = intval($a['timestamp']);
  258. $b = intval($b['timestamp']);
  259. if ($a === $b)
  260. return 0;
  261. return ($a < $b) ? -1 : 1;
  262. });
  263. foreach ($allItems as $item) {
  264. if ($item['action'] === 'insert') {
  265. $alreadyInserted = false;
  266. foreach ($items as $index => $prevItem)
  267. if ($prevItem['hash'] === $item['hash'])
  268. $alreadyInserted = true;
  269. if (!$alreadyInserted)
  270. $items[] = $item;
  271. } elseif ($item['action'] === 'delete') {
  272. foreach ($items as $index => $prevItem)
  273. if ($prevItem['hash'] === $item['hash'])
  274. unset($items[$index]);
  275. }
  276. }
  277. $date = (new \IntlDateFormatter('fr_FR.UTF8', \IntlDateFormatter::FULL, \IntlDateFormatter::NONE, 'Europe/Paris'))->format(new \DateTime($event));
  278. $ago = ago(new \DateTimeImmutable($event));
  279. foreach (['title', 'subtitle', 'description'] as $key) {
  280. while (preg_match('/%([^%]+)%/i', $config[$supplier][$key], $match))
  281. $config[$supplier][$key] = str_replace(
  282. $match[0],
  283. ${$match[1]},
  284. $config[$supplier][$key]
  285. );
  286. }
  287. if (empty($config[$supplier]['title']))
  288. $config[$supplier]['title'] = $supplier;
  289. $stats = [];
  290. foreach ($items as $item)
  291. if (!empty($item['choice']))
  292. $stats[$item['choice']] += 1;
  293. }
  294. if ($supplierIsNew and !empty($suppliers)) {
  295. $closestSuppliers = array_filter(
  296. array_map(
  297. function ($other) use ($supplier) {
  298. return [
  299. 'supplier' => $other,
  300. 'score' => levenshtein($supplier, $other),
  301. ];
  302. },
  303. $suppliers
  304. ),
  305. function ($item) {
  306. return $item['score'] > 0;
  307. }
  308. );
  309. usort($closestSuppliers, function ($a, $b) {
  310. if ($a['score'] == $b['score']) {
  311. return 0;
  312. }
  313. return ($a['score'] < $b['score']) ? -1 : 1;
  314. });
  315. }
  316. $linkUrl = !$hasSupplier ? generateUrl() : (!$hasEvent ? generateUrl($supplier) : generateUrl($supplier, $event));
  317. ?><!DOCTYPE html>
  318. <html lang="fr">
  319. <head>
  320. <meta charset="UTF-8" />
  321. <meta name="viewport" content="width=device-width, initial-scale=1" />
  322. <title><?php if ($hasSupplier) : ?><?php echo strip_tags($config[$supplier]['title']); ?><?php if (!$isConfig) : ?> — <?php echo strip_tags($config[$supplier]['subtitle']); ?><?php endif; ?><?php else : ?><?php echo DEFAULT_TITLE; ?><?php endif; ?></title>
  323. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  324. <style type="text/css">.is-fixed { position: fixed; bottom: 0; width: 100%; box-shadow: 0 0 0.5em rgba(0, 0, 0, 0.5); }</style>
  325. <style type="text/css">.sortable th.dir-d::after{color:inherit;content:' \025BE'}.sortable th.dir-u::after{color:inherit;content:' \025B4'}</style>
  326. </head>
  327. <body>
  328. <header>
  329. <nav class="navbar navbar-dark bg-dark">
  330. <div class="container-fluid">
  331. <a class="navbar-brand" href="<?php echo $hasSupplier ? generateUrl($supplier) : generateUrl(); ?>">
  332. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-basket d-inline-block align-text-top" viewBox="0 0 16 16">
  333. <path d="M5.757 1.071a.5.5 0 0 1 .172.686L3.383 6h9.234L10.07 1.757a.5.5 0 1 1 .858-.514L13.783 6H15a1 1 0 0 1 1 1v1a1 1 0 0 1-1 1v4.5a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 1 13.5V9a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h1.217L5.07 1.243a.5.5 0 0 1 .686-.172zM2 9v4.5A1.5 1.5 0 0 0 3.5 15h9a1.5 1.5 0 0 0 1.5-1.5V9H2zM1 7v1h14V7H1zm3 3a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-1 0v-3A.5.5 0 0 1 4 10zm2 0a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-1 0v-3A.5.5 0 0 1 6 10zm2 0a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-1 0v-3A.5.5 0 0 1 8 10zm2 0a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-1 0v-3a.5.5 0 0 1 .5-.5zm2 0a.5.5 0 0 1 .5.5v3a.5.5 0 0 1-1 0v-3a.5.5 0 0 1 .5-.5z"/>
  334. </svg>
  335. <?php echo $hasSupplier ? $supplier : DEFAULT_TITLE; ?>
  336. </a>
  337. <span class="navbar-text text-muted">
  338. <a class="text-reset me-3" data-bs-toggle="modal" href="#linkModal">Lien</a>
  339. <?php if ($hasSupplier) : ?>
  340. <?php if ($isConfig) : ?>
  341. <a class="text-reset" href="<?php echo generateUrl($supplier); ?>">Retour</a>
  342. <?php else : ?>
  343. <a tabindex="-1" class="text-reset" href="<?php printf('%s?action=config', generateUrl($supplier)); ?>">
  344. <?php if ($hasPassword) : ?>
  345. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-lock" viewBox="0 0 16 16">
  346. <path d="M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2zM5 8h6a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z"/>
  347. </svg>
  348. <?php else : ?>
  349. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-unlock" viewBox="0 0 16 16">
  350. <path d="M11 1a2 2 0 0 0-2 2v4a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h5V3a3 3 0 0 1 6 0v4a.5.5 0 0 1-1 0V3a2 2 0 0 0-2-2zM3 8a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V9a1 1 0 0 0-1-1H3z"/>
  351. </svg>
  352. <?php endif; ?>
  353. Configuration
  354. </a>
  355. <?php endif; ?>
  356. <?php endif; ?>
  357. </span>
  358. </div>
  359. </nav>
  360. </header>
  361. <main>
  362. <?php if (!$hasSupplier) : ?>
  363. <section class="container-fluid pt-3">
  364. <div class="alert alert-danger alert-dismissible mb-3" role="alert">
  365. Pas de fournisseur !
  366. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Fermer"></button>
  367. </div>
  368. <div class="row mb-3 g-3">
  369. <div class="col-12">
  370. <form action="<?php echo generateUrl(); ?>" method="post">
  371. <datalist id="supplierList">
  372. <?php foreach ($suppliers as $supplier) : ?>
  373. <option value="<?php echo $supplier; ?>" />
  374. <?php endforeach; ?>
  375. </datalist>
  376. <div class="input-group input-group-lg">
  377. <span class="input-group-text">
  378. <span class="d-none d-sm-inline"><?php echo generateUrl(); ?></span>
  379. <span class="d-inline d-sm-none" title="<?php echo generateUrl(); ?>">&hellip;</span>
  380. /
  381. </span>
  382. <input type="text" class="form-control js-closealerts" name="supplier" list="supplierList" required placeholder="MonFournisseur" tabindex="1" autofocus />
  383. <button class="btn btn-primary" type="submit">Aller&nbsp;&rarr;</button>
  384. </div>
  385. </form>
  386. </div>
  387. <div class="col-12">
  388. <details>
  389. <summary>Documentation</summary>
  390. </details>
  391. </div>
  392. </div>
  393. </section>
  394. <?php else : ?>
  395. <?php if ($isConfig) : ?>
  396. <section class="container-fluid">
  397. <div class="row my-3 g-3">
  398. <div class="col">
  399. <h1>Configuration</h1>
  400. </div>
  401. </div>
  402. </section>
  403. <section class="container-fluid">
  404. <div class="row g-3">
  405. <form action="<?php echo generateUrl($supplier); ?>" method="post">
  406. <div class="row mb-3">
  407. <label for="title" class="col-sm-2 col-form-label">Titre</label>
  408. <div class="col-sm-10">
  409. <input class="form-control" type="text" name="title" value="<?php echo htmlspecialchars($config[$supplier]['title']); ?>" placeholder="<?php echo $supplier; ?>" />
  410. <div class="form-text">Le titre de la page. Par défaut ce sera le nom du fournisseur </div>
  411. </div>
  412. </div>
  413. <div class="row mb-3">
  414. <label for="description" class="col-sm-2 col-form-label">Description</label>
  415. <div class="col-sm-10">
  416. <textarea class="form-control js-ckeditor" name="description" rows="20"><?php echo $config[$supplier]['description']; ?></textarea>
  417. <div class="form-text">La description affichée sous le titre.</div>
  418. </div>
  419. </div>
  420. <div class="row mb-3">
  421. <label for="choices" class="col-sm-2 col-form-label">Choix</label>
  422. <div class="col-sm-10">
  423. <textarea class="form-control" name="choices" rows="5"><?php echo implode(PHP_EOL, $config[$supplier]['choices']); ?></textarea>
  424. <div class="form-text">Les différents choix possibles. Un par ligne. Ou pas.</div>
  425. </div>
  426. </div>
  427. <div class="row mb-3">
  428. <label for="start" class="col-sm-2 col-form-label">Début</label>
  429. <div class="col-sm-10">
  430. <input class="form-control" type="date" name="start" value="<?php echo $config[$supplier]['start']; ?>" />
  431. <div class="form-text">La date du premier événement, si nécessaire de le préciser.</div>
  432. </div>
  433. </div>
  434. <div class="row mb-3">
  435. <label for="frequency" class="col-sm-2 col-form-label">Fréquence</label>
  436. <div class="col-sm-10">
  437. <input class="form-control" type="text" name="frequency" value="<?php echo $config[$supplier]['frequency']; ?>" />
  438. <div class="form-text">La fréquence des événements dans le format <a class="text-reset" href="https://www.php.net/manual/fr/datetime.formats.relative.php" target="_blank">décrit sur cette page</a>.</div>
  439. </div>
  440. </div>
  441. <div class="row mb-3">
  442. <label for="excludes" class="col-sm-2 col-form-label">Exceptions</label>
  443. <div class="col-sm-10">
  444. <textarea class="form-control" name="excludes" rows="5"><?php echo implode(PHP_EOL, array_map(function ($value) use ($excludesFormatter) { return $excludesFormatter->format(new \DateTimeImmutable($value, new \DateTimeZone('Europe/Paris'))); }, $config[$supplier]['excludes'])); ?></textarea>
  445. <div class="form-text">Les dates à exclure. Une par ligne. Ou pas. En tous cas le format c'est celui de l'<a class="text-reset" href="https://unicode-org.github.io/icu/userguide/format_parse/datetime/" target="_blank">ICU</a> : <kbd><?php echo $excludesFormatter->getPattern(); ?></kbd>. Par exemple <kbd><?php echo $excludesFormatter->format(new \DateTimeImmutable('first day of january this year', new \DateTimeZone('Europe/Paris'))); ?></kbd>, <kbd><?php echo $excludesFormatter->format(new \DateTimeImmutable('now', new \DateTimeZone('Europe/Paris'))); ?></kbd> ou <kbd><?php echo $excludesFormatter->format(new \DateTimeImmutable('last day of december this year', new \DateTimeZone('Europe/Paris'))); ?></kbd>.</div>
  446. </div>
  447. </div>
  448. <div class="row mb-3">
  449. <label for="password" class="col-sm-2 col-form-label">Mot de passe</label>
  450. <div class="col-sm-10">
  451. <input class="form-control" type="text" name="password" value="<?php echo $config[$supplier]['password']; ?>" />
  452. <div class="form-text">Ce mot de passe sera demandé pour accéder à la configuration la prochaine fois. Le nom d'utilisateur est le fournisseur courant (en l'occurrence <kbd><?php echo $supplier; ?></kbd>). Par exemple <kbd><?php echo generatePassword(); ?></kbd>. Et pas de mot de passe, pas de protection.</div>
  453. </div>
  454. </div>
  455. <div class="row">
  456. <div class="col px-0">
  457. <div class="js-fixed bg-light p-3">
  458. <button class="btn btn-primary" type="submit" name="action" value="config">Enregistrer</button>
  459. </div>
  460. </div>
  461. </div>
  462. </form>
  463. </div>
  464. </section>
  465. <?php else /* !$isConfig */ : ?>
  466. <?php if ($supplierIsNew) : ?>
  467. <section class="container-fluid pt-3">
  468. <div class="alert alert-warning alert-dismissible" role="alert">
  469. Ce fournisseur n'existe pas encore !
  470. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Fermer"></button>
  471. </div>
  472. <div class="row g-3">
  473. <div class="col-xs-12 col-sm-6">
  474. <div class="card h-100">
  475. <div class="card-body">
  476. <h2 class="card-title">Oops !</h2>
  477. <p class="card-text">Le nom du fournisseur « <tt><?php echo $supplier; ?></tt> » est probablement mal orthographié, c'est pour ça qu'il n'existe pas.</p>
  478. <p class="card-text">
  479. Peut-être sagissait-il de
  480. <?php $max = 3; foreach ($closestSuppliers as $index => $item) : ?>
  481. <?php if ($index < $max) : ?>
  482. <?php if ($index > 0) : ?>
  483. <?php if ($index === min($max, count($closestSuppliers) - 1)) : ?>
  484. ou
  485. <?php else : ?>
  486. ,
  487. <?php endif; ?>
  488. <?php endif; ?>
  489. « <tt><a class="card-link" href="<?php echo generateUrl($item['supplier']); ?>"><?php echo $item['supplier']; ?></a></tt> »
  490. <?php endif; ?>
  491. <?php endforeach; ?>
  492. ?
  493. </p>
  494. <a class="btn btn-primary" href="<?php echo generateUrl(); ?>">Recommencer</a>
  495. </div>
  496. </div>
  497. </div>
  498. <div class="col-xs-12 col-sm-6">
  499. <div class="card h-100">
  500. <div class="card-body">
  501. <h2 class="card-title">C'est normal !</h2>
  502. <p class="card-text">On souhaite le créer.</p>
  503. <p class="card_text">Une fois configuré il sera prêt à être utilisé.</p>
  504. <a class="btn btn-primary" href="<?php echo generateUrl($supplier) . '?action=config'; ?>">Configurer</a>
  505. </div>
  506. </div>
  507. </div>
  508. </div>
  509. </section>
  510. <?php else /* !$supplierIsNew */ : ?>
  511. <section class="container-fluid">
  512. <div class="row my-3">
  513. <div class="col">
  514. <h1>
  515. <div class="btn-group float-end" role="group">
  516. <?php if (isset($previousEvent)) : ?>
  517. <a class="btn btn-outline-primary" href="<?php echo generateUrl($supplier, $previousEvent); ?>" title="Événement précédent">
  518. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
  519. <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
  520. </svg>
  521. </a>
  522. <?php endif; ?>
  523. <?php /* ?>
  524. <a class="btn btn-outline-primary d-none d-sm-inline" href="<?php echo generateUrl($supplier, $event); ?>" title="Cet événement">
  525. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-link" viewBox="0 0 16 16">
  526. <path d="M6.354 5.5H4a3 3 0 0 0 0 6h3a3 3 0 0 0 2.83-4H9c-.086 0-.17.01-.25.031A2 2 0 0 1 7 10.5H4a2 2 0 1 1 0-4h1.535c.218-.376.495-.714.82-1z"/>
  527. <path d="M9 5.5a3 3 0 0 0-2.83 4h1.098A2 2 0 0 1 9 6.5h3a2 2 0 1 1 0 4h-1.535a4.02 4.02 0 0 1-.82 1H12a3 3 0 1 0 0-6H9z"/>
  528. </svg>
  529. </a>
  530. <?php */ ?>
  531. <?php if (isset($nextEvent)) : ?>
  532. <a class="btn btn-outline-primary" href="<?php echo generateUrl($supplier, $nextEvent); ?>" title="Événement suivant">
  533. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
  534. <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/>
  535. </svg>
  536. </a>
  537. <?php endif; ?>
  538. </div>
  539. <?php echo $config[$supplier]['title']; ?>
  540. <?php echo $config[$supplier]['subtitle']; ?>
  541. </h1>
  542. <?php if (!empty($config[$supplier]['description'])) : ?>
  543. <p class="lead"><?php echo $config[$supplier]['description']; ?></p>
  544. <?php endif; ?>
  545. </div>
  546. </div>
  547. </section>
  548. <section class="container-fluid">
  549. <div class="row g-3">
  550. <form class="js-localremember bg-dark text-light" action="<?php echo generateUrl($supplier); ?>" method="post">
  551. <div class="row my-3">
  552. <label for="title" class="col-sm-2 col-form-label">Nom</label>
  553. <div class="col-sm-10">
  554. <input class="form-control" type="text" name="name" required placeholder="Nom" />
  555. </div>
  556. </div>
  557. <?php if (!empty($config[$supplier]['choices'])) : ?>
  558. <div class="row mb-3">
  559. <label for="title" class="col-sm-2 col-form-label">Choix</label>
  560. <div class="col-sm-10">
  561. <div class="btn-group" role="group">
  562. <?php foreach ($config[$supplier]['choices'] as $index => $choice) : ?>
  563. <input type="radio" class="btn-check" id="<?php printf('option%d', $index); ?>" autocomplete="off" name="choice" value="<?php echo $choice; ?>" required />
  564. <label class="btn btn-outline-light" for="<?php printf('option%d', $index); ?>"><?php echo $choice; ?></label>
  565. <?php endforeach; ?>
  566. </div>
  567. </div>
  568. </div>
  569. <?php endif; ?>
  570. <div class="row">
  571. <div class="col mb-3">
  572. <input type="hidden" name="supplier" value="<?php echo $supplier; ?>" />
  573. <input type="hidden" name="event" value="<?php echo $event; ?>" />
  574. <?php if (empty($config[$supplier]['choices'])) : ?>
  575. <input type="hidden" name="choice" value="" />
  576. <?php endif; ?>
  577. <button class="btn btn-primary" type="submit" name="action" value="insert">Commander</button>
  578. </div>
  579. </div>
  580. </form>
  581. </div>
  582. </section>
  583. <section class="container-fluid">
  584. <div class="row my-3">
  585. <?php if (!empty($items)) : ?>
  586. <div class="col-12">
  587. <div class="table-responsive">
  588. <table class="table table-striped table-hover align-middle sortable">
  589. <thead>
  590. <tr>
  591. <th scope="col">
  592. Nom
  593. </th>
  594. <?php if (!empty($config[$supplier]['choices'])) : ?>
  595. <th scope="col">
  596. Choix
  597. </th>
  598. <?php endif; ?>
  599. <th scope="col" class="no-sort">
  600. &nbsp;
  601. </th>
  602. </tr>
  603. </thead>
  604. <tbody>
  605. <?php foreach ($items as $item) : ?>
  606. <tr>
  607. <td>
  608. <?php echo $item['name']; ?>
  609. </td>
  610. <?php if (!empty($config[$supplier]['choices'])) : ?>
  611. <td>
  612. <?php if (!empty($item['choice'])) : ?>
  613. <?php echo $item['choice']; ?>
  614. <?php endif; ?>
  615. </td>
  616. <?php endif; ?>
  617. <td>
  618. <form onsubmit="return confirm('Souhaitez-vous vraiment annuler cette commande ?');">
  619. <input type="hidden" name="supplier" value="<?php echo $supplier; ?>" />
  620. <input type="hidden" name="event" value="<?php echo $event; ?>" />
  621. <input type="hidden" name="name" value="<?php echo $item['name']; ?>" />
  622. <input type="hidden" name="choice" value="<?php echo $item['choice']; ?>" />
  623. <button class="btn btn-secondary float-end" type="submit" name="action" value="delete">Annuler</button>
  624. </form>
  625. </td>
  626. </tr>
  627. <?php endforeach; ?>
  628. </tbody>
  629. </table>
  630. </div>
  631. </div>
  632. <?php endif; ?>
  633. <div class="col-12">
  634. <div class="accordion accordion-flush">
  635. <div class="accordion-item">
  636. <div id="accordion1" class="accordion-collapse collapse">
  637. <div class="accordion-body">
  638. <ul class="list-group">
  639. <?php foreach ($stats as $choice => $count) : ?>
  640. <li class="list-group-item d-flex justify-content-between align-items-center">
  641. <?php echo $choice; ?>
  642. <span class="badge bg-secondary rounded-pill"><?php echo $count; ?></span>
  643. </li>
  644. <?php endforeach; ?>
  645. </ul>
  646. </div>
  647. </div>
  648. <h2 class="accordion-header">
  649. <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion1" aria-expanded="false">
  650. Commandes
  651. <span class="badge bg-primary rounded-pill ms-1"><?php echo count($items); ?></span>
  652. </button>
  653. </h2>
  654. </div>
  655. </div>
  656. </div>
  657. </div>
  658. </section>
  659. <?php endif; /* $supplierIsNew */ ?>
  660. <?php endif; /* $isConfig*/ ?>
  661. <?php endif; ?>
  662. </main>
  663. <div class="modal fade" id="linkModal" tabindex="-1" aria-hidden="true">
  664. <div class="modal-dialog">
  665. <div class="modal-content">
  666. <div class="modal-header">
  667. <h5 class="modal-title">Lien</h5>
  668. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
  669. </div>
  670. <div class="modal-body">
  671. <div class="container-fluid">
  672. <div class="row g-3">
  673. <div class="col-12">
  674. Adresse web
  675. </div>
  676. <div class="col-12 text-center">
  677. <a href="<?php echo $linkUrl; ?>"><tt id="linkURL"><?php echo $linkUrl; ?></tt></a>
  678. <button class="btn btn-outline-dark js-clipboard" type="button" role="button" data-clipboard-target="#linkURL" data-bs-toggle="tooltip" data-bs-trigger="manual">
  679. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-clipboard" viewBox="0 0 16 16">
  680. <path d="M4 1.5H3a2 2 0 0 0-2 2V14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V3.5a2 2 0 0 0-2-2h-1v1h1a1 1 0 0 1 1 1V14a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3.5a1 1 0 0 1 1-1h1v-1z"/>
  681. <path d="M9.5 1a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5h3zm-3-1A1.5 1.5 0 0 0 5 1.5v1A1.5 1.5 0 0 0 6.5 4h3A1.5 1.5 0 0 0 11 2.5v-1A1.5 1.5 0 0 0 9.5 0h-3z"/>
  682. </svg>
  683. </button>
  684. </div>
  685. <div class="col-12">
  686. QR Code
  687. </div>
  688. <div class="col-12">
  689. <div id="linkQRCode"></div>
  690. </div>
  691. </div>
  692. </div>
  693. </div>
  694. <div class="modal-footer">
  695. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
  696. </div>
  697. </div>
  698. </div>
  699. </div>
  700. <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
  701. <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
  702. <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
  703. <?php if ($isConfig) : ?>
  704. <script src="https://cdn.ckeditor.com/ckeditor5/31.0.0/classic/ckeditor.js"></script>
  705. <script>
  706. document.querySelectorAll('.js-ckeditor').forEach(function (element) {
  707. ClassicEditor.create(element).catch(error => { console.error(error); });
  708. });
  709. </script>
  710. <?php else : ?>
  711. <script>document.addEventListener("click",function(b){function n(a,e){a.className=a.className.replace(u,"")+e}function p(a){return a.getAttribute("data-sort")||a.innerText}var u=/ dir-(u|d) /,c=/\bsortable\b/;b=b.target;if("TH"===b.nodeName)try{var q=b.parentNode,f=q.parentNode.parentNode;if(c.test(f.className)){var g,d=q.cells;for(c=0;c<d.length;c++)d[c]===b?g=c:n(d[c],"");d=" dir-d ";-1!==b.className.indexOf(" dir-d ")&&(d=" dir-u ");n(b,d);var h=f.tBodies[0],k=[].slice.call(h.rows,0),r=" dir-u "===d;k.sort(function(a,
  712. e){var l=p((r?a:e).cells[g]),m=p((r?e:a).cells[g]);return isNaN(l-m)?l.localeCompare(m):l-m});for(var t=h.cloneNode();k.length;)t.appendChild(k.splice(0,1)[0]);f.replaceChild(t,h)}}catch(a){}});</script>
  713. <?php endif; ?>
  714. <script>
  715. document.addEventListener('DOMContentLoaded', function () {
  716. document.querySelectorAll('.js-localremember').forEach(function (form) {
  717. const fields = [ 'name', 'choice' ];
  718. form.addEventListener('submit', function (event) {
  719. fields.forEach(function (field) {
  720. window.localStorage.setItem('mon_panier_bio_' + field, form.elements[field].value);
  721. });
  722. });
  723. fields.forEach(function (field) {
  724. if (
  725. (form.elements[field].value === '')
  726. && (window.localStorage.getItem('mon_panier_bio_' + field) !== null)
  727. ) {
  728. form.elements[field].value = window.localStorage.getItem('mon_panier_bio_' + field);
  729. }
  730. });
  731. });
  732. document.querySelectorAll('.js-closealerts').forEach(function (element) {
  733. element.addEventListener('input', function (event) {
  734. if (event.target.value !== '') {
  735. document.querySelectorAll('.alert').forEach(function (alertElement) {
  736. var alert = bootstrap.Alert.getOrCreateInstance(alertElement)
  737. alert.close();
  738. });
  739. }
  740. });
  741. });
  742. var qrcode = new QRCode('linkQRCode', {
  743. text: document.getElementById('linkURL').innerText,
  744. width: 300,
  745. height: 300,
  746. colorDark : '#000000',
  747. colorLight : '#ffffff',
  748. correctLevel : QRCode.CorrectLevel.H,
  749. });
  750. document.querySelector('#linkQRCode img').classList.add('img-fluid', 'mx-auto', 'd-block');
  751. var clipboard = new ClipboardJS('.js-clipboard');
  752. clipboard.on('success', function (event) {
  753. var tooltip = new bootstrap.Tooltip(event.trigger, {
  754. title: 'Copié dans le presse-papier'
  755. });
  756. tooltip.show();
  757. });
  758. document.querySelectorAll('.js-fixed').forEach(function (element) {
  759. const height = window.getComputedStyle(element).height;
  760. element.parentElement.style.height = height;
  761. element.classList.add('is-fixed');
  762. });
  763. }, false);
  764. </script>
  765. </body>
  766. </html>