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.

474 lines
19 KiB

  1. <?php
  2. $requestUrl = trim(str_replace($_SERVER['QUERY_STRING'], '', $_SERVER['REQUEST_URI']), '?');
  3. define('CONFIG_FILE', __DIR__ . DIRECTORY_SEPARATOR . 'config.php');
  4. define('DATA_FILE', __DIR__ . DIRECTORY_SEPARATOR . 'data.php');
  5. if (file_exists(CONFIG_FILE)) require_once CONFIG_FILE;
  6. if (!isset($config)) $config = [];
  7. $action = (isset($_REQUEST['action']) and preg_match('/^[a-z]{1,16}$/i', $_REQUEST['action'])) ? $_REQUEST['action'] : null;
  8. $hasSupplier = isset($_REQUEST['supplier']) and !empty($_REQUEST['supplier']) and preg_match('/^[A-Za-z]\w{0,31}$/', $_REQUEST['supplier']);
  9. $supplier = $_REQUEST['supplier'];
  10. if ($hasSupplier) {
  11. if (!isset($config[$supplier]))
  12. $config[$supplier] = [];
  13. $config[$supplier] = array_merge(
  14. [
  15. 'title' => '%supplier% <small>%date%</small>',
  16. 'description' => '',
  17. 'choices' => [],
  18. 'start' => 'now 00:00:00',
  19. 'frequency' => '1 day',
  20. 'password' => '',
  21. ],
  22. $config[$supplier]
  23. );
  24. $hasPassword = !empty($config[$supplier]['password']);
  25. if ($action === 'config') {
  26. if ($hasPassword) {
  27. if (!isset($_SERVER['PHP_AUTH_USER'])) {
  28. header(sprintf('WWW-Authenticate: Basic realm="mon-panier-bio config %s"', $supplier));
  29. header('HTTP/1.0 401 Unauthorized');
  30. printf('Cette config est protégée par mot de passe !');
  31. exit;
  32. } elseif (
  33. ($_SERVER['PHP_AUTH_USER'] !== $supplier)
  34. or ($_SERVER['PHP_AUTH_PW'] !== $config[$supplier]['password'])
  35. ) {
  36. header('HTTP/1.0 403 Forbidden');
  37. printf('Cette config est protégée par mot de passe !');
  38. exit;
  39. }
  40. }
  41. foreach (array_keys($config[$supplier]) as $key)
  42. if (isset($_REQUEST[$key]))
  43. $config[$supplier][$key] = (!in_array($key, ['title', 'description']) ? filter_var($_REQUEST[$key], FILTER_SANITIZE_STRING) : $_REQUEST[$key]);
  44. }
  45. if (empty($config[$supplier]['start']))
  46. $config[$supplier]['start'] = 'now 00:00:00';
  47. if (is_string($config[$supplier]['choices']))
  48. $config[$supplier]['choices'] = explode(PHP_EOL, $config[$supplier]['choices']);
  49. if (!is_array($config[$supplier]['choices']))
  50. $config[$supplier]['choices'] = [];
  51. $config[$supplier]['choices'] = array_filter(
  52. $config[$supplier]['choices'],
  53. function ($choice) {
  54. return is_string($choice) and !empty(trim($choice));
  55. }
  56. );
  57. $config[$supplier]['choices'] = array_map('trim', $config[$supplier]['choices']);
  58. }
  59. $isConfig = false;
  60. if ($action === 'config') {
  61. $output = fopen(CONFIG_FILE, 'w+');
  62. if ($output) {
  63. if (flock($output, LOCK_EX)) {
  64. fwrite($output, '<?php' . PHP_EOL);
  65. fprintf(
  66. $output,
  67. '$config = %s;' . PHP_EOL,
  68. var_export($config, true)
  69. );
  70. flock($output, LOCK_UN);
  71. }
  72. fclose($output);
  73. }
  74. $isConfig = true;
  75. }
  76. try {
  77. $hasEvent = (
  78. isset($_REQUEST['event'])
  79. and preg_match('/^\d{4}\-[01]\d\-[0123]\d$/', $_REQUEST['event'])
  80. and ((new \DateTimeImmutable($_REQUEST['event'])) instanceof \DateTimeImmutable)
  81. );
  82. } catch (\Exception $exception) {
  83. $hasEvent = false;
  84. }
  85. if (!$isConfig and $hasSupplier) {
  86. $start = new \DateTime($config[$supplier]['start']);
  87. if (!$hasEvent) {
  88. $now = new \DateTime('now');
  89. $current = clone $start;
  90. $frequency = \DateInterval::createFromDateString($config[$supplier]['frequency']);
  91. $maxIterations = 1000;
  92. while (
  93. ($current->getTimestamp() < $now->getTimestamp())
  94. and ($maxIterations-- > 0)
  95. ) $current->add($frequency);
  96. $nextEvent = $current->format('Y-m-d');
  97. header(sprintf('Location: %s?supplier=%s&event=%s', $requestUrl, $supplier, $nextEvent));
  98. die();
  99. } else {
  100. $event = $_REQUEST['event'];
  101. $current = new \DateTimeImmutable($event);
  102. $frequency = \DateInterval::createFromDateString($config[$supplier]['frequency']);
  103. $previous = $current->sub($frequency);
  104. $previousEvent = $previous->format('Y-m-d');
  105. if (false and !array_key_exists($previousEvent, $data[$supplier]))
  106. unset($previousEvent);
  107. $next = $current->add($frequency);
  108. $nextEvent = $next->format('Y-m-d');
  109. if (false and !array_key_exists($nextEvent, $data[$supplier]))
  110. unset($nextEvent);
  111. }
  112. switch ($action) {
  113. case 'insert' :
  114. case 'delete' :
  115. $isBeginning = (!file_exists(DATA_FILE) or in_array(filesize(DATA_FILE), [ false, 0 ]));
  116. $output = fopen(DATA_FILE, 'a+');
  117. if (!$output) break;
  118. if (!flock($output, LOCK_EX)) break;
  119. if ($isBeginning)
  120. fwrite($output, '<?php' . PHP_EOL);
  121. $item = [];
  122. foreach (['name', 'choice', 'action'] as $field)
  123. $item[$field] = filter_var($_REQUEST[$field], FILTER_SANITIZE_STRING);
  124. $item['timestamp'] = time();
  125. $item['hash'] = md5(implode([ $item['name'], $item['choice'], ]));
  126. fprintf(
  127. $output,
  128. '$data[%s][%s][] = %s;' . PHP_EOL,
  129. var_export($supplier, true),
  130. var_export($event, true),
  131. str_replace(PHP_EOL, '', var_export($item, true))
  132. );
  133. flock($output, LOCK_UN);
  134. fclose($output);
  135. header(sprintf('Location: %s?supplier=%s&event=%s', $requestUrl, $supplier, $event));
  136. die();
  137. }
  138. if (!isset($data)) $data = [];
  139. if (file_exists(DATA_FILE)) include DATA_FILE;
  140. $items = [];
  141. $allItems = isset($data[$supplier][$event]) ? $data[$supplier][$event] : [];
  142. usort($allItems, function ($a, $b) {
  143. $a = intval($a['timestamp']);
  144. $b = intval($b['timestamp']);
  145. if ($a === $b)
  146. return 0;
  147. return ($a < $b) ? -1 : 1;
  148. });
  149. foreach ($allItems as $item) {
  150. if ($item['action'] === 'insert') {
  151. $items[] = $item;
  152. } elseif ($item['action'] === 'delete') {
  153. foreach ($items as $index => $prevItem)
  154. if ($prevItem['hash'] === $item['hash'])
  155. unset($items[$index]);
  156. }
  157. }
  158. $date = (new \IntlDateFormatter('fr_FR.UTF8', \IntlDateFormatter::FULL, \IntlDateFormatter::NONE, 'Europe/Paris'))->format(new \DateTime($event));
  159. while (preg_match('/%([^%]+)%/i', $config[$supplier]['title'], $match))
  160. $config[$supplier]['title'] = str_replace(
  161. $match[0],
  162. ${$match[1]},
  163. $config[$supplier]['title']
  164. );
  165. $stats = [];
  166. foreach ($items as $item)
  167. if (!empty($item['choice']))
  168. $stats[$item['choice']] += 1;
  169. }
  170. ?><!DOCTYPE html>
  171. <html lang="fr">
  172. <head>
  173. <meta charset="UTF-8" />
  174. <meta name="viewport" content="width=device-width, initial-scale=1" />
  175. <title><?php echo strip_tags($config[$supplier]['title']); ?></title>
  176. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  177. </head>
  178. <body>
  179. <header>
  180. <nav class="navbar navbar-dark bg-dark">
  181. <div class="container-fluid">
  182. <a class="navbar-brand" href="<?php echo $hasSupplier ? sprintf('%s?supplier=%s', $requestUrl, $supplier) : $requestUrl; ?>">
  183. <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">
  184. <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"/>
  185. </svg>
  186. <?php echo $hasSupplier ? $supplier : 'Mon panier bio'; ?>
  187. </a>
  188. <?php if ($hasSupplier) : ?>
  189. <span class="navbar-text text-muted">
  190. <?php if ($isConfig) : ?>
  191. <a class="text-reset" href="<?php printf('%s?supplier=%s', $requestUrl, $supplier); ?>">Retour</a>
  192. <?php else : ?>
  193. <?php if ($hasPassword) : ?>
  194. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-lock" viewBox="0 0 16 16">
  195. <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"/>
  196. </svg>
  197. <?php else : ?>
  198. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-unlock" viewBox="0 0 16 16">
  199. <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"/>
  200. </svg>
  201. <?php endif; ?>
  202. <a tabindex="-1" class="text-reset" href="<?php printf('%s?supplier=%s&action=config', $requestUrl, $supplier); ?>">Configuration</a>
  203. <?php endif; ?>
  204. </span>
  205. <?php endif; ?>
  206. </div>
  207. </nav>
  208. </header>
  209. <main>
  210. <?php if (!$hasSupplier) : ?>
  211. <section class="container-fluid">
  212. <div class="row my-3">
  213. <div class="col">
  214. <div class="alert alert-danger" role="alert">
  215. Pas de fournisseur !
  216. </div>
  217. </div>
  218. </div>
  219. </section>
  220. <?php else : ?>
  221. <?php if ($isConfig) : ?>
  222. <section class="container-fluid">
  223. <div class="row g-3">
  224. <div class="col">
  225. <h1>Configuration</h1>
  226. </div>
  227. </div>
  228. </section>
  229. <section class="container-fluid">
  230. <div class="row g-3">
  231. <form action="<?php printf('%s?supplier=%s', $requestUrl, $supplier); ?>" method="post">
  232. <div class="row mb-3">
  233. <label for="title" class="col-sm-2 col-form-label">Titre</label>
  234. <div class="col-sm-10">
  235. <input class="form-control" type="text" name="title" value="<?php echo htmlspecialchars($config[$supplier]['title']); ?>" />
  236. <div class="form-text">Le titre de la page. <kbd>%supplier%</kbd> est le fournisseur et <kbd>%date%</kbd> la date de l'événement.</div>
  237. </div>
  238. </div>
  239. <div class="row mb-3">
  240. <label for="description" class="col-sm-2 col-form-label">Description</label>
  241. <div class="col-sm-10">
  242. <textarea class="form-control js-ckeditor" name="description" rows="10"><?php echo $config[$supplier]['description']; ?></textarea>
  243. <div class="form-text">La description affichée sous le titre.</div>
  244. </div>
  245. </div>
  246. <div class="row mb-3">
  247. <label for="choices" class="col-sm-2 col-form-label">Choix</label>
  248. <div class="col-sm-10">
  249. <textarea class="form-control" name="choices" rows="5"><?php echo implode(PHP_EOL, $config[$supplier]['choices']); ?></textarea>
  250. <div class="form-text">Les différents choix possibles. Un par ligne. Ou pas.</div>
  251. </div>
  252. </div>
  253. <div class="row mb-3">
  254. <label for="start" class="col-sm-2 col-form-label">Début</label>
  255. <div class="col-sm-10">
  256. <input class="form-control" type="date" name="start" value="<?php echo $config[$supplier]['start']; ?>" />
  257. <div class="form-text">La date du premier événement, si nécessaire de le préciser.</div>
  258. </div>
  259. </div>
  260. <div class="row mb-3">
  261. <label for="frequency" class="col-sm-2 col-form-label">Fréquence</label>
  262. <div class="col-sm-10">
  263. <input class="form-control" type="text" name="frequency" value="<?php echo $config[$supplier]['frequency']; ?>" />
  264. <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>
  265. </div>
  266. </div>
  267. <div class="row mb-3">
  268. <label for="password" class="col-sm-2 col-form-label">Mot de passe</label>
  269. <div class="col-sm-10">
  270. <input class="form-control" type="text" name="password" value="<?php echo $config[$supplier]['password']; ?>" />
  271. <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>).</div>
  272. </div>
  273. </div>
  274. <div class="row">
  275. <div class="col mb-3">
  276. <button class="btn btn-primary" type="submit" name="action" value="config">Enregistrer</button>
  277. </div>
  278. </div>
  279. </form>
  280. </div>
  281. </section>
  282. <?php else : ?>
  283. <section class="container-fluid">
  284. <div class="row my-3">
  285. <div class="col">
  286. <h1>
  287. <?php echo $config[$supplier]['title']; ?>
  288. <div class="btn-group float-end" role="group">
  289. <?php if (isset($previousEvent)) : ?>
  290. <a class="btn btn-outline-primary" href="<?php printf('%s?supplier=%s&event=%s', $requestUrl, $supplier, $previousEvent); ?>" title="Événement précédent">
  291. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
  292. <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"/>
  293. </svg>
  294. </a>
  295. <?php endif; ?>
  296. <a class="btn btn-outline-primary" href="<?php printf('%s?supplier=%s&event=%s', $requestUrl, $supplier, $event); ?>" title="Cet événement">
  297. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-link" viewBox="0 0 16 16">
  298. <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"/>
  299. <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"/>
  300. </svg>
  301. </a>
  302. <?php if (isset($nextEvent)) : ?>
  303. <a class="btn btn-outline-primary" href="<?php printf('%s?supplier=%s&event=%s', $requestUrl, $supplier, $nextEvent); ?>" title="Événement suivant">
  304. <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right" viewBox="0 0 16 16">
  305. <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"/>
  306. </svg>
  307. </a>
  308. <?php endif; ?>
  309. </div>
  310. </h1>
  311. <?php if (!empty($config[$supplier]['description'])) : ?>
  312. <p class="lead"><?php echo $config[$supplier]['description']; ?></p>
  313. <?php endif; ?>
  314. </div>
  315. </div>
  316. </section>
  317. <section class="container-fluid">
  318. <div class="row g-3">
  319. <form class="js-localremember" action="<?php printf('%s?supplier=%s', $requestUrl, $supplier); ?>" method="post">
  320. <div class="row mb-3">
  321. <label for="title" class="col-sm-2 col-form-label">Nom</label>
  322. <div class="col-sm-10">
  323. <input class="form-control" type="text" name="name" required placeholder="Nom" />
  324. </div>
  325. </div>
  326. <?php if (!empty($config[$supplier]['choices'])) : ?>
  327. <div class="row mb-3">
  328. <label for="title" class="col-sm-2 col-form-label">Choix</label>
  329. <div class="col-sm-10">
  330. <select class="form-select" name="choice" required>
  331. <option/>
  332. <?php foreach ($config[$supplier]['choices'] as $choice) : ?>
  333. <option><?php echo $choice; ?></option>
  334. <?php endforeach; ?>
  335. </select>
  336. </div>
  337. </div>
  338. <?php endif; ?>
  339. <div class="row">
  340. <div class="col mb-3">
  341. <input type="hidden" name="supplier" value="<?php echo $supplier; ?>" />
  342. <input type="hidden" name="event" value="<?php echo $event; ?>" />
  343. <?php if (empty($config[$supplier]['choices'])) : ?>
  344. <input type="hidden" name="choice" value="" />
  345. <?php endif; ?>
  346. <button class="btn btn-primary" type="submit" name="action" value="insert">Commander</button>
  347. </div>
  348. </div>
  349. </form>
  350. </div>
  351. </section>
  352. <section class="container-fluid">
  353. <div class="row my-3">
  354. <div class="col">
  355. <div class="table-responsive">
  356. <table class="table table-striped table-hover align-middle">
  357. <thead>
  358. <tr>
  359. <th scope="col">
  360. Nom
  361. </th>
  362. <?php if (!empty($config[$supplier]['choices'])) : ?>
  363. <th scope="col">
  364. Choix
  365. </th>
  366. <?php endif; ?>
  367. <th scope="col">
  368. &nbsp;
  369. </th>
  370. </tr>
  371. </thead>
  372. <tbody>
  373. <?php foreach ($items as $item) : ?>
  374. <tr>
  375. <td>
  376. <?php echo $item['name']; ?>
  377. </td>
  378. <?php if (!empty($config[$supplier]['choices'])) : ?>
  379. <td>
  380. <?php if (!empty($item['choice'])) : ?>
  381. <?php echo $item['choice']; ?>
  382. <?php endif; ?>
  383. </td>
  384. <?php endif; ?>
  385. <td>
  386. <form onsubmit="return confirm('Souhaitez-vous vraiment annuler cette commande ?');">
  387. <input type="hidden" name="supplier" value="<?php echo $supplier; ?>" />
  388. <input type="hidden" name="event" value="<?php echo $event; ?>" />
  389. <input type="hidden" name="name" value="<?php echo $item['name']; ?>" />
  390. <input type="hidden" name="choice" value="<?php echo $item['choice']; ?>" />
  391. <button class="btn btn-secondary float-end" type="submit" name="action" value="delete">Annuler</button>
  392. </form>
  393. </td>
  394. </tr>
  395. <?php endforeach; ?>
  396. </tbody>
  397. <caption>
  398. Commandes&nbsp;<span class="badge bg-primary rounded-pill"><?php echo count($items); ?></span>
  399. <?php foreach ($stats as $choice => $count) : ?>
  400. /
  401. <?php echo $choice; ?>&nbsp;<span class="badge bg-secondary rounded-pill"><?php echo $count; ?></span>
  402. <?php endforeach; ?>
  403. </caption>
  404. </table>
  405. </div>
  406. </div>
  407. </div>
  408. </section>
  409. <?php endif; ?>
  410. <?php endif; ?>
  411. </main>
  412. <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>
  413. <?php if ($isConfig) : ?>
  414. <script src="https://cdn.ckeditor.com/ckeditor5/31.0.0/classic/ckeditor.js"></script>
  415. <script>
  416. document.querySelectorAll('.js-ckeditor').forEach(function (element) {
  417. ClassicEditor.create(element).catch(error => { console.error(error); });
  418. });
  419. </script>
  420. <?php endif; ?>
  421. <script>
  422. document.querySelectorAll('.js-localremember').forEach(function (form) {
  423. const fields = [ 'name', 'choice' ];
  424. form.addEventListener('submit', function (event) {
  425. fields.forEach(function (field) {
  426. window.localStorage.setItem('mon_panier_bio_' + field, form.elements[field].value);
  427. });
  428. });
  429. fields.forEach(function (field) {
  430. if (
  431. (form.elements[field].value === '')
  432. && (window.localStorage.getItem('mon_panier_bio_' + field) !== null)
  433. ) {
  434. form.elements[field].value = window.localStorage.getItem('mon_panier_bio_' + field);
  435. }
  436. });
  437. });
  438. </script>
  439. </body>
  440. </html>