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.

845 lines
36 KiB

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