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.

810 lines
33 KiB

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