core.class.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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. $amount = (float)$_amount;
  302. $formattedAmount = number_format($amount, 2, ',', ' ');
  303. return $formattedAmount . ' €';
  304. }
  305. /**
  306. * Vérifie si une chaîne ne contient que des caractères alphabétiques.
  307. *
  308. * @param string $_string La chaîne à vérifier.
  309. * @return bool TRUE si la chaîne contient uniquement des lettres, FALSE sinon.
  310. */
  311. public static function checkStringOnly(string $_string)
  312. {
  313. if (!ctype_alpha($_string)) {
  314. return TRUE;
  315. } else {
  316. return FALSE;
  317. }
  318. }
  319. /**
  320. * Génère un élément de menu.
  321. *
  322. * @param string $_id L'identifiant de l'élément de menu.
  323. * @param string $_href L'URL de destination.
  324. * @param string $_titre Le titre de l'élément de menu.
  325. * @param string|null $_style Le style CSS à appliquer (optionnel).
  326. * @param string|null $_icon L'icône à afficher (optionnel).
  327. * @return void
  328. */
  329. public static function elementMenu(string $_id, string $_href, string $_titre, ?string $_style = NULL, ?string $_icon = NULL)
  330. {
  331. if (access::ifAccesss($_id)) {
  332. ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
  333. 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 . '>';
  334. echo (preg_match('/^compte-\d+$/', $_id)) ? icon::getFont(["type" => $_icon, "size" => "18px"]) : icon::getFont(["type" => $_id, "size" => "18px"]);
  335. echo ' ' . $_titre . '</a></li>';
  336. }
  337. }
  338. /**
  339. * Génère un élément de menu avec un lien.
  340. *
  341. * @param string $_id L'identifiant de l'élément de menu.
  342. * @param string $_href L'URL de destination.
  343. * @param string $_titre Le titre de l'élément de menu.
  344. * @param string|null $_style Le style CSS à appliquer (optionnel).
  345. * @param string $_target La cible du lien (par défaut "_blank").
  346. * @return void
  347. */
  348. public static function elementMenuLink(string $_id, string $_href, string $_titre, ?string $_style = NULL, string $_target = "_blank")
  349. {
  350. if (access::ifAccesss($_id)) {
  351. ($_style != NULL) ? $_style = ' style="' . $_style . '"' : NULL;
  352. echo '<li class="nav-item" style="margin:5px 0;"><a style="display:unset;" class="nav-link" target="' . $_target . '" href="' . $_href . '"' . $_style . '>';
  353. echo icon::getFont(["type" => $_id, "size" => "18px"]);
  354. echo ' ' . $_titre . '</a></li>';
  355. }
  356. }
  357. /**
  358. * Génère un en-tête de section.
  359. *
  360. * @param string $_id L'identifiant de l'en-tête.
  361. * @param string $_titre Le titre de l'en-tête.
  362. * @param string|null $_style Le style CSS à appliquer (optionnel).
  363. * @param string|null $_collapse L'identifiant de la section à réduire/étendre (optionnel).
  364. * @return void
  365. */
  366. public static function elementMenuH6(string $_id, string $_titre, ?string $_style = NULL, ?string $_collapse = NULL)
  367. {
  368. if (access::ifAccesss($_id)) {
  369. ($_style != NULL) ? $_style = $_style : NULL;
  370. echo '<h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
  371. <a style="text-decoration: none; ' . $_style . '" href="#' . $_collapse . '" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle text-dark">' . $_titre . '</a>
  372. </h6>';
  373. }
  374. }
  375. /**
  376. * Génère une fil d'Ariane (breadcrumb).
  377. *
  378. * @param array $_arbo Les éléments de la fil d'Ariane.
  379. * @return string Le code HTML de la fil d'Ariane.
  380. */
  381. public static function filAriane(array $_arbo)
  382. {
  383. $return = '<nav aria-label="breadcrumb bg-300">';
  384. $return .= '<ol class="breadcrumb" style="padding:5px 10px; border-bottom: 1px solid #e9ecef;">';
  385. foreach ($_arbo["arbo"] as $label => $lien) {
  386. if ($_arbo["current"] == $label) {
  387. $return .= '<li class="breadcrumb-item active" aria-current="page"';
  388. if(isset($_arbo["refresh-json"])){
  389. $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"]) . ' ';
  390. } else {
  391. $return .= '>';
  392. }
  393. $return .= $label;
  394. if(isset($_arbo["refresh-json"])){
  395. $return .= '</a>';
  396. }
  397. $return .= '</li>';
  398. } elseif ($lien == NULL) {
  399. $return .= '<li class="breadcrumb-item">' . $label . '</li>';
  400. } else {
  401. $return .= '<li class="breadcrumb-item"><a href="' . $lien . '" title="' . $label . '">' . $label . '</a></li>';
  402. }
  403. }
  404. $return .= '</ol>';
  405. $return .= '</nav>';
  406. if(isset($_arbo["refresh-json"])){
  407. $return .= "<script>
  408. $('#json-refresh').on('click', function() {
  409. $.ajax({
  410. url: '/json.refresh.php',
  411. type: 'GET',
  412. data: {
  413. data: '" . $_arbo["refresh-json"] . "'
  414. },
  415. success: function(response) {
  416. $('#printToastSuccessTxt').html('Mise à jour du Json. Rechargement dans quelques secondes...');
  417. $('#printToastSuccess').toast('show');
  418. $('#printToastSuccess').on('hidden.bs.toast', function () {
  419. location.reload();
  420. });
  421. },
  422. error: function(xhr, status, error) {
  423. $('#printToastErrorTxt').html('Erreur lors de la mise à jour du Json');
  424. $('#printToastError').toast('show');
  425. }
  426. });
  427. });
  428. </script>";
  429. }
  430. return $return;
  431. }
  432. /**
  433. * Calcule un pourcentage.
  434. *
  435. * @param int|null $_nombre Le nombre partiel.
  436. * @param int|null $_total Le nombre total.
  437. * @param int $_pourcentage Le pourcentage à calculer (par défaut 100).
  438. * @return int Le pourcentage calculé.
  439. */
  440. public static function caculPourcentage(?int $_nombre, ?int $_total, int $_pourcentage = 100)
  441. {
  442. if ($_nombre == NULL) return 0;
  443. $resultat = ($_nombre / $_total) * $_pourcentage;
  444. return round($resultat);
  445. }
  446. /**
  447. * Encode une chaîne en UTF-8.
  448. *
  449. * @param string $_data La chaîne à encoder.
  450. * @return string La chaîne encodée en UTF-8.
  451. */
  452. public static function encodeUTF8(string $_data)
  453. {
  454. return (mb_detect_encoding($_data) != "UTF-8") ? mb_convert_encoding($_data, 'UTF-8', mb_list_encodings()) : $_data;
  455. }
  456. /**
  457. * Vérifie la connexion à Internet.
  458. *
  459. * @return bool TRUE si connecté, FALSE sinon.
  460. */
  461. public static function testConnexionInternet()
  462. {
  463. $hosts = ['1.1.1.1', '1.0.0.1', '8.8.8.8', '8.8.4.4'];
  464. foreach ($hosts as $host) {
  465. if ($connected = @fsockopen($host, 443)) {
  466. fclose($connected);
  467. return TRUE;
  468. }
  469. }
  470. return FALSE;
  471. }
  472. /**
  473. * Retourne la date et l'heure actuelles au format texte.
  474. *
  475. * @return string La date et l'heure au format texte.
  476. */
  477. public static function printDateTxt()
  478. {
  479. $date = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::NONE);
  480. return $date->format(time()) . " à " . date("H:i:s");
  481. }
  482. /**
  483. * Réinitialise les données dans la base de données.
  484. *
  485. * @return void
  486. */
  487. public static function resetDatas()
  488. {
  489. db::query("TRUNCATE " . DB_T_TEMP_SALARIES);
  490. db::execute();
  491. json::delete("tmp_salaries");
  492. db::query("TRUNCATE " . DB_T_SALARIES);
  493. db::execute();
  494. json::delete("salaries");
  495. db::query("TRUNCATE " . DB_T_FILES);
  496. db::execute();
  497. file::cleanAllFiles(DIR_DATAS_FILES);
  498. db::query("TRUNCATE " . DB_T_EXCEL);
  499. db::execute();
  500. json::delete("excel");
  501. db::query("TRUNCATE " . DB_T_SALARIES_PROWEB);
  502. db::execute();
  503. json::delete("salaries-proweb");
  504. db::query("TRUNCATE " . DB_T_EVENTS_INSCRITS);
  505. db::execute();
  506. db::query("TRUNCATE " . DB_T_EVENTS);
  507. db::execute();
  508. json::delete("events");
  509. db::query("TRUNCATE " . DB_T_EXCEL_PROWEB);
  510. db::execute();
  511. json::delete("excel-proweb");
  512. file::cleanAllFiles(SFTP_LOCAL);
  513. }
  514. /**
  515. * Encode une chaîne en base64 pour une utilisation dans une URL.
  516. *
  517. * @param string $val La chaîne à encoder.
  518. * @return string La chaîne encodée en base64.
  519. */
  520. public static function base64_url_encode(string $val)
  521. {
  522. return strtr(base64_encode($val), '+/=', '-_,');
  523. }
  524. /**
  525. * Décode une chaîne base64 encodée pour une utilisation dans une URL.
  526. *
  527. * @param string $val La chaîne à décoder.
  528. * @return string La chaîne décodée.
  529. */
  530. public static function base64_url_decode(string $val)
  531. {
  532. return base64_decode(strtr($val, '-_,', '+/='));
  533. }
  534. /**
  535. * Convertit un texte en UTF-8 si nécessaire.
  536. *
  537. * @param string $_texte Le texte à convertir.
  538. * @return string Le texte converti en UTF-8.
  539. */
  540. public static function convertirEnUtf8(string $_texte)
  541. {
  542. if (!mb_detect_encoding($_texte, 'UTF-8', TRUE)) {
  543. return mb_convert_encoding($_texte, 'UTF-8', 'auto');
  544. } else {
  545. return $_texte;
  546. }
  547. }
  548. /**
  549. * Imprime une option sélectionnée dans un formulaire.
  550. *
  551. * @param string|null $_string La valeur de l'option.
  552. * @param mixed $_value La valeur à comparer.
  553. * @return void
  554. */
  555. public static function printFormSelectOption(?string $_string = NULL, $_value)
  556. {
  557. if ($_string != NULL and $_string == $_value) {
  558. echo " selected";
  559. }
  560. }
  561. /**
  562. * Récupère la valeur d'un formulaire.
  563. *
  564. * @param string|null $_string La valeur à récupérer.
  565. * @return string|null La valeur récupérée ou NULL.
  566. */
  567. public static function getFormValue(?string $_string = NULL)
  568. {
  569. if ($_string != NULL) {
  570. return $_string;
  571. }
  572. }
  573. /**
  574. * Imprime la valeur d'un formulaire.
  575. *
  576. * @param string|null $_string La valeur à imprimer.
  577. * @return void
  578. */
  579. public static function printFormValue(?string $_string = NULL)
  580. {
  581. if ($_string != NULL) {
  582. echo $_string;
  583. }
  584. }
  585. /**
  586. * Convertit des octets entre différentes unités.
  587. *
  588. * @param float $val La valeur à convertir.
  589. * @param string $type_val L'unité d'origine.
  590. * @param string $type_wanted L'unité cible.
  591. * @param bool $_float Indique si le résultat doit être un flottant.
  592. * @return string La valeur convertie avec l'unité cible.
  593. */
  594. public static function convertBytes(float $val, string $type_val = "o", string $type_wanted = "Mo", bool $_float = FALSE)
  595. {
  596. $tab_val = array("o", "ko", "Mo", "Go", "To", "Po", "Eo");
  597. if (!(in_array($type_val, $tab_val) && in_array($type_wanted, $tab_val)))
  598. return 0;
  599. $tab = array_flip($tab_val);
  600. $diff = $tab[$type_val] - $tab[$type_wanted];
  601. $type_wanted_print = $_float == FALSE ? $type_wanted : NULL;
  602. if ($diff > 0)
  603. return round(($val * pow(1024, $diff)), 2) . $type_wanted_print;
  604. if ($diff < 0)
  605. return round(($val / pow(1024, -$diff)), 2) . $type_wanted_print;
  606. return round(($val), 2) . $type_wanted_print;
  607. }
  608. /**
  609. * Récupère la taille de la base de données.
  610. *
  611. * @return array Les informations sur la taille de la base de données.
  612. */
  613. public static function getSizeDataBase(){
  614. db::query("SELECT
  615. table_schema AS nameDB,
  616. ROUND(SUM( data_length + index_length ) / 1024 / 1024, 2) AS moDB
  617. FROM information_schema.TABLES
  618. WHERE TABLE_SCHEMA = '".DB_NAME."'");
  619. return db::single();
  620. }
  621. /**
  622. * Génère une barre de progression avec des avertissements.
  623. *
  624. * @param float $_num La valeur actuelle.
  625. * @param float $_max La valeur maximale.
  626. * @param string $_label L'étiquette de la barre de progression.
  627. * @param string $_icon L'icône à afficher.
  628. * @return void
  629. */
  630. public static function progressBarWarning(float $_num, float $_max, string $_label, string $_icon){
  631. $changeUnit = 1073741824;
  632. $valueUnitNum = $_num >= $changeUnit ? "Go" : "Mo";
  633. $valueUnitMax = $_max >= $changeUnit ? "Go" : "Mo";
  634. $pourcentage = number_format(($_num / $_max) * 100, 2);
  635. if($pourcentage < 50){
  636. $infos = ["color" => "bg-success"];
  637. } elseif($pourcentage < 75){
  638. $infos = ["color" => "bg-warning"];
  639. } else {
  640. $infos = ["color" => "bg-danger"];
  641. }
  642. echo ' <div class="mb-3" style="margin:10px 0;">
  643. <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>
  644. <div class="progress" role="progressbar" aria-label="Success example" aria-valuenow="'.$pourcentage.'" aria-valuemin="0" aria-valuemax="100">
  645. <div class="progress-bar '.$infos["color"].'" style="width: '.$pourcentage.'%">'.$pourcentage.'%</div>
  646. </div>
  647. </div>';
  648. }
  649. /**
  650. * Génère un badge d'alerte si nécessaire.
  651. *
  652. * @param bool $_alerte Indique si l'alerte doit être affichée.
  653. * @return string|null Le code HTML du badge ou NULL.
  654. */
  655. static public function printBadgeGeneral(bool $_alerte){
  656. return $_alerte == TRUE ? '<span class="position-absolute start-100 translate-middle p-1 bg-danger border border-light rounded-circle"></span>' : NULL;
  657. }
  658. /**
  659. * Vérifie les alertes pour les documents.
  660. *
  661. * @return array Les informations sur les alertes.
  662. */
  663. static public function ifbadge()
  664. {
  665. $return = [];
  666. $return["DOC"] = document::badgeAlert();
  667. if ($return["DOC"] != NULL) {
  668. $return["ALERTE"] = TRUE;
  669. } else {
  670. $return["ALERTE"] = FALSE;
  671. }
  672. return $return;
  673. }
  674. /**
  675. * Génère un menu de navigation.
  676. *
  677. * @param array $_navInfos Les informations de navigation.
  678. * @return void
  679. */
  680. static public function menu(array $_navInfos){
  681. $badge = self::ifbadge();
  682. echo '<a href="/" style="box-shadow: none; background-color:'. $_navInfos["color"] .';" class="navbar-brand">' . $_navInfos["title"] . '</a>' . debug::getBadges();
  683. echo '<div id="navbarCollapse" class="collapse navbar-collapse p-0">';
  684. echo '<ul class="nav navbar-nav ms-auto">';
  685. echo '<li class="nav-item dropdown">';
  686. echo '<a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">' . session::getName() . self::printBadgeGeneral($badge["ALERTE"]) . '</a>';
  687. echo '<div class="dropdown-menu dropdown-menu-end">';
  688. echo '<a href="/user.html" class="dropdown-item">Mon profil</a>';
  689. if((access::ifAccesss("documents") AND session::getType() == 5) OR session::getType() == 1){ // Membre du bureau ou Admin
  690. $nb = $badge["DOC"] > 0 ? '<span class="position-absolute badge rounded-pill bg-danger" style="right:-10px; margin-top:-10px;">' . $badge["DOC"] . '</span>' : NULL;
  691. echo '<a href="/documents-my-assign.html" class="dropdown-item">Vos assignations' . $nb . '</a>';
  692. echo '<a href="/alertes-emails.html" class="dropdown-item">Vos règles d\'alertes</a>';
  693. }
  694. echo '<div class="dropdown-divider"></div>';
  695. echo '<a href="/submit.php?from=logout" class="dropdown-item">Se déconnecter</a>';
  696. echo '</li>';
  697. echo '</div>';
  698. echo '</ul>';
  699. echo '</div>';
  700. }
  701. /**
  702. * Récupère l'adresse IP de l'utilisateur.
  703. *
  704. * @return string L'adresse IP de l'utilisateur.
  705. */
  706. static public function getUserIP() {
  707. $ip = 'Inconnue';
  708. if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  709. // IP partagée par un proxy
  710. $ip = $_SERVER['HTTP_CLIENT_IP'];
  711. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  712. // IP du client derrière un proxy
  713. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  714. } else {
  715. // IP du client directement connectée au serveur
  716. $ip = $_SERVER['REMOTE_ADDR'];
  717. }
  718. // Nettoyage des IPs multiples dans le cas de 'HTTP_X_FORWARDED_FOR'
  719. if (strpos($ip, ',') !== false) {
  720. $ip = explode(',', $ip)[0];
  721. }
  722. return $ip;
  723. }
  724. /**
  725. * Aplatit un tableau multidimensionnel.
  726. *
  727. * @param array|null $_array Le tableau à aplatir (optionnel).
  728. * @return array|null Le tableau aplati ou NULL.
  729. */
  730. static public function extractArrayInArray(?array $_array = NULL){
  731. if($_array != NULL){
  732. foreach ($_array as $item) {
  733. foreach ($item as $key => $value) {
  734. $flattened[$key] = $value;
  735. }
  736. }
  737. } else {
  738. $flattened = NULL;
  739. }
  740. return $flattened;
  741. }
  742. }