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.

831 lines
34 KiB

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