core.class.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. <?php
  2. /**
  3. * Classe `core`
  4. *
  5. * Cette classe fournit des outils utilitaires pour diverses opérations courantes dans l'application.
  6. *
  7. * Fonctionnalités principales :
  8. * - Gestion des données GET, POST et FILES.
  9. * - Manipulation des dates et des formats.
  10. * - Gestion des configurations de l'application.
  11. * - Génération d'éléments d'interface utilisateur (menus, badges, etc.).
  12. * - Outils divers pour le traitement des chaînes, des fichiers et des données.
  13. *
  14. * @package Core\Class
  15. */
  16. class core
  17. {
  18. /**
  19. * Vérifie si une variable GET est définie.
  20. *
  21. * @param string|null $_string Le nom de la variable GET (optionnel).
  22. * @return bool TRUE si la variable est définie, FALSE sinon.
  23. */
  24. public static function ifGet(?string $_string = NULL)
  25. {
  26. if ($_string == NULL) {
  27. return (empty($_GET)) ? FALSE : TRUE;
  28. } else {
  29. if (isset($_GET[$_string])) {
  30. return TRUE;
  31. } else {
  32. return FALSE;
  33. }
  34. }
  35. }
  36. /**
  37. * Vérifie si une variable POST est définie.
  38. *
  39. * @param string|null $_string Le nom de la variable POST (optionnel).
  40. * @return bool TRUE si la variable est définie, FALSE sinon.
  41. */
  42. public static function ifPost(?string $_string = NULL)
  43. {
  44. if ($_string == NULL) {
  45. return (empty($_POST)) ? FALSE : TRUE;
  46. } else {
  47. if (isset($_POST[$_string])) {
  48. return TRUE;
  49. } else {
  50. return FALSE;
  51. }
  52. }
  53. }
  54. /**
  55. * Vérifie si une variable FILES est définie.
  56. *
  57. * @param string|null $_string Le nom de la variable FILES (optionnel).
  58. * @return bool TRUE si la variable est définie, FALSE sinon.
  59. */
  60. public static function ifFiles(?string $_string = NULL)
  61. {
  62. if ($_string == NULL) {
  63. return (empty($_FILES)) ? FALSE : TRUE;
  64. } else {
  65. if (isset($_FILES[$_string]) and $_FILES[$_string]["size"] > 0) {
  66. return TRUE;
  67. } else {
  68. return FALSE;
  69. }
  70. }
  71. }
  72. /**
  73. * Récupère une variable GET.
  74. *
  75. * @param string|null $_string Le nom de la variable GET (optionnel).
  76. * @return mixed La valeur de la variable GET ou NULL si non définie.
  77. */
  78. public static function getGet(?string $_string = NULL)
  79. {
  80. if ($_string == NULL) {
  81. return $_GET;
  82. } else {
  83. if (isset($_GET[$_string])) {
  84. return $_GET[$_string];
  85. } else {
  86. return NULL;
  87. }
  88. }
  89. }
  90. /**
  91. * Récupère une variable POST.
  92. *
  93. * @param string|null $_string Le nom de la variable POST (optionnel).
  94. * @return mixed La valeur de la variable POST ou NULL si non définie.
  95. */
  96. public static function getPost(?string $_string = NULL)
  97. {
  98. if ($_string == NULL) {
  99. return $_POST;
  100. } else {
  101. if (isset($_POST[$_string])) {
  102. return $_POST[$_string];
  103. } else {
  104. return NULL;
  105. }
  106. }
  107. }
  108. /**
  109. * Récupère une variable FILES.
  110. *
  111. * @param string|null $_string Le nom de la variable FILES (optionnel).
  112. * @return mixed La valeur de la variable FILES ou NULL si non définie.
  113. */
  114. public static function getFiles(?string $_string = NULL)
  115. {
  116. if ($_string == NULL) {
  117. return $_FILES;
  118. } else {
  119. if (isset($_FILES[$_string])) {
  120. return $_FILES[$_string];
  121. } else {
  122. return NULL;
  123. }
  124. }
  125. }
  126. /**
  127. * Vérifie si une chaîne est présente dans un tableau.
  128. *
  129. * @param array $_array Le tableau à vérifier.
  130. * @param string $_string La chaîne à rechercher.
  131. * @param int|null $_exact Indique si la correspondance doit être exacte (1 pour oui, NULL pour non).
  132. * @return bool TRUE si la chaîne est trouvée, FALSE sinon.
  133. */
  134. public static function isInArrayString(array $_array, string $_string, ?int $_exact = NULL)
  135. {
  136. foreach ($_array as $value) {
  137. if (strripos($_string, $value) !== FALSE and $_exact == NULL) {
  138. return TRUE;
  139. } elseif ($_string == $value and $_exact == 1) {
  140. return TRUE;
  141. }
  142. }
  143. return FALSE;
  144. }
  145. /**
  146. * Génère un attribut "checked" pour une case à cocher.
  147. *
  148. * @param bool $_val Indique si la case doit être cochée.
  149. * @param int $_echo Indique si le résultat doit être affiché (1) ou retourné (0).
  150. * @return string|null L'attribut "checked" ou NULL.
  151. */
  152. public static function checkboxSelecter(bool $_val, $_echo = 1)
  153. {
  154. $tmp = ($_val == TRUE) ? "checked" : "";
  155. if ($_echo == 1) {
  156. echo $tmp;
  157. } else {
  158. return $tmp;
  159. }
  160. }
  161. /**
  162. * Récupère toutes les configurations de l'application.
  163. *
  164. * @return array|bool Les configurations ou FALSE en cas d'erreur.
  165. */
  166. public static function getAllConfig()
  167. {
  168. db::query("SELECT "
  169. . "" . DB_T_CONFIG . ".name, "
  170. . "" . DB_T_CONFIG . ".value "
  171. . "FROM " . DB_T_CONFIG);
  172. return db::resultset();
  173. }
  174. /**
  175. * Récupère une configuration spécifique de l'application.
  176. *
  177. * @param string $_name Le nom de la configuration.
  178. * @return mixed La valeur de la configuration.
  179. */
  180. public static function getConfig(string $_name)
  181. {
  182. db::query("SELECT value FROM " . DB_T_CONFIG . " WHERE name = :name");
  183. db::bind(':name', $_name);
  184. return db::single()["value"];
  185. }
  186. /**
  187. * Met à jour une configuration de l'application.
  188. *
  189. * @param string $_name Le nom de la configuration.
  190. * @param string $_value La nouvelle valeur de la configuration.
  191. * @return bool TRUE si la mise à jour a réussi, FALSE sinon.
  192. */
  193. public static function updateConfig(string $_name, string $_value)
  194. {
  195. db::query("UPDATE " . DB_T_CONFIG . " SET "
  196. . "value = :value "
  197. . "WHERE name = :name");
  198. db::bind(':value', $_value);
  199. db::bind(':name', $_name);
  200. try {
  201. db::execute();
  202. return TRUE;
  203. } catch (Exception $ex) {
  204. return FALSE;
  205. }
  206. }
  207. /**
  208. * Supprime les accents d'une chaîne de caractères.
  209. *
  210. * @param string $_data La chaîne à traiter.
  211. * @return string La chaîne sans accents.
  212. */
  213. public static function cleanAccent(string $_data)
  214. {
  215. $search = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ò', 'ó', 'ô', 'õ', 'ö', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ');
  216. $replace = array('A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y');
  217. $return = str_replace($search, $replace, $_data);
  218. return strtoupper($return);
  219. }
  220. /**
  221. * Convertit une date MySQL en format français.
  222. *
  223. * @param string $_datetime La date au format MySQL.
  224. * @param bool $_hour Indique si l'heure doit être incluse.
  225. * @return string La date au format français.
  226. */
  227. public static function convertDate(string $_datetime, bool $_hour = TRUE)
  228. {
  229. $pieces = explode(" ", $_datetime);
  230. if ($_hour == TRUE) {
  231. $pieces3 = explode(":", $pieces[1]);
  232. }
  233. $pieces2 = explode("-", $pieces[0]);
  234. if ($_hour == TRUE) {
  235. return $pieces2[2] . "/" . $pieces2[1] . "/" . $pieces2[0] . " à " . $pieces3[0] . ":" . $pieces3[1];
  236. } else {
  237. return $pieces2[2] . "/" . $pieces2[1] . "/" . $pieces2[0];
  238. }
  239. }
  240. /**
  241. * Retourne la date actuelle au format français.
  242. *
  243. * @param string|null $_timestampMysql Le timestamp MySQL (optionnel).
  244. * @return string|DateTime La date au format français ou un objet DateTime.
  245. */
  246. public static function dateFr(?string $_timestampMysql = NULL)
  247. {
  248. if ($_timestampMysql == NULL) {
  249. $Now = new DateTime('now', new DateTimeZone(TIME_ZONE));
  250. return $Now->format("d/m/Y H:i:s");
  251. } else {
  252. return DateTime::createFromFormat("d/m/Y H:i:s", $_timestampMysql);
  253. }
  254. }
  255. /**
  256. * Convertit un timestamp en date.
  257. *
  258. * @param int|null $_timestamp Le timestamp à convertir (optionnel).
  259. * @return string|null La date au format MySQL ou NULL si aucun timestamp n'est fourni.
  260. */
  261. public static function dateFromTimestamp(?int $_timestamp = NULL)
  262. {
  263. if ($_timestamp == NULL) {
  264. return NULL;
  265. } else {
  266. return date("Y-m-d H:i:s", $_timestamp);
  267. }
  268. }
  269. /**
  270. * Extrait la date sans l'heure d'une chaîne datetime.
  271. *
  272. * @param string $_datetime La chaîne datetime.
  273. * @return string La date sans l'heure.
  274. */
  275. public static function dateWhithoutHours(string $_datetime)
  276. {
  277. return explode(" ", $_datetime)[0];
  278. }
  279. /**
  280. * Formate une taille de fichier en unités lisibles.
  281. *
  282. * @param float $_size La taille en octets.
  283. * @param int $_decimalplaces Le nombre de décimales à inclure.
  284. * @return string La taille formatée.
  285. */
  286. public static function formatFileSize(float $_size, int $_decimalplaces = 0)
  287. {
  288. $sizes = array('O', 'Ko', 'Mo', 'Go', 'To');
  289. for ($i = 0; $_size > 1024 && $i < count($sizes) - 1; $i++) {
  290. $_size /= 1024;
  291. }
  292. return round($_size, $_decimalplaces) . ' ' . $sizes[$i];
  293. }
  294. /**
  295. * Formate un montant en euros.
  296. *
  297. * @param float $_amount Le montant à formater.
  298. * @return string Le montant formaté en euros.
  299. */
  300. public static function formatEuro($_amount)
  301. {
  302. $amount = (float)$_amount;
  303. $formattedAmount = number_format($amount, 2, ',', ' ');
  304. return $formattedAmount . ' €';
  305. }
  306. /**
  307. * Vérifie si une chaîne ne contient que des caractères alphabétiques.
  308. *
  309. * @param string $_string La chaîne à vérifier.
  310. * @return bool TRUE si la chaîne contient uniquement des lettres, FALSE sinon.
  311. */
  312. public static function checkStringOnly(string $_string)
  313. {
  314. if (!ctype_alpha($_string)) {
  315. return TRUE;
  316. } else {
  317. return FALSE;
  318. }
  319. }
  320. /**
  321. * Génère un élément de menu.
  322. *
  323. * @param string $_id L'identifiant de l'élément de menu.
  324. * @param string $_href L'URL de destination.
  325. * @param string $_titre Le titre de l'élément de menu.
  326. * @param string|null $_style Le style CSS à appliquer (optionnel).
  327. * @param string|null $_icon L'icône à afficher (optionnel).
  328. * @return void
  329. */
  330. public static function elementMenu(string $_id, string $_href, string $_titre, ?string $_style = NULL, ?string $_icon = NULL)
  331. {
  332. if (access::ifAccesss($_id)) {
  333. ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
  334. echo '<li class="nav-item" style="margin:5px 0;"><a style="display:unset;" class="nav-link' . get::currentPage($_id) . '" aria-current="page" href="' . $_href . '"' . $_style . '>';
  335. echo (preg_match('/^compte-\d+$/', $_id)) ? icon::getFont(["type" => $_icon, "size" => "18px"]) : icon::getFont(["type" => $_id, "size" => "18px"]);
  336. echo ' ' . $_titre . '</a></li>';
  337. }
  338. }
  339. /**
  340. * Génère un élément de menu avec un lien.
  341. *
  342. * @param string $_id L'identifiant de l'élément de menu.
  343. * @param string $_href L'URL de destination.
  344. * @param string $_titre Le titre de l'élément de menu.
  345. * @param string|null $_style Le style CSS à appliquer (optionnel).
  346. * @param string $_target La cible du lien (par défaut "_blank").
  347. * @return void
  348. */
  349. public static function elementMenuLink(string $_id, string $_href, string $_titre, ?string $_style = NULL, string $_target = "_blank")
  350. {
  351. if (access::ifAccesss($_id)) {
  352. ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
  353. echo '<li class="nav-item" style="margin:5px 0;"><a style="display:unset;" class="nav-link" target="' . $_target . '" href="' . $_href . '"' . $_style . '>';
  354. echo icon::getFont(["type" => $_id, "size" => "18px"]);
  355. echo ' ' . $_titre . '</a></li>';
  356. }
  357. }
  358. /**
  359. * Génère un en-tête de section.
  360. *
  361. * @param string $_id L'identifiant de l'en-tête.
  362. * @param string $_titre Le titre de l'en-tête.
  363. * @param string|null $_style Le style CSS à appliquer (optionnel).
  364. * @param string|null $_collapse L'identifiant de la section à réduire/étendre (optionnel).
  365. * @return void
  366. */
  367. public static function elementMenuH6(string $_id, string $_titre, ?string $_style = NULL, ?string $_collapse = NULL)
  368. {
  369. if (access::ifAccesss($_id)) {
  370. ($_style != NULL) ? $_style = $_style : NULL;
  371. echo '<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
  372. <a style="text-decoration: none; ' . $_style . '" href="#' . $_collapse . '" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle text-dark">' . $_titre . '</a>
  373. </h6>';
  374. }
  375. }
  376. /**
  377. * Génère une fil d'Ariane (breadcrumb).
  378. *
  379. * @param array $_arbo Les éléments de la fil d'Ariane.
  380. * @return string Le code HTML de la fil d'Ariane.
  381. */
  382. public static function filAriane(array $_arbo)
  383. {
  384. $return = '<nav aria-label="breadcrumb bg-300">';
  385. $return .= '<ol class="breadcrumb" style="padding:5px 10px; border-bottom: 1px solid #e9ecef;">';
  386. foreach ($_arbo["arbo"] as $label => $lien) {
  387. if ($_arbo["current"] == $label) {
  388. $return .= '<li class="breadcrumb-item active" aria-current="page"';
  389. if (isset($_arbo["refresh-json"])) {
  390. $return .= 'title="Cliquez ici pour rafraichir les données Json" onclick="return confirm(\'Voulez-vous rafraichir les données Json?\')" id="json-refresh"><a href="#" style="text-decoration:none;">' . icon::getFont(["icon" => "bi bi-arrow-clockwise"]) . ' ';
  391. } else {
  392. $return .= '>';
  393. }
  394. $return .= $label;
  395. if (isset($_arbo["refresh-json"])) {
  396. $return .= '</a>';
  397. }
  398. $return .= '</li>';
  399. } elseif ($lien == NULL) {
  400. $return .= '<li class="breadcrumb-item">' . $label . '</li>';
  401. } else {
  402. $return .= '<li class="breadcrumb-item"><a href="' . $lien . '" title="' . $label . '">' . $label . '</a></li>';
  403. }
  404. }
  405. $return .= '</ol>';
  406. $return .= '</nav>';
  407. if (isset($_arbo["refresh-json"])) {
  408. $return .= "<script>
  409. $('#json-refresh').on('click', function() {
  410. $.ajax({
  411. url: '/json.refresh.php',
  412. type: 'GET',
  413. data: {
  414. data: '" . $_arbo["refresh-json"] . "'
  415. },
  416. success: function(response) {
  417. $('#printToastSuccessTxt').html('Mise à jour du Json. Rechargement dans quelques secondes...');
  418. $('#printToastSuccess').toast('show');
  419. $('#printToastSuccess').on('hidden.bs.toast', function () {
  420. location.reload();
  421. });
  422. },
  423. error: function(xhr, status, error) {
  424. $('#printToastErrorTxt').html('Erreur lors de la mise à jour du Json');
  425. $('#printToastError').toast('show');
  426. }
  427. });
  428. });
  429. </script>";
  430. }
  431. return $return;
  432. }
  433. /**
  434. * Calcule un pourcentage.
  435. *
  436. * @param int|null $_nombre Le nombre partiel.
  437. * @param int|null $_total Le nombre total.
  438. * @param int $_pourcentage Le pourcentage à calculer (par défaut 100).
  439. * @return int Le pourcentage calculé.
  440. */
  441. public static function caculPourcentage(?int $_nombre, ?int $_total, int $_pourcentage = 100)
  442. {
  443. if ($_nombre == NULL) return 0;
  444. $resultat = ($_nombre / $_total) * $_pourcentage;
  445. return round($resultat);
  446. }
  447. /**
  448. * Encode une chaîne en UTF-8.
  449. *
  450. * @param string $_data La chaîne à encoder.
  451. * @return string La chaîne encodée en UTF-8.
  452. */
  453. public static function encodeUTF8(string $_data)
  454. {
  455. return (mb_detect_encoding($_data) != "UTF-8") ? mb_convert_encoding($_data, 'UTF-8', mb_list_encodings()) : $_data;
  456. }
  457. /**
  458. * Vérifie la connexion à Internet.
  459. *
  460. * @return bool TRUE si connecté, FALSE sinon.
  461. */
  462. public static function testConnexionInternet()
  463. {
  464. $hosts = ['1.1.1.1', '1.0.0.1', '8.8.8.8', '8.8.4.4'];
  465. foreach ($hosts as $host) {
  466. if ($connected = @fsockopen($host, 443)) {
  467. fclose($connected);
  468. return TRUE;
  469. }
  470. }
  471. return FALSE;
  472. }
  473. /**
  474. * Retourne la date et l'heure actuelles au format texte.
  475. *
  476. * @return string La date et l'heure au format texte.
  477. */
  478. public static function printDateTxt()
  479. {
  480. $date = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE);
  481. return $date->format(time()) . " à " . date("H:i:s");
  482. }
  483. /**
  484. * Réinitialise les données dans la base de données.
  485. *
  486. * @return void
  487. */
  488. public static function resetDatas()
  489. {
  490. db::query("TRUNCATE " . DB_T_TEMP_SALARIES);
  491. db::execute();
  492. json::delete("tmp_salaries");
  493. db::query("TRUNCATE " . DB_T_SALARIES);
  494. db::execute();
  495. json::delete("salaries");
  496. db::query("TRUNCATE " . DB_T_FILES);
  497. db::execute();
  498. file::cleanAllFiles(DIR_DATAS_FILES);
  499. db::query("TRUNCATE " . DB_T_EXCEL);
  500. db::execute();
  501. json::delete("excel");
  502. db::query("TRUNCATE " . DB_T_SALARIES_PROWEB);
  503. db::execute();
  504. json::delete("salaries-proweb");
  505. db::query("TRUNCATE " . DB_T_EVENTS_INSCRITS);
  506. db::execute();
  507. db::query("TRUNCATE " . DB_T_EVENTS);
  508. db::execute();
  509. json::delete("events");
  510. db::query("TRUNCATE " . DB_T_EXCEL_PROWEB);
  511. db::execute();
  512. json::delete("excel-proweb");
  513. file::cleanAllFiles(SFTP_LOCAL);
  514. }
  515. /**
  516. * Encode une chaîne en base64 pour une utilisation dans une URL.
  517. *
  518. * @param string $val La chaîne à encoder.
  519. * @return string La chaîne encodée en base64.
  520. */
  521. public static function base64_url_encode(string $val)
  522. {
  523. return strtr(base64_encode($val), '+/=', '-_,');
  524. }
  525. /**
  526. * Décode une chaîne base64 encodée pour une utilisation dans une URL.
  527. *
  528. * @param string $val La chaîne à décoder.
  529. * @return string La chaîne décodée.
  530. */
  531. public static function base64_url_decode(string $val)
  532. {
  533. return base64_decode(strtr($val, '-_,', '+/='));
  534. }
  535. /**
  536. * Convertit un texte en UTF-8 si nécessaire.
  537. *
  538. * @param string $_texte Le texte à convertir.
  539. * @return string Le texte converti en UTF-8.
  540. */
  541. public static function convertirEnUtf8(string $_texte)
  542. {
  543. if (!mb_detect_encoding($_texte, 'UTF-8', TRUE)) {
  544. return mb_convert_encoding($_texte, 'UTF-8', 'auto');
  545. } else {
  546. return $_texte;
  547. }
  548. }
  549. /**
  550. * Imprime une option sélectionnée dans un formulaire.
  551. *
  552. * @param mixed $_value La valeur à comparer.
  553. * @param string|null $_string La valeur de l'option.
  554. * @return void
  555. */
  556. public static function printFormSelectOption($_value, ?string $_string = NULL)
  557. {
  558. if ($_string != NULL and $_string == $_value) {
  559. echo " selected";
  560. }
  561. }
  562. /**
  563. * Récupère la valeur d'un formulaire.
  564. *
  565. * @param string|null $_string La valeur à récupérer.
  566. * @return string|null La valeur récupérée ou NULL.
  567. */
  568. public static function getFormValue(?string $_string = NULL)
  569. {
  570. if ($_string != NULL) {
  571. return $_string;
  572. }
  573. }
  574. /**
  575. * Imprime la valeur d'un formulaire.
  576. *
  577. * @param string|null $_string La valeur à imprimer.
  578. * @return void
  579. */
  580. public static function printFormValue(?string $_string = NULL)
  581. {
  582. if ($_string != NULL) {
  583. echo $_string;
  584. }
  585. }
  586. /**
  587. * Convertit des octets entre différentes unités.
  588. *
  589. * @param float $val La valeur à convertir.
  590. * @param string $type_val L'unité d'origine.
  591. * @param string $type_wanted L'unité cible.
  592. * @param bool $_float Indique si le résultat doit être un flottant.
  593. * @return string La valeur convertie avec l'unité cible.
  594. */
  595. public static function convertBytes(float $val, string $type_val = "o", string $type_wanted = "Mo", bool $_float = FALSE)
  596. {
  597. $tab_val = array("o", "ko", "Mo", "Go", "To", "Po", "Eo");
  598. if (!(in_array($type_val, $tab_val) && in_array($type_wanted, $tab_val)))
  599. return 0;
  600. $tab = array_flip($tab_val);
  601. $diff = $tab[$type_val] - $tab[$type_wanted];
  602. $type_wanted_print = $_float == FALSE ? $type_wanted : NULL;
  603. if ($diff > 0)
  604. return round(($val * pow(1024, $diff)), 2) . $type_wanted_print;
  605. if ($diff < 0)
  606. return round(($val / pow(1024, -$diff)), 2) . $type_wanted_print;
  607. return round(($val), 2) . $type_wanted_print;
  608. }
  609. /**
  610. * Récupère la taille de la base de données.
  611. *
  612. * @return array Les informations sur la taille de la base de données.
  613. */
  614. public static function getSizeDataBase()
  615. {
  616. db::query("SELECT
  617. table_schema AS nameDB,
  618. ROUND(SUM( data_length + index_length ) / 1024 / 1024, 2) AS moDB
  619. FROM information_schema.TABLES
  620. WHERE TABLE_SCHEMA = '" . DB_NAME . "'");
  621. return db::single();
  622. }
  623. /**
  624. * Génère une barre de progression avec des avertissements.
  625. *
  626. * @param float $_num La valeur actuelle.
  627. * @param float $_max La valeur maximale.
  628. * @param string $_label L'étiquette de la barre de progression.
  629. * @param string $_icon L'icône à afficher.
  630. * @return void
  631. */
  632. public static function progressBarWarning(float $_num, float $_max, string $_label, string $_icon)
  633. {
  634. $changeUnit = 1073741824;
  635. $valueUnitNum = $_num >= $changeUnit ? "Go" : "Mo";
  636. $valueUnitMax = $_max >= $changeUnit ? "Go" : "Mo";
  637. $pourcentage = number_format(($_num / $_max) * 100, 2);
  638. if ($pourcentage < 50) {
  639. $infos = ["color" => "bg-success"];
  640. } elseif ($pourcentage < 75) {
  641. $infos = ["color" => "bg-warning"];
  642. } else {
  643. $infos = ["color" => "bg-danger"];
  644. }
  645. echo ' <div class="mb-3" style="margin:10px 0;">
  646. <label class="form-label" style=""><i class="' . $_icon . '" style="font-size:18px; margin:4px;"></i> <span style="font-weight: bold;">' . $_label . '</span> [' . core::convertBytes($_num, "o", $valueUnitNum) . ' / ' . core::convertBytes($_max, "o", $valueUnitMax) . ']</label>
  647. <div class="progress" role="progressbar" aria-label="Success example" aria-valuenow="' . $pourcentage . '" aria-valuemin="0" aria-valuemax="100">
  648. <div class="progress-bar ' . $infos["color"] . '" style="width: ' . $pourcentage . '%">' . $pourcentage . '%</div>
  649. </div>
  650. </div>';
  651. }
  652. /**
  653. * Génère un badge d'alerte si nécessaire.
  654. *
  655. * @param bool $_alerte Indique si l'alerte doit être affichée.
  656. * @return string|null Le code HTML du badge ou NULL.
  657. */
  658. static public function printBadgeGeneral(bool $_alerte)
  659. {
  660. return $_alerte == TRUE ? '<span class="position-absolute start-100 translate-middle p-1 bg-danger border border-light rounded-circle"></span>' : NULL;
  661. }
  662. /**
  663. * Vérifie les alertes pour les documents.
  664. *
  665. * @return array Les informations sur les alertes.
  666. */
  667. static public function ifbadge()
  668. {
  669. $return = [];
  670. $return["DOC"] = document::badgeAlert();
  671. if ($return["DOC"] != NULL) {
  672. $return["ALERTE"] = TRUE;
  673. } else {
  674. $return["ALERTE"] = FALSE;
  675. }
  676. return $return;
  677. }
  678. /**
  679. * Génère un menu de navigation.
  680. *
  681. * @param array $_navInfos Les informations de navigation.
  682. * @return void
  683. */
  684. static public function menu(array $_navInfos)
  685. {
  686. $badge = self::ifbadge();
  687. echo '<a href="/" style="box-shadow: none; background-color:' . $_navInfos["color"] . ';" class="navbar-brand">' . $_navInfos["title"] . '</a>' . debug::getBadges();
  688. echo '<div id="navbarCollapse" class="collapse navbar-collapse p-0">';
  689. echo '<ul class="nav navbar-nav ms-auto">';
  690. echo '<li class="nav-item dropdown">';
  691. echo '<a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">' . session::getName() . self::printBadgeGeneral($badge["ALERTE"]) . '</a>';
  692. echo '<div class="dropdown-menu dropdown-menu-end">';
  693. echo '<a href="/user.html" class="dropdown-item">Mon profil</a>';
  694. if ((access::ifAccesss("documents") and session::getType() == 5) or session::getType() == 1) { // Membre du bureau ou Admin
  695. $nb = $badge["DOC"] > 0 ? '<span class="position-absolute badge rounded-pill bg-danger" style="right:-10px; margin-top:-10px;">' . $badge["DOC"] . '</span>' : NULL;
  696. echo '<a href="/documents-my-assign.html" class="dropdown-item">Vos assignations' . $nb . '</a>';
  697. echo '<a href="/alertes-emails.html" class="dropdown-item">Vos règles d\'alertes</a>';
  698. }
  699. echo '<div class="dropdown-divider"></div>';
  700. echo '<a href="/submit.php?from=logout" class="dropdown-item">Se déconnecter</a>';
  701. echo '</li>';
  702. echo '</div>';
  703. echo '</ul>';
  704. echo '</div>';
  705. }
  706. /**
  707. * Récupère l'adresse IP de l'utilisateur.
  708. *
  709. * @return string L'adresse IP de l'utilisateur.
  710. */
  711. static public function getUserIP()
  712. {
  713. $ip = 'Inconnue';
  714. if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  715. // IP partagée par un proxy
  716. $ip = $_SERVER['HTTP_CLIENT_IP'];
  717. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  718. // IP du client derrière un proxy
  719. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  720. } else {
  721. // IP du client directement connectée au serveur
  722. $ip = $_SERVER['REMOTE_ADDR'];
  723. }
  724. // Nettoyage des IPs multiples dans le cas de 'HTTP_X_FORWARDED_FOR'
  725. if (strpos($ip, ',') !== false) {
  726. $ip = explode(',', $ip)[0];
  727. }
  728. return $ip;
  729. }
  730. /**
  731. * Aplatit un tableau multidimensionnel.
  732. *
  733. * @param array|null $_array Le tableau à aplatir (optionnel).
  734. * @return array|null Le tableau aplati ou NULL.
  735. */
  736. static public function extractArrayInArray(?array $_array = NULL)
  737. {
  738. if ($_array != NULL) {
  739. foreach ($_array as $item) {
  740. foreach ($item as $key => $value) {
  741. $flattened[$key] = $value;
  742. }
  743. }
  744. } else {
  745. $flattened = NULL;
  746. }
  747. return $flattened;
  748. }
  749. }