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.

842 lines
35 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('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>Documentation</summary>
  400. </details>
  401. </div>
  402. </div>
  403. </section>
  404. <?php else : ?>
  405. <?php if ($isConfig) : ?>
  406. <section class="container-fluid">
  407. <div class="row my-3 g-3">
  408. <div class="col">
  409. <h1>Configuration</h1>
  410. </div>
  411. </div>
  412. </section>
  413. <section class="container-fluid">
  414. <div class="row g-3">
  415. <form action="<?php echo generateUrl($supplier); ?>" method="post">
  416. <div class="row mb-3">
  417. <label for="title" class="col-sm-2 col-form-label">Titre</label>
  418. <div class="col-sm-10">
  419. <input class="form-control" type="text" name="title" value="<?php echo htmlspecialchars($config[$supplier]['title']); ?>" placeholder="<?php echo $supplier; ?>" />
  420. <div class="form-text">Le titre de la page. Par défaut ce sera le nom du fournisseur </div>
  421. </div>
  422. </div>
  423. <div class="row mb-3">
  424. <label for="description" class="col-sm-2 col-form-label">Description</label>
  425. <div class="col-sm-10">
  426. <textarea class="form-control js-ckeditor" name="description" rows="20"><?php echo $config[$supplier]['description']; ?></textarea>
  427. <div class="form-text">La description affichée sous le titre.</div>
  428. </div>
  429. </div>
  430. <div class="row mb-3">
  431. <label for="choices" class="col-sm-2 col-form-label">Choix</label>
  432. <div class="col-sm-10">
  433. <textarea class="form-control" name="choices" rows="5"><?php echo implode(PHP_EOL, $config[$supplier]['choices']); ?></textarea>
  434. <div class="form-text">Les différents choix possibles. Un par ligne. Ou pas.</div>
  435. </div>
  436. </div>
  437. <div class="row mb-3">
  438. <label for="start" class="col-sm-2 col-form-label">Début</label>
  439. <div class="col-sm-10">
  440. <input class="form-control" type="date" name="start" value="<?php echo $config[$supplier]['start']; ?>" />
  441. <div class="form-text">La date du premier événement, si nécessaire de le préciser.</div>
  442. </div>
  443. </div>
  444. <div class="row mb-3">
  445. <label for="frequency" class="col-sm-2 col-form-label">Fréquence</label>
  446. <div class="col-sm-10">
  447. <input class="form-control" type="text" name="frequency" value="<?php echo $config[$supplier]['frequency']; ?>" />
  448. <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>
  449. </div>
  450. </div>
  451. <div class="row mb-3">
  452. <label for="excludes" class="col-sm-2 col-form-label">Exceptions</label>
  453. <div class="col-sm-10">
  454. <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>
  455. <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>
  456. </div>
  457. </div>
  458. <div class="row mb-3">
  459. <label for="password" class="col-sm-2 col-form-label">Mot de passe</label>
  460. <div class="col-sm-10">
  461. <input class="form-control" type="text" name="password" value="<?php echo $config[$supplier]['password']; ?>" />
  462. <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>
  463. </div>
  464. </div>
  465. <div class="row">
  466. <div class="col px-0">
  467. <div class="js-fixed bg-light p-3">
  468. <button class="btn btn-primary" type="submit" name="action" value="config">Enregistrer</button>
  469. </div>
  470. </div>
  471. </div>
  472. </form>
  473. </div>
  474. </section>
  475. <?php else /* !$isConfig */ : ?>
  476. <?php if ($supplierIsNew) : ?>
  477. <section class="container-fluid pt-3">
  478. <div class="alert alert-warning alert-dismissible" role="alert">
  479. Ce fournisseur n'existe pas encore !
  480. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Fermer"></button>
  481. </div>
  482. <div class="row g-3">
  483. <div class="col-xs-12 col-sm-6">
  484. <div class="card h-100">
  485. <div class="card-body">
  486. <h2 class="card-title">Oops !</h2>
  487. <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>
  488. <p class="card-text">
  489. Peut-être sagissait-il de
  490. <?php $max = 3; foreach ($closestSuppliers as $index => $item) : ?>
  491. <?php if ($index < $max) : ?>
  492. <?php if ($index > 0) : ?>
  493. <?php if ($index === min($max, count($closestSuppliers) - 1)) : ?>
  494. ou
  495. <?php else : ?>
  496. ,
  497. <?php endif; ?>
  498. <?php endif; ?>
  499. « <tt><a class="card-link" href="<?php echo generateUrl($item['supplier']); ?>"><?php echo $item['supplier']; ?></a></tt> »
  500. <?php endif; ?>
  501. <?php endforeach; ?>
  502. ?
  503. </p>
  504. <a class="btn btn-primary" href="<?php echo generateUrl(); ?>">Recommencer</a>
  505. </div>
  506. </div>
  507. </div>
  508. <div class="col-xs-12 col-sm-6">
  509. <div class="card h-100">
  510. <div class="card-body">
  511. <h2 class="card-title">C'est normal !</h2>
  512. <p class="card-text">On souhaite le créer.</p>
  513. <p class="card_text">Une fois configuré il sera prêt à être utilisé.</p>
  514. <a class="btn btn-primary" href="<?php echo generateUrl($supplier) . '?action=config'; ?>">Configurer</a>
  515. </div>
  516. </div>
  517. </div>
  518. </div>
  519. </section>
  520. <?php else /* !$supplierIsNew */ : ?>
  521. <section class="container-fluid">
  522. <div class="row my-3">
  523. <div class="col">
  524. <h1>
  525. <div class="btn-group float-end" role="group">
  526. <?php if (isset($previousEvent)) : ?>
  527. <a class="btn btn-outline-primary" href="<?php echo generateUrl($supplier, $previousEvent); ?>" title="Événement précédent">
  528. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
  529. <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"/>
  530. </svg>
  531. </a>
  532. <?php endif; ?>
  533. <?php /* ?>
  534. <a class="btn btn-outline-primary d-none d-sm-inline" href="<?php echo generateUrl($supplier, $event); ?>" title="Cet événement">
  535. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-link" viewBox="0 0 16 16">
  536. <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"/>
  537. <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"/>
  538. </svg>
  539. </a>
  540. <?php */ ?>
  541. <?php if (isset($nextEvent)) : ?>
  542. <a class="btn btn-outline-primary" href="<?php echo generateUrl($supplier, $nextEvent); ?>" title="Événement suivant">
  543. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
  544. <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"/>
  545. </svg>
  546. </a>
  547. <?php endif; ?>
  548. </div>
  549. <?php echo $config[$supplier]['title']; ?>
  550. <?php echo $config[$supplier]['subtitle']; ?>
  551. </h1>
  552. <?php if (!empty($config[$supplier]['description'])) : ?>
  553. <p class="lead"><?php echo $config[$supplier]['description']; ?></p>
  554. <?php endif; ?>
  555. </div>
  556. </div>
  557. </section>
  558. <section class="container-fluid">
  559. <div class="row g-3">
  560. <form class="js-localremember bg-dark text-light" action="<?php echo generateUrl($supplier); ?>" method="post">
  561. <div class="row my-3">
  562. <label for="title" class="col-sm-2 col-form-label">Nom</label>
  563. <div class="col-sm-10">
  564. <input class="form-control" type="text" name="name" required placeholder="Nom" />
  565. </div>
  566. </div>
  567. <?php if (!empty($config[$supplier]['choices'])) : ?>
  568. <div class="row mb-3">
  569. <label for="title" class="col-sm-2 col-form-label">Choix</label>
  570. <div class="col-sm-10">
  571. <div class="btn-group" role="group">
  572. <?php foreach ($config[$supplier]['choices'] as $index => $choice) : ?>
  573. <input type="radio" class="btn-check" id="<?php printf('option%d', $index); ?>" autocomplete="off" name="choice" value="<?php echo $choice; ?>" required />
  574. <label class="btn btn-outline-light" for="<?php printf('option%d', $index); ?>"><?php echo $choice; ?></label>
  575. <?php endforeach; ?>
  576. </div>
  577. </div>
  578. </div>
  579. <?php endif; ?>
  580. <div class="row">
  581. <div class="col mb-3">
  582. <input type="hidden" name="supplier" value="<?php echo $supplier; ?>" />
  583. <input type="hidden" name="event" value="<?php echo $event; ?>" />
  584. <?php if (empty($config[$supplier]['choices'])) : ?>
  585. <input type="hidden" name="choice" value="" />
  586. <?php endif; ?>
  587. <?php if (isInPast($event)) :?>
  588. <div class="alert alert-warning alert-dismissible" role="alert">
  589. Ê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> ?
  590. <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Fermer"></button>
  591. </div>
  592. <?php endif; ?>
  593. <button class="btn btn-primary" type="submit" name="action" value="insert">Commander</button>
  594. </div>
  595. </div>
  596. </form>
  597. </div>
  598. </section>
  599. <section class="container-fluid">
  600. <div class="row my-3">
  601. <?php if (!empty($items)) : ?>
  602. <div class="col-12">
  603. <div class="table-responsive">
  604. <table class="table table-striped table-hover align-middle sortable">
  605. <thead>
  606. <tr>
  607. <th scope="col">
  608. Nom
  609. </th>
  610. <?php if (!empty($config[$supplier]['choices'])) : ?>
  611. <th scope="col">
  612. Choix
  613. </th>
  614. <?php endif; ?>
  615. <th scope="col" class="no-sort">
  616. &nbsp;
  617. </th>
  618. </tr>
  619. </thead>
  620. <tbody>
  621. <?php foreach ($items as $item) : ?>
  622. <tr>
  623. <td>
  624. <?php echo $item['name']; ?>
  625. </td>
  626. <?php if (!empty($config[$supplier]['choices'])) : ?>
  627. <td>
  628. <?php if (!empty($item['choice'])) : ?>
  629. <?php echo $item['choice']; ?>
  630. <?php endif; ?>
  631. </td>
  632. <?php endif; ?>
  633. <td>
  634. <form onsubmit="return confirm('Souhaitez-vous vraiment annuler cette commande ?');">
  635. <input type="hidden" name="supplier" value="<?php echo $supplier; ?>" />
  636. <input type="hidden" name="event" value="<?php echo $event; ?>" />
  637. <input type="hidden" name="name" value="<?php echo $item['name']; ?>" />
  638. <input type="hidden" name="choice" value="<?php echo $item['choice']; ?>" />
  639. <button class="btn btn-secondary float-end" type="submit" name="action" value="delete">Annuler</button>
  640. </form>
  641. </td>
  642. </tr>
  643. <?php endforeach; ?>
  644. </tbody>
  645. </table>
  646. </div>
  647. </div>
  648. <?php endif; ?>
  649. <div class="col-12">
  650. <div class="accordion accordion-flush">
  651. <div class="accordion-item">
  652. <div id="accordion1" class="accordion-collapse collapse">
  653. <div class="accordion-body">
  654. <ul class="list-group">
  655. <?php foreach ($stats as $choice => $count) : ?>
  656. <li class="list-group-item d-flex justify-content-between align-items-center">
  657. <?php echo $choice; ?>
  658. <span class="badge bg-secondary rounded-pill"><?php echo $count; ?></span>
  659. </li>
  660. <?php endforeach; ?>
  661. </ul>
  662. </div>
  663. </div>
  664. <h2 class="accordion-header">
  665. <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#accordion1" aria-expanded="false">
  666. Commandes
  667. <span class="badge bg-primary rounded-pill ms-1"><?php echo count($items); ?></span>
  668. </button>
  669. </h2>
  670. </div>
  671. </div>
  672. </div>
  673. </div>
  674. </section>
  675. <?php endif; /* $supplierIsNew */ ?>
  676. <?php endif; /* $isConfig*/ ?>
  677. <?php endif; ?>
  678. </main>
  679. <div class="modal fade" id="linkModal" tabindex="-1" aria-hidden="true">
  680. <div class="modal-dialog">
  681. <div class="modal-content">
  682. <div class="modal-header">
  683. <h5 class="modal-title">Lien</h5>
  684. <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
  685. </div>
  686. <div class="modal-body">
  687. <div class="container-fluid">
  688. <div class="row g-3">
  689. <div class="col-12">
  690. Adresse web
  691. </div>
  692. <div class="col-12 text-center">
  693. <a href="<?php echo $linkUrl; ?>"><tt id="linkURL"><?php echo $linkUrl; ?></tt></a>
  694. <button class="btn btn-outline-dark js-clipboard" type="button" role="button" data-clipboard-target="#linkURL" data-bs-toggle="tooltip" data-bs-trigger="manual">
  695. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-clipboard" viewBox="0 0 16 16">
  696. <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"/>
  697. <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"/>
  698. </svg>
  699. </button>
  700. </div>
  701. <div class="col-12">
  702. QR Code
  703. </div>
  704. <div class="col-12">
  705. <div id="linkQRCode"></div>
  706. </div>
  707. </div>
  708. </div>
  709. </div>
  710. <div class="modal-footer">
  711. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
  712. </div>
  713. </div>
  714. </div>
  715. </div>
  716. <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>
  717. <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
  718. <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
  719. <?php if ($isConfig) : ?>
  720. <script src="https://cdn.ckeditor.com/ckeditor5/31.0.0/classic/ckeditor.js"></script>
  721. <script>
  722. document.querySelectorAll('.js-ckeditor').forEach(function (element) {
  723. ClassicEditor.create(element).catch(error => { console.error(error); });
  724. });
  725. </script>
  726. <?php else : ?>
  727. <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,
  728. 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>
  729. <?php endif; ?>
  730. <script>
  731. document.addEventListener('DOMContentLoaded', function () {
  732. document.querySelectorAll('.js-localremember').forEach(function (form) {
  733. const fields = [ 'name', 'choice' ];
  734. form.addEventListener('submit', function (event) {
  735. fields.forEach(function (field) {
  736. window.localStorage.setItem('mon_panier_bio_' + field, form.elements[field].value);
  737. });
  738. });
  739. fields.forEach(function (field) {
  740. if (
  741. (form.elements[field].value === '')
  742. && (window.localStorage.getItem('mon_panier_bio_' + field) !== null)
  743. ) {
  744. form.elements[field].value = window.localStorage.getItem('mon_panier_bio_' + field);
  745. }
  746. });
  747. });
  748. document.querySelectorAll('.js-closealerts').forEach(function (element) {
  749. element.addEventListener('input', function (event) {
  750. if (event.target.value !== '') {
  751. document.querySelectorAll('.alert').forEach(function (alertElement) {
  752. var alert = bootstrap.Alert.getOrCreateInstance(alertElement)
  753. alert.close();
  754. });
  755. }
  756. });
  757. });
  758. var qrcode = new QRCode('linkQRCode', {
  759. text: document.getElementById('linkURL').innerText,
  760. width: 300,
  761. height: 300,
  762. colorDark : '#000000',
  763. colorLight : '#ffffff',
  764. correctLevel : QRCode.CorrectLevel.H,
  765. });
  766. document.querySelector('#linkQRCode img').classList.add('img-fluid', 'mx-auto', 'd-block');
  767. var clipboard = new ClipboardJS('.js-clipboard');
  768. clipboard.on('success', function (event) {
  769. var tooltip = new bootstrap.Tooltip(event.trigger, {
  770. title: 'Copié dans le presse-papier'
  771. });
  772. tooltip.show();
  773. });
  774. document.querySelectorAll('.js-fixed').forEach(function (element) {
  775. const height = window.getComputedStyle(element).height;
  776. element.parentElement.style.height = height;
  777. element.classList.add('is-fixed');
  778. });
  779. }, false);
  780. </script>
  781. </body>
  782. </html>