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.

875 lines
38 KiB

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